blob: 76636c2b9eefa5ad07fe8f41881e19659daa3efc [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 }
chaviw2d2150e2021-10-06 11:53:40 -0500353 } else {
chaviwa840a122021-11-01 09:50:57 -0500354 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500355 }
356 } else {
357 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
358 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800359 }
chaviw71c2cc42020-10-23 16:42:02 -0700360
chaviw71c2cc42020-10-23 16:42:02 -0700361 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700362 }
Valerie Haua32c5522019-12-09 10:11:08 -0800363
chaviw71c2cc42020-10-23 16:42:02 -0700364 if (transactionCompleteCallback) {
365 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800366 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700367}
368
Vishnu Nair1506b182021-02-22 14:35:15 -0800369// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
370// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
371// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
372// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700373static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700374 const sp<Fence>& releaseFence, uint32_t transformHint,
375 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800376 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800377 if (blastBufferQueue) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700378 blastBufferQueue->releaseBufferCallback(id, releaseFence, transformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700379 currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700380 } else {
381 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800382 }
383}
384
chaviw2d2150e2021-10-06 11:53:40 -0500385void BLASTBufferQueue::flushShadowQueueLocked() {
386 BQA_LOGV("flushShadowQueueLocked");
387 int numFramesToFlush = mNumFrameAvailable;
388 while (numFramesToFlush > 0) {
389 acquireNextBufferLocked(std::nullopt);
390 numFramesToFlush--;
391 }
392}
393
394void BLASTBufferQueue::flushShadowQueue() {
395 std::unique_lock _lock{mMutex};
396 flushShadowQueueLocked();
397}
398
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700399void BLASTBufferQueue::releaseBufferCallback(const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700400 const sp<Fence>& releaseFence, uint32_t transformHint,
401 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800402 ATRACE_CALL();
403 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700404 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800405
Robert Carr82d07c92021-05-10 11:36:43 -0700406 if (mSurfaceControl != nullptr) {
Robert Carr97e7cc02021-06-07 10:45:40 -0700407 mTransformHint = transformHint;
408 mSurfaceControl->setTransformHint(transformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700409 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700410 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700411 }
412
Ady Abraham899dcdb2021-06-15 16:56:21 -0700413 // Calculate how many buffers we need to hold before we release them back
414 // to the buffer queue. This will prevent higher latency when we are running
415 // on a lower refresh rate than the max supported. We only do that for EGL
416 // clients as others don't care about latency
417 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700418 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700419 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
420 }();
421
422 const auto numPendingBuffersToHold =
423 isEGL ? std::max(0u, mMaxAcquiredBuffers - currentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700424 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700425
426 // Release all buffers that are beyond the ones that we need to hold
427 while (mPendingRelease.size() > numPendingBuffersToHold) {
428 const auto releaseBuffer = mPendingRelease.front();
429 mPendingRelease.pop_front();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700430 auto it = mSubmitted.find(releaseBuffer.callbackId);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700431 if (it == mSubmitted.end()) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700432 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
433 releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700434 return;
435 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700436 mNumAcquired--;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700437 BQA_LOGV("released %s", id.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700438 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
439 mSubmitted.erase(it);
chaviw2d2150e2021-10-06 11:53:40 -0500440 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
441 // onFrameAvailable handle processing them since it will merge with the nextTransaction.
442 if (!mWaitForTransactionCallback) {
443 acquireNextBufferLocked(std::nullopt);
444 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800445 }
446
Ady Abraham899dcdb2021-06-15 16:56:21 -0700447 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700448 ATRACE_INT(mQueuedBufferTrace.c_str(),
449 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800450 mCallbackCV.notify_all();
451}
452
chaviw2d2150e2021-10-06 11:53:40 -0500453void BLASTBufferQueue::acquireNextBufferLocked(
454 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800455 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800456 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
457 // include the extra buffer when checking if we can acquire the next buffer.
chaviw2d2150e2021-10-06 11:53:40 -0500458 const bool includeExtraAcquire = !transaction;
459 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
460 if (mNumFrameAvailable == 0 || maxAcquired) {
461 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800462 return;
463 }
464
Valerie Haua32c5522019-12-09 10:11:08 -0800465 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700466 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800467 return;
468 }
469
Robert Carr78c25dd2019-08-15 14:10:33 -0700470 SurfaceComposerClient::Transaction localTransaction;
471 bool applyTransaction = true;
472 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviw2d2150e2021-10-06 11:53:40 -0500473 if (transaction) {
474 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700475 applyTransaction = false;
476 }
477
Valerie Haua32c5522019-12-09 10:11:08 -0800478 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800479
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800480 status_t status =
481 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800482 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
483 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
484 return;
485 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700486 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700487 return;
488 }
Valerie Haua32c5522019-12-09 10:11:08 -0800489 auto buffer = bufferItem.mGraphicBuffer;
490 mNumFrameAvailable--;
491
492 if (buffer == nullptr) {
493 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700494 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800495 return;
496 }
497
Vishnu Nair670b3f72020-09-29 17:52:18 -0700498 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700499 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800500 "buffer{size=%dx%d transform=%d}",
501 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
502 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
503 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviw2d2150e2021-10-06 11:53:40 -0500504 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800505 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700506 }
507
Valerie Haua32c5522019-12-09 10:11:08 -0800508 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700509 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
510 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
511 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700512
Valerie Hau871d6352020-01-29 08:44:02 -0800513 bool needsDisconnect = false;
514 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
515
516 // if producer disconnected before, notify SurfaceFlinger
517 if (needsDisconnect) {
518 t->notifyProducerDisconnect(mSurfaceControl);
519 }
520
Robert Carr78c25dd2019-08-15 14:10:33 -0700521 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
522 incStrong((void*)transactionCallbackThunk);
523
Vishnu Nair22b6d232021-12-06 16:45:48 -0800524 const bool updateDestinationFrame = mRequestedSize != mSize;
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700525 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700526 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000527 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
528 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700529 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800530
Vishnu Nair1506b182021-02-22 14:35:15 -0800531 auto releaseBufferCallback =
532 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700533 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
534 std::placeholders::_4);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700535 t->setBuffer(mSurfaceControl, buffer, releaseCallbackId, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500536 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
537 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
538 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700539 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800540 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700541 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviw9d12adc2021-11-17 17:36:50 -0600542
chaviw42026162021-04-16 15:46:12 -0500543 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700544
Vishnu Nair084514a2021-07-30 16:07:42 -0700545 if (updateDestinationFrame) {
546 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
547 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700548 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800549 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800550 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800551 if (!bufferItem.mIsAutoTimestamp) {
552 t->setDesiredPresentTime(bufferItem.mTimestamp);
553 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700554 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700555
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000556 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700557 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000558 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100559 }
560
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800561 if (mAutoRefresh != bufferItem.mAutoRefresh) {
562 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
563 mAutoRefresh = bufferItem.mAutoRefresh;
564 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800565 {
566 std::unique_lock _lock{mTimestampMutex};
567 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
568 if (dequeueTime != mDequeueTimestamps.end()) {
569 Parcel p;
570 p.writeInt64(dequeueTime->second);
571 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
572 mDequeueTimestamps.erase(dequeueTime);
573 }
574 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800575
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800576 auto mergeTransaction =
577 [&t, currentFrameNumber = bufferItem.mFrameNumber](
578 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
579 auto& [targetFrameNumber, transaction] = pendingTransaction;
580 if (currentFrameNumber < targetFrameNumber) {
581 return false;
582 }
583 t->merge(std::move(transaction));
584 return true;
585 };
586
587 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
588 mPendingTransactions.end(), mergeTransaction),
589 mPendingTransactions.end());
590
Robert Carr78c25dd2019-08-15 14:10:33 -0700591 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800592 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700593 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700594
chaviw2d2150e2021-10-06 11:53:40 -0500595 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800596 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700597 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500598 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800599 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700600 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700601 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700602}
603
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800604Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
605 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800606 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800607 }
608 return item.mCrop;
609}
610
chaviw2d2150e2021-10-06 11:53:40 -0500611void BLASTBufferQueue::acquireAndReleaseBuffer() {
612 BufferItem bufferItem;
chaviw8cba4ce2021-10-14 11:57:22 -0500613 status_t status =
614 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
615 if (status != OK) {
616 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
617 statusToString(status).c_str());
618 return;
619 }
chaviw2d2150e2021-10-06 11:53:40 -0500620 mNumFrameAvailable--;
chaviw8cba4ce2021-10-14 11:57:22 -0500621 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviw2d2150e2021-10-06 11:53:40 -0500622}
623
Vishnu Nairaef1de92020-10-22 12:15:53 -0700624void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800625 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800626 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800627
Vishnu Nairdab94092020-09-29 16:09:04 -0700628 const bool nextTransactionSet = mNextTransaction != nullptr;
chaviw2d2150e2021-10-06 11:53:40 -0500629 BQA_LOGV("onFrameAvailable-start nextTransactionSet=%s", boolToString(nextTransactionSet));
Vishnu Nair1506b182021-02-22 14:35:15 -0800630 if (nextTransactionSet) {
chaviw2d2150e2021-10-06 11:53:40 -0500631 if (mWaitForTransactionCallback) {
632 // We are waiting on a previous sync's transaction callback so allow another sync
633 // transaction to proceed.
634 //
635 // We need to first flush out the transactions that were in between the two syncs.
636 // We do this by merging them into mNextTransaction so any buffer merging will get
637 // a release callback invoked. The release callback will be async so we need to wait
638 // on max acquired to make sure we have the capacity to acquire another buffer.
639 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
640 BQA_LOGD("waiting to flush shadow queue...");
641 mCallbackCV.wait(_lock);
642 }
643 while (mNumFrameAvailable > 0) {
644 // flush out the shadow queue
645 acquireAndReleaseBuffer();
646 }
647 }
648
649 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
650 BQA_LOGD("waiting for free buffer.");
Valerie Hau0188adf2020-02-13 08:29:20 -0800651 mCallbackCV.wait(_lock);
652 }
653 }
chaviw2d2150e2021-10-06 11:53:40 -0500654
Valerie Haud3b90d22019-11-06 09:37:31 -0800655 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800656 mNumFrameAvailable++;
Robert Carre9323b32021-11-30 14:47:02 -0800657 if (mWaitForTransactionCallback && mNumFrameAvailable == 2) {
658 acquireAndReleaseBuffer();
659 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700660 ATRACE_INT(mQueuedBufferTrace.c_str(),
661 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800662
663 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
chaviw3277faf2021-05-19 16:45:23 -0500664 boolToString(nextTransactionSet));
chaviw2d2150e2021-10-06 11:53:40 -0500665
666 if (nextTransactionSet) {
667 acquireNextBufferLocked(std::move(mNextTransaction));
chaviw9d12adc2021-11-17 17:36:50 -0600668
669 // Only need a commit callback when syncing to ensure the buffer that's synced has been sent
670 // to SF
671 incStrong((void*)transactionCommittedCallbackThunk);
672 mNextTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
673 static_cast<void*>(this));
674
chaviw2d2150e2021-10-06 11:53:40 -0500675 mNextTransaction = nullptr;
676 mWaitForTransactionCallback = true;
677 } else if (!mWaitForTransactionCallback) {
678 acquireNextBufferLocked(std::nullopt);
679 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800680}
681
Vishnu Nairaef1de92020-10-22 12:15:53 -0700682void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
683 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
684 // Do nothing since we are not storing unacquired buffer items locally.
685}
686
Vishnu Nairadf632b2021-01-07 14:05:08 -0800687void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
688 std::unique_lock _lock{mTimestampMutex};
689 mDequeueTimestamps[bufferId] = systemTime();
690};
691
692void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
693 std::unique_lock _lock{mTimestampMutex};
694 mDequeueTimestamps.erase(bufferId);
695};
696
Robert Carr78c25dd2019-08-15 14:10:33 -0700697void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800698 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700699 mNextTransaction = t;
700}
701
Vishnu Nairea0de002020-11-17 17:42:37 -0800702bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700703 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
704 // Only reject buffers if scaling mode is freeze.
705 return false;
706 }
707
Vishnu Naire1a42322020-10-02 17:42:04 -0700708 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
709 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
710
711 // Take the buffer's orientation into account
712 if (item.mTransform & ui::Transform::ROT_90) {
713 std::swap(bufWidth, bufHeight);
714 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800715 ui::Size bufferSize(bufWidth, bufHeight);
716 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800717 return false;
718 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700719
Vishnu Nair670b3f72020-09-29 17:52:18 -0700720 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800721 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700722}
Vishnu Nairbf255772020-10-16 10:54:41 -0700723
chaviw71c2cc42020-10-23 16:42:02 -0700724void BLASTBufferQueue::setTransactionCompleteCallback(
725 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
726 std::lock_guard _lock{mMutex};
727 if (transactionCompleteCallback == nullptr) {
728 mTransactionCompleteCallback = nullptr;
729 } else {
730 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
731 mTransactionCompleteFrameNumber = frameNumber;
732 }
733}
734
Vishnu Nairbf255772020-10-16 10:54:41 -0700735// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800736// Consumer can acquire an additional buffer if that buffer is not droppable. Set
737// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
738// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
739bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700740 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800741 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700742}
743
Robert Carr05086b22020-10-13 18:22:51 -0700744class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700745private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700746 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700747 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700748 bool mDestroyed = false;
749
Robert Carr05086b22020-10-13 18:22:51 -0700750public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700751 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
752 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
753 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700754
Robert Carr05086b22020-10-13 18:22:51 -0700755 void allocateBuffers() override {
756 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
757 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
758 auto gbp = getIGraphicBufferProducer();
759 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
760 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
761 gbp->allocateBuffers(reqWidth, reqHeight,
762 reqFormat, reqUsage);
763
764 }).detach();
765 }
Robert Carr9c006e02020-10-14 13:41:57 -0700766
Marin Shalamanovc5986772021-03-16 16:09:49 +0100767 status_t setFrameRate(float frameRate, int8_t compatibility,
768 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700769 std::unique_lock _lock{mMutex};
770 if (mDestroyed) {
771 return DEAD_OBJECT;
772 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100773 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
774 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700775 return BAD_VALUE;
776 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100777 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700778 }
Robert Carr9b611b72020-10-19 12:00:23 -0700779
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000780 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700781 std::unique_lock _lock{mMutex};
782 if (mDestroyed) {
783 return DEAD_OBJECT;
784 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000785 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700786 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700787
788 void destroy() override {
789 Surface::destroy();
790
791 std::unique_lock _lock{mMutex};
792 mDestroyed = true;
793 mBbq = nullptr;
794 }
Robert Carr05086b22020-10-13 18:22:51 -0700795};
796
Robert Carr9c006e02020-10-14 13:41:57 -0700797// TODO: Can we coalesce this with frame updates? Need to confirm
798// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200799status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
800 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700801 std::unique_lock _lock{mMutex};
802 SurfaceComposerClient::Transaction t;
803
Marin Shalamanov46084422020-10-13 12:33:42 +0200804 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700805}
806
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000807status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700808 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000809 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100810 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700811}
812
Hongguang Chen621ec582021-02-16 15:42:35 -0800813void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
814 std::unique_lock _lock{mMutex};
815 SurfaceComposerClient::Transaction t;
816
817 t.setSidebandStream(mSurfaceControl, stream).apply();
818}
819
Vishnu Nair992496b2020-10-22 17:27:21 -0700820sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
821 std::unique_lock _lock{mMutex};
822 sp<IBinder> scHandle = nullptr;
823 if (includeSurfaceControlHandle && mSurfaceControl) {
824 scHandle = mSurfaceControl->getHandle();
825 }
826 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700827}
828
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800829void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
830 uint64_t frameNumber) {
831 std::lock_guard _lock{mMutex};
832 if (mLastAcquiredFrameNumber >= frameNumber) {
833 // Apply the transaction since we have already acquired the desired frame.
834 t->apply();
835 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500836 mPendingTransactions.emplace_back(frameNumber, *t);
837 // Clear the transaction so it can't be applied elsewhere.
838 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800839 }
840}
841
Vishnu Nair89496122020-12-14 17:14:53 -0800842// Maintains a single worker thread per process that services a list of runnables.
843class AsyncWorker : public Singleton<AsyncWorker> {
844private:
845 std::thread mThread;
846 bool mDone = false;
847 std::deque<std::function<void()>> mRunnables;
848 std::mutex mMutex;
849 std::condition_variable mCv;
850 void run() {
851 std::unique_lock<std::mutex> lock(mMutex);
852 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800853 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700854 std::deque<std::function<void()>> runnables = std::move(mRunnables);
855 mRunnables.clear();
856 lock.unlock();
857 // Run outside the lock since the runnable might trigger another
858 // post to the async worker.
859 execute(runnables);
860 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800861 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700862 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800863 }
864 }
865
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700866 void execute(std::deque<std::function<void()>>& runnables) {
867 while (!runnables.empty()) {
868 std::function<void()> runnable = runnables.front();
869 runnables.pop_front();
870 runnable();
871 }
872 }
873
Vishnu Nair89496122020-12-14 17:14:53 -0800874public:
875 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
876
877 ~AsyncWorker() {
878 mDone = true;
879 mCv.notify_all();
880 if (mThread.joinable()) {
881 mThread.join();
882 }
883 }
884
885 void post(std::function<void()> runnable) {
886 std::unique_lock<std::mutex> lock(mMutex);
887 mRunnables.emplace_back(std::move(runnable));
888 mCv.notify_one();
889 }
890};
891ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
892
893// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
894class AsyncProducerListener : public BnProducerListener {
895private:
896 const sp<IProducerListener> mListener;
897
898public:
899 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
900
901 void onBufferReleased() override {
902 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
903 }
904
905 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
906 AsyncWorker::getInstance().post(
907 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
908 }
909};
910
911// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
912// can be non-blocking when the producer is in the client process.
913class BBQBufferQueueProducer : public BufferQueueProducer {
914public:
915 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
916 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
917
918 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
919 QueueBufferOutput* output) override {
920 if (!listener) {
921 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
922 }
923
924 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
925 producerControlledByApp, output);
926 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800927
928 int query(int what, int* value) override {
929 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
930 *value = 1;
931 return NO_ERROR;
932 }
933 return BufferQueueProducer::query(what, value);
934 }
Vishnu Nair89496122020-12-14 17:14:53 -0800935};
936
937// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
938// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
939// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
940// we can deadlock.
941void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
942 sp<IGraphicBufferConsumer>* outConsumer) {
943 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
944 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
945
946 sp<BufferQueueCore> core(new BufferQueueCore());
947 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
948
949 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
950 LOG_ALWAYS_FATAL_IF(producer == nullptr,
951 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
952
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800953 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
954 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800955 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
956 "BLASTBufferQueue: failed to create BufferQueueConsumer");
957
958 *outProducer = producer;
959 *outConsumer = consumer;
960}
961
chaviw497e81c2021-02-04 17:09:47 -0800962PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
963 PixelFormat convertedFormat = format;
964 switch (format) {
965 case PIXEL_FORMAT_TRANSPARENT:
966 case PIXEL_FORMAT_TRANSLUCENT:
967 convertedFormat = PIXEL_FORMAT_RGBA_8888;
968 break;
969 case PIXEL_FORMAT_OPAQUE:
970 convertedFormat = PIXEL_FORMAT_RGBX_8888;
971 break;
972 }
973 return convertedFormat;
974}
975
Robert Carr82d07c92021-05-10 11:36:43 -0700976uint32_t BLASTBufferQueue::getLastTransformHint() const {
977 if (mSurfaceControl != nullptr) {
978 return mSurfaceControl->getTransformHint();
979 } else {
980 return 0;
981 }
982}
983
chaviw3d8a3192021-08-20 12:00:47 -0500984uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
985 std::unique_lock _lock{mMutex};
986 return mLastAcquiredFrameNumber;
987}
988
Robert Carr78c25dd2019-08-15 14:10:33 -0700989} // namespace android