blob: 9fc54959386706ed9c6a431f21e1cc95115198f1 [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>
Robert Carr78c25dd2019-08-15 14:10:33 -070032
Valerie Haua32c5522019-12-09 10:11:08 -080033#include <utils/Trace.h>
34
Robert Carr78c25dd2019-08-15 14:10:33 -070035#include <chrono>
36
37using namespace std::chrono_literals;
38
Vishnu Nairdab94092020-09-29 16:09:04 -070039namespace {
40inline const char* toString(bool b) {
41 return b ? "true" : "false";
42}
43} // namespace
44
Robert Carr78c25dd2019-08-15 14:10:33 -070045namespace android {
46
Vishnu Nairdab94092020-09-29 16:09:04 -070047// Macros to include adapter info in log messages
48#define BQA_LOGV(x, ...) \
49 ALOGV("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairc6f89ee2020-12-11 14:27:32 -080050// enable logs for a single layer
51//#define BQA_LOGV(x, ...) \
52// ALOGV_IF((strstr(mName.c_str(), "SurfaceView") != nullptr), "[%s](f:%u,a:%u) " x, \
53// mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
Vishnu Nairdab94092020-09-29 16:09:04 -070054#define BQA_LOGE(x, ...) \
55 ALOGE("[%s](f:%u,a:%u) " x, mName.c_str(), mNumFrameAvailable, mNumAcquired, ##__VA_ARGS__)
56
Valerie Hau871d6352020-01-29 08:44:02 -080057void BLASTBufferItemConsumer::onDisconnect() {
58 Mutex::Autolock lock(mFrameEventHistoryMutex);
59 mPreviouslyConnected = mCurrentlyConnected;
60 mCurrentlyConnected = false;
61 if (mPreviouslyConnected) {
62 mDisconnectEvents.push(mCurrentFrameNumber);
63 }
64 mFrameEventHistory.onDisconnect();
65}
66
67void BLASTBufferItemConsumer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
68 FrameEventHistoryDelta* outDelta) {
69 Mutex::Autolock lock(mFrameEventHistoryMutex);
70 if (newTimestamps) {
71 // BufferQueueProducer only adds a new timestamp on
72 // queueBuffer
73 mCurrentFrameNumber = newTimestamps->frameNumber;
74 mFrameEventHistory.addQueue(*newTimestamps);
75 }
76 if (outDelta) {
77 // frame event histories will be processed
78 // only after the producer connects and requests
79 // deltas for the first time. Forward this intent
80 // to SF-side to turn event processing back on
81 mPreviouslyConnected = mCurrentlyConnected;
82 mCurrentlyConnected = true;
83 mFrameEventHistory.getAndResetDelta(outDelta);
84 }
85}
86
87void BLASTBufferItemConsumer::updateFrameTimestamps(uint64_t frameNumber, nsecs_t refreshStartTime,
88 const sp<Fence>& glDoneFence,
89 const sp<Fence>& presentFence,
90 const sp<Fence>& prevReleaseFence,
91 CompositorTiming compositorTiming,
92 nsecs_t latchTime, nsecs_t dequeueReadyTime) {
93 Mutex::Autolock lock(mFrameEventHistoryMutex);
94
95 // if the producer is not connected, don't bother updating,
96 // the next producer that connects won't access this frame event
97 if (!mCurrentlyConnected) return;
98 std::shared_ptr<FenceTime> glDoneFenceTime = std::make_shared<FenceTime>(glDoneFence);
99 std::shared_ptr<FenceTime> presentFenceTime = std::make_shared<FenceTime>(presentFence);
100 std::shared_ptr<FenceTime> releaseFenceTime = std::make_shared<FenceTime>(prevReleaseFence);
101
102 mFrameEventHistory.addLatch(frameNumber, latchTime);
103 mFrameEventHistory.addRelease(frameNumber, dequeueReadyTime, std::move(releaseFenceTime));
104 mFrameEventHistory.addPreComposition(frameNumber, refreshStartTime);
105 mFrameEventHistory.addPostComposition(frameNumber, glDoneFenceTime, presentFenceTime,
106 compositorTiming);
107}
108
109void BLASTBufferItemConsumer::getConnectionEvents(uint64_t frameNumber, bool* needsDisconnect) {
110 bool disconnect = false;
111 Mutex::Autolock lock(mFrameEventHistoryMutex);
112 while (!mDisconnectEvents.empty() && mDisconnectEvents.front() <= frameNumber) {
113 disconnect = true;
114 mDisconnectEvents.pop();
115 }
116 if (needsDisconnect != nullptr) *needsDisconnect = disconnect;
117}
118
Vishnu Nairdab94092020-09-29 16:09:04 -0700119BLASTBufferQueue::BLASTBufferQueue(const std::string& name, const sp<SurfaceControl>& surface,
120 int width, int height, bool enableTripleBuffering)
121 : mName(name),
122 mSurfaceControl(surface),
Vishnu Nairea0de002020-11-17 17:42:37 -0800123 mSize(width, height),
124 mRequestedSize(mSize),
Valerie Haud3b90d22019-11-06 09:37:31 -0800125 mNextTransaction(nullptr) {
Vishnu Nair89496122020-12-14 17:14:53 -0800126 createBufferQueue(&mProducer, &mConsumer);
Valerie Hau0889c622020-02-19 15:04:47 -0800127 // since the adapter is in the client process, set dequeue timeout
128 // explicitly so that dequeueBuffer will block
129 mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());
Valerie Hau65b8e872020-02-13 09:45:14 -0800130
Robert Carrcedef052020-04-22 15:58:23 -0700131 if (enableTripleBuffering) {
Valerie Hau65b8e872020-02-13 09:45:14 -0800132 mProducer->setMaxDequeuedBufferCount(2);
133 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700134 mBufferItemConsumer =
Robert Carr8304f7f2020-12-02 15:47:16 -0800135 new BLASTBufferItemConsumer(mConsumer, GraphicBuffer::USAGE_HW_COMPOSER, 1, false);
Valerie Haua32c5522019-12-09 10:11:08 -0800136 static int32_t id = 0;
Vishnu Nairdab94092020-09-29 16:09:04 -0700137 auto consumerName = mName + "(BLAST Consumer)" + std::to_string(id);
Valerie Haua32c5522019-12-09 10:11:08 -0800138 id++;
Vishnu Nairdab94092020-09-29 16:09:04 -0700139 mBufferItemConsumer->setName(String8(consumerName.c_str()));
Robert Carr78c25dd2019-08-15 14:10:33 -0700140 mBufferItemConsumer->setFrameAvailableListener(this);
141 mBufferItemConsumer->setBufferFreedListener(this);
Vishnu Nairea0de002020-11-17 17:42:37 -0800142 mBufferItemConsumer->setDefaultBufferSize(mSize.width, mSize.height);
Robert Carr78c25dd2019-08-15 14:10:33 -0700143 mBufferItemConsumer->setDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888);
Robert Carr9f133d72020-04-01 15:51:46 -0700144
Valerie Hau2882e982020-01-23 13:33:10 -0800145 mTransformHint = mSurfaceControl->getTransformHint();
Robert Carr9f133d72020-04-01 15:51:46 -0700146 mBufferItemConsumer->setTransformHint(mTransformHint);
Valerie Haud3b90d22019-11-06 09:37:31 -0800147
Valerie Haua32c5522019-12-09 10:11:08 -0800148 mNumAcquired = 0;
149 mNumFrameAvailable = 0;
150 mPendingReleaseItem.item = BufferItem();
151 mPendingReleaseItem.releaseFence = nullptr;
Robert Carr78c25dd2019-08-15 14:10:33 -0700152}
153
Vishnu Nairdab94092020-09-29 16:09:04 -0700154void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700155 std::unique_lock _lock{mMutex};
156 mSurfaceControl = surface;
Robert Carrfc416512020-04-02 12:32:44 -0700157
Vishnu Nairea0de002020-11-17 17:42:37 -0800158 ui::Size newSize(width, height);
159 if (mRequestedSize != newSize) {
160 mRequestedSize.set(newSize);
161 mBufferItemConsumer->setDefaultBufferSize(mRequestedSize.width, mRequestedSize.height);
Vishnu Nair53c936c2020-12-03 11:46:37 -0800162 if (mLastBufferScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
163 // If the buffer supports scaling, update the frame immediately since the client may
164 // want to scale the existing buffer to the new size.
165 mSize = mRequestedSize;
166 SurfaceComposerClient::Transaction t;
167 t.setFrame(mSurfaceControl,
168 {0, 0, static_cast<int32_t>(mSize.width),
169 static_cast<int32_t>(mSize.height)});
170 t.apply();
171 }
Robert Carrfc416512020-04-02 12:32:44 -0700172 }
Robert Carr78c25dd2019-08-15 14:10:33 -0700173}
174
175static void transactionCallbackThunk(void* context, nsecs_t latchTime,
176 const sp<Fence>& presentFence,
177 const std::vector<SurfaceControlStats>& stats) {
178 if (context == nullptr) {
179 return;
180 }
Robert Carrfbcbb4c2020-11-02 14:14:34 -0800181 sp<BLASTBufferQueue> bq = static_cast<BLASTBufferQueue*>(context);
Robert Carr78c25dd2019-08-15 14:10:33 -0700182 bq->transactionCallback(latchTime, presentFence, stats);
183}
184
185void BLASTBufferQueue::transactionCallback(nsecs_t /*latchTime*/, const sp<Fence>& /*presentFence*/,
186 const std::vector<SurfaceControlStats>& stats) {
187 std::unique_lock _lock{mMutex};
Valerie Haua32c5522019-12-09 10:11:08 -0800188 ATRACE_CALL();
Vishnu Nairdab94092020-09-29 16:09:04 -0700189 BQA_LOGV("transactionCallback");
Vishnu Nair670b3f72020-09-29 17:52:18 -0700190 mInitialCallbackReceived = true;
Vishnu Nairdab94092020-09-29 16:09:04 -0700191
Valerie Hau871d6352020-01-29 08:44:02 -0800192 if (!stats.empty()) {
193 mTransformHint = stats[0].transformHint;
194 mBufferItemConsumer->setTransformHint(mTransformHint);
195 mBufferItemConsumer->updateFrameTimestamps(stats[0].frameEventStats.frameNumber,
196 stats[0].frameEventStats.refreshStartTime,
197 stats[0].frameEventStats.gpuCompositionDoneFence,
198 stats[0].presentFence,
199 stats[0].previousReleaseFence,
200 stats[0].frameEventStats.compositorTiming,
201 stats[0].latchTime,
202 stats[0].frameEventStats.dequeueReadyTime);
203 }
Valerie Haua32c5522019-12-09 10:11:08 -0800204 if (mPendingReleaseItem.item.mGraphicBuffer != nullptr) {
Valerie Hau871d6352020-01-29 08:44:02 -0800205 if (!stats.empty()) {
Valerie Haua32c5522019-12-09 10:11:08 -0800206 mPendingReleaseItem.releaseFence = stats[0].previousReleaseFence;
Valerie Haua32c5522019-12-09 10:11:08 -0800207 } else {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700208 BQA_LOGE("Warning: no SurfaceControlStats returned in BLASTBufferQueue callback");
Valerie Haua32c5522019-12-09 10:11:08 -0800209 mPendingReleaseItem.releaseFence = nullptr;
210 }
211 mBufferItemConsumer->releaseBuffer(mPendingReleaseItem.item,
212 mPendingReleaseItem.releaseFence
213 ? mPendingReleaseItem.releaseFence
Robert Carr78c25dd2019-08-15 14:10:33 -0700214 : Fence::NO_FENCE);
Valerie Haua32c5522019-12-09 10:11:08 -0800215 mNumAcquired--;
216 mPendingReleaseItem.item = BufferItem();
217 mPendingReleaseItem.releaseFence = nullptr;
Robert Carr78c25dd2019-08-15 14:10:33 -0700218 }
Valerie Haua32c5522019-12-09 10:11:08 -0800219
220 if (mSubmitted.empty()) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700221 BQA_LOGE("ERROR: callback with no corresponding submitted buffer item");
Valerie Haua32c5522019-12-09 10:11:08 -0800222 }
223 mPendingReleaseItem.item = std::move(mSubmitted.front());
224 mSubmitted.pop();
Robert Carre4943eb2020-02-15 18:34:59 -0800225
Robert Carr255acdc2020-04-17 14:08:55 -0700226 processNextBufferLocked(false);
Robert Carre4943eb2020-02-15 18:34:59 -0800227
Valerie Haud3b90d22019-11-06 09:37:31 -0800228 mCallbackCV.notify_all();
Robert Carr78c25dd2019-08-15 14:10:33 -0700229 decStrong((void*)transactionCallbackThunk);
230}
231
Robert Carr255acdc2020-04-17 14:08:55 -0700232void BLASTBufferQueue::processNextBufferLocked(bool useNextTransaction) {
Valerie Haua32c5522019-12-09 10:11:08 -0800233 ATRACE_CALL();
Vishnu Nairdab94092020-09-29 16:09:04 -0700234 BQA_LOGV("processNextBufferLocked useNextTransaction=%s", toString(useNextTransaction));
235
Vishnu Nairbf255772020-10-16 10:54:41 -0700236 // Wait to acquire a buffer if there are no frames available or we have acquired the max
Vishnu Nair670b3f72020-09-29 17:52:18 -0700237 // number of buffers.
Vishnu Nairbf255772020-10-16 10:54:41 -0700238 if (mNumFrameAvailable == 0 || maxBuffersAcquired()) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700239 BQA_LOGV("processNextBufferLocked waiting for frame available or callback");
Vishnu Nairea0de002020-11-17 17:42:37 -0800240 mCallbackCV.notify_all();
Valerie Haud3b90d22019-11-06 09:37:31 -0800241 return;
242 }
243
Valerie Haua32c5522019-12-09 10:11:08 -0800244 if (mSurfaceControl == nullptr) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700245 BQA_LOGE("ERROR : surface control is null");
Valerie Haud3b90d22019-11-06 09:37:31 -0800246 return;
247 }
248
Robert Carr78c25dd2019-08-15 14:10:33 -0700249 SurfaceComposerClient::Transaction localTransaction;
250 bool applyTransaction = true;
251 SurfaceComposerClient::Transaction* t = &localTransaction;
Robert Carr255acdc2020-04-17 14:08:55 -0700252 if (mNextTransaction != nullptr && useNextTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700253 t = mNextTransaction;
254 mNextTransaction = nullptr;
255 applyTransaction = false;
256 }
257
Valerie Haua32c5522019-12-09 10:11:08 -0800258 BufferItem bufferItem;
Valerie Haud3b90d22019-11-06 09:37:31 -0800259
Vishnu Nairc6f89ee2020-12-11 14:27:32 -0800260 status_t status =
261 mBufferItemConsumer->acquireBuffer(&bufferItem, 0 /* expectedPresent */, false);
Robert Carr78c25dd2019-08-15 14:10:33 -0700262 if (status != OK) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700263 BQA_LOGE("Failed to acquire a buffer, err=%s", statusToString(status).c_str());
Robert Carr78c25dd2019-08-15 14:10:33 -0700264 return;
265 }
Valerie Haua32c5522019-12-09 10:11:08 -0800266 auto buffer = bufferItem.mGraphicBuffer;
267 mNumFrameAvailable--;
268
269 if (buffer == nullptr) {
270 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
Vishnu Nairbf255772020-10-16 10:54:41 -0700271 BQA_LOGE("Buffer was empty");
Valerie Haua32c5522019-12-09 10:11:08 -0800272 return;
273 }
274
Vishnu Nair670b3f72020-09-29 17:52:18 -0700275 if (rejectBuffer(bufferItem)) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800276 BQA_LOGE("rejecting buffer:active_size=%dx%d, requested_size=%dx%d"
277 "buffer{size=%dx%d transform=%d}",
278 mSize.width, mSize.height, mRequestedSize.width, mRequestedSize.height,
279 buffer->getWidth(), buffer->getHeight(), bufferItem.mTransform);
280 mBufferItemConsumer->releaseBuffer(bufferItem, Fence::NO_FENCE);
281 processNextBufferLocked(useNextTransaction);
282 return;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700283 }
284
Valerie Haua32c5522019-12-09 10:11:08 -0800285 mNumAcquired++;
286 mSubmitted.push(bufferItem);
Robert Carr78c25dd2019-08-15 14:10:33 -0700287
Valerie Hau871d6352020-01-29 08:44:02 -0800288 bool needsDisconnect = false;
289 mBufferItemConsumer->getConnectionEvents(bufferItem.mFrameNumber, &needsDisconnect);
290
291 // if producer disconnected before, notify SurfaceFlinger
292 if (needsDisconnect) {
293 t->notifyProducerDisconnect(mSurfaceControl);
294 }
295
Robert Carr78c25dd2019-08-15 14:10:33 -0700296 // Ensure BLASTBufferQueue stays alive until we receive the transaction complete callback.
297 incStrong((void*)transactionCallbackThunk);
298
Vishnu Nair53c936c2020-12-03 11:46:37 -0800299 mLastBufferScalingMode = bufferItem.mScalingMode;
300
Robert Carr78c25dd2019-08-15 14:10:33 -0700301 t->setBuffer(mSurfaceControl, buffer);
John Reck137069e2020-12-10 22:07:37 -0500302 t->setDataspace(mSurfaceControl, static_cast<ui::Dataspace>(bufferItem.mDataSpace));
303 t->setHdrMetadata(mSurfaceControl, bufferItem.mHdrMetadata);
304 t->setSurfaceDamageRegion(mSurfaceControl, bufferItem.mSurfaceDamage);
Robert Carr78c25dd2019-08-15 14:10:33 -0700305 t->setAcquireFence(mSurfaceControl,
Valerie Haua32c5522019-12-09 10:11:08 -0800306 bufferItem.mFence ? new Fence(bufferItem.mFence->dup()) : Fence::NO_FENCE);
Robert Carr78c25dd2019-08-15 14:10:33 -0700307 t->addTransactionCompletedCallback(transactionCallbackThunk, static_cast<void*>(this));
308
Vishnu Nairdab94092020-09-29 16:09:04 -0700309 t->setFrame(mSurfaceControl,
Vishnu Nairea0de002020-11-17 17:42:37 -0800310 {0, 0, static_cast<int32_t>(mSize.width), static_cast<int32_t>(mSize.height)});
Valerie Haua32c5522019-12-09 10:11:08 -0800311 t->setCrop(mSurfaceControl, computeCrop(bufferItem));
312 t->setTransform(mSurfaceControl, bufferItem.mTransform);
Valerie Hau2882e982020-01-23 13:33:10 -0800313 t->setTransformToDisplayInverse(mSurfaceControl, bufferItem.mTransformToDisplayInverse);
Ady Abrahamf0c56492020-12-17 18:04:15 -0800314 if (!bufferItem.mIsAutoTimestamp) {
315 t->setDesiredPresentTime(bufferItem.mTimestamp);
316 }
Vishnu Nair6b7c5c92020-09-29 17:27:05 -0700317 t->setFrameNumber(mSurfaceControl, bufferItem.mFrameNumber);
Robert Carr78c25dd2019-08-15 14:10:33 -0700318
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100319 if (!mNextFrameTimelineVsyncIdQueue.empty()) {
320 t->setFrameTimelineVsync(mSurfaceControl, mNextFrameTimelineVsyncIdQueue.front());
321 mNextFrameTimelineVsyncIdQueue.pop();
322 }
323
Vishnu Naircf26a0a2020-11-13 12:56:20 -0800324 if (mAutoRefresh != bufferItem.mAutoRefresh) {
325 t->setAutoRefresh(mSurfaceControl, bufferItem.mAutoRefresh);
326 mAutoRefresh = bufferItem.mAutoRefresh;
327 }
328
Robert Carr78c25dd2019-08-15 14:10:33 -0700329 if (applyTransaction) {
Robert Carr78c25dd2019-08-15 14:10:33 -0700330 t->apply();
Robert Carr78c25dd2019-08-15 14:10:33 -0700331 }
Vishnu Nairdab94092020-09-29 16:09:04 -0700332
333 BQA_LOGV("processNextBufferLocked size=%dx%d mFrameNumber=%" PRIu64
334 " applyTransaction=%s mTimestamp=%" PRId64,
Vishnu Nairea0de002020-11-17 17:42:37 -0800335 mSize.width, mSize.height, bufferItem.mFrameNumber, toString(applyTransaction),
Vishnu Nairdab94092020-09-29 16:09:04 -0700336 bufferItem.mTimestamp);
Robert Carr78c25dd2019-08-15 14:10:33 -0700337}
338
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800339Rect BLASTBufferQueue::computeCrop(const BufferItem& item) {
340 if (item.mScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
Vishnu Nairea0de002020-11-17 17:42:37 -0800341 return GLConsumer::scaleDownCrop(item.mCrop, mSize.width, mSize.height);
Valerie Hau45e4b3b2019-12-03 10:49:17 -0800342 }
343 return item.mCrop;
344}
345
Vishnu Nairaef1de92020-10-22 12:15:53 -0700346void BLASTBufferQueue::onFrameAvailable(const BufferItem& item) {
Valerie Haua32c5522019-12-09 10:11:08 -0800347 ATRACE_CALL();
Valerie Hau0188adf2020-02-13 08:29:20 -0800348 std::unique_lock _lock{mMutex};
Valerie Haud3b90d22019-11-06 09:37:31 -0800349
Vishnu Nairdab94092020-09-29 16:09:04 -0700350 const bool nextTransactionSet = mNextTransaction != nullptr;
Vishnu Nairaef1de92020-10-22 12:15:53 -0700351 BQA_LOGV("onFrameAvailable framenumber=%" PRIu64 " nextTransactionSet=%s mFlushShadowQueue=%s",
352 item.mFrameNumber, toString(nextTransactionSet), toString(mFlushShadowQueue));
Vishnu Nairdab94092020-09-29 16:09:04 -0700353
Vishnu Nair7eb670a2020-10-15 12:16:10 -0700354 if (nextTransactionSet || mFlushShadowQueue) {
Vishnu Nairbf255772020-10-16 10:54:41 -0700355 while (mNumFrameAvailable > 0 || maxBuffersAcquired()) {
Vishnu Nair7eb670a2020-10-15 12:16:10 -0700356 BQA_LOGV("waiting in onFrameAvailable...");
Valerie Hau0188adf2020-02-13 08:29:20 -0800357 mCallbackCV.wait(_lock);
358 }
359 }
Vishnu Nair7eb670a2020-10-15 12:16:10 -0700360 mFlushShadowQueue = false;
Valerie Haud3b90d22019-11-06 09:37:31 -0800361 // add to shadow queue
Valerie Haua32c5522019-12-09 10:11:08 -0800362 mNumFrameAvailable++;
Robert Carr255acdc2020-04-17 14:08:55 -0700363 processNextBufferLocked(true);
Valerie Haud3b90d22019-11-06 09:37:31 -0800364}
365
Vishnu Nairaef1de92020-10-22 12:15:53 -0700366void BLASTBufferQueue::onFrameReplaced(const BufferItem& item) {
367 BQA_LOGV("onFrameReplaced framenumber=%" PRIu64, item.mFrameNumber);
368 // Do nothing since we are not storing unacquired buffer items locally.
369}
370
Robert Carr78c25dd2019-08-15 14:10:33 -0700371void BLASTBufferQueue::setNextTransaction(SurfaceComposerClient::Transaction* t) {
Valerie Haud3b90d22019-11-06 09:37:31 -0800372 std::lock_guard _lock{mMutex};
Robert Carr78c25dd2019-08-15 14:10:33 -0700373 mNextTransaction = t;
374}
375
Vishnu Nairea0de002020-11-17 17:42:37 -0800376bool BLASTBufferQueue::rejectBuffer(const BufferItem& item) {
Vishnu Nair670b3f72020-09-29 17:52:18 -0700377 if (item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE) {
378 // Only reject buffers if scaling mode is freeze.
379 return false;
380 }
381
Vishnu Naire1a42322020-10-02 17:42:04 -0700382 uint32_t bufWidth = item.mGraphicBuffer->getWidth();
383 uint32_t bufHeight = item.mGraphicBuffer->getHeight();
384
385 // Take the buffer's orientation into account
386 if (item.mTransform & ui::Transform::ROT_90) {
387 std::swap(bufWidth, bufHeight);
388 }
Vishnu Nairea0de002020-11-17 17:42:37 -0800389 ui::Size bufferSize(bufWidth, bufHeight);
390 if (mRequestedSize != mSize && mRequestedSize == bufferSize) {
391 mSize = mRequestedSize;
392 return false;
393 }
Vishnu Naire1a42322020-10-02 17:42:04 -0700394
Vishnu Nair670b3f72020-09-29 17:52:18 -0700395 // reject buffers if the buffer size doesn't match.
Vishnu Nairea0de002020-11-17 17:42:37 -0800396 return mSize != bufferSize;
Vishnu Nair670b3f72020-09-29 17:52:18 -0700397}
Vishnu Nairbf255772020-10-16 10:54:41 -0700398
399// Check if we have acquired the maximum number of buffers.
400// As a special case, we wait for the first callback before acquiring the second buffer so we
401// can ensure the first buffer is presented if multiple buffers are queued in succession.
402bool BLASTBufferQueue::maxBuffersAcquired() const {
403 return mNumAcquired == MAX_ACQUIRED_BUFFERS + 1 ||
404 (!mInitialCallbackReceived && mNumAcquired == 1);
405}
406
Robert Carr05086b22020-10-13 18:22:51 -0700407class BBQSurface : public Surface {
Robert Carr9c006e02020-10-14 13:41:57 -0700408private:
409 sp<BLASTBufferQueue> mBbq;
Robert Carr05086b22020-10-13 18:22:51 -0700410public:
Vishnu Nair992496b2020-10-22 17:27:21 -0700411 BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
412 const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
413 : Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}
Robert Carr9c006e02020-10-14 13:41:57 -0700414
Robert Carr05086b22020-10-13 18:22:51 -0700415 void allocateBuffers() override {
416 uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
417 uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
418 auto gbp = getIGraphicBufferProducer();
419 std::thread ([reqWidth, reqHeight, gbp=getIGraphicBufferProducer(),
420 reqFormat=mReqFormat, reqUsage=mReqUsage] () {
421 gbp->allocateBuffers(reqWidth, reqHeight,
422 reqFormat, reqUsage);
423
424 }).detach();
425 }
Robert Carr9c006e02020-10-14 13:41:57 -0700426
Marin Shalamanov46084422020-10-13 12:33:42 +0200427 status_t setFrameRate(float frameRate, int8_t compatibility, bool shouldBeSeamless) override {
Robert Carr9c006e02020-10-14 13:41:57 -0700428 if (!ValidateFrameRate(frameRate, compatibility, "BBQSurface::setFrameRate")) {
429 return BAD_VALUE;
430 }
Marin Shalamanov46084422020-10-13 12:33:42 +0200431 return mBbq->setFrameRate(frameRate, compatibility, shouldBeSeamless);
Robert Carr9c006e02020-10-14 13:41:57 -0700432 }
Robert Carr9b611b72020-10-19 12:00:23 -0700433
434 status_t setFrameTimelineVsync(int64_t frameTimelineVsyncId) override {
435 return mBbq->setFrameTimelineVsync(frameTimelineVsyncId);
436 }
Robert Carr05086b22020-10-13 18:22:51 -0700437};
438
Robert Carr9c006e02020-10-14 13:41:57 -0700439// TODO: Can we coalesce this with frame updates? Need to confirm
440// no timing issues.
Marin Shalamanov46084422020-10-13 12:33:42 +0200441status_t BLASTBufferQueue::setFrameRate(float frameRate, int8_t compatibility,
442 bool shouldBeSeamless) {
Robert Carr9c006e02020-10-14 13:41:57 -0700443 std::unique_lock _lock{mMutex};
444 SurfaceComposerClient::Transaction t;
445
Marin Shalamanov46084422020-10-13 12:33:42 +0200446 return t.setFrameRate(mSurfaceControl, frameRate, compatibility, shouldBeSeamless).apply();
Robert Carr9c006e02020-10-14 13:41:57 -0700447}
448
Robert Carr9b611b72020-10-19 12:00:23 -0700449status_t BLASTBufferQueue::setFrameTimelineVsync(int64_t frameTimelineVsyncId) {
450 std::unique_lock _lock{mMutex};
Jorim Jaggia3fe67b2020-12-01 00:24:33 +0100451 mNextFrameTimelineVsyncIdQueue.push(frameTimelineVsyncId);
452 return OK;
Robert Carr9b611b72020-10-19 12:00:23 -0700453}
454
Vishnu Nair992496b2020-10-22 17:27:21 -0700455sp<Surface> BLASTBufferQueue::getSurface(bool includeSurfaceControlHandle) {
456 std::unique_lock _lock{mMutex};
457 sp<IBinder> scHandle = nullptr;
458 if (includeSurfaceControlHandle && mSurfaceControl) {
459 scHandle = mSurfaceControl->getHandle();
460 }
461 return new BBQSurface(mProducer, true, scHandle, this);
Robert Carr05086b22020-10-13 18:22:51 -0700462}
463
Vishnu Nair89496122020-12-14 17:14:53 -0800464// Maintains a single worker thread per process that services a list of runnables.
465class AsyncWorker : public Singleton<AsyncWorker> {
466private:
467 std::thread mThread;
468 bool mDone = false;
469 std::deque<std::function<void()>> mRunnables;
470 std::mutex mMutex;
471 std::condition_variable mCv;
472 void run() {
473 std::unique_lock<std::mutex> lock(mMutex);
474 while (!mDone) {
475 mCv.wait(lock);
476 while (!mRunnables.empty()) {
477 std::function<void()> runnable = mRunnables.front();
478 mRunnables.pop_front();
479 runnable();
480 }
481 }
482 }
483
484public:
485 AsyncWorker() : Singleton<AsyncWorker>() { mThread = std::thread(&AsyncWorker::run, this); }
486
487 ~AsyncWorker() {
488 mDone = true;
489 mCv.notify_all();
490 if (mThread.joinable()) {
491 mThread.join();
492 }
493 }
494
495 void post(std::function<void()> runnable) {
496 std::unique_lock<std::mutex> lock(mMutex);
497 mRunnables.emplace_back(std::move(runnable));
498 mCv.notify_one();
499 }
500};
501ANDROID_SINGLETON_STATIC_INSTANCE(AsyncWorker);
502
503// Asynchronously calls ProducerListener functions so we can emulate one way binder calls.
504class AsyncProducerListener : public BnProducerListener {
505private:
506 const sp<IProducerListener> mListener;
507
508public:
509 AsyncProducerListener(const sp<IProducerListener>& listener) : mListener(listener) {}
510
511 void onBufferReleased() override {
512 AsyncWorker::getInstance().post([listener = mListener]() { listener->onBufferReleased(); });
513 }
514
515 void onBuffersDiscarded(const std::vector<int32_t>& slots) override {
516 AsyncWorker::getInstance().post(
517 [listener = mListener, slots = slots]() { listener->onBuffersDiscarded(slots); });
518 }
519};
520
521// Extends the BufferQueueProducer to create a wrapper around the listener so the listener calls
522// can be non-blocking when the producer is in the client process.
523class BBQBufferQueueProducer : public BufferQueueProducer {
524public:
525 BBQBufferQueueProducer(const sp<BufferQueueCore>& core)
526 : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/) {}
527
528 status_t connect(const sp<IProducerListener>& listener, int api, bool producerControlledByApp,
529 QueueBufferOutput* output) override {
530 if (!listener) {
531 return BufferQueueProducer::connect(listener, api, producerControlledByApp, output);
532 }
533
534 return BufferQueueProducer::connect(new AsyncProducerListener(listener), api,
535 producerControlledByApp, output);
536 }
537};
538
539// Similar to BufferQueue::createBufferQueue but creates an adapter specific bufferqueue producer.
540// This BQP allows invoking client specified ProducerListeners and invoke them asynchronously,
541// emulating one way binder call behavior. Without this, if the listener calls back into the queue,
542// we can deadlock.
543void BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
544 sp<IGraphicBufferConsumer>* outConsumer) {
545 LOG_ALWAYS_FATAL_IF(outProducer == nullptr, "BLASTBufferQueue: outProducer must not be NULL");
546 LOG_ALWAYS_FATAL_IF(outConsumer == nullptr, "BLASTBufferQueue: outConsumer must not be NULL");
547
548 sp<BufferQueueCore> core(new BufferQueueCore());
549 LOG_ALWAYS_FATAL_IF(core == nullptr, "BLASTBufferQueue: failed to create BufferQueueCore");
550
551 sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core));
552 LOG_ALWAYS_FATAL_IF(producer == nullptr,
553 "BLASTBufferQueue: failed to create BBQBufferQueueProducer");
554
555 sp<IGraphicBufferConsumer> consumer(new BufferQueueConsumer(core));
556 LOG_ALWAYS_FATAL_IF(consumer == nullptr,
557 "BLASTBufferQueue: failed to create BufferQueueConsumer");
558
559 *outProducer = producer;
560 *outConsumer = consumer;
561}
562
Robert Carr78c25dd2019-08-15 14:10:33 -0700563} // namespace android