blob: 5b59c592dfb16b631ee6899b3ef444b5f909ddab [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 {
41inline const char* toString(bool b) {
42 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
49#define BQA_LOGV(x, ...) \
50 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080051// enable logs for a single layer
52//#define BQA_LOGV(x, ...) \
53// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
54// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070055#define BQA_LOGE(x, ...) \
56 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
57
Valerie Hau871d6352020-01-29 08:44:02 -080058void BLASTBufferItemConsumer::onDisconnect() {
Hongguang Chen621ec582021-02-16 15:42:35 -080059 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080060 mPreviouslyConnected = mCurrentlyConnected;
61 mCurrentlyConnected = false;
62 if (mPreviouslyConnected) {
63 mDisconnectEvents.push(mCurrentFrameNumber);
64 }
65 mFrameEventHistory.onDisconnect();
66}
67
68void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
69 FrameEventHistoryDelta* outDelta) {
Hongguang Chen621ec582021-02-16 15:42:35 -080070 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080071 if (newTimestamps) {
72 // BufferQueueProducer only adds a new timestamp on
73 // queueBuffer
74 mCurrentFrameNumber = newTimestamps->frameNumber;
75 mFrameEventHistory.addQueue(*newTimestamps);
76 }
77 if (outDelta) {
78 // frame event histories will be processed
79 // only after the producer connects and requests
80 // deltas for the first time. Forward this intent
81 // to SF-side to turn event processing back on
82 mPreviouslyConnected = mCurrentlyConnected;
83 mCurrentlyConnected = true;
84 mFrameEventHistory.getAndResetDelta(outDelta);
85 }
86}
87
88void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
89 const sp<Fence>& glDoneFence,
90 const sp<Fence>& presentFence,
91 const sp<Fence>& prevReleaseFence,
92 CompositorTiming compositorTiming,
93 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
Hongguang Chen621ec582021-02-16 15:42:35 -080094 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -080095
96 // if the producer is not connected, don't bother updating,
97 // the next producer that connects won't access this frame event
98 if (!mCurrentlyConnected) return;
99 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
100 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
101 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
102
103 mFrameEventHistory.addLatch(frameNumber, latchTime);
104 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
105 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
106 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
107 compositorTiming);
108}
109
110void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
111 bool disconnect = false;
Hongguang Chen621ec582021-02-16 15:42:35 -0800112 Mutex::Autolock lock(mMutex);
Valerie Hau871d6352020-01-29 08:44:02 -0800113 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
114 disconnect = true;
115 mDisconnectEvents.pop();
116 }
117 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
118}
119
Hongguang Chen621ec582021-02-16 15:42:35 -0800120void BLASTBufferItemConsumer::onSidebandStreamChanged() {
Ady Abrahamdc76ca02021-12-15 11:58:56 -0800121 sp<BLASTBufferQueue> bbq = mBLASTBufferQueue.promote();
122 if (bbq != nullptr) {
Hongguang Chen621ec582021-02-16 15:42:35 -0800123 sp<NativeHandle> stream = getSidebandStream();
Ady Abrahamdc76ca02021-12-15 11:58:56 -0800124 bbq->setSidebandStream(stream);
Hongguang Chen621ec582021-02-16 15:42:35 -0800125 }
126}
127
Vishnu Nairdab94092020-09-29 16:09:04 -0700128BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700129 int width, int height, int32_t format)
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700130 : mSurfaceControl(surface),
Vishnu Nairea0de002020-11-17 17:42:37 -0800131 mSize(width, height),
132 mRequestedSize(mSize),
chaviw565ee542021-01-14 10:21:23 -0800133 mFormat(format),
Valerie Haud3b90d22019-11-06 09:37:31 -0800134 mNextTransaction(nullptr) {
Vishnu Nair89496122020-12-14 17:14:53 -0800135 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800136 // since the adapter is in the client process, set dequeue timeout
137 // explicitly so that dequeueBuffer will block
138 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800139
Vishnu Nairdebd1cb2021-03-16 10:06:01 -0700140 // safe default, most producers are expected to override this
141 mProducer->setMaxDequeuedBufferCount(2);
Vishnu Nair1618c672021-02-05 13:08:26 -0800142 mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,
143 GraphicBuffer::USAGE_HW_COMPOSER |
144 GraphicBuffer::USAGE_HW_TEXTURE,
Ady Abrahamdc76ca02021-12-15 11:58:56 -0800145 1, false, this);
Valerie Haua32c5522019-12-09 10:11:08 -0800146 static int32_t id = 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700147 mName = name + "#" + std::to_string(id);
Vishnu Nairdab94092020-09-29 16:09:04 -0700148 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700149 mQueuedBufferTrace = "QueuedBuffer - " + mName + "BLAST#" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800150 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700151 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700152 mBufferItemConsumer->setFrameAvailableListener(this);
153 mBufferItemConsumer->setBufferFreedListener(this);
Vishnu Nairea0de002020-11-17 17:42:37 -0800154 mBufferItemConsumer->setDefaultBufferSize(mSize.width, mSize.height);
chaviw497e81c2021-02-04 17:09:47 -0800155 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
Robert Carr9f133d72020-04-01 15:51:46 -0700156
Ady Abraham899dcdb2021-06-15 16:56:21 -0700157 ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);
Ady Abraham0bde6b52021-05-18 13:57:02 -0700158 mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
159
Valerie Hau2882e982020-01-23 13:33:10 -0800160 mTransformHint = mSurfaceControl->getTransformHint();
Robert Carr9f133d72020-04-01 15:51:46 -0700161 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800162 SurfaceComposerClient::Transaction()
Vishnu Nair084514a2021-07-30 16:07:42 -0700163 .setFlags(surface, layer_state_t::eEnableBackpressure,
164 layer_state_t::eEnableBackpressure)
165 .setApplyToken(mApplyToken)
166 .apply();
Valerie Haua32c5522019-12-09 10:11:08 -0800167 mNumAcquired = 0;
168 mNumFrameAvailable = 0;
Vishnu Nair9c161282021-07-07 16:52:34 -0700169 BQA_LOGV("BLASTBufferQueue created width=%d height=%d format=%d mTransformHint=%d", width,
170 height, format, mTransformHint);
Robert Carr78c25dd2019-08-15 14:10:33 -0700171}
172
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800173BLASTBufferQueue::~BLASTBufferQueue() {
174 if (mPendingTransactions.empty()) {
175 return;
176 }
177 BQA_LOGE("Applying pending transactions on dtor %d",
178 static_cast<uint32_t>(mPendingTransactions.size()));
179 SurfaceComposerClient::Transaction t;
180 for (auto& [targetFrameNumber, transaction] : mPendingTransactions) {
181 t.merge(std::move(transaction));
182 }
183 t.apply();
184}
185
chaviw565ee542021-01-14 10:21:23 -0800186void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,
Vishnu Nair084514a2021-07-30 16:07:42 -0700187 int32_t format, SurfaceComposerClient::Transaction* outTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700188 std::unique_lock _lock{mMutex};
chaviw565ee542021-01-14 10:21:23 -0800189 if (mFormat != format) {
190 mFormat = format;
chaviw497e81c2021-02-04 17:09:47 -0800191 mBufferItemConsumer->setDefaultBufferFormat(convertBufferFormat(format));
chaviw565ee542021-01-14 10:21:23 -0800192 }
193
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800194 SurfaceComposerClient::Transaction t;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700195 const bool setBackpressureFlag = !SurfaceControl::isSameSurface(mSurfaceControl, surface);
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800196 bool applyTransaction = false;
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800197
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700198 // Always update the native object even though they might have the same layer handle, so we can
199 // get the updated transform hint from WM.
200 mSurfaceControl = surface;
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800201 if (mSurfaceControl != nullptr) {
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700202 if (setBackpressureFlag) {
203 t.setFlags(mSurfaceControl, layer_state_t::eEnableBackpressure,
204 layer_state_t::eEnableBackpressure);
205 applyTransaction = true;
206 }
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800207 mTransformHint = mSurfaceControl->getTransformHint();
208 mBufferItemConsumer->setTransformHint(mTransformHint);
209 }
Vishnu Nair9c161282021-07-07 16:52:34 -0700210 BQA_LOGV("update width=%d height=%d format=%d mTransformHint=%d", width, height, format,
211 mTransformHint);
Arthur Hungb6aa9a02021-06-09 14:23:01 +0800212
Vishnu Nairea0de002020-11-17 17:42:37 -0800213 ui::Size newSize(width, height);
214 if (mRequestedSize != newSize) {
215 mRequestedSize.set(newSize);
216 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000217 if (mLastBufferInfo.scalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Vishnu Nair53c936c2020-12-03 11:46:37 -0800218 // If the buffer supports scaling, update the frame immediately since the client may
219 // want to scale the existing buffer to the new size.
220 mSize = mRequestedSize;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000221 // We only need to update the scale if we've received at least one buffer. The reason
222 // for this is the scale is calculated based on the requested size and buffer size.
223 // If there's no buffer, the scale will always be 1.
Vishnu Nair084514a2021-07-30 16:07:42 -0700224 SurfaceComposerClient::Transaction* destFrameTransaction =
225 (outTransaction) ? outTransaction : &t;
Vishnu Nair5fa91c22021-06-29 14:30:48 -0700226 if (mSurfaceControl != nullptr && mLastBufferInfo.hasBuffer) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700227 destFrameTransaction->setDestinationFrame(mSurfaceControl,
228 Rect(0, 0, newSize.getWidth(),
229 newSize.getHeight()));
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000230 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800231 applyTransaction = true;
Vishnu Nair53c936c2020-12-03 11:46:37 -0800232 }
Robert Carrfc416512020-04-02 12:32:44 -0700233 }
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800234 if (applyTransaction) {
Vishnu Nair084514a2021-07-30 16:07:42 -0700235 t.setApplyToken(mApplyToken).apply();
Vishnu Nairf6eddb62021-01-27 22:02:11 -0800236 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700237}
238
239static void transactionCallbackThunk(void* context, nsecs_t latchTime,
240 const sp<Fence>& presentFence,
241 const std::vector<SurfaceControlStats>& stats) {
242 if (context == nullptr) {
243 return;
244 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800245 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700246 bq->transactionCallback(latchTime, presentFence, stats);
247}
248
249void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
250 const std::vector<SurfaceControlStats>& stats) {
chaviw71c2cc42020-10-23 16:42:02 -0700251 std::function<void(int64_t)> transactionCompleteCallback = nullptr;
252 uint64_t currFrameNumber = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700253
chaviw71c2cc42020-10-23 16:42:02 -0700254 {
255 std::unique_lock _lock{mMutex};
256 ATRACE_CALL();
257 BQA_LOGV("transactionCallback");
chaviw71c2cc42020-10-23 16:42:02 -0700258
chaviw42026162021-04-16 15:46:12 -0500259 if (!mSurfaceControlsWithPendingCallback.empty()) {
260 sp<SurfaceControl> pendingSC = mSurfaceControlsWithPendingCallback.front();
261 mSurfaceControlsWithPendingCallback.pop();
262 bool found = false;
263 for (auto stat : stats) {
264 if (!SurfaceControl::isSameSurface(pendingSC, stat.surfaceControl)) {
265 continue;
Vishnu Nair1506b182021-02-22 14:35:15 -0800266 }
chaviw42026162021-04-16 15:46:12 -0500267
268 mTransformHint = stat.transformHint;
269 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nair9c161282021-07-07 16:52:34 -0700270 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Vishnu Nairde66dc72021-06-17 17:54:41 -0700271 // Update frametime stamps if the frame was latched and presented, indicated by a
272 // valid latch time.
273 if (stat.latchTime > 0) {
274 mBufferItemConsumer
275 ->updateFrameTimestamps(stat.frameEventStats.frameNumber,
276 stat.frameEventStats.refreshStartTime,
277 stat.frameEventStats.gpuCompositionDoneFence,
278 stat.presentFence, stat.previousReleaseFence,
279 stat.frameEventStats.compositorTiming,
280 stat.latchTime,
281 stat.frameEventStats.dequeueReadyTime);
282 }
chaviw42026162021-04-16 15:46:12 -0500283 currFrameNumber = stat.frameEventStats.frameNumber;
284
285 if (mTransactionCompleteCallback &&
286 currFrameNumber >= mTransactionCompleteFrameNumber) {
287 if (currFrameNumber > mTransactionCompleteFrameNumber) {
288 BQA_LOGE("transactionCallback received for a newer framenumber=%" PRIu64
289 " than expected=%" PRIu64,
290 currFrameNumber, mTransactionCompleteFrameNumber);
291 }
292 transactionCompleteCallback = std::move(mTransactionCompleteCallback);
293 mTransactionCompleteFrameNumber = 0;
294 }
295
296 found = true;
297 break;
chaviw71c2cc42020-10-23 16:42:02 -0700298 }
chaviw42026162021-04-16 15:46:12 -0500299
300 if (!found) {
301 BQA_LOGE("Failed to find matching SurfaceControl in transaction callback");
302 }
303 } else {
304 BQA_LOGE("No matching SurfaceControls found: mSurfaceControlsWithPendingCallback was "
305 "empty.");
Valerie Haua32c5522019-12-09 10:11:08 -0800306 }
chaviw71c2cc42020-10-23 16:42:02 -0700307
chaviw71c2cc42020-10-23 16:42:02 -0700308 decStrong((void*)transactionCallbackThunk);
Robert Carr78c25dd2019-08-15 14:10:33 -0700309 }
Valerie Haua32c5522019-12-09 10:11:08 -0800310
chaviw71c2cc42020-10-23 16:42:02 -0700311 if (transactionCompleteCallback) {
312 transactionCompleteCallback(currFrameNumber);
Valerie Haua32c5522019-12-09 10:11:08 -0800313 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700314}
315
Vishnu Nair1506b182021-02-22 14:35:15 -0800316// Unlike transactionCallbackThunk the release buffer callback does not extend the life of the
317// BBQ. This is because if the BBQ is destroyed, then the buffers will be released by the client.
318// So we pass in a weak pointer to the BBQ and if it still alive, then we release the buffer.
319// Otherwise, this is a no-op.
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700320static void releaseBufferCallbackThunk(wp<BLASTBufferQueue> context, const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700321 const sp<Fence>& releaseFence, uint32_t transformHint,
322 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800323 sp<BLASTBufferQueue> blastBufferQueue = context.promote();
Vishnu Nair1506b182021-02-22 14:35:15 -0800324 if (blastBufferQueue) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700325 blastBufferQueue->releaseBufferCallback(id, releaseFence, transformHint,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700326 currentMaxAcquiredBufferCount);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700327 } else {
328 ALOGV("releaseBufferCallbackThunk %s blastBufferQueue is dead", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800329 }
330}
331
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700332void BLASTBufferQueue::releaseBufferCallback(const ReleaseCallbackId& id,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700333 const sp<Fence>& releaseFence, uint32_t transformHint,
334 uint32_t currentMaxAcquiredBufferCount) {
Vishnu Nair1506b182021-02-22 14:35:15 -0800335 ATRACE_CALL();
336 std::unique_lock _lock{mMutex};
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700337 BQA_LOGV("releaseBufferCallback %s", id.to_string().c_str());
Vishnu Nair1506b182021-02-22 14:35:15 -0800338
Robert Carr82d07c92021-05-10 11:36:43 -0700339 if (mSurfaceControl != nullptr) {
Robert Carr97e7cc02021-06-07 10:45:40 -0700340 mTransformHint = transformHint;
341 mSurfaceControl->setTransformHint(transformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700342 mBufferItemConsumer->setTransformHint(mTransformHint);
Vishnu Nair9c161282021-07-07 16:52:34 -0700343 BQA_LOGV("updated mTransformHint=%d", mTransformHint);
Robert Carr82d07c92021-05-10 11:36:43 -0700344 }
345
Ady Abraham899dcdb2021-06-15 16:56:21 -0700346 // Calculate how many buffers we need to hold before we release them back
347 // to the buffer queue. This will prevent higher latency when we are running
348 // on a lower refresh rate than the max supported. We only do that for EGL
349 // clients as others don't care about latency
350 const bool isEGL = [&] {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700351 const auto it = mSubmitted.find(id);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700352 return it != mSubmitted.end() && it->second.mApi == NATIVE_WINDOW_API_EGL;
353 }();
354
355 const auto numPendingBuffersToHold =
356 isEGL ? std::max(0u, mMaxAcquiredBuffers - currentMaxAcquiredBufferCount) : 0;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700357 mPendingRelease.emplace_back(ReleasedBuffer{id, releaseFence});
Ady Abraham899dcdb2021-06-15 16:56:21 -0700358
359 // Release all buffers that are beyond the ones that we need to hold
360 while (mPendingRelease.size() > numPendingBuffersToHold) {
361 const auto releaseBuffer = mPendingRelease.front();
362 mPendingRelease.pop_front();
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700363 auto it = mSubmitted.find(releaseBuffer.callbackId);
Ady Abraham899dcdb2021-06-15 16:56:21 -0700364 if (it == mSubmitted.end()) {
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700365 BQA_LOGE("ERROR: releaseBufferCallback without corresponding submitted buffer %s",
366 releaseBuffer.callbackId.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700367 return;
368 }
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700369 mNumAcquired--;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700370 BQA_LOGV("released %s", id.to_string().c_str());
Ady Abraham899dcdb2021-06-15 16:56:21 -0700371 mBufferItemConsumer->releaseBuffer(it->second, releaseBuffer.releaseFence);
372 mSubmitted.erase(it);
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700373 processNextBufferLocked(false /* useNextTransaction */);
Vishnu Nair1506b182021-02-22 14:35:15 -0800374 }
375
Ady Abraham899dcdb2021-06-15 16:56:21 -0700376 ATRACE_INT("PendingRelease", mPendingRelease.size());
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700377 ATRACE_INT(mQueuedBufferTrace.c_str(),
378 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800379 mCallbackCV.notify_all();
380}
381
Robert Carr255acdc2020-04-17 14:08:55 -0700382void BLASTBufferQueue::processNextBufferLocked(bool useNextTransaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800383 ATRACE_CALL();
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800384 // If the next transaction is set, we want to guarantee the our acquire will not fail, so don't
385 // include the extra buffer when checking if we can acquire the next buffer.
386 const bool includeExtraAcquire = !useNextTransaction;
387 if (mNumFrameAvailable == 0 || maxBuffersAcquired(includeExtraAcquire)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800388 mCallbackCV.notify_all();
Valerie Haud3b90d22019-11-06 09:37:31 -0800389 return;
390 }
391
Valerie Haua32c5522019-12-09 10:11:08 -0800392 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700393 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800394 return;
395 }
396
Robert Carr78c25dd2019-08-15 14:10:33 -0700397 SurfaceComposerClient::Transaction localTransaction;
398 bool applyTransaction = true;
399 SurfaceComposerClient::Transaction* t = &localTransaction;
Robert Carr255acdc2020-04-17 14:08:55 -0700400 if (mNextTransaction != nullptr && useNextTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700401 t = mNextTransaction;
402 mNextTransaction = nullptr;
403 applyTransaction = false;
404 }
405
Valerie Haua32c5522019-12-09 10:11:08 -0800406 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800407
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800408 status_t status =
409 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800410 if (status == BufferQueue::NO_BUFFER_AVAILABLE) {
411 BQA_LOGV("Failed to acquire a buffer, err=NO_BUFFER_AVAILABLE");
412 return;
413 } else if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700414 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700415 return;
416 }
Valerie Haua32c5522019-12-09 10:11:08 -0800417 auto buffer = bufferItem.mGraphicBuffer;
418 mNumFrameAvailable--;
419
420 if (buffer == nullptr) {
421 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700422 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800423 return;
424 }
425
Vishnu Nair670b3f72020-09-29 17:52:18 -0700426 if (rejectBuffer(bufferItem)) {
Vishnu Nair9c161282021-07-07 16:52:34 -0700427 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d "
Vishnu Nairea0de002020-11-17 17:42:37 -0800428 "buffer{size=%dx%d transform=%d}",
429 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
430 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
431 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
432 processNextBufferLocked(useNextTransaction);
433 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700434 }
435
Valerie Haua32c5522019-12-09 10:11:08 -0800436 mNumAcquired++;
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700437 mLastAcquiredFrameNumber = bufferItem.mFrameNumber;
438 ReleaseCallbackId releaseCallbackId(buffer->getId(), mLastAcquiredFrameNumber);
439 mSubmitted[releaseCallbackId] = bufferItem;
Robert Carr78c25dd2019-08-15 14:10:33 -0700440
Valerie Hau871d6352020-01-29 08:44:02 -0800441 bool needsDisconnect = false;
442 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
443
444 // if producer disconnected before, notify SurfaceFlinger
445 if (needsDisconnect) {
446 t->notifyProducerDisconnect(mSurfaceControl);
447 }
448
Robert Carr78c25dd2019-08-15 14:10:33 -0700449 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
450 incStrong((void*)transactionCallbackThunk);
451
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700452 Rect crop = computeCrop(bufferItem);
Vishnu Nair084514a2021-07-30 16:07:42 -0700453 const bool updateDestinationFrame =
454 bufferItem.mScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE ||
455 !mLastBufferInfo.hasBuffer;
Chavi Weingartena5aedbd2021-04-09 13:37:33 +0000456 mLastBufferInfo.update(true /* hasBuffer */, bufferItem.mGraphicBuffer->getWidth(),
457 bufferItem.mGraphicBuffer->getHeight(), bufferItem.mTransform,
Vishnu Nair5cc9ac02021-04-19 13:23:38 -0700458 bufferItem.mScalingMode, crop);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800459
Vishnu Nair1506b182021-02-22 14:35:15 -0800460 auto releaseBufferCallback =
461 std::bind(releaseBufferCallbackThunk, wp<BLASTBufferQueue>(this) /* callbackContext */,
Ady Abraham899dcdb2021-06-15 16:56:21 -0700462 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
463 std::placeholders::_4);
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700464 t->setBuffer(mSurfaceControl, buffer, releaseCallbackId, releaseBufferCallback);
John Reck137069e2020-12-10 22:07:37 -0500465 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
466 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
467 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700468 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800469 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700470 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
chaviw42026162021-04-16 15:46:12 -0500471 mSurfaceControlsWithPendingCallback.push(mSurfaceControl);
Robert Carr78c25dd2019-08-15 14:10:33 -0700472
Vishnu Nair084514a2021-07-30 16:07:42 -0700473 if (updateDestinationFrame) {
474 t->setDestinationFrame(mSurfaceControl, Rect(0, 0, mSize.getWidth(), mSize.getHeight()));
475 }
Vishnu Nair6bdec7d2021-05-10 15:01:13 -0700476 t->setBufferCrop(mSurfaceControl, crop);
Valerie Haua32c5522019-12-09 10:11:08 -0800477 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800478 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800479 if (!bufferItem.mIsAutoTimestamp) {
480 t->setDesiredPresentTime(bufferItem.mTimestamp);
481 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700482 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700483
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000484 if (!mNextFrameTimelineInfoQueue.empty()) {
Ady Abraham8db10102021-03-15 17:19:23 -0700485 t->setFrameTimelineInfo(mNextFrameTimelineInfoQueue.front());
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000486 mNextFrameTimelineInfoQueue.pop();
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100487 }
488
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800489 if (mAutoRefresh != bufferItem.mAutoRefresh) {
490 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
491 mAutoRefresh = bufferItem.mAutoRefresh;
492 }
Vishnu Nairadf632b2021-01-07 14:05:08 -0800493 {
494 std::unique_lock _lock{mTimestampMutex};
495 auto dequeueTime = mDequeueTimestamps.find(buffer->getId());
496 if (dequeueTime != mDequeueTimestamps.end()) {
497 Parcel p;
498 p.writeInt64(dequeueTime->second);
499 t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p);
500 mDequeueTimestamps.erase(dequeueTime);
501 }
502 }
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800503
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800504 auto mergeTransaction =
505 [&t, currentFrameNumber = bufferItem.mFrameNumber](
506 std::tuple<uint64_t, SurfaceComposerClient::Transaction> pendingTransaction) {
507 auto& [targetFrameNumber, transaction] = pendingTransaction;
508 if (currentFrameNumber < targetFrameNumber) {
509 return false;
510 }
511 t->merge(std::move(transaction));
512 return true;
513 };
514
515 mPendingTransactions.erase(std::remove_if(mPendingTransactions.begin(),
516 mPendingTransactions.end(), mergeTransaction),
517 mPendingTransactions.end());
518
Robert Carr78c25dd2019-08-15 14:10:33 -0700519 if (applyTransaction) {
Vishnu Nair277142c2021-01-05 18:35:29 -0800520 t->setApplyToken(mApplyToken).apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700521 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700522
523 BQA_LOGV("processNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
Vishnu Nair1506b182021-02-22 14:35:15 -0800524 " applyTransaction=%s mTimestamp=%" PRId64 "%s mPendingTransactions.size=%d"
Vishnu Nair9c161282021-07-07 16:52:34 -0700525 " graphicBufferId=%" PRIu64 "%s transform=%d",
Vishnu Nairea0de002020-11-17 17:42:37 -0800526 mSize.width, mSize.height, bufferItem.mFrameNumber, toString(applyTransaction),
Vishnu Nair1506b182021-02-22 14:35:15 -0800527 bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp ? "(auto)" : "",
Vishnu Nair4ba0c2e2021-06-24 11:27:17 -0700528 static_cast<uint32_t>(mPendingTransactions.size()), bufferItem.mGraphicBuffer->getId(),
Vishnu Nair9c161282021-07-07 16:52:34 -0700529 bufferItem.mAutoRefresh ? " mAutoRefresh" : "", bufferItem.mTransform);
Robert Carr78c25dd2019-08-15 14:10:33 -0700530}
531
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800532Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
533 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800534 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800535 }
536 return item.mCrop;
537}
538
Vishnu Nairaef1de92020-10-22 12:15:53 -0700539void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800540 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800541 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800542
Vishnu Nairdab94092020-09-29 16:09:04 -0700543 const bool nextTransactionSet = mNextTransaction != nullptr;
Vishnu Nair1506b182021-02-22 14:35:15 -0800544 if (nextTransactionSet) {
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800545 while (mNumFrameAvailable > 0 || maxBuffersAcquired(false /* includeExtraAcquire */)) {
Vishnu Nair7eb670a2020-10-15 12:16:10 -0700546 BQA_LOGV("waiting in onFrameAvailable...");
Valerie Hau0188adf2020-02-13 08:29:20 -0800547 mCallbackCV.wait(_lock);
548 }
549 }
Valerie Haud3b90d22019-11-06 09:37:31 -0800550 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800551 mNumFrameAvailable++;
Vishnu Nair2a52ca62021-06-24 13:08:53 -0700552 ATRACE_INT(mQueuedBufferTrace.c_str(),
553 mNumFrameAvailable + mNumAcquired - mPendingRelease.size());
Vishnu Nair1506b182021-02-22 14:35:15 -0800554
555 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s", item.mFrameNumber,
556 toString(nextTransactionSet));
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800557 processNextBufferLocked(nextTransactionSet /* useNextTransaction */);
Valerie Haud3b90d22019-11-06 09:37:31 -0800558}
559
Vishnu Nairaef1de92020-10-22 12:15:53 -0700560void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
561 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
562 // Do nothing since we are not storing unacquired buffer items locally.
563}
564
Vishnu Nairadf632b2021-01-07 14:05:08 -0800565void BLASTBufferQueue::onFrameDequeued(const uint64_t bufferId) {
566 std::unique_lock _lock{mTimestampMutex};
567 mDequeueTimestamps[bufferId] = systemTime();
568};
569
570void BLASTBufferQueue::onFrameCancelled(const uint64_t bufferId) {
571 std::unique_lock _lock{mTimestampMutex};
572 mDequeueTimestamps.erase(bufferId);
573};
574
Robert Carr78c25dd2019-08-15 14:10:33 -0700575void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800576 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700577 mNextTransaction = t;
578}
579
Vishnu Nairea0de002020-11-17 17:42:37 -0800580bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700581 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
Hongguang Chen33100282021-04-15 18:36:05 -0700582 mSize = mRequestedSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700583 // Only reject buffers if scaling mode is freeze.
584 return false;
585 }
586
Vishnu Naire1a42322020-10-02 17:42:04 -0700587 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
588 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
589
590 // Take the buffer's orientation into account
591 if (item.mTransform & ui::Transform::ROT_90) {
592 std::swap(bufWidth, bufHeight);
593 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800594 ui::Size bufferSize(bufWidth, bufHeight);
595 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
596 mSize = mRequestedSize;
597 return false;
598 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700599
Vishnu Nair670b3f72020-09-29 17:52:18 -0700600 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800601 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700602}
Vishnu Nairbf255772020-10-16 10:54:41 -0700603
chaviw71c2cc42020-10-23 16:42:02 -0700604void BLASTBufferQueue::setTransactionCompleteCallback(
605 uint64_t frameNumber, std::function<void(int64_t)>&& transactionCompleteCallback) {
606 std::lock_guard _lock{mMutex};
607 if (transactionCompleteCallback == nullptr) {
608 mTransactionCompleteCallback = nullptr;
609 } else {
610 mTransactionCompleteCallback = std::move(transactionCompleteCallback);
611 mTransactionCompleteFrameNumber = frameNumber;
612 }
613}
614
Vishnu Nairbf255772020-10-16 10:54:41 -0700615// Check if we have acquired the maximum number of buffers.
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800616// Consumer can acquire an additional buffer if that buffer is not droppable. Set
617// includeExtraAcquire is true to include this buffer to the count. Since this depends on the state
618// of the buffer, the next acquire may return with NO_BUFFER_AVAILABLE.
619bool BLASTBufferQueue::maxBuffersAcquired(bool includeExtraAcquire) const {
Ady Abraham0bde6b52021-05-18 13:57:02 -0700620 int maxAcquiredBuffers = mMaxAcquiredBuffers + (includeExtraAcquire ? 2 : 1);
Vishnu Nair1506b182021-02-22 14:35:15 -0800621 return mNumAcquired == maxAcquiredBuffers;
Vishnu Nairbf255772020-10-16 10:54:41 -0700622}
623
Robert Carr05086b22020-10-13 18:22:51 -0700624class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700625private:
Vishnu Nairc0fa0072021-08-30 15:31:08 -0700626 std::mutex mMutex;
Robert Carr9c006e02020-10-14 13:41:57 -0700627 sp<BLASTBufferQueue> mBbq;
Vishnu Nairc0fa0072021-08-30 15:31:08 -0700628 bool mDestroyed = false;
629
Robert Carr05086b22020-10-13 18:22:51 -0700630public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700631 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
632 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
633 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700634
Robert Carr05086b22020-10-13 18:22:51 -0700635 void allocateBuffers() override {
636 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
637 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
638 auto gbp = getIGraphicBufferProducer();
639 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
640 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
641 gbp->allocateBuffers(reqWidth, reqHeight,
642 reqFormat, reqUsage);
643
644 }).detach();
645 }
Robert Carr9c006e02020-10-14 13:41:57 -0700646
Marin Shalamanovc5986772021-03-16 16:09:49 +0100647 status_t setFrameRate(float frameRate, int8_t compatibility,
648 int8_t changeFrameRateStrategy) override {
Vishnu Nairc0fa0072021-08-30 15:31:08 -0700649 std::unique_lock _lock{mMutex};
650 if (mDestroyed) {
651 return DEAD_OBJECT;
652 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100653 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
654 "BBQSurface::setFrameRate")) {
Robert Carr9c006e02020-10-14 13:41:57 -0700655 return BAD_VALUE;
656 }
Marin Shalamanovc5986772021-03-16 16:09:49 +0100657 return mBbq->setFrameRate(frameRate, compatibility, changeFrameRateStrategy);
Robert Carr9c006e02020-10-14 13:41:57 -0700658 }
Robert Carr9b611b72020-10-19 12:00:23 -0700659
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000660 status_t setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) override {
Vishnu Nairc0fa0072021-08-30 15:31:08 -0700661 std::unique_lock _lock{mMutex};
662 if (mDestroyed) {
663 return DEAD_OBJECT;
664 }
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000665 return mBbq->setFrameTimelineInfo(frameTimelineInfo);
Robert Carr9b611b72020-10-19 12:00:23 -0700666 }
Vishnu Nairc0fa0072021-08-30 15:31:08 -0700667
668 void destroy() override {
669 Surface::destroy();
670
671 std::unique_lock _lock{mMutex};
672 mDestroyed = true;
673 mBbq = nullptr;
674 }
Robert Carr05086b22020-10-13 18:22:51 -0700675};
676
Robert Carr9c006e02020-10-14 13:41:57 -0700677// TODO: Can we coalesce this with frame updates? Need to confirm
678// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200679status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
680 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700681 std::unique_lock _lock{mMutex};
682 SurfaceComposerClient::Transaction t;
683
Marin Shalamanov46084422020-10-13 12:33:42 +0200684 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700685}
686
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000687status_t BLASTBufferQueue::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) {
Robert Carr9b611b72020-10-19 12:00:23 -0700688 std::unique_lock _lock{mMutex};
Siarhei Vishniakoufc434ac2021-01-13 10:28:00 -1000689 mNextFrameTimelineInfoQueue.push(frameTimelineInfo);
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100690 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700691}
692
Hongguang Chen621ec582021-02-16 15:42:35 -0800693void BLASTBufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
694 std::unique_lock _lock{mMutex};
695 SurfaceComposerClient::Transaction t;
696
697 t.setSidebandStream(mSurfaceControl, stream).apply();
698}
699
Vishnu Nair992496b2020-10-22 17:27:21 -0700700sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
701 std::unique_lock _lock{mMutex};
702 sp<IBinder> scHandle = nullptr;
703 if (includeSurfaceControlHandle && mSurfaceControl) {
704 scHandle = mSurfaceControl->getHandle();
705 }
706 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700707}
708
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800709void BLASTBufferQueue::mergeWithNextTransaction(SurfaceComposerClient::Transaction* t,
710 uint64_t frameNumber) {
711 std::lock_guard _lock{mMutex};
712 if (mLastAcquiredFrameNumber >= frameNumber) {
713 // Apply the transaction since we have already acquired the desired frame.
714 t->apply();
715 } else {
chaviwaad6cf52021-03-23 17:27:20 -0500716 mPendingTransactions.emplace_back(frameNumber, *t);
717 // Clear the transaction so it can't be applied elsewhere.
718 t->clear();
Vishnu Nairc4a40c12020-12-23 09:14:32 -0800719 }
720}
721
Vishnu Nair89496122020-12-14 17:14:53 -0800722// Maintains a single worker thread per process that services a list of runnables.
723class AsyncWorker : public Singleton<AsyncWorker> {
724private:
725 std::thread mThread;
726 bool mDone = false;
727 std::deque<std::function<void()>> mRunnables;
728 std::mutex mMutex;
729 std::condition_variable mCv;
730 void run() {
731 std::unique_lock<std::mutex> lock(mMutex);
732 while (!mDone) {
Vishnu Nair89496122020-12-14 17:14:53 -0800733 while (!mRunnables.empty()) {
734 std::function<void()> runnable = mRunnables.front();
735 mRunnables.pop_front();
736 runnable();
737 }
Wonsik Kim567533e2021-05-04 19:31:29 -0700738 mCv.wait(lock);
Vishnu Nair89496122020-12-14 17:14:53 -0800739 }
740 }
741
742public:
743 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
744
745 ~AsyncWorker() {
746 mDone = true;
747 mCv.notify_all();
748 if (mThread.joinable()) {
749 mThread.join();
750 }
751 }
752
753 void post(std::function<void()> runnable) {
754 std::unique_lock<std::mutex> lock(mMutex);
755 mRunnables.emplace_back(std::move(runnable));
756 mCv.notify_one();
757 }
758};
759ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
760
761// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
762class AsyncProducerListener : public BnProducerListener {
763private:
764 const sp<IProducerListener> mListener;
765
766public:
767 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
768
769 void onBufferReleased() override {
770 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
771 }
772
773 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
774 AsyncWorker::getInstance().post(
775 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
776 }
777};
778
779// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
780// can be non-blocking when the producer is in the client process.
781class BBQBufferQueueProducer : public BufferQueueProducer {
782public:
783 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
784 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
785
786 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
787 QueueBufferOutput* output) override {
788 if (!listener) {
789 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
790 }
791
792 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
793 producerControlledByApp, output);
794 }
Vishnu Nair17dde612020-12-28 11:39:59 -0800795
796 int query(int what, int* value) override {
797 if (what == NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER) {
798 *value = 1;
799 return NO_ERROR;
800 }
801 return BufferQueueProducer::query(what, value);
802 }
Vishnu Nair89496122020-12-14 17:14:53 -0800803};
804
805// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
806// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
807// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
808// we can deadlock.
809void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
810 sp<IGraphicBufferConsumer>* outConsumer) {
811 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
812 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
813
814 sp<BufferQueueCore> core(new BufferQueueCore());
815 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
816
817 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
818 LOG_ALWAYS_FATAL_IF(producer == nullptr,
819 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
820
Vishnu Nair8b30dd12021-01-25 14:16:54 -0800821 sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
822 consumer->setAllowExtraAcquire(true);
Vishnu Nair89496122020-12-14 17:14:53 -0800823 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
824 "BLASTBufferQueue: failed to create BufferQueueConsumer");
825
826 *outProducer = producer;
827 *outConsumer = consumer;
828}
829
chaviw497e81c2021-02-04 17:09:47 -0800830PixelFormat BLASTBufferQueue::convertBufferFormat(PixelFormat& format) {
831 PixelFormat convertedFormat = format;
832 switch (format) {
833 case PIXEL_FORMAT_TRANSPARENT:
834 case PIXEL_FORMAT_TRANSLUCENT:
835 convertedFormat = PIXEL_FORMAT_RGBA_8888;
836 break;
837 case PIXEL_FORMAT_OPAQUE:
838 convertedFormat = PIXEL_FORMAT_RGBX_8888;
839 break;
840 }
841 return convertedFormat;
842}
843
Robert Carr82d07c92021-05-10 11:36:43 -0700844uint32_t BLASTBufferQueue::getLastTransformHint() const {
845 if (mSurfaceControl != nullptr) {
846 return mSurfaceControl->getTransformHint();
847 } else {
848 return 0;
849 }
850}
851
Robert Carr78c25dd2019-08-15 14:10:33 -0700852} // namespace android