blob: bba7387c3ab07b80e1efaebc8a9772e4d9f40544 [file] [log] [blame]
Robert Carr78c25dd2019-08-15 14:10:33 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Valerie Haud3b90d22019-11-06 09:37:31 -080017#undef LOG_TAG
18#define LOG_TAG "BLASTBufferQueue"
19
Valerie Haua32c5522019-12-09 10:11:08 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Vishnu Naire1a42322020-10-02 17:42:04 -070021//#define LOG_NDEBUG 0
Valerie Haua32c5522019-12-09 10:11:08 -080022
Robert Carr78c25dd2019-08-15 14:10:33 -070023#include <gui/BLASTBufferQueue.h>
24#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080025#include <gui/BufferQueueConsumer.h>
26#include <gui/BufferQueueCore.h>
27#include <gui/BufferQueueProducer.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080028#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080029#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070030#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060031#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080032#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080033#include <utils/Trace.h>
34
Ady Abraham0bde6b52021-05-18 13:57:02 -070035#include <private/gui/ComposerService.h>
Huihong Luo02186fb2022-02-23 14:21:54 -080036#include <private/gui/ComposerServiceAIDL.h>
Ady Abraham0bde6b52021-05-18 13:57:02 -070037
Robert Carr78c25dd2019-08-15 14:10:33 -070038#include <chrono>
39
40using namespace std::chrono_literals;
41
Vishnu Nairdab94092020-09-29 16:09:04 -070042namespace {
chaviw3277faf2021-05-19 16:45:23 -050043inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070044 return b ? "true" : "false";
45}
46} // namespace
47
Robert Carr78c25dd2019-08-15 14:10:33 -070048namespace android {
49
Vishnu Nairdab94092020-09-29 16:09:04 -070050// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050051#define BQA_LOGD(x, ...) \
52 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070053#define BQA_LOGV(x, ...) \
54 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080055// enable logs for a single layer
56//#define BQA_LOGV(x, ...) \
57// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
58// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070059#define BQA_LOGE(x, ...) \
60 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
61
chaviw57ae4b22022-02-03 16:51:39 -060062#define BBQ_TRACE(x, ...) \
63 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
64 mNumAcquired, ##__VA_ARGS__)
65
Valerie Hau871d6352020-01-29 08:44:02 -080066void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000067 Mutex::Autolock lock(mMutex);
68 mPreviouslyConnected = mCurrentlyConnected;
69 mCurrentlyConnected = false;
70 if (mPreviouslyConnected) {
71 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080072 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000073 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080074}
75
76void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
77 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080078 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080079 if (newTimestamps) {
80 // BufferQueueProducer only adds a new timestamp on
81 // queueBuffer
82 mCurrentFrameNumber = newTimestamps->frameNumber;
83 mFrameEventHistory.addQueue(*newTimestamps);
84 }
85 if (outDelta) {
86 // frame event histories will be processed
87 // only after the producer connects and requests
88 // deltas for the first time. Forward this intent
89 // to SF-side to turn event processing back on
90 mPreviouslyConnected = mCurrentlyConnected;
91 mCurrentlyConnected = true;
92 mFrameEventHistory.getAndResetDelta(outDelta);
93 }
94}
95
96void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
97 const sp<Fence>& glDoneFence,
98 const sp<Fence>& presentFence,
99 const sp<Fence>& prevReleaseFence,
100 CompositorTiming compositorTiming,
101 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800102 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800103
104 // if the producer is not connected, don't bother updating,
105 // the next producer that connects won't access this frame event
106 if (!mCurrentlyConnected) return;
107 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
108 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
109 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
110
111 mFrameEventHistory.addLatch(frameNumber, latchTime);
112 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
113 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
114 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
115 compositorTiming);
116}
117
118void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
119 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800120 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800121 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
122 disconnect = true;
123 mDisconnectEvents.pop();
124 }
125 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
126}
127
Hongguang Chen621ec582021-02-16 15:42:35 -0800128void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800129 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
130 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800131 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800132 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800133 }
134}
135
Vishnu Naird2aaab12022-02-10 14:49:09 -0800136BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800137 : mSurfaceControl(nullptr),
138 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800139 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800140 mFormat(PIXEL_FORMAT_RGBA_8888),
Tianhao Yao4861b102022-02-03 20:18:35 +0000141 mTransactionReadyCallback(nullptr),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800142 mSyncTransaction(nullptr),
143 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800144 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800145 // since the adapter is in the client process, set dequeue timeout
146 // explicitly so that dequeueBuffer will block
147 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800148
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700149 // safe default, most producers are expected to override this
150 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800151 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
152 GraphicBuffer::USAGE_HW_COMPOSER |
153 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800154 1, false, this);
Valerie Haua32c5522019-12-09 10:11:08 -0800155 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700156 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700157 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700158 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800159 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700160 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700161 mBufferItemConsumer->setFrameAvailableListener(this);
162 mBufferItemConsumer->setBufferFreedListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700163
Huihong Luo02186fb2022-02-23 14:21:54 -0800164 ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700165 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500166 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800167 mNumAcquired = 0;
168 mNumFrameAvailable = 0;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800169 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800170}
171
172BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
173 int width, int height, int32_t format)
174 : BLASTBufferQueue(name) {
175 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700176}
177
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800178BLASTBufferQueue::~BLASTBufferQueue() {
179 if (mPendingTransactions.empty()) {
180 return;
181 }
182 BQA_LOGE("Applying pending transactions on dtor %d",
183 static_cast<uint32_t>(mPendingTransactions.size()));
184 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800185 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -0800186 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
187 t.setApplyToken(mApplyToken).apply(false, true);
chaviw3b4bdcf2022-03-17 09:27:03 -0500188
189 if (mTransactionReadyCallback) {
190 mTransactionReadyCallback(mSyncTransaction);
191 }
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800192}
193
chaviw565ee542021-01-14 10:21:23 -0800194void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800195 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800196 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
197
Robert Carr78c25dd2019-08-15 14:10:33 -0700198 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800199 if (mFormat != format) {
200 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800201 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800202 }
203
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800204 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000205 if (surfaceControlChanged && mSurfaceControl != nullptr) {
206 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
207 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800208 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800209
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700210 // Always update the native object even though they might have the same layer handle, so we can
211 // get the updated transform hint from WM.
212 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800213 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800214 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800215 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
216 layer_state_t::eEnableBackpressure);
217 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800218 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800219 mTransformHint = mSurfaceControl->getTransformHint();
220 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700221 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
222 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800223
Vishnu Nairea0de002020-11-17 17:42:37 -0800224 ui::Size newSize(width, height);
225 if (mRequestedSize != newSize) {
226 mRequestedSize.set(newSize);
227 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000228 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800229 // If the buffer supports scaling, update the frame immediately since the client may
230 // want to scale the existing buffer to the new size.
231 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800232 if (mUpdateDestinationFrame) {
233 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
234 applyTransaction = true;
235 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800236 }
Robert Carrfc416512020-04-02 12:32:44 -0700237 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800238 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800239 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
240 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800241 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700242}
243
chaviwd7deef72021-10-06 11:53:40 -0500244static std::optional<SurfaceControlStats> findMatchingStat(
245 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
246 for (auto stat : stats) {
247 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
248 return stat;
249 }
250 }
251 return std::nullopt;
252}
253
254static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
255 const sp<Fence>& presentFence,
256 const std::vector<SurfaceControlStats>& stats) {
257 if (context == nullptr) {
258 return;
259 }
260 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
261 bq->transactionCommittedCallback(latchTime, presentFence, stats);
262}
263
264void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
265 const sp<Fence>& /*presentFence*/,
266 const std::vector<SurfaceControlStats>& stats) {
267 {
268 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600269 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500270 BQA_LOGV("transactionCommittedCallback");
271 if (!mSurfaceControlsWithPendingCallback.empty()) {
272 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
273 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
274 if (stat) {
275 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
276
277 // We need to check if we were waiting for a transaction callback in order to
278 // process any pending buffers and unblock. It's possible to get transaction
279 // callbacks for previous requests so we need to ensure the frame from this
280 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
281 // will stop processing buffers when mWaitForTransactionCallback is set, we know
282 // that mLastAcquiredFrameNumber is the frame we're waiting on.
283 // We also want to check if mNextTransaction is null because it's possible another
284 // sync request came in while waiting, but it hasn't started processing yet. In that
285 // case, we don't actually want to flush the frames in between since they will get
286 // processed and merged with the sync transaction and released earlier than if they
287 // were sent to SF
chaviwa1c4c822021-11-10 18:11:58 -0600288 if (mWaitForTransactionCallback && mSyncTransaction == nullptr &&
chaviwd7deef72021-10-06 11:53:40 -0500289 currFrameNumber >= mLastAcquiredFrameNumber) {
290 mWaitForTransactionCallback = false;
291 flushShadowQueue();
292 }
293 } else {
chaviw768bfa02021-11-01 09:50:57 -0500294 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500295 }
296 } else {
297 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
298 "empty.");
299 }
300
301 decStrong((void*)transactionCommittedCallbackThunk);
302 }
303}
304
Robert Carr78c25dd2019-08-15 14:10:33 -0700305static void transactionCallbackThunk(void* context, nsecs_t latchTime,
306 const sp<Fence>& presentFence,
307 const std::vector<SurfaceControlStats>& stats) {
308 if (context == nullptr) {
309 return;
310 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800311 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700312 bq->transactionCallback(latchTime, presentFence, stats);
313}
314
315void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
316 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700317 {
318 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600319 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700320 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700321
chaviw42026162021-04-16 15:46:12 -0500322 if (!mSurfaceControlsWithPendingCallback.empty()) {
323 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
324 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500325 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
326 if (statsOptional) {
327 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500328 mTransformHint = stat.transformHint;
329 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700330 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700331 // Update frametime stamps if the frame was latched and presented, indicated by a
332 // valid latch time.
333 if (stat.latchTime > 0) {
334 mBufferItemConsumer
335 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
336 stat.frameEventStats.refreshStartTime,
337 stat.frameEventStats.gpuCompositionDoneFence,
338 stat.presentFence, stat.previousReleaseFence,
339 stat.frameEventStats.compositorTiming,
340 stat.latchTime,
341 stat.frameEventStats.dequeueReadyTime);
342 }
chaviwd7deef72021-10-06 11:53:40 -0500343 } else {
chaviw768bfa02021-11-01 09:50:57 -0500344 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500345 }
346 } else {
347 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
348 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800349 }
chaviw71c2cc42020-10-23 16:42:02 -0700350
chaviw71c2cc42020-10-23 16:42:02 -0700351 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700352 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700353}
354
Vishnu Nair1506b182021-02-22 14:35:15 -0800355// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
356// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
357// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
358// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700359static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500360 const sp<Fence>& releaseFence,
361 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800362 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800363 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500364 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700365 } else {
366 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800367 }
368}
369
chaviwd7deef72021-10-06 11:53:40 -0500370void BLASTBufferQueue::flushShadowQueue() {
371 BQA_LOGV("flushShadowQueue");
372 int numFramesToFlush = mNumFrameAvailable;
373 while (numFramesToFlush > 0) {
374 acquireNextBufferLocked(std::nullopt);
375 numFramesToFlush--;
376 }
377}
378
chaviw69058fb2021-09-27 09:37:30 -0500379void BLASTBufferQueue::releaseBufferCallback(
380 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
381 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
chaviw57ae4b22022-02-03 16:51:39 -0600382 BBQ_TRACE();
Vishnu Nair1506b182021-02-22 14:35:15 -0800383 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700384 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800385
Ady Abraham899dcdb2021-06-15 16:56:21 -0700386 // Calculate how many buffers we need to hold before we release them back
387 // to the buffer queue. This will prevent higher latency when we are running
388 // on a lower refresh rate than the max supported. We only do that for EGL
389 // clients as others don't care about latency
390 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700391 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700392 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
393 }();
394
chaviw69058fb2021-09-27 09:37:30 -0500395 if (currentMaxAcquiredBufferCount) {
396 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
397 }
398
Ady Abraham899dcdb2021-06-15 16:56:21 -0700399 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500400 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700401 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700402
403 // Release all buffers that are beyond the ones that we need to hold
404 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500405 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700406 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500407 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwd7deef72021-10-06 11:53:40 -0500408 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
chaviwa1c4c822021-11-10 18:11:58 -0600409 // onFrameAvailable handle processing them since it will merge with the syncTransaction.
chaviwd7deef72021-10-06 11:53:40 -0500410 if (!mWaitForTransactionCallback) {
411 acquireNextBufferLocked(std::nullopt);
412 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800413 }
414
Ady Abraham899dcdb2021-06-15 16:56:21 -0700415 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700416 ATRACE_INT(mQueuedBufferTrace.c_str(),
417 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800418 mCallbackCV.notify_all();
419}
420
chaviw0acd33a2021-11-02 11:55:37 -0500421void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
422 const sp<Fence>& releaseFence) {
423 auto it = mSubmitted.find(callbackId);
424 if (it == mSubmitted.end()) {
425 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
426 callbackId.to_string().c_str());
427 return;
428 }
429 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600430 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500431 BQA_LOGV("released %s", callbackId.to_string().c_str());
432 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
433 mSubmitted.erase(it);
434}
435
chaviwd7deef72021-10-06 11:53:40 -0500436void BLASTBufferQueue::acquireNextBufferLocked(
437 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800438 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
439 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500440 const bool includeExtraAcquire = !transaction;
441 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
442 if (mNumFrameAvailable == 0 || maxAcquired) {
443 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800444 return;
445 }
446
Valerie Haua32c5522019-12-09 10:11:08 -0800447 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700448 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800449 return;
450 }
451
Robert Carr78c25dd2019-08-15 14:10:33 -0700452 SurfaceComposerClient::Transaction localTransaction;
453 bool applyTransaction = true;
454 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500455 if (transaction) {
456 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700457 applyTransaction = false;
458 }
459
Valerie Haua32c5522019-12-09 10:11:08 -0800460 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800461
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800462 status_t status =
463 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800464 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
465 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
466 return;
467 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700468 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700469 return;
470 }
chaviw57ae4b22022-02-03 16:51:39 -0600471
Valerie Haua32c5522019-12-09 10:11:08 -0800472 auto buffer = bufferItem.mGraphicBuffer;
473 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600474 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800475
476 if (buffer == nullptr) {
477 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700478 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800479 return;
480 }
481
Vishnu Nair670b3f72020-09-29 17:52:18 -0700482 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700483 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800484 "buffer{size=%dx%d transform=%d}",
485 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
486 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
487 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500488 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800489 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700490 }
491
Valerie Haua32c5522019-12-09 10:11:08 -0800492 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700493 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
494 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
495 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700496
Valerie Hau871d6352020-01-29 08:44:02 -0800497 bool needsDisconnect = false;
498 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
499
500 // if producer disconnected before, notify SurfaceFlinger
501 if (needsDisconnect) {
502 t->notifyProducerDisconnect(mSurfaceControl);
503 }
504
Robert Carr78c25dd2019-08-15 14:10:33 -0700505 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
506 incStrong((void*)transactionCallbackThunk);
507
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700508 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700509 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000510 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
511 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700512 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800513
Vishnu Nair1506b182021-02-22 14:35:15 -0800514 auto releaseBufferCallback =
515 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500516 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500517 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600518 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500519 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
520 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
521 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700522 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600523
chaviw42026162021-04-16 15:46:12 -0500524 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700525
Vishnu Naird2aaab12022-02-10 14:49:09 -0800526 if (mUpdateDestinationFrame) {
527 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
528 } else {
529 const bool ignoreDestinationFrame =
530 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
531 t->setFlags(mSurfaceControl,
532 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
533 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700534 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700535 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800536 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800537 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800538 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800539 if (!bufferItem.mIsAutoTimestamp) {
540 t->setDesiredPresentTime(bufferItem.mTimestamp);
541 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700542
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000543 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700544 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000545 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100546 }
547
Vishnu Nairadf632b2021-01-07 14:05:08 -0800548 {
549 std::unique_lock _lock{mTimestampMutex};
550 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
551 if (dequeueTime != mDequeueTimestamps.end()) {
552 Parcel p;
553 p.writeInt64(dequeueTime->second);
554 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
555 mDequeueTimestamps.erase(dequeueTime);
556 }
557 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800558
chaviw6a195272021-09-03 16:14:25 -0500559 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700560 if (applyTransaction) {
Robert Carr79dc06a2022-02-22 15:28:59 -0800561 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
562 t->setApplyToken(mApplyToken).apply(false, true);
563 mAppliedLastTransaction = true;
564 mLastAppliedFrameNumber = bufferItem.mFrameNumber;
565 } else {
566 t->setBufferHasBarrier(mSurfaceControl, mLastAppliedFrameNumber);
567 mAppliedLastTransaction = false;
Robert Carr78c25dd2019-08-15 14:10:33 -0700568 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700569
chaviwd7deef72021-10-06 11:53:40 -0500570 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800571 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700572 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500573 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800574 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700575 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700576 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700577}
578
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800579Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
580 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800581 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800582 }
583 return item.mCrop;
584}
585
chaviwd7deef72021-10-06 11:53:40 -0500586void BLASTBufferQueue::acquireAndReleaseBuffer() {
587 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500588 status_t status =
589 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
590 if (status != OK) {
591 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
592 statusToString(status).c_str());
593 return;
594 }
chaviwd7deef72021-10-06 11:53:40 -0500595 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500596 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500597}
598
chaviw0acd33a2021-11-02 11:55:37 -0500599void BLASTBufferQueue::flushAndWaitForFreeBuffer(std::unique_lock<std::mutex>& lock) {
600 if (mWaitForTransactionCallback && mNumFrameAvailable > 0) {
601 // We are waiting on a previous sync's transaction callback so allow another sync
602 // transaction to proceed.
603 //
604 // We need to first flush out the transactions that were in between the two syncs.
605 // We do this by merging them into mSyncTransaction so any buffer merging will get
606 // a release callback invoked. The release callback will be async so we need to wait
607 // on max acquired to make sure we have the capacity to acquire another buffer.
608 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
609 BQA_LOGD("waiting to flush shadow queue...");
610 mCallbackCV.wait(lock);
611 }
612 while (mNumFrameAvailable > 0) {
613 // flush out the shadow queue
614 acquireAndReleaseBuffer();
615 }
616 }
617
618 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
619 BQA_LOGD("waiting for free buffer.");
620 mCallbackCV.wait(lock);
621 }
622}
623
Vishnu Nairaef1de92020-10-22 12:15:53 -0700624void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Tianhao Yao4861b102022-02-03 20:18:35 +0000625 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
626 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
627 {
628 BBQ_TRACE();
629 std::unique_lock _lock{mMutex};
630 const bool syncTransactionSet = mTransactionReadyCallback != nullptr;
631 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
Valerie Haud3b90d22019-11-06 09:37:31 -0800632
Tianhao Yao4861b102022-02-03 20:18:35 +0000633 if (syncTransactionSet) {
634 bool mayNeedToWaitForBuffer = true;
635 // If we are going to re-use the same mSyncTransaction, release the buffer that may
636 // already be set in the Transaction. This is to allow us a free slot early to continue
637 // processing a new buffer.
638 if (!mAcquireSingleBuffer) {
639 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
640 if (bufferData) {
641 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
642 bufferData->frameNumber);
643 releaseBuffer(bufferData->generateReleaseCallbackId(),
644 bufferData->acquireFence);
645 // Because we just released a buffer, we know there's no need to wait for a free
646 // buffer.
647 mayNeedToWaitForBuffer = false;
648 }
649 }
chaviw0acd33a2021-11-02 11:55:37 -0500650
Tianhao Yao4861b102022-02-03 20:18:35 +0000651 if (mayNeedToWaitForBuffer) {
652 flushAndWaitForFreeBuffer(_lock);
chaviwd7deef72021-10-06 11:53:40 -0500653 }
654 }
655
Tianhao Yao4861b102022-02-03 20:18:35 +0000656 // add to shadow queue
657 mNumFrameAvailable++;
658 if (mWaitForTransactionCallback && mNumFrameAvailable >= 2) {
659 acquireAndReleaseBuffer();
660 }
661 ATRACE_INT(mQueuedBufferTrace.c_str(),
662 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
663
664 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s",
665 item.mFrameNumber, boolToString(syncTransactionSet));
666
667 if (syncTransactionSet) {
668 acquireNextBufferLocked(mSyncTransaction);
669
670 // Only need a commit callback when syncing to ensure the buffer that's synced has been
671 // sent to SF
672 incStrong((void*)transactionCommittedCallbackThunk);
673 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
674 static_cast<void*>(this));
675 mWaitForTransactionCallback = true;
676 if (mAcquireSingleBuffer) {
677 prevCallback = mTransactionReadyCallback;
678 prevTransaction = mSyncTransaction;
679 mTransactionReadyCallback = nullptr;
680 mSyncTransaction = nullptr;
681 }
682 } else if (!mWaitForTransactionCallback) {
683 acquireNextBufferLocked(std::nullopt);
Valerie Hau0188adf2020-02-13 08:29:20 -0800684 }
685 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000686 if (prevCallback) {
687 prevCallback(prevTransaction);
chaviwd7deef72021-10-06 11:53:40 -0500688 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800689}
690
Vishnu Nairaef1de92020-10-22 12:15:53 -0700691void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
692 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
693 // Do nothing since we are not storing unacquired buffer items locally.
694}
695
Vishnu Nairadf632b2021-01-07 14:05:08 -0800696void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
697 std::unique_lock _lock{mTimestampMutex};
698 mDequeueTimestamps[bufferId] = systemTime();
699};
700
701void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
702 std::unique_lock _lock{mTimestampMutex};
703 mDequeueTimestamps.erase(bufferId);
704};
705
Tianhao Yao4861b102022-02-03 20:18:35 +0000706void BLASTBufferQueue::syncNextTransaction(
707 std::function<void(SurfaceComposerClient::Transaction*)> callback,
708 bool acquireSingleBuffer) {
chaviw57ae4b22022-02-03 16:51:39 -0600709 BBQ_TRACE();
chaviw3b4bdcf2022-03-17 09:27:03 -0500710
711 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
712 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
713
714 {
715 std::lock_guard _lock{mMutex};
716 // We're about to overwrite the previous call so we should invoke that callback
717 // immediately.
718 if (mTransactionReadyCallback) {
719 prevCallback = mTransactionReadyCallback;
720 prevTransaction = mSyncTransaction;
721 }
722
723 mTransactionReadyCallback = callback;
724 if (callback) {
725 mSyncTransaction = new SurfaceComposerClient::Transaction();
726 } else {
727 mSyncTransaction = nullptr;
728 }
729 mAcquireSingleBuffer = mTransactionReadyCallback ? acquireSingleBuffer : true;
Tianhao Yao4861b102022-02-03 20:18:35 +0000730 }
chaviw3b4bdcf2022-03-17 09:27:03 -0500731
732 if (prevCallback) {
733 prevCallback(prevTransaction);
734 }
Tianhao Yao4861b102022-02-03 20:18:35 +0000735}
736
737void BLASTBufferQueue::stopContinuousSyncTransaction() {
738 std::function<void(SurfaceComposerClient::Transaction*)> prevCallback = nullptr;
739 SurfaceComposerClient::Transaction* prevTransaction = nullptr;
740 {
741 std::lock_guard _lock{mMutex};
742 bool invokeCallback = mTransactionReadyCallback && !mAcquireSingleBuffer;
743 if (invokeCallback) {
744 prevCallback = mTransactionReadyCallback;
745 prevTransaction = mSyncTransaction;
746 }
747 mTransactionReadyCallback = nullptr;
748 mSyncTransaction = nullptr;
749 mAcquireSingleBuffer = true;
750 }
751 if (prevCallback) {
752 prevCallback(prevTransaction);
753 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700754}
755
Vishnu Nairea0de002020-11-17 17:42:37 -0800756bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700757 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
758 // Only reject buffers if scaling mode is freeze.
759 return false;
760 }
761
Vishnu Naire1a42322020-10-02 17:42:04 -0700762 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
763 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
764
765 // Take the buffer's orientation into account
766 if (item.mTransform & ui::Transform::ROT_90) {
767 std::swap(bufWidth, bufHeight);
768 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800769 ui::Size bufferSize(bufWidth, bufHeight);
770 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800771 return false;
772 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700773
Vishnu Nair670b3f72020-09-29 17:52:18 -0700774 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800775 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700776}
Vishnu Nairbf255772020-10-16 10:54:41 -0700777
778// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800779// Consumer can acquire an additional buffer if that buffer is not droppable. Set
780// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
781// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
782bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700783 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800784 return mNumAcquired >= maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700785}
786
Robert Carr05086b22020-10-13 18:22:51 -0700787class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700788private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700789 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700790 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700791 bool mDestroyed = false;
792
Robert Carr05086b22020-10-13 18:22:51 -0700793public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700794 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
795 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
796 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700797
Robert Carr05086b22020-10-13 18:22:51 -0700798 void allocateBuffers() override {
799 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
800 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
801 auto gbp = getIGraphicBufferProducer();
802 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
803 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
804 gbp->allocateBuffers(reqWidth, reqHeight,
805 reqFormat, reqUsage);
806
807 }).detach();
808 }
Robert Carr9c006e02020-10-14 13:41:57 -0700809
Marin Shalamanovc5986772021-03-16 16:09:49 +0100810 status_t setFrameRate(float frameRate, int8_t compatibility,
811 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700812 std::unique_lock _lock{mMutex};
813 if (mDestroyed) {
814 return DEAD_OBJECT;
815 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100816 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
817 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700818 return BAD_VALUE;
819 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100820 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700821 }
Robert Carr9b611b72020-10-19 12:00:23 -0700822
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000823 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700824 std::unique_lock _lock{mMutex};
825 if (mDestroyed) {
826 return DEAD_OBJECT;
827 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000828 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700829 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700830
831 void destroy() override {
832 Surface::destroy();
833
834 std::unique_lock _lock{mMutex};
835 mDestroyed = true;
836 mBbq = nullptr;
837 }
Robert Carr05086b22020-10-13 18:22:51 -0700838};
839
Robert Carr9c006e02020-10-14 13:41:57 -0700840// TODO: Can we coalesce this with frame updates? Need to confirm
841// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200842status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
843 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700844 std::unique_lock _lock{mMutex};
845 SurfaceComposerClient::Transaction t;
846
Marin Shalamanov46084422020-10-13 12:33:42 +0200847 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700848}
849
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000850status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700851 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000852 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100853 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700854}
855
Hongguang Chen621ec582021-02-16 15:42:35 -0800856void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
857 std::unique_lock _lock{mMutex};
858 SurfaceComposerClient::Transaction t;
859
860 t.setSidebandStream(mSurfaceControl, stream).apply();
861}
862
Vishnu Nair992496b2020-10-22 17:27:21 -0700863sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
864 std::unique_lock _lock{mMutex};
865 sp<IBinder> scHandle = nullptr;
866 if (includeSurfaceControlHandle && mSurfaceControl) {
867 scHandle = mSurfaceControl->getHandle();
868 }
869 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700870}
871
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800872void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
873 uint64_t frameNumber) {
874 std::lock_guard _lock{mMutex};
875 if (mLastAcquiredFrameNumber >= frameNumber) {
876 // Apply the transaction since we have already acquired the desired frame.
877 t->apply();
878 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500879 mPendingTransactions.emplace_back(frameNumber, *t);
880 // Clear the transaction so it can't be applied elsewhere.
881 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800882 }
883}
884
chaviw6a195272021-09-03 16:14:25 -0500885void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
886 std::lock_guard _lock{mMutex};
887
888 SurfaceComposerClient::Transaction t;
889 mergePendingTransactions(&t, frameNumber);
Robert Carr79dc06a2022-02-22 15:28:59 -0800890 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
891 t.setApplyToken(mApplyToken).apply(false, true);
chaviw6a195272021-09-03 16:14:25 -0500892}
893
894void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
895 uint64_t frameNumber) {
896 auto mergeTransaction =
897 [&t, currentFrameNumber = frameNumber](
898 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
899 auto& [targetFrameNumber, transaction] = pendingTransaction;
900 if (currentFrameNumber < targetFrameNumber) {
901 return false;
902 }
903 t->merge(std::move(transaction));
904 return true;
905 };
906
907 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
908 mPendingTransactions.end(), mergeTransaction),
909 mPendingTransactions.end());
910}
911
chaviwd84085a2022-02-08 11:07:04 -0600912SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
913 uint64_t frameNumber) {
914 std::lock_guard _lock{mMutex};
915 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
916 mergePendingTransactions(t, frameNumber);
917 return t;
918}
919
Vishnu Nair89496122020-12-14 17:14:53 -0800920// Maintains a single worker thread per process that services a list of runnables.
921class AsyncWorker : public Singleton<AsyncWorker> {
922private:
923 std::thread mThread;
924 bool mDone = false;
925 std::deque<std::function<void()>> mRunnables;
926 std::mutex mMutex;
927 std::condition_variable mCv;
928 void run() {
929 std::unique_lock<std::mutex> lock(mMutex);
930 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800931 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700932 std::deque<std::function<void()>> runnables = std::move(mRunnables);
933 mRunnables.clear();
934 lock.unlock();
935 // Run outside the lock since the runnable might trigger another
936 // post to the async worker.
937 execute(runnables);
938 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800939 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700940 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800941 }
942 }
943
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700944 void execute(std::deque<std::function<void()>>& runnables) {
945 while (!runnables.empty()) {
946 std::function<void()> runnable = runnables.front();
947 runnables.pop_front();
948 runnable();
949 }
950 }
951
Vishnu Nair89496122020-12-14 17:14:53 -0800952public:
953 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
954
955 ~AsyncWorker() {
956 mDone = true;
957 mCv.notify_all();
958 if (mThread.joinable()) {
959 mThread.join();
960 }
961 }
962
963 void post(std::function<void()> runnable) {
964 std::unique_lock<std::mutex> lock(mMutex);
965 mRunnables.emplace_back(std::move(runnable));
966 mCv.notify_one();
967 }
968};
969ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
970
971// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
972class AsyncProducerListener : public BnProducerListener {
973private:
974 const sp<IProducerListener> mListener;
975
976public:
977 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
978
979 void onBufferReleased() override {
980 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
981 }
982
983 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
984 AsyncWorker::getInstance().post(
985 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
986 }
987};
988
989// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
990// can be non-blocking when the producer is in the client process.
991class BBQBufferQueueProducer : public BufferQueueProducer {
992public:
993 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
994 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
995
996 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
997 QueueBufferOutput* output) override {
998 if (!listener) {
999 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
1000 }
1001
1002 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
1003 producerControlledByApp, output);
1004 }
Vishnu Nair17dde612020-12-28 11:39:59 -08001005
1006 int query(int what, int* value) override {
1007 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
1008 *value = 1;
1009 return NO_ERROR;
1010 }
1011 return BufferQueueProducer::query(what, value);
1012 }
Vishnu Nair89496122020-12-14 17:14:53 -08001013};
1014
1015// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
1016// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
1017// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
1018// we can deadlock.
1019void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
1020 sp<IGraphicBufferConsumer>* outConsumer) {
1021 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
1022 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
1023
1024 sp<BufferQueueCore> core(new BufferQueueCore());
1025 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
1026
1027 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
1028 LOG_ALWAYS_FATAL_IF(producer == nullptr,
1029 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
1030
Vishnu Nair8b30dd12021-01-25 14:16:54 -08001031 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
1032 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -08001033 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
1034 "BLASTBufferQueue: failed to create BufferQueueConsumer");
1035
1036 *outProducer = producer;
1037 *outConsumer = consumer;
1038}
1039
chaviw497e81c2021-02-04 17:09:47 -08001040PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
1041 PixelFormat convertedFormat = format;
1042 switch (format) {
1043 case PIXEL_FORMAT_TRANSPARENT:
1044 case PIXEL_FORMAT_TRANSLUCENT:
1045 convertedFormat = PIXEL_FORMAT_RGBA_8888;
1046 break;
1047 case PIXEL_FORMAT_OPAQUE:
1048 convertedFormat = PIXEL_FORMAT_RGBX_8888;
1049 break;
1050 }
1051 return convertedFormat;
1052}
1053
Robert Carr82d07c92021-05-10 11:36:43 -07001054uint32_t BLASTBufferQueue::getLastTransformHint() const {
1055 if (mSurfaceControl != nullptr) {
1056 return mSurfaceControl->getTransformHint();
1057 } else {
1058 return 0;
1059 }
1060}
1061
chaviw0b020f82021-08-20 12:00:47 -05001062uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
1063 std::unique_lock _lock{mMutex};
1064 return mLastAcquiredFrameNumber;
1065}
1066
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001067void BLASTBufferQueue::abandon() {
1068 std::unique_lock _lock{mMutex};
1069 // flush out the shadow queue
1070 while (mNumFrameAvailable > 0) {
1071 acquireAndReleaseBuffer();
1072 }
1073
1074 // Clear submitted buffer states
1075 mNumAcquired = 0;
1076 mSubmitted.clear();
1077 mPendingRelease.clear();
1078
1079 if (!mPendingTransactions.empty()) {
1080 BQA_LOGD("Applying pending transactions on abandon %d",
1081 static_cast<uint32_t>(mPendingTransactions.size()));
1082 SurfaceComposerClient::Transaction t;
1083 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
Robert Carr79dc06a2022-02-22 15:28:59 -08001084 // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
1085 t.setApplyToken(mApplyToken).apply(false, true);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001086 }
1087
1088 // Clear sync states
1089 if (mWaitForTransactionCallback) {
1090 BQA_LOGD("mWaitForTransactionCallback cleared");
1091 mWaitForTransactionCallback = false;
1092 }
1093
1094 if (mSyncTransaction != nullptr) {
1095 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1096 mAcquireSingleBuffer ? "true" : "false");
1097 mSyncTransaction = nullptr;
1098 mAcquireSingleBuffer = false;
1099 }
1100
1101 // abandon buffer queue
1102 if (mBufferItemConsumer != nullptr) {
1103 mBufferItemConsumer->abandon();
1104 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1105 mBufferItemConsumer->setBufferFreedListener(nullptr);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001106 }
1107 mBufferItemConsumer = nullptr;
1108 mConsumer = nullptr;
1109 mProducer = nullptr;
1110}
1111
1112bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1113 std::unique_lock _lock{mMutex};
1114 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1115}
1116
Robert Carr78c25dd2019-08-15 14:10:33 -07001117} // namespace android