blob: dbccf30faeaf0b444c9b8de9f298ea5357737206 [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>
36
Robert Carr78c25dd2019-08-15 14:10:33 -070037#include <chrono>
38
39using namespace std::chrono_literals;
40
Vishnu Nairdab94092020-09-29 16:09:04 -070041namespace {
chaviw3277faf2021-05-19 16:45:23 -050042inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070043 return b ? "true" : "false";
44}
45} // namespace
46
Robert Carr78c25dd2019-08-15 14:10:33 -070047namespace android {
48
Vishnu Nairdab94092020-09-29 16:09:04 -070049// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050050#define BQA_LOGD(x, ...) \
51 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070052#define BQA_LOGV(x, ...) \
53 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080054// enable logs for a single layer
55//#define BQA_LOGV(x, ...) \
56// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
57// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070058#define BQA_LOGE(x, ...) \
59 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
60
chaviw57ae4b22022-02-03 16:51:39 -060061#define BBQ_TRACE(x, ...) \
62 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
63 mNumAcquired, ##__VA_ARGS__)
64
Valerie Hau871d6352020-01-29 08:44:02 -080065void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000066 Mutex::Autolock lock(mMutex);
67 mPreviouslyConnected = mCurrentlyConnected;
68 mCurrentlyConnected = false;
69 if (mPreviouslyConnected) {
70 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080071 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000072 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080073}
74
75void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
76 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080077 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080078 if (newTimestamps) {
79 // BufferQueueProducer only adds a new timestamp on
80 // queueBuffer
81 mCurrentFrameNumber = newTimestamps->frameNumber;
82 mFrameEventHistory.addQueue(*newTimestamps);
83 }
84 if (outDelta) {
85 // frame event histories will be processed
86 // only after the producer connects and requests
87 // deltas for the first time. Forward this intent
88 // to SF-side to turn event processing back on
89 mPreviouslyConnected = mCurrentlyConnected;
90 mCurrentlyConnected = true;
91 mFrameEventHistory.getAndResetDelta(outDelta);
92 }
93}
94
95void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
96 const sp<Fence>& glDoneFence,
97 const sp<Fence>& presentFence,
98 const sp<Fence>& prevReleaseFence,
99 CompositorTiming compositorTiming,
100 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800101 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800102
103 // if the producer is not connected, don't bother updating,
104 // the next producer that connects won't access this frame event
105 if (!mCurrentlyConnected) return;
106 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
107 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
108 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
109
110 mFrameEventHistory.addLatch(frameNumber, latchTime);
111 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
112 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
113 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
114 compositorTiming);
115}
116
117void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
118 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800119 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800120 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
121 disconnect = true;
122 mDisconnectEvents.pop();
123 }
124 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
125}
126
Hongguang Chen621ec582021-02-16 15:42:35 -0800127void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800128 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
129 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800130 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800131 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800132 }
133}
134
Vishnu Naird2aaab12022-02-10 14:49:09 -0800135BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800136 : 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),
Tianhao Yao4861b102022-02-03 20:18:35 +0000140 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800141 mSyncTransaction(nullptr),
142 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800143 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800144 // since the adapter is in the client process, set dequeue timeout
145 // explicitly so that dequeueBuffer will block
146 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800147
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700148 // safe default, most producers are expected to override this
149 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800150 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
151 GraphicBuffer::USAGE_HW_COMPOSER |
152 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800153 1, false, this);
Valerie Haua32c5522019-12-09 10:11:08 -0800154 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700155 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700156 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700157 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800158 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700159 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700160 mBufferItemConsumer->setFrameAvailableListener(this);
161 mBufferItemConsumer->setBufferFreedListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700162
Ady Abraham899dcdb2021-06-15 16:56:21 -0700163 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700164 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500165 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800166 mNumAcquired = 0;
167 mNumFrameAvailable = 0;
Robert Carr4c1b6462021-12-21 10:30:50 -0800168
169 TransactionCompletedListener::getInstance()->addQueueStallListener(
170 [&]() {
171 std::function<void(bool)> callbackCopy;
172 {
173 std::unique_lock _lock{mMutex};
174 callbackCopy = mTransactionHangCallback;
175 }
176 if (callbackCopy) callbackCopy(true);
177 }, this);
178
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800179 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800180}
181
182BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
183 int width, int height, int32_t format)
184 : BLASTBufferQueue(name) {
185 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700186}
187
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800188BLASTBufferQueue::~BLASTBufferQueue() {
Robert Carr4c1b6462021-12-21 10:30:50 -0800189 TransactionCompletedListener::getInstance()->removeQueueStallListener(this);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800190 if (mPendingTransactions.empty()) {
191 return;
192 }
193 BQA_LOGE("Applying pending transactions on dtor %d",
194 static_cast<uint32_t>(mPendingTransactions.size()));
195 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800196 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800197 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
198 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500199
200 if (mTransactionReadyCallback) {
201 mTransactionReadyCallback(mSyncTransaction);
202 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800203}
204
chaviw565ee542021-01-14 10:21:23 -0800205void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800206 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800207 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
208
Robert Carr78c25dd2019-08-15 14:10:33 -0700209 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800210 if (mFormat != format) {
211 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800212 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800213 }
214
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800215 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000216 if (surfaceControlChanged && mSurfaceControl != nullptr) {
217 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
218 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800219 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800220
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700221 // Always update the native object even though they might have the same layer handle, so we can
222 // get the updated transform hint from WM.
223 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800224 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800225 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800226 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
227 layer_state_t::eEnableBackpressure);
228 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800229 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800230 mTransformHint = mSurfaceControl->getTransformHint();
231 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700232 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
233 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800234
Vishnu Nairea0de002020-11-17 17:42:37 -0800235 ui::Size newSize(width, height);
236 if (mRequestedSize != newSize) {
237 mRequestedSize.set(newSize);
238 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000239 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800240 // If the buffer supports scaling, update the frame immediately since the client may
241 // want to scale the existing buffer to the new size.
242 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800243 if (mUpdateDestinationFrame) {
244 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
245 applyTransaction = true;
246 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800247 }
Robert Carrfc416512020-04-02 12:32:44 -0700248 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800249 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800250 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
251 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800252 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700253}
254
chaviwd7deef72021-10-06 11:53:40 -0500255static std::optional<SurfaceControlStats> findMatchingStat(
256 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
257 for (auto stat : stats) {
258 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
259 return stat;
260 }
261 }
262 return std::nullopt;
263}
264
265static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
266 const sp<Fence>& presentFence,
267 const std::vector<SurfaceControlStats>& stats) {
268 if (context == nullptr) {
269 return;
270 }
271 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
272 bq->transactionCommittedCallback(latchTime, presentFence, stats);
273}
274
275void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
276 const sp<Fence>& /*presentFence*/,
277 const std::vector<SurfaceControlStats>& stats) {
278 {
279 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600280 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500281 BQA_LOGV("transactionCommittedCallback");
282 if (!mSurfaceControlsWithPendingCallback.empty()) {
283 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
284 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
285 if (stat) {
286 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
287
288 // We need to check if we were waiting for a transaction callback in order to
289 // process any pending buffers and unblock. It's possible to get transaction
290 // callbacks for previous requests so we need to ensure the frame from this
291 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
292 // will stop processing buffers when mWaitForTransactionCallback is set, we know
293 // that mLastAcquiredFrameNumber is the frame we're waiting on.
294 // We also want to check if mNextTransaction is null because it's possible another
295 // sync request came in while waiting, but it hasn't started processing yet. In that
296 // case, we don't actually want to flush the frames in between since they will get
297 // processed and merged with the sync transaction and released earlier than if they
298 // were sent to SF
chaviwa1c4c822021-11-10 18:11:58 -0600299 if (mWaitForTransactionCallback && mSyncTransaction == nullptr &&
chaviwd7deef72021-10-06 11:53:40 -0500300 currFrameNumber >= mLastAcquiredFrameNumber) {
301 mWaitForTransactionCallback = false;
302 flushShadowQueue();
303 }
304 } else {
chaviw768bfa02021-11-01 09:50:57 -0500305 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500306 }
307 } else {
308 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
309 "empty.");
310 }
311
312 decStrong((void*)transactionCommittedCallbackThunk);
313 }
314}
315
Robert Carr78c25dd2019-08-15 14:10:33 -0700316static void transactionCallbackThunk(void* context, nsecs_t latchTime,
317 const sp<Fence>& presentFence,
318 const std::vector<SurfaceControlStats>& stats) {
319 if (context == nullptr) {
320 return;
321 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800322 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700323 bq->transactionCallback(latchTime, presentFence, stats);
324}
325
326void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
327 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700328 {
329 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600330 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700331 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700332
chaviw42026162021-04-16 15:46:12 -0500333 if (!mSurfaceControlsWithPendingCallback.empty()) {
334 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
335 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500336 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
337 if (statsOptional) {
338 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500339 mTransformHint = stat.transformHint;
340 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700341 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700342 // Update frametime stamps if the frame was latched and presented, indicated by a
343 // valid latch time.
344 if (stat.latchTime > 0) {
345 mBufferItemConsumer
346 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
347 stat.frameEventStats.refreshStartTime,
348 stat.frameEventStats.gpuCompositionDoneFence,
349 stat.presentFence, stat.previousReleaseFence,
350 stat.frameEventStats.compositorTiming,
351 stat.latchTime,
352 stat.frameEventStats.dequeueReadyTime);
353 }
chaviwd7deef72021-10-06 11:53:40 -0500354 } else {
chaviw768bfa02021-11-01 09:50:57 -0500355 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500356 }
357 } else {
358 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
359 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800360 }
chaviw71c2cc42020-10-23 16:42:02 -0700361
chaviw71c2cc42020-10-23 16:42:02 -0700362 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700363 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700364}
365
Vishnu Nair1506b182021-02-22 14:35:15 -0800366// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
367// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
368// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
369// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700370static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500371 const sp<Fence>& releaseFence,
372 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800373 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800374 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500375 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700376 } else {
377 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800378 }
379}
380
chaviwd7deef72021-10-06 11:53:40 -0500381void BLASTBufferQueue::flushShadowQueue() {
382 BQA_LOGV("flushShadowQueue");
383 int numFramesToFlush = mNumFrameAvailable;
384 while (numFramesToFlush > 0) {
385 acquireNextBufferLocked(std::nullopt);
386 numFramesToFlush--;
387 }
388}
389
chaviw69058fb2021-09-27 09:37:30 -0500390void BLASTBufferQueue::releaseBufferCallback(
391 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
392 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
chaviw57ae4b22022-02-03 16:51:39 -0600393 BBQ_TRACE();
Vishnu Nair1506b182021-02-22 14:35:15 -0800394 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700395 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800396
Ady Abraham899dcdb2021-06-15 16:56:21 -0700397 // Calculate how many buffers we need to hold before we release them back
398 // to the buffer queue. This will prevent higher latency when we are running
399 // on a lower refresh rate than the max supported. We only do that for EGL
400 // clients as others don't care about latency
401 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700402 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700403 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
404 }();
405
chaviw69058fb2021-09-27 09:37:30 -0500406 if (currentMaxAcquiredBufferCount) {
407 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
408 }
409
Ady Abraham899dcdb2021-06-15 16:56:21 -0700410 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500411 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700412 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700413
414 // Release all buffers that are beyond the ones that we need to hold
415 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500416 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700417 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500418 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwd7deef72021-10-06 11:53:40 -0500419 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
chaviwa1c4c822021-11-10 18:11:58 -0600420 // onFrameAvailable handle processing them since it will merge with the syncTransaction.
chaviwd7deef72021-10-06 11:53:40 -0500421 if (!mWaitForTransactionCallback) {
422 acquireNextBufferLocked(std::nullopt);
423 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800424 }
425
Ady Abraham899dcdb2021-06-15 16:56:21 -0700426 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700427 ATRACE_INT(mQueuedBufferTrace.c_str(),
428 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800429 mCallbackCV.notify_all();
430}
431
chaviw0acd33a2021-11-02 11:55:37 -0500432void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
433 const sp<Fence>& releaseFence) {
434 auto it = mSubmitted.find(callbackId);
435 if (it == mSubmitted.end()) {
436 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
437 callbackId.to_string().c_str());
438 return;
439 }
440 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600441 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500442 BQA_LOGV("released %s", callbackId.to_string().c_str());
443 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
444 mSubmitted.erase(it);
445}
446
chaviwd7deef72021-10-06 11:53:40 -0500447void BLASTBufferQueue::acquireNextBufferLocked(
448 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800449 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
450 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500451 const bool includeExtraAcquire = !transaction;
452 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
453 if (mNumFrameAvailable == 0 || maxAcquired) {
454 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800455 return;
456 }
457
Valerie Haua32c5522019-12-09 10:11:08 -0800458 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700459 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800460 return;
461 }
462
Robert Carr78c25dd2019-08-15 14:10:33 -0700463 SurfaceComposerClient::Transaction localTransaction;
464 bool applyTransaction = true;
465 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500466 if (transaction) {
467 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700468 applyTransaction = false;
469 }
470
Valerie Haua32c5522019-12-09 10:11:08 -0800471 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800472
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800473 status_t status =
474 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800475 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
476 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
477 return;
478 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700479 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700480 return;
481 }
chaviw57ae4b22022-02-03 16:51:39 -0600482
Valerie Haua32c5522019-12-09 10:11:08 -0800483 auto buffer = bufferItem.mGraphicBuffer;
484 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600485 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800486
487 if (buffer == nullptr) {
488 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700489 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800490 return;
491 }
492
Vishnu Nair670b3f72020-09-29 17:52:18 -0700493 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700494 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800495 "buffer{size=%dx%d transform=%d}",
496 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
497 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
498 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500499 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800500 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700501 }
502
Valerie Haua32c5522019-12-09 10:11:08 -0800503 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700504 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
505 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
506 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700507
Valerie Hau871d6352020-01-29 08:44:02 -0800508 bool needsDisconnect = false;
509 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
510
511 // if producer disconnected before, notify SurfaceFlinger
512 if (needsDisconnect) {
513 t->notifyProducerDisconnect(mSurfaceControl);
514 }
515
Robert Carr78c25dd2019-08-15 14:10:33 -0700516 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
517 incStrong((void*)transactionCallbackThunk);
518
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700519 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700520 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000521 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
522 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700523 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800524
Vishnu Nair1506b182021-02-22 14:35:15 -0800525 auto releaseBufferCallback =
526 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500527 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500528 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600529 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500530 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
531 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
532 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700533 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600534
chaviw42026162021-04-16 15:46:12 -0500535 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700536
Vishnu Naird2aaab12022-02-10 14:49:09 -0800537 if (mUpdateDestinationFrame) {
538 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
539 } else {
540 const bool ignoreDestinationFrame =
541 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
542 t->setFlags(mSurfaceControl,
543 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
544 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700545 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700546 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800547 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800548 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800549 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800550 if (!bufferItem.mIsAutoTimestamp) {
551 t->setDesiredPresentTime(bufferItem.mTimestamp);
552 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700553
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000554 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700555 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000556 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100557 }
558
Vishnu Nairadf632b2021-01-07 14:05:08 -0800559 {
560 std::unique_lock _lock{mTimestampMutex};
561 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
562 if (dequeueTime != mDequeueTimestamps.end()) {
563 Parcel p;
564 p.writeInt64(dequeueTime->second);
565 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
566 mDequeueTimestamps.erase(dequeueTime);
567 }
568 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800569
chaviw6a195272021-09-03 16:14:25 -0500570 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700571 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800572 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
573 t->setApplyToken(mApplyToken).apply(false, true);
574 mAppliedLastTransaction = true;
575 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
576 } else {
577 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
578 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700579 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700580
chaviwd7deef72021-10-06 11:53:40 -0500581 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800582 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700583 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500584 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800585 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700586 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700587 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700588}
589
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800590Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
591 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800592 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800593 }
594 return item.mCrop;
595}
596
chaviwd7deef72021-10-06 11:53:40 -0500597void BLASTBufferQueue::acquireAndReleaseBuffer() {
598 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500599 status_t status =
600 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
601 if (status != OK) {
602 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
603 statusToString(status).c_str());
604 return;
605 }
chaviwd7deef72021-10-06 11:53:40 -0500606 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500607 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500608}
609
chaviw0acd33a2021-11-02 11:55:37 -0500610void BLASTBufferQueue::flushAndWaitForFreeBuffer(std::unique_lock<std::mutex>& lock) {
611 if (mWaitForTransactionCallback && mNumFrameAvailable > 0) {
612 // We are waiting on a previous sync's transaction callback so allow another sync
613 // transaction to proceed.
614 //
615 // We need to first flush out the transactions that were in between the two syncs.
616 // We do this by merging them into mSyncTransaction so any buffer merging will get
617 // a release callback invoked. The release callback will be async so we need to wait
618 // on max acquired to make sure we have the capacity to acquire another buffer.
619 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
620 BQA_LOGD("waiting to flush shadow queue...");
621 mCallbackCV.wait(lock);
622 }
623 while (mNumFrameAvailable > 0) {
624 // flush out the shadow queue
625 acquireAndReleaseBuffer();
626 }
627 }
628
629 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
630 BQA_LOGD("waiting for free buffer.");
631 mCallbackCV.wait(lock);
632 }
633}
634
Vishnu Nairaef1de92020-10-22 12:15:53 -0700635void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000636 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
637 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
638 {
639 BBQ_TRACE();
640 std::unique_lock _lock{mMutex};
641 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
642 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800643
Tianhao Yao4861b102022-02-03 20:18:35 +0000644 if (syncTransactionSet) {
645 bool mayNeedToWaitForBuffer = true;
646 // If we are going to re-use the same mSyncTransaction, release the buffer that may
647 // already be set in the Transaction. This is to allow us a free slot early to continue
648 // processing a new buffer.
649 if (!mAcquireSingleBuffer) {
650 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
651 if (bufferData) {
652 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
653 bufferData->frameNumber);
654 releaseBuffer(bufferData->generateReleaseCallbackId(),
655 bufferData->acquireFence);
656 // Because we just released a buffer, we know there's no need to wait for a free
657 // buffer.
658 mayNeedToWaitForBuffer = false;
659 }
660 }
chaviw0acd33a2021-11-02 11:55:37 -0500661
Tianhao Yao4861b102022-02-03 20:18:35 +0000662 if (mayNeedToWaitForBuffer) {
663 flushAndWaitForFreeBuffer(_lock);
chaviwd7deef72021-10-06 11:53:40 -0500664 }
665 }
666
Tianhao Yao4861b102022-02-03 20:18:35 +0000667 // add to shadow queue
668 mNumFrameAvailable++;
669 if (mWaitForTransactionCallback && mNumFrameAvailable >= 2) {
670 acquireAndReleaseBuffer();
671 }
672 ATRACE_INT(mQueuedBufferTrace.c_str(),
673 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
674
675 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
676 item.mFrameNumber, boolToString(syncTransactionSet));
677
678 if (syncTransactionSet) {
679 acquireNextBufferLocked(mSyncTransaction);
680
681 // Only need a commit callback when syncing to ensure the buffer that's synced has been
682 // sent to SF
683 incStrong((void*)transactionCommittedCallbackThunk);
684 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
685 static_cast<void*>(this));
686 mWaitForTransactionCallback = true;
687 if (mAcquireSingleBuffer) {
688 prevCallback = mTransactionReadyCallback;
689 prevTransaction = mSyncTransaction;
690 mTransactionReadyCallback = nullptr;
691 mSyncTransaction = nullptr;
692 }
693 } else if (!mWaitForTransactionCallback) {
694 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800695 }
696 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000697 if (prevCallback) {
698 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500699 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800700}
701
Vishnu Nairaef1de92020-10-22 12:15:53 -0700702void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
703 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
704 // Do nothing since we are not storing unacquired buffer items locally.
705}
706
Vishnu Nairadf632b2021-01-07 14:05:08 -0800707void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
708 std::unique_lock _lock{mTimestampMutex};
709 mDequeueTimestamps[bufferId] = systemTime();
710};
711
712void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
713 std::unique_lock _lock{mTimestampMutex};
714 mDequeueTimestamps.erase(bufferId);
715};
716
Tianhao Yao4861b102022-02-03 20:18:35 +0000717void BLASTBufferQueue::syncNextTransaction(
718 std::function<void(SurfaceComposerClient::Transaction*)> callback,
719 bool acquireSingleBuffer) {
chaviw57ae4b22022-02-03 16:51:39 -0600720 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500721
722 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
723 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
724
725 {
726 std::lock_guard _lock{mMutex};
727 // We're about to overwrite the previous call so we should invoke that callback
728 // immediately.
729 if (mTransactionReadyCallback) {
730 prevCallback = mTransactionReadyCallback;
731 prevTransaction = mSyncTransaction;
732 }
733
734 mTransactionReadyCallback = callback;
735 if (callback) {
736 mSyncTransaction = new SurfaceComposerClient::Transaction();
737 } else {
738 mSyncTransaction = nullptr;
739 }
740 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000741 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500742
743 if (prevCallback) {
744 prevCallback(prevTransaction);
745 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000746}
747
748void BLASTBufferQueue::stopContinuousSyncTransaction() {
749 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
750 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
751 {
752 std::lock_guard _lock{mMutex};
753 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
754 if (invokeCallback) {
755 prevCallback = mTransactionReadyCallback;
756 prevTransaction = mSyncTransaction;
757 }
758 mTransactionReadyCallback = nullptr;
759 mSyncTransaction = nullptr;
760 mAcquireSingleBuffer = true;
761 }
762 if (prevCallback) {
763 prevCallback(prevTransaction);
764 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700765}
766
Vishnu Nairea0de002020-11-17 17:42:37 -0800767bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700768 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
769 // Only reject buffers if scaling mode is freeze.
770 return false;
771 }
772
Vishnu Naire1a42322020-10-02 17:42:04 -0700773 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
774 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
775
776 // Take the buffer's orientation into account
777 if (item.mTransform & ui::Transform::ROT_90) {
778 std::swap(bufWidth, bufHeight);
779 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800780 ui::Size bufferSize(bufWidth, bufHeight);
781 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800782 return false;
783 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700784
Vishnu Nair670b3f72020-09-29 17:52:18 -0700785 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800786 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700787}
Vishnu Nairbf255772020-10-16 10:54:41 -0700788
789// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800790// Consumer can acquire an additional buffer if that buffer is not droppable. Set
791// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
792// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
793bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700794 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800795 return mNumAcquired >= maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700796}
797
Robert Carr05086b22020-10-13 18:22:51 -0700798class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700799private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700800 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700801 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700802 bool mDestroyed = false;
803
Robert Carr05086b22020-10-13 18:22:51 -0700804public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700805 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
806 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
807 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700808
Robert Carr05086b22020-10-13 18:22:51 -0700809 void allocateBuffers() override {
810 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
811 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
812 auto gbp = getIGraphicBufferProducer();
813 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
814 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
815 gbp->allocateBuffers(reqWidth, reqHeight,
816 reqFormat, reqUsage);
817
818 }).detach();
819 }
Robert Carr9c006e02020-10-14 13:41:57 -0700820
Marin Shalamanovc5986772021-03-16 16:09:49 +0100821 status_t setFrameRate(float frameRate, int8_t compatibility,
822 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700823 std::unique_lock _lock{mMutex};
824 if (mDestroyed) {
825 return DEAD_OBJECT;
826 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100827 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
828 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700829 return BAD_VALUE;
830 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100831 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700832 }
Robert Carr9b611b72020-10-19 12:00:23 -0700833
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000834 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700835 std::unique_lock _lock{mMutex};
836 if (mDestroyed) {
837 return DEAD_OBJECT;
838 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000839 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700840 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700841
842 void destroy() override {
843 Surface::destroy();
844
845 std::unique_lock _lock{mMutex};
846 mDestroyed = true;
847 mBbq = nullptr;
848 }
Robert Carr05086b22020-10-13 18:22:51 -0700849};
850
Robert Carr9c006e02020-10-14 13:41:57 -0700851// TODO: Can we coalesce this with frame updates? Need to confirm
852// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200853status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
854 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700855 std::unique_lock _lock{mMutex};
856 SurfaceComposerClient::Transaction t;
857
Marin Shalamanov46084422020-10-13 12:33:42 +0200858 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700859}
860
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000861status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700862 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000863 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100864 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700865}
866
Hongguang Chen621ec582021-02-16 15:42:35 -0800867void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
868 std::unique_lock _lock{mMutex};
869 SurfaceComposerClient::Transaction t;
870
871 t.setSidebandStream(mSurfaceControl, stream).apply();
872}
873
Vishnu Nair992496b2020-10-22 17:27:21 -0700874sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
875 std::unique_lock _lock{mMutex};
876 sp<IBinder> scHandle = nullptr;
877 if (includeSurfaceControlHandle && mSurfaceControl) {
878 scHandle = mSurfaceControl->getHandle();
879 }
880 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700881}
882
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800883void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
884 uint64_t frameNumber) {
885 std::lock_guard _lock{mMutex};
886 if (mLastAcquiredFrameNumber >= frameNumber) {
887 // Apply the transaction since we have already acquired the desired frame.
888 t->apply();
889 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500890 mPendingTransactions.emplace_back(frameNumber, *t);
891 // Clear the transaction so it can't be applied elsewhere.
892 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800893 }
894}
895
chaviw6a195272021-09-03 16:14:25 -0500896void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
897 std::lock_guard _lock{mMutex};
898
899 SurfaceComposerClient::Transaction t;
900 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800901 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
902 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500903}
904
905void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
906 uint64_t frameNumber) {
907 auto mergeTransaction =
908 [&t, currentFrameNumber = frameNumber](
909 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
910 auto& [targetFrameNumber, transaction] = pendingTransaction;
911 if (currentFrameNumber < targetFrameNumber) {
912 return false;
913 }
914 t->merge(std::move(transaction));
915 return true;
916 };
917
918 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
919 mPendingTransactions.end(), mergeTransaction),
920 mPendingTransactions.end());
921}
922
chaviwd84085a2022-02-08 11:07:04 -0600923SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
924 uint64_t frameNumber) {
925 std::lock_guard _lock{mMutex};
926 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
927 mergePendingTransactions(t, frameNumber);
928 return t;
929}
930
Vishnu Nair89496122020-12-14 17:14:53 -0800931// Maintains a single worker thread per process that services a list of runnables.
932class AsyncWorker : public Singleton<AsyncWorker> {
933private:
934 std::thread mThread;
935 bool mDone = false;
936 std::deque<std::function<void()>> mRunnables;
937 std::mutex mMutex;
938 std::condition_variable mCv;
939 void run() {
940 std::unique_lock<std::mutex> lock(mMutex);
941 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800942 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700943 std::deque<std::function<void()>> runnables = std::move(mRunnables);
944 mRunnables.clear();
945 lock.unlock();
946 // Run outside the lock since the runnable might trigger another
947 // post to the async worker.
948 execute(runnables);
949 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800950 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700951 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800952 }
953 }
954
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700955 void execute(std::deque<std::function<void()>>& runnables) {
956 while (!runnables.empty()) {
957 std::function<void()> runnable = runnables.front();
958 runnables.pop_front();
959 runnable();
960 }
961 }
962
Vishnu Nair89496122020-12-14 17:14:53 -0800963public:
964 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
965
966 ~AsyncWorker() {
967 mDone = true;
968 mCv.notify_all();
969 if (mThread.joinable()) {
970 mThread.join();
971 }
972 }
973
974 void post(std::function<void()> runnable) {
975 std::unique_lock<std::mutex> lock(mMutex);
976 mRunnables.emplace_back(std::move(runnable));
977 mCv.notify_one();
978 }
979};
980ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
981
982// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
983class AsyncProducerListener : public BnProducerListener {
984private:
985 const sp<IProducerListener> mListener;
986
987public:
988 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
989
990 void onBufferReleased() override {
991 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
992 }
993
994 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
995 AsyncWorker::getInstance().post(
996 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
997 }
998};
999
1000// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
1001// can be non-blocking when the producer is in the client process.
1002class BBQBufferQueueProducer : public BufferQueueProducer {
1003public:
1004 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
1005 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
1006
1007 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
1008 QueueBufferOutput* output) override {
1009 if (!listener) {
1010 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1011 }
1012
1013 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1014 producerControlledByApp, output);
1015 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001016
1017 int query(int what, int* value) override {
1018 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1019 *value = 1;
1020 return NO_ERROR;
1021 }
1022 return BufferQueueProducer::query(what, value);
1023 }
Vishnu Nair89496122020-12-14 17:14:53 -08001024};
1025
1026// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1027// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1028// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1029// we can deadlock.
1030void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1031 sp<IGraphicBufferConsumer>* outConsumer) {
1032 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1033 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1034
1035 sp<BufferQueueCore> core(new BufferQueueCore());
1036 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1037
1038 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1039 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1040 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1041
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001042 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1043 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001044 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1045 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1046
1047 *outProducer = producer;
1048 *outConsumer = consumer;
1049}
1050
chaviw497e81c2021-02-04 17:09:47 -08001051PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1052 PixelFormat convertedFormat = format;
1053 switch (format) {
1054 case PIXEL_FORMAT_TRANSPARENT:
1055 case PIXEL_FORMAT_TRANSLUCENT:
1056 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1057 break;
1058 case PIXEL_FORMAT_OPAQUE:
1059 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1060 break;
1061 }
1062 return convertedFormat;
1063}
1064
Robert Carr82d07c92021-05-10 11:36:43 -07001065uint32_t BLASTBufferQueue::getLastTransformHint() const {
1066 if (mSurfaceControl != nullptr) {
1067 return mSurfaceControl->getTransformHint();
1068 } else {
1069 return 0;
1070 }
1071}
1072
chaviw0b020f82021-08-20 12:00:47 -05001073uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
1074 std::unique_lock _lock{mMutex};
1075 return mLastAcquiredFrameNumber;
1076}
1077
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001078void BLASTBufferQueue::abandon() {
1079 std::unique_lock _lock{mMutex};
1080 // flush out the shadow queue
1081 while (mNumFrameAvailable > 0) {
1082 acquireAndReleaseBuffer();
1083 }
1084
1085 // Clear submitted buffer states
1086 mNumAcquired = 0;
1087 mSubmitted.clear();
1088 mPendingRelease.clear();
1089
1090 if (!mPendingTransactions.empty()) {
1091 BQA_LOGD("Applying pending transactions on abandon %d",
1092 static_cast<uint32_t>(mPendingTransactions.size()));
1093 SurfaceComposerClient::Transaction t;
1094 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -08001095 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1096 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001097 }
1098
1099 // Clear sync states
1100 if (mWaitForTransactionCallback) {
1101 BQA_LOGD("mWaitForTransactionCallback cleared");
1102 mWaitForTransactionCallback = false;
1103 }
1104
1105 if (mSyncTransaction != nullptr) {
1106 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1107 mAcquireSingleBuffer ? "true" : "false");
1108 mSyncTransaction = nullptr;
1109 mAcquireSingleBuffer = false;
1110 }
1111
1112 // abandon buffer queue
1113 if (mBufferItemConsumer != nullptr) {
1114 mBufferItemConsumer->abandon();
1115 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1116 mBufferItemConsumer->setBufferFreedListener(nullptr);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001117 }
1118 mBufferItemConsumer = nullptr;
1119 mConsumer = nullptr;
1120 mProducer = nullptr;
1121}
1122
1123bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1124 std::unique_lock _lock{mMutex};
1125 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1126}
1127
Robert Carr4c1b6462021-12-21 10:30:50 -08001128void BLASTBufferQueue::setTransactionHangCallback(std::function<void(bool)> callback) {
1129 std::unique_lock _lock{mMutex};
1130 mTransactionHangCallback = callback;
1131}
1132
Robert Carr78c25dd2019-08-15 14:10:33 -07001133} // namespace android