blob: ebc436f913d6b7ed9d9b0f469ff58179641afb8a [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
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 Nair4ba0c2e2021-06-24 11:27:17 -0700135 : 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 Nair4ba0c2e2021-06-24 11:27:17 -0700152 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700153 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700154 mQueuedBufferTrace = "QueuedBuffer - " + 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;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700200 const bool setBackpressureFlag = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800201 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800202
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700203 // Always update the native object even though they might have the same layer handle, so we can
204 // get the updated transform hint from WM.
205 mSurfaceControl = surface;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800206 if (mSurfaceControl != nullptr) {
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700207 if (setBackpressureFlag) {
208 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
209 layer_state_t::eEnableBackpressure);
210 applyTransaction = true;
211 }
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800212 mTransformHint = mSurfaceControl->getTransformHint();
213 mBufferItemConsumer->setTransformHint(mTransformHint);
214 }
215
Vishnu Nairea0de002020-11-17 17:42:37 -0800216 ui::Size newSize(width, height);
217 if (mRequestedSize != newSize) {
218 mRequestedSize.set(newSize);
219 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000220 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800221 // If the buffer supports scaling, update the frame immediately since the client may
222 // want to scale the existing buffer to the new size.
223 mSize = mRequestedSize;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000224 // We only need to update the scale if we've received at least one buffer. The reason
225 // for this is the scale is calculated based on the requested size and buffer size.
226 // If there's no buffer, the scale will always be 1.
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700227 if (mSurfaceControl != nullptr && mLastBufferInfo.hasBuffer) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700228 t.setDestinationFrame(mSurfaceControl,
229 Rect(0, 0, newSize.getWidth(), newSize.getHeight()));
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000230 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800231 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800232 }
Robert Carrfc416512020-04-02 12:32:44 -0700233 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800234 if (applyTransaction) {
235 t.apply();
236 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700237}
238
239static void transactionCallbackThunk(void* context, nsecs_t latchTime,
240 const sp<Fence>& presentFence,
241 const std::vector<SurfaceControlStats>& stats) {
242 if (context == nullptr) {
243 return;
244 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800245 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700246 bq->transactionCallback(latchTime, presentFence, stats);
247}
248
249void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
250 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700251 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
252 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700253
chaviw71c2cc42020-10-23 16:42:02 -0700254 {
255 std::unique_lock _lock{mMutex};
256 ATRACE_CALL();
257 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700258
chaviw42026162021-04-16 15:46:12 -0500259 if (!mSurfaceControlsWithPendingCallback.empty()) {
260 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
261 mSurfaceControlsWithPendingCallback.pop();
262 bool found = false;
263 for (auto stat : stats) {
264 if (!SurfaceControl::isSameSurface(pendingSC, stat.surfaceControl)) {
265 continue;
Vishnu Nair1506b182021-02-22 14:35:15 -0800266 }
chaviw42026162021-04-16 15:46:12 -0500267
268 mTransformHint = stat.transformHint;
269 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700270 // Update frametime stamps if the frame was latched and presented, indicated by a
271 // valid latch time.
272 if (stat.latchTime > 0) {
273 mBufferItemConsumer
274 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
275 stat.frameEventStats.refreshStartTime,
276 stat.frameEventStats.gpuCompositionDoneFence,
277 stat.presentFence, stat.previousReleaseFence,
278 stat.frameEventStats.compositorTiming,
279 stat.latchTime,
280 stat.frameEventStats.dequeueReadyTime);
281 }
chaviw42026162021-04-16 15:46:12 -0500282 currFrameNumber = stat.frameEventStats.frameNumber;
283
284 if (mTransactionCompleteCallback &&
285 currFrameNumber >= mTransactionCompleteFrameNumber) {
286 if (currFrameNumber > mTransactionCompleteFrameNumber) {
287 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
288 " than expected=%" PRIu64,
289 currFrameNumber, mTransactionCompleteFrameNumber);
290 }
291 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
292 mTransactionCompleteFrameNumber = 0;
293 }
294
295 found = true;
296 break;
chaviw71c2cc42020-10-23 16:42:02 -0700297 }
chaviw42026162021-04-16 15:46:12 -0500298
299 if (!found) {
300 BQA_LOGE("Failed to find matching SurfaceControl in transaction callback");
301 }
302 } else {
303 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
304 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800305 }
chaviw71c2cc42020-10-23 16:42:02 -0700306
chaviw71c2cc42020-10-23 16:42:02 -0700307 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700308 }
Valerie Haua32c5522019-12-09 10:11:08 -0800309
chaviw71c2cc42020-10-23 16:42:02 -0700310 if (transactionCompleteCallback) {
311 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800312 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700313}
314
Vishnu Nair1506b182021-02-22 14:35:15 -0800315// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
316// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
317// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
318// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700319static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700320 const sp<Fence>& releaseFence, uint32_t transformHint,
321 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800322 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800323 if (blastBufferQueue) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700324 blastBufferQueue->releaseBufferCallback(id, releaseFence, transformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700325 currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700326 } else {
327 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800328 }
329}
330
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700331void BLASTBufferQueue::releaseBufferCallback(const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700332 const sp<Fence>& releaseFence, uint32_t transformHint,
333 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800334 ATRACE_CALL();
335 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700336 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800337
Robert Carr82d07c92021-05-10 11:36:43 -0700338 if (mSurfaceControl != nullptr) {
Robert Carr97e7cc02021-06-07 10:45:40 -0700339 mTransformHint = transformHint;
340 mSurfaceControl->setTransformHint(transformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700341 mBufferItemConsumer->setTransformHint(mTransformHint);
342 }
343
Ady Abraham899dcdb2021-06-15 16:56:21 -0700344 // Calculate how many buffers we need to hold before we release them back
345 // to the buffer queue. This will prevent higher latency when we are running
346 // on a lower refresh rate than the max supported. We only do that for EGL
347 // clients as others don't care about latency
348 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700349 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700350 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
351 }();
352
353 const auto numPendingBuffersToHold =
354 isEGL ? std::max(0u, mMaxAcquiredBuffers - currentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700355 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700356
357 // Release all buffers that are beyond the ones that we need to hold
358 while (mPendingRelease.size() > numPendingBuffersToHold) {
359 const auto releaseBuffer = mPendingRelease.front();
360 mPendingRelease.pop_front();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700361 auto it = mSubmitted.find(releaseBuffer.callbackId);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700362 if (it == mSubmitted.end()) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700363 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
364 releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700365 return;
366 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700367 mNumAcquired--;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700368 BQA_LOGV("released %s", id.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700369 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
370 mSubmitted.erase(it);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700371 processNextBufferLocked(false /* useNextTransaction */);
Vishnu Nair1506b182021-02-22 14:35:15 -0800372 }
373
Ady Abraham899dcdb2021-06-15 16:56:21 -0700374 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700375 ATRACE_INT(mQueuedBufferTrace.c_str(),
376 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800377 mCallbackCV.notify_all();
378}
379
Robert Carr255acdc2020-04-17 14:08:55 -0700380void BLASTBufferQueue::processNextBufferLocked(bool useNextTransaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800381 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800382 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
383 // include the extra buffer when checking if we can acquire the next buffer.
384 const bool includeExtraAcquire = !useNextTransaction;
385 if (mNumFrameAvailable == 0 || maxBuffersAcquired(includeExtraAcquire)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800386 mCallbackCV.notify_all();
Valerie Haud3b90d22019-11-06 09:37:31 -0800387 return;
388 }
389
Valerie Haua32c5522019-12-09 10:11:08 -0800390 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700391 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800392 return;
393 }
394
Robert Carr78c25dd2019-08-15 14:10:33 -0700395 SurfaceComposerClient::Transaction localTransaction;
396 bool applyTransaction = true;
397 SurfaceComposerClient::Transaction* t = &localTransaction;
Robert Carr255acdc2020-04-17 14:08:55 -0700398 if (mNextTransaction != nullptr && useNextTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700399 t = mNextTransaction;
400 mNextTransaction = nullptr;
401 applyTransaction = false;
402 }
403
Valerie Haua32c5522019-12-09 10:11:08 -0800404 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800405
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800406 status_t status =
407 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800408 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
409 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
410 return;
411 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700412 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700413 return;
414 }
Valerie Haua32c5522019-12-09 10:11:08 -0800415 auto buffer = bufferItem.mGraphicBuffer;
416 mNumFrameAvailable--;
417
418 if (buffer == nullptr) {
419 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700420 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800421 return;
422 }
423
Vishnu Nair670b3f72020-09-29 17:52:18 -0700424 if (rejectBuffer(bufferItem)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800425 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d"
426 "buffer{size=%dx%d transform=%d}",
427 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
428 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
429 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
430 processNextBufferLocked(useNextTransaction);
431 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700432 }
433
Valerie Haua32c5522019-12-09 10:11:08 -0800434 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700435 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
436 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
437 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700438
Valerie Hau871d6352020-01-29 08:44:02 -0800439 bool needsDisconnect = false;
440 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
441
442 // if producer disconnected before, notify SurfaceFlinger
443 if (needsDisconnect) {
444 t->notifyProducerDisconnect(mSurfaceControl);
445 }
446
Robert Carr78c25dd2019-08-15 14:10:33 -0700447 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
448 incStrong((void*)transactionCallbackThunk);
449
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700450 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000451 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
452 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700453 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800454
Vishnu Nair1506b182021-02-22 14:35:15 -0800455 auto releaseBufferCallback =
456 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700457 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
458 std::placeholders::_4);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700459 t->setBuffer(mSurfaceControl, buffer, releaseCallbackId, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500460 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
461 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
462 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700463 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800464 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700465 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviw42026162021-04-16 15:46:12 -0500466 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700467
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700468 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
469 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800470 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800471 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800472 if (!bufferItem.mIsAutoTimestamp) {
473 t->setDesiredPresentTime(bufferItem.mTimestamp);
474 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700475 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700476
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000477 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700478 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000479 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100480 }
481
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800482 if (mAutoRefresh != bufferItem.mAutoRefresh) {
483 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
484 mAutoRefresh = bufferItem.mAutoRefresh;
485 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800486 {
487 std::unique_lock _lock{mTimestampMutex};
488 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
489 if (dequeueTime != mDequeueTimestamps.end()) {
490 Parcel p;
491 p.writeInt64(dequeueTime->second);
492 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
493 mDequeueTimestamps.erase(dequeueTime);
494 }
495 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800496
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800497 auto mergeTransaction =
498 [&t, currentFrameNumber = bufferItem.mFrameNumber](
499 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
500 auto& [targetFrameNumber, transaction] = pendingTransaction;
501 if (currentFrameNumber < targetFrameNumber) {
502 return false;
503 }
504 t->merge(std::move(transaction));
505 return true;
506 };
507
508 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
509 mPendingTransactions.end(), mergeTransaction),
510 mPendingTransactions.end());
511
Robert Carr78c25dd2019-08-15 14:10:33 -0700512 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800513 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700514 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700515
516 BQA_LOGV("processNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800517 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700518 " graphicBufferId=%" PRIu64 "%s",
chaviw3277faf2021-05-19 16:45:23 -0500519 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800520 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700521 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
522 bufferItem.mAutoRefresh ? " mAutoRefresh" : "");
Robert Carr78c25dd2019-08-15 14:10:33 -0700523}
524
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800525Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
526 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800527 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800528 }
529 return item.mCrop;
530}
531
Vishnu Nairaef1de92020-10-22 12:15:53 -0700532void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800533 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800534 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800535
Vishnu Nairdab94092020-09-29 16:09:04 -0700536 const bool nextTransactionSet = mNextTransaction != nullptr;
Vishnu Nair1506b182021-02-22 14:35:15 -0800537 if (nextTransactionSet) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800538 while (mNumFrameAvailable > 0 || maxBuffersAcquired(false /* includeExtraAcquire */)) {
Vishnu Nair7eb670a2020-10-15 12:16:10 -0700539 BQA_LOGV("waiting in onFrameAvailable...");
Valerie Hau0188adf2020-02-13 08:29:20 -0800540 mCallbackCV.wait(_lock);
541 }
542 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800543 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800544 mNumFrameAvailable++;
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700545 ATRACE_INT(mQueuedBufferTrace.c_str(),
546 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800547
548 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
chaviw3277faf2021-05-19 16:45:23 -0500549 boolToString(nextTransactionSet));
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800550 processNextBufferLocked(nextTransactionSet /* useNextTransaction */);
Valerie Haud3b90d22019-11-06 09:37:31 -0800551}
552
Vishnu Nairaef1de92020-10-22 12:15:53 -0700553void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
554 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
555 // Do nothing since we are not storing unacquired buffer items locally.
556}
557
Vishnu Nairadf632b2021-01-07 14:05:08 -0800558void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
559 std::unique_lock _lock{mTimestampMutex};
560 mDequeueTimestamps[bufferId] = systemTime();
561};
562
563void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
564 std::unique_lock _lock{mTimestampMutex};
565 mDequeueTimestamps.erase(bufferId);
566};
567
Robert Carr78c25dd2019-08-15 14:10:33 -0700568void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800569 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700570 mNextTransaction = t;
571}
572
Vishnu Nairea0de002020-11-17 17:42:37 -0800573bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700574 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Hongguang Chen33100282021-04-15 18:36:05 -0700575 mSize = mRequestedSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700576 // Only reject buffers if scaling mode is freeze.
577 return false;
578 }
579
Vishnu Naire1a42322020-10-02 17:42:04 -0700580 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
581 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
582
583 // Take the buffer's orientation into account
584 if (item.mTransform & ui::Transform::ROT_90) {
585 std::swap(bufWidth, bufHeight);
586 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800587 ui::Size bufferSize(bufWidth, bufHeight);
588 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
589 mSize = mRequestedSize;
590 return false;
591 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700592
Vishnu Nair670b3f72020-09-29 17:52:18 -0700593 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800594 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700595}
Vishnu Nairbf255772020-10-16 10:54:41 -0700596
chaviw71c2cc42020-10-23 16:42:02 -0700597void BLASTBufferQueue::setTransactionCompleteCallback(
598 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
599 std::lock_guard _lock{mMutex};
600 if (transactionCompleteCallback == nullptr) {
601 mTransactionCompleteCallback = nullptr;
602 } else {
603 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
604 mTransactionCompleteFrameNumber = frameNumber;
605 }
606}
607
Vishnu Nairbf255772020-10-16 10:54:41 -0700608// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800609// Consumer can acquire an additional buffer if that buffer is not droppable. Set
610// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
611// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
612bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700613 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800614 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700615}
616
Robert Carr05086b22020-10-13 18:22:51 -0700617class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700618private:
619 sp<BLASTBufferQueue> mBbq;
Robert Carr05086b22020-10-13 18:22:51 -0700620public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700621 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
622 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
623 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700624
Robert Carr05086b22020-10-13 18:22:51 -0700625 void allocateBuffers() override {
626 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
627 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
628 auto gbp = getIGraphicBufferProducer();
629 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
630 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
631 gbp->allocateBuffers(reqWidth, reqHeight,
632 reqFormat, reqUsage);
633
634 }).detach();
635 }
Robert Carr9c006e02020-10-14 13:41:57 -0700636
Marin Shalamanovc5986772021-03-16 16:09:49 +0100637 status_t setFrameRate(float frameRate, int8_t compatibility,
638 int8_t changeFrameRateStrategy) override {
639 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
640 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700641 return BAD_VALUE;
642 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100643 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700644 }
Robert Carr9b611b72020-10-19 12:00:23 -0700645
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000646 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
647 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700648 }
Robert Carr82d07c92021-05-10 11:36:43 -0700649 protected:
650 uint32_t getTransformHint() const override {
651 if (mStickyTransform == 0 && !transformToDisplayInverse()) {
652 return mBbq->getLastTransformHint();
653 } else {
654 return 0;
655 }
656 }
Robert Carr05086b22020-10-13 18:22:51 -0700657};
658
Robert Carr9c006e02020-10-14 13:41:57 -0700659// TODO: Can we coalesce this with frame updates? Need to confirm
660// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200661status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
662 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700663 std::unique_lock _lock{mMutex};
664 SurfaceComposerClient::Transaction t;
665
Marin Shalamanov46084422020-10-13 12:33:42 +0200666 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700667}
668
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000669status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700670 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000671 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100672 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700673}
674
Hongguang Chen621ec582021-02-16 15:42:35 -0800675void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
676 std::unique_lock _lock{mMutex};
677 SurfaceComposerClient::Transaction t;
678
679 t.setSidebandStream(mSurfaceControl, stream).apply();
680}
681
Vishnu Nair992496b2020-10-22 17:27:21 -0700682sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
683 std::unique_lock _lock{mMutex};
684 sp<IBinder> scHandle = nullptr;
685 if (includeSurfaceControlHandle && mSurfaceControl) {
686 scHandle = mSurfaceControl->getHandle();
687 }
688 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700689}
690
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800691void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
692 uint64_t frameNumber) {
693 std::lock_guard _lock{mMutex};
694 if (mLastAcquiredFrameNumber >= frameNumber) {
695 // Apply the transaction since we have already acquired the desired frame.
696 t->apply();
697 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500698 mPendingTransactions.emplace_back(frameNumber, *t);
699 // Clear the transaction so it can't be applied elsewhere.
700 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800701 }
702}
703
Vishnu Nair89496122020-12-14 17:14:53 -0800704// Maintains a single worker thread per process that services a list of runnables.
705class AsyncWorker : public Singleton<AsyncWorker> {
706private:
707 std::thread mThread;
708 bool mDone = false;
709 std::deque<std::function<void()>> mRunnables;
710 std::mutex mMutex;
711 std::condition_variable mCv;
712 void run() {
713 std::unique_lock<std::mutex> lock(mMutex);
714 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800715 while (!mRunnables.empty()) {
716 std::function<void()> runnable = mRunnables.front();
717 mRunnables.pop_front();
718 runnable();
719 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700720 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800721 }
722 }
723
724public:
725 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
726
727 ~AsyncWorker() {
728 mDone = true;
729 mCv.notify_all();
730 if (mThread.joinable()) {
731 mThread.join();
732 }
733 }
734
735 void post(std::function<void()> runnable) {
736 std::unique_lock<std::mutex> lock(mMutex);
737 mRunnables.emplace_back(std::move(runnable));
738 mCv.notify_one();
739 }
740};
741ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
742
743// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
744class AsyncProducerListener : public BnProducerListener {
745private:
746 const sp<IProducerListener> mListener;
747
748public:
749 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
750
751 void onBufferReleased() override {
752 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
753 }
754
755 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
756 AsyncWorker::getInstance().post(
757 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
758 }
759};
760
761// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
762// can be non-blocking when the producer is in the client process.
763class BBQBufferQueueProducer : public BufferQueueProducer {
764public:
765 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
766 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
767
768 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
769 QueueBufferOutput* output) override {
770 if (!listener) {
771 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
772 }
773
774 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
775 producerControlledByApp, output);
776 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800777
778 int query(int what, int* value) override {
779 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
780 *value = 1;
781 return NO_ERROR;
782 }
783 return BufferQueueProducer::query(what, value);
784 }
Vishnu Nair89496122020-12-14 17:14:53 -0800785};
786
787// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
788// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
789// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
790// we can deadlock.
791void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
792 sp<IGraphicBufferConsumer>* outConsumer) {
793 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
794 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
795
796 sp<BufferQueueCore> core(new BufferQueueCore());
797 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
798
799 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
800 LOG_ALWAYS_FATAL_IF(producer == nullptr,
801 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
802
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800803 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
804 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800805 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
806 "BLASTBufferQueue: failed to create BufferQueueConsumer");
807
808 *outProducer = producer;
809 *outConsumer = consumer;
810}
811
chaviw497e81c2021-02-04 17:09:47 -0800812PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
813 PixelFormat convertedFormat = format;
814 switch (format) {
815 case PIXEL_FORMAT_TRANSPARENT:
816 case PIXEL_FORMAT_TRANSLUCENT:
817 convertedFormat = PIXEL_FORMAT_RGBA_8888;
818 break;
819 case PIXEL_FORMAT_OPAQUE:
820 convertedFormat = PIXEL_FORMAT_RGBX_8888;
821 break;
822 }
823 return convertedFormat;
824}
825
Robert Carr82d07c92021-05-10 11:36:43 -0700826uint32_t BLASTBufferQueue::getLastTransformHint() const {
827 if (mSurfaceControl != nullptr) {
828 return mSurfaceControl->getTransformHint();
829 } else {
830 return 0;
831 }
832}
833
Robert Carr78c25dd2019-08-15 14:10:33 -0700834} // namespace android