blob: 2d2b6b26f6b831ede5a3759f2e8a70389f60a832 [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
chaviwd7deef72021-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);
chaviw69058fb2021-09-27 09:37:30 -0500167 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Ady Abraham0bde6b52021-05-18 13:57:02 -0700168
Valerie Hau2882e982020-01-23 13:33:10 -0800169 mTransformHint = mSurfaceControl->getTransformHint();
Robert Carr9f133d72020-04-01 15:51:46 -0700170 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800171 SurfaceComposerClient::Transaction()
Vishnu Nair084514a2021-07-30 16:07:42 -0700172 .setFlags(surface, layer_state_t::eEnableBackpressure,
173 layer_state_t::eEnableBackpressure)
174 .setApplyToken(mApplyToken)
175 .apply();
Valerie Haua32c5522019-12-09 10:11:08 -0800176 mNumAcquired = 0;
177 mNumFrameAvailable = 0;
Vishnu Naira4fbca52021-07-07 16:52:34 -0700178 BQA_LOGV("BLASTBufferQueue created width=%d height=%d format=%d mTransformHint=%d", width,
179 height, format, mTransformHint);
Robert Carr78c25dd2019-08-15 14:10:33 -0700180}
181
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800182BLASTBufferQueue::~BLASTBufferQueue() {
Hongguang Chen621ec582021-02-16 15:42:35 -0800183 mBufferItemConsumer->setBlastBufferQueue(nullptr);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800184 if (mPendingTransactions.empty()) {
185 return;
186 }
187 BQA_LOGE("Applying pending transactions on dtor %d",
188 static_cast<uint32_t>(mPendingTransactions.size()));
189 SurfaceComposerClient::Transaction t;
190 for (auto& [targetFrameNumber, transaction] : mPendingTransactions) {
191 t.merge(std::move(transaction));
192 }
193 t.apply();
194}
195
chaviw565ee542021-01-14 10:21:23 -0800196void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Nair084514a2021-07-30 16:07:42 -0700197 int32_t format, SurfaceComposerClient::Transaction* outTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700198 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800199 if (mFormat != format) {
200 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800201 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800202 }
203
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800204 SurfaceComposerClient::Transaction t;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700205 const bool setBackpressureFlag = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800206 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800207
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700208 // Always update the native object even though they might have the same layer handle, so we can
209 // get the updated transform hint from WM.
210 mSurfaceControl = surface;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800211 if (mSurfaceControl != nullptr) {
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700212 if (setBackpressureFlag) {
213 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
214 layer_state_t::eEnableBackpressure);
215 applyTransaction = true;
216 }
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800217 mTransformHint = mSurfaceControl->getTransformHint();
218 mBufferItemConsumer->setTransformHint(mTransformHint);
219 }
Vishnu Naira4fbca52021-07-07 16:52:34 -0700220 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
221 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800222
Vishnu Nairea0de002020-11-17 17:42:37 -0800223 ui::Size newSize(width, height);
224 if (mRequestedSize != newSize) {
225 mRequestedSize.set(newSize);
226 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000227 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800228 // If the buffer supports scaling, update the frame immediately since the client may
229 // want to scale the existing buffer to the new size.
230 mSize = mRequestedSize;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000231 // We only need to update the scale if we've received at least one buffer. The reason
232 // for this is the scale is calculated based on the requested size and buffer size.
233 // If there's no buffer, the scale will always be 1.
Vishnu Nair084514a2021-07-30 16:07:42 -0700234 SurfaceComposerClient::Transaction* destFrameTransaction =
235 (outTransaction) ? outTransaction : &t;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700236 if (mSurfaceControl != nullptr && mLastBufferInfo.hasBuffer) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700237 destFrameTransaction->setDestinationFrame(mSurfaceControl,
238 Rect(0, 0, newSize.getWidth(),
239 newSize.getHeight()));
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000240 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800241 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800242 }
Robert Carrfc416512020-04-02 12:32:44 -0700243 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800244 if (applyTransaction) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700245 t.setApplyToken(mApplyToken).apply();
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800246 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700247}
248
chaviwd7deef72021-10-06 11:53:40 -0500249static std::optional<SurfaceControlStats> findMatchingStat(
250 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
251 for (auto stat : stats) {
252 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
253 return stat;
254 }
255 }
256 return std::nullopt;
257}
258
259static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
260 const sp<Fence>& presentFence,
261 const std::vector<SurfaceControlStats>& stats) {
262 if (context == nullptr) {
263 return;
264 }
265 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
266 bq->transactionCommittedCallback(latchTime, presentFence, stats);
267}
268
269void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
270 const sp<Fence>& /*presentFence*/,
271 const std::vector<SurfaceControlStats>& stats) {
272 {
273 std::unique_lock _lock{mMutex};
274 ATRACE_CALL();
275 BQA_LOGV("transactionCommittedCallback");
276 if (!mSurfaceControlsWithPendingCallback.empty()) {
277 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
278 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
279 if (stat) {
280 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
281
282 // We need to check if we were waiting for a transaction callback in order to
283 // process any pending buffers and unblock. It's possible to get transaction
284 // callbacks for previous requests so we need to ensure the frame from this
285 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
286 // will stop processing buffers when mWaitForTransactionCallback is set, we know
287 // that mLastAcquiredFrameNumber is the frame we're waiting on.
288 // We also want to check if mNextTransaction is null because it's possible another
289 // sync request came in while waiting, but it hasn't started processing yet. In that
290 // case, we don't actually want to flush the frames in between since they will get
291 // processed and merged with the sync transaction and released earlier than if they
292 // were sent to SF
293 if (mWaitForTransactionCallback && mNextTransaction == nullptr &&
294 currFrameNumber >= mLastAcquiredFrameNumber) {
295 mWaitForTransactionCallback = false;
296 flushShadowQueue();
297 }
298 } else {
299 BQA_LOGE("Failed to find matching SurfaceControl in transaction callback");
300 }
301 } else {
302 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
303 "empty.");
304 }
305
306 decStrong((void*)transactionCommittedCallbackThunk);
307 }
308}
309
Robert Carr78c25dd2019-08-15 14:10:33 -0700310static void transactionCallbackThunk(void* context, nsecs_t latchTime,
311 const sp<Fence>& presentFence,
312 const std::vector<SurfaceControlStats>& stats) {
313 if (context == nullptr) {
314 return;
315 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800316 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700317 bq->transactionCallback(latchTime, presentFence, stats);
318}
319
320void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
321 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700322 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
323 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700324
chaviw71c2cc42020-10-23 16:42:02 -0700325 {
326 std::unique_lock _lock{mMutex};
327 ATRACE_CALL();
328 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700329
chaviw42026162021-04-16 15:46:12 -0500330 if (!mSurfaceControlsWithPendingCallback.empty()) {
331 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
332 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500333 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
334 if (statsOptional) {
335 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500336 mTransformHint = stat.transformHint;
337 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700338 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700339 // Update frametime stamps if the frame was latched and presented, indicated by a
340 // valid latch time.
341 if (stat.latchTime > 0) {
342 mBufferItemConsumer
343 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
344 stat.frameEventStats.refreshStartTime,
345 stat.frameEventStats.gpuCompositionDoneFence,
346 stat.presentFence, stat.previousReleaseFence,
347 stat.frameEventStats.compositorTiming,
348 stat.latchTime,
349 stat.frameEventStats.dequeueReadyTime);
350 }
chaviw42026162021-04-16 15:46:12 -0500351 currFrameNumber = stat.frameEventStats.frameNumber;
352
353 if (mTransactionCompleteCallback &&
354 currFrameNumber >= mTransactionCompleteFrameNumber) {
355 if (currFrameNumber > mTransactionCompleteFrameNumber) {
356 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
357 " than expected=%" PRIu64,
358 currFrameNumber, mTransactionCompleteFrameNumber);
359 }
360 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
361 mTransactionCompleteFrameNumber = 0;
362 }
chaviwd7deef72021-10-06 11:53:40 -0500363 } else {
chaviw42026162021-04-16 15:46:12 -0500364 BQA_LOGE("Failed to find matching SurfaceControl in transaction callback");
365 }
366 } else {
367 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
368 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800369 }
chaviw71c2cc42020-10-23 16:42:02 -0700370
chaviw71c2cc42020-10-23 16:42:02 -0700371 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700372 }
Valerie Haua32c5522019-12-09 10:11:08 -0800373
chaviw71c2cc42020-10-23 16:42:02 -0700374 if (transactionCompleteCallback) {
375 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800376 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700377}
378
Vishnu Nair1506b182021-02-22 14:35:15 -0800379// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
380// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
381// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
382// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700383static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500384 const sp<Fence>& releaseFence,
385 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800386 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800387 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500388 blastBufferQueue->releaseBufferCallback(id, releaseFence, 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
chaviwd7deef72021-10-06 11:53:40 -0500394void BLASTBufferQueue::flushShadowQueue() {
395 BQA_LOGV("flushShadowQueue");
396 int numFramesToFlush = mNumFrameAvailable;
397 while (numFramesToFlush > 0) {
398 acquireNextBufferLocked(std::nullopt);
399 numFramesToFlush--;
400 }
401}
402
chaviw69058fb2021-09-27 09:37:30 -0500403void BLASTBufferQueue::releaseBufferCallback(
404 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
405 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800406 ATRACE_CALL();
407 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700408 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800409
Ady Abraham899dcdb2021-06-15 16:56:21 -0700410 // Calculate how many buffers we need to hold before we release them back
411 // to the buffer queue. This will prevent higher latency when we are running
412 // on a lower refresh rate than the max supported. We only do that for EGL
413 // clients as others don't care about latency
414 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700415 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700416 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
417 }();
418
chaviw69058fb2021-09-27 09:37:30 -0500419 if (currentMaxAcquiredBufferCount) {
420 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
421 }
422
Ady Abraham899dcdb2021-06-15 16:56:21 -0700423 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500424 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700425 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700426
427 // Release all buffers that are beyond the ones that we need to hold
428 while (mPendingRelease.size() > numPendingBuffersToHold) {
429 const auto releaseBuffer = mPendingRelease.front();
430 mPendingRelease.pop_front();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700431 auto it = mSubmitted.find(releaseBuffer.callbackId);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700432 if (it == mSubmitted.end()) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700433 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
434 releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700435 return;
436 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700437 mNumAcquired--;
chaviw69058fb2021-09-27 09:37:30 -0500438 BQA_LOGV("released %s", releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700439 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
440 mSubmitted.erase(it);
chaviwd7deef72021-10-06 11:53:40 -0500441 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
442 // onFrameAvailable handle processing them since it will merge with the nextTransaction.
443 if (!mWaitForTransactionCallback) {
444 acquireNextBufferLocked(std::nullopt);
445 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800446 }
447
Ady Abraham899dcdb2021-06-15 16:56:21 -0700448 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700449 ATRACE_INT(mQueuedBufferTrace.c_str(),
450 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800451 mCallbackCV.notify_all();
452}
453
chaviwd7deef72021-10-06 11:53:40 -0500454void BLASTBufferQueue::acquireNextBufferLocked(
455 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800456 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800457 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
458 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500459 const bool includeExtraAcquire = !transaction;
460 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
461 if (mNumFrameAvailable == 0 || maxAcquired) {
462 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800463 return;
464 }
465
Valerie Haua32c5522019-12-09 10:11:08 -0800466 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700467 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800468 return;
469 }
470
Robert Carr78c25dd2019-08-15 14:10:33 -0700471 SurfaceComposerClient::Transaction localTransaction;
472 bool applyTransaction = true;
473 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500474 if (transaction) {
475 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700476 applyTransaction = false;
477 }
478
Valerie Haua32c5522019-12-09 10:11:08 -0800479 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800480
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800481 status_t status =
482 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800483 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
484 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
485 return;
486 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700487 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700488 return;
489 }
Valerie Haua32c5522019-12-09 10:11:08 -0800490 auto buffer = bufferItem.mGraphicBuffer;
491 mNumFrameAvailable--;
492
493 if (buffer == nullptr) {
494 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700495 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800496 return;
497 }
498
Vishnu Nair670b3f72020-09-29 17:52:18 -0700499 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700500 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800501 "buffer{size=%dx%d transform=%d}",
502 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
503 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
504 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500505 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800506 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700507 }
508
Valerie Haua32c5522019-12-09 10:11:08 -0800509 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700510 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
511 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
512 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700513
Valerie Hau871d6352020-01-29 08:44:02 -0800514 bool needsDisconnect = false;
515 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
516
517 // if producer disconnected before, notify SurfaceFlinger
518 if (needsDisconnect) {
519 t->notifyProducerDisconnect(mSurfaceControl);
520 }
521
Robert Carr78c25dd2019-08-15 14:10:33 -0700522 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
523 incStrong((void*)transactionCallbackThunk);
chaviwd7deef72021-10-06 11:53:40 -0500524 incStrong((void*)transactionCommittedCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700525
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700526 const bool sizeHasChanged = mRequestedSize != mSize;
527 mSize = mRequestedSize;
528 const bool updateDestinationFrame = sizeHasChanged || !mLastBufferInfo.hasBuffer;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700529 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000530 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
531 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700532 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800533
Vishnu Nair1506b182021-02-22 14:35:15 -0800534 auto releaseBufferCallback =
535 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500536 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500537 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
538 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseCallbackId,
539 releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500540 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
541 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
542 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700543 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwd7deef72021-10-06 11:53:40 -0500544 t->addTransactionCommittedCallback(transactionCommittedCallbackThunk, static_cast<void*>(this));
chaviw42026162021-04-16 15:46:12 -0500545 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700546
Vishnu Nair084514a2021-07-30 16:07:42 -0700547 if (updateDestinationFrame) {
548 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
549 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700550 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800551 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800552 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800553 if (!bufferItem.mIsAutoTimestamp) {
554 t->setDesiredPresentTime(bufferItem.mTimestamp);
555 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700556
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000557 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700558 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000559 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100560 }
561
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800562 if (mAutoRefresh != bufferItem.mAutoRefresh) {
563 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
564 mAutoRefresh = bufferItem.mAutoRefresh;
565 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800566 {
567 std::unique_lock _lock{mTimestampMutex};
568 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
569 if (dequeueTime != mDequeueTimestamps.end()) {
570 Parcel p;
571 p.writeInt64(dequeueTime->second);
572 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
573 mDequeueTimestamps.erase(dequeueTime);
574 }
575 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800576
chaviw6a195272021-09-03 16:14:25 -0500577 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700578 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800579 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700580 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700581
chaviwd7deef72021-10-06 11:53:40 -0500582 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800583 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700584 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500585 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800586 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700587 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700588 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700589}
590
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800591Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
592 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800593 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800594 }
595 return item.mCrop;
596}
597
chaviwd7deef72021-10-06 11:53:40 -0500598void BLASTBufferQueue::acquireAndReleaseBuffer() {
599 BufferItem bufferItem;
600 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
601 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
602 mNumFrameAvailable--;
603}
604
Vishnu Nairaef1de92020-10-22 12:15:53 -0700605void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800606 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800607 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800608
Vishnu Nairdab94092020-09-29 16:09:04 -0700609 const bool nextTransactionSet = mNextTransaction != nullptr;
chaviwd7deef72021-10-06 11:53:40 -0500610 BQA_LOGV("onFrameAvailable-start nextTransactionSet=%s", boolToString(nextTransactionSet));
Vishnu Nair1506b182021-02-22 14:35:15 -0800611 if (nextTransactionSet) {
chaviwd7deef72021-10-06 11:53:40 -0500612 if (mWaitForTransactionCallback) {
613 // We are waiting on a previous sync's transaction callback so allow another sync
614 // transaction to proceed.
615 //
616 // We need to first flush out the transactions that were in between the two syncs.
617 // We do this by merging them into mNextTransaction so any buffer merging will get
618 // a release callback invoked. The release callback will be async so we need to wait
619 // on max acquired to make sure we have the capacity to acquire another buffer.
620 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
621 BQA_LOGD("waiting to flush shadow queue...");
622 mCallbackCV.wait(_lock);
623 }
624 while (mNumFrameAvailable > 0) {
625 // flush out the shadow queue
626 acquireAndReleaseBuffer();
627 }
628 }
629
630 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
631 BQA_LOGD("waiting for free buffer.");
Valerie Hau0188adf2020-02-13 08:29:20 -0800632 mCallbackCV.wait(_lock);
633 }
634 }
chaviwd7deef72021-10-06 11:53:40 -0500635
Valerie Haud3b90d22019-11-06 09:37:31 -0800636 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800637 mNumFrameAvailable++;
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700638 ATRACE_INT(mQueuedBufferTrace.c_str(),
639 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800640
641 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
chaviw3277faf2021-05-19 16:45:23 -0500642 boolToString(nextTransactionSet));
chaviwd7deef72021-10-06 11:53:40 -0500643
644 if (nextTransactionSet) {
645 acquireNextBufferLocked(std::move(mNextTransaction));
646 mNextTransaction = nullptr;
647 mWaitForTransactionCallback = true;
648 } else if (!mWaitForTransactionCallback) {
649 acquireNextBufferLocked(std::nullopt);
650 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800651}
652
Vishnu Nairaef1de92020-10-22 12:15:53 -0700653void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
654 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
655 // Do nothing since we are not storing unacquired buffer items locally.
656}
657
Vishnu Nairadf632b2021-01-07 14:05:08 -0800658void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
659 std::unique_lock _lock{mTimestampMutex};
660 mDequeueTimestamps[bufferId] = systemTime();
661};
662
663void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
664 std::unique_lock _lock{mTimestampMutex};
665 mDequeueTimestamps.erase(bufferId);
666};
667
Robert Carr78c25dd2019-08-15 14:10:33 -0700668void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800669 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700670 mNextTransaction = t;
671}
672
Vishnu Nairea0de002020-11-17 17:42:37 -0800673bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700674 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
675 // Only reject buffers if scaling mode is freeze.
676 return false;
677 }
678
Vishnu Naire1a42322020-10-02 17:42:04 -0700679 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
680 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
681
682 // Take the buffer's orientation into account
683 if (item.mTransform & ui::Transform::ROT_90) {
684 std::swap(bufWidth, bufHeight);
685 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800686 ui::Size bufferSize(bufWidth, bufHeight);
687 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800688 return false;
689 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700690
Vishnu Nair670b3f72020-09-29 17:52:18 -0700691 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800692 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700693}
Vishnu Nairbf255772020-10-16 10:54:41 -0700694
chaviw71c2cc42020-10-23 16:42:02 -0700695void BLASTBufferQueue::setTransactionCompleteCallback(
696 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
697 std::lock_guard _lock{mMutex};
698 if (transactionCompleteCallback == nullptr) {
699 mTransactionCompleteCallback = nullptr;
700 } else {
701 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
702 mTransactionCompleteFrameNumber = frameNumber;
703 }
704}
705
Vishnu Nairbf255772020-10-16 10:54:41 -0700706// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800707// Consumer can acquire an additional buffer if that buffer is not droppable. Set
708// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
709// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
710bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700711 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800712 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700713}
714
Robert Carr05086b22020-10-13 18:22:51 -0700715class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700716private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700717 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700718 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700719 bool mDestroyed = false;
720
Robert Carr05086b22020-10-13 18:22:51 -0700721public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700722 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
723 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
724 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700725
Robert Carr05086b22020-10-13 18:22:51 -0700726 void allocateBuffers() override {
727 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
728 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
729 auto gbp = getIGraphicBufferProducer();
730 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
731 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
732 gbp->allocateBuffers(reqWidth, reqHeight,
733 reqFormat, reqUsage);
734
735 }).detach();
736 }
Robert Carr9c006e02020-10-14 13:41:57 -0700737
Marin Shalamanovc5986772021-03-16 16:09:49 +0100738 status_t setFrameRate(float frameRate, int8_t compatibility,
739 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700740 std::unique_lock _lock{mMutex};
741 if (mDestroyed) {
742 return DEAD_OBJECT;
743 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100744 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
745 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700746 return BAD_VALUE;
747 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100748 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700749 }
Robert Carr9b611b72020-10-19 12:00:23 -0700750
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000751 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700752 std::unique_lock _lock{mMutex};
753 if (mDestroyed) {
754 return DEAD_OBJECT;
755 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000756 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700757 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700758
759 void destroy() override {
760 Surface::destroy();
761
762 std::unique_lock _lock{mMutex};
763 mDestroyed = true;
764 mBbq = nullptr;
765 }
Robert Carr05086b22020-10-13 18:22:51 -0700766};
767
Robert Carr9c006e02020-10-14 13:41:57 -0700768// TODO: Can we coalesce this with frame updates? Need to confirm
769// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200770status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
771 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700772 std::unique_lock _lock{mMutex};
773 SurfaceComposerClient::Transaction t;
774
Marin Shalamanov46084422020-10-13 12:33:42 +0200775 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700776}
777
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000778status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700779 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000780 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100781 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700782}
783
Hongguang Chen621ec582021-02-16 15:42:35 -0800784void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
785 std::unique_lock _lock{mMutex};
786 SurfaceComposerClient::Transaction t;
787
788 t.setSidebandStream(mSurfaceControl, stream).apply();
789}
790
Vishnu Nair992496b2020-10-22 17:27:21 -0700791sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
792 std::unique_lock _lock{mMutex};
793 sp<IBinder> scHandle = nullptr;
794 if (includeSurfaceControlHandle && mSurfaceControl) {
795 scHandle = mSurfaceControl->getHandle();
796 }
797 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700798}
799
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800800void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
801 uint64_t frameNumber) {
802 std::lock_guard _lock{mMutex};
803 if (mLastAcquiredFrameNumber >= frameNumber) {
804 // Apply the transaction since we have already acquired the desired frame.
805 t->apply();
806 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500807 mPendingTransactions.emplace_back(frameNumber, *t);
808 // Clear the transaction so it can't be applied elsewhere.
809 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800810 }
811}
812
chaviw6a195272021-09-03 16:14:25 -0500813void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
814 std::lock_guard _lock{mMutex};
815
816 SurfaceComposerClient::Transaction t;
817 mergePendingTransactions(&t, frameNumber);
818 t.setApplyToken(mApplyToken).apply();
819}
820
821void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
822 uint64_t frameNumber) {
823 auto mergeTransaction =
824 [&t, currentFrameNumber = frameNumber](
825 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
826 auto& [targetFrameNumber, transaction] = pendingTransaction;
827 if (currentFrameNumber < targetFrameNumber) {
828 return false;
829 }
830 t->merge(std::move(transaction));
831 return true;
832 };
833
834 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
835 mPendingTransactions.end(), mergeTransaction),
836 mPendingTransactions.end());
837}
838
Vishnu Nair89496122020-12-14 17:14:53 -0800839// Maintains a single worker thread per process that services a list of runnables.
840class AsyncWorker : public Singleton<AsyncWorker> {
841private:
842 std::thread mThread;
843 bool mDone = false;
844 std::deque<std::function<void()>> mRunnables;
845 std::mutex mMutex;
846 std::condition_variable mCv;
847 void run() {
848 std::unique_lock<std::mutex> lock(mMutex);
849 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800850 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700851 std::deque<std::function<void()>> runnables = std::move(mRunnables);
852 mRunnables.clear();
853 lock.unlock();
854 // Run outside the lock since the runnable might trigger another
855 // post to the async worker.
856 execute(runnables);
857 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800858 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700859 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800860 }
861 }
862
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700863 void execute(std::deque<std::function<void()>>& runnables) {
864 while (!runnables.empty()) {
865 std::function<void()> runnable = runnables.front();
866 runnables.pop_front();
867 runnable();
868 }
869 }
870
Vishnu Nair89496122020-12-14 17:14:53 -0800871public:
872 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
873
874 ~AsyncWorker() {
875 mDone = true;
876 mCv.notify_all();
877 if (mThread.joinable()) {
878 mThread.join();
879 }
880 }
881
882 void post(std::function<void()> runnable) {
883 std::unique_lock<std::mutex> lock(mMutex);
884 mRunnables.emplace_back(std::move(runnable));
885 mCv.notify_one();
886 }
887};
888ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
889
890// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
891class AsyncProducerListener : public BnProducerListener {
892private:
893 const sp<IProducerListener> mListener;
894
895public:
896 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
897
898 void onBufferReleased() override {
899 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
900 }
901
902 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
903 AsyncWorker::getInstance().post(
904 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
905 }
906};
907
908// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
909// can be non-blocking when the producer is in the client process.
910class BBQBufferQueueProducer : public BufferQueueProducer {
911public:
912 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
913 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
914
915 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
916 QueueBufferOutput* output) override {
917 if (!listener) {
918 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
919 }
920
921 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
922 producerControlledByApp, output);
923 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800924
925 int query(int what, int* value) override {
926 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
927 *value = 1;
928 return NO_ERROR;
929 }
930 return BufferQueueProducer::query(what, value);
931 }
Vishnu Nair89496122020-12-14 17:14:53 -0800932};
933
934// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
935// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
936// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
937// we can deadlock.
938void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
939 sp<IGraphicBufferConsumer>* outConsumer) {
940 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
941 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
942
943 sp<BufferQueueCore> core(new BufferQueueCore());
944 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
945
946 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
947 LOG_ALWAYS_FATAL_IF(producer == nullptr,
948 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
949
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800950 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
951 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800952 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
953 "BLASTBufferQueue: failed to create BufferQueueConsumer");
954
955 *outProducer = producer;
956 *outConsumer = consumer;
957}
958
chaviw497e81c2021-02-04 17:09:47 -0800959PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
960 PixelFormat convertedFormat = format;
961 switch (format) {
962 case PIXEL_FORMAT_TRANSPARENT:
963 case PIXEL_FORMAT_TRANSLUCENT:
964 convertedFormat = PIXEL_FORMAT_RGBA_8888;
965 break;
966 case PIXEL_FORMAT_OPAQUE:
967 convertedFormat = PIXEL_FORMAT_RGBX_8888;
968 break;
969 }
970 return convertedFormat;
971}
972
Robert Carr82d07c92021-05-10 11:36:43 -0700973uint32_t BLASTBufferQueue::getLastTransformHint() const {
974 if (mSurfaceControl != nullptr) {
975 return mSurfaceControl->getTransformHint();
976 } else {
977 return 0;
978 }
979}
980
chaviw0b020f82021-08-20 12:00:47 -0500981uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
982 std::unique_lock _lock{mMutex};
983 return mLastAcquiredFrameNumber;
984}
985
Robert Carr78c25dd2019-08-15 14:10:33 -0700986} // namespace android