blob: dbb1cb0c173dea694bfe97b4e4154ed9bf6eb1a2 [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;
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
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800208 if (mSurfaceControl != nullptr) {
209 mTransformHint = mSurfaceControl->getTransformHint();
210 mBufferItemConsumer->setTransformHint(mTransformHint);
211 }
212
Vishnu Nairea0de002020-11-17 17:42:37 -0800213 ui::Size newSize(width, height);
214 if (mRequestedSize != newSize) {
215 mRequestedSize.set(newSize);
216 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000217 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800218 // If the buffer supports scaling, update the frame immediately since the client may
219 // want to scale the existing buffer to the new size.
220 mSize = mRequestedSize;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000221 // We only need to update the scale if we've received at least one buffer. The reason
222 // for this is the scale is calculated based on the requested size and buffer size.
223 // If there's no buffer, the scale will always be 1.
224 if (mLastBufferInfo.hasBuffer) {
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700225 t.setDestinationFrame(mSurfaceControl,
226 Rect(0, 0, newSize.getWidth(), newSize.getHeight()));
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000227 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800228 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800229 }
Robert Carrfc416512020-04-02 12:32:44 -0700230 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800231 if (applyTransaction) {
232 t.apply();
233 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700234}
235
236static void transactionCallbackThunk(void* context, nsecs_t latchTime,
237 const sp<Fence>& presentFence,
238 const std::vector<SurfaceControlStats>& stats) {
239 if (context == nullptr) {
240 return;
241 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800242 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700243 bq->transactionCallback(latchTime, presentFence, stats);
244}
245
246void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
247 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700248 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
249 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700250
chaviw71c2cc42020-10-23 16:42:02 -0700251 {
252 std::unique_lock _lock{mMutex};
253 ATRACE_CALL();
254 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700255
chaviw42026162021-04-16 15:46:12 -0500256 if (!mSurfaceControlsWithPendingCallback.empty()) {
257 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
258 mSurfaceControlsWithPendingCallback.pop();
259 bool found = false;
260 for (auto stat : stats) {
261 if (!SurfaceControl::isSameSurface(pendingSC, stat.surfaceControl)) {
262 continue;
Vishnu Nair1506b182021-02-22 14:35:15 -0800263 }
chaviw42026162021-04-16 15:46:12 -0500264
265 mTransformHint = stat.transformHint;
266 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700267 // Update frametime stamps if the frame was latched and presented, indicated by a
268 // valid latch time.
269 if (stat.latchTime > 0) {
270 mBufferItemConsumer
271 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
272 stat.frameEventStats.refreshStartTime,
273 stat.frameEventStats.gpuCompositionDoneFence,
274 stat.presentFence, stat.previousReleaseFence,
275 stat.frameEventStats.compositorTiming,
276 stat.latchTime,
277 stat.frameEventStats.dequeueReadyTime);
278 }
chaviw42026162021-04-16 15:46:12 -0500279 currFrameNumber = stat.frameEventStats.frameNumber;
280
281 if (mTransactionCompleteCallback &&
282 currFrameNumber >= mTransactionCompleteFrameNumber) {
283 if (currFrameNumber > mTransactionCompleteFrameNumber) {
284 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
285 " than expected=%" PRIu64,
286 currFrameNumber, mTransactionCompleteFrameNumber);
287 }
288 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
289 mTransactionCompleteFrameNumber = 0;
290 }
291
292 found = true;
293 break;
chaviw71c2cc42020-10-23 16:42:02 -0700294 }
chaviw42026162021-04-16 15:46:12 -0500295
296 if (!found) {
297 BQA_LOGE("Failed to find matching SurfaceControl in transaction callback");
298 }
299 } else {
300 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
301 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800302 }
chaviw71c2cc42020-10-23 16:42:02 -0700303
chaviw71c2cc42020-10-23 16:42:02 -0700304 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700305 }
Valerie Haua32c5522019-12-09 10:11:08 -0800306
chaviw71c2cc42020-10-23 16:42:02 -0700307 if (transactionCompleteCallback) {
308 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800309 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700310}
311
Vishnu Nair1506b182021-02-22 14:35:15 -0800312// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
313// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
314// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
315// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700316static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700317 const sp<Fence>& releaseFence, uint32_t transformHint,
318 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800319 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800320 if (blastBufferQueue) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700321 blastBufferQueue->releaseBufferCallback(id, releaseFence, transformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700322 currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700323 } else {
324 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800325 }
326}
327
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700328void BLASTBufferQueue::releaseBufferCallback(const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700329 const sp<Fence>& releaseFence, uint32_t transformHint,
330 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800331 ATRACE_CALL();
332 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700333 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800334
Robert Carr82d07c92021-05-10 11:36:43 -0700335 if (mSurfaceControl != nullptr) {
Robert Carr97e7cc02021-06-07 10:45:40 -0700336 mTransformHint = transformHint;
337 mSurfaceControl->setTransformHint(transformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700338 mBufferItemConsumer->setTransformHint(mTransformHint);
339 }
340
Ady Abraham899dcdb2021-06-15 16:56:21 -0700341 // Calculate how many buffers we need to hold before we release them back
342 // to the buffer queue. This will prevent higher latency when we are running
343 // on a lower refresh rate than the max supported. We only do that for EGL
344 // clients as others don't care about latency
345 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700346 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700347 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
348 }();
349
350 const auto numPendingBuffersToHold =
351 isEGL ? std::max(0u, mMaxAcquiredBuffers - currentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700352 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700353
354 // Release all buffers that are beyond the ones that we need to hold
355 while (mPendingRelease.size() > numPendingBuffersToHold) {
356 const auto releaseBuffer = mPendingRelease.front();
357 mPendingRelease.pop_front();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700358 auto it = mSubmitted.find(releaseBuffer.callbackId);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700359 if (it == mSubmitted.end()) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700360 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
361 releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700362 return;
363 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700364 mNumAcquired--;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700365 BQA_LOGV("released %s", id.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700366 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
367 mSubmitted.erase(it);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700368 processNextBufferLocked(false /* useNextTransaction */);
Vishnu Nair1506b182021-02-22 14:35:15 -0800369 }
370
Ady Abraham899dcdb2021-06-15 16:56:21 -0700371 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700372 ATRACE_INT(mQueuedBufferTrace.c_str(),
373 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800374 mCallbackCV.notify_all();
375}
376
Robert Carr255acdc2020-04-17 14:08:55 -0700377void BLASTBufferQueue::processNextBufferLocked(bool useNextTransaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800378 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800379 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
380 // include the extra buffer when checking if we can acquire the next buffer.
381 const bool includeExtraAcquire = !useNextTransaction;
382 if (mNumFrameAvailable == 0 || maxBuffersAcquired(includeExtraAcquire)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800383 mCallbackCV.notify_all();
Valerie Haud3b90d22019-11-06 09:37:31 -0800384 return;
385 }
386
Valerie Haua32c5522019-12-09 10:11:08 -0800387 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700388 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800389 return;
390 }
391
Robert Carr78c25dd2019-08-15 14:10:33 -0700392 SurfaceComposerClient::Transaction localTransaction;
393 bool applyTransaction = true;
394 SurfaceComposerClient::Transaction* t = &localTransaction;
Robert Carr255acdc2020-04-17 14:08:55 -0700395 if (mNextTransaction != nullptr && useNextTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700396 t = mNextTransaction;
397 mNextTransaction = nullptr;
398 applyTransaction = false;
399 }
400
Valerie Haua32c5522019-12-09 10:11:08 -0800401 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800402
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800403 status_t status =
404 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800405 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
406 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
407 return;
408 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700409 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700410 return;
411 }
Valerie Haua32c5522019-12-09 10:11:08 -0800412 auto buffer = bufferItem.mGraphicBuffer;
413 mNumFrameAvailable--;
414
415 if (buffer == nullptr) {
416 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700417 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800418 return;
419 }
420
Vishnu Nair670b3f72020-09-29 17:52:18 -0700421 if (rejectBuffer(bufferItem)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800422 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d"
423 "buffer{size=%dx%d transform=%d}",
424 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
425 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
426 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
427 processNextBufferLocked(useNextTransaction);
428 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700429 }
430
Valerie Haua32c5522019-12-09 10:11:08 -0800431 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700432 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
433 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
434 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700435
Valerie Hau871d6352020-01-29 08:44:02 -0800436 bool needsDisconnect = false;
437 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
438
439 // if producer disconnected before, notify SurfaceFlinger
440 if (needsDisconnect) {
441 t->notifyProducerDisconnect(mSurfaceControl);
442 }
443
Robert Carr78c25dd2019-08-15 14:10:33 -0700444 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
445 incStrong((void*)transactionCallbackThunk);
446
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700447 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000448 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
449 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700450 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800451
Vishnu Nair1506b182021-02-22 14:35:15 -0800452 auto releaseBufferCallback =
453 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700454 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
455 std::placeholders::_4);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700456 t->setBuffer(mSurfaceControl, buffer, releaseCallbackId, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500457 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
458 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
459 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700460 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800461 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700462 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviw42026162021-04-16 15:46:12 -0500463 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700464
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700465 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
466 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800467 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800468 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800469 if (!bufferItem.mIsAutoTimestamp) {
470 t->setDesiredPresentTime(bufferItem.mTimestamp);
471 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700472 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700473
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000474 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700475 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000476 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100477 }
478
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800479 if (mAutoRefresh != bufferItem.mAutoRefresh) {
480 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
481 mAutoRefresh = bufferItem.mAutoRefresh;
482 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800483 {
484 std::unique_lock _lock{mTimestampMutex};
485 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
486 if (dequeueTime != mDequeueTimestamps.end()) {
487 Parcel p;
488 p.writeInt64(dequeueTime->second);
489 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
490 mDequeueTimestamps.erase(dequeueTime);
491 }
492 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800493
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800494 auto mergeTransaction =
495 [&t, currentFrameNumber = bufferItem.mFrameNumber](
496 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
497 auto& [targetFrameNumber, transaction] = pendingTransaction;
498 if (currentFrameNumber < targetFrameNumber) {
499 return false;
500 }
501 t->merge(std::move(transaction));
502 return true;
503 };
504
505 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
506 mPendingTransactions.end(), mergeTransaction),
507 mPendingTransactions.end());
508
Robert Carr78c25dd2019-08-15 14:10:33 -0700509 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800510 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700511 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700512
513 BQA_LOGV("processNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800514 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700515 " graphicBufferId=%" PRIu64 "%s",
chaviw3277faf2021-05-19 16:45:23 -0500516 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800517 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700518 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
519 bufferItem.mAutoRefresh ? " mAutoRefresh" : "");
Robert Carr78c25dd2019-08-15 14:10:33 -0700520}
521
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800522Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
523 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800524 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800525 }
526 return item.mCrop;
527}
528
Vishnu Nairaef1de92020-10-22 12:15:53 -0700529void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800530 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800531 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800532
Vishnu Nairdab94092020-09-29 16:09:04 -0700533 const bool nextTransactionSet = mNextTransaction != nullptr;
Vishnu Nair1506b182021-02-22 14:35:15 -0800534 if (nextTransactionSet) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800535 while (mNumFrameAvailable > 0 || maxBuffersAcquired(false /* includeExtraAcquire */)) {
Vishnu Nair7eb670a2020-10-15 12:16:10 -0700536 BQA_LOGV("waiting in onFrameAvailable...");
Valerie Hau0188adf2020-02-13 08:29:20 -0800537 mCallbackCV.wait(_lock);
538 }
539 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800540 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800541 mNumFrameAvailable++;
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700542 ATRACE_INT(mQueuedBufferTrace.c_str(),
543 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800544
545 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
chaviw3277faf2021-05-19 16:45:23 -0500546 boolToString(nextTransactionSet));
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800547 processNextBufferLocked(nextTransactionSet /* useNextTransaction */);
Valerie Haud3b90d22019-11-06 09:37:31 -0800548}
549
Vishnu Nairaef1de92020-10-22 12:15:53 -0700550void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
551 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
552 // Do nothing since we are not storing unacquired buffer items locally.
553}
554
Vishnu Nairadf632b2021-01-07 14:05:08 -0800555void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
556 std::unique_lock _lock{mTimestampMutex};
557 mDequeueTimestamps[bufferId] = systemTime();
558};
559
560void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
561 std::unique_lock _lock{mTimestampMutex};
562 mDequeueTimestamps.erase(bufferId);
563};
564
Robert Carr78c25dd2019-08-15 14:10:33 -0700565void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800566 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700567 mNextTransaction = t;
568}
569
Vishnu Nairea0de002020-11-17 17:42:37 -0800570bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700571 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Hongguang Chen33100282021-04-15 18:36:05 -0700572 mSize = mRequestedSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700573 // Only reject buffers if scaling mode is freeze.
574 return false;
575 }
576
Vishnu Naire1a42322020-10-02 17:42:04 -0700577 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
578 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
579
580 // Take the buffer's orientation into account
581 if (item.mTransform & ui::Transform::ROT_90) {
582 std::swap(bufWidth, bufHeight);
583 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800584 ui::Size bufferSize(bufWidth, bufHeight);
585 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
586 mSize = mRequestedSize;
587 return false;
588 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700589
Vishnu Nair670b3f72020-09-29 17:52:18 -0700590 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800591 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700592}
Vishnu Nairbf255772020-10-16 10:54:41 -0700593
chaviw71c2cc42020-10-23 16:42:02 -0700594void BLASTBufferQueue::setTransactionCompleteCallback(
595 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
596 std::lock_guard _lock{mMutex};
597 if (transactionCompleteCallback == nullptr) {
598 mTransactionCompleteCallback = nullptr;
599 } else {
600 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
601 mTransactionCompleteFrameNumber = frameNumber;
602 }
603}
604
Vishnu Nairbf255772020-10-16 10:54:41 -0700605// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800606// Consumer can acquire an additional buffer if that buffer is not droppable. Set
607// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
608// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
609bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700610 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800611 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700612}
613
Robert Carr05086b22020-10-13 18:22:51 -0700614class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700615private:
616 sp<BLASTBufferQueue> mBbq;
Robert Carr05086b22020-10-13 18:22:51 -0700617public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700618 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
619 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
620 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700621
Robert Carr05086b22020-10-13 18:22:51 -0700622 void allocateBuffers() override {
623 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
624 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
625 auto gbp = getIGraphicBufferProducer();
626 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
627 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
628 gbp->allocateBuffers(reqWidth, reqHeight,
629 reqFormat, reqUsage);
630
631 }).detach();
632 }
Robert Carr9c006e02020-10-14 13:41:57 -0700633
Marin Shalamanovc5986772021-03-16 16:09:49 +0100634 status_t setFrameRate(float frameRate, int8_t compatibility,
635 int8_t changeFrameRateStrategy) override {
636 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
637 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700638 return BAD_VALUE;
639 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100640 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700641 }
Robert Carr9b611b72020-10-19 12:00:23 -0700642
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000643 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
644 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700645 }
Robert Carr82d07c92021-05-10 11:36:43 -0700646 protected:
647 uint32_t getTransformHint() const override {
648 if (mStickyTransform == 0 && !transformToDisplayInverse()) {
649 return mBbq->getLastTransformHint();
650 } else {
651 return 0;
652 }
653 }
Robert Carr05086b22020-10-13 18:22:51 -0700654};
655
Robert Carr9c006e02020-10-14 13:41:57 -0700656// TODO: Can we coalesce this with frame updates? Need to confirm
657// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200658status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
659 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700660 std::unique_lock _lock{mMutex};
661 SurfaceComposerClient::Transaction t;
662
Marin Shalamanov46084422020-10-13 12:33:42 +0200663 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700664}
665
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000666status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700667 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000668 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100669 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700670}
671
Hongguang Chen621ec582021-02-16 15:42:35 -0800672void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
673 std::unique_lock _lock{mMutex};
674 SurfaceComposerClient::Transaction t;
675
676 t.setSidebandStream(mSurfaceControl, stream).apply();
677}
678
Vishnu Nair992496b2020-10-22 17:27:21 -0700679sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
680 std::unique_lock _lock{mMutex};
681 sp<IBinder> scHandle = nullptr;
682 if (includeSurfaceControlHandle && mSurfaceControl) {
683 scHandle = mSurfaceControl->getHandle();
684 }
685 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700686}
687
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800688void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
689 uint64_t frameNumber) {
690 std::lock_guard _lock{mMutex};
691 if (mLastAcquiredFrameNumber >= frameNumber) {
692 // Apply the transaction since we have already acquired the desired frame.
693 t->apply();
694 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500695 mPendingTransactions.emplace_back(frameNumber, *t);
696 // Clear the transaction so it can't be applied elsewhere.
697 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800698 }
699}
700
Vishnu Nair89496122020-12-14 17:14:53 -0800701// Maintains a single worker thread per process that services a list of runnables.
702class AsyncWorker : public Singleton<AsyncWorker> {
703private:
704 std::thread mThread;
705 bool mDone = false;
706 std::deque<std::function<void()>> mRunnables;
707 std::mutex mMutex;
708 std::condition_variable mCv;
709 void run() {
710 std::unique_lock<std::mutex> lock(mMutex);
711 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800712 while (!mRunnables.empty()) {
713 std::function<void()> runnable = mRunnables.front();
714 mRunnables.pop_front();
715 runnable();
716 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700717 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800718 }
719 }
720
721public:
722 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
723
724 ~AsyncWorker() {
725 mDone = true;
726 mCv.notify_all();
727 if (mThread.joinable()) {
728 mThread.join();
729 }
730 }
731
732 void post(std::function<void()> runnable) {
733 std::unique_lock<std::mutex> lock(mMutex);
734 mRunnables.emplace_back(std::move(runnable));
735 mCv.notify_one();
736 }
737};
738ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
739
740// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
741class AsyncProducerListener : public BnProducerListener {
742private:
743 const sp<IProducerListener> mListener;
744
745public:
746 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
747
748 void onBufferReleased() override {
749 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
750 }
751
752 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
753 AsyncWorker::getInstance().post(
754 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
755 }
756};
757
758// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
759// can be non-blocking when the producer is in the client process.
760class BBQBufferQueueProducer : public BufferQueueProducer {
761public:
762 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
763 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
764
765 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
766 QueueBufferOutput* output) override {
767 if (!listener) {
768 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
769 }
770
771 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
772 producerControlledByApp, output);
773 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800774
775 int query(int what, int* value) override {
776 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
777 *value = 1;
778 return NO_ERROR;
779 }
780 return BufferQueueProducer::query(what, value);
781 }
Vishnu Nair89496122020-12-14 17:14:53 -0800782};
783
784// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
785// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
786// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
787// we can deadlock.
788void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
789 sp<IGraphicBufferConsumer>* outConsumer) {
790 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
791 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
792
793 sp<BufferQueueCore> core(new BufferQueueCore());
794 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
795
796 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
797 LOG_ALWAYS_FATAL_IF(producer == nullptr,
798 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
799
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800800 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
801 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800802 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
803 "BLASTBufferQueue: failed to create BufferQueueConsumer");
804
805 *outProducer = producer;
806 *outConsumer = consumer;
807}
808
chaviw497e81c2021-02-04 17:09:47 -0800809PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
810 PixelFormat convertedFormat = format;
811 switch (format) {
812 case PIXEL_FORMAT_TRANSPARENT:
813 case PIXEL_FORMAT_TRANSLUCENT:
814 convertedFormat = PIXEL_FORMAT_RGBA_8888;
815 break;
816 case PIXEL_FORMAT_OPAQUE:
817 convertedFormat = PIXEL_FORMAT_RGBX_8888;
818 break;
819 }
820 return convertedFormat;
821}
822
Robert Carr82d07c92021-05-10 11:36:43 -0700823uint32_t BLASTBufferQueue::getLastTransformHint() const {
824 if (mSurfaceControl != nullptr) {
825 return mSurfaceControl->getTransformHint();
826 } else {
827 return 0;
828 }
829}
830
Robert Carr78c25dd2019-08-15 14:10:33 -0700831} // namespace android