blob: 2e7cef08475ad2f54e3a640d87646736f50c4e24 [file] [log] [blame]
Dan Stoza289ade12014-02-28 11:17:17 -08001/*
2 * Copyright 2014 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
Mark Salyzyn8f515ce2014-06-09 14:32:04 -070017#include <inttypes.h>
18
Dan Stoza3e96f192014-03-03 10:16:19 -080019#define LOG_TAG "BufferQueueProducer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21//#define LOG_NDEBUG 0
22
Pablo Ceballos9e314332016-01-12 13:49:19 -080023#if DEBUG_ONLY_CODE
24#define VALIDATE_CONSISTENCY() do { mCore->validateConsistencyLocked(); } while (0)
25#else
26#define VALIDATE_CONSISTENCY()
27#endif
28
Dan Stoza289ade12014-02-28 11:17:17 -080029#define EGL_EGLEXT_PROTOTYPES
30
Robert Carr97b9c862016-09-08 13:54:35 -070031#include <binder/IPCThreadState.h>
Dan Stoza289ade12014-02-28 11:17:17 -080032#include <gui/BufferItem.h>
33#include <gui/BufferQueueCore.h>
34#include <gui/BufferQueueProducer.h>
Ady Abraham107788e2023-10-17 12:31:08 -070035
Ady Abraham6cdd3fd2023-09-07 18:45:58 -070036#include <gui/FrameRateUtils.h>
John Reck1a61da52016-04-28 13:18:15 -070037#include <gui/GLConsumer.h>
Dan Stoza289ade12014-02-28 11:17:17 -080038#include <gui/IConsumerListener.h>
Dan Stozaf0eaf252014-03-21 13:05:51 -070039#include <gui/IProducerListener.h>
Vishnu Nair14a3c112023-04-21 14:49:47 -070040#include <gui/TraceUtils.h>
Jayant Chowdharyad9fe272019-03-07 22:36:06 -080041#include <private/gui/BufferQueueThreadState.h>
Dan Stoza289ade12014-02-28 11:17:17 -080042
43#include <utils/Log.h>
44#include <utils/Trace.h>
45
Mathias Agopian6a3c05b2017-04-27 20:06:55 -070046#include <system/window.h>
47
Mathias Agopianb96661f2024-09-17 11:45:38 -070048#include <com_android_graphics_libgui_flags.h>
49
Dan Stoza289ade12014-02-28 11:17:17 -080050namespace android {
Mathias Agopianb96661f2024-09-17 11:45:38 -070051using namespace com::android::graphics::libgui;
Dan Stoza289ade12014-02-28 11:17:17 -080052
Iris Chang430193f2019-12-04 16:25:46 +080053// Macros for include BufferQueueCore information in log messages
54#define BQ_LOGV(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000055 ALOGV("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080056 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
57 ##__VA_ARGS__)
58#define BQ_LOGD(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000059 ALOGD("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080060 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
61 ##__VA_ARGS__)
62#define BQ_LOGI(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000063 ALOGI("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080064 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
65 ##__VA_ARGS__)
66#define BQ_LOGW(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000067 ALOGW("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080068 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
69 ##__VA_ARGS__)
70#define BQ_LOGE(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000071 ALOGE("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080072 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
73 ##__VA_ARGS__)
74
Craig Donner6ebc46a2016-10-21 15:23:44 -070075static constexpr uint32_t BQ_LAYER_COUNT = 1;
Chong Zhang62493092020-01-15 16:04:47 -080076ProducerListener::~ProducerListener() = default;
Craig Donner6ebc46a2016-10-21 15:23:44 -070077
Irvel468051e2016-06-13 16:44:44 -070078BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core,
79 bool consumerIsSurfaceFlinger) :
Dan Stoza289ade12014-02-28 11:17:17 -080080 mCore(core),
81 mSlots(core->mSlots),
Ruben Brunk1681d952014-06-27 15:51:55 -070082 mConsumerName(),
Eric Penner99a0afb2014-09-30 11:28:30 -070083 mStickyTransform(0),
Irvel468051e2016-06-13 16:44:44 -070084 mConsumerIsSurfaceFlinger(consumerIsSurfaceFlinger),
Dan Stoza8dc55392014-11-04 11:37:46 -080085 mLastQueueBufferFence(Fence::NO_FENCE),
Pablo Ceballosbd3577e2016-06-20 17:40:34 -070086 mLastQueuedTransform(0),
Dan Stoza8dc55392014-11-04 11:37:46 -080087 mCallbackMutex(),
88 mNextCallbackTicket(0),
89 mCurrentCallbackTicket(0),
Dan Stoza127fc632015-06-30 13:43:32 -070090 mCallbackCondition(),
Jorim Jaggi35b4e382019-03-28 00:44:03 +010091 mDequeueTimeout(-1),
92 mDequeueWaitingForAllocation(false) {}
Dan Stoza289ade12014-02-28 11:17:17 -080093
94BufferQueueProducer::~BufferQueueProducer() {}
95
96status_t BufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
97 ATRACE_CALL();
98 BQ_LOGV("requestBuffer: slot %d", slot);
Jorim Jaggi6ae55032019-04-02 02:27:44 +020099 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800100
101 if (mCore->mIsAbandoned) {
102 BQ_LOGE("requestBuffer: BufferQueue has been abandoned");
103 return NO_INIT;
104 }
105
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700106 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
107 BQ_LOGE("requestBuffer: BufferQueue has no connected producer");
108 return NO_INIT;
109 }
110
Dan Stoza3e96f192014-03-03 10:16:19 -0800111 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
Dan Stoza289ade12014-02-28 11:17:17 -0800112 BQ_LOGE("requestBuffer: slot index %d out of range [0, %d)",
Dan Stoza3e96f192014-03-03 10:16:19 -0800113 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
Dan Stoza289ade12014-02-28 11:17:17 -0800114 return BAD_VALUE;
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700115 } else if (!mSlots[slot].mBufferState.isDequeued()) {
Dan Stoza289ade12014-02-28 11:17:17 -0800116 BQ_LOGE("requestBuffer: slot %d is not owned by the producer "
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700117 "(state = %s)", slot, mSlots[slot].mBufferState.string());
Dan Stoza289ade12014-02-28 11:17:17 -0800118 return BAD_VALUE;
119 }
120
121 mSlots[slot].mRequestBufferCalled = true;
122 *buf = mSlots[slot].mGraphicBuffer;
123 return NO_ERROR;
124}
125
Pablo Ceballosfa455352015-08-12 17:47:47 -0700126status_t BufferQueueProducer::setMaxDequeuedBufferCount(
127 int maxDequeuedBuffers) {
Brian Lindahlc794b692023-01-31 15:42:47 -0700128 int maxBufferCount;
129 return setMaxDequeuedBufferCount(maxDequeuedBuffers, &maxBufferCount);
130}
131
132status_t BufferQueueProducer::setMaxDequeuedBufferCount(int maxDequeuedBuffers,
133 int* maxBufferCount) {
Vishnu Nair14a3c112023-04-21 14:49:47 -0700134 ATRACE_FORMAT("%s(%d)", __func__, maxDequeuedBuffers);
Pablo Ceballosfa455352015-08-12 17:47:47 -0700135 BQ_LOGV("setMaxDequeuedBufferCount: maxDequeuedBuffers = %d",
136 maxDequeuedBuffers);
137
Pablo Ceballos981066c2016-02-18 12:54:37 -0800138 sp<IConsumerListener> listener;
Pablo Ceballosfa455352015-08-12 17:47:47 -0700139 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200140 std::unique_lock<std::mutex> lock(mCore->mMutex);
141 mCore->waitWhileAllocatingLocked(lock);
Pablo Ceballosfa455352015-08-12 17:47:47 -0700142
143 if (mCore->mIsAbandoned) {
144 BQ_LOGE("setMaxDequeuedBufferCount: BufferQueue has been "
145 "abandoned");
146 return NO_INIT;
147 }
148
Brian Lindahlc794b692023-01-31 15:42:47 -0700149 *maxBufferCount = mCore->getMaxBufferCountLocked();
150
Pablo Ceballos245cc5b2016-04-19 11:33:00 -0700151 if (maxDequeuedBuffers == mCore->mMaxDequeuedBufferCount) {
152 return NO_ERROR;
153 }
154
Pablo Ceballos72daab62015-12-07 16:38:43 -0800155 // The new maxDequeuedBuffer count should not be violated by the number
156 // of currently dequeued buffers
157 int dequeuedCount = 0;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800158 for (int s : mCore->mActiveBuffers) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700159 if (mSlots[s].mBufferState.isDequeued()) {
Pablo Ceballos72daab62015-12-07 16:38:43 -0800160 dequeuedCount++;
Pablo Ceballosfa455352015-08-12 17:47:47 -0700161 }
162 }
Pablo Ceballos72daab62015-12-07 16:38:43 -0800163 if (dequeuedCount > maxDequeuedBuffers) {
164 BQ_LOGE("setMaxDequeuedBufferCount: the requested maxDequeuedBuffer"
165 "count (%d) exceeds the current dequeued buffer count (%d)",
166 maxDequeuedBuffers, dequeuedCount);
167 return BAD_VALUE;
168 }
Pablo Ceballosfa455352015-08-12 17:47:47 -0700169
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700170 int bufferCount = mCore->getMinUndequeuedBufferCountLocked();
Pablo Ceballosfa455352015-08-12 17:47:47 -0700171 bufferCount += maxDequeuedBuffers;
172
173 if (bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) {
174 BQ_LOGE("setMaxDequeuedBufferCount: bufferCount %d too large "
175 "(max %d)", bufferCount, BufferQueueDefs::NUM_BUFFER_SLOTS);
176 return BAD_VALUE;
177 }
178
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700179 const int minBufferSlots = mCore->getMinMaxBufferCountLocked();
Pablo Ceballosfa455352015-08-12 17:47:47 -0700180 if (bufferCount < minBufferSlots) {
181 BQ_LOGE("setMaxDequeuedBufferCount: requested buffer count %d is "
182 "less than minimum %d", bufferCount, minBufferSlots);
183 return BAD_VALUE;
184 }
185
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700186 if (bufferCount > mCore->mMaxBufferCount) {
187 BQ_LOGE("setMaxDequeuedBufferCount: %d dequeued buffers would "
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700188 "exceed the maxBufferCount (%d) (maxAcquired %d async %d "
189 "mDequeuedBufferCannotBlock %d)", maxDequeuedBuffers,
190 mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
191 mCore->mAsyncMode, mCore->mDequeueBufferCannotBlock);
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700192 return BAD_VALUE;
193 }
194
Pablo Ceballos72daab62015-12-07 16:38:43 -0800195 int delta = maxDequeuedBuffers - mCore->mMaxDequeuedBufferCount;
Pablo Ceballos981066c2016-02-18 12:54:37 -0800196 if (!mCore->adjustAvailableSlotsLocked(delta)) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800197 return BAD_VALUE;
198 }
Pablo Ceballosfa455352015-08-12 17:47:47 -0700199 mCore->mMaxDequeuedBufferCount = maxDequeuedBuffers;
Brian Lindahlc794b692023-01-31 15:42:47 -0700200 *maxBufferCount = mCore->getMaxBufferCountLocked();
Pablo Ceballos9e314332016-01-12 13:49:19 -0800201 VALIDATE_CONSISTENCY();
Pablo Ceballos72daab62015-12-07 16:38:43 -0800202 if (delta < 0) {
Pablo Ceballos981066c2016-02-18 12:54:37 -0800203 listener = mCore->mConsumerListener;
Pablo Ceballos72daab62015-12-07 16:38:43 -0800204 }
Patrick Williams078d7362024-08-27 10:20:39 -0500205#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
206 mCore->notifyBufferReleased();
207#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200208 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -0500209#endif
Pablo Ceballosfa455352015-08-12 17:47:47 -0700210 } // Autolock scope
211
212 // Call back without lock held
Yi Kong48a619f2018-06-05 16:34:59 -0700213 if (listener != nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -0800214 listener->onBuffersReleased();
Pablo Ceballosfa455352015-08-12 17:47:47 -0700215 }
216
217 return NO_ERROR;
218}
219
220status_t BufferQueueProducer::setAsyncMode(bool async) {
221 ATRACE_CALL();
222 BQ_LOGV("setAsyncMode: async = %d", async);
223
Pablo Ceballos981066c2016-02-18 12:54:37 -0800224 sp<IConsumerListener> listener;
Pablo Ceballosfa455352015-08-12 17:47:47 -0700225 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200226 std::unique_lock<std::mutex> lock(mCore->mMutex);
227 mCore->waitWhileAllocatingLocked(lock);
Pablo Ceballosfa455352015-08-12 17:47:47 -0700228
229 if (mCore->mIsAbandoned) {
230 BQ_LOGE("setAsyncMode: BufferQueue has been abandoned");
231 return NO_INIT;
232 }
233
Pablo Ceballos245cc5b2016-04-19 11:33:00 -0700234 if (async == mCore->mAsyncMode) {
235 return NO_ERROR;
236 }
237
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700238 if ((mCore->mMaxAcquiredBufferCount + mCore->mMaxDequeuedBufferCount +
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700239 (async || mCore->mDequeueBufferCannotBlock ? 1 : 0)) >
240 mCore->mMaxBufferCount) {
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700241 BQ_LOGE("setAsyncMode(%d): this call would cause the "
242 "maxBufferCount (%d) to be exceeded (maxAcquired %d "
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700243 "maxDequeued %d mDequeueBufferCannotBlock %d)", async,
244 mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
245 mCore->mMaxDequeuedBufferCount,
246 mCore->mDequeueBufferCannotBlock);
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700247 return BAD_VALUE;
248 }
249
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800250 int delta = mCore->getMaxBufferCountLocked(async,
251 mCore->mDequeueBufferCannotBlock, mCore->mMaxBufferCount)
252 - mCore->getMaxBufferCountLocked();
253
Pablo Ceballos981066c2016-02-18 12:54:37 -0800254 if (!mCore->adjustAvailableSlotsLocked(delta)) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800255 BQ_LOGE("setAsyncMode: BufferQueue failed to adjust the number of "
256 "available slots. Delta = %d", delta);
257 return BAD_VALUE;
258 }
Pablo Ceballosfa455352015-08-12 17:47:47 -0700259 mCore->mAsyncMode = async;
Pablo Ceballos9e314332016-01-12 13:49:19 -0800260 VALIDATE_CONSISTENCY();
Patrick Williams078d7362024-08-27 10:20:39 -0500261#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
262 mCore->notifyBufferReleased();
263#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200264 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -0500265#endif
266
Pablo Ceballos245cc5b2016-04-19 11:33:00 -0700267 if (delta < 0) {
268 listener = mCore->mConsumerListener;
269 }
Pablo Ceballosfa455352015-08-12 17:47:47 -0700270 } // Autolock scope
271
272 // Call back without lock held
Yi Kong48a619f2018-06-05 16:34:59 -0700273 if (listener != nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -0800274 listener->onBuffersReleased();
Pablo Ceballosfa455352015-08-12 17:47:47 -0700275 }
276 return NO_ERROR;
277}
278
Dan Stoza5ecfb682016-01-04 17:01:02 -0800279int BufferQueueProducer::getFreeBufferLocked() const {
280 if (mCore->mFreeBuffers.empty()) {
281 return BufferQueueCore::INVALID_BUFFER_SLOT;
282 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800283 int slot = mCore->mFreeBuffers.front();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800284 mCore->mFreeBuffers.pop_front();
285 return slot;
286}
287
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800288int BufferQueueProducer::getFreeSlotLocked() const {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800289 if (mCore->mFreeSlots.empty()) {
290 return BufferQueueCore::INVALID_BUFFER_SLOT;
291 }
Pablo Ceballosdce5c552016-02-10 15:43:22 -0800292 int slot = *(mCore->mFreeSlots.begin());
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800293 mCore->mFreeSlots.erase(slot);
Pablo Ceballosdce5c552016-02-10 15:43:22 -0800294 return slot;
Dan Stoza5ecfb682016-01-04 17:01:02 -0800295}
296
297status_t BufferQueueProducer::waitForFreeSlotThenRelock(FreeSlotCaller caller,
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200298 std::unique_lock<std::mutex>& lock, int* found) const {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800299 auto callerString = (caller == FreeSlotCaller::Dequeue) ?
300 "dequeueBuffer" : "attachBuffer";
Dan Stoza9f3053d2014-03-06 15:14:33 -0800301 bool tryAgain = true;
302 while (tryAgain) {
303 if (mCore->mIsAbandoned) {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800304 BQ_LOGE("%s: BufferQueue has been abandoned", callerString);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800305 return NO_INIT;
306 }
307
Dan Stoza9f3053d2014-03-06 15:14:33 -0800308 int dequeuedCount = 0;
309 int acquiredCount = 0;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800310 for (int s : mCore->mActiveBuffers) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700311 if (mSlots[s].mBufferState.isDequeued()) {
312 ++dequeuedCount;
313 }
314 if (mSlots[s].mBufferState.isAcquired()) {
315 ++acquiredCount;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800316 }
317 }
318
Pablo Ceballose5b755a2015-08-13 16:18:19 -0700319 // Producers are not allowed to dequeue more than
320 // mMaxDequeuedBufferCount buffers.
321 // This check is only done if a buffer has already been queued
322 if (mCore->mBufferHasBeenQueued &&
323 dequeuedCount >= mCore->mMaxDequeuedBufferCount) {
Sungtak Leeaf141242019-04-24 16:36:44 -0700324 // Supress error logs when timeout is non-negative.
325 if (mDequeueTimeout < 0) {
326 BQ_LOGE("%s: attempting to exceed the max dequeued buffer "
327 "count (%d)", callerString,
328 mCore->mMaxDequeuedBufferCount);
329 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800330 return INVALID_OPERATION;
331 }
332
Dan Stoza0de7ea72015-04-23 13:20:51 -0700333 *found = BufferQueueCore::INVALID_BUFFER_SLOT;
334
Dan Stozaae3c3682014-04-18 15:43:35 -0700335 // If we disconnect and reconnect quickly, we can be in a state where
336 // our slots are empty but we have many buffers in the queue. This can
337 // cause us to run out of memory if we outrun the consumer. Wait here if
338 // it looks like we have too many buffers queued up.
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800339 const int maxBufferCount = mCore->getMaxBufferCountLocked();
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700340 bool tooManyBuffers = mCore->mQueue.size()
341 > static_cast<size_t>(maxBufferCount);
Dan Stozaae3c3682014-04-18 15:43:35 -0700342 if (tooManyBuffers) {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800343 BQ_LOGV("%s: queue size is %zu, waiting", callerString,
Dan Stozaae3c3682014-04-18 15:43:35 -0700344 mCore->mQueue.size());
Dan Stoza0de7ea72015-04-23 13:20:51 -0700345 } else {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700346 // If in shared buffer mode and a shared buffer exists, always
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700347 // return it.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700348 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot !=
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700349 BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700350 *found = mCore->mSharedBufferSlot;
Dan Stoza5ecfb682016-01-04 17:01:02 -0800351 } else {
352 if (caller == FreeSlotCaller::Dequeue) {
353 // If we're calling this from dequeue, prefer free buffers
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800354 int slot = getFreeBufferLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800355 if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
356 *found = slot;
357 } else if (mCore->mAllowAllocation) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800358 *found = getFreeSlotLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800359 }
360 } else {
361 // If we're calling this from attach, prefer free slots
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800362 int slot = getFreeSlotLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800363 if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
364 *found = slot;
365 } else {
366 *found = getFreeBufferLocked();
367 }
Dan Stoza0de7ea72015-04-23 13:20:51 -0700368 }
369 }
Dan Stozaae3c3682014-04-18 15:43:35 -0700370 }
371
372 // If no buffer is found, or if the queue has too many buffers
373 // outstanding, wait for a buffer to be acquired or released, or for the
374 // max buffer count to change.
375 tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
376 tooManyBuffers;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800377 if (tryAgain) {
378 // Return an error if we're in non-blocking mode (producer and
379 // consumer are controlled by the application).
380 // However, the consumer is allowed to briefly acquire an extra
381 // buffer (which could cause us to have to wait here), which is
382 // okay, since it is only used to implement an atomic acquire +
383 // release (e.g., in GLConsumer::updateTexImage())
Pablo Ceballosfa455352015-08-12 17:47:47 -0700384 if ((mCore->mDequeueBufferCannotBlock || mCore->mAsyncMode) &&
Dan Stoza9f3053d2014-03-06 15:14:33 -0800385 (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
386 return WOULD_BLOCK;
387 }
Patrick Williams078d7362024-08-27 10:20:39 -0500388#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
389 if (status_t status = waitForBufferRelease(lock, mDequeueTimeout);
390 status == TIMED_OUT) {
391 return TIMED_OUT;
392 }
393#else
Dan Stoza127fc632015-06-30 13:43:32 -0700394 if (mDequeueTimeout >= 0) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200395 std::cv_status result = mCore->mDequeueCondition.wait_for(lock,
396 std::chrono::nanoseconds(mDequeueTimeout));
397 if (result == std::cv_status::timeout) {
398 return TIMED_OUT;
Dan Stoza127fc632015-06-30 13:43:32 -0700399 }
400 } else {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200401 mCore->mDequeueCondition.wait(lock);
Dan Stoza127fc632015-06-30 13:43:32 -0700402 }
Patrick Williams078d7362024-08-27 10:20:39 -0500403#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800404 }
405 } // while (tryAgain)
406
407 return NO_ERROR;
408}
409
Patrick Williams078d7362024-08-27 10:20:39 -0500410#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
411status_t BufferQueueProducer::waitForBufferRelease(std::unique_lock<std::mutex>& lock,
412 nsecs_t timeout) const {
413 if (mDequeueTimeout >= 0) {
414 std::cv_status result =
415 mCore->mDequeueCondition.wait_for(lock, std::chrono::nanoseconds(timeout));
416 if (result == std::cv_status::timeout) {
417 return TIMED_OUT;
418 }
419 } else {
420 mCore->mDequeueCondition.wait(lock);
421 }
422 return OK;
423}
424#endif
425
Ian Elliottd11b0442017-07-18 11:05:49 -0600426status_t BufferQueueProducer::dequeueBuffer(int* outSlot, sp<android::Fence>* outFence,
427 uint32_t width, uint32_t height, PixelFormat format,
428 uint64_t usage, uint64_t* outBufferAge,
429 FrameEventHistoryDelta* outTimestamps) {
Dan Stoza289ade12014-02-28 11:17:17 -0800430 ATRACE_CALL();
431 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200432 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800433 mConsumerName = mCore->mConsumerName;
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700434
435 if (mCore->mIsAbandoned) {
436 BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
437 return NO_INIT;
438 }
439
440 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
441 BQ_LOGE("dequeueBuffer: BufferQueue has no connected producer");
442 return NO_INIT;
443 }
Dan Stoza289ade12014-02-28 11:17:17 -0800444 } // Autolock scope
445
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700446 BQ_LOGV("dequeueBuffer: w=%u h=%u format=%#x, usage=%#" PRIx64, width, height, format, usage);
Dan Stoza289ade12014-02-28 11:17:17 -0800447
448 if ((width && !height) || (!width && height)) {
449 BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
450 return BAD_VALUE;
451 }
452
453 status_t returnFlags = NO_ERROR;
Jim Shargo90842182024-11-14 00:49:27 +0000454#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800455 EGLDisplay eglDisplay = EGL_NO_DISPLAY;
456 EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000457#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800458 bool attachedByConsumer = false;
Dan Stoza289ade12014-02-28 11:17:17 -0800459
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000460 sp<IConsumerListener> listener;
461 bool callOnFrameDequeued = false;
462 uint64_t bufferId = 0; // Only used if callOnFrameDequeued == true
John Reckdb164ff2024-04-03 16:59:28 -0400463#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
464 std::vector<gui::AdditionalOptions> allocOptions;
465 uint32_t allocOptionsGenId = 0;
466#endif
467
Dan Stoza289ade12014-02-28 11:17:17 -0800468 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200469 std::unique_lock<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800470
Jorim Jaggi35b4e382019-03-28 00:44:03 +0100471 // If we don't have a free buffer, but we are currently allocating, we wait until allocation
472 // is finished such that we don't allocate in parallel.
473 if (mCore->mFreeBuffers.empty() && mCore->mIsAllocating) {
474 mDequeueWaitingForAllocation = true;
475 mCore->waitWhileAllocatingLocked(lock);
476 mDequeueWaitingForAllocation = false;
477 mDequeueWaitingForAllocationCondition.notify_all();
478 }
Dan Stoza289ade12014-02-28 11:17:17 -0800479
480 if (format == 0) {
481 format = mCore->mDefaultBufferFormat;
482 }
483
484 // Enable the usage bits the consumer requested
485 usage |= mCore->mConsumerUsageBits;
486
Dan Stoza9de72932015-04-16 17:28:43 -0700487 const bool useDefaultSize = !width && !height;
488 if (useDefaultSize) {
489 width = mCore->mDefaultWidth;
490 height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -0700491 if (mCore->mAutoPrerotation &&
492 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
493 std::swap(width, height);
494 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800495 }
Dan Stoza289ade12014-02-28 11:17:17 -0800496
Pablo Ceballos981066c2016-02-18 12:54:37 -0800497 int found = BufferItem::INVALID_BUFFER_SLOT;
Dan Stoza9de72932015-04-16 17:28:43 -0700498 while (found == BufferItem::INVALID_BUFFER_SLOT) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200499 status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Dequeue, lock, &found);
Dan Stoza9de72932015-04-16 17:28:43 -0700500 if (status != NO_ERROR) {
501 return status;
502 }
503
504 // This should not happen
505 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
506 BQ_LOGE("dequeueBuffer: no available buffer slots");
507 return -EBUSY;
508 }
509
510 const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
511
512 // If we are not allowed to allocate new buffers,
513 // waitForFreeSlotThenRelock must have returned a slot containing a
514 // buffer. If this buffer would require reallocation to meet the
515 // requested attributes, we free it and attempt to get another one.
516 if (!mCore->mAllowAllocation) {
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700517 if (buffer->needsReallocation(width, height, format, BQ_LAYER_COUNT, usage)) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700518 if (mCore->mSharedBufferSlot == found) {
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700519 BQ_LOGE("dequeueBuffer: cannot re-allocate a sharedbuffer");
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700520 return BAD_VALUE;
521 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800522 mCore->mFreeSlots.insert(found);
523 mCore->clearBufferSlotLocked(found);
Dan Stoza9de72932015-04-16 17:28:43 -0700524 found = BufferItem::INVALID_BUFFER_SLOT;
525 continue;
526 }
527 }
Dan Stoza289ade12014-02-28 11:17:17 -0800528 }
529
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800530 const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800531
John Reckdb164ff2024-04-03 16:59:28 -0400532 bool needsReallocation = buffer == nullptr ||
533 buffer->needsReallocation(width, height, format, BQ_LAYER_COUNT, usage);
534
535#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
536 needsReallocation |= mSlots[found].mAdditionalOptionsGenerationId !=
537 mCore->mAdditionalOptionsGenerationId;
538#endif
539
540 if (mCore->mSharedBufferSlot == found && needsReallocation) {
541 BQ_LOGE("dequeueBuffer: cannot re-allocate a shared buffer");
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800542 return BAD_VALUE;
543 }
544
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700545 if (mCore->mSharedBufferSlot != found) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800546 mCore->mActiveBuffers.insert(found);
547 }
Dan Stoza289ade12014-02-28 11:17:17 -0800548 *outSlot = found;
549 ATRACE_BUFFER_INDEX(found);
550
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800551 attachedByConsumer = mSlots[found].mNeedsReallocation;
552 mSlots[found].mNeedsReallocation = false;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800553
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700554 mSlots[found].mBufferState.dequeue();
555
John Reckdb164ff2024-04-03 16:59:28 -0400556 if (needsReallocation) {
Vishnu Nair14a3c112023-04-21 14:49:47 -0700557 if (CC_UNLIKELY(ATRACE_ENABLED())) {
558 if (buffer == nullptr) {
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +0000559 ATRACE_FORMAT_INSTANT("%s buffer reallocation: null", mConsumerName.c_str());
Vishnu Nair14a3c112023-04-21 14:49:47 -0700560 } else {
561 ATRACE_FORMAT_INSTANT("%s buffer reallocation actual %dx%d format:%d "
562 "layerCount:%d "
563 "usage:%d requested: %dx%d format:%d layerCount:%d "
564 "usage:%d ",
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +0000565 mConsumerName.c_str(), width, height, format,
Vishnu Nair14a3c112023-04-21 14:49:47 -0700566 BQ_LAYER_COUNT, usage, buffer->getWidth(),
567 buffer->getHeight(), buffer->getPixelFormat(),
568 buffer->getLayerCount(), buffer->getUsage());
569 }
570 }
Dan Stoza289ade12014-02-28 11:17:17 -0800571 mSlots[found].mAcquireCalled = false;
Yi Kong48a619f2018-06-05 16:34:59 -0700572 mSlots[found].mGraphicBuffer = nullptr;
Dan Stoza289ade12014-02-28 11:17:17 -0800573 mSlots[found].mRequestBufferCalled = false;
Jim Shargo90842182024-11-14 00:49:27 +0000574#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800575 mSlots[found].mEglDisplay = EGL_NO_DISPLAY;
576 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000577#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800578 mSlots[found].mFence = Fence::NO_FENCE;
Dan Stoza4afd8b62015-02-25 16:49:08 -0800579 mCore->mBufferAge = 0;
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700580 mCore->mIsAllocating = true;
John Reckdb164ff2024-04-03 16:59:28 -0400581#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
582 allocOptions = mCore->mAdditionalOptions;
583 allocOptionsGenId = mCore->mAdditionalOptionsGenerationId;
584#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800585
586 returnFlags |= BUFFER_NEEDS_REALLOCATION;
Dan Stoza4afd8b62015-02-25 16:49:08 -0800587 } else {
588 // We add 1 because that will be the frame number when this buffer
589 // is queued
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700590 mCore->mBufferAge = mCore->mFrameCounter + 1 - mSlots[found].mFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -0800591 }
592
Dan Stoza800b41a2015-04-28 14:20:04 -0700593 BQ_LOGV("dequeueBuffer: setting buffer age to %" PRIu64,
594 mCore->mBufferAge);
Dan Stoza4afd8b62015-02-25 16:49:08 -0800595
Yi Kong48a619f2018-06-05 16:34:59 -0700596 if (CC_UNLIKELY(mSlots[found].mFence == nullptr)) {
Dan Stoza289ade12014-02-28 11:17:17 -0800597 BQ_LOGE("dequeueBuffer: about to return a NULL fence - "
598 "slot=%d w=%d h=%d format=%u",
599 found, buffer->width, buffer->height, buffer->format);
600 }
601
Jim Shargo90842182024-11-14 00:49:27 +0000602#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800603 eglDisplay = mSlots[found].mEglDisplay;
604 eglFence = mSlots[found].mEglFence;
Jim Shargo90842182024-11-14 00:49:27 +0000605#endif
Pablo Ceballos28c65ad2016-06-01 15:03:21 -0700606 // Don't return a fence in shared buffer mode, except for the first
607 // frame.
608 *outFence = (mCore->mSharedBufferMode &&
609 mCore->mSharedBufferSlot == found) ?
610 Fence::NO_FENCE : mSlots[found].mFence;
Jim Shargo90842182024-11-14 00:49:27 +0000611#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800612 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000613#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800614 mSlots[found].mFence = Fence::NO_FENCE;
Pablo Ceballos28c65ad2016-06-01 15:03:21 -0700615
616 // If shared buffer mode has just been enabled, cache the slot of the
617 // first buffer that is dequeued and mark it as the shared buffer.
618 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
619 BufferQueueCore::INVALID_BUFFER_SLOT) {
620 mCore->mSharedBufferSlot = found;
621 mSlots[found].mBufferState.mShared = true;
622 }
Adithya Srinivasana820af92019-11-01 13:55:17 -0700623
624 if (!(returnFlags & BUFFER_NEEDS_REALLOCATION)) {
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000625 callOnFrameDequeued = true;
626 bufferId = mSlots[*outSlot].mGraphicBuffer->getId();
Adithya Srinivasana820af92019-11-01 13:55:17 -0700627 }
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000628
629 listener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -0800630 } // Autolock scope
631
632 if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
Dan Stoza29a3e902014-06-20 13:13:57 -0700633 BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
John Reckdb164ff2024-04-03 16:59:28 -0400634
635#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
636 std::vector<GraphicBufferAllocator::AdditionalOptions> tempOptions;
637 tempOptions.reserve(allocOptions.size());
638 for (const auto& it : allocOptions) {
639 tempOptions.emplace_back(it.name.c_str(), it.value);
640 }
641 const GraphicBufferAllocator::AllocationRequest allocRequest = {
642 .importBuffer = true,
643 .width = width,
644 .height = height,
645 .format = format,
646 .layerCount = BQ_LAYER_COUNT,
647 .usage = usage,
648 .requestorName = {mConsumerName.c_str(), mConsumerName.size()},
649 .extras = std::move(tempOptions),
650 };
651 sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(allocRequest);
652#else
Tomasz Wasilczykf2add402023-08-11 00:06:51 +0000653 sp<GraphicBuffer> graphicBuffer =
654 new GraphicBuffer(width, height, format, BQ_LAYER_COUNT, usage,
655 {mConsumerName.c_str(), mConsumerName.size()});
John Reckdb164ff2024-04-03 16:59:28 -0400656#endif
Mathias Agopian0556d792017-03-22 15:49:32 -0700657
658 status_t error = graphicBuffer->initCheck();
659
Dan Stoza289ade12014-02-28 11:17:17 -0800660 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200661 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800662
Chia-I Wufeec3b12017-05-25 09:34:56 -0700663 if (error == NO_ERROR && !mCore->mIsAbandoned) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700664 graphicBuffer->setGenerationNumber(mCore->mGenerationNumber);
665 mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
John Reckdb164ff2024-04-03 16:59:28 -0400666#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
667 mSlots[*outSlot].mAdditionalOptionsGenerationId = allocOptionsGenId;
668#endif
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000669 callOnFrameDequeued = true;
670 bufferId = mSlots[*outSlot].mGraphicBuffer->getId();
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700671 }
672
673 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200674 mCore->mIsAllocatingCondition.notify_all();
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700675
Chia-I Wufeec3b12017-05-25 09:34:56 -0700676 if (error != NO_ERROR) {
Pablo Ceballos0a068092016-06-29 15:08:33 -0700677 mCore->mFreeSlots.insert(*outSlot);
678 mCore->clearBufferSlotLocked(*outSlot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700679 BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
680 return error;
681 }
682
Dan Stoza289ade12014-02-28 11:17:17 -0800683 if (mCore->mIsAbandoned) {
Pablo Ceballos0a068092016-06-29 15:08:33 -0700684 mCore->mFreeSlots.insert(*outSlot);
685 mCore->clearBufferSlotLocked(*outSlot);
Dan Stoza289ade12014-02-28 11:17:17 -0800686 BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
687 return NO_INIT;
688 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800689
Pablo Ceballos9e314332016-01-12 13:49:19 -0800690 VALIDATE_CONSISTENCY();
Dan Stoza289ade12014-02-28 11:17:17 -0800691 } // Autolock scope
692 }
693
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000694 if (listener != nullptr && callOnFrameDequeued) {
695 listener->onFrameDequeued(bufferId);
696 }
697
Dan Stoza9f3053d2014-03-06 15:14:33 -0800698 if (attachedByConsumer) {
699 returnFlags |= BUFFER_NEEDS_REALLOCATION;
700 }
701
Jim Shargo90842182024-11-14 00:49:27 +0000702#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800703 if (eglFence != EGL_NO_SYNC_KHR) {
704 EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0,
705 1000000000);
706 // If something goes wrong, log the error, but return the buffer without
707 // synchronizing access to it. It's too late at this point to abort the
708 // dequeue operation.
709 if (result == EGL_FALSE) {
710 BQ_LOGE("dequeueBuffer: error %#x waiting for fence",
711 eglGetError());
712 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
713 BQ_LOGE("dequeueBuffer: timeout waiting for fence");
714 }
715 eglDestroySyncKHR(eglDisplay, eglFence);
716 }
Jim Shargo90842182024-11-14 00:49:27 +0000717#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800718
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700719 BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
720 *outSlot,
Dan Stoza289ade12014-02-28 11:17:17 -0800721 mSlots[*outSlot].mFrameNumber,
tangcheng5614ca02022-04-07 14:26:05 +0800722 mSlots[*outSlot].mGraphicBuffer != nullptr ?
723 mSlots[*outSlot].mGraphicBuffer->handle : nullptr, returnFlags);
Dan Stoza289ade12014-02-28 11:17:17 -0800724
Ian Elliottd11b0442017-07-18 11:05:49 -0600725 if (outBufferAge) {
726 *outBufferAge = mCore->mBufferAge;
727 }
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700728 addAndGetFrameTimestamps(nullptr, outTimestamps);
729
Dan Stoza289ade12014-02-28 11:17:17 -0800730 return returnFlags;
731}
732
Dan Stoza9f3053d2014-03-06 15:14:33 -0800733status_t BufferQueueProducer::detachBuffer(int slot) {
734 ATRACE_CALL();
735 ATRACE_BUFFER_INDEX(slot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700736 BQ_LOGV("detachBuffer: slot %d", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800737
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700738 sp<IConsumerListener> listener;
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000739 bool callOnFrameDetached = false;
740 uint64_t bufferId = 0; // Only used if callOnFrameDetached is true
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700741 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200742 std::lock_guard<std::mutex> lock(mCore->mMutex);
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700743
744 if (mCore->mIsAbandoned) {
745 BQ_LOGE("detachBuffer: BufferQueue has been abandoned");
746 return NO_INIT;
747 }
748
749 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
750 BQ_LOGE("detachBuffer: BufferQueue has no connected producer");
751 return NO_INIT;
752 }
753
754 if (mCore->mSharedBufferMode || mCore->mSharedBufferSlot == slot) {
755 BQ_LOGE("detachBuffer: cannot detach a buffer in shared buffer mode");
756 return BAD_VALUE;
757 }
758
759 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
760 BQ_LOGE("detachBuffer: slot index %d out of range [0, %d)",
761 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
762 return BAD_VALUE;
763 } else if (!mSlots[slot].mBufferState.isDequeued()) {
Darwin Huang29936fa2021-09-08 18:29:18 +0000764 // TODO(http://b/140581935): This message is BQ_LOGW because it
765 // often logs when no actionable errors are present. Return to
766 // using BQ_LOGE after ensuring this only logs during errors.
767 BQ_LOGW("detachBuffer: slot %d is not owned by the producer "
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700768 "(state = %s)", slot, mSlots[slot].mBufferState.string());
769 return BAD_VALUE;
770 } else if (!mSlots[slot].mRequestBufferCalled) {
771 BQ_LOGE("detachBuffer: buffer in slot %d has not been requested",
772 slot);
773 return BAD_VALUE;
774 }
775
Adithya Srinivasan2e434382019-10-09 11:43:01 -0700776 listener = mCore->mConsumerListener;
Robert Carrfc069ba2020-04-20 13:26:31 -0700777 auto gb = mSlots[slot].mGraphicBuffer;
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000778 if (gb != nullptr) {
779 callOnFrameDetached = true;
780 bufferId = gb->getId();
Adithya Srinivasan2e434382019-10-09 11:43:01 -0700781 }
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700782 mSlots[slot].mBufferState.detachProducer();
783 mCore->mActiveBuffers.erase(slot);
784 mCore->mFreeSlots.insert(slot);
785 mCore->clearBufferSlotLocked(slot);
Patrick Williams078d7362024-08-27 10:20:39 -0500786#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
787 mCore->notifyBufferReleased();
788#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200789 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -0500790#endif
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700791 VALIDATE_CONSISTENCY();
Dan Stoza9f3053d2014-03-06 15:14:33 -0800792 }
793
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000794 if (listener != nullptr && callOnFrameDetached) {
795 listener->onFrameDetached(bufferId);
796 }
797
Yi Kong48a619f2018-06-05 16:34:59 -0700798 if (listener != nullptr) {
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700799 listener->onBuffersReleased();
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700800 }
Pablo Ceballos981066c2016-02-18 12:54:37 -0800801
Dan Stoza9f3053d2014-03-06 15:14:33 -0800802 return NO_ERROR;
803}
804
Dan Stozad9822a32014-03-28 15:25:31 -0700805status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
806 sp<Fence>* outFence) {
807 ATRACE_CALL();
808
Yi Kong48a619f2018-06-05 16:34:59 -0700809 if (outBuffer == nullptr) {
Dan Stozad9822a32014-03-28 15:25:31 -0700810 BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
811 return BAD_VALUE;
Yi Kong48a619f2018-06-05 16:34:59 -0700812 } else if (outFence == nullptr) {
Dan Stozad9822a32014-03-28 15:25:31 -0700813 BQ_LOGE("detachNextBuffer: outFence must not be NULL");
814 return BAD_VALUE;
815 }
816
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700817 sp<IConsumerListener> listener;
818 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200819 std::unique_lock<std::mutex> lock(mCore->mMutex);
Dan Stozad9822a32014-03-28 15:25:31 -0700820
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700821 if (mCore->mIsAbandoned) {
822 BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
823 return NO_INIT;
824 }
825
826 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
827 BQ_LOGE("detachNextBuffer: BufferQueue has no connected producer");
828 return NO_INIT;
829 }
830
831 if (mCore->mSharedBufferMode) {
832 BQ_LOGE("detachNextBuffer: cannot detach a buffer in shared buffer "
833 "mode");
834 return BAD_VALUE;
835 }
836
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200837 mCore->waitWhileAllocatingLocked(lock);
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700838
839 if (mCore->mFreeBuffers.empty()) {
840 return NO_MEMORY;
841 }
842
843 int found = mCore->mFreeBuffers.front();
844 mCore->mFreeBuffers.remove(found);
845 mCore->mFreeSlots.insert(found);
846
847 BQ_LOGV("detachNextBuffer detached slot %d", found);
848
849 *outBuffer = mSlots[found].mGraphicBuffer;
850 *outFence = mSlots[found].mFence;
851 mCore->clearBufferSlotLocked(found);
852 VALIDATE_CONSISTENCY();
853 listener = mCore->mConsumerListener;
Dan Stozad9822a32014-03-28 15:25:31 -0700854 }
855
Yi Kong48a619f2018-06-05 16:34:59 -0700856 if (listener != nullptr) {
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700857 listener->onBuffersReleased();
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700858 }
Pablo Ceballos981066c2016-02-18 12:54:37 -0800859
Dan Stozad9822a32014-03-28 15:25:31 -0700860 return NO_ERROR;
861}
862
Dan Stoza9f3053d2014-03-06 15:14:33 -0800863status_t BufferQueueProducer::attachBuffer(int* outSlot,
864 const sp<android::GraphicBuffer>& buffer) {
865 ATRACE_CALL();
866
Yi Kong48a619f2018-06-05 16:34:59 -0700867 if (outSlot == nullptr) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700868 BQ_LOGE("attachBuffer: outSlot must not be NULL");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800869 return BAD_VALUE;
Yi Kong48a619f2018-06-05 16:34:59 -0700870 } else if (buffer == nullptr) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700871 BQ_LOGE("attachBuffer: cannot attach NULL buffer");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800872 return BAD_VALUE;
873 }
874
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200875 std::unique_lock<std::mutex> lock(mCore->mMutex);
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700876
877 if (mCore->mIsAbandoned) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700878 BQ_LOGE("attachBuffer: BufferQueue has been abandoned");
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700879 return NO_INIT;
880 }
881
882 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700883 BQ_LOGE("attachBuffer: BufferQueue has no connected producer");
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700884 return NO_INIT;
885 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800886
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700887 if (mCore->mSharedBufferMode) {
888 BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode");
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700889 return BAD_VALUE;
890 }
891
Dan Stoza812ed062015-06-02 15:45:22 -0700892 if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
893 BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
894 "[queue %u]", buffer->getGenerationNumber(),
895 mCore->mGenerationNumber);
896 return BAD_VALUE;
897 }
898
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200899 mCore->waitWhileAllocatingLocked(lock);
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700900
Dan Stoza9f3053d2014-03-06 15:14:33 -0800901 status_t returnFlags = NO_ERROR;
902 int found;
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200903 status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Attach, lock, &found);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800904 if (status != NO_ERROR) {
905 return status;
906 }
907
908 // This should not happen
909 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700910 BQ_LOGE("attachBuffer: no available buffer slots");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800911 return -EBUSY;
912 }
913
914 *outSlot = found;
915 ATRACE_BUFFER_INDEX(*outSlot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700916 BQ_LOGV("attachBuffer: returning slot %d flags=%#x",
Dan Stoza9f3053d2014-03-06 15:14:33 -0800917 *outSlot, returnFlags);
918
919 mSlots[*outSlot].mGraphicBuffer = buffer;
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700920 mSlots[*outSlot].mBufferState.attachProducer();
Jim Shargo90842182024-11-14 00:49:27 +0000921#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza9f3053d2014-03-06 15:14:33 -0800922 mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000923#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800924 mSlots[*outSlot].mFence = Fence::NO_FENCE;
Dan Stoza2443c792014-03-24 15:03:46 -0700925 mSlots[*outSlot].mRequestBufferCalled = true;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800926 mSlots[*outSlot].mAcquireCalled = false;
Jammy Yu69958b82017-02-22 16:41:38 -0800927 mSlots[*outSlot].mNeedsReallocation = false;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800928 mCore->mActiveBuffers.insert(found);
Pablo Ceballos9e314332016-01-12 13:49:19 -0800929 VALIDATE_CONSISTENCY();
Dan Stoza0de7ea72015-04-23 13:20:51 -0700930
Dan Stoza9f3053d2014-03-06 15:14:33 -0800931 return returnFlags;
932}
933
Dan Stoza289ade12014-02-28 11:17:17 -0800934status_t BufferQueueProducer::queueBuffer(int slot,
935 const QueueBufferInput &input, QueueBufferOutput *output) {
936 ATRACE_CALL();
937 ATRACE_BUFFER_INDEX(slot);
938
Brian Andersond6927fb2016-07-23 23:37:30 -0700939 int64_t requestedPresentTimestamp;
Dan Stoza289ade12014-02-28 11:17:17 -0800940 bool isAutoTimestamp;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -0800941 android_dataspace dataSpace;
Pablo Ceballos60d69222015-08-07 14:47:20 -0700942 Rect crop(Rect::EMPTY_RECT);
Dan Stoza289ade12014-02-28 11:17:17 -0800943 int scalingMode;
944 uint32_t transform;
Ruben Brunk1681d952014-06-27 15:51:55 -0700945 uint32_t stickyTransform;
Brian Andersond6927fb2016-07-23 23:37:30 -0700946 sp<Fence> acquireFence;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700947 bool getFrameTimestamps = false;
Brian Andersond6927fb2016-07-23 23:37:30 -0700948 input.deflate(&requestedPresentTimestamp, &isAutoTimestamp, &dataSpace,
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700949 &crop, &scalingMode, &transform, &acquireFence, &stickyTransform,
950 &getFrameTimestamps);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700951 const Region& surfaceDamage = input.getSurfaceDamage();
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -0700952 const HdrMetadata& hdrMetadata = input.getHdrMetadata();
Brian Lindahl628cff42024-10-30 11:50:28 -0600953 const std::optional<PictureProfileHandle>& pictureProfileHandle =
954 input.getPictureProfileHandle();
Dan Stoza289ade12014-02-28 11:17:17 -0800955
Yi Kong48a619f2018-06-05 16:34:59 -0700956 if (acquireFence == nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -0800957 BQ_LOGE("queueBuffer: fence is NULL");
Jesse Hallde288fe2014-11-04 08:30:48 -0800958 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800959 }
960
Brian Anderson3d4039d2016-09-23 16:31:30 -0700961 auto acquireFenceTime = std::make_shared<FenceTime>(acquireFence);
962
Dan Stoza289ade12014-02-28 11:17:17 -0800963 switch (scalingMode) {
964 case NATIVE_WINDOW_SCALING_MODE_FREEZE:
965 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
966 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
967 case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
968 break;
969 default:
970 BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800971 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800972 }
973
Dan Stoza8dc55392014-11-04 11:37:46 -0800974 sp<IConsumerListener> frameAvailableListener;
975 sp<IConsumerListener> frameReplacedListener;
976 int callbackTicket = 0;
Brian Andersond6927fb2016-07-23 23:37:30 -0700977 uint64_t currentFrameNumber = 0;
Dan Stoza8dc55392014-11-04 11:37:46 -0800978 BufferItem item;
John Reckd2c4a4a2024-02-07 10:31:09 -0500979 int connectedApi;
Mathias Agopianb96661f2024-09-17 11:45:38 -0700980 bool enableEglCpuThrottling = true;
John Reckd2c4a4a2024-02-07 10:31:09 -0500981 sp<Fence> lastQueuedFence;
982
Dan Stoza289ade12014-02-28 11:17:17 -0800983 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200984 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800985
986 if (mCore->mIsAbandoned) {
987 BQ_LOGE("queueBuffer: BufferQueue has been abandoned");
988 return NO_INIT;
989 }
990
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700991 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
992 BQ_LOGE("queueBuffer: BufferQueue has no connected producer");
993 return NO_INIT;
994 }
995
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800996 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
Dan Stoza289ade12014-02-28 11:17:17 -0800997 BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)",
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800998 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800999 return BAD_VALUE;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001000 } else if (!mSlots[slot].mBufferState.isDequeued()) {
Dan Stoza289ade12014-02-28 11:17:17 -08001001 BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001002 "(state = %s)", slot, mSlots[slot].mBufferState.string());
Dan Stoza9f3053d2014-03-06 15:14:33 -08001003 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001004 } else if (!mSlots[slot].mRequestBufferCalled) {
1005 BQ_LOGE("queueBuffer: slot %d was queued without requesting "
1006 "a buffer", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001007 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001008 }
1009
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001010 // If shared buffer mode has just been enabled, cache the slot of the
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001011 // first buffer that is queued and mark it as the shared buffer.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001012 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001013 BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001014 mCore->mSharedBufferSlot = slot;
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001015 mSlots[slot].mBufferState.mShared = true;
1016 }
1017
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001018 BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d"
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -07001019 " validHdrMetadataTypes=0x%x crop=[%d,%d,%d,%d] transform=%#x scale=%s",
1020 slot, mCore->mFrameCounter + 1, requestedPresentTimestamp, dataSpace,
1021 hdrMetadata.validTypes, crop.left, crop.top, crop.right, crop.bottom,
Brian Andersond6927fb2016-07-23 23:37:30 -07001022 transform,
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001023 BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
Dan Stoza289ade12014-02-28 11:17:17 -08001024
1025 const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
1026 Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
Pablo Ceballos60d69222015-08-07 14:47:20 -07001027 Rect croppedRect(Rect::EMPTY_RECT);
Dan Stoza289ade12014-02-28 11:17:17 -08001028 crop.intersect(bufferRect, &croppedRect);
1029 if (croppedRect != crop) {
1030 BQ_LOGE("queueBuffer: crop rect is not contained within the "
1031 "buffer in slot %d", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001032 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001033 }
1034
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001035 // Override UNKNOWN dataspace with consumer default
1036 if (dataSpace == HAL_DATASPACE_UNKNOWN) {
1037 dataSpace = mCore->mDefaultBufferDataSpace;
1038 }
1039
Brian Andersond6927fb2016-07-23 23:37:30 -07001040 mSlots[slot].mFence = acquireFence;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001041 mSlots[slot].mBufferState.queue();
1042
Brian Andersond6927fb2016-07-23 23:37:30 -07001043 // Increment the frame counter and store a local version of it
1044 // for use outside the lock on mCore->mMutex.
Dan Stoza289ade12014-02-28 11:17:17 -08001045 ++mCore->mFrameCounter;
Brian Andersond6927fb2016-07-23 23:37:30 -07001046 currentFrameNumber = mCore->mFrameCounter;
1047 mSlots[slot].mFrameNumber = currentFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -08001048
Dan Stoza289ade12014-02-28 11:17:17 -08001049 item.mAcquireCalled = mSlots[slot].mAcquireCalled;
1050 item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
1051 item.mCrop = crop;
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001052 item.mTransform = transform &
1053 ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
Dan Stoza289ade12014-02-28 11:17:17 -08001054 item.mTransformToDisplayInverse =
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001055 (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
1056 item.mScalingMode = static_cast<uint32_t>(scalingMode);
Brian Andersond6927fb2016-07-23 23:37:30 -07001057 item.mTimestamp = requestedPresentTimestamp;
Dan Stoza289ade12014-02-28 11:17:17 -08001058 item.mIsAutoTimestamp = isAutoTimestamp;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001059 item.mDataSpace = dataSpace;
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -07001060 item.mHdrMetadata = hdrMetadata;
Brian Lindahl628cff42024-10-30 11:50:28 -06001061 item.mPictureProfileHandle = pictureProfileHandle;
Brian Andersond6927fb2016-07-23 23:37:30 -07001062 item.mFrameNumber = currentFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -08001063 item.mSlot = slot;
Brian Andersond6927fb2016-07-23 23:37:30 -07001064 item.mFence = acquireFence;
Brian Anderson3d4039d2016-09-23 16:31:30 -07001065 item.mFenceTime = acquireFenceTime;
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001066 item.mIsDroppable = mCore->mAsyncMode ||
Sungtak Lee45e9e0b2019-05-28 13:38:23 -07001067 (mConsumerIsSurfaceFlinger && mCore->mQueueBufferCanDrop) ||
Sungtak Lee3249fb62019-03-02 16:40:47 -08001068 (mCore->mLegacyBufferDrop && mCore->mQueueBufferCanDrop) ||
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001069 (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == slot);
Dan Stoza5065a552015-03-17 16:23:42 -07001070 item.mSurfaceDamage = surfaceDamage;
Pablo Ceballos06312182015-10-07 16:32:12 -07001071 item.mQueuedBuffer = true;
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001072 item.mAutoRefresh = mCore->mSharedBufferMode && mCore->mAutoRefresh;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001073 item.mApi = mCore->mConnectedApi;
Dan Stoza289ade12014-02-28 11:17:17 -08001074
Ruben Brunk1681d952014-06-27 15:51:55 -07001075 mStickyTransform = stickyTransform;
1076
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001077 // Cache the shared buffer data so that the BufferItem can be recreated.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001078 if (mCore->mSharedBufferMode) {
1079 mCore->mSharedBufferCache.crop = crop;
1080 mCore->mSharedBufferCache.transform = transform;
1081 mCore->mSharedBufferCache.scalingMode = static_cast<uint32_t>(
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001082 scalingMode);
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001083 mCore->mSharedBufferCache.dataspace = dataSpace;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001084 }
1085
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001086 output->bufferReplaced = false;
Dan Stoza289ade12014-02-28 11:17:17 -08001087 if (mCore->mQueue.empty()) {
1088 // When the queue is empty, we can ignore mDequeueBufferCannotBlock
1089 // and simply queue this buffer
1090 mCore->mQueue.push_back(item);
Dan Stoza8dc55392014-11-04 11:37:46 -08001091 frameAvailableListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001092 } else {
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001093 // When the queue is not empty, we need to look at the last buffer
1094 // in the queue to see if we need to replace it
1095 const BufferItem& last = mCore->mQueue.itemAt(
1096 mCore->mQueue.size() - 1);
1097 if (last.mIsDroppable) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001098
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001099 if (!last.mIsStale) {
1100 mSlots[last.mSlot].mBufferState.freeQueued();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001101
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001102 // After leaving shared buffer mode, the shared buffer will
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001103 // still be around. Mark it as no longer shared if this
1104 // operation causes it to be free.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001105 if (!mCore->mSharedBufferMode &&
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001106 mSlots[last.mSlot].mBufferState.isFree()) {
1107 mSlots[last.mSlot].mBufferState.mShared = false;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001108 }
1109 // Don't put the shared buffer on the free list.
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001110 if (!mSlots[last.mSlot].mBufferState.isShared()) {
1111 mCore->mActiveBuffers.erase(last.mSlot);
1112 mCore->mFreeBuffers.push_back(last.mSlot);
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001113 output->bufferReplaced = true;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001114 }
Dan Stoza289ade12014-02-28 11:17:17 -08001115 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001116
Steven Thomas862e7532019-07-10 19:21:03 -07001117 // Make sure to merge the damage rect from the frame we're about
1118 // to drop into the new frame's damage rect.
1119 if (last.mSurfaceDamage.bounds() == Rect::INVALID_RECT ||
1120 item.mSurfaceDamage.bounds() == Rect::INVALID_RECT) {
1121 item.mSurfaceDamage = Region::INVALID_REGION;
1122 } else {
1123 item.mSurfaceDamage |= last.mSurfaceDamage;
1124 }
1125
Dan Stoza289ade12014-02-28 11:17:17 -08001126 // Overwrite the droppable buffer with the incoming one
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001127 mCore->mQueue.editItemAt(mCore->mQueue.size() - 1) = item;
Dan Stoza8dc55392014-11-04 11:37:46 -08001128 frameReplacedListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001129 } else {
1130 mCore->mQueue.push_back(item);
Dan Stoza8dc55392014-11-04 11:37:46 -08001131 frameAvailableListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001132 }
1133 }
1134
1135 mCore->mBufferHasBeenQueued = true;
Patrick Williams078d7362024-08-27 10:20:39 -05001136#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1137 mCore->notifyBufferReleased();
1138#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001139 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001140#endif
Dan Stoza50101d02016-04-07 16:53:23 -07001141 mCore->mLastQueuedSlot = slot;
Dan Stoza289ade12014-02-28 11:17:17 -08001142
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001143 output->width = mCore->mDefaultWidth;
1144 output->height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001145 output->transformHint = mCore->mTransformHintInUse = mCore->mTransformHint;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001146 output->numPendingBuffers = static_cast<uint32_t>(mCore->mQueue.size());
1147 output->nextFrameNumber = mCore->mFrameCounter + 1;
Dan Stoza289ade12014-02-28 11:17:17 -08001148
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001149 ATRACE_INT(mCore->mConsumerName.c_str(), static_cast<int32_t>(mCore->mQueue.size()));
Chong Zhang62493092020-01-15 16:04:47 -08001150#ifndef NO_BINDER
Dan Stozae77c7662016-05-13 11:37:28 -07001151 mCore->mOccupancyTracker.registerOccupancyChange(mCore->mQueue.size());
Chong Zhang62493092020-01-15 16:04:47 -08001152#endif
Dan Stoza8dc55392014-11-04 11:37:46 -08001153 // Take a ticket for the callback functions
1154 callbackTicket = mNextCallbackTicket++;
Dan Stoza0de7ea72015-04-23 13:20:51 -07001155
Pablo Ceballos9e314332016-01-12 13:49:19 -08001156 VALIDATE_CONSISTENCY();
John Reckd2c4a4a2024-02-07 10:31:09 -05001157
1158 connectedApi = mCore->mConnectedApi;
Mathias Agopianb96661f2024-09-17 11:45:38 -07001159 if (flags::bq_producer_throttles_only_async_mode()) {
1160 enableEglCpuThrottling = mCore->mAsyncMode || mCore->mDequeueBufferCannotBlock;
1161 }
John Reckd2c4a4a2024-02-07 10:31:09 -05001162 lastQueuedFence = std::move(mLastQueueBufferFence);
1163
1164 mLastQueueBufferFence = std::move(acquireFence);
1165 mLastQueuedCrop = item.mCrop;
1166 mLastQueuedTransform = item.mTransform;
Dan Stoza289ade12014-02-28 11:17:17 -08001167 } // Autolock scope
1168
Irvel468051e2016-06-13 16:44:44 -07001169 // It is okay not to clear the GraphicBuffer when the consumer is SurfaceFlinger because
1170 // it is guaranteed that the BufferQueue is inside SurfaceFlinger's process and
1171 // there will be no Binder call
1172 if (!mConsumerIsSurfaceFlinger) {
1173 item.mGraphicBuffer.clear();
1174 }
1175
JihCheng Chiu544c5222019-04-02 20:50:58 +08001176 // Update and get FrameEventHistory.
1177 nsecs_t postedTime = systemTime(SYSTEM_TIME_MONOTONIC);
1178 NewFrameEventsEntry newFrameEventsEntry = {
1179 currentFrameNumber,
1180 postedTime,
1181 requestedPresentTimestamp,
1182 std::move(acquireFenceTime)
1183 };
1184 addAndGetFrameTimestamps(&newFrameEventsEntry,
1185 getFrameTimestamps ? &output->frameTimestamps : nullptr);
1186
Dan Stoza8dc55392014-11-04 11:37:46 -08001187 // Call back without the main BufferQueue lock held, but with the callback
1188 // lock held so we can ensure that callbacks occur in order
Mathias Agopian4f6ce7c2017-04-03 17:14:31 -07001189
Mathias Agopian4f6ce7c2017-04-03 17:14:31 -07001190 { // scope for the lock
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001191 std::unique_lock<std::mutex> lock(mCallbackMutex);
Dan Stoza8dc55392014-11-04 11:37:46 -08001192 while (callbackTicket != mCurrentCallbackTicket) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001193 mCallbackCondition.wait(lock);
Dan Stoza8dc55392014-11-04 11:37:46 -08001194 }
1195
Yi Kong48a619f2018-06-05 16:34:59 -07001196 if (frameAvailableListener != nullptr) {
Dan Stoza8dc55392014-11-04 11:37:46 -08001197 frameAvailableListener->onFrameAvailable(item);
Yi Kong48a619f2018-06-05 16:34:59 -07001198 } else if (frameReplacedListener != nullptr) {
Dan Stoza8dc55392014-11-04 11:37:46 -08001199 frameReplacedListener->onFrameReplaced(item);
1200 }
1201
1202 ++mCurrentCallbackTicket;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001203 mCallbackCondition.notify_all();
Dan Stoza289ade12014-02-28 11:17:17 -08001204 }
1205
Yiwei Zhangcb7dd002019-04-16 11:03:01 -07001206 // Wait without lock held
Mathias Agopianb96661f2024-09-17 11:45:38 -07001207 if (connectedApi == NATIVE_WINDOW_API_EGL && enableEglCpuThrottling) {
Yiwei Zhangcb7dd002019-04-16 11:03:01 -07001208 // Waiting here allows for two full buffers to be queued but not a
1209 // third. In the event that frames take varying time, this makes a
1210 // small trade-off in favor of latency rather than throughput.
1211 lastQueuedFence->waitForever("Throttling EGL Production");
1212 }
1213
Dan Stoza289ade12014-02-28 11:17:17 -08001214 return NO_ERROR;
1215}
1216
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001217status_t BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
Dan Stoza289ade12014-02-28 11:17:17 -08001218 ATRACE_CALL();
1219 BQ_LOGV("cancelBuffer: slot %d", slot);
Dan Stoza289ade12014-02-28 11:17:17 -08001220
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001221 sp<IConsumerListener> listener;
1222 bool callOnFrameCancelled = false;
1223 uint64_t bufferId = 0; // Only used if callOnFrameCancelled == true
1224 {
1225 std::lock_guard<std::mutex> lock(mCore->mMutex);
1226
1227 if (mCore->mIsAbandoned) {
1228 BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
1229 return NO_INIT;
1230 }
1231
1232 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1233 BQ_LOGE("cancelBuffer: BufferQueue has no connected producer");
1234 return NO_INIT;
1235 }
1236
1237 if (mCore->mSharedBufferMode) {
1238 BQ_LOGE("cancelBuffer: cannot cancel a buffer in shared buffer mode");
1239 return BAD_VALUE;
1240 }
1241
1242 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
1243 BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)", slot,
1244 BufferQueueDefs::NUM_BUFFER_SLOTS);
1245 return BAD_VALUE;
1246 } else if (!mSlots[slot].mBufferState.isDequeued()) {
1247 BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
1248 "(state = %s)",
1249 slot, mSlots[slot].mBufferState.string());
1250 return BAD_VALUE;
1251 } else if (fence == nullptr) {
1252 BQ_LOGE("cancelBuffer: fence is NULL");
1253 return BAD_VALUE;
1254 }
1255
1256 mSlots[slot].mBufferState.cancel();
1257
1258 // After leaving shared buffer mode, the shared buffer will still be around.
1259 // Mark it as no longer shared if this operation causes it to be free.
1260 if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) {
1261 mSlots[slot].mBufferState.mShared = false;
1262 }
1263
1264 // Don't put the shared buffer on the free list.
1265 if (!mSlots[slot].mBufferState.isShared()) {
1266 mCore->mActiveBuffers.erase(slot);
1267 mCore->mFreeBuffers.push_back(slot);
1268 }
1269
1270 auto gb = mSlots[slot].mGraphicBuffer;
1271 if (gb != nullptr) {
1272 callOnFrameCancelled = true;
1273 bufferId = gb->getId();
1274 }
1275 mSlots[slot].mFence = fence;
Patrick Williams078d7362024-08-27 10:20:39 -05001276#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1277 mCore->notifyBufferReleased();
1278#else
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001279 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001280#endif
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001281 listener = mCore->mConsumerListener;
1282 VALIDATE_CONSISTENCY();
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001283 }
1284
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001285 if (listener != nullptr && callOnFrameCancelled) {
1286 listener->onFrameCancelled(bufferId);
Dan Stoza289ade12014-02-28 11:17:17 -08001287 }
1288
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001289 return NO_ERROR;
Dan Stoza289ade12014-02-28 11:17:17 -08001290}
1291
1292int BufferQueueProducer::query(int what, int *outValue) {
1293 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001294 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -08001295
Yi Kong48a619f2018-06-05 16:34:59 -07001296 if (outValue == nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -08001297 BQ_LOGE("query: outValue was NULL");
1298 return BAD_VALUE;
1299 }
1300
1301 if (mCore->mIsAbandoned) {
1302 BQ_LOGE("query: BufferQueue has been abandoned");
1303 return NO_INIT;
1304 }
1305
1306 int value;
1307 switch (what) {
1308 case NATIVE_WINDOW_WIDTH:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001309 value = static_cast<int32_t>(mCore->mDefaultWidth);
Dan Stoza289ade12014-02-28 11:17:17 -08001310 break;
1311 case NATIVE_WINDOW_HEIGHT:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001312 value = static_cast<int32_t>(mCore->mDefaultHeight);
Dan Stoza289ade12014-02-28 11:17:17 -08001313 break;
1314 case NATIVE_WINDOW_FORMAT:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001315 value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
Dan Stoza289ade12014-02-28 11:17:17 -08001316 break;
Craig Donner6ebc46a2016-10-21 15:23:44 -07001317 case NATIVE_WINDOW_LAYER_COUNT:
1318 // All BufferQueue buffers have a single layer.
1319 value = BQ_LAYER_COUNT;
1320 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001321 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001322 value = mCore->getMinUndequeuedBufferCountLocked();
Dan Stoza289ade12014-02-28 11:17:17 -08001323 break;
Ruben Brunk1681d952014-06-27 15:51:55 -07001324 case NATIVE_WINDOW_STICKY_TRANSFORM:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001325 value = static_cast<int32_t>(mStickyTransform);
Ruben Brunk1681d952014-06-27 15:51:55 -07001326 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001327 case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
1328 value = (mCore->mQueue.size() > 1);
1329 break;
1330 case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
Chia-I Wue2786ea2017-08-07 10:36:08 -07001331 // deprecated; higher 32 bits are truncated
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001332 value = static_cast<int32_t>(mCore->mConsumerUsageBits);
Dan Stoza289ade12014-02-28 11:17:17 -08001333 break;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001334 case NATIVE_WINDOW_DEFAULT_DATASPACE:
1335 value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace);
1336 break;
Dan Stoza4afd8b62015-02-25 16:49:08 -08001337 case NATIVE_WINDOW_BUFFER_AGE:
1338 if (mCore->mBufferAge > INT32_MAX) {
1339 value = 0;
1340 } else {
1341 value = static_cast<int32_t>(mCore->mBufferAge);
1342 }
1343 break;
Jiwen 'Steve' Cai20419132017-04-21 18:49:53 -07001344 case NATIVE_WINDOW_CONSUMER_IS_PROTECTED:
1345 value = static_cast<int32_t>(mCore->mConsumerIsProtected);
1346 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001347 default:
1348 return BAD_VALUE;
1349 }
1350
1351 BQ_LOGV("query: %d? %d", what, value);
1352 *outValue = value;
1353 return NO_ERROR;
1354}
1355
Dan Stozaf0eaf252014-03-21 13:05:51 -07001356status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
Dan Stoza289ade12014-02-28 11:17:17 -08001357 int api, bool producerControlledByApp, QueueBufferOutput *output) {
1358 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001359 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballos981066c2016-02-18 12:54:37 -08001360 mConsumerName = mCore->mConsumerName;
1361 BQ_LOGV("connect: api=%d producerControlledByApp=%s", api,
1362 producerControlledByApp ? "true" : "false");
1363
1364 if (mCore->mIsAbandoned) {
1365 BQ_LOGE("connect: BufferQueue has been abandoned");
1366 return NO_INIT;
1367 }
1368
Yi Kong48a619f2018-06-05 16:34:59 -07001369 if (mCore->mConsumerListener == nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -08001370 BQ_LOGE("connect: BufferQueue has no consumer");
1371 return NO_INIT;
1372 }
1373
Yi Kong48a619f2018-06-05 16:34:59 -07001374 if (output == nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -08001375 BQ_LOGE("connect: output was NULL");
1376 return BAD_VALUE;
1377 }
1378
1379 if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
1380 BQ_LOGE("connect: already connected (cur=%d req=%d)",
1381 mCore->mConnectedApi, api);
1382 return BAD_VALUE;
1383 }
1384
1385 int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode,
1386 mDequeueTimeout < 0 ?
1387 mCore->mConsumerControlledByApp && producerControlledByApp : false,
1388 mCore->mMaxBufferCount) -
1389 mCore->getMaxBufferCountLocked();
1390 if (!mCore->adjustAvailableSlotsLocked(delta)) {
1391 BQ_LOGE("connect: BufferQueue failed to adjust the number of available "
1392 "slots. Delta = %d", delta);
1393 return BAD_VALUE;
1394 }
1395
Dan Stoza289ade12014-02-28 11:17:17 -08001396 int status = NO_ERROR;
Pablo Ceballos981066c2016-02-18 12:54:37 -08001397 switch (api) {
1398 case NATIVE_WINDOW_API_EGL:
1399 case NATIVE_WINDOW_API_CPU:
1400 case NATIVE_WINDOW_API_MEDIA:
1401 case NATIVE_WINDOW_API_CAMERA:
1402 mCore->mConnectedApi = api;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001403
1404 output->width = mCore->mDefaultWidth;
1405 output->height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001406 output->transformHint = mCore->mTransformHintInUse = mCore->mTransformHint;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001407 output->numPendingBuffers =
1408 static_cast<uint32_t>(mCore->mQueue.size());
1409 output->nextFrameNumber = mCore->mFrameCounter + 1;
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001410 output->bufferReplaced = false;
silence_dogoode9d092a2019-06-19 16:14:53 -07001411 output->maxBufferCount = mCore->mMaxBufferCount;
Dan Stoza289ade12014-02-28 11:17:17 -08001412
Yi Kong48a619f2018-06-05 16:34:59 -07001413 if (listener != nullptr) {
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001414 // Set up a death notification so that we can disconnect
1415 // automatically if the remote producer dies
Chong Zhang62493092020-01-15 16:04:47 -08001416#ifndef NO_BINDER
Yi Kong48a619f2018-06-05 16:34:59 -07001417 if (IInterface::asBinder(listener)->remoteBinder() != nullptr) {
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001418 status = IInterface::asBinder(listener)->linkToDeath(
1419 static_cast<IBinder::DeathRecipient*>(this));
1420 if (status != NO_ERROR) {
1421 BQ_LOGE("connect: linkToDeath failed: %s (%d)",
1422 strerror(-status), status);
1423 }
1424 mCore->mLinkedToDeath = listener;
1425 }
Chong Zhang62493092020-01-15 16:04:47 -08001426#endif
Shuzhen Wang067fcd32019-08-14 10:41:12 -07001427 mCore->mConnectedProducerListener = listener;
1428 mCore->mBufferReleasedCbEnabled = listener->needsReleaseNotify();
Sungtak Leecd217472024-07-19 17:17:40 +00001429#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1430 mCore->mBufferAttachedCbEnabled = listener->needsAttachNotify();
1431#endif
Pablo Ceballos981066c2016-02-18 12:54:37 -08001432 }
Pablo Ceballos981066c2016-02-18 12:54:37 -08001433 break;
1434 default:
1435 BQ_LOGE("connect: unknown API %d", api);
1436 status = BAD_VALUE;
1437 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001438 }
Jayant Chowdharyad9fe272019-03-07 22:36:06 -08001439 mCore->mConnectedPid = BufferQueueThreadState::getCallingPid();
Pablo Ceballos981066c2016-02-18 12:54:37 -08001440 mCore->mBufferHasBeenQueued = false;
1441 mCore->mDequeueBufferCannotBlock = false;
Sungtak Lee3249fb62019-03-02 16:40:47 -08001442 mCore->mQueueBufferCanDrop = false;
1443 mCore->mLegacyBufferDrop = true;
1444 if (mCore->mConsumerControlledByApp && producerControlledByApp) {
1445 mCore->mDequeueBufferCannotBlock = mDequeueTimeout < 0;
1446 mCore->mQueueBufferCanDrop = mDequeueTimeout <= 0;
Dan Stoza127fc632015-06-30 13:43:32 -07001447 }
Dan Stoza289ade12014-02-28 11:17:17 -08001448
Pablo Ceballos981066c2016-02-18 12:54:37 -08001449 mCore->mAllowAllocation = true;
John Reckdb164ff2024-04-03 16:59:28 -04001450#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1451 mCore->mAdditionalOptions.clear();
1452#endif
Pablo Ceballos981066c2016-02-18 12:54:37 -08001453 VALIDATE_CONSISTENCY();
Dan Stoza289ade12014-02-28 11:17:17 -08001454 return status;
1455}
1456
Robert Carr97b9c862016-09-08 13:54:35 -07001457status_t BufferQueueProducer::disconnect(int api, DisconnectMode mode) {
Dan Stoza289ade12014-02-28 11:17:17 -08001458 ATRACE_CALL();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001459 BQ_LOGV("disconnect: api %d", api);
Dan Stoza289ade12014-02-28 11:17:17 -08001460
1461 int status = NO_ERROR;
1462 sp<IConsumerListener> listener;
1463 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001464 std::unique_lock<std::mutex> lock(mCore->mMutex);
Robert Carr97b9c862016-09-08 13:54:35 -07001465
1466 if (mode == DisconnectMode::AllLocal) {
Jayant Chowdharyad9fe272019-03-07 22:36:06 -08001467 if (BufferQueueThreadState::getCallingPid() != mCore->mConnectedPid) {
Robert Carr97b9c862016-09-08 13:54:35 -07001468 return NO_ERROR;
1469 }
1470 api = BufferQueueCore::CURRENTLY_CONNECTED_API;
1471 }
1472
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001473 mCore->waitWhileAllocatingLocked(lock);
Dan Stoza289ade12014-02-28 11:17:17 -08001474
1475 if (mCore->mIsAbandoned) {
1476 // It's not really an error to disconnect after the surface has
1477 // been abandoned; it should just be a no-op.
1478 return NO_ERROR;
1479 }
1480
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001481 if (api == BufferQueueCore::CURRENTLY_CONNECTED_API) {
Chong Zhang5ac51482017-02-16 15:52:33 -08001482 if (mCore->mConnectedApi == NATIVE_WINDOW_API_MEDIA) {
1483 ALOGD("About to force-disconnect API_MEDIA, mode=%d", mode);
1484 }
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001485 api = mCore->mConnectedApi;
Chong Zhang26bb2b12016-03-08 12:08:33 -08001486 // If we're asked to disconnect the currently connected api but
1487 // nobody is connected, it's not really an error.
1488 if (api == BufferQueueCore::NO_CONNECTED_API) {
1489 return NO_ERROR;
1490 }
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001491 }
1492
Dan Stoza289ade12014-02-28 11:17:17 -08001493 switch (api) {
1494 case NATIVE_WINDOW_API_EGL:
1495 case NATIVE_WINDOW_API_CPU:
1496 case NATIVE_WINDOW_API_MEDIA:
1497 case NATIVE_WINDOW_API_CAMERA:
1498 if (mCore->mConnectedApi == api) {
1499 mCore->freeAllBuffersLocked();
1500
Chong Zhang62493092020-01-15 16:04:47 -08001501#ifndef NO_BINDER
Dan Stoza289ade12014-02-28 11:17:17 -08001502 // Remove our death notification callback if we have one
Yi Kong48a619f2018-06-05 16:34:59 -07001503 if (mCore->mLinkedToDeath != nullptr) {
Dan Stozaf0eaf252014-03-21 13:05:51 -07001504 sp<IBinder> token =
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001505 IInterface::asBinder(mCore->mLinkedToDeath);
Dan Stoza289ade12014-02-28 11:17:17 -08001506 // This can fail if we're here because of the death
1507 // notification, but we just ignore it
1508 token->unlinkToDeath(
1509 static_cast<IBinder::DeathRecipient*>(this));
1510 }
Chong Zhang62493092020-01-15 16:04:47 -08001511#endif
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001512 mCore->mSharedBufferSlot =
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001513 BufferQueueCore::INVALID_BUFFER_SLOT;
Yi Kong48a619f2018-06-05 16:34:59 -07001514 mCore->mLinkedToDeath = nullptr;
1515 mCore->mConnectedProducerListener = nullptr;
Dan Stoza289ade12014-02-28 11:17:17 -08001516 mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API;
Robert Carr97b9c862016-09-08 13:54:35 -07001517 mCore->mConnectedPid = -1;
Jesse Hall399184a2014-03-03 15:42:54 -08001518 mCore->mSidebandStream.clear();
Patrick Williams078d7362024-08-27 10:20:39 -05001519#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1520 mCore->notifyBufferReleased();
1521#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001522 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001523#endif
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001524 mCore->mAutoPrerotation = false;
John Reckdb164ff2024-04-03 16:59:28 -04001525#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1526 mCore->mAdditionalOptions.clear();
1527#endif
Dan Stoza289ade12014-02-28 11:17:17 -08001528 listener = mCore->mConsumerListener;
Wonsik Kim3e198b22017-04-07 15:43:16 -07001529 } else if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1530 BQ_LOGE("disconnect: not connected (req=%d)", api);
1531 status = NO_INIT;
1532 } else {
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001533 BQ_LOGE("disconnect: still connected to another API "
Dan Stoza289ade12014-02-28 11:17:17 -08001534 "(cur=%d req=%d)", mCore->mConnectedApi, api);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001535 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001536 }
1537 break;
1538 default:
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001539 BQ_LOGE("disconnect: unknown API %d", api);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001540 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001541 break;
1542 }
1543 } // Autolock scope
1544
1545 // Call back without lock held
Yi Kong48a619f2018-06-05 16:34:59 -07001546 if (listener != nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -08001547 listener->onBuffersReleased();
Brian Anderson5ea5e592016-12-01 16:54:33 -08001548 listener->onDisconnect();
Dan Stoza289ade12014-02-28 11:17:17 -08001549 }
1550
1551 return status;
1552}
1553
Jesse Hall399184a2014-03-03 15:42:54 -08001554status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
Wonsik Kimafe30812014-03-31 23:16:08 +09001555 sp<IConsumerListener> listener;
1556 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001557 std::lock_guard<std::mutex> _l(mCore->mMutex);
Wonsik Kimafe30812014-03-31 23:16:08 +09001558 mCore->mSidebandStream = stream;
1559 listener = mCore->mConsumerListener;
1560 } // Autolock scope
1561
Yi Kong48a619f2018-06-05 16:34:59 -07001562 if (listener != nullptr) {
Wonsik Kimafe30812014-03-31 23:16:08 +09001563 listener->onSidebandStreamChanged();
1564 }
Jesse Hall399184a2014-03-03 15:42:54 -08001565 return NO_ERROR;
1566}
1567
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001568void BufferQueueProducer::allocateBuffers(uint32_t width, uint32_t height,
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001569 PixelFormat format, uint64_t usage) {
Antoine Labour78014f32014-07-15 21:17:03 -07001570 ATRACE_CALL();
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001571
1572 const bool useDefaultSize = !width && !height;
Antoine Labour78014f32014-07-15 21:17:03 -07001573 while (true) {
Antoine Labour78014f32014-07-15 21:17:03 -07001574 uint32_t allocWidth = 0;
1575 uint32_t allocHeight = 0;
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001576 PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001577 uint64_t allocUsage = 0;
Chia-I Wu1dbf0e32018-02-07 14:40:08 -08001578 std::string allocName;
John Reckdb164ff2024-04-03 16:59:28 -04001579#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1580 std::vector<gui::AdditionalOptions> allocOptions;
1581 uint32_t allocOptionsGenId = 0;
1582#endif
Antoine Labour78014f32014-07-15 21:17:03 -07001583 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001584 std::unique_lock<std::mutex> lock(mCore->mMutex);
1585 mCore->waitWhileAllocatingLocked(lock);
Dan Stoza29a3e902014-06-20 13:13:57 -07001586
Dan Stoza9de72932015-04-16 17:28:43 -07001587 if (!mCore->mAllowAllocation) {
1588 BQ_LOGE("allocateBuffers: allocation is not allowed for this "
1589 "BufferQueue");
1590 return;
1591 }
1592
Jorim Jaggi0a3e7842018-07-17 13:48:33 +02001593 // Only allocate one buffer at a time to reduce risks of overlapping an allocation from
1594 // both allocateBuffers and dequeueBuffer.
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001595 if (mCore->mFreeSlots.empty()) {
1596 BQ_LOGV("allocateBuffers: a slot was occupied while "
1597 "allocating. Dropping allocated buffer.");
Antoine Labour78014f32014-07-15 21:17:03 -07001598 return;
1599 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001600
Antoine Labour78014f32014-07-15 21:17:03 -07001601 allocWidth = width > 0 ? width : mCore->mDefaultWidth;
1602 allocHeight = height > 0 ? height : mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001603 if (useDefaultSize && mCore->mAutoPrerotation &&
1604 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
1605 std::swap(allocWidth, allocHeight);
1606 }
1607
Antoine Labour78014f32014-07-15 21:17:03 -07001608 allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
1609 allocUsage = usage | mCore->mConsumerUsageBits;
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001610 allocName.assign(mCore->mConsumerName.c_str(), mCore->mConsumerName.size());
Antoine Labour78014f32014-07-15 21:17:03 -07001611
John Reckdb164ff2024-04-03 16:59:28 -04001612#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1613 allocOptions = mCore->mAdditionalOptions;
1614 allocOptionsGenId = mCore->mAdditionalOptionsGenerationId;
1615#endif
1616
Antoine Labour78014f32014-07-15 21:17:03 -07001617 mCore->mIsAllocating = true;
John Reckdb164ff2024-04-03 16:59:28 -04001618
Antoine Labour78014f32014-07-15 21:17:03 -07001619 } // Autolock scope
1620
John Reckdb164ff2024-04-03 16:59:28 -04001621#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1622 std::vector<GraphicBufferAllocator::AdditionalOptions> tempOptions;
1623 tempOptions.reserve(allocOptions.size());
1624 for (const auto& it : allocOptions) {
1625 tempOptions.emplace_back(it.name.c_str(), it.value);
1626 }
1627 const GraphicBufferAllocator::AllocationRequest allocRequest = {
1628 .importBuffer = true,
1629 .width = allocWidth,
1630 .height = allocHeight,
1631 .format = allocFormat,
1632 .layerCount = BQ_LAYER_COUNT,
1633 .usage = allocUsage,
1634 .requestorName = allocName,
1635 .extras = std::move(tempOptions),
1636 };
1637#endif
1638
John Reckdb164ff2024-04-03 16:59:28 -04001639#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001640 sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(allocRequest);
John Reckdb164ff2024-04-03 16:59:28 -04001641#else
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001642 sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(
1643 allocWidth, allocHeight, allocFormat, BQ_LAYER_COUNT,
1644 allocUsage, allocName);
John Reckdb164ff2024-04-03 16:59:28 -04001645#endif
Mathias Agopian0556d792017-03-22 15:49:32 -07001646
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001647 status_t result = graphicBuffer->initCheck();
Mathias Agopian0556d792017-03-22 15:49:32 -07001648
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001649 if (result != NO_ERROR) {
1650 BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format"
1651 " %u, usage %#" PRIx64 ")", width, height, format, usage);
1652 std::lock_guard<std::mutex> lock(mCore->mMutex);
1653 mCore->mIsAllocating = false;
1654 mCore->mIsAllocatingCondition.notify_all();
1655 return;
Antoine Labour78014f32014-07-15 21:17:03 -07001656 }
1657
1658 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001659 std::unique_lock<std::mutex> lock(mCore->mMutex);
Antoine Labour78014f32014-07-15 21:17:03 -07001660 uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
1661 uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001662 if (useDefaultSize && mCore->mAutoPrerotation &&
1663 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
1664 std::swap(checkWidth, checkHeight);
1665 }
1666
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001667 PixelFormat checkFormat = format != 0 ?
1668 format : mCore->mDefaultBufferFormat;
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001669 uint64_t checkUsage = usage | mCore->mConsumerUsageBits;
John Reckdb164ff2024-04-03 16:59:28 -04001670 bool allocOptionsChanged = false;
1671#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1672 allocOptionsChanged = allocOptionsGenId != mCore->mAdditionalOptionsGenerationId;
1673#endif
Antoine Labour78014f32014-07-15 21:17:03 -07001674 if (checkWidth != allocWidth || checkHeight != allocHeight ||
John Reckdb164ff2024-04-03 16:59:28 -04001675 checkFormat != allocFormat || checkUsage != allocUsage || allocOptionsChanged) {
Antoine Labour78014f32014-07-15 21:17:03 -07001676 // Something changed while we released the lock. Retry.
1677 BQ_LOGV("allocateBuffers: size/format/usage changed while allocating. Retrying.");
1678 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001679 mCore->mIsAllocatingCondition.notify_all();
Dan Stoza29a3e902014-06-20 13:13:57 -07001680 continue;
1681 }
1682
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001683 if (mCore->mFreeSlots.empty()) {
1684 BQ_LOGV("allocateBuffers: a slot was occupied while "
1685 "allocating. Dropping allocated buffer.");
1686 } else {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001687 auto slot = mCore->mFreeSlots.begin();
1688 mCore->clearBufferSlotLocked(*slot); // Clean up the slot first
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001689 mSlots[*slot].mGraphicBuffer = graphicBuffer;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001690 mSlots[*slot].mFence = Fence::NO_FENCE;
John Reckdb164ff2024-04-03 16:59:28 -04001691#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1692 mSlots[*slot].mAdditionalOptionsGenerationId = allocOptionsGenId;
1693#endif
Dan Stoza0de7ea72015-04-23 13:20:51 -07001694
1695 // freeBufferLocked puts this slot on the free slots list. Since
1696 // we then attached a buffer, move the slot to free buffer list.
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001697 mCore->mFreeBuffers.push_front(*slot);
Dan Stoza0de7ea72015-04-23 13:20:51 -07001698
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001699 BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d",
1700 *slot);
Christopher Ferris87e94cd2016-04-26 11:29:08 -07001701
1702 // Make sure the erase is done after all uses of the slot
1703 // iterator since it will be invalid after this point.
1704 mCore->mFreeSlots.erase(slot);
Antoine Labour78014f32014-07-15 21:17:03 -07001705 }
Dan Stoza29a3e902014-06-20 13:13:57 -07001706
Antoine Labour78014f32014-07-15 21:17:03 -07001707 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001708 mCore->mIsAllocatingCondition.notify_all();
Pablo Ceballos9e314332016-01-12 13:49:19 -08001709 VALIDATE_CONSISTENCY();
Jorim Jaggi35b4e382019-03-28 00:44:03 +01001710
1711 // If dequeue is waiting for to allocate a buffer, release the lock until it's not
1712 // waiting anymore so it can use the buffer we just allocated.
1713 while (mDequeueWaitingForAllocation) {
1714 mDequeueWaitingForAllocationCondition.wait(lock);
1715 }
Antoine Labour78014f32014-07-15 21:17:03 -07001716 } // Autolock scope
Dan Stoza29a3e902014-06-20 13:13:57 -07001717 }
1718}
1719
Dan Stoza9de72932015-04-16 17:28:43 -07001720status_t BufferQueueProducer::allowAllocation(bool allow) {
1721 ATRACE_CALL();
1722 BQ_LOGV("allowAllocation: %s", allow ? "true" : "false");
1723
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001724 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza9de72932015-04-16 17:28:43 -07001725 mCore->mAllowAllocation = allow;
1726 return NO_ERROR;
1727}
1728
Dan Stoza812ed062015-06-02 15:45:22 -07001729status_t BufferQueueProducer::setGenerationNumber(uint32_t generationNumber) {
1730 ATRACE_CALL();
1731 BQ_LOGV("setGenerationNumber: %u", generationNumber);
1732
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001733 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza812ed062015-06-02 15:45:22 -07001734 mCore->mGenerationNumber = generationNumber;
1735 return NO_ERROR;
1736}
1737
Dan Stozac6f30bd2015-06-08 09:32:50 -07001738String8 BufferQueueProducer::getConsumerName() const {
1739 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001740 std::lock_guard<std::mutex> lock(mCore->mMutex);
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001741 BQ_LOGV("getConsumerName: %s", mConsumerName.c_str());
Dan Stozac6f30bd2015-06-08 09:32:50 -07001742 return mConsumerName;
1743}
1744
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001745status_t BufferQueueProducer::setSharedBufferMode(bool sharedBufferMode) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001746 ATRACE_CALL();
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001747 BQ_LOGV("setSharedBufferMode: %d", sharedBufferMode);
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001748
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001749 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001750 if (!sharedBufferMode) {
1751 mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001752 }
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001753 mCore->mSharedBufferMode = sharedBufferMode;
Dan Stoza127fc632015-06-30 13:43:32 -07001754 return NO_ERROR;
1755}
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001756
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001757status_t BufferQueueProducer::setAutoRefresh(bool autoRefresh) {
1758 ATRACE_CALL();
1759 BQ_LOGV("setAutoRefresh: %d", autoRefresh);
1760
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001761 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001762
1763 mCore->mAutoRefresh = autoRefresh;
1764 return NO_ERROR;
1765}
1766
Dan Stoza127fc632015-06-30 13:43:32 -07001767status_t BufferQueueProducer::setDequeueTimeout(nsecs_t timeout) {
1768 ATRACE_CALL();
1769 BQ_LOGV("setDequeueTimeout: %" PRId64, timeout);
1770
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001771 std::lock_guard<std::mutex> lock(mCore->mMutex);
Sungtak Lee42a94c62019-05-24 14:27:14 -07001772 bool dequeueBufferCannotBlock =
1773 timeout >= 0 ? false : mCore->mDequeueBufferCannotBlock;
1774 int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode, dequeueBufferCannotBlock,
Pablo Ceballos981066c2016-02-18 12:54:37 -08001775 mCore->mMaxBufferCount) - mCore->getMaxBufferCountLocked();
1776 if (!mCore->adjustAvailableSlotsLocked(delta)) {
1777 BQ_LOGE("setDequeueTimeout: BufferQueue failed to adjust the number of "
1778 "available slots. Delta = %d", delta);
1779 return BAD_VALUE;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001780 }
1781
Pablo Ceballos981066c2016-02-18 12:54:37 -08001782 mDequeueTimeout = timeout;
Sungtak Lee42a94c62019-05-24 14:27:14 -07001783 mCore->mDequeueBufferCannotBlock = dequeueBufferCannotBlock;
1784 if (timeout > 0) {
1785 mCore->mQueueBufferCanDrop = false;
Sungtak Lee3249fb62019-03-02 16:40:47 -08001786 }
Pablo Ceballos9e314332016-01-12 13:49:19 -08001787
Pablo Ceballos981066c2016-02-18 12:54:37 -08001788 VALIDATE_CONSISTENCY();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001789 return NO_ERROR;
1790}
1791
Sungtak Lee3249fb62019-03-02 16:40:47 -08001792status_t BufferQueueProducer::setLegacyBufferDrop(bool drop) {
1793 ATRACE_CALL();
1794 BQ_LOGV("setLegacyBufferDrop: drop = %d", drop);
1795
1796 std::lock_guard<std::mutex> lock(mCore->mMutex);
1797 mCore->mLegacyBufferDrop = drop;
1798 return NO_ERROR;
1799}
1800
Dan Stoza50101d02016-04-07 16:53:23 -07001801status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
John Reck1a61da52016-04-28 13:18:15 -07001802 sp<Fence>* outFence, float outTransformMatrix[16]) {
Dan Stoza50101d02016-04-07 16:53:23 -07001803 ATRACE_CALL();
Dan Stoza50101d02016-04-07 16:53:23 -07001804
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001805 std::lock_guard<std::mutex> lock(mCore->mMutex);
John Reckd2c4a4a2024-02-07 10:31:09 -05001806 BQ_LOGV("getLastQueuedBuffer, slot=%d", mCore->mLastQueuedSlot);
1807
Dan Stoza50101d02016-04-07 16:53:23 -07001808 if (mCore->mLastQueuedSlot == BufferItem::INVALID_BUFFER_SLOT) {
1809 *outBuffer = nullptr;
1810 *outFence = Fence::NO_FENCE;
1811 return NO_ERROR;
1812 }
1813
1814 *outBuffer = mSlots[mCore->mLastQueuedSlot].mGraphicBuffer;
1815 *outFence = mLastQueueBufferFence;
1816
John Reck1a61da52016-04-28 13:18:15 -07001817 // Currently only SurfaceFlinger internally ever changes
1818 // GLConsumer's filtering mode, so we just use 'true' here as
1819 // this is slightly specialized for the current client of this API,
1820 // which does want filtering.
1821 GLConsumer::computeTransformMatrix(outTransformMatrix,
1822 mSlots[mCore->mLastQueuedSlot].mGraphicBuffer, mLastQueuedCrop,
1823 mLastQueuedTransform, true /* filter */);
1824
Dan Stoza50101d02016-04-07 16:53:23 -07001825 return NO_ERROR;
1826}
1827
John Reckf0f13e82021-05-18 00:42:56 -04001828status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer, sp<Fence>* outFence,
1829 Rect* outRect, uint32_t* outTransform) {
1830 ATRACE_CALL();
John Reckf0f13e82021-05-18 00:42:56 -04001831
1832 std::lock_guard<std::mutex> lock(mCore->mMutex);
John Reckd2c4a4a2024-02-07 10:31:09 -05001833 BQ_LOGV("getLastQueuedBuffer, slot=%d", mCore->mLastQueuedSlot);
1834 if (mCore->mLastQueuedSlot == BufferItem::INVALID_BUFFER_SLOT ||
1835 mSlots[mCore->mLastQueuedSlot].mBufferState.isDequeued()) {
John Reckf0f13e82021-05-18 00:42:56 -04001836 *outBuffer = nullptr;
1837 *outFence = Fence::NO_FENCE;
1838 return NO_ERROR;
1839 }
1840
1841 *outBuffer = mSlots[mCore->mLastQueuedSlot].mGraphicBuffer;
1842 *outFence = mLastQueueBufferFence;
1843 *outRect = mLastQueuedCrop;
1844 *outTransform = mLastQueuedTransform;
1845
1846 return NO_ERROR;
1847}
1848
Brian Anderson3890c392016-07-25 12:48:08 -07001849void BufferQueueProducer::getFrameTimestamps(FrameEventHistoryDelta* outDelta) {
1850 addAndGetFrameTimestamps(nullptr, outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07001851}
Pablo Ceballosce796e72016-02-04 19:10:51 -08001852
Brian Anderson3890c392016-07-25 12:48:08 -07001853void BufferQueueProducer::addAndGetFrameTimestamps(
Brian Andersond6927fb2016-07-23 23:37:30 -07001854 const NewFrameEventsEntry* newTimestamps,
Brian Anderson3890c392016-07-25 12:48:08 -07001855 FrameEventHistoryDelta* outDelta) {
1856 if (newTimestamps == nullptr && outDelta == nullptr) {
1857 return;
Brian Andersond6927fb2016-07-23 23:37:30 -07001858 }
1859
1860 ATRACE_CALL();
1861 BQ_LOGV("addAndGetFrameTimestamps");
1862 sp<IConsumerListener> listener;
Pablo Ceballosce796e72016-02-04 19:10:51 -08001863 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001864 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballosce796e72016-02-04 19:10:51 -08001865 listener = mCore->mConsumerListener;
1866 }
Yi Kong48a619f2018-06-05 16:34:59 -07001867 if (listener != nullptr) {
Brian Anderson3890c392016-07-25 12:48:08 -07001868 listener->addAndGetFrameTimestamps(newTimestamps, outDelta);
Pablo Ceballosce796e72016-02-04 19:10:51 -08001869 }
Pablo Ceballosce796e72016-02-04 19:10:51 -08001870}
1871
Dan Stoza289ade12014-02-28 11:17:17 -08001872void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
1873 // If we're here, it means that a producer we were connected to died.
1874 // We're guaranteed that we are still connected to it because we remove
1875 // this callback upon disconnect. It's therefore safe to read mConnectedApi
1876 // without synchronization here.
1877 int api = mCore->mConnectedApi;
1878 disconnect(api);
1879}
1880
Pablo Ceballos8e3e92b2016-06-27 17:56:53 -07001881status_t BufferQueueProducer::getUniqueId(uint64_t* outId) const {
1882 BQ_LOGV("getUniqueId");
1883
1884 *outId = mCore->mUniqueId;
1885 return NO_ERROR;
1886}
1887
Chia-I Wue2786ea2017-08-07 10:36:08 -07001888status_t BufferQueueProducer::getConsumerUsage(uint64_t* outUsage) const {
1889 BQ_LOGV("getConsumerUsage");
1890
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001891 std::lock_guard<std::mutex> lock(mCore->mMutex);
Chia-I Wue2786ea2017-08-07 10:36:08 -07001892 *outUsage = mCore->mConsumerUsageBits;
1893 return NO_ERROR;
1894}
1895
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001896status_t BufferQueueProducer::setAutoPrerotation(bool autoPrerotation) {
1897 ATRACE_CALL();
1898 BQ_LOGV("setAutoPrerotation: %d", autoPrerotation);
1899
1900 std::lock_guard<std::mutex> lock(mCore->mMutex);
1901
1902 mCore->mAutoPrerotation = autoPrerotation;
1903 return NO_ERROR;
1904}
1905
Ady Abraham107788e2023-10-17 12:31:08 -07001906#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
Ady Abraham6cdd3fd2023-09-07 18:45:58 -07001907status_t BufferQueueProducer::setFrameRate(float frameRate, int8_t compatibility,
1908 int8_t changeFrameRateStrategy) {
1909 ATRACE_CALL();
1910 BQ_LOGV("setFrameRate: %.2f", frameRate);
1911
1912 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
1913 "BufferQueueProducer::setFrameRate")) {
1914 return BAD_VALUE;
1915 }
1916
1917 sp<IConsumerListener> listener;
1918 {
1919 std::lock_guard<std::mutex> lock(mCore->mMutex);
1920 listener = mCore->mConsumerListener;
1921 }
1922 if (listener != nullptr) {
1923 listener->onSetFrameRate(frameRate, compatibility, changeFrameRateStrategy);
1924 }
1925 return NO_ERROR;
1926}
1927#endif
1928
John Reckdb164ff2024-04-03 16:59:28 -04001929#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1930status_t BufferQueueProducer::setAdditionalOptions(
1931 const std::vector<gui::AdditionalOptions>& options) {
1932 ATRACE_CALL();
1933 BQ_LOGV("setAdditionalOptions, size = %zu", options.size());
1934
1935 if (!GraphicBufferAllocator::get().supportsAdditionalOptions()) {
1936 return INVALID_OPERATION;
1937 }
1938
1939 std::lock_guard<std::mutex> lock(mCore->mMutex);
1940
1941 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1942 BQ_LOGE("setAdditionalOptions: BufferQueue not connected, cannot set additional options");
1943 return NO_INIT;
1944 }
1945
1946 if (mCore->mAdditionalOptions != options) {
1947 mCore->mAdditionalOptions = options;
1948 mCore->mAdditionalOptionsGenerationId++;
1949 }
1950 return NO_ERROR;
1951}
1952#endif
1953
Dan Stoza289ade12014-02-28 11:17:17 -08001954} // namespace android