blob: b7a7aa0ccb09b563009c9759770f37fcdbbaadb4 [file] [log] [blame]
Robert Carr78c25dd2019-08-15 14:10:33 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Valerie Haud3b90d22019-11-06 09:37:31 -080017#undef LOG_TAG
18#define LOG_TAG "BLASTBufferQueue"
19
Valerie Haua32c5522019-12-09 10:11:08 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Vishnu Naire1a42322020-10-02 17:42:04 -070021//#define LOG_NDEBUG 0
Valerie Haua32c5522019-12-09 10:11:08 -080022
Robert Carr78c25dd2019-08-15 14:10:33 -070023#include <gui/BLASTBufferQueue.h>
24#include <gui/BufferItemConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080025#include <gui/BufferQueueConsumer.h>
26#include <gui/BufferQueueCore.h>
27#include <gui/BufferQueueProducer.h>
Valerie Hau45e4b3b2019-12-03 10:49:17 -080028#include <gui/GLConsumer.h>
Vishnu Nair89496122020-12-14 17:14:53 -080029#include <gui/IProducerListener.h>
Robert Carr05086b22020-10-13 18:22:51 -070030#include <gui/Surface.h>
chaviw57ae4b22022-02-03 16:51:39 -060031#include <gui/TraceUtils.h>
Vishnu Nair89496122020-12-14 17:14:53 -080032#include <utils/Singleton.h>
Valerie Haua32c5522019-12-09 10:11:08 -080033#include <utils/Trace.h>
34
Ady Abraham0bde6b52021-05-18 13:57:02 -070035#include <private/gui/ComposerService.h>
36
Robert Carr78c25dd2019-08-15 14:10:33 -070037#include <chrono>
38
39using namespace std::chrono_literals;
40
Vishnu Nairdab94092020-09-29 16:09:04 -070041namespace {
chaviw3277faf2021-05-19 16:45:23 -050042inline const char* boolToString(bool b) {
Vishnu Nairdab94092020-09-29 16:09:04 -070043 return b ? "true" : "false";
44}
45} // namespace
46
Robert Carr78c25dd2019-08-15 14:10:33 -070047namespace android {
48
Vishnu Nairdab94092020-09-29 16:09:04 -070049// Macros to include adapter info in log messages
chaviwd7deef72021-10-06 11:53:40 -050050#define BQA_LOGD(x, ...) \
51 ALOGD("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070052#define BQA_LOGV(x, ...) \
53 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080054// enable logs for a single layer
55//#define BQA_LOGV(x, ...) \
56// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
57// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070058#define BQA_LOGE(x, ...) \
59 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
60
chaviw57ae4b22022-02-03 16:51:39 -060061#define BBQ_TRACE(x, ...) \
62 ATRACE_FORMAT("%s - %s(f:%u,a:%u)" x, __FUNCTION__, mName.c_str(), mNumFrameAvailable, \
63 mNumAcquired, ##__VA_ARGS__)
64
Valerie Hau871d6352020-01-29 08:44:02 -080065void BLASTBufferItemConsumer::onDisconnect() {
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000066 Mutex::Autolock lock(mMutex);
67 mPreviouslyConnected = mCurrentlyConnected;
68 mCurrentlyConnected = false;
69 if (mPreviouslyConnected) {
70 mDisconnectEvents.push(mCurrentFrameNumber);
Valerie Hau871d6352020-01-29 08:44:02 -080071 }
Jiakai Zhangc33c63a2021-11-09 11:24:04 +000072 mFrameEventHistory.onDisconnect();
Valerie Hau871d6352020-01-29 08:44:02 -080073}
74
75void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
76 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080077 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080078 if (newTimestamps) {
79 // BufferQueueProducer only adds a new timestamp on
80 // queueBuffer
81 mCurrentFrameNumber = newTimestamps->frameNumber;
82 mFrameEventHistory.addQueue(*newTimestamps);
83 }
84 if (outDelta) {
85 // frame event histories will be processed
86 // only after the producer connects and requests
87 // deltas for the first time. Forward this intent
88 // to SF-side to turn event processing back on
89 mPreviouslyConnected = mCurrentlyConnected;
90 mCurrentlyConnected = true;
91 mFrameEventHistory.getAndResetDelta(outDelta);
92 }
93}
94
95void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
96 const sp<Fence>& glDoneFence,
97 const sp<Fence>& presentFence,
98 const sp<Fence>& prevReleaseFence,
99 CompositorTiming compositorTiming,
100 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800101 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800102
103 // if the producer is not connected, don't bother updating,
104 // the next producer that connects won't access this frame event
105 if (!mCurrentlyConnected) return;
106 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
107 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
108 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
109
110 mFrameEventHistory.addLatch(frameNumber, latchTime);
111 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
112 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
113 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
114 compositorTiming);
115}
116
117void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
118 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800119 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800120 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
121 disconnect = true;
122 mDisconnectEvents.pop();
123 }
124 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
125}
126
Hongguang Chen621ec582021-02-16 15:42:35 -0800127void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdbca1352021-12-15 11:58:56 -0800128 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
129 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800130 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdbca1352021-12-15 11:58:56 -0800131 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800132 }
133}
134
Vishnu Naird2aaab12022-02-10 14:49:09 -0800135BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800136 : mSurfaceControl(nullptr),
137 mSize(1, 1),
Vishnu Nairea0de002020-11-17 17:42:37 -0800138 mRequestedSize(mSize),
Vishnu Nair1cb8e892021-12-06 16:45:48 -0800139 mFormat(PIXEL_FORMAT_RGBA_8888),
Vishnu Naird2aaab12022-02-10 14:49:09 -0800140 mSyncTransaction(nullptr),
141 mUpdateDestinationFrame(updateDestinationFrame) {
Vishnu Nair89496122020-12-14 17:14:53 -0800142 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800143 // since the adapter is in the client process, set dequeue timeout
144 // explicitly so that dequeueBuffer will block
145 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800146
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700147 // safe default, most producers are expected to override this
148 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800149 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
150 GraphicBuffer::USAGE_HW_COMPOSER |
151 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdbca1352021-12-15 11:58:56 -0800152 1, false, this);
Valerie Haua32c5522019-12-09 10:11:08 -0800153 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700154 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700155 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700156 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800157 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700158 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700159 mBufferItemConsumer->setFrameAvailableListener(this);
160 mBufferItemConsumer->setBufferFreedListener(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() {
177 if (mPendingTransactions.empty()) {
178 return;
179 }
180 BQA_LOGE("Applying pending transactions on dtor %d",
181 static_cast<uint32_t>(mPendingTransactions.size()));
182 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800183 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
184 t.setApplyToken(mApplyToken).apply();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800185}
186
chaviw565ee542021-01-14 10:21:23 -0800187void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Naird2aaab12022-02-10 14:49:09 -0800188 int32_t format) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800189 LOG_ALWAYS_FATAL_IF(surface == nullptr, "BLASTBufferQueue: mSurfaceControl must not be NULL");
190
Robert Carr78c25dd2019-08-15 14:10:33 -0700191 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800192 if (mFormat != format) {
193 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800194 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800195 }
196
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800197 const bool surfaceControlChanged = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairab066512022-01-04 22:28:00 +0000198 if (surfaceControlChanged && mSurfaceControl != nullptr) {
199 BQA_LOGD("Updating SurfaceControl without recreating BBQ");
200 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800201 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800202
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700203 // Always update the native object even though they might have the same layer handle, so we can
204 // get the updated transform hint from WM.
205 mSurfaceControl = surface;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800206 SurfaceComposerClient::Transaction t;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800207 if (surfaceControlChanged) {
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800208 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
209 layer_state_t::eEnableBackpressure);
210 applyTransaction = true;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800211 }
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800212 mTransformHint = mSurfaceControl->getTransformHint();
213 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700214 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
215 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800216
Vishnu Nairea0de002020-11-17 17:42:37 -0800217 ui::Size newSize(width, height);
218 if (mRequestedSize != newSize) {
219 mRequestedSize.set(newSize);
220 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000221 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800222 // If the buffer supports scaling, update the frame immediately since the client may
223 // want to scale the existing buffer to the new size.
224 mSize = mRequestedSize;
Vishnu Naird2aaab12022-02-10 14:49:09 -0800225 if (mUpdateDestinationFrame) {
226 t.setDestinationFrame(mSurfaceControl, Rect(newSize));
227 applyTransaction = true;
228 }
Vishnu Nair53c936c2020-12-03 11:46:37 -0800229 }
Robert Carrfc416512020-04-02 12:32:44 -0700230 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800231 if (applyTransaction) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700232 t.setApplyToken(mApplyToken).apply();
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800233 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700234}
235
chaviwd7deef72021-10-06 11:53:40 -0500236static std::optional<SurfaceControlStats> findMatchingStat(
237 const std::vector<SurfaceControlStats>& stats, const sp<SurfaceControl>& sc) {
238 for (auto stat : stats) {
239 if (SurfaceControl::isSameSurface(sc, stat.surfaceControl)) {
240 return stat;
241 }
242 }
243 return std::nullopt;
244}
245
246static void transactionCommittedCallbackThunk(void* context, nsecs_t latchTime,
247 const sp<Fence>& presentFence,
248 const std::vector<SurfaceControlStats>& stats) {
249 if (context == nullptr) {
250 return;
251 }
252 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
253 bq->transactionCommittedCallback(latchTime, presentFence, stats);
254}
255
256void BLASTBufferQueue::transactionCommittedCallback(nsecs_t /*latchTime*/,
257 const sp<Fence>& /*presentFence*/,
258 const std::vector<SurfaceControlStats>& stats) {
259 {
260 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600261 BBQ_TRACE();
chaviwd7deef72021-10-06 11:53:40 -0500262 BQA_LOGV("transactionCommittedCallback");
263 if (!mSurfaceControlsWithPendingCallback.empty()) {
264 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
265 std::optional<SurfaceControlStats> stat = findMatchingStat(stats, pendingSC);
266 if (stat) {
267 uint64_t currFrameNumber = stat->frameEventStats.frameNumber;
268
269 // We need to check if we were waiting for a transaction callback in order to
270 // process any pending buffers and unblock. It's possible to get transaction
271 // callbacks for previous requests so we need to ensure the frame from this
272 // transaction callback matches the last acquired buffer. Since acquireNextBuffer
273 // will stop processing buffers when mWaitForTransactionCallback is set, we know
274 // that mLastAcquiredFrameNumber is the frame we're waiting on.
275 // We also want to check if mNextTransaction is null because it's possible another
276 // sync request came in while waiting, but it hasn't started processing yet. In that
277 // case, we don't actually want to flush the frames in between since they will get
278 // processed and merged with the sync transaction and released earlier than if they
279 // were sent to SF
chaviwa1c4c822021-11-10 18:11:58 -0600280 if (mWaitForTransactionCallback && mSyncTransaction == nullptr &&
chaviwd7deef72021-10-06 11:53:40 -0500281 currFrameNumber >= mLastAcquiredFrameNumber) {
282 mWaitForTransactionCallback = false;
283 flushShadowQueue();
284 }
285 } else {
chaviw768bfa02021-11-01 09:50:57 -0500286 BQA_LOGE("Failed to find matching SurfaceControl in transactionCommittedCallback");
chaviwd7deef72021-10-06 11:53:40 -0500287 }
288 } else {
289 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
290 "empty.");
291 }
292
293 decStrong((void*)transactionCommittedCallbackThunk);
294 }
295}
296
Robert Carr78c25dd2019-08-15 14:10:33 -0700297static void transactionCallbackThunk(void* context, nsecs_t latchTime,
298 const sp<Fence>& presentFence,
299 const std::vector<SurfaceControlStats>& stats) {
300 if (context == nullptr) {
301 return;
302 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800303 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700304 bq->transactionCallback(latchTime, presentFence, stats);
305}
306
307void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
308 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700309 {
310 std::unique_lock _lock{mMutex};
chaviw57ae4b22022-02-03 16:51:39 -0600311 BBQ_TRACE();
chaviw71c2cc42020-10-23 16:42:02 -0700312 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700313
chaviw42026162021-04-16 15:46:12 -0500314 if (!mSurfaceControlsWithPendingCallback.empty()) {
315 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
316 mSurfaceControlsWithPendingCallback.pop();
chaviwd7deef72021-10-06 11:53:40 -0500317 std::optional<SurfaceControlStats> statsOptional = findMatchingStat(stats, pendingSC);
318 if (statsOptional) {
319 SurfaceControlStats stat = *statsOptional;
chaviw42026162021-04-16 15:46:12 -0500320 mTransformHint = stat.transformHint;
321 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Naira4fbca52021-07-07 16:52:34 -0700322 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700323 // Update frametime stamps if the frame was latched and presented, indicated by a
324 // valid latch time.
325 if (stat.latchTime > 0) {
326 mBufferItemConsumer
327 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
328 stat.frameEventStats.refreshStartTime,
329 stat.frameEventStats.gpuCompositionDoneFence,
330 stat.presentFence, stat.previousReleaseFence,
331 stat.frameEventStats.compositorTiming,
332 stat.latchTime,
333 stat.frameEventStats.dequeueReadyTime);
334 }
chaviwd7deef72021-10-06 11:53:40 -0500335 } else {
chaviw768bfa02021-11-01 09:50:57 -0500336 BQA_LOGE("Failed to find matching SurfaceControl in transactionCallback");
chaviw42026162021-04-16 15:46:12 -0500337 }
338 } else {
339 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
340 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800341 }
chaviw71c2cc42020-10-23 16:42:02 -0700342
chaviw71c2cc42020-10-23 16:42:02 -0700343 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700344 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700345}
346
Vishnu Nair1506b182021-02-22 14:35:15 -0800347// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
348// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
349// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
350// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700351static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
chaviw69058fb2021-09-27 09:37:30 -0500352 const sp<Fence>& releaseFence,
353 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800354 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800355 if (blastBufferQueue) {
chaviw69058fb2021-09-27 09:37:30 -0500356 blastBufferQueue->releaseBufferCallback(id, releaseFence, currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700357 } else {
358 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800359 }
360}
361
chaviwd7deef72021-10-06 11:53:40 -0500362void BLASTBufferQueue::flushShadowQueue() {
363 BQA_LOGV("flushShadowQueue");
364 int numFramesToFlush = mNumFrameAvailable;
365 while (numFramesToFlush > 0) {
366 acquireNextBufferLocked(std::nullopt);
367 numFramesToFlush--;
368 }
369}
370
chaviw69058fb2021-09-27 09:37:30 -0500371void BLASTBufferQueue::releaseBufferCallback(
372 const ReleaseCallbackId& id, const sp<Fence>& releaseFence,
373 std::optional<uint32_t> currentMaxAcquiredBufferCount) {
chaviw57ae4b22022-02-03 16:51:39 -0600374 BBQ_TRACE();
Vishnu Nair1506b182021-02-22 14:35:15 -0800375 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700376 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800377
Ady Abraham899dcdb2021-06-15 16:56:21 -0700378 // Calculate how many buffers we need to hold before we release them back
379 // to the buffer queue. This will prevent higher latency when we are running
380 // on a lower refresh rate than the max supported. We only do that for EGL
381 // clients as others don't care about latency
382 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700383 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700384 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
385 }();
386
chaviw69058fb2021-09-27 09:37:30 -0500387 if (currentMaxAcquiredBufferCount) {
388 mCurrentMaxAcquiredBufferCount = *currentMaxAcquiredBufferCount;
389 }
390
Ady Abraham899dcdb2021-06-15 16:56:21 -0700391 const auto numPendingBuffersToHold =
chaviw69058fb2021-09-27 09:37:30 -0500392 isEGL ? std::max(0u, mMaxAcquiredBuffers - mCurrentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700393 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700394
395 // Release all buffers that are beyond the ones that we need to hold
396 while (mPendingRelease.size() > numPendingBuffersToHold) {
chaviw0acd33a2021-11-02 11:55:37 -0500397 const auto releasedBuffer = mPendingRelease.front();
Ady Abraham899dcdb2021-06-15 16:56:21 -0700398 mPendingRelease.pop_front();
chaviw0acd33a2021-11-02 11:55:37 -0500399 releaseBuffer(releasedBuffer.callbackId, releasedBuffer.releaseFence);
chaviwd7deef72021-10-06 11:53:40 -0500400 // Don't process the transactions here if mWaitForTransactionCallback is set. Instead, let
chaviwa1c4c822021-11-10 18:11:58 -0600401 // onFrameAvailable handle processing them since it will merge with the syncTransaction.
chaviwd7deef72021-10-06 11:53:40 -0500402 if (!mWaitForTransactionCallback) {
403 acquireNextBufferLocked(std::nullopt);
404 }
Vishnu Nair1506b182021-02-22 14:35:15 -0800405 }
406
Ady Abraham899dcdb2021-06-15 16:56:21 -0700407 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700408 ATRACE_INT(mQueuedBufferTrace.c_str(),
409 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800410 mCallbackCV.notify_all();
411}
412
chaviw0acd33a2021-11-02 11:55:37 -0500413void BLASTBufferQueue::releaseBuffer(const ReleaseCallbackId& callbackId,
414 const sp<Fence>& releaseFence) {
415 auto it = mSubmitted.find(callbackId);
416 if (it == mSubmitted.end()) {
417 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
418 callbackId.to_string().c_str());
419 return;
420 }
421 mNumAcquired--;
chaviw57ae4b22022-02-03 16:51:39 -0600422 BBQ_TRACE("frame=%" PRIu64, callbackId.framenumber);
chaviw0acd33a2021-11-02 11:55:37 -0500423 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) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800430 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
431 // include the extra buffer when checking if we can acquire the next buffer.
chaviwd7deef72021-10-06 11:53:40 -0500432 const bool includeExtraAcquire = !transaction;
433 const bool maxAcquired = maxBuffersAcquired(includeExtraAcquire);
434 if (mNumFrameAvailable == 0 || maxAcquired) {
435 BQA_LOGV("Can't process next buffer maxBuffersAcquired=%s", boolToString(maxAcquired));
Valerie Haud3b90d22019-11-06 09:37:31 -0800436 return;
437 }
438
Valerie Haua32c5522019-12-09 10:11:08 -0800439 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700440 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800441 return;
442 }
443
Robert Carr78c25dd2019-08-15 14:10:33 -0700444 SurfaceComposerClient::Transaction localTransaction;
445 bool applyTransaction = true;
446 SurfaceComposerClient::Transaction* t = &localTransaction;
chaviwd7deef72021-10-06 11:53:40 -0500447 if (transaction) {
448 t = *transaction;
Robert Carr78c25dd2019-08-15 14:10:33 -0700449 applyTransaction = false;
450 }
451
Valerie Haua32c5522019-12-09 10:11:08 -0800452 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800453
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800454 status_t status =
455 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800456 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
457 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
458 return;
459 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700460 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700461 return;
462 }
chaviw57ae4b22022-02-03 16:51:39 -0600463
Valerie Haua32c5522019-12-09 10:11:08 -0800464 auto buffer = bufferItem.mGraphicBuffer;
465 mNumFrameAvailable--;
chaviw57ae4b22022-02-03 16:51:39 -0600466 BBQ_TRACE("frame=%" PRIu64, bufferItem.mFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800467
468 if (buffer == nullptr) {
469 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700470 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800471 return;
472 }
473
Vishnu Nair670b3f72020-09-29 17:52:18 -0700474 if (rejectBuffer(bufferItem)) {
Vishnu Naira4fbca52021-07-07 16:52:34 -0700475 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800476 "buffer{size=%dx%d transform=%d}",
477 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
478 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
479 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
chaviwd7deef72021-10-06 11:53:40 -0500480 acquireNextBufferLocked(transaction);
Vishnu Nairea0de002020-11-17 17:42:37 -0800481 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700482 }
483
Valerie Haua32c5522019-12-09 10:11:08 -0800484 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700485 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
486 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
487 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700488
Valerie Hau871d6352020-01-29 08:44:02 -0800489 bool needsDisconnect = false;
490 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
491
492 // if producer disconnected before, notify SurfaceFlinger
493 if (needsDisconnect) {
494 t->notifyProducerDisconnect(mSurfaceControl);
495 }
496
Robert Carr78c25dd2019-08-15 14:10:33 -0700497 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
498 incStrong((void*)transactionCallbackThunk);
499
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 Naird2aaab12022-02-10 14:49:09 -0800518 if (mUpdateDestinationFrame) {
519 t->setDestinationFrame(mSurfaceControl, Rect(mSize));
520 } else {
521 const bool ignoreDestinationFrame =
522 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE;
523 t->setFlags(mSurfaceControl,
524 ignoreDestinationFrame ? layer_state_t::eIgnoreDestinationFrame : 0,
525 layer_state_t::eIgnoreDestinationFrame);
Vishnu Nair084514a2021-07-30 16:07:42 -0700526 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700527 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800528 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800529 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Vishnu Naird2aaab12022-02-10 14:49:09 -0800530 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800531 if (!bufferItem.mIsAutoTimestamp) {
532 t->setDesiredPresentTime(bufferItem.mTimestamp);
533 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700534
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000535 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700536 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000537 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100538 }
539
Vishnu Nairadf632b2021-01-07 14:05:08 -0800540 {
541 std::unique_lock _lock{mTimestampMutex};
542 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
543 if (dequeueTime != mDequeueTimestamps.end()) {
544 Parcel p;
545 p.writeInt64(dequeueTime->second);
546 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
547 mDequeueTimestamps.erase(dequeueTime);
548 }
549 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800550
chaviw6a195272021-09-03 16:14:25 -0500551 mergePendingTransactions(t, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700552 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800553 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700554 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700555
chaviwd7deef72021-10-06 11:53:40 -0500556 BQA_LOGV("acquireNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800557 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Naira4fbca52021-07-07 16:52:34 -0700558 " graphicBufferId=%" PRIu64 "%s transform=%d",
chaviw3277faf2021-05-19 16:45:23 -0500559 mSize.width, mSize.height, bufferItem.mFrameNumber, boolToString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800560 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700561 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Naira4fbca52021-07-07 16:52:34 -0700562 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700563}
564
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800565Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
566 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800567 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800568 }
569 return item.mCrop;
570}
571
chaviwd7deef72021-10-06 11:53:40 -0500572void BLASTBufferQueue::acquireAndReleaseBuffer() {
573 BufferItem bufferItem;
chaviw6ebdf5f2021-10-14 11:57:22 -0500574 status_t status =
575 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
576 if (status != OK) {
577 BQA_LOGE("Failed to acquire a buffer in acquireAndReleaseBuffer, err=%s",
578 statusToString(status).c_str());
579 return;
580 }
chaviwd7deef72021-10-06 11:53:40 -0500581 mNumFrameAvailable--;
chaviw6ebdf5f2021-10-14 11:57:22 -0500582 mBufferItemConsumer->releaseBuffer(bufferItem, bufferItem.mFence);
chaviwd7deef72021-10-06 11:53:40 -0500583}
584
chaviw0acd33a2021-11-02 11:55:37 -0500585void BLASTBufferQueue::flushAndWaitForFreeBuffer(std::unique_lock<std::mutex>& lock) {
586 if (mWaitForTransactionCallback && mNumFrameAvailable > 0) {
587 // We are waiting on a previous sync's transaction callback so allow another sync
588 // transaction to proceed.
589 //
590 // We need to first flush out the transactions that were in between the two syncs.
591 // We do this by merging them into mSyncTransaction so any buffer merging will get
592 // a release callback invoked. The release callback will be async so we need to wait
593 // on max acquired to make sure we have the capacity to acquire another buffer.
594 if (maxBuffersAcquired(false /* includeExtraAcquire */)) {
595 BQA_LOGD("waiting to flush shadow queue...");
596 mCallbackCV.wait(lock);
597 }
598 while (mNumFrameAvailable > 0) {
599 // flush out the shadow queue
600 acquireAndReleaseBuffer();
601 }
602 }
603
604 while (maxBuffersAcquired(false /* includeExtraAcquire */)) {
605 BQA_LOGD("waiting for free buffer.");
606 mCallbackCV.wait(lock);
607 }
608}
609
Vishnu Nairaef1de92020-10-22 12:15:53 -0700610void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
chaviw57ae4b22022-02-03 16:51:39 -0600611 BBQ_TRACE();
Valerie Hau0188adf2020-02-13 08:29:20 -0800612 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800613
chaviwa1c4c822021-11-10 18:11:58 -0600614 const bool syncTransactionSet = mSyncTransaction != nullptr;
615 BQA_LOGV("onFrameAvailable-start syncTransactionSet=%s", boolToString(syncTransactionSet));
chaviw0acd33a2021-11-02 11:55:37 -0500616
chaviwa1c4c822021-11-10 18:11:58 -0600617 if (syncTransactionSet) {
chaviw0acd33a2021-11-02 11:55:37 -0500618 bool mayNeedToWaitForBuffer = true;
619 // If we are going to re-use the same mSyncTransaction, release the buffer that may already
620 // be set in the Transaction. This is to allow us a free slot early to continue processing
621 // a new buffer.
622 if (!mAcquireSingleBuffer) {
623 auto bufferData = mSyncTransaction->getAndClearBuffer(mSurfaceControl);
624 if (bufferData) {
625 BQA_LOGD("Releasing previous buffer when syncing: framenumber=%" PRIu64,
626 bufferData->frameNumber);
chaviw8dd181f2022-01-05 18:36:46 -0600627 releaseBuffer(bufferData->generateReleaseCallbackId(), bufferData->acquireFence);
chaviw0acd33a2021-11-02 11:55:37 -0500628 // Because we just released a buffer, we know there's no need to wait for a free
629 // buffer.
630 mayNeedToWaitForBuffer = false;
chaviwd7deef72021-10-06 11:53:40 -0500631 }
632 }
633
chaviw0acd33a2021-11-02 11:55:37 -0500634 if (mayNeedToWaitForBuffer) {
635 flushAndWaitForFreeBuffer(_lock);
Valerie Hau0188adf2020-02-13 08:29:20 -0800636 }
637 }
chaviwd7deef72021-10-06 11:53:40 -0500638
Valerie Haud3b90d22019-11-06 09:37:31 -0800639 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800640 mNumFrameAvailable++;
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800641 if (mWaitForTransactionCallback && mNumFrameAvailable >= 2) {
Robert Carrcf2f21f2021-11-30 14:47:02 -0800642 acquireAndReleaseBuffer();
643 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700644 ATRACE_INT(mQueuedBufferTrace.c_str(),
645 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800646
chaviwa1c4c822021-11-10 18:11:58 -0600647 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " syncTransactionSet=%s", item.mFrameNumber,
648 boolToString(syncTransactionSet));
chaviwd7deef72021-10-06 11:53:40 -0500649
chaviwa1c4c822021-11-10 18:11:58 -0600650 if (syncTransactionSet) {
chaviw0acd33a2021-11-02 11:55:37 -0500651 acquireNextBufferLocked(mSyncTransaction);
chaviwf2dace72021-11-17 17:36:50 -0600652
653 // Only need a commit callback when syncing to ensure the buffer that's synced has been sent
654 // to SF
655 incStrong((void*)transactionCommittedCallbackThunk);
656 mSyncTransaction->addTransactionCommittedCallback(transactionCommittedCallbackThunk,
657 static_cast<void*>(this));
658
chaviw0acd33a2021-11-02 11:55:37 -0500659 if (mAcquireSingleBuffer) {
660 mSyncTransaction = nullptr;
661 }
chaviwd7deef72021-10-06 11:53:40 -0500662 mWaitForTransactionCallback = true;
663 } else if (!mWaitForTransactionCallback) {
664 acquireNextBufferLocked(std::nullopt);
665 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800666}
667
Vishnu Nairaef1de92020-10-22 12:15:53 -0700668void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
669 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
670 // Do nothing since we are not storing unacquired buffer items locally.
671}
672
Vishnu Nairadf632b2021-01-07 14:05:08 -0800673void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
674 std::unique_lock _lock{mTimestampMutex};
675 mDequeueTimestamps[bufferId] = systemTime();
676};
677
678void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
679 std::unique_lock _lock{mTimestampMutex};
680 mDequeueTimestamps.erase(bufferId);
681};
682
chaviw0acd33a2021-11-02 11:55:37 -0500683void BLASTBufferQueue::setSyncTransaction(SurfaceComposerClient::Transaction* t,
684 bool acquireSingleBuffer) {
chaviw57ae4b22022-02-03 16:51:39 -0600685 BBQ_TRACE();
Valerie Haud3b90d22019-11-06 09:37:31 -0800686 std::lock_guard _lock{mMutex};
chaviwa1c4c822021-11-10 18:11:58 -0600687 mSyncTransaction = t;
chaviw0acd33a2021-11-02 11:55:37 -0500688 mAcquireSingleBuffer = mSyncTransaction ? acquireSingleBuffer : true;
Robert Carr78c25dd2019-08-15 14:10:33 -0700689}
690
Vishnu Nairea0de002020-11-17 17:42:37 -0800691bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700692 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
693 // Only reject buffers if scaling mode is freeze.
694 return false;
695 }
696
Vishnu Naire1a42322020-10-02 17:42:04 -0700697 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
698 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
699
700 // Take the buffer's orientation into account
701 if (item.mTransform & ui::Transform::ROT_90) {
702 std::swap(bufWidth, bufHeight);
703 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800704 ui::Size bufferSize(bufWidth, bufHeight);
705 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800706 return false;
707 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700708
Vishnu Nair670b3f72020-09-29 17:52:18 -0700709 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800710 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700711}
Vishnu Nairbf255772020-10-16 10:54:41 -0700712
713// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800714// Consumer can acquire an additional buffer if that buffer is not droppable. Set
715// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
716// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
717bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700718 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1e8bf102021-12-28 14:36:59 -0800719 return mNumAcquired >= maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700720}
721
Robert Carr05086b22020-10-13 18:22:51 -0700722class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700723private:
Vishnu Nair95b6d512021-08-30 15:31:08 -0700724 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700725 sp<BLASTBufferQueue> mBbq;
Vishnu Nair95b6d512021-08-30 15:31:08 -0700726 bool mDestroyed = false;
727
Robert Carr05086b22020-10-13 18:22:51 -0700728public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700729 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
730 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
731 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700732
Robert Carr05086b22020-10-13 18:22:51 -0700733 void allocateBuffers() override {
734 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
735 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
736 auto gbp = getIGraphicBufferProducer();
737 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
738 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
739 gbp->allocateBuffers(reqWidth, reqHeight,
740 reqFormat, reqUsage);
741
742 }).detach();
743 }
Robert Carr9c006e02020-10-14 13:41:57 -0700744
Marin Shalamanovc5986772021-03-16 16:09:49 +0100745 status_t setFrameRate(float frameRate, int8_t compatibility,
746 int8_t changeFrameRateStrategy) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700747 std::unique_lock _lock{mMutex};
748 if (mDestroyed) {
749 return DEAD_OBJECT;
750 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100751 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
752 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700753 return BAD_VALUE;
754 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100755 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700756 }
Robert Carr9b611b72020-10-19 12:00:23 -0700757
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000758 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nair95b6d512021-08-30 15:31:08 -0700759 std::unique_lock _lock{mMutex};
760 if (mDestroyed) {
761 return DEAD_OBJECT;
762 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000763 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700764 }
Vishnu Nair95b6d512021-08-30 15:31:08 -0700765
766 void destroy() override {
767 Surface::destroy();
768
769 std::unique_lock _lock{mMutex};
770 mDestroyed = true;
771 mBbq = nullptr;
772 }
Robert Carr05086b22020-10-13 18:22:51 -0700773};
774
Robert Carr9c006e02020-10-14 13:41:57 -0700775// TODO: Can we coalesce this with frame updates? Need to confirm
776// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200777status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
778 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700779 std::unique_lock _lock{mMutex};
780 SurfaceComposerClient::Transaction t;
781
Marin Shalamanov46084422020-10-13 12:33:42 +0200782 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700783}
784
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000785status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700786 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000787 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100788 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700789}
790
Hongguang Chen621ec582021-02-16 15:42:35 -0800791void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
792 std::unique_lock _lock{mMutex};
793 SurfaceComposerClient::Transaction t;
794
795 t.setSidebandStream(mSurfaceControl, stream).apply();
796}
797
Vishnu Nair992496b2020-10-22 17:27:21 -0700798sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
799 std::unique_lock _lock{mMutex};
800 sp<IBinder> scHandle = nullptr;
801 if (includeSurfaceControlHandle && mSurfaceControl) {
802 scHandle = mSurfaceControl->getHandle();
803 }
804 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700805}
806
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800807void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
808 uint64_t frameNumber) {
809 std::lock_guard _lock{mMutex};
810 if (mLastAcquiredFrameNumber >= frameNumber) {
811 // Apply the transaction since we have already acquired the desired frame.
812 t->apply();
813 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500814 mPendingTransactions.emplace_back(frameNumber, *t);
815 // Clear the transaction so it can't be applied elsewhere.
816 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800817 }
818}
819
chaviw6a195272021-09-03 16:14:25 -0500820void BLASTBufferQueue::applyPendingTransactions(uint64_t frameNumber) {
821 std::lock_guard _lock{mMutex};
822
823 SurfaceComposerClient::Transaction t;
824 mergePendingTransactions(&t, frameNumber);
825 t.setApplyToken(mApplyToken).apply();
826}
827
828void BLASTBufferQueue::mergePendingTransactions(SurfaceComposerClient::Transaction* t,
829 uint64_t frameNumber) {
830 auto mergeTransaction =
831 [&t, currentFrameNumber = frameNumber](
832 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
833 auto& [targetFrameNumber, transaction] = pendingTransaction;
834 if (currentFrameNumber < targetFrameNumber) {
835 return false;
836 }
837 t->merge(std::move(transaction));
838 return true;
839 };
840
841 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
842 mPendingTransactions.end(), mergeTransaction),
843 mPendingTransactions.end());
844}
845
chaviwd84085a2022-02-08 11:07:04 -0600846SurfaceComposerClient::Transaction* BLASTBufferQueue::gatherPendingTransactions(
847 uint64_t frameNumber) {
848 std::lock_guard _lock{mMutex};
849 SurfaceComposerClient::Transaction* t = new SurfaceComposerClient::Transaction();
850 mergePendingTransactions(t, frameNumber);
851 return t;
852}
853
Vishnu Nair89496122020-12-14 17:14:53 -0800854// Maintains a single worker thread per process that services a list of runnables.
855class AsyncWorker : public Singleton<AsyncWorker> {
856private:
857 std::thread mThread;
858 bool mDone = false;
859 std::deque<std::function<void()>> mRunnables;
860 std::mutex mMutex;
861 std::condition_variable mCv;
862 void run() {
863 std::unique_lock<std::mutex> lock(mMutex);
864 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800865 while (!mRunnables.empty()) {
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700866 std::deque<std::function<void()>> runnables = std::move(mRunnables);
867 mRunnables.clear();
868 lock.unlock();
869 // Run outside the lock since the runnable might trigger another
870 // post to the async worker.
871 execute(runnables);
872 lock.lock();
Vishnu Nair89496122020-12-14 17:14:53 -0800873 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700874 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800875 }
876 }
877
Vishnu Nair51e4dc82021-10-01 15:32:33 -0700878 void execute(std::deque<std::function<void()>>& runnables) {
879 while (!runnables.empty()) {
880 std::function<void()> runnable = runnables.front();
881 runnables.pop_front();
882 runnable();
883 }
884 }
885
Vishnu Nair89496122020-12-14 17:14:53 -0800886public:
887 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
888
889 ~AsyncWorker() {
890 mDone = true;
891 mCv.notify_all();
892 if (mThread.joinable()) {
893 mThread.join();
894 }
895 }
896
897 void post(std::function<void()> runnable) {
898 std::unique_lock<std::mutex> lock(mMutex);
899 mRunnables.emplace_back(std::move(runnable));
900 mCv.notify_one();
901 }
902};
903ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
904
905// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
906class AsyncProducerListener : public BnProducerListener {
907private:
908 const sp<IProducerListener> mListener;
909
910public:
911 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
912
913 void onBufferReleased() override {
914 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
915 }
916
917 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
918 AsyncWorker::getInstance().post(
919 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
920 }
921};
922
923// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
924// can be non-blocking when the producer is in the client process.
925class BBQBufferQueueProducer : public BufferQueueProducer {
926public:
927 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
928 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
929
930 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
931 QueueBufferOutput* output) override {
932 if (!listener) {
933 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
934 }
935
936 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
937 producerControlledByApp, output);
938 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800939
940 int query(int what, int* value) override {
941 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
942 *value = 1;
943 return NO_ERROR;
944 }
945 return BufferQueueProducer::query(what, value);
946 }
Vishnu Nair89496122020-12-14 17:14:53 -0800947};
948
949// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
950// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
951// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
952// we can deadlock.
953void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
954 sp<IGraphicBufferConsumer>* outConsumer) {
955 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
956 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
957
958 sp<BufferQueueCore> core(new BufferQueueCore());
959 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
960
961 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
962 LOG_ALWAYS_FATAL_IF(producer == nullptr,
963 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
964
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800965 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
966 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800967 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
968 "BLASTBufferQueue: failed to create BufferQueueConsumer");
969
970 *outProducer = producer;
971 *outConsumer = consumer;
972}
973
chaviw497e81c2021-02-04 17:09:47 -0800974PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
975 PixelFormat convertedFormat = format;
976 switch (format) {
977 case PIXEL_FORMAT_TRANSPARENT:
978 case PIXEL_FORMAT_TRANSLUCENT:
979 convertedFormat = PIXEL_FORMAT_RGBA_8888;
980 break;
981 case PIXEL_FORMAT_OPAQUE:
982 convertedFormat = PIXEL_FORMAT_RGBX_8888;
983 break;
984 }
985 return convertedFormat;
986}
987
Robert Carr82d07c92021-05-10 11:36:43 -0700988uint32_t BLASTBufferQueue::getLastTransformHint() const {
989 if (mSurfaceControl != nullptr) {
990 return mSurfaceControl->getTransformHint();
991 } else {
992 return 0;
993 }
994}
995
chaviw0b020f82021-08-20 12:00:47 -0500996uint64_t BLASTBufferQueue::getLastAcquiredFrameNum() {
997 std::unique_lock _lock{mMutex};
998 return mLastAcquiredFrameNumber;
999}
1000
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001001void BLASTBufferQueue::abandon() {
1002 std::unique_lock _lock{mMutex};
1003 // flush out the shadow queue
1004 while (mNumFrameAvailable > 0) {
1005 acquireAndReleaseBuffer();
1006 }
1007
1008 // Clear submitted buffer states
1009 mNumAcquired = 0;
1010 mSubmitted.clear();
1011 mPendingRelease.clear();
1012
1013 if (!mPendingTransactions.empty()) {
1014 BQA_LOGD("Applying pending transactions on abandon %d",
1015 static_cast<uint32_t>(mPendingTransactions.size()));
1016 SurfaceComposerClient::Transaction t;
1017 mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
1018 t.setApplyToken(mApplyToken).apply();
1019 }
1020
1021 // Clear sync states
1022 if (mWaitForTransactionCallback) {
1023 BQA_LOGD("mWaitForTransactionCallback cleared");
1024 mWaitForTransactionCallback = false;
1025 }
1026
1027 if (mSyncTransaction != nullptr) {
1028 BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
1029 mAcquireSingleBuffer ? "true" : "false");
1030 mSyncTransaction = nullptr;
1031 mAcquireSingleBuffer = false;
1032 }
1033
1034 // abandon buffer queue
1035 if (mBufferItemConsumer != nullptr) {
1036 mBufferItemConsumer->abandon();
1037 mBufferItemConsumer->setFrameAvailableListener(nullptr);
1038 mBufferItemConsumer->setBufferFreedListener(nullptr);
Vishnu Nair1e8bf102021-12-28 14:36:59 -08001039 }
1040 mBufferItemConsumer = nullptr;
1041 mConsumer = nullptr;
1042 mProducer = nullptr;
1043}
1044
1045bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
1046 std::unique_lock _lock{mMutex};
1047 return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
1048}
1049
Robert Carr78c25dd2019-08-15 14:10:33 -07001050} // namespace android