blob: 038e23df4c5def38cc4577c620250c9546e800c6 [file] [log] [blame]
Robert Carr78c25dd2019-08-15 14:10:33 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Valerie Haud3b90d22019-11-06 09:37:31 -080017#undef LOG_TAG
18#define LOG_TAG "BLASTBufferQueue"
19
Valerie Haua32c5522019-12-09 10:11:08 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Vishnu Naire1a42322020-10-02 17:42:04 -070021//#define LOG_NDEBUG 0
Valerie Haua32c5522019-12-09 10:11:08 -080022
Robert Carr78c25dd2019-08-15 14:10:33 -070023#include <gui/BLASTBufferQueue.h>
24#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080025#include <gui/BufferQueueConsumer.h>
26#include <gui/BufferQueueCore.h>
27#include <gui/BufferQueueProducer.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080028#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080029#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070030#include <gui/Surface.h>
Vishnu Nair89496122020-12-14 17:14:53 -080031#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080032#include <utils/Trace.h>
33
Ady Abraham0bde6b52021-05-18 13:57:02 -070034#include <private/gui/ComposerService.h>
35
Robert Carr78c25dd2019-08-15 14:10:33 -070036#include <chrono>
37
38using namespace std::chrono_literals;
39
Vishnu Nairdab94092020-09-29 16:09:04 -070040namespace {
chaviw3277faf2021-05-19 16:45:23 -050041inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070042 return b ? "true" : "false";
43}
44} // namespace
45
Robert Carr78c25dd2019-08-15 14:10:33 -070046namespace android {
47
Vishnu Nairdab94092020-09-29 16:09:04 -070048// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050049#define BQA_LOGD(x, ...) \
50 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070051#define BQA_LOGV(x, ...) \
52 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080053// enable logs for a single layer
54//#define BQA_LOGV(x, ...) \
55// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
56// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070057#define BQA_LOGE(x, ...) \
58 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
59
Valerie Hau871d6352020-01-29 08:44:02 -080060void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000061 Mutex::Autolock lock(mMutex);
62 mPreviouslyConnected = mCurrentlyConnected;
63 mCurrentlyConnected = false;
64 if (mPreviouslyConnected) {
65 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080066 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000067 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080068}
69
70void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
71 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080072 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080073 if (newTimestamps) {
74 // BufferQueueProducer only adds a new timestamp on
75 // queueBuffer
76 mCurrentFrameNumber = newTimestamps->frameNumber;
77 mFrameEventHistory.addQueue(*newTimestamps);
78 }
79 if (outDelta) {
80 // frame event histories will be processed
81 // only after the producer connects and requests
82 // deltas for the first time. Forward this intent
83 // to SF-side to turn event processing back on
84 mPreviouslyConnected = mCurrentlyConnected;
85 mCurrentlyConnected = true;
86 mFrameEventHistory.getAndResetDelta(outDelta);
87 }
88}
89
90void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
91 const sp<Fence>& glDoneFence,
92 const sp<Fence>& presentFence,
93 const sp<Fence>& prevReleaseFence,
94 CompositorTiming compositorTiming,
95 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -080096 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080097
98 // if the producer is not connected, don't bother updating,
99 // the next producer that connects won't access this frame event
100 if (!mCurrentlyConnected) return;
101 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
102 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
103 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
104
105 mFrameEventHistory.addLatch(frameNumber, latchTime);
106 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
107 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
108 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
109 compositorTiming);
110}
111
112void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
113 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800114 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800115 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
116 disconnect = true;
117 mDisconnectEvents.pop();
118 }
119 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
120}
121
Hongguang Chen621ec582021-02-16 15:42:35 -0800122void BLASTBufferItemConsumer::setBlastBufferQueue(BLASTBufferQueue* blastbufferqueue) {
Alec Mouri5c8b18c2021-08-19 16:52:34 -0700123 std::scoped_lock lock(mBufferQueueMutex);
Hongguang Chen621ec582021-02-16 15:42:35 -0800124 mBLASTBufferQueue = blastbufferqueue;
125}
126
127void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Alec Mouri5c8b18c2021-08-19 16:52:34 -0700128 std::scoped_lock lock(mBufferQueueMutex);
Hongguang Chen621ec582021-02-16 15:42:35 -0800129 if (mBLASTBufferQueue != nullptr) {
130 sp<NativeHandle> stream = getSidebandStream();
131 mBLASTBufferQueue->setSidebandStream(stream);
132 }
133}
134
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800135BLASTBufferQueue::BLASTBufferQueue(const std::string& name)
136 : mSurfaceControl(nullptr),
137 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800138 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800139 mFormat(PIXEL_FORMAT_RGBA_8888),
chaviwa1c4c822021-11-10 18:11:58 -0600140 mSyncTransaction(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 Nair4ba0c2e2021-06-24 11:27:17 -0700153 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700154 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700155 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800156 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700157 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700158 mBufferItemConsumer->setFrameAvailableListener(this);
159 mBufferItemConsumer->setBufferFreedListener(this);
Hongguang Chen621ec582021-02-16 15:42:35 -0800160 mBufferItemConsumer->setBlastBufferQueue(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700161
Ady Abraham899dcdb2021-06-15 16:56:21 -0700162 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700163 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500164 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800165 mNumAcquired = 0;
166 mNumFrameAvailable = 0;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800167 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800168}
169
170BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
171 int width, int height, int32_t format)
172 : BLASTBufferQueue(name) {
173 update(surface, width, height, format);
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;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800184 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
185 t.setApplyToken(mApplyToken).apply();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800186}
187
chaviw565ee542021-01-14 10:21:23 -0800188void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Nair084514a2021-07-30 16:07:42 -0700189 int32_t format, SurfaceComposerClient::Transaction* outTransaction) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800190 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
191
Robert Carr78c25dd2019-08-15 14:10:33 -0700192 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800193 if (mFormat != format) {
194 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800195 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800196 }
197
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800198 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800199 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000200 if (surfaceControlChanged && mSurfaceControl != nullptr) {
201 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
202 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800203 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800204
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700205 // Always update the native object even though they might have the same layer handle, so we can
206 // get the updated transform hint from WM.
207 mSurfaceControl = surface;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800208 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800209 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
210 layer_state_t::eEnableBackpressure);
211 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800212 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800213 mTransformHint = mSurfaceControl->getTransformHint();
214 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700215 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
216 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800217
Vishnu Nairea0de002020-11-17 17:42:37 -0800218 ui::Size newSize(width, height);
219 if (mRequestedSize != newSize) {
220 mRequestedSize.set(newSize);
221 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000222 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800223 // If the buffer supports scaling, update the frame immediately since the client may
224 // want to scale the existing buffer to the new size.
225 mSize = mRequestedSize;
Vishnu Nair084514a2021-07-30 16:07:42 -0700226 SurfaceComposerClient::Transaction* destFrameTransaction =
227 (outTransaction) ? outTransaction : &t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800228 destFrameTransaction->setDestinationFrame(mSurfaceControl,
229 Rect(0, 0, newSize.getWidth(),
230 newSize.getHeight()));
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) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700235 t.setApplyToken(mApplyToken).apply();
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800236 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700237}
238
chaviwd7deef72021-10-06 11:53:40 -0500239static std::optional<SurfaceControlStats> findMatchingStat(
240 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
241 for (auto stat : stats) {
242 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
243 return stat;
244 }
245 }
246 return std::nullopt;
247}
248
249static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
250 const sp<Fence>& presentFence,
251 const std::vector<SurfaceControlStats>& stats) {
252 if (context == nullptr) {
253 return;
254 }
255 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
256 bq->transactionCommittedCallback(latchTime, presentFence, stats);
257}
258
259void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
260 const sp<Fence>& /*presentFence*/,
261 const std::vector<SurfaceControlStats>& stats) {
262 {
263 std::unique_lock _lock{mMutex};
264 ATRACE_CALL();
265 BQA_LOGV("transactionCommittedCallback");
266 if (!mSurfaceControlsWithPendingCallback.empty()) {
267 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
268 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
269 if (stat) {
270 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
271
272 // We need to check if we were waiting for a transaction callback in order to
273 // process any pending buffers and unblock. It's possible to get transaction
274 // callbacks for previous requests so we need to ensure the frame from this
275 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
276 // will stop processing buffers when mWaitForTransactionCallback is set, we know
277 // that mLastAcquiredFrameNumber is the frame we're waiting on.
278 // We also want to check if mNextTransaction is null because it's possible another
279 // sync request came in while waiting, but it hasn't started processing yet. In that
280 // case, we don't actually want to flush the frames in between since they will get
281 // processed and merged with the sync transaction and released earlier than if they
282 // were sent to SF
chaviwa1c4c822021-11-10 18:11:58 -0600283 if (mWaitForTransactionCallback && mSyncTransaction == nullptr &&
chaviwd7deef72021-10-06 11:53:40 -0500284 currFrameNumber >= mLastAcquiredFrameNumber) {
285 mWaitForTransactionCallback = false;
286 flushShadowQueue();
287 }
288 } else {
chaviw768bfa02021-11-01 09:50:57 -0500289 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500290 }
291 } else {
292 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
293 "empty.");
294 }
295
296 decStrong((void*)transactionCommittedCallbackThunk);
297 }
298}
299
Robert Carr78c25dd2019-08-15 14:10:33 -0700300static void transactionCallbackThunk(void* context, nsecs_t latchTime,
301 const sp<Fence>& presentFence,
302 const std::vector<SurfaceControlStats>& stats) {
303 if (context == nullptr) {
304 return;
305 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800306 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700307 bq->transactionCallback(latchTime, presentFence, stats);
308}
309
310void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
311 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700312 {
313 std::unique_lock _lock{mMutex};
314 ATRACE_CALL();
315 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700316
chaviw42026162021-04-16 15:46:12 -0500317 if (!mSurfaceControlsWithPendingCallback.empty()) {
318 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
319 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500320 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
321 if (statsOptional) {
322 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500323 mTransformHint = stat.transformHint;
324 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700325 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700326 // Update frametime stamps if the frame was latched and presented, indicated by a
327 // valid latch time.
328 if (stat.latchTime > 0) {
329 mBufferItemConsumer
330 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
331 stat.frameEventStats.refreshStartTime,
332 stat.frameEventStats.gpuCompositionDoneFence,
333 stat.presentFence, stat.previousReleaseFence,
334 stat.frameEventStats.compositorTiming,
335 stat.latchTime,
336 stat.frameEventStats.dequeueReadyTime);
337 }
chaviwd7deef72021-10-06 11:53:40 -0500338 } else {
chaviw768bfa02021-11-01 09:50:57 -0500339 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500340 }
341 } else {
342 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
343 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800344 }
chaviw71c2cc42020-10-23 16:42:02 -0700345
chaviw71c2cc42020-10-23 16:42:02 -0700346 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700347 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700348}
349
Vishnu Nair1506b182021-02-22 14:35:15 -0800350// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
351// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
352// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
353// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700354static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500355 const sp<Fence>& releaseFence,
356 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800357 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800358 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500359 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700360 } else {
361 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800362 }
363}
364
chaviwd7deef72021-10-06 11:53:40 -0500365void BLASTBufferQueue::flushShadowQueue() {
366 BQA_LOGV("flushShadowQueue");
367 int numFramesToFlush = mNumFrameAvailable;
368 while (numFramesToFlush > 0) {
369 acquireNextBufferLocked(std::nullopt);
370 numFramesToFlush--;
371 }
372}
373
chaviw69058fb2021-09-27 09:37:30 -0500374void BLASTBufferQueue::releaseBufferCallback(
375 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
376 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800377 ATRACE_CALL();
378 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700379 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800380
Ady Abraham899dcdb2021-06-15 16:56:21 -0700381 // Calculate how many buffers we need to hold before we release them back
382 // to the buffer queue. This will prevent higher latency when we are running
383 // on a lower refresh rate than the max supported. We only do that for EGL
384 // clients as others don't care about latency
385 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700386 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700387 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
388 }();
389
chaviw69058fb2021-09-27 09:37:30 -0500390 if (currentMaxAcquiredBufferCount) {
391 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
392 }
393
Ady Abraham899dcdb2021-06-15 16:56:21 -0700394 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500395 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700396 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700397
398 // Release all buffers that are beyond the ones that we need to hold
399 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500400 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700401 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500402 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwd7deef72021-10-06 11:53:40 -0500403 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
chaviwa1c4c822021-11-10 18:11:58 -0600404 // onFrameAvailable handle processing them since it will merge with the syncTransaction.
chaviwd7deef72021-10-06 11:53:40 -0500405 if (!mWaitForTransactionCallback) {
406 acquireNextBufferLocked(std::nullopt);
407 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800408 }
409
Ady Abraham899dcdb2021-06-15 16:56:21 -0700410 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700411 ATRACE_INT(mQueuedBufferTrace.c_str(),
412 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800413 mCallbackCV.notify_all();
414}
415
chaviw0acd33a2021-11-02 11:55:37 -0500416void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
417 const sp<Fence>& releaseFence) {
418 auto it = mSubmitted.find(callbackId);
419 if (it == mSubmitted.end()) {
420 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
421 callbackId.to_string().c_str());
422 return;
423 }
424 mNumAcquired--;
425 BQA_LOGV("released %s", callbackId.to_string().c_str());
426 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
427 mSubmitted.erase(it);
428}
429
chaviwd7deef72021-10-06 11:53:40 -0500430void BLASTBufferQueue::acquireNextBufferLocked(
431 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800432 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800433 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
434 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500435 const bool includeExtraAcquire = !transaction;
436 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
437 if (mNumFrameAvailable == 0 || maxAcquired) {
438 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800439 return;
440 }
441
Valerie Haua32c5522019-12-09 10:11:08 -0800442 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700443 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800444 return;
445 }
446
Robert Carr78c25dd2019-08-15 14:10:33 -0700447 SurfaceComposerClient::Transaction localTransaction;
448 bool applyTransaction = true;
449 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500450 if (transaction) {
451 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700452 applyTransaction = false;
453 }
454
Valerie Haua32c5522019-12-09 10:11:08 -0800455 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800456
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800457 status_t status =
458 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800459 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
460 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
461 return;
462 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700463 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700464 return;
465 }
Valerie Haua32c5522019-12-09 10:11:08 -0800466 auto buffer = bufferItem.mGraphicBuffer;
467 mNumFrameAvailable--;
468
469 if (buffer == nullptr) {
470 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700471 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800472 return;
473 }
474
Vishnu Nair670b3f72020-09-29 17:52:18 -0700475 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700476 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800477 "buffer{size=%dx%d transform=%d}",
478 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
479 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
480 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500481 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800482 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700483 }
484
Valerie Haua32c5522019-12-09 10:11:08 -0800485 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700486 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
487 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
488 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700489
Valerie Hau871d6352020-01-29 08:44:02 -0800490 bool needsDisconnect = false;
491 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
492
493 // if producer disconnected before, notify SurfaceFlinger
494 if (needsDisconnect) {
495 t->notifyProducerDisconnect(mSurfaceControl);
496 }
497
Robert Carr78c25dd2019-08-15 14:10:33 -0700498 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
499 incStrong((void*)transactionCallbackThunk);
500
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800501 const bool updateDestinationFrame = mRequestedSize != mSize;
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700502 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700503 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000504 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
505 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700506 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800507
Vishnu Nair1506b182021-02-22 14:35:15 -0800508 auto releaseBufferCallback =
509 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500510 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500511 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
512 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseCallbackId,
513 releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500514 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
515 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
516 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700517 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600518
chaviw42026162021-04-16 15:46:12 -0500519 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700520
Vishnu Nair084514a2021-07-30 16:07:42 -0700521 if (updateDestinationFrame) {
522 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
523 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700524 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800525 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800526 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800527 if (!bufferItem.mIsAutoTimestamp) {
528 t->setDesiredPresentTime(bufferItem.mTimestamp);
529 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700530
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000531 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700532 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000533 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100534 }
535
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800536 if (mAutoRefresh != bufferItem.mAutoRefresh) {
537 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
538 mAutoRefresh = bufferItem.mAutoRefresh;
539 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800540 {
541 std::unique_lock _lock{mTimestampMutex};
542 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
543 if (dequeueTime != mDequeueTimestamps.end()) {
544 Parcel p;
545 p.writeInt64(dequeueTime->second);
546 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
547 mDequeueTimestamps.erase(dequeueTime);
548 }
549 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800550
chaviw6a195272021-09-03 16:14:25 -0500551 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700552 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800553 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700554 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700555
chaviwd7deef72021-10-06 11:53:40 -0500556 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800557 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700558 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500559 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800560 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700561 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700562 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700563}
564
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800565Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
566 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800567 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800568 }
569 return item.mCrop;
570}
571
chaviwd7deef72021-10-06 11:53:40 -0500572void BLASTBufferQueue::acquireAndReleaseBuffer() {
573 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500574 status_t status =
575 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
576 if (status != OK) {
577 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
578 statusToString(status).c_str());
579 return;
580 }
chaviwd7deef72021-10-06 11:53:40 -0500581 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500582 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500583}
584
chaviw0acd33a2021-11-02 11:55:37 -0500585void BLASTBufferQueue::flushAndWaitForFreeBuffer(std::unique_lock<std::mutex>& lock) {
586 if (mWaitForTransactionCallback && mNumFrameAvailable > 0) {
587 // We are waiting on a previous sync's transaction callback so allow another sync
588 // transaction to proceed.
589 //
590 // We need to first flush out the transactions that were in between the two syncs.
591 // We do this by merging them into mSyncTransaction so any buffer merging will get
592 // a release callback invoked. The release callback will be async so we need to wait
593 // on max acquired to make sure we have the capacity to acquire another buffer.
594 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
595 BQA_LOGD("waiting to flush shadow queue...");
596 mCallbackCV.wait(lock);
597 }
598 while (mNumFrameAvailable > 0) {
599 // flush out the shadow queue
600 acquireAndReleaseBuffer();
601 }
602 }
603
604 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
605 BQA_LOGD("waiting for free buffer.");
606 mCallbackCV.wait(lock);
607 }
608}
609
Vishnu Nairaef1de92020-10-22 12:15:53 -0700610void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800611 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800612 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800613
chaviwa1c4c822021-11-10 18:11:58 -0600614 const bool syncTransactionSet = mSyncTransaction != nullptr;
615 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
chaviw0acd33a2021-11-02 11:55:37 -0500616
chaviwa1c4c822021-11-10 18:11:58 -0600617 if (syncTransactionSet) {
chaviw0acd33a2021-11-02 11:55:37 -0500618 bool mayNeedToWaitForBuffer = true;
619 // If we are going to re-use the same mSyncTransaction, release the buffer that may already
620 // be set in the Transaction. This is to allow us a free slot early to continue processing
621 // a new buffer.
622 if (!mAcquireSingleBuffer) {
623 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
624 if (bufferData) {
625 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
626 bufferData->frameNumber);
627 releaseBuffer(bufferData->releaseCallbackId, bufferData->acquireFence);
628 // Because we just released a buffer, we know there's no need to wait for a free
629 // buffer.
630 mayNeedToWaitForBuffer = false;
chaviwd7deef72021-10-06 11:53:40 -0500631 }
632 }
633
chaviw0acd33a2021-11-02 11:55:37 -0500634 if (mayNeedToWaitForBuffer) {
635 flushAndWaitForFreeBuffer(_lock);
Valerie Hau0188adf2020-02-13 08:29:20 -0800636 }
637 }
chaviwd7deef72021-10-06 11:53:40 -0500638
Valerie Haud3b90d22019-11-06 09:37:31 -0800639 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800640 mNumFrameAvailable++;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800641 if (mWaitForTransactionCallback && mNumFrameAvailable >= 2) {
Robert Carrcf2f21f2021-11-30 14:47:02 -0800642 acquireAndReleaseBuffer();
643 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700644 ATRACE_INT(mQueuedBufferTrace.c_str(),
645 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800646
chaviwa1c4c822021-11-10 18:11:58 -0600647 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s", item.mFrameNumber,
648 boolToString(syncTransactionSet));
chaviwd7deef72021-10-06 11:53:40 -0500649
chaviwa1c4c822021-11-10 18:11:58 -0600650 if (syncTransactionSet) {
chaviw0acd33a2021-11-02 11:55:37 -0500651 acquireNextBufferLocked(mSyncTransaction);
chaviwf2dace72021-11-17 17:36:50 -0600652
653 // Only need a commit callback when syncing to ensure the buffer that's synced has been sent
654 // to SF
655 incStrong((void*)transactionCommittedCallbackThunk);
656 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
657 static_cast<void*>(this));
658
chaviw0acd33a2021-11-02 11:55:37 -0500659 if (mAcquireSingleBuffer) {
660 mSyncTransaction = nullptr;
661 }
chaviwd7deef72021-10-06 11:53:40 -0500662 mWaitForTransactionCallback = true;
663 } else if (!mWaitForTransactionCallback) {
664 acquireNextBufferLocked(std::nullopt);
665 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800666}
667
Vishnu Nairaef1de92020-10-22 12:15:53 -0700668void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
669 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
670 // Do nothing since we are not storing unacquired buffer items locally.
671}
672
Vishnu Nairadf632b2021-01-07 14:05:08 -0800673void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
674 std::unique_lock _lock{mTimestampMutex};
675 mDequeueTimestamps[bufferId] = systemTime();
676};
677
678void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
679 std::unique_lock _lock{mTimestampMutex};
680 mDequeueTimestamps.erase(bufferId);
681};
682
chaviw0acd33a2021-11-02 11:55:37 -0500683void BLASTBufferQueue::setSyncTransaction(SurfaceComposerClient::Transaction* t,
684 bool acquireSingleBuffer) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800685 std::lock_guard _lock{mMutex};
chaviwa1c4c822021-11-10 18:11:58 -0600686 mSyncTransaction = t;
chaviw0acd33a2021-11-02 11:55:37 -0500687 mAcquireSingleBuffer = mSyncTransaction ? acquireSingleBuffer : true;
Robert Carr78c25dd2019-08-15 14:10:33 -0700688}
689
Vishnu Nairea0de002020-11-17 17:42:37 -0800690bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700691 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
692 // Only reject buffers if scaling mode is freeze.
693 return false;
694 }
695
Vishnu Naire1a42322020-10-02 17:42:04 -0700696 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
697 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
698
699 // Take the buffer's orientation into account
700 if (item.mTransform & ui::Transform::ROT_90) {
701 std::swap(bufWidth, bufHeight);
702 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800703 ui::Size bufferSize(bufWidth, bufHeight);
704 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800705 return false;
706 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700707
Vishnu Nair670b3f72020-09-29 17:52:18 -0700708 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800709 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700710}
Vishnu Nairbf255772020-10-16 10:54:41 -0700711
712// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800713// Consumer can acquire an additional buffer if that buffer is not droppable. Set
714// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
715// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
716bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700717 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800718 return mNumAcquired >= maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700719}
720
Robert Carr05086b22020-10-13 18:22:51 -0700721class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700722private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700723 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700724 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700725 bool mDestroyed = false;
726
Robert Carr05086b22020-10-13 18:22:51 -0700727public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700728 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
729 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
730 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700731
Robert Carr05086b22020-10-13 18:22:51 -0700732 void allocateBuffers() override {
733 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
734 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
735 auto gbp = getIGraphicBufferProducer();
736 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
737 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
738 gbp->allocateBuffers(reqWidth, reqHeight,
739 reqFormat, reqUsage);
740
741 }).detach();
742 }
Robert Carr9c006e02020-10-14 13:41:57 -0700743
Marin Shalamanovc5986772021-03-16 16:09:49 +0100744 status_t setFrameRate(float frameRate, int8_t compatibility,
745 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700746 std::unique_lock _lock{mMutex};
747 if (mDestroyed) {
748 return DEAD_OBJECT;
749 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100750 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
751 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700752 return BAD_VALUE;
753 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100754 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700755 }
Robert Carr9b611b72020-10-19 12:00:23 -0700756
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000757 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700758 std::unique_lock _lock{mMutex};
759 if (mDestroyed) {
760 return DEAD_OBJECT;
761 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000762 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700763 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700764
765 void destroy() override {
766 Surface::destroy();
767
768 std::unique_lock _lock{mMutex};
769 mDestroyed = true;
770 mBbq = nullptr;
771 }
Robert Carr05086b22020-10-13 18:22:51 -0700772};
773
Robert Carr9c006e02020-10-14 13:41:57 -0700774// TODO: Can we coalesce this with frame updates? Need to confirm
775// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200776status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
777 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700778 std::unique_lock _lock{mMutex};
779 SurfaceComposerClient::Transaction t;
780
Marin Shalamanov46084422020-10-13 12:33:42 +0200781 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700782}
783
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000784status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700785 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000786 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100787 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700788}
789
Hongguang Chen621ec582021-02-16 15:42:35 -0800790void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
791 std::unique_lock _lock{mMutex};
792 SurfaceComposerClient::Transaction t;
793
794 t.setSidebandStream(mSurfaceControl, stream).apply();
795}
796
Vishnu Nair992496b2020-10-22 17:27:21 -0700797sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
798 std::unique_lock _lock{mMutex};
799 sp<IBinder> scHandle = nullptr;
800 if (includeSurfaceControlHandle && mSurfaceControl) {
801 scHandle = mSurfaceControl->getHandle();
802 }
803 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700804}
805
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800806void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
807 uint64_t frameNumber) {
808 std::lock_guard _lock{mMutex};
809 if (mLastAcquiredFrameNumber >= frameNumber) {
810 // Apply the transaction since we have already acquired the desired frame.
811 t->apply();
812 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500813 mPendingTransactions.emplace_back(frameNumber, *t);
814 // Clear the transaction so it can't be applied elsewhere.
815 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800816 }
817}
818
chaviw6a195272021-09-03 16:14:25 -0500819void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
820 std::lock_guard _lock{mMutex};
821
822 SurfaceComposerClient::Transaction t;
823 mergePendingTransactions(&t, frameNumber);
824 t.setApplyToken(mApplyToken).apply();
825}
826
827void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
828 uint64_t frameNumber) {
829 auto mergeTransaction =
830 [&t, currentFrameNumber = frameNumber](
831 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
832 auto& [targetFrameNumber, transaction] = pendingTransaction;
833 if (currentFrameNumber < targetFrameNumber) {
834 return false;
835 }
836 t->merge(std::move(transaction));
837 return true;
838 };
839
840 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
841 mPendingTransactions.end(), mergeTransaction),
842 mPendingTransactions.end());
843}
844
Vishnu Nair89496122020-12-14 17:14:53 -0800845// Maintains a single worker thread per process that services a list of runnables.
846class AsyncWorker : public Singleton<AsyncWorker> {
847private:
848 std::thread mThread;
849 bool mDone = false;
850 std::deque<std::function<void()>> mRunnables;
851 std::mutex mMutex;
852 std::condition_variable mCv;
853 void run() {
854 std::unique_lock<std::mutex> lock(mMutex);
855 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800856 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700857 std::deque<std::function<void()>> runnables = std::move(mRunnables);
858 mRunnables.clear();
859 lock.unlock();
860 // Run outside the lock since the runnable might trigger another
861 // post to the async worker.
862 execute(runnables);
863 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800864 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700865 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800866 }
867 }
868
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700869 void execute(std::deque<std::function<void()>>& runnables) {
870 while (!runnables.empty()) {
871 std::function<void()> runnable = runnables.front();
872 runnables.pop_front();
873 runnable();
874 }
875 }
876
Vishnu Nair89496122020-12-14 17:14:53 -0800877public:
878 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
879
880 ~AsyncWorker() {
881 mDone = true;
882 mCv.notify_all();
883 if (mThread.joinable()) {
884 mThread.join();
885 }
886 }
887
888 void post(std::function<void()> runnable) {
889 std::unique_lock<std::mutex> lock(mMutex);
890 mRunnables.emplace_back(std::move(runnable));
891 mCv.notify_one();
892 }
893};
894ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
895
896// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
897class AsyncProducerListener : public BnProducerListener {
898private:
899 const sp<IProducerListener> mListener;
900
901public:
902 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
903
904 void onBufferReleased() override {
905 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
906 }
907
908 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
909 AsyncWorker::getInstance().post(
910 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
911 }
912};
913
914// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
915// can be non-blocking when the producer is in the client process.
916class BBQBufferQueueProducer : public BufferQueueProducer {
917public:
918 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
919 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
920
921 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
922 QueueBufferOutput* output) override {
923 if (!listener) {
924 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
925 }
926
927 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
928 producerControlledByApp, output);
929 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800930
931 int query(int what, int* value) override {
932 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
933 *value = 1;
934 return NO_ERROR;
935 }
936 return BufferQueueProducer::query(what, value);
937 }
Vishnu Nair89496122020-12-14 17:14:53 -0800938};
939
940// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
941// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
942// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
943// we can deadlock.
944void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
945 sp<IGraphicBufferConsumer>* outConsumer) {
946 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
947 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
948
949 sp<BufferQueueCore> core(new BufferQueueCore());
950 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
951
952 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
953 LOG_ALWAYS_FATAL_IF(producer == nullptr,
954 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
955
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800956 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
957 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800958 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
959 "BLASTBufferQueue: failed to create BufferQueueConsumer");
960
961 *outProducer = producer;
962 *outConsumer = consumer;
963}
964
chaviw497e81c2021-02-04 17:09:47 -0800965PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
966 PixelFormat convertedFormat = format;
967 switch (format) {
968 case PIXEL_FORMAT_TRANSPARENT:
969 case PIXEL_FORMAT_TRANSLUCENT:
970 convertedFormat = PIXEL_FORMAT_RGBA_8888;
971 break;
972 case PIXEL_FORMAT_OPAQUE:
973 convertedFormat = PIXEL_FORMAT_RGBX_8888;
974 break;
975 }
976 return convertedFormat;
977}
978
Robert Carr82d07c92021-05-10 11:36:43 -0700979uint32_t BLASTBufferQueue::getLastTransformHint() const {
980 if (mSurfaceControl != nullptr) {
981 return mSurfaceControl->getTransformHint();
982 } else {
983 return 0;
984 }
985}
986
chaviw0b020f82021-08-20 12:00:47 -0500987uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
988 std::unique_lock _lock{mMutex};
989 return mLastAcquiredFrameNumber;
990}
991
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800992void BLASTBufferQueue::abandon() {
993 std::unique_lock _lock{mMutex};
994 // flush out the shadow queue
995 while (mNumFrameAvailable > 0) {
996 acquireAndReleaseBuffer();
997 }
998
999 // Clear submitted buffer states
1000 mNumAcquired = 0;
1001 mSubmitted.clear();
1002 mPendingRelease.clear();
1003
1004 if (!mPendingTransactions.empty()) {
1005 BQA_LOGD("Applying pending transactions on abandon %d",
1006 static_cast<uint32_t>(mPendingTransactions.size()));
1007 SurfaceComposerClient::Transaction t;
1008 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
1009 t.setApplyToken(mApplyToken).apply();
1010 }
1011
1012 // Clear sync states
1013 if (mWaitForTransactionCallback) {
1014 BQA_LOGD("mWaitForTransactionCallback cleared");
1015 mWaitForTransactionCallback = false;
1016 }
1017
1018 if (mSyncTransaction != nullptr) {
1019 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1020 mAcquireSingleBuffer ? "true" : "false");
1021 mSyncTransaction = nullptr;
1022 mAcquireSingleBuffer = false;
1023 }
1024
1025 // abandon buffer queue
1026 if (mBufferItemConsumer != nullptr) {
1027 mBufferItemConsumer->abandon();
1028 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1029 mBufferItemConsumer->setBufferFreedListener(nullptr);
1030 mBufferItemConsumer->setBlastBufferQueue(nullptr);
1031 }
1032 mBufferItemConsumer = nullptr;
1033 mConsumer = nullptr;
1034 mProducer = nullptr;
1035}
1036
1037bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1038 std::unique_lock _lock{mMutex};
1039 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1040}
1041
Robert Carr78c25dd2019-08-15 14:10:33 -07001042} // namespace android