blob: c2793ac5de0f164d0260fea640a096ed3d710299 [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;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800168 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800169}
170
171BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
172 int width, int height, int32_t format)
173 : BLASTBufferQueue(name) {
174 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700175}
176
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800177BLASTBufferQueue::~BLASTBufferQueue() {
178 if (mPendingTransactions.empty()) {
179 return;
180 }
181 BQA_LOGE("Applying pending transactions on dtor %d",
182 static_cast<uint32_t>(mPendingTransactions.size()));
183 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800184 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800185 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
186 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500187
188 if (mTransactionReadyCallback) {
189 mTransactionReadyCallback(mSyncTransaction);
190 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800191}
192
chaviw565ee542021-01-14 10:21:23 -0800193void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800194 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800195 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
196
Robert Carr78c25dd2019-08-15 14:10:33 -0700197 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800198 if (mFormat != format) {
199 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800200 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800201 }
202
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800203 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000204 if (surfaceControlChanged && mSurfaceControl != nullptr) {
205 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
206 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800207 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800208
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700209 // Always update the native object even though they might have the same layer handle, so we can
210 // get the updated transform hint from WM.
211 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800212 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800213 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800214 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
215 layer_state_t::eEnableBackpressure);
216 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800217 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800218 mTransformHint = mSurfaceControl->getTransformHint();
219 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700220 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
221 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800222
Vishnu Nairea0de002020-11-17 17:42:37 -0800223 ui::Size newSize(width, height);
224 if (mRequestedSize != newSize) {
225 mRequestedSize.set(newSize);
226 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000227 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800228 // If the buffer supports scaling, update the frame immediately since the client may
229 // want to scale the existing buffer to the new size.
230 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800231 if (mUpdateDestinationFrame) {
232 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
233 applyTransaction = true;
234 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800235 }
Robert Carrfc416512020-04-02 12:32:44 -0700236 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800237 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800238 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
239 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800240 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700241}
242
chaviwd7deef72021-10-06 11:53:40 -0500243static std::optional<SurfaceControlStats> findMatchingStat(
244 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
245 for (auto stat : stats) {
246 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
247 return stat;
248 }
249 }
250 return std::nullopt;
251}
252
253static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
254 const sp<Fence>& presentFence,
255 const std::vector<SurfaceControlStats>& stats) {
256 if (context == nullptr) {
257 return;
258 }
259 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
260 bq->transactionCommittedCallback(latchTime, presentFence, stats);
261}
262
263void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
264 const sp<Fence>& /*presentFence*/,
265 const std::vector<SurfaceControlStats>& stats) {
266 {
267 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600268 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500269 BQA_LOGV("transactionCommittedCallback");
270 if (!mSurfaceControlsWithPendingCallback.empty()) {
271 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
272 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
273 if (stat) {
274 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
275
276 // We need to check if we were waiting for a transaction callback in order to
277 // process any pending buffers and unblock. It's possible to get transaction
278 // callbacks for previous requests so we need to ensure the frame from this
279 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
280 // will stop processing buffers when mWaitForTransactionCallback is set, we know
281 // that mLastAcquiredFrameNumber is the frame we're waiting on.
282 // We also want to check if mNextTransaction is null because it's possible another
283 // sync request came in while waiting, but it hasn't started processing yet. In that
284 // case, we don't actually want to flush the frames in between since they will get
285 // processed and merged with the sync transaction and released earlier than if they
286 // were sent to SF
chaviwa1c4c822021-11-10 18:11:58 -0600287 if (mWaitForTransactionCallback && mSyncTransaction == nullptr &&
chaviwd7deef72021-10-06 11:53:40 -0500288 currFrameNumber >= mLastAcquiredFrameNumber) {
289 mWaitForTransactionCallback = false;
290 flushShadowQueue();
291 }
292 } else {
chaviw768bfa02021-11-01 09:50:57 -0500293 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500294 }
295 } else {
296 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
297 "empty.");
298 }
299
300 decStrong((void*)transactionCommittedCallbackThunk);
301 }
302}
303
Robert Carr78c25dd2019-08-15 14:10:33 -0700304static void transactionCallbackThunk(void* context, nsecs_t latchTime,
305 const sp<Fence>& presentFence,
306 const std::vector<SurfaceControlStats>& stats) {
307 if (context == nullptr) {
308 return;
309 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800310 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700311 bq->transactionCallback(latchTime, presentFence, stats);
312}
313
314void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
315 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700316 {
317 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600318 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700319 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700320
chaviw42026162021-04-16 15:46:12 -0500321 if (!mSurfaceControlsWithPendingCallback.empty()) {
322 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
323 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500324 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
325 if (statsOptional) {
326 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500327 mTransformHint = stat.transformHint;
328 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700329 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700330 // Update frametime stamps if the frame was latched and presented, indicated by a
331 // valid latch time.
332 if (stat.latchTime > 0) {
333 mBufferItemConsumer
334 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
335 stat.frameEventStats.refreshStartTime,
336 stat.frameEventStats.gpuCompositionDoneFence,
337 stat.presentFence, stat.previousReleaseFence,
338 stat.frameEventStats.compositorTiming,
339 stat.latchTime,
340 stat.frameEventStats.dequeueReadyTime);
341 }
chaviwd7deef72021-10-06 11:53:40 -0500342 } else {
chaviw768bfa02021-11-01 09:50:57 -0500343 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500344 }
345 } else {
346 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
347 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800348 }
chaviw71c2cc42020-10-23 16:42:02 -0700349
chaviw71c2cc42020-10-23 16:42:02 -0700350 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700351 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700352}
353
Vishnu Nair1506b182021-02-22 14:35:15 -0800354// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
355// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
356// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
357// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700358static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500359 const sp<Fence>& releaseFence,
360 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800361 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800362 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500363 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700364 } else {
365 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800366 }
367}
368
chaviwd7deef72021-10-06 11:53:40 -0500369void BLASTBufferQueue::flushShadowQueue() {
370 BQA_LOGV("flushShadowQueue");
371 int numFramesToFlush = mNumFrameAvailable;
372 while (numFramesToFlush > 0) {
373 acquireNextBufferLocked(std::nullopt);
374 numFramesToFlush--;
375 }
376}
377
chaviw69058fb2021-09-27 09:37:30 -0500378void BLASTBufferQueue::releaseBufferCallback(
379 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
380 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
chaviw57ae4b22022-02-03 16:51:39 -0600381 BBQ_TRACE();
Vishnu Nair1506b182021-02-22 14:35:15 -0800382 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700383 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800384
Ady Abraham899dcdb2021-06-15 16:56:21 -0700385 // Calculate how many buffers we need to hold before we release them back
386 // to the buffer queue. This will prevent higher latency when we are running
387 // on a lower refresh rate than the max supported. We only do that for EGL
388 // clients as others don't care about latency
389 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700390 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700391 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
392 }();
393
chaviw69058fb2021-09-27 09:37:30 -0500394 if (currentMaxAcquiredBufferCount) {
395 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
396 }
397
Ady Abraham899dcdb2021-06-15 16:56:21 -0700398 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500399 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700400 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700401
402 // Release all buffers that are beyond the ones that we need to hold
403 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500404 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700405 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500406 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwd7deef72021-10-06 11:53:40 -0500407 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
chaviwa1c4c822021-11-10 18:11:58 -0600408 // onFrameAvailable handle processing them since it will merge with the syncTransaction.
chaviwd7deef72021-10-06 11:53:40 -0500409 if (!mWaitForTransactionCallback) {
410 acquireNextBufferLocked(std::nullopt);
411 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800412 }
413
Ady Abraham899dcdb2021-06-15 16:56:21 -0700414 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700415 ATRACE_INT(mQueuedBufferTrace.c_str(),
416 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800417 mCallbackCV.notify_all();
418}
419
chaviw0acd33a2021-11-02 11:55:37 -0500420void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
421 const sp<Fence>& releaseFence) {
422 auto it = mSubmitted.find(callbackId);
423 if (it == mSubmitted.end()) {
424 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
425 callbackId.to_string().c_str());
426 return;
427 }
428 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600429 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500430 BQA_LOGV("released %s", callbackId.to_string().c_str());
431 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
432 mSubmitted.erase(it);
433}
434
chaviwd7deef72021-10-06 11:53:40 -0500435void BLASTBufferQueue::acquireNextBufferLocked(
436 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800437 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
438 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500439 const bool includeExtraAcquire = !transaction;
440 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
441 if (mNumFrameAvailable == 0 || maxAcquired) {
442 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800443 return;
444 }
445
Valerie Haua32c5522019-12-09 10:11:08 -0800446 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700447 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800448 return;
449 }
450
Robert Carr78c25dd2019-08-15 14:10:33 -0700451 SurfaceComposerClient::Transaction localTransaction;
452 bool applyTransaction = true;
453 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500454 if (transaction) {
455 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700456 applyTransaction = false;
457 }
458
Valerie Haua32c5522019-12-09 10:11:08 -0800459 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800460
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800461 status_t status =
462 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800463 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
464 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
465 return;
466 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700467 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700468 return;
469 }
chaviw57ae4b22022-02-03 16:51:39 -0600470
Valerie Haua32c5522019-12-09 10:11:08 -0800471 auto buffer = bufferItem.mGraphicBuffer;
472 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600473 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800474
475 if (buffer == nullptr) {
476 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700477 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800478 return;
479 }
480
Vishnu Nair670b3f72020-09-29 17:52:18 -0700481 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700482 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800483 "buffer{size=%dx%d transform=%d}",
484 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
485 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
486 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500487 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800488 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700489 }
490
Valerie Haua32c5522019-12-09 10:11:08 -0800491 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700492 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
493 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
494 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700495
Valerie Hau871d6352020-01-29 08:44:02 -0800496 bool needsDisconnect = false;
497 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
498
499 // if producer disconnected before, notify SurfaceFlinger
500 if (needsDisconnect) {
501 t->notifyProducerDisconnect(mSurfaceControl);
502 }
503
Robert Carr78c25dd2019-08-15 14:10:33 -0700504 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
505 incStrong((void*)transactionCallbackThunk);
506
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700507 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700508 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000509 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
510 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700511 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800512
Vishnu Nair1506b182021-02-22 14:35:15 -0800513 auto releaseBufferCallback =
514 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500515 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500516 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600517 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500518 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
519 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
520 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700521 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600522
chaviw42026162021-04-16 15:46:12 -0500523 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700524
Vishnu Naird2aaab12022-02-10 14:49:09 -0800525 if (mUpdateDestinationFrame) {
526 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
527 } else {
528 const bool ignoreDestinationFrame =
529 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
530 t->setFlags(mSurfaceControl,
531 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
532 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700533 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700534 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800535 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800536 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800537 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800538 if (!bufferItem.mIsAutoTimestamp) {
539 t->setDesiredPresentTime(bufferItem.mTimestamp);
540 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700541
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000542 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700543 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000544 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100545 }
546
Vishnu Nairadf632b2021-01-07 14:05:08 -0800547 {
548 std::unique_lock _lock{mTimestampMutex};
549 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
550 if (dequeueTime != mDequeueTimestamps.end()) {
551 Parcel p;
552 p.writeInt64(dequeueTime->second);
553 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
554 mDequeueTimestamps.erase(dequeueTime);
555 }
556 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800557
chaviw6a195272021-09-03 16:14:25 -0500558 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700559 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800560 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
561 t->setApplyToken(mApplyToken).apply(false, true);
562 mAppliedLastTransaction = true;
563 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
564 } else {
565 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
566 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700567 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700568
chaviwd7deef72021-10-06 11:53:40 -0500569 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800570 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700571 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500572 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800573 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700574 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700575 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700576}
577
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800578Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
579 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800580 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800581 }
582 return item.mCrop;
583}
584
chaviwd7deef72021-10-06 11:53:40 -0500585void BLASTBufferQueue::acquireAndReleaseBuffer() {
586 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500587 status_t status =
588 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
589 if (status != OK) {
590 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
591 statusToString(status).c_str());
592 return;
593 }
chaviwd7deef72021-10-06 11:53:40 -0500594 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500595 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500596}
597
chaviw0acd33a2021-11-02 11:55:37 -0500598void BLASTBufferQueue::flushAndWaitForFreeBuffer(std::unique_lock<std::mutex>& lock) {
599 if (mWaitForTransactionCallback && mNumFrameAvailable > 0) {
600 // We are waiting on a previous sync's transaction callback so allow another sync
601 // transaction to proceed.
602 //
603 // We need to first flush out the transactions that were in between the two syncs.
604 // We do this by merging them into mSyncTransaction so any buffer merging will get
605 // a release callback invoked. The release callback will be async so we need to wait
606 // on max acquired to make sure we have the capacity to acquire another buffer.
607 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
608 BQA_LOGD("waiting to flush shadow queue...");
609 mCallbackCV.wait(lock);
610 }
611 while (mNumFrameAvailable > 0) {
612 // flush out the shadow queue
613 acquireAndReleaseBuffer();
614 }
615 }
616
617 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
618 BQA_LOGD("waiting for free buffer.");
619 mCallbackCV.wait(lock);
620 }
621}
622
Vishnu Nairaef1de92020-10-22 12:15:53 -0700623void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000624 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
625 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
626 {
627 BBQ_TRACE();
628 std::unique_lock _lock{mMutex};
629 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
630 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800631
Tianhao Yao4861b102022-02-03 20:18:35 +0000632 if (syncTransactionSet) {
633 bool mayNeedToWaitForBuffer = true;
634 // If we are going to re-use the same mSyncTransaction, release the buffer that may
635 // already be set in the Transaction. This is to allow us a free slot early to continue
636 // processing a new buffer.
637 if (!mAcquireSingleBuffer) {
638 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
639 if (bufferData) {
640 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
641 bufferData->frameNumber);
642 releaseBuffer(bufferData->generateReleaseCallbackId(),
643 bufferData->acquireFence);
644 // Because we just released a buffer, we know there's no need to wait for a free
645 // buffer.
646 mayNeedToWaitForBuffer = false;
647 }
648 }
chaviw0acd33a2021-11-02 11:55:37 -0500649
Tianhao Yao4861b102022-02-03 20:18:35 +0000650 if (mayNeedToWaitForBuffer) {
651 flushAndWaitForFreeBuffer(_lock);
chaviwd7deef72021-10-06 11:53:40 -0500652 }
653 }
654
Tianhao Yao4861b102022-02-03 20:18:35 +0000655 // add to shadow queue
656 mNumFrameAvailable++;
657 if (mWaitForTransactionCallback && mNumFrameAvailable >= 2) {
658 acquireAndReleaseBuffer();
659 }
660 ATRACE_INT(mQueuedBufferTrace.c_str(),
661 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
662
663 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
664 item.mFrameNumber, boolToString(syncTransactionSet));
665
666 if (syncTransactionSet) {
667 acquireNextBufferLocked(mSyncTransaction);
668
669 // Only need a commit callback when syncing to ensure the buffer that's synced has been
670 // sent to SF
671 incStrong((void*)transactionCommittedCallbackThunk);
672 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
673 static_cast<void*>(this));
674 mWaitForTransactionCallback = true;
675 if (mAcquireSingleBuffer) {
676 prevCallback = mTransactionReadyCallback;
677 prevTransaction = mSyncTransaction;
678 mTransactionReadyCallback = nullptr;
679 mSyncTransaction = nullptr;
680 }
681 } else if (!mWaitForTransactionCallback) {
682 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800683 }
684 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000685 if (prevCallback) {
686 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500687 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800688}
689
Vishnu Nairaef1de92020-10-22 12:15:53 -0700690void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
691 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
692 // Do nothing since we are not storing unacquired buffer items locally.
693}
694
Vishnu Nairadf632b2021-01-07 14:05:08 -0800695void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
696 std::unique_lock _lock{mTimestampMutex};
697 mDequeueTimestamps[bufferId] = systemTime();
698};
699
700void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
701 std::unique_lock _lock{mTimestampMutex};
702 mDequeueTimestamps.erase(bufferId);
703};
704
Tianhao Yao4861b102022-02-03 20:18:35 +0000705void BLASTBufferQueue::syncNextTransaction(
706 std::function<void(SurfaceComposerClient::Transaction*)> callback,
707 bool acquireSingleBuffer) {
chaviw57ae4b22022-02-03 16:51:39 -0600708 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500709
710 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
711 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
712
713 {
714 std::lock_guard _lock{mMutex};
715 // We're about to overwrite the previous call so we should invoke that callback
716 // immediately.
717 if (mTransactionReadyCallback) {
718 prevCallback = mTransactionReadyCallback;
719 prevTransaction = mSyncTransaction;
720 }
721
722 mTransactionReadyCallback = callback;
723 if (callback) {
724 mSyncTransaction = new SurfaceComposerClient::Transaction();
725 } else {
726 mSyncTransaction = nullptr;
727 }
728 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000729 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500730
731 if (prevCallback) {
732 prevCallback(prevTransaction);
733 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000734}
735
736void BLASTBufferQueue::stopContinuousSyncTransaction() {
737 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
738 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
739 {
740 std::lock_guard _lock{mMutex};
741 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
742 if (invokeCallback) {
743 prevCallback = mTransactionReadyCallback;
744 prevTransaction = mSyncTransaction;
745 }
746 mTransactionReadyCallback = nullptr;
747 mSyncTransaction = nullptr;
748 mAcquireSingleBuffer = true;
749 }
750 if (prevCallback) {
751 prevCallback(prevTransaction);
752 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700753}
754
Vishnu Nairea0de002020-11-17 17:42:37 -0800755bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700756 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
757 // Only reject buffers if scaling mode is freeze.
758 return false;
759 }
760
Vishnu Naire1a42322020-10-02 17:42:04 -0700761 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
762 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
763
764 // Take the buffer's orientation into account
765 if (item.mTransform & ui::Transform::ROT_90) {
766 std::swap(bufWidth, bufHeight);
767 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800768 ui::Size bufferSize(bufWidth, bufHeight);
769 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800770 return false;
771 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700772
Vishnu Nair670b3f72020-09-29 17:52:18 -0700773 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800774 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700775}
Vishnu Nairbf255772020-10-16 10:54:41 -0700776
777// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800778// Consumer can acquire an additional buffer if that buffer is not droppable. Set
779// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
780// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
781bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700782 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800783 return mNumAcquired >= maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700784}
785
Robert Carr05086b22020-10-13 18:22:51 -0700786class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700787private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700788 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700789 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700790 bool mDestroyed = false;
791
Robert Carr05086b22020-10-13 18:22:51 -0700792public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700793 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
794 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
795 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700796
Robert Carr05086b22020-10-13 18:22:51 -0700797 void allocateBuffers() override {
798 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
799 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
800 auto gbp = getIGraphicBufferProducer();
801 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
802 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
803 gbp->allocateBuffers(reqWidth, reqHeight,
804 reqFormat, reqUsage);
805
806 }).detach();
807 }
Robert Carr9c006e02020-10-14 13:41:57 -0700808
Marin Shalamanovc5986772021-03-16 16:09:49 +0100809 status_t setFrameRate(float frameRate, int8_t compatibility,
810 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700811 std::unique_lock _lock{mMutex};
812 if (mDestroyed) {
813 return DEAD_OBJECT;
814 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100815 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
816 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700817 return BAD_VALUE;
818 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100819 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700820 }
Robert Carr9b611b72020-10-19 12:00:23 -0700821
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000822 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700823 std::unique_lock _lock{mMutex};
824 if (mDestroyed) {
825 return DEAD_OBJECT;
826 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000827 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700828 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700829
830 void destroy() override {
831 Surface::destroy();
832
833 std::unique_lock _lock{mMutex};
834 mDestroyed = true;
835 mBbq = nullptr;
836 }
Robert Carr05086b22020-10-13 18:22:51 -0700837};
838
Robert Carr9c006e02020-10-14 13:41:57 -0700839// TODO: Can we coalesce this with frame updates? Need to confirm
840// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200841status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
842 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700843 std::unique_lock _lock{mMutex};
844 SurfaceComposerClient::Transaction t;
845
Marin Shalamanov46084422020-10-13 12:33:42 +0200846 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700847}
848
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000849status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700850 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000851 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100852 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700853}
854
Hongguang Chen621ec582021-02-16 15:42:35 -0800855void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
856 std::unique_lock _lock{mMutex};
857 SurfaceComposerClient::Transaction t;
858
859 t.setSidebandStream(mSurfaceControl, stream).apply();
860}
861
Vishnu Nair992496b2020-10-22 17:27:21 -0700862sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
863 std::unique_lock _lock{mMutex};
864 sp<IBinder> scHandle = nullptr;
865 if (includeSurfaceControlHandle && mSurfaceControl) {
866 scHandle = mSurfaceControl->getHandle();
867 }
868 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700869}
870
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800871void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
872 uint64_t frameNumber) {
873 std::lock_guard _lock{mMutex};
874 if (mLastAcquiredFrameNumber >= frameNumber) {
875 // Apply the transaction since we have already acquired the desired frame.
876 t->apply();
877 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500878 mPendingTransactions.emplace_back(frameNumber, *t);
879 // Clear the transaction so it can't be applied elsewhere.
880 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800881 }
882}
883
chaviw6a195272021-09-03 16:14:25 -0500884void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
885 std::lock_guard _lock{mMutex};
886
887 SurfaceComposerClient::Transaction t;
888 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800889 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
890 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500891}
892
893void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
894 uint64_t frameNumber) {
895 auto mergeTransaction =
896 [&t, currentFrameNumber = frameNumber](
897 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
898 auto& [targetFrameNumber, transaction] = pendingTransaction;
899 if (currentFrameNumber < targetFrameNumber) {
900 return false;
901 }
902 t->merge(std::move(transaction));
903 return true;
904 };
905
906 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
907 mPendingTransactions.end(), mergeTransaction),
908 mPendingTransactions.end());
909}
910
chaviwd84085a2022-02-08 11:07:04 -0600911SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
912 uint64_t frameNumber) {
913 std::lock_guard _lock{mMutex};
914 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
915 mergePendingTransactions(t, frameNumber);
916 return t;
917}
918
Vishnu Nair89496122020-12-14 17:14:53 -0800919// Maintains a single worker thread per process that services a list of runnables.
920class AsyncWorker : public Singleton<AsyncWorker> {
921private:
922 std::thread mThread;
923 bool mDone = false;
924 std::deque<std::function<void()>> mRunnables;
925 std::mutex mMutex;
926 std::condition_variable mCv;
927 void run() {
928 std::unique_lock<std::mutex> lock(mMutex);
929 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800930 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700931 std::deque<std::function<void()>> runnables = std::move(mRunnables);
932 mRunnables.clear();
933 lock.unlock();
934 // Run outside the lock since the runnable might trigger another
935 // post to the async worker.
936 execute(runnables);
937 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800938 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700939 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800940 }
941 }
942
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700943 void execute(std::deque<std::function<void()>>& runnables) {
944 while (!runnables.empty()) {
945 std::function<void()> runnable = runnables.front();
946 runnables.pop_front();
947 runnable();
948 }
949 }
950
Vishnu Nair89496122020-12-14 17:14:53 -0800951public:
952 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
953
954 ~AsyncWorker() {
955 mDone = true;
956 mCv.notify_all();
957 if (mThread.joinable()) {
958 mThread.join();
959 }
960 }
961
962 void post(std::function<void()> runnable) {
963 std::unique_lock<std::mutex> lock(mMutex);
964 mRunnables.emplace_back(std::move(runnable));
965 mCv.notify_one();
966 }
967};
968ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
969
970// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
971class AsyncProducerListener : public BnProducerListener {
972private:
973 const sp<IProducerListener> mListener;
974
975public:
976 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
977
978 void onBufferReleased() override {
979 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
980 }
981
982 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
983 AsyncWorker::getInstance().post(
984 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
985 }
986};
987
988// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
989// can be non-blocking when the producer is in the client process.
990class BBQBufferQueueProducer : public BufferQueueProducer {
991public:
992 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
993 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
994
995 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
996 QueueBufferOutput* output) override {
997 if (!listener) {
998 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
999 }
1000
1001 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1002 producerControlledByApp, output);
1003 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001004
1005 int query(int what, int* value) override {
1006 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1007 *value = 1;
1008 return NO_ERROR;
1009 }
1010 return BufferQueueProducer::query(what, value);
1011 }
Vishnu Nair89496122020-12-14 17:14:53 -08001012};
1013
1014// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1015// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1016// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1017// we can deadlock.
1018void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1019 sp<IGraphicBufferConsumer>* outConsumer) {
1020 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1021 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1022
1023 sp<BufferQueueCore> core(new BufferQueueCore());
1024 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1025
1026 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1027 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1028 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1029
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001030 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1031 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001032 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1033 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1034
1035 *outProducer = producer;
1036 *outConsumer = consumer;
1037}
1038
chaviw497e81c2021-02-04 17:09:47 -08001039PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1040 PixelFormat convertedFormat = format;
1041 switch (format) {
1042 case PIXEL_FORMAT_TRANSPARENT:
1043 case PIXEL_FORMAT_TRANSLUCENT:
1044 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1045 break;
1046 case PIXEL_FORMAT_OPAQUE:
1047 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1048 break;
1049 }
1050 return convertedFormat;
1051}
1052
Robert Carr82d07c92021-05-10 11:36:43 -07001053uint32_t BLASTBufferQueue::getLastTransformHint() const {
1054 if (mSurfaceControl != nullptr) {
1055 return mSurfaceControl->getTransformHint();
1056 } else {
1057 return 0;
1058 }
1059}
1060
chaviw0b020f82021-08-20 12:00:47 -05001061uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
1062 std::unique_lock _lock{mMutex};
1063 return mLastAcquiredFrameNumber;
1064}
1065
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001066void BLASTBufferQueue::abandon() {
1067 std::unique_lock _lock{mMutex};
1068 // flush out the shadow queue
1069 while (mNumFrameAvailable > 0) {
1070 acquireAndReleaseBuffer();
1071 }
1072
1073 // Clear submitted buffer states
1074 mNumAcquired = 0;
1075 mSubmitted.clear();
1076 mPendingRelease.clear();
1077
1078 if (!mPendingTransactions.empty()) {
1079 BQA_LOGD("Applying pending transactions on abandon %d",
1080 static_cast<uint32_t>(mPendingTransactions.size()));
1081 SurfaceComposerClient::Transaction t;
1082 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -08001083 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1084 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001085 }
1086
1087 // Clear sync states
1088 if (mWaitForTransactionCallback) {
1089 BQA_LOGD("mWaitForTransactionCallback cleared");
1090 mWaitForTransactionCallback = false;
1091 }
1092
1093 if (mSyncTransaction != nullptr) {
1094 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1095 mAcquireSingleBuffer ? "true" : "false");
1096 mSyncTransaction = nullptr;
1097 mAcquireSingleBuffer = false;
1098 }
1099
1100 // abandon buffer queue
1101 if (mBufferItemConsumer != nullptr) {
1102 mBufferItemConsumer->abandon();
1103 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1104 mBufferItemConsumer->setBufferFreedListener(nullptr);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001105 }
1106 mBufferItemConsumer = nullptr;
1107 mConsumer = nullptr;
1108 mProducer = nullptr;
1109}
1110
1111bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1112 std::unique_lock _lock{mMutex};
1113 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1114}
1115
Robert Carr78c25dd2019-08-15 14:10:33 -07001116} // namespace android