blob: ec4c7c10a4d45ea3a3af729b09ae776e07240a4a [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);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800187}
188
chaviw565ee542021-01-14 10:21:23 -0800189void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800190 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800191 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
192
Robert Carr78c25dd2019-08-15 14:10:33 -0700193 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800194 if (mFormat != format) {
195 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800196 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800197 }
198
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800199 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000200 if (surfaceControlChanged && mSurfaceControl != nullptr) {
201 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
202 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800203 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800204
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700205 // Always update the native object even though they might have the same layer handle, so we can
206 // get the updated transform hint from WM.
207 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800208 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800209 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800210 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
211 layer_state_t::eEnableBackpressure);
212 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800213 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800214 mTransformHint = mSurfaceControl->getTransformHint();
215 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700216 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
217 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800218
Vishnu Nairea0de002020-11-17 17:42:37 -0800219 ui::Size newSize(width, height);
220 if (mRequestedSize != newSize) {
221 mRequestedSize.set(newSize);
222 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000223 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800224 // If the buffer supports scaling, update the frame immediately since the client may
225 // want to scale the existing buffer to the new size.
226 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800227 if (mUpdateDestinationFrame) {
228 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
229 applyTransaction = true;
230 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800231 }
Robert Carrfc416512020-04-02 12:32:44 -0700232 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800233 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800234 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
235 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800236 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700237}
238
chaviwd7deef72021-10-06 11:53:40 -0500239static std::optional<SurfaceControlStats> findMatchingStat(
240 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
241 for (auto stat : stats) {
242 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
243 return stat;
244 }
245 }
246 return std::nullopt;
247}
248
249static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
250 const sp<Fence>& presentFence,
251 const std::vector<SurfaceControlStats>& stats) {
252 if (context == nullptr) {
253 return;
254 }
255 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
256 bq->transactionCommittedCallback(latchTime, presentFence, stats);
257}
258
259void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
260 const sp<Fence>& /*presentFence*/,
261 const std::vector<SurfaceControlStats>& stats) {
262 {
263 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600264 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500265 BQA_LOGV("transactionCommittedCallback");
266 if (!mSurfaceControlsWithPendingCallback.empty()) {
267 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
268 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
269 if (stat) {
270 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
271
272 // We need to check if we were waiting for a transaction callback in order to
273 // process any pending buffers and unblock. It's possible to get transaction
274 // callbacks for previous requests so we need to ensure the frame from this
275 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
276 // will stop processing buffers when mWaitForTransactionCallback is set, we know
277 // that mLastAcquiredFrameNumber is the frame we're waiting on.
278 // We also want to check if mNextTransaction is null because it's possible another
279 // sync request came in while waiting, but it hasn't started processing yet. In that
280 // case, we don't actually want to flush the frames in between since they will get
281 // processed and merged with the sync transaction and released earlier than if they
282 // were sent to SF
chaviwa1c4c822021-11-10 18:11:58 -0600283 if (mWaitForTransactionCallback && mSyncTransaction == nullptr &&
chaviwd7deef72021-10-06 11:53:40 -0500284 currFrameNumber >= mLastAcquiredFrameNumber) {
285 mWaitForTransactionCallback = false;
286 flushShadowQueue();
287 }
288 } else {
chaviw768bfa02021-11-01 09:50:57 -0500289 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500290 }
291 } else {
292 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
293 "empty.");
294 }
295
296 decStrong((void*)transactionCommittedCallbackThunk);
297 }
298}
299
Robert Carr78c25dd2019-08-15 14:10:33 -0700300static void transactionCallbackThunk(void* context, nsecs_t latchTime,
301 const sp<Fence>& presentFence,
302 const std::vector<SurfaceControlStats>& stats) {
303 if (context == nullptr) {
304 return;
305 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800306 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700307 bq->transactionCallback(latchTime, presentFence, stats);
308}
309
310void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
311 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700312 {
313 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600314 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700315 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700316
chaviw42026162021-04-16 15:46:12 -0500317 if (!mSurfaceControlsWithPendingCallback.empty()) {
318 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
319 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500320 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
321 if (statsOptional) {
322 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500323 mTransformHint = stat.transformHint;
324 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700325 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700326 // Update frametime stamps if the frame was latched and presented, indicated by a
327 // valid latch time.
328 if (stat.latchTime > 0) {
329 mBufferItemConsumer
330 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
331 stat.frameEventStats.refreshStartTime,
332 stat.frameEventStats.gpuCompositionDoneFence,
333 stat.presentFence, stat.previousReleaseFence,
334 stat.frameEventStats.compositorTiming,
335 stat.latchTime,
336 stat.frameEventStats.dequeueReadyTime);
337 }
chaviwd7deef72021-10-06 11:53:40 -0500338 } else {
chaviw768bfa02021-11-01 09:50:57 -0500339 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500340 }
341 } else {
342 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
343 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800344 }
chaviw71c2cc42020-10-23 16:42:02 -0700345
chaviw71c2cc42020-10-23 16:42:02 -0700346 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700347 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700348}
349
Vishnu Nair1506b182021-02-22 14:35:15 -0800350// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
351// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
352// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
353// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700354static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500355 const sp<Fence>& releaseFence,
356 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800357 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800358 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500359 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700360 } else {
361 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800362 }
363}
364
chaviwd7deef72021-10-06 11:53:40 -0500365void BLASTBufferQueue::flushShadowQueue() {
366 BQA_LOGV("flushShadowQueue");
367 int numFramesToFlush = mNumFrameAvailable;
368 while (numFramesToFlush > 0) {
369 acquireNextBufferLocked(std::nullopt);
370 numFramesToFlush--;
371 }
372}
373
chaviw69058fb2021-09-27 09:37:30 -0500374void BLASTBufferQueue::releaseBufferCallback(
375 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
376 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
chaviw57ae4b22022-02-03 16:51:39 -0600377 BBQ_TRACE();
Vishnu Nair1506b182021-02-22 14:35:15 -0800378 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700379 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800380
Ady Abraham899dcdb2021-06-15 16:56:21 -0700381 // Calculate how many buffers we need to hold before we release them back
382 // to the buffer queue. This will prevent higher latency when we are running
383 // on a lower refresh rate than the max supported. We only do that for EGL
384 // clients as others don't care about latency
385 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700386 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700387 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
388 }();
389
chaviw69058fb2021-09-27 09:37:30 -0500390 if (currentMaxAcquiredBufferCount) {
391 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
392 }
393
Ady Abraham899dcdb2021-06-15 16:56:21 -0700394 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500395 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700396 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700397
398 // Release all buffers that are beyond the ones that we need to hold
399 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500400 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700401 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500402 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwd7deef72021-10-06 11:53:40 -0500403 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
chaviwa1c4c822021-11-10 18:11:58 -0600404 // onFrameAvailable handle processing them since it will merge with the syncTransaction.
chaviwd7deef72021-10-06 11:53:40 -0500405 if (!mWaitForTransactionCallback) {
406 acquireNextBufferLocked(std::nullopt);
407 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800408 }
409
Ady Abraham899dcdb2021-06-15 16:56:21 -0700410 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700411 ATRACE_INT(mQueuedBufferTrace.c_str(),
412 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800413 mCallbackCV.notify_all();
414}
415
chaviw0acd33a2021-11-02 11:55:37 -0500416void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
417 const sp<Fence>& releaseFence) {
418 auto it = mSubmitted.find(callbackId);
419 if (it == mSubmitted.end()) {
420 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
421 callbackId.to_string().c_str());
422 return;
423 }
424 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600425 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500426 BQA_LOGV("released %s", callbackId.to_string().c_str());
427 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
428 mSubmitted.erase(it);
429}
430
chaviwd7deef72021-10-06 11:53:40 -0500431void BLASTBufferQueue::acquireNextBufferLocked(
432 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800433 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
434 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500435 const bool includeExtraAcquire = !transaction;
436 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
437 if (mNumFrameAvailable == 0 || maxAcquired) {
438 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800439 return;
440 }
441
Valerie Haua32c5522019-12-09 10:11:08 -0800442 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700443 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800444 return;
445 }
446
Robert Carr78c25dd2019-08-15 14:10:33 -0700447 SurfaceComposerClient::Transaction localTransaction;
448 bool applyTransaction = true;
449 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500450 if (transaction) {
451 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700452 applyTransaction = false;
453 }
454
Valerie Haua32c5522019-12-09 10:11:08 -0800455 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800456
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800457 status_t status =
458 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800459 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
460 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
461 return;
462 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700463 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700464 return;
465 }
chaviw57ae4b22022-02-03 16:51:39 -0600466
Valerie Haua32c5522019-12-09 10:11:08 -0800467 auto buffer = bufferItem.mGraphicBuffer;
468 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600469 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800470
471 if (buffer == nullptr) {
472 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700473 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800474 return;
475 }
476
Vishnu Nair670b3f72020-09-29 17:52:18 -0700477 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700478 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800479 "buffer{size=%dx%d transform=%d}",
480 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
481 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
482 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500483 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800484 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700485 }
486
Valerie Haua32c5522019-12-09 10:11:08 -0800487 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700488 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
489 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
490 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700491
Valerie Hau871d6352020-01-29 08:44:02 -0800492 bool needsDisconnect = false;
493 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
494
495 // if producer disconnected before, notify SurfaceFlinger
496 if (needsDisconnect) {
497 t->notifyProducerDisconnect(mSurfaceControl);
498 }
499
Robert Carr78c25dd2019-08-15 14:10:33 -0700500 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
501 incStrong((void*)transactionCallbackThunk);
502
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700503 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700504 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000505 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
506 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700507 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800508
Vishnu Nair1506b182021-02-22 14:35:15 -0800509 auto releaseBufferCallback =
510 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500511 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500512 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600513 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500514 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
515 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
516 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700517 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600518
chaviw42026162021-04-16 15:46:12 -0500519 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700520
Vishnu Naird2aaab12022-02-10 14:49:09 -0800521 if (mUpdateDestinationFrame) {
522 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
523 } else {
524 const bool ignoreDestinationFrame =
525 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
526 t->setFlags(mSurfaceControl,
527 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
528 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700529 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700530 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800531 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800532 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800533 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800534 if (!bufferItem.mIsAutoTimestamp) {
535 t->setDesiredPresentTime(bufferItem.mTimestamp);
536 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700537
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000538 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700539 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000540 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100541 }
542
Vishnu Nairadf632b2021-01-07 14:05:08 -0800543 {
544 std::unique_lock _lock{mTimestampMutex};
545 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
546 if (dequeueTime != mDequeueTimestamps.end()) {
547 Parcel p;
548 p.writeInt64(dequeueTime->second);
549 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
550 mDequeueTimestamps.erase(dequeueTime);
551 }
552 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800553
chaviw6a195272021-09-03 16:14:25 -0500554 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700555 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800556 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
557 t->setApplyToken(mApplyToken).apply(false, true);
558 mAppliedLastTransaction = true;
559 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
560 } else {
561 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
562 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700563 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700564
chaviwd7deef72021-10-06 11:53:40 -0500565 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800566 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700567 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500568 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800569 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700570 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700571 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700572}
573
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800574Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
575 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800576 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800577 }
578 return item.mCrop;
579}
580
chaviwd7deef72021-10-06 11:53:40 -0500581void BLASTBufferQueue::acquireAndReleaseBuffer() {
582 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500583 status_t status =
584 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
585 if (status != OK) {
586 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
587 statusToString(status).c_str());
588 return;
589 }
chaviwd7deef72021-10-06 11:53:40 -0500590 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500591 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500592}
593
chaviw0acd33a2021-11-02 11:55:37 -0500594void BLASTBufferQueue::flushAndWaitForFreeBuffer(std::unique_lock<std::mutex>& lock) {
595 if (mWaitForTransactionCallback && mNumFrameAvailable > 0) {
596 // We are waiting on a previous sync's transaction callback so allow another sync
597 // transaction to proceed.
598 //
599 // We need to first flush out the transactions that were in between the two syncs.
600 // We do this by merging them into mSyncTransaction so any buffer merging will get
601 // a release callback invoked. The release callback will be async so we need to wait
602 // on max acquired to make sure we have the capacity to acquire another buffer.
603 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
604 BQA_LOGD("waiting to flush shadow queue...");
605 mCallbackCV.wait(lock);
606 }
607 while (mNumFrameAvailable > 0) {
608 // flush out the shadow queue
609 acquireAndReleaseBuffer();
610 }
611 }
612
613 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
614 BQA_LOGD("waiting for free buffer.");
615 mCallbackCV.wait(lock);
616 }
617}
618
Vishnu Nairaef1de92020-10-22 12:15:53 -0700619void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000620 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
621 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
622 {
623 BBQ_TRACE();
624 std::unique_lock _lock{mMutex};
625 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
626 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800627
Tianhao Yao4861b102022-02-03 20:18:35 +0000628 if (syncTransactionSet) {
629 bool mayNeedToWaitForBuffer = true;
630 // If we are going to re-use the same mSyncTransaction, release the buffer that may
631 // already be set in the Transaction. This is to allow us a free slot early to continue
632 // processing a new buffer.
633 if (!mAcquireSingleBuffer) {
634 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
635 if (bufferData) {
636 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
637 bufferData->frameNumber);
638 releaseBuffer(bufferData->generateReleaseCallbackId(),
639 bufferData->acquireFence);
640 // Because we just released a buffer, we know there's no need to wait for a free
641 // buffer.
642 mayNeedToWaitForBuffer = false;
643 }
644 }
chaviw0acd33a2021-11-02 11:55:37 -0500645
Tianhao Yao4861b102022-02-03 20:18:35 +0000646 if (mayNeedToWaitForBuffer) {
647 flushAndWaitForFreeBuffer(_lock);
chaviwd7deef72021-10-06 11:53:40 -0500648 }
649 }
650
Tianhao Yao4861b102022-02-03 20:18:35 +0000651 // add to shadow queue
652 mNumFrameAvailable++;
653 if (mWaitForTransactionCallback && mNumFrameAvailable >= 2) {
654 acquireAndReleaseBuffer();
655 }
656 ATRACE_INT(mQueuedBufferTrace.c_str(),
657 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
658
659 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
660 item.mFrameNumber, boolToString(syncTransactionSet));
661
662 if (syncTransactionSet) {
663 acquireNextBufferLocked(mSyncTransaction);
664
665 // Only need a commit callback when syncing to ensure the buffer that's synced has been
666 // sent to SF
667 incStrong((void*)transactionCommittedCallbackThunk);
668 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
669 static_cast<void*>(this));
670 mWaitForTransactionCallback = true;
671 if (mAcquireSingleBuffer) {
672 prevCallback = mTransactionReadyCallback;
673 prevTransaction = mSyncTransaction;
674 mTransactionReadyCallback = nullptr;
675 mSyncTransaction = nullptr;
676 }
677 } else if (!mWaitForTransactionCallback) {
678 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800679 }
680 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000681 if (prevCallback) {
682 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500683 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800684}
685
Vishnu Nairaef1de92020-10-22 12:15:53 -0700686void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
687 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
688 // Do nothing since we are not storing unacquired buffer items locally.
689}
690
Vishnu Nairadf632b2021-01-07 14:05:08 -0800691void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
692 std::unique_lock _lock{mTimestampMutex};
693 mDequeueTimestamps[bufferId] = systemTime();
694};
695
696void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
697 std::unique_lock _lock{mTimestampMutex};
698 mDequeueTimestamps.erase(bufferId);
699};
700
Tianhao Yao4861b102022-02-03 20:18:35 +0000701void BLASTBufferQueue::syncNextTransaction(
702 std::function<void(SurfaceComposerClient::Transaction*)> callback,
703 bool acquireSingleBuffer) {
chaviw57ae4b22022-02-03 16:51:39 -0600704 BBQ_TRACE();
Valerie Haud3b90d22019-11-06 09:37:31 -0800705 std::lock_guard _lock{mMutex};
Tianhao Yao4861b102022-02-03 20:18:35 +0000706 mTransactionReadyCallback = callback;
707 if (callback) {
708 mSyncTransaction = new SurfaceComposerClient::Transaction();
709 } else {
710 mSyncTransaction = nullptr;
711 }
712 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
713}
714
715void BLASTBufferQueue::stopContinuousSyncTransaction() {
716 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
717 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
718 {
719 std::lock_guard _lock{mMutex};
720 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
721 if (invokeCallback) {
722 prevCallback = mTransactionReadyCallback;
723 prevTransaction = mSyncTransaction;
724 }
725 mTransactionReadyCallback = nullptr;
726 mSyncTransaction = nullptr;
727 mAcquireSingleBuffer = true;
728 }
729 if (prevCallback) {
730 prevCallback(prevTransaction);
731 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700732}
733
Vishnu Nairea0de002020-11-17 17:42:37 -0800734bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700735 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
736 // Only reject buffers if scaling mode is freeze.
737 return false;
738 }
739
Vishnu Naire1a42322020-10-02 17:42:04 -0700740 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
741 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
742
743 // Take the buffer's orientation into account
744 if (item.mTransform & ui::Transform::ROT_90) {
745 std::swap(bufWidth, bufHeight);
746 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800747 ui::Size bufferSize(bufWidth, bufHeight);
748 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800749 return false;
750 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700751
Vishnu Nair670b3f72020-09-29 17:52:18 -0700752 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800753 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700754}
Vishnu Nairbf255772020-10-16 10:54:41 -0700755
756// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800757// Consumer can acquire an additional buffer if that buffer is not droppable. Set
758// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
759// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
760bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700761 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800762 return mNumAcquired >= maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700763}
764
Robert Carr05086b22020-10-13 18:22:51 -0700765class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700766private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700767 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700768 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700769 bool mDestroyed = false;
770
Robert Carr05086b22020-10-13 18:22:51 -0700771public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700772 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
773 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
774 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700775
Robert Carr05086b22020-10-13 18:22:51 -0700776 void allocateBuffers() override {
777 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
778 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
779 auto gbp = getIGraphicBufferProducer();
780 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
781 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
782 gbp->allocateBuffers(reqWidth, reqHeight,
783 reqFormat, reqUsage);
784
785 }).detach();
786 }
Robert Carr9c006e02020-10-14 13:41:57 -0700787
Marin Shalamanovc5986772021-03-16 16:09:49 +0100788 status_t setFrameRate(float frameRate, int8_t compatibility,
789 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700790 std::unique_lock _lock{mMutex};
791 if (mDestroyed) {
792 return DEAD_OBJECT;
793 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100794 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
795 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700796 return BAD_VALUE;
797 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100798 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700799 }
Robert Carr9b611b72020-10-19 12:00:23 -0700800
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000801 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700802 std::unique_lock _lock{mMutex};
803 if (mDestroyed) {
804 return DEAD_OBJECT;
805 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000806 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700807 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700808
809 void destroy() override {
810 Surface::destroy();
811
812 std::unique_lock _lock{mMutex};
813 mDestroyed = true;
814 mBbq = nullptr;
815 }
Robert Carr05086b22020-10-13 18:22:51 -0700816};
817
Robert Carr9c006e02020-10-14 13:41:57 -0700818// TODO: Can we coalesce this with frame updates? Need to confirm
819// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200820status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
821 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700822 std::unique_lock _lock{mMutex};
823 SurfaceComposerClient::Transaction t;
824
Marin Shalamanov46084422020-10-13 12:33:42 +0200825 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700826}
827
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000828status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700829 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000830 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100831 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700832}
833
Hongguang Chen621ec582021-02-16 15:42:35 -0800834void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
835 std::unique_lock _lock{mMutex};
836 SurfaceComposerClient::Transaction t;
837
838 t.setSidebandStream(mSurfaceControl, stream).apply();
839}
840
Vishnu Nair992496b2020-10-22 17:27:21 -0700841sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
842 std::unique_lock _lock{mMutex};
843 sp<IBinder> scHandle = nullptr;
844 if (includeSurfaceControlHandle && mSurfaceControl) {
845 scHandle = mSurfaceControl->getHandle();
846 }
847 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700848}
849
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800850void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
851 uint64_t frameNumber) {
852 std::lock_guard _lock{mMutex};
853 if (mLastAcquiredFrameNumber >= frameNumber) {
854 // Apply the transaction since we have already acquired the desired frame.
855 t->apply();
856 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500857 mPendingTransactions.emplace_back(frameNumber, *t);
858 // Clear the transaction so it can't be applied elsewhere.
859 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800860 }
861}
862
chaviw6a195272021-09-03 16:14:25 -0500863void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
864 std::lock_guard _lock{mMutex};
865
866 SurfaceComposerClient::Transaction t;
867 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800868 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
869 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500870}
871
872void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
873 uint64_t frameNumber) {
874 auto mergeTransaction =
875 [&t, currentFrameNumber = frameNumber](
876 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
877 auto& [targetFrameNumber, transaction] = pendingTransaction;
878 if (currentFrameNumber < targetFrameNumber) {
879 return false;
880 }
881 t->merge(std::move(transaction));
882 return true;
883 };
884
885 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
886 mPendingTransactions.end(), mergeTransaction),
887 mPendingTransactions.end());
888}
889
chaviwd84085a2022-02-08 11:07:04 -0600890SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
891 uint64_t frameNumber) {
892 std::lock_guard _lock{mMutex};
893 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
894 mergePendingTransactions(t, frameNumber);
895 return t;
896}
897
Vishnu Nair89496122020-12-14 17:14:53 -0800898// Maintains a single worker thread per process that services a list of runnables.
899class AsyncWorker : public Singleton<AsyncWorker> {
900private:
901 std::thread mThread;
902 bool mDone = false;
903 std::deque<std::function<void()>> mRunnables;
904 std::mutex mMutex;
905 std::condition_variable mCv;
906 void run() {
907 std::unique_lock<std::mutex> lock(mMutex);
908 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800909 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700910 std::deque<std::function<void()>> runnables = std::move(mRunnables);
911 mRunnables.clear();
912 lock.unlock();
913 // Run outside the lock since the runnable might trigger another
914 // post to the async worker.
915 execute(runnables);
916 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800917 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700918 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800919 }
920 }
921
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700922 void execute(std::deque<std::function<void()>>& runnables) {
923 while (!runnables.empty()) {
924 std::function<void()> runnable = runnables.front();
925 runnables.pop_front();
926 runnable();
927 }
928 }
929
Vishnu Nair89496122020-12-14 17:14:53 -0800930public:
931 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
932
933 ~AsyncWorker() {
934 mDone = true;
935 mCv.notify_all();
936 if (mThread.joinable()) {
937 mThread.join();
938 }
939 }
940
941 void post(std::function<void()> runnable) {
942 std::unique_lock<std::mutex> lock(mMutex);
943 mRunnables.emplace_back(std::move(runnable));
944 mCv.notify_one();
945 }
946};
947ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
948
949// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
950class AsyncProducerListener : public BnProducerListener {
951private:
952 const sp<IProducerListener> mListener;
953
954public:
955 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
956
957 void onBufferReleased() override {
958 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
959 }
960
961 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
962 AsyncWorker::getInstance().post(
963 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
964 }
965};
966
967// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
968// can be non-blocking when the producer is in the client process.
969class BBQBufferQueueProducer : public BufferQueueProducer {
970public:
971 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
972 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
973
974 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
975 QueueBufferOutput* output) override {
976 if (!listener) {
977 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
978 }
979
980 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
981 producerControlledByApp, output);
982 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800983
984 int query(int what, int* value) override {
985 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
986 *value = 1;
987 return NO_ERROR;
988 }
989 return BufferQueueProducer::query(what, value);
990 }
Vishnu Nair89496122020-12-14 17:14:53 -0800991};
992
993// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
994// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
995// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
996// we can deadlock.
997void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
998 sp<IGraphicBufferConsumer>* outConsumer) {
999 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1000 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1001
1002 sp<BufferQueueCore> core(new BufferQueueCore());
1003 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1004
1005 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1006 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1007 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1008
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001009 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1010 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001011 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1012 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1013
1014 *outProducer = producer;
1015 *outConsumer = consumer;
1016}
1017
chaviw497e81c2021-02-04 17:09:47 -08001018PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1019 PixelFormat convertedFormat = format;
1020 switch (format) {
1021 case PIXEL_FORMAT_TRANSPARENT:
1022 case PIXEL_FORMAT_TRANSLUCENT:
1023 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1024 break;
1025 case PIXEL_FORMAT_OPAQUE:
1026 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1027 break;
1028 }
1029 return convertedFormat;
1030}
1031
Robert Carr82d07c92021-05-10 11:36:43 -07001032uint32_t BLASTBufferQueue::getLastTransformHint() const {
1033 if (mSurfaceControl != nullptr) {
1034 return mSurfaceControl->getTransformHint();
1035 } else {
1036 return 0;
1037 }
1038}
1039
chaviw0b020f82021-08-20 12:00:47 -05001040uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
1041 std::unique_lock _lock{mMutex};
1042 return mLastAcquiredFrameNumber;
1043}
1044
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001045void BLASTBufferQueue::abandon() {
1046 std::unique_lock _lock{mMutex};
1047 // flush out the shadow queue
1048 while (mNumFrameAvailable > 0) {
1049 acquireAndReleaseBuffer();
1050 }
1051
1052 // Clear submitted buffer states
1053 mNumAcquired = 0;
1054 mSubmitted.clear();
1055 mPendingRelease.clear();
1056
1057 if (!mPendingTransactions.empty()) {
1058 BQA_LOGD("Applying pending transactions on abandon %d",
1059 static_cast<uint32_t>(mPendingTransactions.size()));
1060 SurfaceComposerClient::Transaction t;
1061 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -08001062 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1063 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001064 }
1065
1066 // Clear sync states
1067 if (mWaitForTransactionCallback) {
1068 BQA_LOGD("mWaitForTransactionCallback cleared");
1069 mWaitForTransactionCallback = false;
1070 }
1071
1072 if (mSyncTransaction != nullptr) {
1073 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1074 mAcquireSingleBuffer ? "true" : "false");
1075 mSyncTransaction = nullptr;
1076 mAcquireSingleBuffer = false;
1077 }
1078
1079 // abandon buffer queue
1080 if (mBufferItemConsumer != nullptr) {
1081 mBufferItemConsumer->abandon();
1082 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1083 mBufferItemConsumer->setBufferFreedListener(nullptr);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001084 }
1085 mBufferItemConsumer = nullptr;
1086 mConsumer = nullptr;
1087 mProducer = nullptr;
1088}
1089
1090bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1091 std::unique_lock _lock{mMutex};
1092 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1093}
1094
Robert Carr78c25dd2019-08-15 14:10:33 -07001095} // namespace android