blob: 60c2e2e6754d7851bb26d1a8efebaa59db580d88 [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 Nairdab94092020-09-29 16:09:04 -0700135BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700136 int width, int height, int32_t format)
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700137 : mSurfaceControl(surface),
Vishnu Nairea0de002020-11-17 17:42:37 -0800138 mSize(width, height),
139 mRequestedSize(mSize),
chaviw565ee542021-01-14 10:21:23 -0800140 mFormat(format),
Valerie Haud3b90d22019-11-06 09:37:31 -0800141 mNextTransaction(nullptr) {
Vishnu Nair89496122020-12-14 17:14:53 -0800142 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800143 // since the adapter is in the client process, set dequeue timeout
144 // explicitly so that dequeueBuffer will block
145 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800146
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700147 // safe default, most producers are expected to override this
148 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800149 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
150 GraphicBuffer::USAGE_HW_COMPOSER |
151 GraphicBuffer::USAGE_HW_TEXTURE,
152 1, false);
Valerie Haua32c5522019-12-09 10:11:08 -0800153 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700154 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700155 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700156 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800157 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700158 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700159 mBufferItemConsumer->setFrameAvailableListener(this);
160 mBufferItemConsumer->setBufferFreedListener(this);
Vishnu Nairea0de002020-11-17 17:42:37 -0800161 mBufferItemConsumer->setDefaultBufferSize(mSize.width, mSize.height);
chaviw497e81c2021-02-04 17:09:47 -0800162 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
Hongguang Chen621ec582021-02-16 15:42:35 -0800163 mBufferItemConsumer->setBlastBufferQueue(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700164
Ady Abraham899dcdb2021-06-15 16:56:21 -0700165 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700166 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
167
Valerie Hau2882e982020-01-23 13:33:10 -0800168 mTransformHint = mSurfaceControl->getTransformHint();
Robert Carr9f133d72020-04-01 15:51:46 -0700169 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800170 SurfaceComposerClient::Transaction()
Vishnu Nair084514a2021-07-30 16:07:42 -0700171 .setFlags(surface, layer_state_t::eEnableBackpressure,
172 layer_state_t::eEnableBackpressure)
173 .setApplyToken(mApplyToken)
174 .apply();
Valerie Haua32c5522019-12-09 10:11:08 -0800175 mNumAcquired = 0;
176 mNumFrameAvailable = 0;
Vishnu Naira4fbca52021-07-07 16:52:34 -0700177 BQA_LOGV("BLASTBufferQueue created width=%d height=%d format=%d mTransformHint=%d", width,
178 height, format, mTransformHint);
Robert Carr78c25dd2019-08-15 14:10:33 -0700179}
180
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800181BLASTBufferQueue::~BLASTBufferQueue() {
Hongguang Chen621ec582021-02-16 15:42:35 -0800182 mBufferItemConsumer->setBlastBufferQueue(nullptr);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800183 if (mPendingTransactions.empty()) {
184 return;
185 }
186 BQA_LOGE("Applying pending transactions on dtor %d",
187 static_cast<uint32_t>(mPendingTransactions.size()));
188 SurfaceComposerClient::Transaction t;
189 for (auto& [targetFrameNumber, transaction] : mPendingTransactions) {
190 t.merge(std::move(transaction));
191 }
192 t.apply();
193}
194
chaviw565ee542021-01-14 10:21:23 -0800195void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Nair084514a2021-07-30 16:07:42 -0700196 int32_t format, SurfaceComposerClient::Transaction* outTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700197 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800198 if (mFormat != format) {
199 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800200 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800201 }
202
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800203 SurfaceComposerClient::Transaction t;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700204 const bool setBackpressureFlag = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800205 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800206
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700207 // Always update the native object even though they might have the same layer handle, so we can
208 // get the updated transform hint from WM.
209 mSurfaceControl = surface;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800210 if (mSurfaceControl != nullptr) {
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700211 if (setBackpressureFlag) {
212 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
213 layer_state_t::eEnableBackpressure);
214 applyTransaction = true;
215 }
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800216 mTransformHint = mSurfaceControl->getTransformHint();
217 mBufferItemConsumer->setTransformHint(mTransformHint);
218 }
Vishnu Naira4fbca52021-07-07 16:52:34 -0700219 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
220 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800221
Vishnu Nairea0de002020-11-17 17:42:37 -0800222 ui::Size newSize(width, height);
223 if (mRequestedSize != newSize) {
224 mRequestedSize.set(newSize);
225 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000226 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800227 // If the buffer supports scaling, update the frame immediately since the client may
228 // want to scale the existing buffer to the new size.
229 mSize = mRequestedSize;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000230 // We only need to update the scale if we've received at least one buffer. The reason
231 // for this is the scale is calculated based on the requested size and buffer size.
232 // If there's no buffer, the scale will always be 1.
Vishnu Nair084514a2021-07-30 16:07:42 -0700233 SurfaceComposerClient::Transaction* destFrameTransaction =
234 (outTransaction) ? outTransaction : &t;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700235 if (mSurfaceControl != nullptr && mLastBufferInfo.hasBuffer) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700236 destFrameTransaction->setDestinationFrame(mSurfaceControl,
237 Rect(0, 0, newSize.getWidth(),
238 newSize.getHeight()));
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000239 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800240 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800241 }
Robert Carrfc416512020-04-02 12:32:44 -0700242 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800243 if (applyTransaction) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700244 t.setApplyToken(mApplyToken).apply();
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800245 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700246}
247
chaviw2d2150e2021-10-06 11:53:40 -0500248static std::optional<SurfaceControlStats> findMatchingStat(
249 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
250 for (auto stat : stats) {
251 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
252 return stat;
253 }
254 }
255 return std::nullopt;
256}
257
258static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
259 const sp<Fence>& presentFence,
260 const std::vector<SurfaceControlStats>& stats) {
261 if (context == nullptr) {
262 return;
263 }
264 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
265 bq->transactionCommittedCallback(latchTime, presentFence, stats);
266}
267
268void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
269 const sp<Fence>& /*presentFence*/,
270 const std::vector<SurfaceControlStats>& stats) {
271 {
272 std::unique_lock _lock{mMutex};
273 ATRACE_CALL();
274 BQA_LOGV("transactionCommittedCallback");
275 if (!mSurfaceControlsWithPendingCallback.empty()) {
276 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
277 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
278 if (stat) {
279 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
280
281 // We need to check if we were waiting for a transaction callback in order to
282 // process any pending buffers and unblock. It's possible to get transaction
283 // callbacks for previous requests so we need to ensure the frame from this
284 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
285 // will stop processing buffers when mWaitForTransactionCallback is set, we know
286 // that mLastAcquiredFrameNumber is the frame we're waiting on.
287 // We also want to check if mNextTransaction is null because it's possible another
288 // sync request came in while waiting, but it hasn't started processing yet. In that
289 // case, we don't actually want to flush the frames in between since they will get
290 // processed and merged with the sync transaction and released earlier than if they
291 // were sent to SF
292 if (mWaitForTransactionCallback && mNextTransaction == nullptr &&
293 currFrameNumber >= mLastAcquiredFrameNumber) {
294 mWaitForTransactionCallback = false;
295 flushShadowQueueLocked();
296 }
297 } else {
chaviwa840a122021-11-01 09:50:57 -0500298 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviw2d2150e2021-10-06 11:53:40 -0500299 }
300 } else {
301 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
302 "empty.");
303 }
304
305 decStrong((void*)transactionCommittedCallbackThunk);
306 }
307}
308
Robert Carr78c25dd2019-08-15 14:10:33 -0700309static void transactionCallbackThunk(void* context, nsecs_t latchTime,
310 const sp<Fence>& presentFence,
311 const std::vector<SurfaceControlStats>& stats) {
312 if (context == nullptr) {
313 return;
314 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800315 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700316 bq->transactionCallback(latchTime, presentFence, stats);
317}
318
319void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
320 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700321 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
322 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700323
chaviw71c2cc42020-10-23 16:42:02 -0700324 {
325 std::unique_lock _lock{mMutex};
326 ATRACE_CALL();
327 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700328
chaviw42026162021-04-16 15:46:12 -0500329 if (!mSurfaceControlsWithPendingCallback.empty()) {
330 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
331 mSurfaceControlsWithPendingCallback.pop();
chaviw2d2150e2021-10-06 11:53:40 -0500332 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
333 if (statsOptional) {
334 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500335 mTransformHint = stat.transformHint;
336 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700337 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700338 // Update frametime stamps if the frame was latched and presented, indicated by a
339 // valid latch time.
340 if (stat.latchTime > 0) {
341 mBufferItemConsumer
342 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
343 stat.frameEventStats.refreshStartTime,
344 stat.frameEventStats.gpuCompositionDoneFence,
345 stat.presentFence, stat.previousReleaseFence,
346 stat.frameEventStats.compositorTiming,
347 stat.latchTime,
348 stat.frameEventStats.dequeueReadyTime);
349 }
chaviw42026162021-04-16 15:46:12 -0500350 currFrameNumber = stat.frameEventStats.frameNumber;
351
352 if (mTransactionCompleteCallback &&
353 currFrameNumber >= mTransactionCompleteFrameNumber) {
354 if (currFrameNumber > mTransactionCompleteFrameNumber) {
355 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
356 " than expected=%" PRIu64,
357 currFrameNumber, mTransactionCompleteFrameNumber);
358 }
359 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
360 mTransactionCompleteFrameNumber = 0;
361 }
chaviw2d2150e2021-10-06 11:53:40 -0500362 } else {
chaviwa840a122021-11-01 09:50:57 -0500363 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500364 }
365 } else {
366 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
367 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800368 }
chaviw71c2cc42020-10-23 16:42:02 -0700369
chaviw71c2cc42020-10-23 16:42:02 -0700370 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700371 }
Valerie Haua32c5522019-12-09 10:11:08 -0800372
chaviw71c2cc42020-10-23 16:42:02 -0700373 if (transactionCompleteCallback) {
374 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800375 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700376}
377
Vishnu Nair1506b182021-02-22 14:35:15 -0800378// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
379// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
380// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
381// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700382static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700383 const sp<Fence>& releaseFence, uint32_t transformHint,
384 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800385 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800386 if (blastBufferQueue) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700387 blastBufferQueue->releaseBufferCallback(id, releaseFence, transformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700388 currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700389 } else {
390 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800391 }
392}
393
chaviw2d2150e2021-10-06 11:53:40 -0500394void BLASTBufferQueue::flushShadowQueueLocked() {
395 BQA_LOGV("flushShadowQueueLocked");
396 int numFramesToFlush = mNumFrameAvailable;
397 while (numFramesToFlush > 0) {
398 acquireNextBufferLocked(std::nullopt);
399 numFramesToFlush--;
400 }
401}
402
403void BLASTBufferQueue::flushShadowQueue() {
404 std::unique_lock _lock{mMutex};
405 flushShadowQueueLocked();
406}
407
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700408void BLASTBufferQueue::releaseBufferCallback(const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700409 const sp<Fence>& releaseFence, uint32_t transformHint,
410 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800411 ATRACE_CALL();
412 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700413 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800414
Robert Carr82d07c92021-05-10 11:36:43 -0700415 if (mSurfaceControl != nullptr) {
Robert Carr97e7cc02021-06-07 10:45:40 -0700416 mTransformHint = transformHint;
417 mSurfaceControl->setTransformHint(transformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700418 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700419 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700420 }
421
Ady Abraham899dcdb2021-06-15 16:56:21 -0700422 // Calculate how many buffers we need to hold before we release them back
423 // to the buffer queue. This will prevent higher latency when we are running
424 // on a lower refresh rate than the max supported. We only do that for EGL
425 // clients as others don't care about latency
426 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700427 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700428 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
429 }();
430
431 const auto numPendingBuffersToHold =
432 isEGL ? std::max(0u, mMaxAcquiredBuffers - currentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700433 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700434
435 // Release all buffers that are beyond the ones that we need to hold
436 while (mPendingRelease.size() > numPendingBuffersToHold) {
437 const auto releaseBuffer = mPendingRelease.front();
438 mPendingRelease.pop_front();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700439 auto it = mSubmitted.find(releaseBuffer.callbackId);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700440 if (it == mSubmitted.end()) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700441 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
442 releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700443 return;
444 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700445 mNumAcquired--;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700446 BQA_LOGV("released %s", id.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700447 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
448 mSubmitted.erase(it);
chaviw2d2150e2021-10-06 11:53:40 -0500449 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
450 // onFrameAvailable handle processing them since it will merge with the nextTransaction.
451 if (!mWaitForTransactionCallback) {
452 acquireNextBufferLocked(std::nullopt);
453 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800454 }
455
Ady Abraham899dcdb2021-06-15 16:56:21 -0700456 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700457 ATRACE_INT(mQueuedBufferTrace.c_str(),
458 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800459 mCallbackCV.notify_all();
460}
461
chaviw2d2150e2021-10-06 11:53:40 -0500462void BLASTBufferQueue::acquireNextBufferLocked(
463 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800464 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800465 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
466 // include the extra buffer when checking if we can acquire the next buffer.
chaviw2d2150e2021-10-06 11:53:40 -0500467 const bool includeExtraAcquire = !transaction;
468 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
469 if (mNumFrameAvailable == 0 || maxAcquired) {
470 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800471 return;
472 }
473
Valerie Haua32c5522019-12-09 10:11:08 -0800474 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700475 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800476 return;
477 }
478
Robert Carr78c25dd2019-08-15 14:10:33 -0700479 SurfaceComposerClient::Transaction localTransaction;
480 bool applyTransaction = true;
481 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviw2d2150e2021-10-06 11:53:40 -0500482 if (transaction) {
483 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700484 applyTransaction = false;
485 }
486
Valerie Haua32c5522019-12-09 10:11:08 -0800487 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800488
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800489 status_t status =
490 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800491 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
492 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
493 return;
494 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700495 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700496 return;
497 }
Valerie Haua32c5522019-12-09 10:11:08 -0800498 auto buffer = bufferItem.mGraphicBuffer;
499 mNumFrameAvailable--;
500
501 if (buffer == nullptr) {
502 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700503 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800504 return;
505 }
506
Vishnu Nair670b3f72020-09-29 17:52:18 -0700507 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700508 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800509 "buffer{size=%dx%d transform=%d}",
510 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
511 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
512 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviw2d2150e2021-10-06 11:53:40 -0500513 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800514 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700515 }
516
Valerie Haua32c5522019-12-09 10:11:08 -0800517 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700518 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
519 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
520 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700521
Valerie Hau871d6352020-01-29 08:44:02 -0800522 bool needsDisconnect = false;
523 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
524
525 // if producer disconnected before, notify SurfaceFlinger
526 if (needsDisconnect) {
527 t->notifyProducerDisconnect(mSurfaceControl);
528 }
529
Robert Carr78c25dd2019-08-15 14:10:33 -0700530 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
531 incStrong((void*)transactionCallbackThunk);
532
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700533 const bool sizeHasChanged = mRequestedSize != mSize;
534 mSize = mRequestedSize;
535 const bool updateDestinationFrame = sizeHasChanged || !mLastBufferInfo.hasBuffer;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700536 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000537 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
538 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700539 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800540
Vishnu Nair1506b182021-02-22 14:35:15 -0800541 auto releaseBufferCallback =
542 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700543 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
544 std::placeholders::_4);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700545 t->setBuffer(mSurfaceControl, buffer, releaseCallbackId, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500546 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
547 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
548 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700549 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800550 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700551 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviw9d12adc2021-11-17 17:36:50 -0600552
chaviw42026162021-04-16 15:46:12 -0500553 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700554
Vishnu Nair084514a2021-07-30 16:07:42 -0700555 if (updateDestinationFrame) {
556 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
557 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700558 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800559 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800560 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800561 if (!bufferItem.mIsAutoTimestamp) {
562 t->setDesiredPresentTime(bufferItem.mTimestamp);
563 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700564 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700565
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000566 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700567 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000568 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100569 }
570
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800571 if (mAutoRefresh != bufferItem.mAutoRefresh) {
572 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
573 mAutoRefresh = bufferItem.mAutoRefresh;
574 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800575 {
576 std::unique_lock _lock{mTimestampMutex};
577 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
578 if (dequeueTime != mDequeueTimestamps.end()) {
579 Parcel p;
580 p.writeInt64(dequeueTime->second);
581 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
582 mDequeueTimestamps.erase(dequeueTime);
583 }
584 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800585
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800586 auto mergeTransaction =
587 [&t, currentFrameNumber = bufferItem.mFrameNumber](
588 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
589 auto& [targetFrameNumber, transaction] = pendingTransaction;
590 if (currentFrameNumber < targetFrameNumber) {
591 return false;
592 }
593 t->merge(std::move(transaction));
594 return true;
595 };
596
597 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
598 mPendingTransactions.end(), mergeTransaction),
599 mPendingTransactions.end());
600
Robert Carr78c25dd2019-08-15 14:10:33 -0700601 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800602 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700603 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700604
chaviw2d2150e2021-10-06 11:53:40 -0500605 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800606 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700607 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500608 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800609 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700610 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700611 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700612}
613
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800614Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
615 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800616 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800617 }
618 return item.mCrop;
619}
620
chaviw2d2150e2021-10-06 11:53:40 -0500621void BLASTBufferQueue::acquireAndReleaseBuffer() {
622 BufferItem bufferItem;
chaviw8cba4ce2021-10-14 11:57:22 -0500623 status_t status =
624 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
625 if (status != OK) {
626 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
627 statusToString(status).c_str());
628 return;
629 }
chaviw2d2150e2021-10-06 11:53:40 -0500630 mNumFrameAvailable--;
chaviw8cba4ce2021-10-14 11:57:22 -0500631 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviw2d2150e2021-10-06 11:53:40 -0500632}
633
Vishnu Nairaef1de92020-10-22 12:15:53 -0700634void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800635 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800636 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800637
Vishnu Nairdab94092020-09-29 16:09:04 -0700638 const bool nextTransactionSet = mNextTransaction != nullptr;
chaviw2d2150e2021-10-06 11:53:40 -0500639 BQA_LOGV("onFrameAvailable-start nextTransactionSet=%s", boolToString(nextTransactionSet));
Vishnu Nair1506b182021-02-22 14:35:15 -0800640 if (nextTransactionSet) {
chaviw2d2150e2021-10-06 11:53:40 -0500641 if (mWaitForTransactionCallback) {
642 // We are waiting on a previous sync's transaction callback so allow another sync
643 // transaction to proceed.
644 //
645 // We need to first flush out the transactions that were in between the two syncs.
646 // We do this by merging them into mNextTransaction so any buffer merging will get
647 // a release callback invoked. The release callback will be async so we need to wait
648 // on max acquired to make sure we have the capacity to acquire another buffer.
649 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
650 BQA_LOGD("waiting to flush shadow queue...");
651 mCallbackCV.wait(_lock);
652 }
653 while (mNumFrameAvailable > 0) {
654 // flush out the shadow queue
655 acquireAndReleaseBuffer();
656 }
657 }
658
659 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
660 BQA_LOGD("waiting for free buffer.");
Valerie Hau0188adf2020-02-13 08:29:20 -0800661 mCallbackCV.wait(_lock);
662 }
663 }
chaviw2d2150e2021-10-06 11:53:40 -0500664
Valerie Haud3b90d22019-11-06 09:37:31 -0800665 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800666 mNumFrameAvailable++;
Robert Carre9323b32021-11-30 14:47:02 -0800667 if (mWaitForTransactionCallback && mNumFrameAvailable == 2) {
668 acquireAndReleaseBuffer();
669 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700670 ATRACE_INT(mQueuedBufferTrace.c_str(),
671 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800672
673 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
chaviw3277faf2021-05-19 16:45:23 -0500674 boolToString(nextTransactionSet));
chaviw2d2150e2021-10-06 11:53:40 -0500675
676 if (nextTransactionSet) {
677 acquireNextBufferLocked(std::move(mNextTransaction));
chaviw9d12adc2021-11-17 17:36:50 -0600678
679 // Only need a commit callback when syncing to ensure the buffer that's synced has been sent
680 // to SF
681 incStrong((void*)transactionCommittedCallbackThunk);
682 mNextTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
683 static_cast<void*>(this));
684
chaviw2d2150e2021-10-06 11:53:40 -0500685 mNextTransaction = nullptr;
686 mWaitForTransactionCallback = true;
687 } else if (!mWaitForTransactionCallback) {
688 acquireNextBufferLocked(std::nullopt);
689 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800690}
691
Vishnu Nairaef1de92020-10-22 12:15:53 -0700692void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
693 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
694 // Do nothing since we are not storing unacquired buffer items locally.
695}
696
Vishnu Nairadf632b2021-01-07 14:05:08 -0800697void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
698 std::unique_lock _lock{mTimestampMutex};
699 mDequeueTimestamps[bufferId] = systemTime();
700};
701
702void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
703 std::unique_lock _lock{mTimestampMutex};
704 mDequeueTimestamps.erase(bufferId);
705};
706
Robert Carr78c25dd2019-08-15 14:10:33 -0700707void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800708 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700709 mNextTransaction = t;
710}
711
Vishnu Nairea0de002020-11-17 17:42:37 -0800712bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700713 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
714 // Only reject buffers if scaling mode is freeze.
715 return false;
716 }
717
Vishnu Naire1a42322020-10-02 17:42:04 -0700718 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
719 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
720
721 // Take the buffer's orientation into account
722 if (item.mTransform & ui::Transform::ROT_90) {
723 std::swap(bufWidth, bufHeight);
724 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800725 ui::Size bufferSize(bufWidth, bufHeight);
726 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800727 return false;
728 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700729
Vishnu Nair670b3f72020-09-29 17:52:18 -0700730 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800731 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700732}
Vishnu Nairbf255772020-10-16 10:54:41 -0700733
chaviw71c2cc42020-10-23 16:42:02 -0700734void BLASTBufferQueue::setTransactionCompleteCallback(
735 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
736 std::lock_guard _lock{mMutex};
737 if (transactionCompleteCallback == nullptr) {
738 mTransactionCompleteCallback = nullptr;
739 } else {
740 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
741 mTransactionCompleteFrameNumber = frameNumber;
742 }
743}
744
Vishnu Nairbf255772020-10-16 10:54:41 -0700745// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800746// Consumer can acquire an additional buffer if that buffer is not droppable. Set
747// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
748// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
749bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700750 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800751 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700752}
753
Robert Carr05086b22020-10-13 18:22:51 -0700754class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700755private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700756 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700757 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700758 bool mDestroyed = false;
759
Robert Carr05086b22020-10-13 18:22:51 -0700760public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700761 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
762 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
763 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700764
Robert Carr05086b22020-10-13 18:22:51 -0700765 void allocateBuffers() override {
766 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
767 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
768 auto gbp = getIGraphicBufferProducer();
769 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
770 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
771 gbp->allocateBuffers(reqWidth, reqHeight,
772 reqFormat, reqUsage);
773
774 }).detach();
775 }
Robert Carr9c006e02020-10-14 13:41:57 -0700776
Marin Shalamanovc5986772021-03-16 16:09:49 +0100777 status_t setFrameRate(float frameRate, int8_t compatibility,
778 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700779 std::unique_lock _lock{mMutex};
780 if (mDestroyed) {
781 return DEAD_OBJECT;
782 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100783 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
784 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700785 return BAD_VALUE;
786 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100787 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700788 }
Robert Carr9b611b72020-10-19 12:00:23 -0700789
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000790 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700791 std::unique_lock _lock{mMutex};
792 if (mDestroyed) {
793 return DEAD_OBJECT;
794 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000795 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700796 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700797
798 void destroy() override {
799 Surface::destroy();
800
801 std::unique_lock _lock{mMutex};
802 mDestroyed = true;
803 mBbq = nullptr;
804 }
Robert Carr05086b22020-10-13 18:22:51 -0700805};
806
Robert Carr9c006e02020-10-14 13:41:57 -0700807// TODO: Can we coalesce this with frame updates? Need to confirm
808// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200809status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
810 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700811 std::unique_lock _lock{mMutex};
812 SurfaceComposerClient::Transaction t;
813
Marin Shalamanov46084422020-10-13 12:33:42 +0200814 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700815}
816
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000817status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700818 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000819 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100820 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700821}
822
Hongguang Chen621ec582021-02-16 15:42:35 -0800823void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
824 std::unique_lock _lock{mMutex};
825 SurfaceComposerClient::Transaction t;
826
827 t.setSidebandStream(mSurfaceControl, stream).apply();
828}
829
Vishnu Nair992496b2020-10-22 17:27:21 -0700830sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
831 std::unique_lock _lock{mMutex};
832 sp<IBinder> scHandle = nullptr;
833 if (includeSurfaceControlHandle && mSurfaceControl) {
834 scHandle = mSurfaceControl->getHandle();
835 }
836 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700837}
838
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800839void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
840 uint64_t frameNumber) {
841 std::lock_guard _lock{mMutex};
842 if (mLastAcquiredFrameNumber >= frameNumber) {
843 // Apply the transaction since we have already acquired the desired frame.
844 t->apply();
845 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500846 mPendingTransactions.emplace_back(frameNumber, *t);
847 // Clear the transaction so it can't be applied elsewhere.
848 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800849 }
850}
851
Vishnu Nair89496122020-12-14 17:14:53 -0800852// Maintains a single worker thread per process that services a list of runnables.
853class AsyncWorker : public Singleton<AsyncWorker> {
854private:
855 std::thread mThread;
856 bool mDone = false;
857 std::deque<std::function<void()>> mRunnables;
858 std::mutex mMutex;
859 std::condition_variable mCv;
860 void run() {
861 std::unique_lock<std::mutex> lock(mMutex);
862 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800863 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700864 std::deque<std::function<void()>> runnables = std::move(mRunnables);
865 mRunnables.clear();
866 lock.unlock();
867 // Run outside the lock since the runnable might trigger another
868 // post to the async worker.
869 execute(runnables);
870 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800871 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700872 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800873 }
874 }
875
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700876 void execute(std::deque<std::function<void()>>& runnables) {
877 while (!runnables.empty()) {
878 std::function<void()> runnable = runnables.front();
879 runnables.pop_front();
880 runnable();
881 }
882 }
883
Vishnu Nair89496122020-12-14 17:14:53 -0800884public:
885 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
886
887 ~AsyncWorker() {
888 mDone = true;
889 mCv.notify_all();
890 if (mThread.joinable()) {
891 mThread.join();
892 }
893 }
894
895 void post(std::function<void()> runnable) {
896 std::unique_lock<std::mutex> lock(mMutex);
897 mRunnables.emplace_back(std::move(runnable));
898 mCv.notify_one();
899 }
900};
901ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
902
903// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
904class AsyncProducerListener : public BnProducerListener {
905private:
906 const sp<IProducerListener> mListener;
907
908public:
909 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
910
911 void onBufferReleased() override {
912 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
913 }
914
915 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
916 AsyncWorker::getInstance().post(
917 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
918 }
919};
920
921// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
922// can be non-blocking when the producer is in the client process.
923class BBQBufferQueueProducer : public BufferQueueProducer {
924public:
925 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
926 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
927
928 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
929 QueueBufferOutput* output) override {
930 if (!listener) {
931 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
932 }
933
934 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
935 producerControlledByApp, output);
936 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800937
938 int query(int what, int* value) override {
939 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
940 *value = 1;
941 return NO_ERROR;
942 }
943 return BufferQueueProducer::query(what, value);
944 }
Vishnu Nair89496122020-12-14 17:14:53 -0800945};
946
947// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
948// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
949// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
950// we can deadlock.
951void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
952 sp<IGraphicBufferConsumer>* outConsumer) {
953 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
954 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
955
956 sp<BufferQueueCore> core(new BufferQueueCore());
957 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
958
959 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
960 LOG_ALWAYS_FATAL_IF(producer == nullptr,
961 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
962
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800963 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
964 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800965 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
966 "BLASTBufferQueue: failed to create BufferQueueConsumer");
967
968 *outProducer = producer;
969 *outConsumer = consumer;
970}
971
chaviw497e81c2021-02-04 17:09:47 -0800972PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
973 PixelFormat convertedFormat = format;
974 switch (format) {
975 case PIXEL_FORMAT_TRANSPARENT:
976 case PIXEL_FORMAT_TRANSLUCENT:
977 convertedFormat = PIXEL_FORMAT_RGBA_8888;
978 break;
979 case PIXEL_FORMAT_OPAQUE:
980 convertedFormat = PIXEL_FORMAT_RGBX_8888;
981 break;
982 }
983 return convertedFormat;
984}
985
Robert Carr82d07c92021-05-10 11:36:43 -0700986uint32_t BLASTBufferQueue::getLastTransformHint() const {
987 if (mSurfaceControl != nullptr) {
988 return mSurfaceControl->getTransformHint();
989 } else {
990 return 0;
991 }
992}
993
chaviw3d8a3192021-08-20 12:00:47 -0500994uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
995 std::unique_lock _lock{mMutex};
996 return mLastAcquiredFrameNumber;
997}
998
Robert Carr78c25dd2019-08-15 14:10:33 -0700999} // namespace android