blob: dc943a567fedf3835e2a99cb100d802373da3086 [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 {
41inline const char* toString(bool b) {
42 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
49#define BQA_LOGV(x, ...) \
50 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080051// enable logs for a single layer
52//#define BQA_LOGV(x, ...) \
53// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
54// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070055#define BQA_LOGE(x, ...) \
56 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
57
Valerie Hau871d6352020-01-29 08:44:02 -080058void BLASTBufferItemConsumer::onDisconnect() {
Hongguang Chen621ec582021-02-16 15:42:35 -080059 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080060 mPreviouslyConnected = mCurrentlyConnected;
61 mCurrentlyConnected = false;
62 if (mPreviouslyConnected) {
63 mDisconnectEvents.push(mCurrentFrameNumber);
64 }
65 mFrameEventHistory.onDisconnect();
66}
67
68void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
69 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080070 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080071 if (newTimestamps) {
72 // BufferQueueProducer only adds a new timestamp on
73 // queueBuffer
74 mCurrentFrameNumber = newTimestamps->frameNumber;
75 mFrameEventHistory.addQueue(*newTimestamps);
76 }
77 if (outDelta) {
78 // frame event histories will be processed
79 // only after the producer connects and requests
80 // deltas for the first time. Forward this intent
81 // to SF-side to turn event processing back on
82 mPreviouslyConnected = mCurrentlyConnected;
83 mCurrentlyConnected = true;
84 mFrameEventHistory.getAndResetDelta(outDelta);
85 }
86}
87
88void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
89 const sp<Fence>& glDoneFence,
90 const sp<Fence>& presentFence,
91 const sp<Fence>& prevReleaseFence,
92 CompositorTiming compositorTiming,
93 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -080094 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080095
96 // if the producer is not connected, don't bother updating,
97 // the next producer that connects won't access this frame event
98 if (!mCurrentlyConnected) return;
99 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
100 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
101 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
102
103 mFrameEventHistory.addLatch(frameNumber, latchTime);
104 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
105 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
106 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
107 compositorTiming);
108}
109
110void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
111 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800112 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800113 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
114 disconnect = true;
115 mDisconnectEvents.pop();
116 }
117 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
118}
119
Hongguang Chen621ec582021-02-16 15:42:35 -0800120void BLASTBufferItemConsumer::setBlastBufferQueue(BLASTBufferQueue* blastbufferqueue) {
121 Mutex::Autolock lock(mMutex);
122 mBLASTBufferQueue = blastbufferqueue;
123}
124
125void BLASTBufferItemConsumer::onSidebandStreamChanged() {
126 Mutex::Autolock lock(mMutex);
127 if (mBLASTBufferQueue != nullptr) {
128 sp<NativeHandle> stream = getSidebandStream();
129 mBLASTBufferQueue->setSidebandStream(stream);
130 }
131}
132
Vishnu Nairdab94092020-09-29 16:09:04 -0700133BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700134 int width, int height, int32_t format)
Vishnu Nairdab94092020-09-29 16:09:04 -0700135 : mName(name),
136 mSurfaceControl(surface),
Vishnu Nairea0de002020-11-17 17:42:37 -0800137 mSize(width, height),
138 mRequestedSize(mSize),
chaviw565ee542021-01-14 10:21:23 -0800139 mFormat(format),
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 Nairdab94092020-09-29 16:09:04 -0700153 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Ady Abraham9dfe2b22021-06-11 16:48:58 -0700154 mPendingBufferTrace = "PendingBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800155 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700156 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700157 mBufferItemConsumer->setFrameAvailableListener(this);
158 mBufferItemConsumer->setBufferFreedListener(this);
Vishnu Nairea0de002020-11-17 17:42:37 -0800159 mBufferItemConsumer->setDefaultBufferSize(mSize.width, mSize.height);
chaviw497e81c2021-02-04 17:09:47 -0800160 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
Hongguang Chen621ec582021-02-16 15:42:35 -0800161 mBufferItemConsumer->setBlastBufferQueue(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700162
Ady Abraham899dcdb2021-06-15 16:56:21 -0700163 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700164 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
165
Valerie Hau2882e982020-01-23 13:33:10 -0800166 mTransformHint = mSurfaceControl->getTransformHint();
Robert Carr9f133d72020-04-01 15:51:46 -0700167 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800168 SurfaceComposerClient::Transaction()
Robert Carr5b3b9142021-02-22 12:27:32 -0800169 .setFlags(surface, layer_state_t::eEnableBackpressure,
170 layer_state_t::eEnableBackpressure)
171 .apply();
Valerie Haua32c5522019-12-09 10:11:08 -0800172 mNumAcquired = 0;
173 mNumFrameAvailable = 0;
Robert Carr78c25dd2019-08-15 14:10:33 -0700174}
175
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800176BLASTBufferQueue::~BLASTBufferQueue() {
Hongguang Chen621ec582021-02-16 15:42:35 -0800177 mBufferItemConsumer->setBlastBufferQueue(nullptr);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800178 if (mPendingTransactions.empty()) {
179 return;
180 }
181 BQA_LOGE("Applying pending transactions on dtor %d",
182 static_cast<uint32_t>(mPendingTransactions.size()));
183 SurfaceComposerClient::Transaction t;
184 for (auto& [targetFrameNumber, transaction] : mPendingTransactions) {
185 t.merge(std::move(transaction));
186 }
187 t.apply();
188}
189
chaviw565ee542021-01-14 10:21:23 -0800190void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
191 int32_t format) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700192 std::unique_lock _lock{mMutex};
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700193 BQA_LOGV("update width=%d height=%d format=%d", width, height, format);
chaviw565ee542021-01-14 10:21:23 -0800194 if (mFormat != format) {
195 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800196 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800197 }
198
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800199 SurfaceComposerClient::Transaction t;
200 bool applyTransaction = false;
201 if (!SurfaceControl::isSameSurface(mSurfaceControl, surface)) {
202 mSurfaceControl = surface;
203 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
204 layer_state_t::eEnableBackpressure);
205 applyTransaction = true;
206 }
207
Vishnu Nairea0de002020-11-17 17:42:37 -0800208 ui::Size newSize(width, height);
209 if (mRequestedSize != newSize) {
210 mRequestedSize.set(newSize);
211 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000212 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800213 // If the buffer supports scaling, update the frame immediately since the client may
214 // want to scale the existing buffer to the new size.
215 mSize = mRequestedSize;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000216 // We only need to update the scale if we've received at least one buffer. The reason
217 // for this is the scale is calculated based on the requested size and buffer size.
218 // If there's no buffer, the scale will always be 1.
219 if (mLastBufferInfo.hasBuffer) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700220 t.setDestinationFrame(mSurfaceControl,
221 Rect(0, 0, newSize.getWidth(), newSize.getHeight()));
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000222 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800223 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800224 }
Robert Carrfc416512020-04-02 12:32:44 -0700225 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800226 if (applyTransaction) {
227 t.apply();
228 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700229}
230
231static void transactionCallbackThunk(void* context, nsecs_t latchTime,
232 const sp<Fence>& presentFence,
233 const std::vector<SurfaceControlStats>& stats) {
234 if (context == nullptr) {
235 return;
236 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800237 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700238 bq->transactionCallback(latchTime, presentFence, stats);
239}
240
241void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
242 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700243 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
244 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700245
chaviw71c2cc42020-10-23 16:42:02 -0700246 {
247 std::unique_lock _lock{mMutex};
248 ATRACE_CALL();
249 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700250
chaviw42026162021-04-16 15:46:12 -0500251 if (!mSurfaceControlsWithPendingCallback.empty()) {
252 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
253 mSurfaceControlsWithPendingCallback.pop();
254 bool found = false;
255 for (auto stat : stats) {
256 if (!SurfaceControl::isSameSurface(pendingSC, stat.surfaceControl)) {
257 continue;
Vishnu Nair1506b182021-02-22 14:35:15 -0800258 }
chaviw42026162021-04-16 15:46:12 -0500259
260 mTransformHint = stat.transformHint;
261 mBufferItemConsumer->setTransformHint(mTransformHint);
262 mBufferItemConsumer
263 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
264 stat.frameEventStats.refreshStartTime,
265 stat.frameEventStats.gpuCompositionDoneFence,
266 stat.presentFence, stat.previousReleaseFence,
267 stat.frameEventStats.compositorTiming,
268 stat.latchTime,
269 stat.frameEventStats.dequeueReadyTime);
270
271 currFrameNumber = stat.frameEventStats.frameNumber;
272
273 if (mTransactionCompleteCallback &&
274 currFrameNumber >= mTransactionCompleteFrameNumber) {
275 if (currFrameNumber > mTransactionCompleteFrameNumber) {
276 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
277 " than expected=%" PRIu64,
278 currFrameNumber, mTransactionCompleteFrameNumber);
279 }
280 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
281 mTransactionCompleteFrameNumber = 0;
282 }
283
284 found = true;
285 break;
chaviw71c2cc42020-10-23 16:42:02 -0700286 }
chaviw42026162021-04-16 15:46:12 -0500287
288 if (!found) {
289 BQA_LOGE("Failed to find matching SurfaceControl in transaction callback");
290 }
291 } else {
292 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
293 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800294 }
chaviw71c2cc42020-10-23 16:42:02 -0700295
chaviw71c2cc42020-10-23 16:42:02 -0700296 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700297 }
Valerie Haua32c5522019-12-09 10:11:08 -0800298
chaviw71c2cc42020-10-23 16:42:02 -0700299 if (transactionCompleteCallback) {
300 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800301 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700302}
303
Vishnu Nair1506b182021-02-22 14:35:15 -0800304// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
305// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
306// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
307// Otherwise, this is a no-op.
308static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, uint64_t graphicBufferId,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700309 const sp<Fence>& releaseFence, uint32_t transformHint,
310 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800311 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
312 ALOGV("releaseBufferCallbackThunk graphicBufferId=%" PRIu64 " blastBufferQueue=%s",
313 graphicBufferId, blastBufferQueue ? "alive" : "dead");
314 if (blastBufferQueue) {
Ady Abraham899dcdb2021-06-15 16:56:21 -0700315 blastBufferQueue->releaseBufferCallback(graphicBufferId, releaseFence, transformHint,
316 currentMaxAcquiredBufferCount);
Vishnu Nair1506b182021-02-22 14:35:15 -0800317 }
318}
319
320void BLASTBufferQueue::releaseBufferCallback(uint64_t graphicBufferId,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700321 const sp<Fence>& releaseFence, uint32_t transformHint,
322 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800323 ATRACE_CALL();
324 std::unique_lock _lock{mMutex};
325 BQA_LOGV("releaseBufferCallback graphicBufferId=%" PRIu64, graphicBufferId);
326
Robert Carr82d07c92021-05-10 11:36:43 -0700327 if (mSurfaceControl != nullptr) {
Robert Carr97e7cc02021-06-07 10:45:40 -0700328 mTransformHint = transformHint;
329 mSurfaceControl->setTransformHint(transformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700330 mBufferItemConsumer->setTransformHint(mTransformHint);
331 }
332
Ady Abraham899dcdb2021-06-15 16:56:21 -0700333 // Calculate how many buffers we need to hold before we release them back
334 // to the buffer queue. This will prevent higher latency when we are running
335 // on a lower refresh rate than the max supported. We only do that for EGL
336 // clients as others don't care about latency
337 const bool isEGL = [&] {
338 const auto it = mSubmitted.find(graphicBufferId);
339 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
340 }();
341
342 const auto numPendingBuffersToHold =
343 isEGL ? std::max(0u, mMaxAcquiredBuffers - currentMaxAcquiredBufferCount) : 0;
344 mPendingRelease.emplace_back(ReleasedBuffer{graphicBufferId, releaseFence});
345
346 // Release all buffers that are beyond the ones that we need to hold
347 while (mPendingRelease.size() > numPendingBuffersToHold) {
348 const auto releaseBuffer = mPendingRelease.front();
349 mPendingRelease.pop_front();
350 auto it = mSubmitted.find(releaseBuffer.bufferId);
351 if (it == mSubmitted.end()) {
352 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %" PRIu64,
353 graphicBufferId);
354 return;
355 }
356
357 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
358 mSubmitted.erase(it);
Vishnu Nair1506b182021-02-22 14:35:15 -0800359 }
360
Ady Abraham899dcdb2021-06-15 16:56:21 -0700361 ATRACE_INT("PendingRelease", mPendingRelease.size());
362
Vishnu Nair1506b182021-02-22 14:35:15 -0800363 mNumAcquired--;
Ady Abraham9dfe2b22021-06-11 16:48:58 -0700364 ATRACE_INT(mPendingBufferTrace.c_str(), mNumFrameAvailable + mNumAcquired);
Vishnu Nair1506b182021-02-22 14:35:15 -0800365 processNextBufferLocked(false /* useNextTransaction */);
366 mCallbackCV.notify_all();
367}
368
Robert Carr255acdc2020-04-17 14:08:55 -0700369void BLASTBufferQueue::processNextBufferLocked(bool useNextTransaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800370 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800371 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
372 // include the extra buffer when checking if we can acquire the next buffer.
373 const bool includeExtraAcquire = !useNextTransaction;
374 if (mNumFrameAvailable == 0 || maxBuffersAcquired(includeExtraAcquire)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800375 mCallbackCV.notify_all();
Valerie Haud3b90d22019-11-06 09:37:31 -0800376 return;
377 }
378
Valerie Haua32c5522019-12-09 10:11:08 -0800379 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700380 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800381 return;
382 }
383
Robert Carr78c25dd2019-08-15 14:10:33 -0700384 SurfaceComposerClient::Transaction localTransaction;
385 bool applyTransaction = true;
386 SurfaceComposerClient::Transaction* t = &localTransaction;
Robert Carr255acdc2020-04-17 14:08:55 -0700387 if (mNextTransaction != nullptr && useNextTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700388 t = mNextTransaction;
389 mNextTransaction = nullptr;
390 applyTransaction = false;
391 }
392
Valerie Haua32c5522019-12-09 10:11:08 -0800393 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800394
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800395 status_t status =
396 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800397 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
398 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
399 return;
400 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700401 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700402 return;
403 }
Valerie Haua32c5522019-12-09 10:11:08 -0800404 auto buffer = bufferItem.mGraphicBuffer;
405 mNumFrameAvailable--;
406
407 if (buffer == nullptr) {
408 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700409 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800410 return;
411 }
412
Vishnu Nair670b3f72020-09-29 17:52:18 -0700413 if (rejectBuffer(bufferItem)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800414 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d"
415 "buffer{size=%dx%d transform=%d}",
416 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
417 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
418 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
419 processNextBufferLocked(useNextTransaction);
420 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700421 }
422
Valerie Haua32c5522019-12-09 10:11:08 -0800423 mNumAcquired++;
Vishnu Nair1506b182021-02-22 14:35:15 -0800424 mSubmitted[buffer->getId()] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700425
Valerie Hau871d6352020-01-29 08:44:02 -0800426 bool needsDisconnect = false;
427 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
428
429 // if producer disconnected before, notify SurfaceFlinger
430 if (needsDisconnect) {
431 t->notifyProducerDisconnect(mSurfaceControl);
432 }
433
Robert Carr78c25dd2019-08-15 14:10:33 -0700434 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
435 incStrong((void*)transactionCallbackThunk);
436
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700437 Rect crop = computeCrop(bufferItem);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800438 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000439 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
440 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700441 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800442
Vishnu Nair1506b182021-02-22 14:35:15 -0800443 auto releaseBufferCallback =
444 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700445 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
446 std::placeholders::_4);
Vishnu Nair1506b182021-02-22 14:35:15 -0800447 t->setBuffer(mSurfaceControl, buffer, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500448 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
449 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
450 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700451 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800452 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700453 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviw42026162021-04-16 15:46:12 -0500454 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700455
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700456 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
457 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800458 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800459 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800460 if (!bufferItem.mIsAutoTimestamp) {
461 t->setDesiredPresentTime(bufferItem.mTimestamp);
462 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700463 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700464
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000465 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700466 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000467 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100468 }
469
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800470 if (mAutoRefresh != bufferItem.mAutoRefresh) {
471 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
472 mAutoRefresh = bufferItem.mAutoRefresh;
473 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800474 {
475 std::unique_lock _lock{mTimestampMutex};
476 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
477 if (dequeueTime != mDequeueTimestamps.end()) {
478 Parcel p;
479 p.writeInt64(dequeueTime->second);
480 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
481 mDequeueTimestamps.erase(dequeueTime);
482 }
483 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800484
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800485 auto mergeTransaction =
486 [&t, currentFrameNumber = bufferItem.mFrameNumber](
487 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
488 auto& [targetFrameNumber, transaction] = pendingTransaction;
489 if (currentFrameNumber < targetFrameNumber) {
490 return false;
491 }
492 t->merge(std::move(transaction));
493 return true;
494 };
495
496 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
497 mPendingTransactions.end(), mergeTransaction),
498 mPendingTransactions.end());
499
Robert Carr78c25dd2019-08-15 14:10:33 -0700500 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800501 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700502 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700503
504 BQA_LOGV("processNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800505 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
506 " graphicBufferId=%" PRIu64,
Vishnu Nairea0de002020-11-17 17:42:37 -0800507 mSize.width, mSize.height, bufferItem.mFrameNumber, toString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800508 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
509 static_cast<uint32_t>(mPendingTransactions.size()),
510 bufferItem.mGraphicBuffer->getId());
Robert Carr78c25dd2019-08-15 14:10:33 -0700511}
512
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800513Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
514 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800515 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800516 }
517 return item.mCrop;
518}
519
Vishnu Nairaef1de92020-10-22 12:15:53 -0700520void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800521 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800522 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800523
Vishnu Nairdab94092020-09-29 16:09:04 -0700524 const bool nextTransactionSet = mNextTransaction != nullptr;
Vishnu Nair1506b182021-02-22 14:35:15 -0800525 if (nextTransactionSet) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800526 while (mNumFrameAvailable > 0 || maxBuffersAcquired(false /* includeExtraAcquire */)) {
Vishnu Nair7eb670a2020-10-15 12:16:10 -0700527 BQA_LOGV("waiting in onFrameAvailable...");
Valerie Hau0188adf2020-02-13 08:29:20 -0800528 mCallbackCV.wait(_lock);
529 }
530 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800531 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800532 mNumFrameAvailable++;
Ady Abraham9dfe2b22021-06-11 16:48:58 -0700533 ATRACE_INT(mPendingBufferTrace.c_str(), mNumFrameAvailable + mNumAcquired);
Vishnu Nair1506b182021-02-22 14:35:15 -0800534
535 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
536 toString(nextTransactionSet));
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800537 processNextBufferLocked(nextTransactionSet /* useNextTransaction */);
Valerie Haud3b90d22019-11-06 09:37:31 -0800538}
539
Vishnu Nairaef1de92020-10-22 12:15:53 -0700540void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
541 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
542 // Do nothing since we are not storing unacquired buffer items locally.
543}
544
Vishnu Nairadf632b2021-01-07 14:05:08 -0800545void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
546 std::unique_lock _lock{mTimestampMutex};
547 mDequeueTimestamps[bufferId] = systemTime();
548};
549
550void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
551 std::unique_lock _lock{mTimestampMutex};
552 mDequeueTimestamps.erase(bufferId);
553};
554
Robert Carr78c25dd2019-08-15 14:10:33 -0700555void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800556 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700557 mNextTransaction = t;
558}
559
Vishnu Nairea0de002020-11-17 17:42:37 -0800560bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700561 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Hongguang Chen33100282021-04-15 18:36:05 -0700562 mSize = mRequestedSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700563 // Only reject buffers if scaling mode is freeze.
564 return false;
565 }
566
Vishnu Naire1a42322020-10-02 17:42:04 -0700567 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
568 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
569
570 // Take the buffer's orientation into account
571 if (item.mTransform & ui::Transform::ROT_90) {
572 std::swap(bufWidth, bufHeight);
573 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800574 ui::Size bufferSize(bufWidth, bufHeight);
575 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
576 mSize = mRequestedSize;
577 return false;
578 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700579
Vishnu Nair670b3f72020-09-29 17:52:18 -0700580 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800581 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700582}
Vishnu Nairbf255772020-10-16 10:54:41 -0700583
chaviw71c2cc42020-10-23 16:42:02 -0700584void BLASTBufferQueue::setTransactionCompleteCallback(
585 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
586 std::lock_guard _lock{mMutex};
587 if (transactionCompleteCallback == nullptr) {
588 mTransactionCompleteCallback = nullptr;
589 } else {
590 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
591 mTransactionCompleteFrameNumber = frameNumber;
592 }
593}
594
Vishnu Nairbf255772020-10-16 10:54:41 -0700595// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800596// Consumer can acquire an additional buffer if that buffer is not droppable. Set
597// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
598// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
599bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700600 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800601 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700602}
603
Robert Carr05086b22020-10-13 18:22:51 -0700604class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700605private:
606 sp<BLASTBufferQueue> mBbq;
Robert Carr05086b22020-10-13 18:22:51 -0700607public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700608 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
609 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
610 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700611
Robert Carr05086b22020-10-13 18:22:51 -0700612 void allocateBuffers() override {
613 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
614 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
615 auto gbp = getIGraphicBufferProducer();
616 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
617 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
618 gbp->allocateBuffers(reqWidth, reqHeight,
619 reqFormat, reqUsage);
620
621 }).detach();
622 }
Robert Carr9c006e02020-10-14 13:41:57 -0700623
Marin Shalamanovc5986772021-03-16 16:09:49 +0100624 status_t setFrameRate(float frameRate, int8_t compatibility,
625 int8_t changeFrameRateStrategy) override {
626 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
627 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700628 return BAD_VALUE;
629 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100630 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700631 }
Robert Carr9b611b72020-10-19 12:00:23 -0700632
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000633 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
634 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700635 }
Robert Carr82d07c92021-05-10 11:36:43 -0700636 protected:
637 uint32_t getTransformHint() const override {
638 if (mStickyTransform == 0 && !transformToDisplayInverse()) {
639 return mBbq->getLastTransformHint();
640 } else {
641 return 0;
642 }
643 }
Robert Carr05086b22020-10-13 18:22:51 -0700644};
645
Robert Carr9c006e02020-10-14 13:41:57 -0700646// TODO: Can we coalesce this with frame updates? Need to confirm
647// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200648status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
649 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700650 std::unique_lock _lock{mMutex};
651 SurfaceComposerClient::Transaction t;
652
Marin Shalamanov46084422020-10-13 12:33:42 +0200653 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700654}
655
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000656status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700657 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000658 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100659 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700660}
661
Hongguang Chen621ec582021-02-16 15:42:35 -0800662void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
663 std::unique_lock _lock{mMutex};
664 SurfaceComposerClient::Transaction t;
665
666 t.setSidebandStream(mSurfaceControl, stream).apply();
667}
668
Vishnu Nair992496b2020-10-22 17:27:21 -0700669sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
670 std::unique_lock _lock{mMutex};
671 sp<IBinder> scHandle = nullptr;
672 if (includeSurfaceControlHandle && mSurfaceControl) {
673 scHandle = mSurfaceControl->getHandle();
674 }
675 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700676}
677
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800678void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
679 uint64_t frameNumber) {
680 std::lock_guard _lock{mMutex};
681 if (mLastAcquiredFrameNumber >= frameNumber) {
682 // Apply the transaction since we have already acquired the desired frame.
683 t->apply();
684 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500685 mPendingTransactions.emplace_back(frameNumber, *t);
686 // Clear the transaction so it can't be applied elsewhere.
687 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800688 }
689}
690
Vishnu Nair89496122020-12-14 17:14:53 -0800691// Maintains a single worker thread per process that services a list of runnables.
692class AsyncWorker : public Singleton<AsyncWorker> {
693private:
694 std::thread mThread;
695 bool mDone = false;
696 std::deque<std::function<void()>> mRunnables;
697 std::mutex mMutex;
698 std::condition_variable mCv;
699 void run() {
700 std::unique_lock<std::mutex> lock(mMutex);
701 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800702 while (!mRunnables.empty()) {
703 std::function<void()> runnable = mRunnables.front();
704 mRunnables.pop_front();
705 runnable();
706 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700707 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800708 }
709 }
710
711public:
712 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
713
714 ~AsyncWorker() {
715 mDone = true;
716 mCv.notify_all();
717 if (mThread.joinable()) {
718 mThread.join();
719 }
720 }
721
722 void post(std::function<void()> runnable) {
723 std::unique_lock<std::mutex> lock(mMutex);
724 mRunnables.emplace_back(std::move(runnable));
725 mCv.notify_one();
726 }
727};
728ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
729
730// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
731class AsyncProducerListener : public BnProducerListener {
732private:
733 const sp<IProducerListener> mListener;
734
735public:
736 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
737
738 void onBufferReleased() override {
739 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
740 }
741
742 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
743 AsyncWorker::getInstance().post(
744 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
745 }
746};
747
748// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
749// can be non-blocking when the producer is in the client process.
750class BBQBufferQueueProducer : public BufferQueueProducer {
751public:
752 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
753 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
754
755 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
756 QueueBufferOutput* output) override {
757 if (!listener) {
758 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
759 }
760
761 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
762 producerControlledByApp, output);
763 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800764
765 int query(int what, int* value) override {
766 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
767 *value = 1;
768 return NO_ERROR;
769 }
770 return BufferQueueProducer::query(what, value);
771 }
Vishnu Nair89496122020-12-14 17:14:53 -0800772};
773
774// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
775// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
776// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
777// we can deadlock.
778void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
779 sp<IGraphicBufferConsumer>* outConsumer) {
780 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
781 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
782
783 sp<BufferQueueCore> core(new BufferQueueCore());
784 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
785
786 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
787 LOG_ALWAYS_FATAL_IF(producer == nullptr,
788 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
789
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800790 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
791 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800792 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
793 "BLASTBufferQueue: failed to create BufferQueueConsumer");
794
795 *outProducer = producer;
796 *outConsumer = consumer;
797}
798
chaviw497e81c2021-02-04 17:09:47 -0800799PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
800 PixelFormat convertedFormat = format;
801 switch (format) {
802 case PIXEL_FORMAT_TRANSPARENT:
803 case PIXEL_FORMAT_TRANSLUCENT:
804 convertedFormat = PIXEL_FORMAT_RGBA_8888;
805 break;
806 case PIXEL_FORMAT_OPAQUE:
807 convertedFormat = PIXEL_FORMAT_RGBX_8888;
808 break;
809 }
810 return convertedFormat;
811}
812
Robert Carr82d07c92021-05-10 11:36:43 -0700813uint32_t BLASTBufferQueue::getLastTransformHint() const {
814 if (mSurfaceControl != nullptr) {
815 return mSurfaceControl->getTransformHint();
816 } else {
817 return 0;
818 }
819}
820
Robert Carr78c25dd2019-08-15 14:10:33 -0700821} // namespace android