blob: a726fee66d98bd208a592228bbeb3cb23181c756 [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>
Vishnu Nair89496122020-12-14 17:14:53 -080031#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080032#include <utils/Trace.h>
33
Ady Abraham0bde6b52021-05-18 13:57:02 -070034#include <private/gui/ComposerService.h>
35
Robert Carr78c25dd2019-08-15 14:10:33 -070036#include <chrono>
37
38using namespace std::chrono_literals;
39
Vishnu Nairdab94092020-09-29 16:09:04 -070040namespace {
chaviw3277faf2021-05-19 16:45:23 -050041inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070042 return b ? "true" : "false";
43}
44} // namespace
45
Robert Carr78c25dd2019-08-15 14:10:33 -070046namespace android {
47
Vishnu Nairdab94092020-09-29 16:09:04 -070048// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050049#define BQA_LOGD(x, ...) \
50 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070051#define BQA_LOGV(x, ...) \
52 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080053// enable logs for a single layer
54//#define BQA_LOGV(x, ...) \
55// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
56// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070057#define BQA_LOGE(x, ...) \
58 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
59
Valerie Hau871d6352020-01-29 08:44:02 -080060void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000061 Mutex::Autolock lock(mMutex);
62 mPreviouslyConnected = mCurrentlyConnected;
63 mCurrentlyConnected = false;
64 if (mPreviouslyConnected) {
65 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080066 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000067 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080068}
69
70void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
71 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080072 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080073 if (newTimestamps) {
74 // BufferQueueProducer only adds a new timestamp on
75 // queueBuffer
76 mCurrentFrameNumber = newTimestamps->frameNumber;
77 mFrameEventHistory.addQueue(*newTimestamps);
78 }
79 if (outDelta) {
80 // frame event histories will be processed
81 // only after the producer connects and requests
82 // deltas for the first time. Forward this intent
83 // to SF-side to turn event processing back on
84 mPreviouslyConnected = mCurrentlyConnected;
85 mCurrentlyConnected = true;
86 mFrameEventHistory.getAndResetDelta(outDelta);
87 }
88}
89
90void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
91 const sp<Fence>& glDoneFence,
92 const sp<Fence>& presentFence,
93 const sp<Fence>& prevReleaseFence,
94 CompositorTiming compositorTiming,
95 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -080096 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080097
98 // if the producer is not connected, don't bother updating,
99 // the next producer that connects won't access this frame event
100 if (!mCurrentlyConnected) return;
101 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
102 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
103 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
104
105 mFrameEventHistory.addLatch(frameNumber, latchTime);
106 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
107 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
108 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
109 compositorTiming);
110}
111
112void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
113 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800114 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800115 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
116 disconnect = true;
117 mDisconnectEvents.pop();
118 }
119 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
120}
121
Hongguang Chen621ec582021-02-16 15:42:35 -0800122void BLASTBufferItemConsumer::setBlastBufferQueue(BLASTBufferQueue* blastbufferqueue) {
Alec Mouri5c8b18c2021-08-19 16:52:34 -0700123 std::scoped_lock lock(mBufferQueueMutex);
Hongguang Chen621ec582021-02-16 15:42:35 -0800124 mBLASTBufferQueue = blastbufferqueue;
125}
126
127void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Alec Mouri5c8b18c2021-08-19 16:52:34 -0700128 std::scoped_lock lock(mBufferQueueMutex);
Hongguang Chen621ec582021-02-16 15:42:35 -0800129 if (mBLASTBufferQueue != nullptr) {
130 sp<NativeHandle> stream = getSidebandStream();
131 mBLASTBufferQueue->setSidebandStream(stream);
132 }
133}
134
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800135BLASTBufferQueue::BLASTBufferQueue(const std::string& name)
136 : 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),
chaviwa1c4c822021-11-10 18:11:58 -0600140 mSyncTransaction(nullptr) {
Vishnu Nair89496122020-12-14 17:14:53 -0800141 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800142 // since the adapter is in the client process, set dequeue timeout
143 // explicitly so that dequeueBuffer will block
144 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800145
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700146 // safe default, most producers are expected to override this
147 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800148 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
149 GraphicBuffer::USAGE_HW_COMPOSER |
150 GraphicBuffer::USAGE_HW_TEXTURE,
151 1, false);
Valerie Haua32c5522019-12-09 10:11:08 -0800152 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700153 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700154 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700155 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800156 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700157 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700158 mBufferItemConsumer->setFrameAvailableListener(this);
159 mBufferItemConsumer->setBufferFreedListener(this);
Hongguang Chen621ec582021-02-16 15:42:35 -0800160 mBufferItemConsumer->setBlastBufferQueue(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700161
Ady Abraham899dcdb2021-06-15 16:56:21 -0700162 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700163 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
chaviw69058fb2021-09-27 09:37:30 -0500164 mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;
Valerie Haua32c5522019-12-09 10:11:08 -0800165 mNumAcquired = 0;
166 mNumFrameAvailable = 0;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800167 BQA_LOGV("BLASTBufferQueue created");
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800168}
169
170BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
171 int width, int height, int32_t format)
172 : BLASTBufferQueue(name) {
173 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700174}
175
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800176BLASTBufferQueue::~BLASTBufferQueue() {
Hongguang Chen621ec582021-02-16 15:42:35 -0800177 mBufferItemConsumer->setBlastBufferQueue(nullptr);
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800178 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 */);
185 t.setApplyToken(mApplyToken).apply();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800186}
187
chaviw565ee542021-01-14 10:21:23 -0800188void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Nair084514a2021-07-30 16:07:42 -0700189 int32_t format, SurfaceComposerClient::Transaction* outTransaction) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800190 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
191
Robert Carr78c25dd2019-08-15 14:10:33 -0700192 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800193 if (mFormat != format) {
194 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800195 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800196 }
197
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800198 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800199 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800200 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800201
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700202 // Always update the native object even though they might have the same layer handle, so we can
203 // get the updated transform hint from WM.
204 mSurfaceControl = surface;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800205 if (surfaceControlChanged) {
206 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
207 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
208 layer_state_t::eEnableBackpressure);
209 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800210 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800211 mTransformHint = mSurfaceControl->getTransformHint();
212 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700213 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
214 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800215
Vishnu Nairea0de002020-11-17 17:42:37 -0800216 ui::Size newSize(width, height);
217 if (mRequestedSize != newSize) {
218 mRequestedSize.set(newSize);
219 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000220 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800221 // If the buffer supports scaling, update the frame immediately since the client may
222 // want to scale the existing buffer to the new size.
223 mSize = mRequestedSize;
Vishnu Nair084514a2021-07-30 16:07:42 -0700224 SurfaceComposerClient::Transaction* destFrameTransaction =
225 (outTransaction) ? outTransaction : &t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800226 destFrameTransaction->setDestinationFrame(mSurfaceControl,
227 Rect(0, 0, newSize.getWidth(),
228 newSize.getHeight()));
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800229 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800230 }
Robert Carrfc416512020-04-02 12:32:44 -0700231 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800232 if (applyTransaction) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700233 t.setApplyToken(mApplyToken).apply();
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800234 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700235}
236
chaviwd7deef72021-10-06 11:53:40 -0500237static std::optional<SurfaceControlStats> findMatchingStat(
238 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
239 for (auto stat : stats) {
240 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
241 return stat;
242 }
243 }
244 return std::nullopt;
245}
246
247static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
248 const sp<Fence>& presentFence,
249 const std::vector<SurfaceControlStats>& stats) {
250 if (context == nullptr) {
251 return;
252 }
253 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
254 bq->transactionCommittedCallback(latchTime, presentFence, stats);
255}
256
257void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
258 const sp<Fence>& /*presentFence*/,
259 const std::vector<SurfaceControlStats>& stats) {
260 {
261 std::unique_lock _lock{mMutex};
262 ATRACE_CALL();
263 BQA_LOGV("transactionCommittedCallback");
264 if (!mSurfaceControlsWithPendingCallback.empty()) {
265 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
266 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
267 if (stat) {
268 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
269
270 // We need to check if we were waiting for a transaction callback in order to
271 // process any pending buffers and unblock. It's possible to get transaction
272 // callbacks for previous requests so we need to ensure the frame from this
273 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
274 // will stop processing buffers when mWaitForTransactionCallback is set, we know
275 // that mLastAcquiredFrameNumber is the frame we're waiting on.
276 // We also want to check if mNextTransaction is null because it's possible another
277 // sync request came in while waiting, but it hasn't started processing yet. In that
278 // case, we don't actually want to flush the frames in between since they will get
279 // processed and merged with the sync transaction and released earlier than if they
280 // were sent to SF
chaviwa1c4c822021-11-10 18:11:58 -0600281 if (mWaitForTransactionCallback && mSyncTransaction == nullptr &&
chaviwd7deef72021-10-06 11:53:40 -0500282 currFrameNumber >= mLastAcquiredFrameNumber) {
283 mWaitForTransactionCallback = false;
284 flushShadowQueue();
285 }
286 } else {
chaviw768bfa02021-11-01 09:50:57 -0500287 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500288 }
289 } else {
290 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
291 "empty.");
292 }
293
294 decStrong((void*)transactionCommittedCallbackThunk);
295 }
296}
297
Robert Carr78c25dd2019-08-15 14:10:33 -0700298static void transactionCallbackThunk(void* context, nsecs_t latchTime,
299 const sp<Fence>& presentFence,
300 const std::vector<SurfaceControlStats>& stats) {
301 if (context == nullptr) {
302 return;
303 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800304 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700305 bq->transactionCallback(latchTime, presentFence, stats);
306}
307
308void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
309 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700310 {
311 std::unique_lock _lock{mMutex};
312 ATRACE_CALL();
313 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700314
chaviw42026162021-04-16 15:46:12 -0500315 if (!mSurfaceControlsWithPendingCallback.empty()) {
316 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
317 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500318 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
319 if (statsOptional) {
320 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500321 mTransformHint = stat.transformHint;
322 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700323 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700324 // Update frametime stamps if the frame was latched and presented, indicated by a
325 // valid latch time.
326 if (stat.latchTime > 0) {
327 mBufferItemConsumer
328 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
329 stat.frameEventStats.refreshStartTime,
330 stat.frameEventStats.gpuCompositionDoneFence,
331 stat.presentFence, stat.previousReleaseFence,
332 stat.frameEventStats.compositorTiming,
333 stat.latchTime,
334 stat.frameEventStats.dequeueReadyTime);
335 }
chaviwd7deef72021-10-06 11:53:40 -0500336 } else {
chaviw768bfa02021-11-01 09:50:57 -0500337 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500338 }
339 } else {
340 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
341 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800342 }
chaviw71c2cc42020-10-23 16:42:02 -0700343
chaviw71c2cc42020-10-23 16:42:02 -0700344 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700345 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700346}
347
Vishnu Nair1506b182021-02-22 14:35:15 -0800348// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
349// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
350// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
351// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700352static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500353 const sp<Fence>& releaseFence,
354 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800355 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800356 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500357 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700358 } else {
359 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800360 }
361}
362
chaviwd7deef72021-10-06 11:53:40 -0500363void BLASTBufferQueue::flushShadowQueue() {
364 BQA_LOGV("flushShadowQueue");
365 int numFramesToFlush = mNumFrameAvailable;
366 while (numFramesToFlush > 0) {
367 acquireNextBufferLocked(std::nullopt);
368 numFramesToFlush--;
369 }
370}
371
chaviw69058fb2021-09-27 09:37:30 -0500372void BLASTBufferQueue::releaseBufferCallback(
373 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
374 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800375 ATRACE_CALL();
376 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700377 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800378
Ady Abraham899dcdb2021-06-15 16:56:21 -0700379 // Calculate how many buffers we need to hold before we release them back
380 // to the buffer queue. This will prevent higher latency when we are running
381 // on a lower refresh rate than the max supported. We only do that for EGL
382 // clients as others don't care about latency
383 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700384 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700385 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
386 }();
387
chaviw69058fb2021-09-27 09:37:30 -0500388 if (currentMaxAcquiredBufferCount) {
389 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
390 }
391
Ady Abraham899dcdb2021-06-15 16:56:21 -0700392 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500393 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700394 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700395
396 // Release all buffers that are beyond the ones that we need to hold
397 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500398 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700399 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500400 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwd7deef72021-10-06 11:53:40 -0500401 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
chaviwa1c4c822021-11-10 18:11:58 -0600402 // onFrameAvailable handle processing them since it will merge with the syncTransaction.
chaviwd7deef72021-10-06 11:53:40 -0500403 if (!mWaitForTransactionCallback) {
404 acquireNextBufferLocked(std::nullopt);
405 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800406 }
407
Ady Abraham899dcdb2021-06-15 16:56:21 -0700408 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700409 ATRACE_INT(mQueuedBufferTrace.c_str(),
410 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800411 mCallbackCV.notify_all();
412}
413
chaviw0acd33a2021-11-02 11:55:37 -0500414void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
415 const sp<Fence>& releaseFence) {
416 auto it = mSubmitted.find(callbackId);
417 if (it == mSubmitted.end()) {
418 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
419 callbackId.to_string().c_str());
420 return;
421 }
422 mNumAcquired--;
423 BQA_LOGV("released %s", callbackId.to_string().c_str());
424 mBufferItemConsumer->releaseBuffer(it->second, releaseFence);
425 mSubmitted.erase(it);
426}
427
chaviwd7deef72021-10-06 11:53:40 -0500428void BLASTBufferQueue::acquireNextBufferLocked(
429 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800430 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800431 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
432 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500433 const bool includeExtraAcquire = !transaction;
434 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
435 if (mNumFrameAvailable == 0 || maxAcquired) {
436 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800437 return;
438 }
439
Valerie Haua32c5522019-12-09 10:11:08 -0800440 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700441 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800442 return;
443 }
444
Robert Carr78c25dd2019-08-15 14:10:33 -0700445 SurfaceComposerClient::Transaction localTransaction;
446 bool applyTransaction = true;
447 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500448 if (transaction) {
449 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700450 applyTransaction = false;
451 }
452
Valerie Haua32c5522019-12-09 10:11:08 -0800453 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800454
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800455 status_t status =
456 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800457 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
458 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
459 return;
460 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700461 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700462 return;
463 }
Valerie Haua32c5522019-12-09 10:11:08 -0800464 auto buffer = bufferItem.mGraphicBuffer;
465 mNumFrameAvailable--;
466
467 if (buffer == nullptr) {
468 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700469 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800470 return;
471 }
472
Vishnu Nair670b3f72020-09-29 17:52:18 -0700473 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700474 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800475 "buffer{size=%dx%d transform=%d}",
476 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
477 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
478 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500479 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800480 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700481 }
482
Valerie Haua32c5522019-12-09 10:11:08 -0800483 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700484 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
485 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
486 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700487
Valerie Hau871d6352020-01-29 08:44:02 -0800488 bool needsDisconnect = false;
489 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
490
491 // if producer disconnected before, notify SurfaceFlinger
492 if (needsDisconnect) {
493 t->notifyProducerDisconnect(mSurfaceControl);
494 }
495
Robert Carr78c25dd2019-08-15 14:10:33 -0700496 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
497 incStrong((void*)transactionCallbackThunk);
498
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800499 const bool updateDestinationFrame = mRequestedSize != mSize;
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700500 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700501 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000502 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
503 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700504 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800505
Vishnu Nair1506b182021-02-22 14:35:15 -0800506 auto releaseBufferCallback =
507 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
chaviw69058fb2021-09-27 09:37:30 -0500508 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
chaviwba4320c2021-09-15 15:20:53 -0500509 sp<Fence> fence = bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE;
chaviw8dd181f2022-01-05 18:36:46 -0600510 t->setBuffer(mSurfaceControl, buffer, fence, bufferItem.mFrameNumber, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500511 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
512 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
513 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700514 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviwf2dace72021-11-17 17:36:50 -0600515
chaviw42026162021-04-16 15:46:12 -0500516 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700517
Vishnu Nair084514a2021-07-30 16:07:42 -0700518 if (updateDestinationFrame) {
519 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
520 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700521 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800522 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800523 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800524 if (!bufferItem.mIsAutoTimestamp) {
525 t->setDesiredPresentTime(bufferItem.mTimestamp);
526 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700527
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000528 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700529 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000530 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100531 }
532
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800533 if (mAutoRefresh != bufferItem.mAutoRefresh) {
534 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
535 mAutoRefresh = bufferItem.mAutoRefresh;
536 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800537 {
538 std::unique_lock _lock{mTimestampMutex};
539 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
540 if (dequeueTime != mDequeueTimestamps.end()) {
541 Parcel p;
542 p.writeInt64(dequeueTime->second);
543 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
544 mDequeueTimestamps.erase(dequeueTime);
545 }
546 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800547
chaviw6a195272021-09-03 16:14:25 -0500548 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700549 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800550 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700551 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700552
chaviwd7deef72021-10-06 11:53:40 -0500553 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800554 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700555 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500556 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800557 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700558 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700559 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700560}
561
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800562Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
563 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800564 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800565 }
566 return item.mCrop;
567}
568
chaviwd7deef72021-10-06 11:53:40 -0500569void BLASTBufferQueue::acquireAndReleaseBuffer() {
570 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500571 status_t status =
572 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
573 if (status != OK) {
574 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
575 statusToString(status).c_str());
576 return;
577 }
chaviwd7deef72021-10-06 11:53:40 -0500578 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500579 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500580}
581
chaviw0acd33a2021-11-02 11:55:37 -0500582void BLASTBufferQueue::flushAndWaitForFreeBuffer(std::unique_lock<std::mutex>& lock) {
583 if (mWaitForTransactionCallback && mNumFrameAvailable > 0) {
584 // We are waiting on a previous sync's transaction callback so allow another sync
585 // transaction to proceed.
586 //
587 // We need to first flush out the transactions that were in between the two syncs.
588 // We do this by merging them into mSyncTransaction so any buffer merging will get
589 // a release callback invoked. The release callback will be async so we need to wait
590 // on max acquired to make sure we have the capacity to acquire another buffer.
591 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
592 BQA_LOGD("waiting to flush shadow queue...");
593 mCallbackCV.wait(lock);
594 }
595 while (mNumFrameAvailable > 0) {
596 // flush out the shadow queue
597 acquireAndReleaseBuffer();
598 }
599 }
600
601 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
602 BQA_LOGD("waiting for free buffer.");
603 mCallbackCV.wait(lock);
604 }
605}
606
Vishnu Nairaef1de92020-10-22 12:15:53 -0700607void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800608 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800609 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800610
chaviwa1c4c822021-11-10 18:11:58 -0600611 const bool syncTransactionSet = mSyncTransaction != nullptr;
612 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
chaviw0acd33a2021-11-02 11:55:37 -0500613
chaviwa1c4c822021-11-10 18:11:58 -0600614 if (syncTransactionSet) {
chaviw0acd33a2021-11-02 11:55:37 -0500615 bool mayNeedToWaitForBuffer = true;
616 // If we are going to re-use the same mSyncTransaction, release the buffer that may already
617 // be set in the Transaction. This is to allow us a free slot early to continue processing
618 // a new buffer.
619 if (!mAcquireSingleBuffer) {
620 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
621 if (bufferData) {
622 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
623 bufferData->frameNumber);
chaviw8dd181f2022-01-05 18:36:46 -0600624 releaseBuffer(bufferData->generateReleaseCallbackId(), bufferData->acquireFence);
chaviw0acd33a2021-11-02 11:55:37 -0500625 // Because we just released a buffer, we know there's no need to wait for a free
626 // buffer.
627 mayNeedToWaitForBuffer = false;
chaviwd7deef72021-10-06 11:53:40 -0500628 }
629 }
630
chaviw0acd33a2021-11-02 11:55:37 -0500631 if (mayNeedToWaitForBuffer) {
632 flushAndWaitForFreeBuffer(_lock);
Valerie Hau0188adf2020-02-13 08:29:20 -0800633 }
634 }
chaviwd7deef72021-10-06 11:53:40 -0500635
Valerie Haud3b90d22019-11-06 09:37:31 -0800636 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800637 mNumFrameAvailable++;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800638 if (mWaitForTransactionCallback && mNumFrameAvailable >= 2) {
Robert Carrcf2f21f2021-11-30 14:47:02 -0800639 acquireAndReleaseBuffer();
640 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700641 ATRACE_INT(mQueuedBufferTrace.c_str(),
642 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800643
chaviwa1c4c822021-11-10 18:11:58 -0600644 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s", item.mFrameNumber,
645 boolToString(syncTransactionSet));
chaviwd7deef72021-10-06 11:53:40 -0500646
chaviwa1c4c822021-11-10 18:11:58 -0600647 if (syncTransactionSet) {
chaviw0acd33a2021-11-02 11:55:37 -0500648 acquireNextBufferLocked(mSyncTransaction);
chaviwf2dace72021-11-17 17:36:50 -0600649
650 // Only need a commit callback when syncing to ensure the buffer that's synced has been sent
651 // to SF
652 incStrong((void*)transactionCommittedCallbackThunk);
653 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
654 static_cast<void*>(this));
655
chaviw0acd33a2021-11-02 11:55:37 -0500656 if (mAcquireSingleBuffer) {
657 mSyncTransaction = nullptr;
658 }
chaviwd7deef72021-10-06 11:53:40 -0500659 mWaitForTransactionCallback = true;
660 } else if (!mWaitForTransactionCallback) {
661 acquireNextBufferLocked(std::nullopt);
662 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800663}
664
Vishnu Nairaef1de92020-10-22 12:15:53 -0700665void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
666 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
667 // Do nothing since we are not storing unacquired buffer items locally.
668}
669
Vishnu Nairadf632b2021-01-07 14:05:08 -0800670void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
671 std::unique_lock _lock{mTimestampMutex};
672 mDequeueTimestamps[bufferId] = systemTime();
673};
674
675void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
676 std::unique_lock _lock{mTimestampMutex};
677 mDequeueTimestamps.erase(bufferId);
678};
679
chaviw0acd33a2021-11-02 11:55:37 -0500680void BLASTBufferQueue::setSyncTransaction(SurfaceComposerClient::Transaction* t,
681 bool acquireSingleBuffer) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800682 std::lock_guard _lock{mMutex};
chaviwa1c4c822021-11-10 18:11:58 -0600683 mSyncTransaction = t;
chaviw0acd33a2021-11-02 11:55:37 -0500684 mAcquireSingleBuffer = mSyncTransaction ? acquireSingleBuffer : true;
Robert Carr78c25dd2019-08-15 14:10:33 -0700685}
686
Vishnu Nairea0de002020-11-17 17:42:37 -0800687bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700688 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
689 // Only reject buffers if scaling mode is freeze.
690 return false;
691 }
692
Vishnu Naire1a42322020-10-02 17:42:04 -0700693 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
694 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
695
696 // Take the buffer's orientation into account
697 if (item.mTransform & ui::Transform::ROT_90) {
698 std::swap(bufWidth, bufHeight);
699 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800700 ui::Size bufferSize(bufWidth, bufHeight);
701 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800702 return false;
703 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700704
Vishnu Nair670b3f72020-09-29 17:52:18 -0700705 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800706 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700707}
Vishnu Nairbf255772020-10-16 10:54:41 -0700708
709// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800710// Consumer can acquire an additional buffer if that buffer is not droppable. Set
711// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
712// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
713bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700714 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800715 return mNumAcquired >= maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700716}
717
Robert Carr05086b22020-10-13 18:22:51 -0700718class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700719private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700720 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700721 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700722 bool mDestroyed = false;
723
Robert Carr05086b22020-10-13 18:22:51 -0700724public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700725 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
726 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
727 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700728
Robert Carr05086b22020-10-13 18:22:51 -0700729 void allocateBuffers() override {
730 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
731 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
732 auto gbp = getIGraphicBufferProducer();
733 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
734 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
735 gbp->allocateBuffers(reqWidth, reqHeight,
736 reqFormat, reqUsage);
737
738 }).detach();
739 }
Robert Carr9c006e02020-10-14 13:41:57 -0700740
Marin Shalamanovc5986772021-03-16 16:09:49 +0100741 status_t setFrameRate(float frameRate, int8_t compatibility,
742 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700743 std::unique_lock _lock{mMutex};
744 if (mDestroyed) {
745 return DEAD_OBJECT;
746 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100747 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
748 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700749 return BAD_VALUE;
750 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100751 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700752 }
Robert Carr9b611b72020-10-19 12:00:23 -0700753
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000754 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700755 std::unique_lock _lock{mMutex};
756 if (mDestroyed) {
757 return DEAD_OBJECT;
758 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000759 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700760 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700761
762 void destroy() override {
763 Surface::destroy();
764
765 std::unique_lock _lock{mMutex};
766 mDestroyed = true;
767 mBbq = nullptr;
768 }
Robert Carr05086b22020-10-13 18:22:51 -0700769};
770
Robert Carr9c006e02020-10-14 13:41:57 -0700771// TODO: Can we coalesce this with frame updates? Need to confirm
772// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200773status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
774 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700775 std::unique_lock _lock{mMutex};
776 SurfaceComposerClient::Transaction t;
777
Marin Shalamanov46084422020-10-13 12:33:42 +0200778 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700779}
780
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000781status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700782 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000783 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100784 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700785}
786
Hongguang Chen621ec582021-02-16 15:42:35 -0800787void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
788 std::unique_lock _lock{mMutex};
789 SurfaceComposerClient::Transaction t;
790
791 t.setSidebandStream(mSurfaceControl, stream).apply();
792}
793
Vishnu Nair992496b2020-10-22 17:27:21 -0700794sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
795 std::unique_lock _lock{mMutex};
796 sp<IBinder> scHandle = nullptr;
797 if (includeSurfaceControlHandle && mSurfaceControl) {
798 scHandle = mSurfaceControl->getHandle();
799 }
800 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700801}
802
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800803void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
804 uint64_t frameNumber) {
805 std::lock_guard _lock{mMutex};
806 if (mLastAcquiredFrameNumber >= frameNumber) {
807 // Apply the transaction since we have already acquired the desired frame.
808 t->apply();
809 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500810 mPendingTransactions.emplace_back(frameNumber, *t);
811 // Clear the transaction so it can't be applied elsewhere.
812 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800813 }
814}
815
chaviw6a195272021-09-03 16:14:25 -0500816void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
817 std::lock_guard _lock{mMutex};
818
819 SurfaceComposerClient::Transaction t;
820 mergePendingTransactions(&t, frameNumber);
821 t.setApplyToken(mApplyToken).apply();
822}
823
824void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
825 uint64_t frameNumber) {
826 auto mergeTransaction =
827 [&t, currentFrameNumber = frameNumber](
828 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
829 auto& [targetFrameNumber, transaction] = pendingTransaction;
830 if (currentFrameNumber < targetFrameNumber) {
831 return false;
832 }
833 t->merge(std::move(transaction));
834 return true;
835 };
836
837 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
838 mPendingTransactions.end(), mergeTransaction),
839 mPendingTransactions.end());
840}
841
Vishnu Nair89496122020-12-14 17:14:53 -0800842// Maintains a single worker thread per process that services a list of runnables.
843class AsyncWorker : public Singleton<AsyncWorker> {
844private:
845 std::thread mThread;
846 bool mDone = false;
847 std::deque<std::function<void()>> mRunnables;
848 std::mutex mMutex;
849 std::condition_variable mCv;
850 void run() {
851 std::unique_lock<std::mutex> lock(mMutex);
852 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800853 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700854 std::deque<std::function<void()>> runnables = std::move(mRunnables);
855 mRunnables.clear();
856 lock.unlock();
857 // Run outside the lock since the runnable might trigger another
858 // post to the async worker.
859 execute(runnables);
860 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800861 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700862 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800863 }
864 }
865
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700866 void execute(std::deque<std::function<void()>>& runnables) {
867 while (!runnables.empty()) {
868 std::function<void()> runnable = runnables.front();
869 runnables.pop_front();
870 runnable();
871 }
872 }
873
Vishnu Nair89496122020-12-14 17:14:53 -0800874public:
875 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
876
877 ~AsyncWorker() {
878 mDone = true;
879 mCv.notify_all();
880 if (mThread.joinable()) {
881 mThread.join();
882 }
883 }
884
885 void post(std::function<void()> runnable) {
886 std::unique_lock<std::mutex> lock(mMutex);
887 mRunnables.emplace_back(std::move(runnable));
888 mCv.notify_one();
889 }
890};
891ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
892
893// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
894class AsyncProducerListener : public BnProducerListener {
895private:
896 const sp<IProducerListener> mListener;
897
898public:
899 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
900
901 void onBufferReleased() override {
902 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
903 }
904
905 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
906 AsyncWorker::getInstance().post(
907 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
908 }
909};
910
911// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
912// can be non-blocking when the producer is in the client process.
913class BBQBufferQueueProducer : public BufferQueueProducer {
914public:
915 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
916 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
917
918 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
919 QueueBufferOutput* output) override {
920 if (!listener) {
921 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
922 }
923
924 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
925 producerControlledByApp, output);
926 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800927
928 int query(int what, int* value) override {
929 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
930 *value = 1;
931 return NO_ERROR;
932 }
933 return BufferQueueProducer::query(what, value);
934 }
Vishnu Nair89496122020-12-14 17:14:53 -0800935};
936
937// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
938// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
939// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
940// we can deadlock.
941void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
942 sp<IGraphicBufferConsumer>* outConsumer) {
943 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
944 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
945
946 sp<BufferQueueCore> core(new BufferQueueCore());
947 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
948
949 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
950 LOG_ALWAYS_FATAL_IF(producer == nullptr,
951 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
952
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800953 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
954 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800955 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
956 "BLASTBufferQueue: failed to create BufferQueueConsumer");
957
958 *outProducer = producer;
959 *outConsumer = consumer;
960}
961
chaviw497e81c2021-02-04 17:09:47 -0800962PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
963 PixelFormat convertedFormat = format;
964 switch (format) {
965 case PIXEL_FORMAT_TRANSPARENT:
966 case PIXEL_FORMAT_TRANSLUCENT:
967 convertedFormat = PIXEL_FORMAT_RGBA_8888;
968 break;
969 case PIXEL_FORMAT_OPAQUE:
970 convertedFormat = PIXEL_FORMAT_RGBX_8888;
971 break;
972 }
973 return convertedFormat;
974}
975
Robert Carr82d07c92021-05-10 11:36:43 -0700976uint32_t BLASTBufferQueue::getLastTransformHint() const {
977 if (mSurfaceControl != nullptr) {
978 return mSurfaceControl->getTransformHint();
979 } else {
980 return 0;
981 }
982}
983
chaviw0b020f82021-08-20 12:00:47 -0500984uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
985 std::unique_lock _lock{mMutex};
986 return mLastAcquiredFrameNumber;
987}
988
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800989void BLASTBufferQueue::abandon() {
990 std::unique_lock _lock{mMutex};
991 // flush out the shadow queue
992 while (mNumFrameAvailable > 0) {
993 acquireAndReleaseBuffer();
994 }
995
996 // Clear submitted buffer states
997 mNumAcquired = 0;
998 mSubmitted.clear();
999 mPendingRelease.clear();
1000
1001 if (!mPendingTransactions.empty()) {
1002 BQA_LOGD("Applying pending transactions on abandon %d",
1003 static_cast<uint32_t>(mPendingTransactions.size()));
1004 SurfaceComposerClient::Transaction t;
1005 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
1006 t.setApplyToken(mApplyToken).apply();
1007 }
1008
1009 // Clear sync states
1010 if (mWaitForTransactionCallback) {
1011 BQA_LOGD("mWaitForTransactionCallback cleared");
1012 mWaitForTransactionCallback = false;
1013 }
1014
1015 if (mSyncTransaction != nullptr) {
1016 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1017 mAcquireSingleBuffer ? "true" : "false");
1018 mSyncTransaction = nullptr;
1019 mAcquireSingleBuffer = false;
1020 }
1021
1022 // abandon buffer queue
1023 if (mBufferItemConsumer != nullptr) {
1024 mBufferItemConsumer->abandon();
1025 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1026 mBufferItemConsumer->setBufferFreedListener(nullptr);
1027 mBufferItemConsumer->setBlastBufferQueue(nullptr);
1028 }
1029 mBufferItemConsumer = nullptr;
1030 mConsumer = nullptr;
1031 mProducer = nullptr;
1032}
1033
1034bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1035 std::unique_lock _lock{mMutex};
1036 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1037}
1038
Robert Carr78c25dd2019-08-15 14:10:33 -07001039} // namespace android