blob: f0346426819ebcb36ba533129e0276246a969dbf [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
chaviw2d2150e2021-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() {
Hongguang Chen621ec582021-02-16 15:42:35 -080061 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080062 mPreviouslyConnected = mCurrentlyConnected;
63 mCurrentlyConnected = false;
64 if (mPreviouslyConnected) {
65 mDisconnectEvents.push(mCurrentFrameNumber);
66 }
67 mFrameEventHistory.onDisconnect();
68}
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::onSidebandStreamChanged() {
Ady Abrahamb6f84792021-12-15 11:58:56 -0800123 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
124 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800125 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamb6f84792021-12-15 11:58:56 -0800126 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800127 }
128}
129
Vishnu Nair22b6d232021-12-06 16:45:48 -0800130BLASTBufferQueue::BLASTBufferQueue(const std::string& name)
131 : mSurfaceControl(nullptr),
132 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800133 mRequestedSize(mSize),
Vishnu Nair22b6d232021-12-06 16:45:48 -0800134 mFormat(PIXEL_FORMAT_RGBA_8888),
Valerie Haud3b90d22019-11-06 09:37:31 -0800135 mNextTransaction(nullptr) {
Vishnu Nair89496122020-12-14 17:14:53 -0800136 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800137 // since the adapter is in the client process, set dequeue timeout
138 // explicitly so that dequeueBuffer will block
139 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800140
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700141 // safe default, most producers are expected to override this
142 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800143 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
144 GraphicBuffer::USAGE_HW_COMPOSER |
145 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamb6f84792021-12-15 11:58:56 -0800146 1, false, this);
Valerie Haua32c5522019-12-09 10:11:08 -0800147 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700148 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700149 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700150 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800151 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700152 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700153 mBufferItemConsumer->setFrameAvailableListener(this);
154 mBufferItemConsumer->setBufferFreedListener(this);
Robert Carr9f133d72020-04-01 15:51:46 -0700155
Ady Abraham899dcdb2021-06-15 16:56:21 -0700156 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700157 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
Valerie Haua32c5522019-12-09 10:11:08 -0800158 mNumAcquired = 0;
159 mNumFrameAvailable = 0;
Vishnu Nair22b6d232021-12-06 16:45:48 -0800160 BQA_LOGV("BLASTBufferQueue created");
161}
162
163BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
164 int width, int height, int32_t format)
165 : BLASTBufferQueue(name) {
166 update(surface, width, height, format);
Robert Carr78c25dd2019-08-15 14:10:33 -0700167}
168
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800169BLASTBufferQueue::~BLASTBufferQueue() {
170 if (mPendingTransactions.empty()) {
171 return;
172 }
173 BQA_LOGE("Applying pending transactions on dtor %d",
174 static_cast<uint32_t>(mPendingTransactions.size()));
175 SurfaceComposerClient::Transaction t;
176 for (auto& [targetFrameNumber, transaction] : mPendingTransactions) {
177 t.merge(std::move(transaction));
178 }
179 t.apply();
180}
181
chaviw565ee542021-01-14 10:21:23 -0800182void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Nair084514a2021-07-30 16:07:42 -0700183 int32_t format, SurfaceComposerClient::Transaction* outTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700184 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800185 if (mFormat != format) {
186 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800187 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800188 }
189
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800190 SurfaceComposerClient::Transaction t;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700191 const bool setBackpressureFlag = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800192 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800193
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700194 // Always update the native object even though they might have the same layer handle, so we can
195 // get the updated transform hint from WM.
196 mSurfaceControl = surface;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800197 if (mSurfaceControl != nullptr) {
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700198 if (setBackpressureFlag) {
199 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
200 layer_state_t::eEnableBackpressure);
201 applyTransaction = true;
202 }
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800203 mTransformHint = mSurfaceControl->getTransformHint();
204 mBufferItemConsumer->setTransformHint(mTransformHint);
205 }
Vishnu Naira4fbca52021-07-07 16:52:34 -0700206 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
207 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800208
Vishnu Nairea0de002020-11-17 17:42:37 -0800209 ui::Size newSize(width, height);
210 if (mRequestedSize != newSize) {
211 mRequestedSize.set(newSize);
212 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000213 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800214 // If the buffer supports scaling, update the frame immediately since the client may
215 // want to scale the existing buffer to the new size.
216 mSize = mRequestedSize;
Vishnu Nair084514a2021-07-30 16:07:42 -0700217 SurfaceComposerClient::Transaction* destFrameTransaction =
218 (outTransaction) ? outTransaction : &t;
Vishnu Nair22b6d232021-12-06 16:45:48 -0800219 if (mSurfaceControl != nullptr) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700220 destFrameTransaction->setDestinationFrame(mSurfaceControl,
221 Rect(0, 0, newSize.getWidth(),
222 newSize.getHeight()));
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000223 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800224 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800225 }
Robert Carrfc416512020-04-02 12:32:44 -0700226 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800227 if (applyTransaction) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700228 t.setApplyToken(mApplyToken).apply();
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800229 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700230}
231
chaviw2d2150e2021-10-06 11:53:40 -0500232static std::optional<SurfaceControlStats> findMatchingStat(
233 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
234 for (auto stat : stats) {
235 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
236 return stat;
237 }
238 }
239 return std::nullopt;
240}
241
242static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
243 const sp<Fence>& presentFence,
244 const std::vector<SurfaceControlStats>& stats) {
245 if (context == nullptr) {
246 return;
247 }
248 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
249 bq->transactionCommittedCallback(latchTime, presentFence, stats);
250}
251
252void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
253 const sp<Fence>& /*presentFence*/,
254 const std::vector<SurfaceControlStats>& stats) {
255 {
256 std::unique_lock _lock{mMutex};
257 ATRACE_CALL();
258 BQA_LOGV("transactionCommittedCallback");
259 if (!mSurfaceControlsWithPendingCallback.empty()) {
260 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
261 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
262 if (stat) {
263 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
264
265 // We need to check if we were waiting for a transaction callback in order to
266 // process any pending buffers and unblock. It's possible to get transaction
267 // callbacks for previous requests so we need to ensure the frame from this
268 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
269 // will stop processing buffers when mWaitForTransactionCallback is set, we know
270 // that mLastAcquiredFrameNumber is the frame we're waiting on.
271 // We also want to check if mNextTransaction is null because it's possible another
272 // sync request came in while waiting, but it hasn't started processing yet. In that
273 // case, we don't actually want to flush the frames in between since they will get
274 // processed and merged with the sync transaction and released earlier than if they
275 // were sent to SF
276 if (mWaitForTransactionCallback && mNextTransaction == nullptr &&
277 currFrameNumber >= mLastAcquiredFrameNumber) {
278 mWaitForTransactionCallback = false;
279 flushShadowQueueLocked();
280 }
281 } else {
chaviwa840a122021-11-01 09:50:57 -0500282 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviw2d2150e2021-10-06 11:53:40 -0500283 }
284 } else {
285 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
286 "empty.");
287 }
288
289 decStrong((void*)transactionCommittedCallbackThunk);
290 }
291}
292
Robert Carr78c25dd2019-08-15 14:10:33 -0700293static void transactionCallbackThunk(void* context, nsecs_t latchTime,
294 const sp<Fence>& presentFence,
295 const std::vector<SurfaceControlStats>& stats) {
296 if (context == nullptr) {
297 return;
298 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800299 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700300 bq->transactionCallback(latchTime, presentFence, stats);
301}
302
303void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
304 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700305 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
306 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700307
chaviw71c2cc42020-10-23 16:42:02 -0700308 {
309 std::unique_lock _lock{mMutex};
310 ATRACE_CALL();
311 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700312
chaviw42026162021-04-16 15:46:12 -0500313 if (!mSurfaceControlsWithPendingCallback.empty()) {
314 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
315 mSurfaceControlsWithPendingCallback.pop();
chaviw2d2150e2021-10-06 11:53:40 -0500316 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
317 if (statsOptional) {
318 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500319 mTransformHint = stat.transformHint;
320 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700321 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700322 // Update frametime stamps if the frame was latched and presented, indicated by a
323 // valid latch time.
324 if (stat.latchTime > 0) {
325 mBufferItemConsumer
326 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
327 stat.frameEventStats.refreshStartTime,
328 stat.frameEventStats.gpuCompositionDoneFence,
329 stat.presentFence, stat.previousReleaseFence,
330 stat.frameEventStats.compositorTiming,
331 stat.latchTime,
332 stat.frameEventStats.dequeueReadyTime);
333 }
chaviw42026162021-04-16 15:46:12 -0500334 currFrameNumber = stat.frameEventStats.frameNumber;
335
336 if (mTransactionCompleteCallback &&
337 currFrameNumber >= mTransactionCompleteFrameNumber) {
338 if (currFrameNumber > mTransactionCompleteFrameNumber) {
339 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
340 " than expected=%" PRIu64,
341 currFrameNumber, mTransactionCompleteFrameNumber);
342 }
343 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
344 mTransactionCompleteFrameNumber = 0;
345 }
Robert Carraca25f62021-12-31 16:59:34 -0800346 std::vector<ReleaseCallbackId> staleReleases;
347 for (const auto& [key, value]: mSubmitted) {
348 if (currFrameNumber > key.framenumber) {
349 staleReleases.push_back(key);
350 }
351 }
352 for (const auto& staleRelease : staleReleases) {
353 releaseBufferCallbackLocked(staleRelease, stat.previousReleaseFence ? stat.previousReleaseFence : Fence::NO_FENCE,
354 stat.transformHint, stat.currentMaxAcquiredBufferCount);
355 }
chaviw2d2150e2021-10-06 11:53:40 -0500356 } else {
chaviwa840a122021-11-01 09:50:57 -0500357 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500358 }
359 } else {
360 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
361 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800362 }
chaviw71c2cc42020-10-23 16:42:02 -0700363
Robert Carraca25f62021-12-31 16:59:34 -0800364
chaviw71c2cc42020-10-23 16:42:02 -0700365 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700366 }
Valerie Haua32c5522019-12-09 10:11:08 -0800367
chaviw71c2cc42020-10-23 16:42:02 -0700368 if (transactionCompleteCallback) {
369 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800370 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700371}
372
Vishnu Nair1506b182021-02-22 14:35:15 -0800373// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
374// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
375// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
376// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700377static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700378 const sp<Fence>& releaseFence, uint32_t transformHint,
379 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800380 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800381 if (blastBufferQueue) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700382 blastBufferQueue->releaseBufferCallback(id, releaseFence, transformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700383 currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700384 } else {
385 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800386 }
387}
388
chaviw2d2150e2021-10-06 11:53:40 -0500389void BLASTBufferQueue::flushShadowQueueLocked() {
390 BQA_LOGV("flushShadowQueueLocked");
391 int numFramesToFlush = mNumFrameAvailable;
392 while (numFramesToFlush > 0) {
393 acquireNextBufferLocked(std::nullopt);
394 numFramesToFlush--;
395 }
396}
397
398void BLASTBufferQueue::flushShadowQueue() {
399 std::unique_lock _lock{mMutex};
400 flushShadowQueueLocked();
401}
402
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700403void BLASTBufferQueue::releaseBufferCallback(const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700404 const sp<Fence>& releaseFence, uint32_t transformHint,
405 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800406 std::unique_lock _lock{mMutex};
Robert Carraca25f62021-12-31 16:59:34 -0800407 releaseBufferCallbackLocked(id, releaseFence, transformHint, currentMaxAcquiredBufferCount);
408}
409
410void BLASTBufferQueue::releaseBufferCallbackLocked(const ReleaseCallbackId& id,
411 const sp<Fence>& releaseFence, uint32_t transformHint,
412 uint32_t currentMaxAcquiredBufferCount) {
413 ATRACE_CALL();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700414 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800415
Robert Carr82d07c92021-05-10 11:36:43 -0700416 if (mSurfaceControl != nullptr) {
Robert Carr97e7cc02021-06-07 10:45:40 -0700417 mTransformHint = transformHint;
418 mSurfaceControl->setTransformHint(transformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700419 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700420 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700421 }
422
Ady Abraham899dcdb2021-06-15 16:56:21 -0700423 // Calculate how many buffers we need to hold before we release them back
424 // to the buffer queue. This will prevent higher latency when we are running
425 // on a lower refresh rate than the max supported. We only do that for EGL
426 // clients as others don't care about latency
427 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700428 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700429 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
430 }();
431
432 const auto numPendingBuffersToHold =
433 isEGL ? std::max(0u, mMaxAcquiredBuffers - currentMaxAcquiredBufferCount) : 0;
Robert Carraca25f62021-12-31 16:59:34 -0800434 auto rb = ReleasedBuffer{id, releaseFence};
435 if (std::find(mPendingRelease.begin(), mPendingRelease.end(), rb) == mPendingRelease.end()) {
436 mPendingRelease.emplace_back(rb);
437 }
Ady Abraham899dcdb2021-06-15 16:56:21 -0700438
439 // Release all buffers that are beyond the ones that we need to hold
440 while (mPendingRelease.size() > numPendingBuffersToHold) {
441 const auto releaseBuffer = mPendingRelease.front();
442 mPendingRelease.pop_front();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700443 auto it = mSubmitted.find(releaseBuffer.callbackId);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700444 if (it == mSubmitted.end()) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700445 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
446 releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700447 return;
448 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700449 mNumAcquired--;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700450 BQA_LOGV("released %s", id.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700451 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
452 mSubmitted.erase(it);
chaviw2d2150e2021-10-06 11:53:40 -0500453 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
454 // onFrameAvailable handle processing them since it will merge with the nextTransaction.
455 if (!mWaitForTransactionCallback) {
456 acquireNextBufferLocked(std::nullopt);
457 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800458 }
459
Ady Abraham899dcdb2021-06-15 16:56:21 -0700460 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700461 ATRACE_INT(mQueuedBufferTrace.c_str(),
462 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800463 mCallbackCV.notify_all();
464}
465
chaviw2d2150e2021-10-06 11:53:40 -0500466void BLASTBufferQueue::acquireNextBufferLocked(
467 const std::optional<SurfaceComposerClient::Transaction*> transaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800468 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800469 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
470 // include the extra buffer when checking if we can acquire the next buffer.
chaviw2d2150e2021-10-06 11:53:40 -0500471 const bool includeExtraAcquire = !transaction;
472 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
473 if (mNumFrameAvailable == 0 || maxAcquired) {
474 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800475 return;
476 }
477
Valerie Haua32c5522019-12-09 10:11:08 -0800478 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700479 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800480 return;
481 }
482
Robert Carr78c25dd2019-08-15 14:10:33 -0700483 SurfaceComposerClient::Transaction localTransaction;
484 bool applyTransaction = true;
485 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviw2d2150e2021-10-06 11:53:40 -0500486 if (transaction) {
487 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700488 applyTransaction = false;
489 }
490
Valerie Haua32c5522019-12-09 10:11:08 -0800491 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800492
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800493 status_t status =
494 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800495 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
496 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
497 return;
498 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700499 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700500 return;
501 }
Valerie Haua32c5522019-12-09 10:11:08 -0800502 auto buffer = bufferItem.mGraphicBuffer;
503 mNumFrameAvailable--;
504
505 if (buffer == nullptr) {
506 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700507 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800508 return;
509 }
510
Vishnu Nair670b3f72020-09-29 17:52:18 -0700511 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700512 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800513 "buffer{size=%dx%d transform=%d}",
514 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
515 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
516 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviw2d2150e2021-10-06 11:53:40 -0500517 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800518 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700519 }
520
Valerie Haua32c5522019-12-09 10:11:08 -0800521 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700522 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
523 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
524 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700525
Valerie Hau871d6352020-01-29 08:44:02 -0800526 bool needsDisconnect = false;
527 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
528
529 // if producer disconnected before, notify SurfaceFlinger
530 if (needsDisconnect) {
531 t->notifyProducerDisconnect(mSurfaceControl);
532 }
533
Robert Carr78c25dd2019-08-15 14:10:33 -0700534 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
535 incStrong((void*)transactionCallbackThunk);
536
Vishnu Nair22b6d232021-12-06 16:45:48 -0800537 const bool updateDestinationFrame = mRequestedSize != mSize;
Vishnu Nair932f6ae2021-09-29 17:33:10 -0700538 mSize = mRequestedSize;
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700539 Rect crop = computeCrop(bufferItem);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000540 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
541 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700542 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800543
Vishnu Nair1506b182021-02-22 14:35:15 -0800544 auto releaseBufferCallback =
545 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700546 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
547 std::placeholders::_4);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700548 t->setBuffer(mSurfaceControl, buffer, releaseCallbackId, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500549 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
550 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
551 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700552 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800553 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700554 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviw9d12adc2021-11-17 17:36:50 -0600555
chaviw42026162021-04-16 15:46:12 -0500556 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700557
Vishnu Nair084514a2021-07-30 16:07:42 -0700558 if (updateDestinationFrame) {
559 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
560 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700561 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800562 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800563 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800564 if (!bufferItem.mIsAutoTimestamp) {
565 t->setDesiredPresentTime(bufferItem.mTimestamp);
566 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700567 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700568
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000569 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700570 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000571 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100572 }
573
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800574 if (mAutoRefresh != bufferItem.mAutoRefresh) {
575 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
576 mAutoRefresh = bufferItem.mAutoRefresh;
577 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800578 {
579 std::unique_lock _lock{mTimestampMutex};
580 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
581 if (dequeueTime != mDequeueTimestamps.end()) {
582 Parcel p;
583 p.writeInt64(dequeueTime->second);
584 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
585 mDequeueTimestamps.erase(dequeueTime);
586 }
587 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800588
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800589 auto mergeTransaction =
590 [&t, currentFrameNumber = bufferItem.mFrameNumber](
591 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
592 auto& [targetFrameNumber, transaction] = pendingTransaction;
593 if (currentFrameNumber < targetFrameNumber) {
594 return false;
595 }
596 t->merge(std::move(transaction));
597 return true;
598 };
599
600 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
601 mPendingTransactions.end(), mergeTransaction),
602 mPendingTransactions.end());
603
Robert Carr78c25dd2019-08-15 14:10:33 -0700604 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800605 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700606 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700607
chaviw2d2150e2021-10-06 11:53:40 -0500608 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800609 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700610 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500611 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800612 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700613 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700614 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700615}
616
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800617Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
618 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800619 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800620 }
621 return item.mCrop;
622}
623
chaviw2d2150e2021-10-06 11:53:40 -0500624void BLASTBufferQueue::acquireAndReleaseBuffer() {
625 BufferItem bufferItem;
chaviw8cba4ce2021-10-14 11:57:22 -0500626 status_t status =
627 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
628 if (status != OK) {
629 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
630 statusToString(status).c_str());
631 return;
632 }
chaviw2d2150e2021-10-06 11:53:40 -0500633 mNumFrameAvailable--;
chaviw8cba4ce2021-10-14 11:57:22 -0500634 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviw2d2150e2021-10-06 11:53:40 -0500635}
636
Vishnu Nairaef1de92020-10-22 12:15:53 -0700637void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800638 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800639 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800640
Vishnu Nairdab94092020-09-29 16:09:04 -0700641 const bool nextTransactionSet = mNextTransaction != nullptr;
chaviw2d2150e2021-10-06 11:53:40 -0500642 BQA_LOGV("onFrameAvailable-start nextTransactionSet=%s", boolToString(nextTransactionSet));
Vishnu Nair1506b182021-02-22 14:35:15 -0800643 if (nextTransactionSet) {
chaviw2d2150e2021-10-06 11:53:40 -0500644 if (mWaitForTransactionCallback) {
645 // We are waiting on a previous sync's transaction callback so allow another sync
646 // transaction to proceed.
647 //
648 // We need to first flush out the transactions that were in between the two syncs.
649 // We do this by merging them into mNextTransaction so any buffer merging will get
650 // a release callback invoked. The release callback will be async so we need to wait
651 // on max acquired to make sure we have the capacity to acquire another buffer.
652 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
653 BQA_LOGD("waiting to flush shadow queue...");
654 mCallbackCV.wait(_lock);
655 }
656 while (mNumFrameAvailable > 0) {
657 // flush out the shadow queue
658 acquireAndReleaseBuffer();
659 }
660 }
661
662 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
663 BQA_LOGD("waiting for free buffer.");
Valerie Hau0188adf2020-02-13 08:29:20 -0800664 mCallbackCV.wait(_lock);
665 }
666 }
chaviw2d2150e2021-10-06 11:53:40 -0500667
Valerie Haud3b90d22019-11-06 09:37:31 -0800668 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800669 mNumFrameAvailable++;
Robert Carre9323b32021-11-30 14:47:02 -0800670 if (mWaitForTransactionCallback && mNumFrameAvailable == 2) {
671 acquireAndReleaseBuffer();
672 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700673 ATRACE_INT(mQueuedBufferTrace.c_str(),
674 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800675
676 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
chaviw3277faf2021-05-19 16:45:23 -0500677 boolToString(nextTransactionSet));
chaviw2d2150e2021-10-06 11:53:40 -0500678
679 if (nextTransactionSet) {
680 acquireNextBufferLocked(std::move(mNextTransaction));
chaviw9d12adc2021-11-17 17:36:50 -0600681
682 // Only need a commit callback when syncing to ensure the buffer that's synced has been sent
683 // to SF
684 incStrong((void*)transactionCommittedCallbackThunk);
685 mNextTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
686 static_cast<void*>(this));
687
chaviw2d2150e2021-10-06 11:53:40 -0500688 mNextTransaction = nullptr;
689 mWaitForTransactionCallback = true;
690 } else if (!mWaitForTransactionCallback) {
691 acquireNextBufferLocked(std::nullopt);
692 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800693}
694
Vishnu Nairaef1de92020-10-22 12:15:53 -0700695void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
696 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
697 // Do nothing since we are not storing unacquired buffer items locally.
698}
699
Vishnu Nairadf632b2021-01-07 14:05:08 -0800700void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
701 std::unique_lock _lock{mTimestampMutex};
702 mDequeueTimestamps[bufferId] = systemTime();
703};
704
705void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
706 std::unique_lock _lock{mTimestampMutex};
707 mDequeueTimestamps.erase(bufferId);
708};
709
Robert Carr78c25dd2019-08-15 14:10:33 -0700710void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800711 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700712 mNextTransaction = t;
713}
714
Vishnu Nairea0de002020-11-17 17:42:37 -0800715bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700716 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
717 // Only reject buffers if scaling mode is freeze.
718 return false;
719 }
720
Vishnu Naire1a42322020-10-02 17:42:04 -0700721 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
722 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
723
724 // Take the buffer's orientation into account
725 if (item.mTransform & ui::Transform::ROT_90) {
726 std::swap(bufWidth, bufHeight);
727 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800728 ui::Size bufferSize(bufWidth, bufHeight);
729 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800730 return false;
731 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700732
Vishnu Nair670b3f72020-09-29 17:52:18 -0700733 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800734 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700735}
Vishnu Nairbf255772020-10-16 10:54:41 -0700736
chaviw71c2cc42020-10-23 16:42:02 -0700737void BLASTBufferQueue::setTransactionCompleteCallback(
738 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
739 std::lock_guard _lock{mMutex};
740 if (transactionCompleteCallback == nullptr) {
741 mTransactionCompleteCallback = nullptr;
742 } else {
743 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
744 mTransactionCompleteFrameNumber = frameNumber;
745 }
746}
747
Vishnu Nairbf255772020-10-16 10:54:41 -0700748// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800749// Consumer can acquire an additional buffer if that buffer is not droppable. Set
750// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
751// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
752bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700753 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800754 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700755}
756
Robert Carr05086b22020-10-13 18:22:51 -0700757class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700758private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700759 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700760 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700761 bool mDestroyed = false;
762
Robert Carr05086b22020-10-13 18:22:51 -0700763public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700764 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
765 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
766 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700767
Robert Carr05086b22020-10-13 18:22:51 -0700768 void allocateBuffers() override {
769 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
770 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
771 auto gbp = getIGraphicBufferProducer();
772 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
773 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
774 gbp->allocateBuffers(reqWidth, reqHeight,
775 reqFormat, reqUsage);
776
777 }).detach();
778 }
Robert Carr9c006e02020-10-14 13:41:57 -0700779
Marin Shalamanovc5986772021-03-16 16:09:49 +0100780 status_t setFrameRate(float frameRate, int8_t compatibility,
781 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700782 std::unique_lock _lock{mMutex};
783 if (mDestroyed) {
784 return DEAD_OBJECT;
785 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100786 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
787 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700788 return BAD_VALUE;
789 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100790 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700791 }
Robert Carr9b611b72020-10-19 12:00:23 -0700792
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000793 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700794 std::unique_lock _lock{mMutex};
795 if (mDestroyed) {
796 return DEAD_OBJECT;
797 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000798 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700799 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700800
801 void destroy() override {
802 Surface::destroy();
803
804 std::unique_lock _lock{mMutex};
805 mDestroyed = true;
806 mBbq = nullptr;
807 }
Robert Carr05086b22020-10-13 18:22:51 -0700808};
809
Robert Carr9c006e02020-10-14 13:41:57 -0700810// TODO: Can we coalesce this with frame updates? Need to confirm
811// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200812status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
813 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700814 std::unique_lock _lock{mMutex};
815 SurfaceComposerClient::Transaction t;
816
Marin Shalamanov46084422020-10-13 12:33:42 +0200817 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700818}
819
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000820status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700821 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000822 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100823 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700824}
825
Hongguang Chen621ec582021-02-16 15:42:35 -0800826void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
827 std::unique_lock _lock{mMutex};
828 SurfaceComposerClient::Transaction t;
829
830 t.setSidebandStream(mSurfaceControl, stream).apply();
831}
832
Vishnu Nair992496b2020-10-22 17:27:21 -0700833sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
834 std::unique_lock _lock{mMutex};
835 sp<IBinder> scHandle = nullptr;
836 if (includeSurfaceControlHandle && mSurfaceControl) {
837 scHandle = mSurfaceControl->getHandle();
838 }
839 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700840}
841
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800842void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
843 uint64_t frameNumber) {
844 std::lock_guard _lock{mMutex};
845 if (mLastAcquiredFrameNumber >= frameNumber) {
846 // Apply the transaction since we have already acquired the desired frame.
847 t->apply();
848 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500849 mPendingTransactions.emplace_back(frameNumber, *t);
850 // Clear the transaction so it can't be applied elsewhere.
851 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800852 }
853}
854
Vishnu Nair89496122020-12-14 17:14:53 -0800855// Maintains a single worker thread per process that services a list of runnables.
856class AsyncWorker : public Singleton<AsyncWorker> {
857private:
858 std::thread mThread;
859 bool mDone = false;
860 std::deque<std::function<void()>> mRunnables;
861 std::mutex mMutex;
862 std::condition_variable mCv;
863 void run() {
864 std::unique_lock<std::mutex> lock(mMutex);
865 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800866 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700867 std::deque<std::function<void()>> runnables = std::move(mRunnables);
868 mRunnables.clear();
869 lock.unlock();
870 // Run outside the lock since the runnable might trigger another
871 // post to the async worker.
872 execute(runnables);
873 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800874 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700875 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800876 }
877 }
878
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700879 void execute(std::deque<std::function<void()>>& runnables) {
880 while (!runnables.empty()) {
881 std::function<void()> runnable = runnables.front();
882 runnables.pop_front();
883 runnable();
884 }
885 }
886
Vishnu Nair89496122020-12-14 17:14:53 -0800887public:
888 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
889
890 ~AsyncWorker() {
891 mDone = true;
892 mCv.notify_all();
893 if (mThread.joinable()) {
894 mThread.join();
895 }
896 }
897
898 void post(std::function<void()> runnable) {
899 std::unique_lock<std::mutex> lock(mMutex);
900 mRunnables.emplace_back(std::move(runnable));
901 mCv.notify_one();
902 }
903};
904ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
905
906// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
907class AsyncProducerListener : public BnProducerListener {
908private:
909 const sp<IProducerListener> mListener;
910
911public:
912 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
913
914 void onBufferReleased() override {
915 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
916 }
917
918 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
919 AsyncWorker::getInstance().post(
920 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
921 }
922};
923
924// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
925// can be non-blocking when the producer is in the client process.
926class BBQBufferQueueProducer : public BufferQueueProducer {
927public:
928 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
929 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
930
931 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
932 QueueBufferOutput* output) override {
933 if (!listener) {
934 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
935 }
936
937 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
938 producerControlledByApp, output);
939 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800940
941 int query(int what, int* value) override {
942 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
943 *value = 1;
944 return NO_ERROR;
945 }
946 return BufferQueueProducer::query(what, value);
947 }
Vishnu Nair89496122020-12-14 17:14:53 -0800948};
949
950// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
951// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
952// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
953// we can deadlock.
954void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
955 sp<IGraphicBufferConsumer>* outConsumer) {
956 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
957 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
958
959 sp<BufferQueueCore> core(new BufferQueueCore());
960 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
961
962 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
963 LOG_ALWAYS_FATAL_IF(producer == nullptr,
964 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
965
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800966 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
967 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800968 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
969 "BLASTBufferQueue: failed to create BufferQueueConsumer");
970
971 *outProducer = producer;
972 *outConsumer = consumer;
973}
974
chaviw497e81c2021-02-04 17:09:47 -0800975PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
976 PixelFormat convertedFormat = format;
977 switch (format) {
978 case PIXEL_FORMAT_TRANSPARENT:
979 case PIXEL_FORMAT_TRANSLUCENT:
980 convertedFormat = PIXEL_FORMAT_RGBA_8888;
981 break;
982 case PIXEL_FORMAT_OPAQUE:
983 convertedFormat = PIXEL_FORMAT_RGBX_8888;
984 break;
985 }
986 return convertedFormat;
987}
988
Robert Carr82d07c92021-05-10 11:36:43 -0700989uint32_t BLASTBufferQueue::getLastTransformHint() const {
990 if (mSurfaceControl != nullptr) {
991 return mSurfaceControl->getTransformHint();
992 } else {
993 return 0;
994 }
995}
996
chaviw3d8a3192021-08-20 12:00:47 -0500997uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
998 std::unique_lock _lock{mMutex};
999 return mLastAcquiredFrameNumber;
1000}
1001
Robert Carr78c25dd2019-08-15 14:10:33 -07001002} // namespace android