blob: f34061492a984b8c1d8be92fce18c577e16e4e7e [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>
chaviw57ae4b22022-02-03 16:51:39 -060031#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080032#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080033#include <utils/Trace.h>
34
Ady Abraham0bde6b52021-05-18 13:57:02 -070035#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080036#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070037
Robert Carr78c25dd2019-08-15 14:10:33 -070038#include <chrono>
39
40using namespace std::chrono_literals;
41
Vishnu Nairdab94092020-09-29 16:09:04 -070042namespace {
chaviw3277faf2021-05-19 16:45:23 -050043inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070044 return b ? "true" : "false";
45}
46} // namespace
47
Robert Carr78c25dd2019-08-15 14:10:33 -070048namespace android {
49
Vishnu Nairdab94092020-09-29 16:09:04 -070050// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050051#define BQA_LOGD(x, ...) \
52 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070053#define BQA_LOGV(x, ...) \
54 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080055// enable logs for a single layer
56//#define BQA_LOGV(x, ...) \
57// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
58// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070059#define BQA_LOGE(x, ...) \
60 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
61
chaviw57ae4b22022-02-03 16:51:39 -060062#define BBQ_TRACE(x, ...) \
63 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
64 mNumAcquired, ##__VA_ARGS__)
65
Valerie Hau871d6352020-01-29 08:44:02 -080066void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000067 Mutex::Autolock lock(mMutex);
68 mPreviouslyConnected = mCurrentlyConnected;
69 mCurrentlyConnected = false;
70 if (mPreviouslyConnected) {
71 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080072 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000073 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080074}
75
76void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
77 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080078 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080079 if (newTimestamps) {
80 // BufferQueueProducer only adds a new timestamp on
81 // queueBuffer
82 mCurrentFrameNumber = newTimestamps->frameNumber;
83 mFrameEventHistory.addQueue(*newTimestamps);
84 }
85 if (outDelta) {
86 // frame event histories will be processed
87 // only after the producer connects and requests
88 // deltas for the first time. Forward this intent
89 // to SF-side to turn event processing back on
90 mPreviouslyConnected = mCurrentlyConnected;
91 mCurrentlyConnected = true;
92 mFrameEventHistory.getAndResetDelta(outDelta);
93 }
94}
95
96void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
97 const sp<Fence>& glDoneFence,
98 const sp<Fence>& presentFence,
99 const sp<Fence>& prevReleaseFence,
100 CompositorTiming compositorTiming,
101 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800102 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800103
104 // if the producer is not connected, don't bother updating,
105 // the next producer that connects won't access this frame event
106 if (!mCurrentlyConnected) return;
107 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
108 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
109 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
110
111 mFrameEventHistory.addLatch(frameNumber, latchTime);
112 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
113 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
114 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
115 compositorTiming);
116}
117
118void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
119 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800120 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800121 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
122 disconnect = true;
123 mDisconnectEvents.pop();
124 }
125 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
126}
127
Hongguang Chen621ec582021-02-16 15:42:35 -0800128void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800129 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
130 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800131 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800132 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800133 }
134}
135
Vishnu Naird2aaab12022-02-10 14:49:09 -0800136BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800137 : mSurfaceControl(nullptr),
138 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800139 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800140 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000141 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800142 mSyncTransaction(nullptr),
143 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800144 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800145 // since the adapter is in the client process, set dequeue timeout
146 // explicitly so that dequeueBuffer will block
147 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800148
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700149 // safe default, most producers are expected to override this
150 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800151 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
152 GraphicBuffer::USAGE_HW_COMPOSER |
153 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800154 1, false, this);
Valerie Haua32c5522019-12-09 10:11:08 -0800155 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700156 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700157 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700158 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800159 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700160 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700161 mBufferItemConsumer->setFrameAvailableListener(this);
162 mBufferItemConsumer->setBufferFreedListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700163
Huihong Luo02186fb2022-02-23 14:21:54 -0800164 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700165 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500166 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800167 mNumAcquired = 0;
168 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800169
170 TransactionCompletedListener::getInstance()->addQueueStallListener(
171 [&]() {
172 std::function<void(bool)> callbackCopy;
173 {
174 std::unique_lock _lock{mMutex};
175 callbackCopy = mTransactionHangCallback;
176 }
177 if (callbackCopy) callbackCopy(true);
178 }, this);
179
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800180 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800181}
182
183BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
184 int width, int height, int32_t format)
185 : BLASTBufferQueue(name) {
186 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700187}
188
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800189BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800190 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800191 if (mPendingTransactions.empty()) {
192 return;
193 }
194 BQA_LOGE("Applying pending transactions on dtor %d",
195 static_cast<uint32_t>(mPendingTransactions.size()));
196 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800197 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800198 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
199 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500200
201 if (mTransactionReadyCallback) {
202 mTransactionReadyCallback(mSyncTransaction);
203 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800204}
205
chaviw565ee542021-01-14 10:21:23 -0800206void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800207 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800208 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
209
Robert Carr78c25dd2019-08-15 14:10:33 -0700210 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800211 if (mFormat != format) {
212 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800213 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800214 }
215
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800216 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000217 if (surfaceControlChanged && mSurfaceControl != nullptr) {
218 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
219 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800220 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800221
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700222 // Always update the native object even though they might have the same layer handle, so we can
223 // get the updated transform hint from WM.
224 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800225 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800226 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800227 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
228 layer_state_t::eEnableBackpressure);
229 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800230 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800231 mTransformHint = mSurfaceControl->getTransformHint();
232 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700233 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
234 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800235
Vishnu Nairea0de002020-11-17 17:42:37 -0800236 ui::Size newSize(width, height);
237 if (mRequestedSize != newSize) {
238 mRequestedSize.set(newSize);
239 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000240 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800241 // If the buffer supports scaling, update the frame immediately since the client may
242 // want to scale the existing buffer to the new size.
243 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800244 if (mUpdateDestinationFrame) {
245 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
246 applyTransaction = true;
247 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800248 }
Robert Carrfc416512020-04-02 12:32:44 -0700249 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800250 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800251 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
252 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800253 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700254}
255
chaviwd7deef72021-10-06 11:53:40 -0500256static std::optional<SurfaceControlStats> findMatchingStat(
257 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
258 for (auto stat : stats) {
259 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
260 return stat;
261 }
262 }
263 return std::nullopt;
264}
265
266static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
267 const sp<Fence>& presentFence,
268 const std::vector<SurfaceControlStats>& stats) {
269 if (context == nullptr) {
270 return;
271 }
272 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
273 bq->transactionCommittedCallback(latchTime, presentFence, stats);
274}
275
276void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
277 const sp<Fence>& /*presentFence*/,
278 const std::vector<SurfaceControlStats>& stats) {
279 {
280 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600281 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500282 BQA_LOGV("transactionCommittedCallback");
283 if (!mSurfaceControlsWithPendingCallback.empty()) {
284 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
285 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
286 if (stat) {
287 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
288
289 // We need to check if we were waiting for a transaction callback in order to
290 // process any pending buffers and unblock. It's possible to get transaction
291 // callbacks for previous requests so we need to ensure the frame from this
292 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
293 // will stop processing buffers when mWaitForTransactionCallback is set, we know
294 // that mLastAcquiredFrameNumber is the frame we're waiting on.
295 // We also want to check if mNextTransaction is null because it's possible another
296 // sync request came in while waiting, but it hasn't started processing yet. In that
297 // case, we don't actually want to flush the frames in between since they will get
298 // processed and merged with the sync transaction and released earlier than if they
299 // were sent to SF
chaviwa1c4c822021-11-10 18:11:58 -0600300 if (mWaitForTransactionCallback && mSyncTransaction == nullptr &&
chaviwd7deef72021-10-06 11:53:40 -0500301 currFrameNumber >= mLastAcquiredFrameNumber) {
302 mWaitForTransactionCallback = false;
303 flushShadowQueue();
304 }
305 } else {
chaviw768bfa02021-11-01 09:50:57 -0500306 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500307 }
308 } else {
309 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
310 "empty.");
311 }
312
313 decStrong((void*)transactionCommittedCallbackThunk);
314 }
315}
316
Robert Carr78c25dd2019-08-15 14:10:33 -0700317static void transactionCallbackThunk(void* context, nsecs_t latchTime,
318 const sp<Fence>& presentFence,
319 const std::vector<SurfaceControlStats>& stats) {
320 if (context == nullptr) {
321 return;
322 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800323 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700324 bq->transactionCallback(latchTime, presentFence, stats);
325}
326
327void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
328 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700329 {
330 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600331 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700332 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700333
chaviw42026162021-04-16 15:46:12 -0500334 if (!mSurfaceControlsWithPendingCallback.empty()) {
335 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
336 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500337 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
338 if (statsOptional) {
339 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500340 mTransformHint = stat.transformHint;
341 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700342 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700343 // Update frametime stamps if the frame was latched and presented, indicated by a
344 // valid latch time.
345 if (stat.latchTime > 0) {
346 mBufferItemConsumer
347 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
348 stat.frameEventStats.refreshStartTime,
349 stat.frameEventStats.gpuCompositionDoneFence,
350 stat.presentFence, stat.previousReleaseFence,
351 stat.frameEventStats.compositorTiming,
352 stat.latchTime,
353 stat.frameEventStats.dequeueReadyTime);
354 }
chaviwd7deef72021-10-06 11:53:40 -0500355 } else {
chaviw768bfa02021-11-01 09:50:57 -0500356 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500357 }
358 } else {
359 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
360 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800361 }
chaviw71c2cc42020-10-23 16:42:02 -0700362
chaviw71c2cc42020-10-23 16:42:02 -0700363 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700364 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700365}
366
Vishnu Nair1506b182021-02-22 14:35:15 -0800367// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
368// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
369// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
370// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700371static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500372 const sp<Fence>& releaseFence,
373 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800374 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800375 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500376 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700377 } else {
378 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800379 }
380}
381
chaviwd7deef72021-10-06 11:53:40 -0500382void BLASTBufferQueue::flushShadowQueue() {
383 BQA_LOGV("flushShadowQueue");
384 int numFramesToFlush = mNumFrameAvailable;
385 while (numFramesToFlush > 0) {
386 acquireNextBufferLocked(std::nullopt);
387 numFramesToFlush--;
388 }
389}
390
chaviw69058fb2021-09-27 09:37:30 -0500391void BLASTBufferQueue::releaseBufferCallback(
392 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
393 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
chaviw57ae4b22022-02-03 16:51:39 -0600394 BBQ_TRACE();
Vishnu Nair1506b182021-02-22 14:35:15 -0800395 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700396 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800397
Ady Abraham899dcdb2021-06-15 16:56:21 -0700398 // Calculate how many buffers we need to hold before we release them back
399 // to the buffer queue. This will prevent higher latency when we are running
400 // on a lower refresh rate than the max supported. We only do that for EGL
401 // clients as others don't care about latency
402 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700403 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700404 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
405 }();
406
chaviw69058fb2021-09-27 09:37:30 -0500407 if (currentMaxAcquiredBufferCount) {
408 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
409 }
410
Ady Abraham899dcdb2021-06-15 16:56:21 -0700411 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500412 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700413 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700414
415 // Release all buffers that are beyond the ones that we need to hold
416 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500417 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700418 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500419 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwd7deef72021-10-06 11:53:40 -0500420 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
chaviwa1c4c822021-11-10 18:11:58 -0600421 // onFrameAvailable handle processing them since it will merge with the syncTransaction.
chaviwd7deef72021-10-06 11:53:40 -0500422 if (!mWaitForTransactionCallback) {
423 acquireNextBufferLocked(std::nullopt);
424 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800425 }
426
Ady Abraham899dcdb2021-06-15 16:56:21 -0700427 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700428 ATRACE_INT(mQueuedBufferTrace.c_str(),
429 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800430 mCallbackCV.notify_all();
431}
432
chaviw0acd33a2021-11-02 11:55:37 -0500433void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
434 const sp<Fence>& releaseFence) {
435 auto it = mSubmitted.find(callbackId);
436 if (it == mSubmitted.end()) {
437 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
438 callbackId.to_string().c_str());
439 return;
440 }
441 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600442 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500443 BQA_LOGV("released %s", callbackId.to_string().c_str());
444 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
445 mSubmitted.erase(it);
446}
447
chaviwd7deef72021-10-06 11:53:40 -0500448void BLASTBufferQueue::acquireNextBufferLocked(
449 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800450 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
451 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500452 const bool includeExtraAcquire = !transaction;
453 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
454 if (mNumFrameAvailable == 0 || maxAcquired) {
455 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800456 return;
457 }
458
Valerie Haua32c5522019-12-09 10:11:08 -0800459 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700460 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800461 return;
462 }
463
Robert Carr78c25dd2019-08-15 14:10:33 -0700464 SurfaceComposerClient::Transaction localTransaction;
465 bool applyTransaction = true;
466 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500467 if (transaction) {
468 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700469 applyTransaction = false;
470 }
471
Valerie Haua32c5522019-12-09 10:11:08 -0800472 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800473
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800474 status_t status =
475 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800476 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
477 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
478 return;
479 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700480 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700481 return;
482 }
chaviw57ae4b22022-02-03 16:51:39 -0600483
Valerie Haua32c5522019-12-09 10:11:08 -0800484 auto buffer = bufferItem.mGraphicBuffer;
485 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600486 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800487
488 if (buffer == nullptr) {
489 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700490 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800491 return;
492 }
493
Vishnu Nair670b3f72020-09-29 17:52:18 -0700494 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700495 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800496 "buffer{size=%dx%d transform=%d}",
497 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
498 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
499 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500500 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800501 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700502 }
503
Valerie Haua32c5522019-12-09 10:11:08 -0800504 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700505 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
506 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
507 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700508
Valerie Hau871d6352020-01-29 08:44:02 -0800509 bool needsDisconnect = false;
510 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
511
512 // if producer disconnected before, notify SurfaceFlinger
513 if (needsDisconnect) {
514 t->notifyProducerDisconnect(mSurfaceControl);
515 }
516
Robert Carr78c25dd2019-08-15 14:10:33 -0700517 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
518 incStrong((void*)transactionCallbackThunk);
519
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700520 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700521 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000522 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
523 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700524 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800525
Vishnu Nair1506b182021-02-22 14:35:15 -0800526 auto releaseBufferCallback =
527 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500528 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500529 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600530 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500531 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
532 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
533 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700534 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600535
chaviw42026162021-04-16 15:46:12 -0500536 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700537
Vishnu Naird2aaab12022-02-10 14:49:09 -0800538 if (mUpdateDestinationFrame) {
539 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
540 } else {
541 const bool ignoreDestinationFrame =
542 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
543 t->setFlags(mSurfaceControl,
544 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
545 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700546 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700547 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800548 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800549 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800550 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800551 if (!bufferItem.mIsAutoTimestamp) {
552 t->setDesiredPresentTime(bufferItem.mTimestamp);
553 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700554
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000555 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700556 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000557 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100558 }
559
Vishnu Nairadf632b2021-01-07 14:05:08 -0800560 {
561 std::unique_lock _lock{mTimestampMutex};
562 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
563 if (dequeueTime != mDequeueTimestamps.end()) {
564 Parcel p;
565 p.writeInt64(dequeueTime->second);
Huihong Luod3d8f8e2022-03-08 14:48:46 -0800566 t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p);
Vishnu Nairadf632b2021-01-07 14:05:08 -0800567 mDequeueTimestamps.erase(dequeueTime);
568 }
569 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800570
chaviw6a195272021-09-03 16:14:25 -0500571 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700572 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800573 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
574 t->setApplyToken(mApplyToken).apply(false, true);
575 mAppliedLastTransaction = true;
576 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
577 } else {
578 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
579 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700580 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700581
chaviwd7deef72021-10-06 11:53:40 -0500582 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800583 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700584 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500585 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800586 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700587 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700588 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700589}
590
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800591Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
592 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800593 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800594 }
595 return item.mCrop;
596}
597
chaviwd7deef72021-10-06 11:53:40 -0500598void BLASTBufferQueue::acquireAndReleaseBuffer() {
599 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500600 status_t status =
601 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
602 if (status != OK) {
603 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
604 statusToString(status).c_str());
605 return;
606 }
chaviwd7deef72021-10-06 11:53:40 -0500607 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500608 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500609}
610
chaviw0acd33a2021-11-02 11:55:37 -0500611void BLASTBufferQueue::flushAndWaitForFreeBuffer(std::unique_lock<std::mutex>& lock) {
612 if (mWaitForTransactionCallback && mNumFrameAvailable > 0) {
613 // We are waiting on a previous sync's transaction callback so allow another sync
614 // transaction to proceed.
615 //
616 // We need to first flush out the transactions that were in between the two syncs.
617 // We do this by merging them into mSyncTransaction so any buffer merging will get
618 // a release callback invoked. The release callback will be async so we need to wait
619 // on max acquired to make sure we have the capacity to acquire another buffer.
620 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
621 BQA_LOGD("waiting to flush shadow queue...");
622 mCallbackCV.wait(lock);
623 }
624 while (mNumFrameAvailable > 0) {
625 // flush out the shadow queue
626 acquireAndReleaseBuffer();
627 }
628 }
629
630 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
631 BQA_LOGD("waiting for free buffer.");
632 mCallbackCV.wait(lock);
633 }
634}
635
Vishnu Nairaef1de92020-10-22 12:15:53 -0700636void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000637 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
638 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
639 {
640 BBQ_TRACE();
641 std::unique_lock _lock{mMutex};
642 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
643 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800644
Tianhao Yao4861b102022-02-03 20:18:35 +0000645 if (syncTransactionSet) {
646 bool mayNeedToWaitForBuffer = true;
647 // If we are going to re-use the same mSyncTransaction, release the buffer that may
648 // already be set in the Transaction. This is to allow us a free slot early to continue
649 // processing a new buffer.
650 if (!mAcquireSingleBuffer) {
651 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
652 if (bufferData) {
653 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
654 bufferData->frameNumber);
655 releaseBuffer(bufferData->generateReleaseCallbackId(),
656 bufferData->acquireFence);
657 // Because we just released a buffer, we know there's no need to wait for a free
658 // buffer.
659 mayNeedToWaitForBuffer = false;
660 }
661 }
chaviw0acd33a2021-11-02 11:55:37 -0500662
Tianhao Yao4861b102022-02-03 20:18:35 +0000663 if (mayNeedToWaitForBuffer) {
664 flushAndWaitForFreeBuffer(_lock);
chaviwd7deef72021-10-06 11:53:40 -0500665 }
666 }
667
Tianhao Yao4861b102022-02-03 20:18:35 +0000668 // add to shadow queue
669 mNumFrameAvailable++;
670 if (mWaitForTransactionCallback && mNumFrameAvailable >= 2) {
671 acquireAndReleaseBuffer();
672 }
673 ATRACE_INT(mQueuedBufferTrace.c_str(),
674 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
675
676 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
677 item.mFrameNumber, boolToString(syncTransactionSet));
678
679 if (syncTransactionSet) {
680 acquireNextBufferLocked(mSyncTransaction);
681
682 // Only need a commit callback when syncing to ensure the buffer that's synced has been
683 // sent to SF
684 incStrong((void*)transactionCommittedCallbackThunk);
685 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
686 static_cast<void*>(this));
687 mWaitForTransactionCallback = true;
688 if (mAcquireSingleBuffer) {
689 prevCallback = mTransactionReadyCallback;
690 prevTransaction = mSyncTransaction;
691 mTransactionReadyCallback = nullptr;
692 mSyncTransaction = nullptr;
693 }
694 } else if (!mWaitForTransactionCallback) {
695 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800696 }
697 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000698 if (prevCallback) {
699 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500700 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800701}
702
Vishnu Nairaef1de92020-10-22 12:15:53 -0700703void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
704 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
705 // Do nothing since we are not storing unacquired buffer items locally.
706}
707
Vishnu Nairadf632b2021-01-07 14:05:08 -0800708void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
709 std::unique_lock _lock{mTimestampMutex};
710 mDequeueTimestamps[bufferId] = systemTime();
711};
712
713void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
714 std::unique_lock _lock{mTimestampMutex};
715 mDequeueTimestamps.erase(bufferId);
716};
717
Tianhao Yao4861b102022-02-03 20:18:35 +0000718void BLASTBufferQueue::syncNextTransaction(
719 std::function<void(SurfaceComposerClient::Transaction*)> callback,
720 bool acquireSingleBuffer) {
chaviw57ae4b22022-02-03 16:51:39 -0600721 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500722
723 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
724 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
725
726 {
727 std::lock_guard _lock{mMutex};
728 // We're about to overwrite the previous call so we should invoke that callback
729 // immediately.
730 if (mTransactionReadyCallback) {
731 prevCallback = mTransactionReadyCallback;
732 prevTransaction = mSyncTransaction;
733 }
734
735 mTransactionReadyCallback = callback;
736 if (callback) {
737 mSyncTransaction = new SurfaceComposerClient::Transaction();
738 } else {
739 mSyncTransaction = nullptr;
740 }
741 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000742 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500743
744 if (prevCallback) {
745 prevCallback(prevTransaction);
746 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000747}
748
749void BLASTBufferQueue::stopContinuousSyncTransaction() {
750 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
751 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
752 {
753 std::lock_guard _lock{mMutex};
754 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
755 if (invokeCallback) {
756 prevCallback = mTransactionReadyCallback;
757 prevTransaction = mSyncTransaction;
758 }
759 mTransactionReadyCallback = nullptr;
760 mSyncTransaction = nullptr;
761 mAcquireSingleBuffer = true;
762 }
763 if (prevCallback) {
764 prevCallback(prevTransaction);
765 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700766}
767
Vishnu Nairea0de002020-11-17 17:42:37 -0800768bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700769 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
770 // Only reject buffers if scaling mode is freeze.
771 return false;
772 }
773
Vishnu Naire1a42322020-10-02 17:42:04 -0700774 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
775 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
776
777 // Take the buffer's orientation into account
778 if (item.mTransform & ui::Transform::ROT_90) {
779 std::swap(bufWidth, bufHeight);
780 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800781 ui::Size bufferSize(bufWidth, bufHeight);
782 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800783 return false;
784 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700785
Vishnu Nair670b3f72020-09-29 17:52:18 -0700786 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800787 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700788}
Vishnu Nairbf255772020-10-16 10:54:41 -0700789
790// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800791// Consumer can acquire an additional buffer if that buffer is not droppable. Set
792// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
793// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
794bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700795 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800796 return mNumAcquired >= maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700797}
798
Robert Carr05086b22020-10-13 18:22:51 -0700799class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700800private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700801 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700802 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700803 bool mDestroyed = false;
804
Robert Carr05086b22020-10-13 18:22:51 -0700805public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700806 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
807 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
808 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700809
Robert Carr05086b22020-10-13 18:22:51 -0700810 void allocateBuffers() override {
811 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
812 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
813 auto gbp = getIGraphicBufferProducer();
814 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
815 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
816 gbp->allocateBuffers(reqWidth, reqHeight,
817 reqFormat, reqUsage);
818
819 }).detach();
820 }
Robert Carr9c006e02020-10-14 13:41:57 -0700821
Marin Shalamanovc5986772021-03-16 16:09:49 +0100822 status_t setFrameRate(float frameRate, int8_t compatibility,
823 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700824 std::unique_lock _lock{mMutex};
825 if (mDestroyed) {
826 return DEAD_OBJECT;
827 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100828 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
829 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700830 return BAD_VALUE;
831 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100832 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700833 }
Robert Carr9b611b72020-10-19 12:00:23 -0700834
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000835 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700836 std::unique_lock _lock{mMutex};
837 if (mDestroyed) {
838 return DEAD_OBJECT;
839 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000840 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700841 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700842
843 void destroy() override {
844 Surface::destroy();
845
846 std::unique_lock _lock{mMutex};
847 mDestroyed = true;
848 mBbq = nullptr;
849 }
Robert Carr05086b22020-10-13 18:22:51 -0700850};
851
Robert Carr9c006e02020-10-14 13:41:57 -0700852// TODO: Can we coalesce this with frame updates? Need to confirm
853// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200854status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
855 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700856 std::unique_lock _lock{mMutex};
857 SurfaceComposerClient::Transaction t;
858
Marin Shalamanov46084422020-10-13 12:33:42 +0200859 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700860}
861
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000862status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700863 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000864 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100865 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700866}
867
Hongguang Chen621ec582021-02-16 15:42:35 -0800868void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
869 std::unique_lock _lock{mMutex};
870 SurfaceComposerClient::Transaction t;
871
872 t.setSidebandStream(mSurfaceControl, stream).apply();
873}
874
Vishnu Nair992496b2020-10-22 17:27:21 -0700875sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
876 std::unique_lock _lock{mMutex};
877 sp<IBinder> scHandle = nullptr;
878 if (includeSurfaceControlHandle && mSurfaceControl) {
879 scHandle = mSurfaceControl->getHandle();
880 }
881 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700882}
883
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800884void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
885 uint64_t frameNumber) {
886 std::lock_guard _lock{mMutex};
887 if (mLastAcquiredFrameNumber >= frameNumber) {
888 // Apply the transaction since we have already acquired the desired frame.
889 t->apply();
890 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500891 mPendingTransactions.emplace_back(frameNumber, *t);
892 // Clear the transaction so it can't be applied elsewhere.
893 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800894 }
895}
896
chaviw6a195272021-09-03 16:14:25 -0500897void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
898 std::lock_guard _lock{mMutex};
899
900 SurfaceComposerClient::Transaction t;
901 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800902 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
903 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500904}
905
906void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
907 uint64_t frameNumber) {
908 auto mergeTransaction =
909 [&t, currentFrameNumber = frameNumber](
910 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
911 auto& [targetFrameNumber, transaction] = pendingTransaction;
912 if (currentFrameNumber < targetFrameNumber) {
913 return false;
914 }
915 t->merge(std::move(transaction));
916 return true;
917 };
918
919 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
920 mPendingTransactions.end(), mergeTransaction),
921 mPendingTransactions.end());
922}
923
chaviwd84085a2022-02-08 11:07:04 -0600924SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
925 uint64_t frameNumber) {
926 std::lock_guard _lock{mMutex};
927 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
928 mergePendingTransactions(t, frameNumber);
929 return t;
930}
931
Vishnu Nair89496122020-12-14 17:14:53 -0800932// Maintains a single worker thread per process that services a list of runnables.
933class AsyncWorker : public Singleton<AsyncWorker> {
934private:
935 std::thread mThread;
936 bool mDone = false;
937 std::deque<std::function<void()>> mRunnables;
938 std::mutex mMutex;
939 std::condition_variable mCv;
940 void run() {
941 std::unique_lock<std::mutex> lock(mMutex);
942 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800943 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700944 std::deque<std::function<void()>> runnables = std::move(mRunnables);
945 mRunnables.clear();
946 lock.unlock();
947 // Run outside the lock since the runnable might trigger another
948 // post to the async worker.
949 execute(runnables);
950 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800951 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700952 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800953 }
954 }
955
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700956 void execute(std::deque<std::function<void()>>& runnables) {
957 while (!runnables.empty()) {
958 std::function<void()> runnable = runnables.front();
959 runnables.pop_front();
960 runnable();
961 }
962 }
963
Vishnu Nair89496122020-12-14 17:14:53 -0800964public:
965 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
966
967 ~AsyncWorker() {
968 mDone = true;
969 mCv.notify_all();
970 if (mThread.joinable()) {
971 mThread.join();
972 }
973 }
974
975 void post(std::function<void()> runnable) {
976 std::unique_lock<std::mutex> lock(mMutex);
977 mRunnables.emplace_back(std::move(runnable));
978 mCv.notify_one();
979 }
980};
981ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
982
983// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
984class AsyncProducerListener : public BnProducerListener {
985private:
986 const sp<IProducerListener> mListener;
987
988public:
989 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
990
991 void onBufferReleased() override {
992 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
993 }
994
995 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
996 AsyncWorker::getInstance().post(
997 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
998 }
999};
1000
1001// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1002// can be non-blocking when the producer is in the client process.
1003class BBQBufferQueueProducer : public BufferQueueProducer {
1004public:
1005 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
1006 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
1007
1008 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1009 QueueBufferOutput* output) override {
1010 if (!listener) {
1011 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1012 }
1013
1014 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1015 producerControlledByApp, output);
1016 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001017
1018 int query(int what, int* value) override {
1019 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1020 *value = 1;
1021 return NO_ERROR;
1022 }
1023 return BufferQueueProducer::query(what, value);
1024 }
Vishnu Nair89496122020-12-14 17:14:53 -08001025};
1026
1027// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1028// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1029// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1030// we can deadlock.
1031void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1032 sp<IGraphicBufferConsumer>* outConsumer) {
1033 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1034 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1035
1036 sp<BufferQueueCore> core(new BufferQueueCore());
1037 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1038
1039 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1040 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1041 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1042
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001043 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1044 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001045 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1046 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1047
1048 *outProducer = producer;
1049 *outConsumer = consumer;
1050}
1051
chaviw497e81c2021-02-04 17:09:47 -08001052PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1053 PixelFormat convertedFormat = format;
1054 switch (format) {
1055 case PIXEL_FORMAT_TRANSPARENT:
1056 case PIXEL_FORMAT_TRANSLUCENT:
1057 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1058 break;
1059 case PIXEL_FORMAT_OPAQUE:
1060 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1061 break;
1062 }
1063 return convertedFormat;
1064}
1065
Robert Carr82d07c92021-05-10 11:36:43 -07001066uint32_t BLASTBufferQueue::getLastTransformHint() const {
1067 if (mSurfaceControl != nullptr) {
1068 return mSurfaceControl->getTransformHint();
1069 } else {
1070 return 0;
1071 }
1072}
1073
chaviw0b020f82021-08-20 12:00:47 -05001074uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
1075 std::unique_lock _lock{mMutex};
1076 return mLastAcquiredFrameNumber;
1077}
1078
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001079void BLASTBufferQueue::abandon() {
1080 std::unique_lock _lock{mMutex};
1081 // flush out the shadow queue
1082 while (mNumFrameAvailable > 0) {
1083 acquireAndReleaseBuffer();
1084 }
1085
1086 // Clear submitted buffer states
1087 mNumAcquired = 0;
1088 mSubmitted.clear();
1089 mPendingRelease.clear();
1090
1091 if (!mPendingTransactions.empty()) {
1092 BQA_LOGD("Applying pending transactions on abandon %d",
1093 static_cast<uint32_t>(mPendingTransactions.size()));
1094 SurfaceComposerClient::Transaction t;
1095 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -08001096 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1097 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001098 }
1099
1100 // Clear sync states
1101 if (mWaitForTransactionCallback) {
1102 BQA_LOGD("mWaitForTransactionCallback cleared");
1103 mWaitForTransactionCallback = false;
1104 }
1105
1106 if (mSyncTransaction != nullptr) {
1107 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1108 mAcquireSingleBuffer ? "true" : "false");
1109 mSyncTransaction = nullptr;
1110 mAcquireSingleBuffer = false;
1111 }
1112
1113 // abandon buffer queue
1114 if (mBufferItemConsumer != nullptr) {
1115 mBufferItemConsumer->abandon();
1116 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1117 mBufferItemConsumer->setBufferFreedListener(nullptr);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001118 }
1119 mBufferItemConsumer = nullptr;
1120 mConsumer = nullptr;
1121 mProducer = nullptr;
1122}
1123
1124bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1125 std::unique_lock _lock{mMutex};
1126 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1127}
1128
Robert Carr4c1b6462021-12-21 10:30:50 -08001129void BLASTBufferQueue::setTransactionHangCallback(std::function<void(bool)> callback) {
1130 std::unique_lock _lock{mMutex};
1131 mTransactionHangCallback = callback;
1132}
1133
Robert Carr78c25dd2019-08-15 14:10:33 -07001134} // namespace android