blob: bcdd06b6c89eb9fa9f9f0d69822ff7812645ca3a [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>
Robert Carr78c25dd2019-08-15 14:10:33 -070032
Valerie Haua32c5522019-12-09 10:11:08 -080033#include <utils/Trace.h>
34
Robert Carr78c25dd2019-08-15 14:10:33 -070035#include <chrono>
36
37using namespace std::chrono_literals;
38
Vishnu Nairdab94092020-09-29 16:09:04 -070039namespace {
40inline const char* toString(bool b) {
41 return b ? "true" : "false";
42}
43} // namespace
44
Robert Carr78c25dd2019-08-15 14:10:33 -070045namespace android {
46
Vishnu Nairdab94092020-09-29 16:09:04 -070047// Macros to include adapter info in log messages
48#define BQA_LOGV(x, ...) \
49 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080050// enable logs for a single layer
51//#define BQA_LOGV(x, ...) \
52// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
53// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070054#define BQA_LOGE(x, ...) \
55 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
56
Valerie Hau871d6352020-01-29 08:44:02 -080057void BLASTBufferItemConsumer::onDisconnect() {
Hongguang Chen621ec582021-02-16 15:42:35 -080058 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080059 mPreviouslyConnected = mCurrentlyConnected;
60 mCurrentlyConnected = false;
61 if (mPreviouslyConnected) {
62 mDisconnectEvents.push(mCurrentFrameNumber);
63 }
64 mFrameEventHistory.onDisconnect();
65}
66
67void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
68 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080069 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080070 if (newTimestamps) {
71 // BufferQueueProducer only adds a new timestamp on
72 // queueBuffer
73 mCurrentFrameNumber = newTimestamps->frameNumber;
74 mFrameEventHistory.addQueue(*newTimestamps);
75 }
76 if (outDelta) {
77 // frame event histories will be processed
78 // only after the producer connects and requests
79 // deltas for the first time. Forward this intent
80 // to SF-side to turn event processing back on
81 mPreviouslyConnected = mCurrentlyConnected;
82 mCurrentlyConnected = true;
83 mFrameEventHistory.getAndResetDelta(outDelta);
84 }
85}
86
87void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
88 const sp<Fence>& glDoneFence,
89 const sp<Fence>& presentFence,
90 const sp<Fence>& prevReleaseFence,
91 CompositorTiming compositorTiming,
92 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -080093 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080094
95 // if the producer is not connected, don't bother updating,
96 // the next producer that connects won't access this frame event
97 if (!mCurrentlyConnected) return;
98 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
99 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
100 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
101
102 mFrameEventHistory.addLatch(frameNumber, latchTime);
103 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
104 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
105 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
106 compositorTiming);
107}
108
109void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
110 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800111 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800112 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
113 disconnect = true;
114 mDisconnectEvents.pop();
115 }
116 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
117}
118
Hongguang Chen621ec582021-02-16 15:42:35 -0800119void BLASTBufferItemConsumer::setBlastBufferQueue(BLASTBufferQueue* blastbufferqueue) {
120 Mutex::Autolock lock(mMutex);
121 mBLASTBufferQueue = blastbufferqueue;
122}
123
124void BLASTBufferItemConsumer::onSidebandStreamChanged() {
125 Mutex::Autolock lock(mMutex);
126 if (mBLASTBufferQueue != nullptr) {
127 sp<NativeHandle> stream = getSidebandStream();
128 mBLASTBufferQueue->setSidebandStream(stream);
129 }
130}
131
Vishnu Nairdab94092020-09-29 16:09:04 -0700132BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700133 int width, int height, int32_t format)
Vishnu Nairdab94092020-09-29 16:09:04 -0700134 : mName(name),
135 mSurfaceControl(surface),
Vishnu Nairea0de002020-11-17 17:42:37 -0800136 mSize(width, height),
137 mRequestedSize(mSize),
chaviw565ee542021-01-14 10:21:23 -0800138 mFormat(format),
Valerie Haud3b90d22019-11-06 09:37:31 -0800139 mNextTransaction(nullptr) {
Vishnu Nair89496122020-12-14 17:14:53 -0800140 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800141 // since the adapter is in the client process, set dequeue timeout
142 // explicitly so that dequeueBuffer will block
143 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800144
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700145 // safe default, most producers are expected to override this
146 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800147 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
148 GraphicBuffer::USAGE_HW_COMPOSER |
149 GraphicBuffer::USAGE_HW_TEXTURE,
150 1, false);
Valerie Haua32c5522019-12-09 10:11:08 -0800151 static int32_t id = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700152 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800153 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700154 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700155 mBufferItemConsumer->setFrameAvailableListener(this);
156 mBufferItemConsumer->setBufferFreedListener(this);
Vishnu Nairea0de002020-11-17 17:42:37 -0800157 mBufferItemConsumer->setDefaultBufferSize(mSize.width, mSize.height);
chaviw497e81c2021-02-04 17:09:47 -0800158 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
Hongguang Chen621ec582021-02-16 15:42:35 -0800159 mBufferItemConsumer->setBlastBufferQueue(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700160
Valerie Hau2882e982020-01-23 13:33:10 -0800161 mTransformHint = mSurfaceControl->getTransformHint();
Robert Carr9f133d72020-04-01 15:51:46 -0700162 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800163 SurfaceComposerClient::Transaction()
164 .setFlags(surface, layer_state_t::eEnableBackpressure,
165 layer_state_t::eEnableBackpressure)
166 .apply();
Valerie Haud3b90d22019-11-06 09:37:31 -0800167
Valerie Haua32c5522019-12-09 10:11:08 -0800168 mNumAcquired = 0;
169 mNumFrameAvailable = 0;
Robert Carr78c25dd2019-08-15 14:10:33 -0700170}
171
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800172BLASTBufferQueue::~BLASTBufferQueue() {
Hongguang Chen621ec582021-02-16 15:42:35 -0800173 mBufferItemConsumer->setBlastBufferQueue(nullptr);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800174 if (mPendingTransactions.empty()) {
175 return;
176 }
177 BQA_LOGE("Applying pending transactions on dtor %d",
178 static_cast<uint32_t>(mPendingTransactions.size()));
179 SurfaceComposerClient::Transaction t;
180 for (auto& [targetFrameNumber, transaction] : mPendingTransactions) {
181 t.merge(std::move(transaction));
182 }
183 t.apply();
184}
185
chaviw565ee542021-01-14 10:21:23 -0800186void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
187 int32_t format) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700188 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800189 if (mFormat != format) {
190 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800191 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800192 }
193
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800194 SurfaceComposerClient::Transaction t;
195 bool applyTransaction = false;
196 if (!SurfaceControl::isSameSurface(mSurfaceControl, surface)) {
197 mSurfaceControl = surface;
198 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
199 layer_state_t::eEnableBackpressure);
200 applyTransaction = true;
201 }
202
Vishnu Nairea0de002020-11-17 17:42:37 -0800203 ui::Size newSize(width, height);
204 if (mRequestedSize != newSize) {
205 mRequestedSize.set(newSize);
206 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Orion Hodson1014c4b2021-04-08 12:30:21 +0000207 if (mLastBufferScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800208 // If the buffer supports scaling, update the frame immediately since the client may
209 // want to scale the existing buffer to the new size.
210 mSize = mRequestedSize;
Orion Hodson1014c4b2021-04-08 12:30:21 +0000211 t.setFrame(mSurfaceControl,
212 {0, 0, static_cast<int32_t>(mSize.width),
213 static_cast<int32_t>(mSize.height)});
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800214 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800215 }
Robert Carrfc416512020-04-02 12:32:44 -0700216 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800217 if (applyTransaction) {
218 t.apply();
219 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700220}
221
222static void transactionCallbackThunk(void* context, nsecs_t latchTime,
223 const sp<Fence>& presentFence,
224 const std::vector<SurfaceControlStats>& stats) {
225 if (context == nullptr) {
226 return;
227 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800228 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700229 bq->transactionCallback(latchTime, presentFence, stats);
230}
231
232void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
233 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700234 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
235 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700236
chaviw71c2cc42020-10-23 16:42:02 -0700237 {
238 std::unique_lock _lock{mMutex};
239 ATRACE_CALL();
240 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700241
Valerie Hau871d6352020-01-29 08:44:02 -0800242 if (!stats.empty()) {
chaviw71c2cc42020-10-23 16:42:02 -0700243 mTransformHint = stats[0].transformHint;
244 mBufferItemConsumer->setTransformHint(mTransformHint);
245 mBufferItemConsumer
246 ->updateFrameTimestamps(stats[0].frameEventStats.frameNumber,
247 stats[0].frameEventStats.refreshStartTime,
248 stats[0].frameEventStats.gpuCompositionDoneFence,
249 stats[0].presentFence, stats[0].previousReleaseFence,
250 stats[0].frameEventStats.compositorTiming,
251 stats[0].latchTime,
252 stats[0].frameEventStats.dequeueReadyTime);
Vishnu Nair1506b182021-02-22 14:35:15 -0800253 currFrameNumber = stats[0].frameEventStats.frameNumber;
254
255 if (mTransactionCompleteCallback &&
256 currFrameNumber >= mTransactionCompleteFrameNumber) {
257 if (currFrameNumber > mTransactionCompleteFrameNumber) {
258 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
259 " than expected=%" PRIu64,
260 currFrameNumber, mTransactionCompleteFrameNumber);
261 }
262 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
263 mTransactionCompleteFrameNumber = 0;
chaviw71c2cc42020-10-23 16:42:02 -0700264 }
Valerie Haua32c5522019-12-09 10:11:08 -0800265 }
chaviw71c2cc42020-10-23 16:42:02 -0700266
chaviw71c2cc42020-10-23 16:42:02 -0700267 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700268 }
Valerie Haua32c5522019-12-09 10:11:08 -0800269
chaviw71c2cc42020-10-23 16:42:02 -0700270 if (transactionCompleteCallback) {
271 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800272 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700273}
274
Vishnu Nair1506b182021-02-22 14:35:15 -0800275// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
276// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
277// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
278// Otherwise, this is a no-op.
279static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, uint64_t graphicBufferId,
280 const sp<Fence>& releaseFence) {
281 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
282 ALOGV("releaseBufferCallbackThunk graphicBufferId=%" PRIu64 " blastBufferQueue=%s",
283 graphicBufferId, blastBufferQueue ? "alive" : "dead");
284 if (blastBufferQueue) {
285 blastBufferQueue->releaseBufferCallback(graphicBufferId, releaseFence);
286 }
287}
288
289void BLASTBufferQueue::releaseBufferCallback(uint64_t graphicBufferId,
290 const sp<Fence>& releaseFence) {
291 ATRACE_CALL();
292 std::unique_lock _lock{mMutex};
293 BQA_LOGV("releaseBufferCallback graphicBufferId=%" PRIu64, graphicBufferId);
294
295 auto it = mSubmitted.find(graphicBufferId);
296 if (it == mSubmitted.end()) {
297 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %" PRIu64,
298 graphicBufferId);
299 return;
300 }
301
302 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
303 mSubmitted.erase(it);
304 mNumAcquired--;
305 processNextBufferLocked(false /* useNextTransaction */);
306 mCallbackCV.notify_all();
307}
308
Robert Carr255acdc2020-04-17 14:08:55 -0700309void BLASTBufferQueue::processNextBufferLocked(bool useNextTransaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800310 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800311 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
312 // include the extra buffer when checking if we can acquire the next buffer.
313 const bool includeExtraAcquire = !useNextTransaction;
314 if (mNumFrameAvailable == 0 || maxBuffersAcquired(includeExtraAcquire)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800315 mCallbackCV.notify_all();
Valerie Haud3b90d22019-11-06 09:37:31 -0800316 return;
317 }
318
Valerie Haua32c5522019-12-09 10:11:08 -0800319 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700320 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800321 return;
322 }
323
Robert Carr78c25dd2019-08-15 14:10:33 -0700324 SurfaceComposerClient::Transaction localTransaction;
325 bool applyTransaction = true;
326 SurfaceComposerClient::Transaction* t = &localTransaction;
Robert Carr255acdc2020-04-17 14:08:55 -0700327 if (mNextTransaction != nullptr && useNextTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700328 t = mNextTransaction;
329 mNextTransaction = nullptr;
330 applyTransaction = false;
331 }
332
Valerie Haua32c5522019-12-09 10:11:08 -0800333 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800334
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800335 status_t status =
336 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800337 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
338 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
339 return;
340 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700341 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700342 return;
343 }
Valerie Haua32c5522019-12-09 10:11:08 -0800344 auto buffer = bufferItem.mGraphicBuffer;
345 mNumFrameAvailable--;
346
347 if (buffer == nullptr) {
348 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700349 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800350 return;
351 }
352
Vishnu Nair670b3f72020-09-29 17:52:18 -0700353 if (rejectBuffer(bufferItem)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800354 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d"
355 "buffer{size=%dx%d transform=%d}",
356 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
357 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
358 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
359 processNextBufferLocked(useNextTransaction);
360 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700361 }
362
Valerie Haua32c5522019-12-09 10:11:08 -0800363 mNumAcquired++;
Vishnu Nair1506b182021-02-22 14:35:15 -0800364 mSubmitted[buffer->getId()] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700365
Valerie Hau871d6352020-01-29 08:44:02 -0800366 bool needsDisconnect = false;
367 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
368
369 // if producer disconnected before, notify SurfaceFlinger
370 if (needsDisconnect) {
371 t->notifyProducerDisconnect(mSurfaceControl);
372 }
373
Robert Carr78c25dd2019-08-15 14:10:33 -0700374 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
375 incStrong((void*)transactionCallbackThunk);
376
Orion Hodson1014c4b2021-04-08 12:30:21 +0000377 mLastBufferScalingMode = bufferItem.mScalingMode;
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800378 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800379
Vishnu Nair1506b182021-02-22 14:35:15 -0800380 auto releaseBufferCallback =
381 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
382 std::placeholders::_1, std::placeholders::_2);
383 t->setBuffer(mSurfaceControl, buffer, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500384 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
385 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
386 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700387 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800388 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700389 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
390
Orion Hodson1014c4b2021-04-08 12:30:21 +0000391 t->setFrame(mSurfaceControl,
392 {0, 0, static_cast<int32_t>(mSize.width), static_cast<int32_t>(mSize.height)});
Valerie Haua32c5522019-12-09 10:11:08 -0800393 t->setCrop(mSurfaceControl, computeCrop(bufferItem));
394 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800395 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800396 if (!bufferItem.mIsAutoTimestamp) {
397 t->setDesiredPresentTime(bufferItem.mTimestamp);
398 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700399 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700400
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000401 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700402 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000403 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100404 }
405
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800406 if (mAutoRefresh != bufferItem.mAutoRefresh) {
407 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
408 mAutoRefresh = bufferItem.mAutoRefresh;
409 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800410 {
411 std::unique_lock _lock{mTimestampMutex};
412 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
413 if (dequeueTime != mDequeueTimestamps.end()) {
414 Parcel p;
415 p.writeInt64(dequeueTime->second);
416 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
417 mDequeueTimestamps.erase(dequeueTime);
418 }
419 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800420
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800421 auto mergeTransaction =
422 [&t, currentFrameNumber = bufferItem.mFrameNumber](
423 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
424 auto& [targetFrameNumber, transaction] = pendingTransaction;
425 if (currentFrameNumber < targetFrameNumber) {
426 return false;
427 }
428 t->merge(std::move(transaction));
429 return true;
430 };
431
432 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
433 mPendingTransactions.end(), mergeTransaction),
434 mPendingTransactions.end());
435
Robert Carr78c25dd2019-08-15 14:10:33 -0700436 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800437 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700438 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700439
440 BQA_LOGV("processNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800441 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
442 " graphicBufferId=%" PRIu64,
Vishnu Nairea0de002020-11-17 17:42:37 -0800443 mSize.width, mSize.height, bufferItem.mFrameNumber, toString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800444 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
445 static_cast<uint32_t>(mPendingTransactions.size()),
446 bufferItem.mGraphicBuffer->getId());
Robert Carr78c25dd2019-08-15 14:10:33 -0700447}
448
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800449Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
450 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800451 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800452 }
453 return item.mCrop;
454}
455
Vishnu Nairaef1de92020-10-22 12:15:53 -0700456void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800457 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800458 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800459
Vishnu Nairdab94092020-09-29 16:09:04 -0700460 const bool nextTransactionSet = mNextTransaction != nullptr;
Vishnu Nair1506b182021-02-22 14:35:15 -0800461 if (nextTransactionSet) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800462 while (mNumFrameAvailable > 0 || maxBuffersAcquired(false /* includeExtraAcquire */)) {
Vishnu Nair7eb670a2020-10-15 12:16:10 -0700463 BQA_LOGV("waiting in onFrameAvailable...");
Valerie Hau0188adf2020-02-13 08:29:20 -0800464 mCallbackCV.wait(_lock);
465 }
466 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800467 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800468 mNumFrameAvailable++;
Vishnu Nair1506b182021-02-22 14:35:15 -0800469
470 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
471 toString(nextTransactionSet));
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800472 processNextBufferLocked(nextTransactionSet /* useNextTransaction */);
Valerie Haud3b90d22019-11-06 09:37:31 -0800473}
474
Vishnu Nairaef1de92020-10-22 12:15:53 -0700475void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
476 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
477 // Do nothing since we are not storing unacquired buffer items locally.
478}
479
Vishnu Nairadf632b2021-01-07 14:05:08 -0800480void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
481 std::unique_lock _lock{mTimestampMutex};
482 mDequeueTimestamps[bufferId] = systemTime();
483};
484
485void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
486 std::unique_lock _lock{mTimestampMutex};
487 mDequeueTimestamps.erase(bufferId);
488};
489
Robert Carr78c25dd2019-08-15 14:10:33 -0700490void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800491 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700492 mNextTransaction = t;
493}
494
Vishnu Nairea0de002020-11-17 17:42:37 -0800495bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700496 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
497 // Only reject buffers if scaling mode is freeze.
498 return false;
499 }
500
Vishnu Naire1a42322020-10-02 17:42:04 -0700501 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
502 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
503
504 // Take the buffer's orientation into account
505 if (item.mTransform & ui::Transform::ROT_90) {
506 std::swap(bufWidth, bufHeight);
507 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800508 ui::Size bufferSize(bufWidth, bufHeight);
509 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
510 mSize = mRequestedSize;
511 return false;
512 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700513
Vishnu Nair670b3f72020-09-29 17:52:18 -0700514 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800515 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700516}
Vishnu Nairbf255772020-10-16 10:54:41 -0700517
chaviw71c2cc42020-10-23 16:42:02 -0700518void BLASTBufferQueue::setTransactionCompleteCallback(
519 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
520 std::lock_guard _lock{mMutex};
521 if (transactionCompleteCallback == nullptr) {
522 mTransactionCompleteCallback = nullptr;
523 } else {
524 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
525 mTransactionCompleteFrameNumber = frameNumber;
526 }
527}
528
Vishnu Nairbf255772020-10-16 10:54:41 -0700529// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800530// Consumer can acquire an additional buffer if that buffer is not droppable. Set
531// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
532// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
533bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
534 int maxAcquiredBuffers = MAX_ACQUIRED_BUFFERS + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800535 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700536}
537
Robert Carr05086b22020-10-13 18:22:51 -0700538class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700539private:
540 sp<BLASTBufferQueue> mBbq;
Robert Carr05086b22020-10-13 18:22:51 -0700541public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700542 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
543 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
544 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700545
Robert Carr05086b22020-10-13 18:22:51 -0700546 void allocateBuffers() override {
547 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
548 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
549 auto gbp = getIGraphicBufferProducer();
550 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
551 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
552 gbp->allocateBuffers(reqWidth, reqHeight,
553 reqFormat, reqUsage);
554
555 }).detach();
556 }
Robert Carr9c006e02020-10-14 13:41:57 -0700557
Marin Shalamanovc5986772021-03-16 16:09:49 +0100558 status_t setFrameRate(float frameRate, int8_t compatibility,
559 int8_t changeFrameRateStrategy) override {
560 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
561 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700562 return BAD_VALUE;
563 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100564 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700565 }
Robert Carr9b611b72020-10-19 12:00:23 -0700566
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000567 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
568 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700569 }
Robert Carr05086b22020-10-13 18:22:51 -0700570};
571
Robert Carr9c006e02020-10-14 13:41:57 -0700572// TODO: Can we coalesce this with frame updates? Need to confirm
573// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200574status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
575 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700576 std::unique_lock _lock{mMutex};
577 SurfaceComposerClient::Transaction t;
578
Marin Shalamanov46084422020-10-13 12:33:42 +0200579 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700580}
581
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000582status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700583 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000584 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100585 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700586}
587
Hongguang Chen621ec582021-02-16 15:42:35 -0800588void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
589 std::unique_lock _lock{mMutex};
590 SurfaceComposerClient::Transaction t;
591
592 t.setSidebandStream(mSurfaceControl, stream).apply();
593}
594
Vishnu Nair992496b2020-10-22 17:27:21 -0700595sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
596 std::unique_lock _lock{mMutex};
597 sp<IBinder> scHandle = nullptr;
598 if (includeSurfaceControlHandle && mSurfaceControl) {
599 scHandle = mSurfaceControl->getHandle();
600 }
601 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700602}
603
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800604void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
605 uint64_t frameNumber) {
606 std::lock_guard _lock{mMutex};
607 if (mLastAcquiredFrameNumber >= frameNumber) {
608 // Apply the transaction since we have already acquired the desired frame.
609 t->apply();
610 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500611 mPendingTransactions.emplace_back(frameNumber, *t);
612 // Clear the transaction so it can't be applied elsewhere.
613 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800614 }
615}
616
Vishnu Nair89496122020-12-14 17:14:53 -0800617// Maintains a single worker thread per process that services a list of runnables.
618class AsyncWorker : public Singleton<AsyncWorker> {
619private:
620 std::thread mThread;
621 bool mDone = false;
622 std::deque<std::function<void()>> mRunnables;
623 std::mutex mMutex;
624 std::condition_variable mCv;
625 void run() {
626 std::unique_lock<std::mutex> lock(mMutex);
627 while (!mDone) {
628 mCv.wait(lock);
629 while (!mRunnables.empty()) {
630 std::function<void()> runnable = mRunnables.front();
631 mRunnables.pop_front();
632 runnable();
633 }
634 }
635 }
636
637public:
638 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
639
640 ~AsyncWorker() {
641 mDone = true;
642 mCv.notify_all();
643 if (mThread.joinable()) {
644 mThread.join();
645 }
646 }
647
648 void post(std::function<void()> runnable) {
649 std::unique_lock<std::mutex> lock(mMutex);
650 mRunnables.emplace_back(std::move(runnable));
651 mCv.notify_one();
652 }
653};
654ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
655
656// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
657class AsyncProducerListener : public BnProducerListener {
658private:
659 const sp<IProducerListener> mListener;
660
661public:
662 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
663
664 void onBufferReleased() override {
665 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
666 }
667
668 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
669 AsyncWorker::getInstance().post(
670 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
671 }
672};
673
674// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
675// can be non-blocking when the producer is in the client process.
676class BBQBufferQueueProducer : public BufferQueueProducer {
677public:
678 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
679 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
680
681 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
682 QueueBufferOutput* output) override {
683 if (!listener) {
684 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
685 }
686
687 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
688 producerControlledByApp, output);
689 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800690
691 int query(int what, int* value) override {
692 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
693 *value = 1;
694 return NO_ERROR;
695 }
696 return BufferQueueProducer::query(what, value);
697 }
Vishnu Nair89496122020-12-14 17:14:53 -0800698};
699
700// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
701// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
702// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
703// we can deadlock.
704void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
705 sp<IGraphicBufferConsumer>* outConsumer) {
706 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
707 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
708
709 sp<BufferQueueCore> core(new BufferQueueCore());
710 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
711
712 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
713 LOG_ALWAYS_FATAL_IF(producer == nullptr,
714 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
715
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800716 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
717 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800718 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
719 "BLASTBufferQueue: failed to create BufferQueueConsumer");
720
721 *outProducer = producer;
722 *outConsumer = consumer;
723}
724
chaviw497e81c2021-02-04 17:09:47 -0800725PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
726 PixelFormat convertedFormat = format;
727 switch (format) {
728 case PIXEL_FORMAT_TRANSPARENT:
729 case PIXEL_FORMAT_TRANSLUCENT:
730 convertedFormat = PIXEL_FORMAT_RGBA_8888;
731 break;
732 case PIXEL_FORMAT_OPAQUE:
733 convertedFormat = PIXEL_FORMAT_RGBX_8888;
734 break;
735 }
736 return convertedFormat;
737}
738
Robert Carr78c25dd2019-08-15 14:10:33 -0700739} // namespace android