blob: 5961b41478eb85b6658925720099bcc746974aeb [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
Jim Shargo2e614a42024-10-02 19:31:53 +000043#include <utils/Errors.h>
Dan Stoza289ade12014-02-28 11:17:17 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46
Mathias Agopian6a3c05b2017-04-27 20:06:55 -070047#include <system/window.h>
48
Mathias Agopianb96661f2024-09-17 11:45:38 -070049#include <com_android_graphics_libgui_flags.h>
50
Dan Stoza289ade12014-02-28 11:17:17 -080051namespace android {
Mathias Agopianb96661f2024-09-17 11:45:38 -070052using namespace com::android::graphics::libgui;
Dan Stoza289ade12014-02-28 11:17:17 -080053
Iris Chang430193f2019-12-04 16:25:46 +080054// Macros for include BufferQueueCore information in log messages
55#define BQ_LOGV(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000056 ALOGV("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080057 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
58 ##__VA_ARGS__)
59#define BQ_LOGD(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000060 ALOGD("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080061 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
62 ##__VA_ARGS__)
63#define BQ_LOGI(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000064 ALOGI("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080065 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
66 ##__VA_ARGS__)
67#define BQ_LOGW(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000068 ALOGW("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080069 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
70 ##__VA_ARGS__)
71#define BQ_LOGE(x, ...) \
Tomasz Wasilczykf2add402023-08-11 00:06:51 +000072 ALOGE("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.c_str(), \
Iris Chang430193f2019-12-04 16:25:46 +080073 mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
74 ##__VA_ARGS__)
75
Craig Donner6ebc46a2016-10-21 15:23:44 -070076static constexpr uint32_t BQ_LAYER_COUNT = 1;
Chong Zhang62493092020-01-15 16:04:47 -080077ProducerListener::~ProducerListener() = default;
Craig Donner6ebc46a2016-10-21 15:23:44 -070078
Irvel468051e2016-06-13 16:44:44 -070079BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core,
80 bool consumerIsSurfaceFlinger) :
Dan Stoza289ade12014-02-28 11:17:17 -080081 mCore(core),
82 mSlots(core->mSlots),
Ruben Brunk1681d952014-06-27 15:51:55 -070083 mConsumerName(),
Eric Penner99a0afb2014-09-30 11:28:30 -070084 mStickyTransform(0),
Irvel468051e2016-06-13 16:44:44 -070085 mConsumerIsSurfaceFlinger(consumerIsSurfaceFlinger),
Dan Stoza8dc55392014-11-04 11:37:46 -080086 mLastQueueBufferFence(Fence::NO_FENCE),
Pablo Ceballosbd3577e2016-06-20 17:40:34 -070087 mLastQueuedTransform(0),
Dan Stoza8dc55392014-11-04 11:37:46 -080088 mCallbackMutex(),
89 mNextCallbackTicket(0),
90 mCurrentCallbackTicket(0),
Dan Stoza127fc632015-06-30 13:43:32 -070091 mCallbackCondition(),
Jorim Jaggi35b4e382019-03-28 00:44:03 +010092 mDequeueTimeout(-1),
93 mDequeueWaitingForAllocation(false) {}
Dan Stoza289ade12014-02-28 11:17:17 -080094
95BufferQueueProducer::~BufferQueueProducer() {}
96
97status_t BufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
98 ATRACE_CALL();
99 BQ_LOGV("requestBuffer: slot %d", slot);
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200100 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800101
102 if (mCore->mIsAbandoned) {
103 BQ_LOGE("requestBuffer: BufferQueue has been abandoned");
104 return NO_INIT;
105 }
106
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700107 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
108 BQ_LOGE("requestBuffer: BufferQueue has no connected producer");
109 return NO_INIT;
110 }
111
Jim Shargo2e614a42024-10-02 19:31:53 +0000112 int maxSlot = mCore->getTotalSlotCountLocked();
113 if (slot < 0 || slot >= maxSlot) {
114 BQ_LOGE("requestBuffer: slot index %d out of range [0, %d)", slot, maxSlot);
Dan Stoza289ade12014-02-28 11:17:17 -0800115 return BAD_VALUE;
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700116 } else if (!mSlots[slot].mBufferState.isDequeued()) {
Dan Stoza289ade12014-02-28 11:17:17 -0800117 BQ_LOGE("requestBuffer: slot %d is not owned by the producer "
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700118 "(state = %s)", slot, mSlots[slot].mBufferState.string());
Dan Stoza289ade12014-02-28 11:17:17 -0800119 return BAD_VALUE;
120 }
121
122 mSlots[slot].mRequestBufferCalled = true;
123 *buf = mSlots[slot].mGraphicBuffer;
124 return NO_ERROR;
125}
126
Jim Shargo2e614a42024-10-02 19:31:53 +0000127#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_UNLIMITED_SLOTS)
128status_t BufferQueueProducer::extendSlotCount(int size) {
129 ATRACE_CALL();
130
131 sp<IConsumerListener> listener;
132 {
133 std::lock_guard<std::mutex> lock(mCore->mMutex);
134 BQ_LOGV("extendSlotCount: size %d", size);
135
136 if (mCore->mIsAbandoned) {
137 BQ_LOGE("extendSlotCount: BufferQueue has been abandoned");
138 return NO_INIT;
139 }
140
141 if (!mCore->mAllowExtendedSlotCount) {
142 BQ_LOGE("extendSlotCount: Consumer did not allow unlimited slots");
143 return INVALID_OPERATION;
144 }
145
146 int maxBeforeExtension = mCore->mMaxBufferCount;
147
148 if (size == maxBeforeExtension) {
149 return NO_ERROR;
150 }
151
152 if (size < maxBeforeExtension) {
153 return BAD_VALUE;
154 }
155
156 if (status_t ret = mCore->extendSlotCountLocked(size); ret != OK) {
157 return ret;
158 }
159 listener = mCore->mConsumerListener;
160 }
161
162 if (listener) {
163 listener->onSlotCountChanged(size);
164 }
165
166 return NO_ERROR;
167}
168#endif
169
Pablo Ceballosfa455352015-08-12 17:47:47 -0700170status_t BufferQueueProducer::setMaxDequeuedBufferCount(
171 int maxDequeuedBuffers) {
Brian Lindahlc794b692023-01-31 15:42:47 -0700172 int maxBufferCount;
173 return setMaxDequeuedBufferCount(maxDequeuedBuffers, &maxBufferCount);
174}
175
176status_t BufferQueueProducer::setMaxDequeuedBufferCount(int maxDequeuedBuffers,
177 int* maxBufferCount) {
Vishnu Nair14a3c112023-04-21 14:49:47 -0700178 ATRACE_FORMAT("%s(%d)", __func__, maxDequeuedBuffers);
Pablo Ceballosfa455352015-08-12 17:47:47 -0700179 BQ_LOGV("setMaxDequeuedBufferCount: maxDequeuedBuffers = %d",
180 maxDequeuedBuffers);
181
Pablo Ceballos981066c2016-02-18 12:54:37 -0800182 sp<IConsumerListener> listener;
Pablo Ceballosfa455352015-08-12 17:47:47 -0700183 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200184 std::unique_lock<std::mutex> lock(mCore->mMutex);
185 mCore->waitWhileAllocatingLocked(lock);
Pablo Ceballosfa455352015-08-12 17:47:47 -0700186
187 if (mCore->mIsAbandoned) {
188 BQ_LOGE("setMaxDequeuedBufferCount: BufferQueue has been "
189 "abandoned");
190 return NO_INIT;
191 }
192
Brian Lindahlc794b692023-01-31 15:42:47 -0700193 *maxBufferCount = mCore->getMaxBufferCountLocked();
194
Pablo Ceballos245cc5b2016-04-19 11:33:00 -0700195 if (maxDequeuedBuffers == mCore->mMaxDequeuedBufferCount) {
196 return NO_ERROR;
197 }
198
Pablo Ceballos72daab62015-12-07 16:38:43 -0800199 // The new maxDequeuedBuffer count should not be violated by the number
200 // of currently dequeued buffers
201 int dequeuedCount = 0;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800202 for (int s : mCore->mActiveBuffers) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700203 if (mSlots[s].mBufferState.isDequeued()) {
Pablo Ceballos72daab62015-12-07 16:38:43 -0800204 dequeuedCount++;
Pablo Ceballosfa455352015-08-12 17:47:47 -0700205 }
206 }
Pablo Ceballos72daab62015-12-07 16:38:43 -0800207 if (dequeuedCount > maxDequeuedBuffers) {
208 BQ_LOGE("setMaxDequeuedBufferCount: the requested maxDequeuedBuffer"
209 "count (%d) exceeds the current dequeued buffer count (%d)",
210 maxDequeuedBuffers, dequeuedCount);
211 return BAD_VALUE;
212 }
Pablo Ceballosfa455352015-08-12 17:47:47 -0700213
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700214 int bufferCount = mCore->getMinUndequeuedBufferCountLocked();
Pablo Ceballosfa455352015-08-12 17:47:47 -0700215 bufferCount += maxDequeuedBuffers;
216
Jim Shargo2e614a42024-10-02 19:31:53 +0000217 if (bufferCount > mCore->getTotalSlotCountLocked()) {
Pablo Ceballosfa455352015-08-12 17:47:47 -0700218 BQ_LOGE("setMaxDequeuedBufferCount: bufferCount %d too large "
Jim Shargo2e614a42024-10-02 19:31:53 +0000219 "(max %d)",
220 bufferCount, mCore->getTotalSlotCountLocked());
Pablo Ceballosfa455352015-08-12 17:47:47 -0700221 return BAD_VALUE;
222 }
223
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700224 const int minBufferSlots = mCore->getMinMaxBufferCountLocked();
Pablo Ceballosfa455352015-08-12 17:47:47 -0700225 if (bufferCount < minBufferSlots) {
226 BQ_LOGE("setMaxDequeuedBufferCount: requested buffer count %d is "
227 "less than minimum %d", bufferCount, minBufferSlots);
228 return BAD_VALUE;
229 }
230
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700231 if (bufferCount > mCore->mMaxBufferCount) {
232 BQ_LOGE("setMaxDequeuedBufferCount: %d dequeued buffers would "
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700233 "exceed the maxBufferCount (%d) (maxAcquired %d async %d "
234 "mDequeuedBufferCannotBlock %d)", maxDequeuedBuffers,
235 mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
236 mCore->mAsyncMode, mCore->mDequeueBufferCannotBlock);
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700237 return BAD_VALUE;
238 }
239
Pablo Ceballos72daab62015-12-07 16:38:43 -0800240 int delta = maxDequeuedBuffers - mCore->mMaxDequeuedBufferCount;
Pablo Ceballos981066c2016-02-18 12:54:37 -0800241 if (!mCore->adjustAvailableSlotsLocked(delta)) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800242 return BAD_VALUE;
243 }
Pablo Ceballosfa455352015-08-12 17:47:47 -0700244 mCore->mMaxDequeuedBufferCount = maxDequeuedBuffers;
Brian Lindahlc794b692023-01-31 15:42:47 -0700245 *maxBufferCount = mCore->getMaxBufferCountLocked();
Pablo Ceballos9e314332016-01-12 13:49:19 -0800246 VALIDATE_CONSISTENCY();
Pablo Ceballos72daab62015-12-07 16:38:43 -0800247 if (delta < 0) {
Pablo Ceballos981066c2016-02-18 12:54:37 -0800248 listener = mCore->mConsumerListener;
Pablo Ceballos72daab62015-12-07 16:38:43 -0800249 }
Patrick Williams078d7362024-08-27 10:20:39 -0500250#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
251 mCore->notifyBufferReleased();
252#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200253 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -0500254#endif
Pablo Ceballosfa455352015-08-12 17:47:47 -0700255 } // Autolock scope
256
257 // Call back without lock held
Yi Kong48a619f2018-06-05 16:34:59 -0700258 if (listener != nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -0800259 listener->onBuffersReleased();
Pablo Ceballosfa455352015-08-12 17:47:47 -0700260 }
261
262 return NO_ERROR;
263}
264
265status_t BufferQueueProducer::setAsyncMode(bool async) {
266 ATRACE_CALL();
267 BQ_LOGV("setAsyncMode: async = %d", async);
268
Pablo Ceballos981066c2016-02-18 12:54:37 -0800269 sp<IConsumerListener> listener;
Pablo Ceballosfa455352015-08-12 17:47:47 -0700270 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200271 std::unique_lock<std::mutex> lock(mCore->mMutex);
272 mCore->waitWhileAllocatingLocked(lock);
Pablo Ceballosfa455352015-08-12 17:47:47 -0700273
274 if (mCore->mIsAbandoned) {
275 BQ_LOGE("setAsyncMode: BufferQueue has been abandoned");
276 return NO_INIT;
277 }
278
Pablo Ceballos245cc5b2016-04-19 11:33:00 -0700279 if (async == mCore->mAsyncMode) {
280 return NO_ERROR;
281 }
282
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700283 if ((mCore->mMaxAcquiredBufferCount + mCore->mMaxDequeuedBufferCount +
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700284 (async || mCore->mDequeueBufferCannotBlock ? 1 : 0)) >
285 mCore->mMaxBufferCount) {
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700286 BQ_LOGE("setAsyncMode(%d): this call would cause the "
287 "maxBufferCount (%d) to be exceeded (maxAcquired %d "
Pablo Ceballos567dbbb2015-08-26 18:59:08 -0700288 "maxDequeued %d mDequeueBufferCannotBlock %d)", async,
289 mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
290 mCore->mMaxDequeuedBufferCount,
291 mCore->mDequeueBufferCannotBlock);
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700292 return BAD_VALUE;
293 }
294
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800295 int delta = mCore->getMaxBufferCountLocked(async,
296 mCore->mDequeueBufferCannotBlock, mCore->mMaxBufferCount)
297 - mCore->getMaxBufferCountLocked();
298
Pablo Ceballos981066c2016-02-18 12:54:37 -0800299 if (!mCore->adjustAvailableSlotsLocked(delta)) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800300 BQ_LOGE("setAsyncMode: BufferQueue failed to adjust the number of "
301 "available slots. Delta = %d", delta);
302 return BAD_VALUE;
303 }
Pablo Ceballosfa455352015-08-12 17:47:47 -0700304 mCore->mAsyncMode = async;
Pablo Ceballos9e314332016-01-12 13:49:19 -0800305 VALIDATE_CONSISTENCY();
Patrick Williams078d7362024-08-27 10:20:39 -0500306#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
307 mCore->notifyBufferReleased();
308#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200309 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -0500310#endif
311
Pablo Ceballos245cc5b2016-04-19 11:33:00 -0700312 if (delta < 0) {
313 listener = mCore->mConsumerListener;
314 }
Pablo Ceballosfa455352015-08-12 17:47:47 -0700315 } // Autolock scope
316
317 // Call back without lock held
Yi Kong48a619f2018-06-05 16:34:59 -0700318 if (listener != nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -0800319 listener->onBuffersReleased();
Pablo Ceballosfa455352015-08-12 17:47:47 -0700320 }
321 return NO_ERROR;
322}
323
Dan Stoza5ecfb682016-01-04 17:01:02 -0800324int BufferQueueProducer::getFreeBufferLocked() const {
325 if (mCore->mFreeBuffers.empty()) {
326 return BufferQueueCore::INVALID_BUFFER_SLOT;
327 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800328 int slot = mCore->mFreeBuffers.front();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800329 mCore->mFreeBuffers.pop_front();
330 return slot;
331}
332
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800333int BufferQueueProducer::getFreeSlotLocked() const {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800334 if (mCore->mFreeSlots.empty()) {
335 return BufferQueueCore::INVALID_BUFFER_SLOT;
336 }
Pablo Ceballosdce5c552016-02-10 15:43:22 -0800337 int slot = *(mCore->mFreeSlots.begin());
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800338 mCore->mFreeSlots.erase(slot);
Pablo Ceballosdce5c552016-02-10 15:43:22 -0800339 return slot;
Dan Stoza5ecfb682016-01-04 17:01:02 -0800340}
341
342status_t BufferQueueProducer::waitForFreeSlotThenRelock(FreeSlotCaller caller,
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200343 std::unique_lock<std::mutex>& lock, int* found) const {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800344 auto callerString = (caller == FreeSlotCaller::Dequeue) ?
345 "dequeueBuffer" : "attachBuffer";
Dan Stoza9f3053d2014-03-06 15:14:33 -0800346 bool tryAgain = true;
347 while (tryAgain) {
348 if (mCore->mIsAbandoned) {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800349 BQ_LOGE("%s: BufferQueue has been abandoned", callerString);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800350 return NO_INIT;
351 }
352
Dan Stoza9f3053d2014-03-06 15:14:33 -0800353 int dequeuedCount = 0;
354 int acquiredCount = 0;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800355 for (int s : mCore->mActiveBuffers) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700356 if (mSlots[s].mBufferState.isDequeued()) {
357 ++dequeuedCount;
358 }
359 if (mSlots[s].mBufferState.isAcquired()) {
360 ++acquiredCount;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800361 }
362 }
363
Pablo Ceballose5b755a2015-08-13 16:18:19 -0700364 // Producers are not allowed to dequeue more than
365 // mMaxDequeuedBufferCount buffers.
366 // This check is only done if a buffer has already been queued
367 if (mCore->mBufferHasBeenQueued &&
368 dequeuedCount >= mCore->mMaxDequeuedBufferCount) {
Sungtak Leeaf141242019-04-24 16:36:44 -0700369 // Supress error logs when timeout is non-negative.
370 if (mDequeueTimeout < 0) {
371 BQ_LOGE("%s: attempting to exceed the max dequeued buffer "
372 "count (%d)", callerString,
373 mCore->mMaxDequeuedBufferCount);
374 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800375 return INVALID_OPERATION;
376 }
377
Dan Stoza0de7ea72015-04-23 13:20:51 -0700378 *found = BufferQueueCore::INVALID_BUFFER_SLOT;
379
Dan Stozaae3c3682014-04-18 15:43:35 -0700380 // If we disconnect and reconnect quickly, we can be in a state where
381 // our slots are empty but we have many buffers in the queue. This can
382 // cause us to run out of memory if we outrun the consumer. Wait here if
383 // it looks like we have too many buffers queued up.
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800384 const int maxBufferCount = mCore->getMaxBufferCountLocked();
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700385 bool tooManyBuffers = mCore->mQueue.size()
386 > static_cast<size_t>(maxBufferCount);
Dan Stozaae3c3682014-04-18 15:43:35 -0700387 if (tooManyBuffers) {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800388 BQ_LOGV("%s: queue size is %zu, waiting", callerString,
Dan Stozaae3c3682014-04-18 15:43:35 -0700389 mCore->mQueue.size());
Dan Stoza0de7ea72015-04-23 13:20:51 -0700390 } else {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700391 // If in shared buffer mode and a shared buffer exists, always
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700392 // return it.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700393 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot !=
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700394 BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700395 *found = mCore->mSharedBufferSlot;
Dan Stoza5ecfb682016-01-04 17:01:02 -0800396 } else {
397 if (caller == FreeSlotCaller::Dequeue) {
398 // If we're calling this from dequeue, prefer free buffers
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800399 int slot = getFreeBufferLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800400 if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
401 *found = slot;
402 } else if (mCore->mAllowAllocation) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800403 *found = getFreeSlotLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800404 }
405 } else {
406 // If we're calling this from attach, prefer free slots
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800407 int slot = getFreeSlotLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800408 if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
409 *found = slot;
410 } else {
411 *found = getFreeBufferLocked();
412 }
Dan Stoza0de7ea72015-04-23 13:20:51 -0700413 }
414 }
Dan Stozaae3c3682014-04-18 15:43:35 -0700415 }
416
417 // If no buffer is found, or if the queue has too many buffers
418 // outstanding, wait for a buffer to be acquired or released, or for the
419 // max buffer count to change.
420 tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
421 tooManyBuffers;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800422 if (tryAgain) {
423 // Return an error if we're in non-blocking mode (producer and
424 // consumer are controlled by the application).
425 // However, the consumer is allowed to briefly acquire an extra
426 // buffer (which could cause us to have to wait here), which is
427 // okay, since it is only used to implement an atomic acquire +
428 // release (e.g., in GLConsumer::updateTexImage())
Pablo Ceballosfa455352015-08-12 17:47:47 -0700429 if ((mCore->mDequeueBufferCannotBlock || mCore->mAsyncMode) &&
Dan Stoza9f3053d2014-03-06 15:14:33 -0800430 (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
431 return WOULD_BLOCK;
432 }
Patrick Williams078d7362024-08-27 10:20:39 -0500433#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
434 if (status_t status = waitForBufferRelease(lock, mDequeueTimeout);
435 status == TIMED_OUT) {
436 return TIMED_OUT;
437 }
438#else
Dan Stoza127fc632015-06-30 13:43:32 -0700439 if (mDequeueTimeout >= 0) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200440 std::cv_status result = mCore->mDequeueCondition.wait_for(lock,
441 std::chrono::nanoseconds(mDequeueTimeout));
442 if (result == std::cv_status::timeout) {
443 return TIMED_OUT;
Dan Stoza127fc632015-06-30 13:43:32 -0700444 }
445 } else {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200446 mCore->mDequeueCondition.wait(lock);
Dan Stoza127fc632015-06-30 13:43:32 -0700447 }
Patrick Williams078d7362024-08-27 10:20:39 -0500448#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800449 }
450 } // while (tryAgain)
451
452 return NO_ERROR;
453}
454
Patrick Williams078d7362024-08-27 10:20:39 -0500455#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
456status_t BufferQueueProducer::waitForBufferRelease(std::unique_lock<std::mutex>& lock,
457 nsecs_t timeout) const {
458 if (mDequeueTimeout >= 0) {
459 std::cv_status result =
460 mCore->mDequeueCondition.wait_for(lock, std::chrono::nanoseconds(timeout));
461 if (result == std::cv_status::timeout) {
462 return TIMED_OUT;
463 }
464 } else {
465 mCore->mDequeueCondition.wait(lock);
466 }
467 return OK;
468}
469#endif
470
Ian Elliottd11b0442017-07-18 11:05:49 -0600471status_t BufferQueueProducer::dequeueBuffer(int* outSlot, sp<android::Fence>* outFence,
472 uint32_t width, uint32_t height, PixelFormat format,
473 uint64_t usage, uint64_t* outBufferAge,
474 FrameEventHistoryDelta* outTimestamps) {
Dan Stoza289ade12014-02-28 11:17:17 -0800475 ATRACE_CALL();
476 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200477 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800478 mConsumerName = mCore->mConsumerName;
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700479
480 if (mCore->mIsAbandoned) {
481 BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
482 return NO_INIT;
483 }
484
485 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
486 BQ_LOGE("dequeueBuffer: BufferQueue has no connected producer");
487 return NO_INIT;
488 }
Dan Stoza289ade12014-02-28 11:17:17 -0800489 } // Autolock scope
490
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700491 BQ_LOGV("dequeueBuffer: w=%u h=%u format=%#x, usage=%#" PRIx64, width, height, format, usage);
Dan Stoza289ade12014-02-28 11:17:17 -0800492
493 if ((width && !height) || (!width && height)) {
494 BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
495 return BAD_VALUE;
496 }
497
498 status_t returnFlags = NO_ERROR;
Jim Shargo90842182024-11-14 00:49:27 +0000499#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800500 EGLDisplay eglDisplay = EGL_NO_DISPLAY;
501 EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000502#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800503 bool attachedByConsumer = false;
Dan Stoza289ade12014-02-28 11:17:17 -0800504
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000505 sp<IConsumerListener> listener;
506 bool callOnFrameDequeued = false;
507 uint64_t bufferId = 0; // Only used if callOnFrameDequeued == true
John Reckdb164ff2024-04-03 16:59:28 -0400508#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
509 std::vector<gui::AdditionalOptions> allocOptions;
510 uint32_t allocOptionsGenId = 0;
511#endif
512
Dan Stoza289ade12014-02-28 11:17:17 -0800513 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200514 std::unique_lock<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800515
Jorim Jaggi35b4e382019-03-28 00:44:03 +0100516 // If we don't have a free buffer, but we are currently allocating, we wait until allocation
517 // is finished such that we don't allocate in parallel.
518 if (mCore->mFreeBuffers.empty() && mCore->mIsAllocating) {
519 mDequeueWaitingForAllocation = true;
520 mCore->waitWhileAllocatingLocked(lock);
521 mDequeueWaitingForAllocation = false;
522 mDequeueWaitingForAllocationCondition.notify_all();
523 }
Dan Stoza289ade12014-02-28 11:17:17 -0800524
525 if (format == 0) {
526 format = mCore->mDefaultBufferFormat;
527 }
528
529 // Enable the usage bits the consumer requested
530 usage |= mCore->mConsumerUsageBits;
531
Dan Stoza9de72932015-04-16 17:28:43 -0700532 const bool useDefaultSize = !width && !height;
533 if (useDefaultSize) {
534 width = mCore->mDefaultWidth;
535 height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -0700536 if (mCore->mAutoPrerotation &&
537 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
538 std::swap(width, height);
539 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800540 }
Dan Stoza289ade12014-02-28 11:17:17 -0800541
Pablo Ceballos981066c2016-02-18 12:54:37 -0800542 int found = BufferItem::INVALID_BUFFER_SLOT;
Dan Stoza9de72932015-04-16 17:28:43 -0700543 while (found == BufferItem::INVALID_BUFFER_SLOT) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200544 status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Dequeue, lock, &found);
Dan Stoza9de72932015-04-16 17:28:43 -0700545 if (status != NO_ERROR) {
546 return status;
547 }
548
549 // This should not happen
550 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
551 BQ_LOGE("dequeueBuffer: no available buffer slots");
552 return -EBUSY;
553 }
554
555 const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
556
557 // If we are not allowed to allocate new buffers,
558 // waitForFreeSlotThenRelock must have returned a slot containing a
559 // buffer. If this buffer would require reallocation to meet the
560 // requested attributes, we free it and attempt to get another one.
561 if (!mCore->mAllowAllocation) {
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700562 if (buffer->needsReallocation(width, height, format, BQ_LAYER_COUNT, usage)) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700563 if (mCore->mSharedBufferSlot == found) {
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700564 BQ_LOGE("dequeueBuffer: cannot re-allocate a sharedbuffer");
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700565 return BAD_VALUE;
566 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800567 mCore->mFreeSlots.insert(found);
568 mCore->clearBufferSlotLocked(found);
Dan Stoza9de72932015-04-16 17:28:43 -0700569 found = BufferItem::INVALID_BUFFER_SLOT;
570 continue;
571 }
572 }
Dan Stoza289ade12014-02-28 11:17:17 -0800573 }
574
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800575 const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800576
John Reckdb164ff2024-04-03 16:59:28 -0400577 bool needsReallocation = buffer == nullptr ||
578 buffer->needsReallocation(width, height, format, BQ_LAYER_COUNT, usage);
579
580#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
581 needsReallocation |= mSlots[found].mAdditionalOptionsGenerationId !=
582 mCore->mAdditionalOptionsGenerationId;
583#endif
584
585 if (mCore->mSharedBufferSlot == found && needsReallocation) {
586 BQ_LOGE("dequeueBuffer: cannot re-allocate a shared buffer");
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800587 return BAD_VALUE;
588 }
589
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700590 if (mCore->mSharedBufferSlot != found) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800591 mCore->mActiveBuffers.insert(found);
592 }
Dan Stoza289ade12014-02-28 11:17:17 -0800593 *outSlot = found;
594 ATRACE_BUFFER_INDEX(found);
595
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800596 attachedByConsumer = mSlots[found].mNeedsReallocation;
597 mSlots[found].mNeedsReallocation = false;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800598
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700599 mSlots[found].mBufferState.dequeue();
600
John Reckdb164ff2024-04-03 16:59:28 -0400601 if (needsReallocation) {
Vishnu Nair14a3c112023-04-21 14:49:47 -0700602 if (CC_UNLIKELY(ATRACE_ENABLED())) {
603 if (buffer == nullptr) {
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +0000604 ATRACE_FORMAT_INSTANT("%s buffer reallocation: null", mConsumerName.c_str());
Vishnu Nair14a3c112023-04-21 14:49:47 -0700605 } else {
606 ATRACE_FORMAT_INSTANT("%s buffer reallocation actual %dx%d format:%d "
607 "layerCount:%d "
608 "usage:%d requested: %dx%d format:%d layerCount:%d "
609 "usage:%d ",
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +0000610 mConsumerName.c_str(), width, height, format,
Vishnu Nair14a3c112023-04-21 14:49:47 -0700611 BQ_LAYER_COUNT, usage, buffer->getWidth(),
612 buffer->getHeight(), buffer->getPixelFormat(),
613 buffer->getLayerCount(), buffer->getUsage());
614 }
615 }
Dan Stoza289ade12014-02-28 11:17:17 -0800616 mSlots[found].mAcquireCalled = false;
Yi Kong48a619f2018-06-05 16:34:59 -0700617 mSlots[found].mGraphicBuffer = nullptr;
Dan Stoza289ade12014-02-28 11:17:17 -0800618 mSlots[found].mRequestBufferCalled = false;
Jim Shargo90842182024-11-14 00:49:27 +0000619#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800620 mSlots[found].mEglDisplay = EGL_NO_DISPLAY;
621 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000622#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800623 mSlots[found].mFence = Fence::NO_FENCE;
Dan Stoza4afd8b62015-02-25 16:49:08 -0800624 mCore->mBufferAge = 0;
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700625 mCore->mIsAllocating = true;
John Reckdb164ff2024-04-03 16:59:28 -0400626#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
627 allocOptions = mCore->mAdditionalOptions;
628 allocOptionsGenId = mCore->mAdditionalOptionsGenerationId;
629#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800630
631 returnFlags |= BUFFER_NEEDS_REALLOCATION;
Dan Stoza4afd8b62015-02-25 16:49:08 -0800632 } else {
633 // We add 1 because that will be the frame number when this buffer
634 // is queued
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700635 mCore->mBufferAge = mCore->mFrameCounter + 1 - mSlots[found].mFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -0800636 }
637
Dan Stoza800b41a2015-04-28 14:20:04 -0700638 BQ_LOGV("dequeueBuffer: setting buffer age to %" PRIu64,
639 mCore->mBufferAge);
Dan Stoza4afd8b62015-02-25 16:49:08 -0800640
Yi Kong48a619f2018-06-05 16:34:59 -0700641 if (CC_UNLIKELY(mSlots[found].mFence == nullptr)) {
Dan Stoza289ade12014-02-28 11:17:17 -0800642 BQ_LOGE("dequeueBuffer: about to return a NULL fence - "
643 "slot=%d w=%d h=%d format=%u",
644 found, buffer->width, buffer->height, buffer->format);
645 }
646
Jim Shargo90842182024-11-14 00:49:27 +0000647#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800648 eglDisplay = mSlots[found].mEglDisplay;
649 eglFence = mSlots[found].mEglFence;
Jim Shargo90842182024-11-14 00:49:27 +0000650#endif
Pablo Ceballos28c65ad2016-06-01 15:03:21 -0700651 // Don't return a fence in shared buffer mode, except for the first
652 // frame.
653 *outFence = (mCore->mSharedBufferMode &&
654 mCore->mSharedBufferSlot == found) ?
655 Fence::NO_FENCE : mSlots[found].mFence;
Jim Shargo90842182024-11-14 00:49:27 +0000656#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800657 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000658#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800659 mSlots[found].mFence = Fence::NO_FENCE;
Pablo Ceballos28c65ad2016-06-01 15:03:21 -0700660
661 // If shared buffer mode has just been enabled, cache the slot of the
662 // first buffer that is dequeued and mark it as the shared buffer.
663 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
664 BufferQueueCore::INVALID_BUFFER_SLOT) {
665 mCore->mSharedBufferSlot = found;
666 mSlots[found].mBufferState.mShared = true;
667 }
Adithya Srinivasana820af92019-11-01 13:55:17 -0700668
669 if (!(returnFlags & BUFFER_NEEDS_REALLOCATION)) {
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000670 callOnFrameDequeued = true;
671 bufferId = mSlots[*outSlot].mGraphicBuffer->getId();
Adithya Srinivasana820af92019-11-01 13:55:17 -0700672 }
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000673
674 listener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -0800675 } // Autolock scope
676
677 if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
Dan Stoza29a3e902014-06-20 13:13:57 -0700678 BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
John Reckdb164ff2024-04-03 16:59:28 -0400679
680#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
681 std::vector<GraphicBufferAllocator::AdditionalOptions> tempOptions;
682 tempOptions.reserve(allocOptions.size());
683 for (const auto& it : allocOptions) {
684 tempOptions.emplace_back(it.name.c_str(), it.value);
685 }
686 const GraphicBufferAllocator::AllocationRequest allocRequest = {
687 .importBuffer = true,
688 .width = width,
689 .height = height,
690 .format = format,
691 .layerCount = BQ_LAYER_COUNT,
692 .usage = usage,
693 .requestorName = {mConsumerName.c_str(), mConsumerName.size()},
694 .extras = std::move(tempOptions),
695 };
Anton Ivanov8ed86592025-02-20 11:52:50 -0800696 sp<GraphicBuffer> graphicBuffer = sp<GraphicBuffer>::make(allocRequest);
John Reckdb164ff2024-04-03 16:59:28 -0400697#else
Tomasz Wasilczykf2add402023-08-11 00:06:51 +0000698 sp<GraphicBuffer> graphicBuffer =
Anton Ivanov8ed86592025-02-20 11:52:50 -0800699 sp<GraphicBuffer>::make(width, height, format, BQ_LAYER_COUNT, usage,
700 std::string{mConsumerName.c_str(), mConsumerName.size()});
John Reckdb164ff2024-04-03 16:59:28 -0400701#endif
Mathias Agopian0556d792017-03-22 15:49:32 -0700702
703 status_t error = graphicBuffer->initCheck();
704
Dan Stoza289ade12014-02-28 11:17:17 -0800705 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200706 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800707
Chia-I Wufeec3b12017-05-25 09:34:56 -0700708 if (error == NO_ERROR && !mCore->mIsAbandoned) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700709 graphicBuffer->setGenerationNumber(mCore->mGenerationNumber);
710 mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
John Reckdb164ff2024-04-03 16:59:28 -0400711#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
712 mSlots[*outSlot].mAdditionalOptionsGenerationId = allocOptionsGenId;
713#endif
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000714 callOnFrameDequeued = true;
715 bufferId = mSlots[*outSlot].mGraphicBuffer->getId();
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700716 }
717
718 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200719 mCore->mIsAllocatingCondition.notify_all();
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700720
Chia-I Wufeec3b12017-05-25 09:34:56 -0700721 if (error != NO_ERROR) {
Pablo Ceballos0a068092016-06-29 15:08:33 -0700722 mCore->mFreeSlots.insert(*outSlot);
723 mCore->clearBufferSlotLocked(*outSlot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700724 BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
725 return error;
726 }
727
Dan Stoza289ade12014-02-28 11:17:17 -0800728 if (mCore->mIsAbandoned) {
Pablo Ceballos0a068092016-06-29 15:08:33 -0700729 mCore->mFreeSlots.insert(*outSlot);
730 mCore->clearBufferSlotLocked(*outSlot);
Dan Stoza289ade12014-02-28 11:17:17 -0800731 BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
732 return NO_INIT;
733 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800734
Pablo Ceballos9e314332016-01-12 13:49:19 -0800735 VALIDATE_CONSISTENCY();
Dan Stoza289ade12014-02-28 11:17:17 -0800736 } // Autolock scope
737 }
738
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000739 if (listener != nullptr && callOnFrameDequeued) {
740 listener->onFrameDequeued(bufferId);
741 }
742
Dan Stoza9f3053d2014-03-06 15:14:33 -0800743 if (attachedByConsumer) {
744 returnFlags |= BUFFER_NEEDS_REALLOCATION;
745 }
746
Jim Shargo90842182024-11-14 00:49:27 +0000747#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800748 if (eglFence != EGL_NO_SYNC_KHR) {
749 EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0,
750 1000000000);
751 // If something goes wrong, log the error, but return the buffer without
752 // synchronizing access to it. It's too late at this point to abort the
753 // dequeue operation.
754 if (result == EGL_FALSE) {
755 BQ_LOGE("dequeueBuffer: error %#x waiting for fence",
756 eglGetError());
757 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
758 BQ_LOGE("dequeueBuffer: timeout waiting for fence");
759 }
760 eglDestroySyncKHR(eglDisplay, eglFence);
761 }
Jim Shargo90842182024-11-14 00:49:27 +0000762#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800763
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700764 BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
765 *outSlot,
Dan Stoza289ade12014-02-28 11:17:17 -0800766 mSlots[*outSlot].mFrameNumber,
tangcheng5614ca02022-04-07 14:26:05 +0800767 mSlots[*outSlot].mGraphicBuffer != nullptr ?
768 mSlots[*outSlot].mGraphicBuffer->handle : nullptr, returnFlags);
Dan Stoza289ade12014-02-28 11:17:17 -0800769
Ian Elliottd11b0442017-07-18 11:05:49 -0600770 if (outBufferAge) {
771 *outBufferAge = mCore->mBufferAge;
772 }
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700773 addAndGetFrameTimestamps(nullptr, outTimestamps);
774
Dan Stoza289ade12014-02-28 11:17:17 -0800775 return returnFlags;
776}
777
Dan Stoza9f3053d2014-03-06 15:14:33 -0800778status_t BufferQueueProducer::detachBuffer(int slot) {
779 ATRACE_CALL();
780 ATRACE_BUFFER_INDEX(slot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700781 BQ_LOGV("detachBuffer: slot %d", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800782
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700783 sp<IConsumerListener> listener;
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000784 bool callOnFrameDetached = false;
785 uint64_t bufferId = 0; // Only used if callOnFrameDetached is true
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700786 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200787 std::lock_guard<std::mutex> lock(mCore->mMutex);
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700788
789 if (mCore->mIsAbandoned) {
790 BQ_LOGE("detachBuffer: BufferQueue has been abandoned");
791 return NO_INIT;
792 }
793
794 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
795 BQ_LOGE("detachBuffer: BufferQueue has no connected producer");
796 return NO_INIT;
797 }
798
799 if (mCore->mSharedBufferMode || mCore->mSharedBufferSlot == slot) {
800 BQ_LOGE("detachBuffer: cannot detach a buffer in shared buffer mode");
801 return BAD_VALUE;
802 }
803
Jim Shargo2e614a42024-10-02 19:31:53 +0000804 const int totalSlotCount = mCore->getTotalSlotCountLocked();
805 if (slot < 0 || slot >= totalSlotCount) {
806 BQ_LOGE("detachBuffer: slot index %d out of range [0, %d)", slot, totalSlotCount);
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700807 return BAD_VALUE;
808 } else if (!mSlots[slot].mBufferState.isDequeued()) {
Darwin Huang29936fa2021-09-08 18:29:18 +0000809 // TODO(http://b/140581935): This message is BQ_LOGW because it
810 // often logs when no actionable errors are present. Return to
811 // using BQ_LOGE after ensuring this only logs during errors.
812 BQ_LOGW("detachBuffer: slot %d is not owned by the producer "
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700813 "(state = %s)", slot, mSlots[slot].mBufferState.string());
814 return BAD_VALUE;
815 } else if (!mSlots[slot].mRequestBufferCalled) {
816 BQ_LOGE("detachBuffer: buffer in slot %d has not been requested",
817 slot);
818 return BAD_VALUE;
819 }
820
Adithya Srinivasan2e434382019-10-09 11:43:01 -0700821 listener = mCore->mConsumerListener;
Robert Carrfc069ba2020-04-20 13:26:31 -0700822 auto gb = mSlots[slot].mGraphicBuffer;
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000823 if (gb != nullptr) {
824 callOnFrameDetached = true;
825 bufferId = gb->getId();
Adithya Srinivasan2e434382019-10-09 11:43:01 -0700826 }
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700827 mSlots[slot].mBufferState.detachProducer();
828 mCore->mActiveBuffers.erase(slot);
829 mCore->mFreeSlots.insert(slot);
830 mCore->clearBufferSlotLocked(slot);
Patrick Williams078d7362024-08-27 10:20:39 -0500831#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
832 mCore->notifyBufferReleased();
833#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200834 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -0500835#endif
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700836 VALIDATE_CONSISTENCY();
Dan Stoza9f3053d2014-03-06 15:14:33 -0800837 }
838
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000839 if (listener != nullptr && callOnFrameDetached) {
840 listener->onFrameDetached(bufferId);
841 }
842
Yi Kong48a619f2018-06-05 16:34:59 -0700843 if (listener != nullptr) {
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700844 listener->onBuffersReleased();
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700845 }
Pablo Ceballos981066c2016-02-18 12:54:37 -0800846
Dan Stoza9f3053d2014-03-06 15:14:33 -0800847 return NO_ERROR;
848}
849
Dan Stozad9822a32014-03-28 15:25:31 -0700850status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
851 sp<Fence>* outFence) {
852 ATRACE_CALL();
853
Yi Kong48a619f2018-06-05 16:34:59 -0700854 if (outBuffer == nullptr) {
Dan Stozad9822a32014-03-28 15:25:31 -0700855 BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
856 return BAD_VALUE;
Yi Kong48a619f2018-06-05 16:34:59 -0700857 } else if (outFence == nullptr) {
Dan Stozad9822a32014-03-28 15:25:31 -0700858 BQ_LOGE("detachNextBuffer: outFence must not be NULL");
859 return BAD_VALUE;
860 }
861
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700862 sp<IConsumerListener> listener;
863 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200864 std::unique_lock<std::mutex> lock(mCore->mMutex);
Dan Stozad9822a32014-03-28 15:25:31 -0700865
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700866 if (mCore->mIsAbandoned) {
867 BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
868 return NO_INIT;
869 }
870
871 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
872 BQ_LOGE("detachNextBuffer: BufferQueue has no connected producer");
873 return NO_INIT;
874 }
875
876 if (mCore->mSharedBufferMode) {
877 BQ_LOGE("detachNextBuffer: cannot detach a buffer in shared buffer "
878 "mode");
879 return BAD_VALUE;
880 }
881
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200882 mCore->waitWhileAllocatingLocked(lock);
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700883
884 if (mCore->mFreeBuffers.empty()) {
885 return NO_MEMORY;
886 }
887
888 int found = mCore->mFreeBuffers.front();
889 mCore->mFreeBuffers.remove(found);
890 mCore->mFreeSlots.insert(found);
891
892 BQ_LOGV("detachNextBuffer detached slot %d", found);
893
894 *outBuffer = mSlots[found].mGraphicBuffer;
895 *outFence = mSlots[found].mFence;
896 mCore->clearBufferSlotLocked(found);
897 VALIDATE_CONSISTENCY();
898 listener = mCore->mConsumerListener;
Dan Stozad9822a32014-03-28 15:25:31 -0700899 }
900
Yi Kong48a619f2018-06-05 16:34:59 -0700901 if (listener != nullptr) {
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700902 listener->onBuffersReleased();
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700903 }
Pablo Ceballos981066c2016-02-18 12:54:37 -0800904
Dan Stozad9822a32014-03-28 15:25:31 -0700905 return NO_ERROR;
906}
907
Dan Stoza9f3053d2014-03-06 15:14:33 -0800908status_t BufferQueueProducer::attachBuffer(int* outSlot,
909 const sp<android::GraphicBuffer>& buffer) {
910 ATRACE_CALL();
911
Yi Kong48a619f2018-06-05 16:34:59 -0700912 if (outSlot == nullptr) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700913 BQ_LOGE("attachBuffer: outSlot must not be NULL");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800914 return BAD_VALUE;
Yi Kong48a619f2018-06-05 16:34:59 -0700915 } else if (buffer == nullptr) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700916 BQ_LOGE("attachBuffer: cannot attach NULL buffer");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800917 return BAD_VALUE;
918 }
919
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200920 std::unique_lock<std::mutex> lock(mCore->mMutex);
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700921
922 if (mCore->mIsAbandoned) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700923 BQ_LOGE("attachBuffer: BufferQueue has been abandoned");
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700924 return NO_INIT;
925 }
926
927 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700928 BQ_LOGE("attachBuffer: BufferQueue has no connected producer");
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700929 return NO_INIT;
930 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800931
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700932 if (mCore->mSharedBufferMode) {
933 BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode");
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700934 return BAD_VALUE;
935 }
936
Dan Stoza812ed062015-06-02 15:45:22 -0700937 if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
938 BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
939 "[queue %u]", buffer->getGenerationNumber(),
940 mCore->mGenerationNumber);
941 return BAD_VALUE;
942 }
943
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200944 mCore->waitWhileAllocatingLocked(lock);
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700945
Dan Stoza9f3053d2014-03-06 15:14:33 -0800946 status_t returnFlags = NO_ERROR;
947 int found;
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200948 status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Attach, lock, &found);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800949 if (status != NO_ERROR) {
950 return status;
951 }
952
953 // This should not happen
954 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700955 BQ_LOGE("attachBuffer: no available buffer slots");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800956 return -EBUSY;
957 }
958
959 *outSlot = found;
960 ATRACE_BUFFER_INDEX(*outSlot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700961 BQ_LOGV("attachBuffer: returning slot %d flags=%#x",
Dan Stoza9f3053d2014-03-06 15:14:33 -0800962 *outSlot, returnFlags);
963
964 mSlots[*outSlot].mGraphicBuffer = buffer;
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700965 mSlots[*outSlot].mBufferState.attachProducer();
Jim Shargo90842182024-11-14 00:49:27 +0000966#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza9f3053d2014-03-06 15:14:33 -0800967 mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000968#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800969 mSlots[*outSlot].mFence = Fence::NO_FENCE;
Dan Stoza2443c792014-03-24 15:03:46 -0700970 mSlots[*outSlot].mRequestBufferCalled = true;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800971 mSlots[*outSlot].mAcquireCalled = false;
Jammy Yu69958b82017-02-22 16:41:38 -0800972 mSlots[*outSlot].mNeedsReallocation = false;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800973 mCore->mActiveBuffers.insert(found);
Pablo Ceballos9e314332016-01-12 13:49:19 -0800974 VALIDATE_CONSISTENCY();
Dan Stoza0de7ea72015-04-23 13:20:51 -0700975
Dan Stoza9f3053d2014-03-06 15:14:33 -0800976 return returnFlags;
977}
978
Dan Stoza289ade12014-02-28 11:17:17 -0800979status_t BufferQueueProducer::queueBuffer(int slot,
980 const QueueBufferInput &input, QueueBufferOutput *output) {
981 ATRACE_CALL();
982 ATRACE_BUFFER_INDEX(slot);
983
Brian Andersond6927fb2016-07-23 23:37:30 -0700984 int64_t requestedPresentTimestamp;
Dan Stoza289ade12014-02-28 11:17:17 -0800985 bool isAutoTimestamp;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -0800986 android_dataspace dataSpace;
Pablo Ceballos60d69222015-08-07 14:47:20 -0700987 Rect crop(Rect::EMPTY_RECT);
Dan Stoza289ade12014-02-28 11:17:17 -0800988 int scalingMode;
989 uint32_t transform;
Ruben Brunk1681d952014-06-27 15:51:55 -0700990 uint32_t stickyTransform;
Brian Andersond6927fb2016-07-23 23:37:30 -0700991 sp<Fence> acquireFence;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700992 bool getFrameTimestamps = false;
Brian Andersond6927fb2016-07-23 23:37:30 -0700993 input.deflate(&requestedPresentTimestamp, &isAutoTimestamp, &dataSpace,
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700994 &crop, &scalingMode, &transform, &acquireFence, &stickyTransform,
995 &getFrameTimestamps);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700996 const Region& surfaceDamage = input.getSurfaceDamage();
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -0700997 const HdrMetadata& hdrMetadata = input.getHdrMetadata();
Brian Lindahl628cff42024-10-30 11:50:28 -0600998 const std::optional<PictureProfileHandle>& pictureProfileHandle =
999 input.getPictureProfileHandle();
Dan Stoza289ade12014-02-28 11:17:17 -08001000
Yi Kong48a619f2018-06-05 16:34:59 -07001001 if (acquireFence == nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -08001002 BQ_LOGE("queueBuffer: fence is NULL");
Jesse Hallde288fe2014-11-04 08:30:48 -08001003 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001004 }
1005
Brian Anderson3d4039d2016-09-23 16:31:30 -07001006 auto acquireFenceTime = std::make_shared<FenceTime>(acquireFence);
1007
Dan Stoza289ade12014-02-28 11:17:17 -08001008 switch (scalingMode) {
1009 case NATIVE_WINDOW_SCALING_MODE_FREEZE:
1010 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
1011 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
1012 case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
1013 break;
1014 default:
1015 BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001016 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001017 }
1018
Dan Stoza8dc55392014-11-04 11:37:46 -08001019 sp<IConsumerListener> frameAvailableListener;
1020 sp<IConsumerListener> frameReplacedListener;
1021 int callbackTicket = 0;
Brian Andersond6927fb2016-07-23 23:37:30 -07001022 uint64_t currentFrameNumber = 0;
Dan Stoza8dc55392014-11-04 11:37:46 -08001023 BufferItem item;
John Reckd2c4a4a2024-02-07 10:31:09 -05001024 int connectedApi;
Mathias Agopianb96661f2024-09-17 11:45:38 -07001025 bool enableEglCpuThrottling = true;
John Reckd2c4a4a2024-02-07 10:31:09 -05001026 sp<Fence> lastQueuedFence;
1027
Dan Stoza289ade12014-02-28 11:17:17 -08001028 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001029 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -08001030
1031 if (mCore->mIsAbandoned) {
1032 BQ_LOGE("queueBuffer: BufferQueue has been abandoned");
1033 return NO_INIT;
1034 }
1035
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001036 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1037 BQ_LOGE("queueBuffer: BufferQueue has no connected producer");
1038 return NO_INIT;
1039 }
1040
Jim Shargo2e614a42024-10-02 19:31:53 +00001041 const int totalSlotCount = mCore->getTotalSlotCountLocked();
1042 if (slot < 0 || slot >= totalSlotCount) {
1043 BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)", slot, totalSlotCount);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001044 return BAD_VALUE;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001045 } else if (!mSlots[slot].mBufferState.isDequeued()) {
Dan Stoza289ade12014-02-28 11:17:17 -08001046 BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001047 "(state = %s)", slot, mSlots[slot].mBufferState.string());
Dan Stoza9f3053d2014-03-06 15:14:33 -08001048 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001049 } else if (!mSlots[slot].mRequestBufferCalled) {
1050 BQ_LOGE("queueBuffer: slot %d was queued without requesting "
1051 "a buffer", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001052 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001053 }
1054
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001055 // If shared buffer mode has just been enabled, cache the slot of the
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001056 // first buffer that is queued and mark it as the shared buffer.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001057 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001058 BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001059 mCore->mSharedBufferSlot = slot;
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001060 mSlots[slot].mBufferState.mShared = true;
1061 }
1062
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001063 BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d"
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -07001064 " validHdrMetadataTypes=0x%x crop=[%d,%d,%d,%d] transform=%#x scale=%s",
1065 slot, mCore->mFrameCounter + 1, requestedPresentTimestamp, dataSpace,
1066 hdrMetadata.validTypes, crop.left, crop.top, crop.right, crop.bottom,
Brian Andersond6927fb2016-07-23 23:37:30 -07001067 transform,
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001068 BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
Dan Stoza289ade12014-02-28 11:17:17 -08001069
1070 const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
1071 Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
Pablo Ceballos60d69222015-08-07 14:47:20 -07001072 Rect croppedRect(Rect::EMPTY_RECT);
Dan Stoza289ade12014-02-28 11:17:17 -08001073 crop.intersect(bufferRect, &croppedRect);
1074 if (croppedRect != crop) {
1075 BQ_LOGE("queueBuffer: crop rect is not contained within the "
1076 "buffer in slot %d", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001077 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001078 }
1079
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001080 // Override UNKNOWN dataspace with consumer default
1081 if (dataSpace == HAL_DATASPACE_UNKNOWN) {
1082 dataSpace = mCore->mDefaultBufferDataSpace;
1083 }
1084
Brian Andersond6927fb2016-07-23 23:37:30 -07001085 mSlots[slot].mFence = acquireFence;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001086 mSlots[slot].mBufferState.queue();
1087
Brian Andersond6927fb2016-07-23 23:37:30 -07001088 // Increment the frame counter and store a local version of it
1089 // for use outside the lock on mCore->mMutex.
Dan Stoza289ade12014-02-28 11:17:17 -08001090 ++mCore->mFrameCounter;
Brian Andersond6927fb2016-07-23 23:37:30 -07001091 currentFrameNumber = mCore->mFrameCounter;
1092 mSlots[slot].mFrameNumber = currentFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -08001093
Dan Stoza289ade12014-02-28 11:17:17 -08001094 item.mAcquireCalled = mSlots[slot].mAcquireCalled;
1095 item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
1096 item.mCrop = crop;
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001097 item.mTransform = transform &
1098 ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
Dan Stoza289ade12014-02-28 11:17:17 -08001099 item.mTransformToDisplayInverse =
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001100 (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
1101 item.mScalingMode = static_cast<uint32_t>(scalingMode);
Brian Andersond6927fb2016-07-23 23:37:30 -07001102 item.mTimestamp = requestedPresentTimestamp;
Dan Stoza289ade12014-02-28 11:17:17 -08001103 item.mIsAutoTimestamp = isAutoTimestamp;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001104 item.mDataSpace = dataSpace;
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -07001105 item.mHdrMetadata = hdrMetadata;
Brian Lindahl628cff42024-10-30 11:50:28 -06001106 item.mPictureProfileHandle = pictureProfileHandle;
Brian Andersond6927fb2016-07-23 23:37:30 -07001107 item.mFrameNumber = currentFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -08001108 item.mSlot = slot;
Brian Andersond6927fb2016-07-23 23:37:30 -07001109 item.mFence = acquireFence;
Brian Anderson3d4039d2016-09-23 16:31:30 -07001110 item.mFenceTime = acquireFenceTime;
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001111 item.mIsDroppable = mCore->mAsyncMode ||
Sungtak Lee45e9e0b2019-05-28 13:38:23 -07001112 (mConsumerIsSurfaceFlinger && mCore->mQueueBufferCanDrop) ||
Sungtak Lee3249fb62019-03-02 16:40:47 -08001113 (mCore->mLegacyBufferDrop && mCore->mQueueBufferCanDrop) ||
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001114 (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == slot);
Dan Stoza5065a552015-03-17 16:23:42 -07001115 item.mSurfaceDamage = surfaceDamage;
Pablo Ceballos06312182015-10-07 16:32:12 -07001116 item.mQueuedBuffer = true;
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001117 item.mAutoRefresh = mCore->mSharedBufferMode && mCore->mAutoRefresh;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001118 item.mApi = mCore->mConnectedApi;
Dan Stoza289ade12014-02-28 11:17:17 -08001119
Ruben Brunk1681d952014-06-27 15:51:55 -07001120 mStickyTransform = stickyTransform;
1121
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001122 // Cache the shared buffer data so that the BufferItem can be recreated.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001123 if (mCore->mSharedBufferMode) {
1124 mCore->mSharedBufferCache.crop = crop;
1125 mCore->mSharedBufferCache.transform = transform;
1126 mCore->mSharedBufferCache.scalingMode = static_cast<uint32_t>(
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001127 scalingMode);
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001128 mCore->mSharedBufferCache.dataspace = dataSpace;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001129 }
1130
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001131 output->bufferReplaced = false;
Dan Stoza289ade12014-02-28 11:17:17 -08001132 if (mCore->mQueue.empty()) {
1133 // When the queue is empty, we can ignore mDequeueBufferCannotBlock
1134 // and simply queue this buffer
1135 mCore->mQueue.push_back(item);
Dan Stoza8dc55392014-11-04 11:37:46 -08001136 frameAvailableListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001137 } else {
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001138 // When the queue is not empty, we need to look at the last buffer
1139 // in the queue to see if we need to replace it
1140 const BufferItem& last = mCore->mQueue.itemAt(
1141 mCore->mQueue.size() - 1);
1142 if (last.mIsDroppable) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001143
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001144 if (!last.mIsStale) {
1145 mSlots[last.mSlot].mBufferState.freeQueued();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001146
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001147 // After leaving shared buffer mode, the shared buffer will
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001148 // still be around. Mark it as no longer shared if this
1149 // operation causes it to be free.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001150 if (!mCore->mSharedBufferMode &&
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001151 mSlots[last.mSlot].mBufferState.isFree()) {
1152 mSlots[last.mSlot].mBufferState.mShared = false;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001153 }
1154 // Don't put the shared buffer on the free list.
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001155 if (!mSlots[last.mSlot].mBufferState.isShared()) {
1156 mCore->mActiveBuffers.erase(last.mSlot);
1157 mCore->mFreeBuffers.push_back(last.mSlot);
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001158 output->bufferReplaced = true;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001159 }
Dan Stoza289ade12014-02-28 11:17:17 -08001160 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001161
Steven Thomas862e7532019-07-10 19:21:03 -07001162 // Make sure to merge the damage rect from the frame we're about
1163 // to drop into the new frame's damage rect.
1164 if (last.mSurfaceDamage.bounds() == Rect::INVALID_RECT ||
1165 item.mSurfaceDamage.bounds() == Rect::INVALID_RECT) {
1166 item.mSurfaceDamage = Region::INVALID_REGION;
1167 } else {
1168 item.mSurfaceDamage |= last.mSurfaceDamage;
1169 }
1170
Dan Stoza289ade12014-02-28 11:17:17 -08001171 // Overwrite the droppable buffer with the incoming one
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001172 mCore->mQueue.editItemAt(mCore->mQueue.size() - 1) = item;
Dan Stoza8dc55392014-11-04 11:37:46 -08001173 frameReplacedListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001174 } else {
1175 mCore->mQueue.push_back(item);
Dan Stoza8dc55392014-11-04 11:37:46 -08001176 frameAvailableListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001177 }
1178 }
1179
1180 mCore->mBufferHasBeenQueued = true;
Patrick Williams078d7362024-08-27 10:20:39 -05001181#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1182 mCore->notifyBufferReleased();
1183#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001184 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001185#endif
Dan Stoza50101d02016-04-07 16:53:23 -07001186 mCore->mLastQueuedSlot = slot;
Dan Stoza289ade12014-02-28 11:17:17 -08001187
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001188 output->width = mCore->mDefaultWidth;
1189 output->height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001190 output->transformHint = mCore->mTransformHintInUse = mCore->mTransformHint;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001191 output->numPendingBuffers = static_cast<uint32_t>(mCore->mQueue.size());
1192 output->nextFrameNumber = mCore->mFrameCounter + 1;
Dan Stoza289ade12014-02-28 11:17:17 -08001193
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001194 ATRACE_INT(mCore->mConsumerName.c_str(), static_cast<int32_t>(mCore->mQueue.size()));
Chong Zhang62493092020-01-15 16:04:47 -08001195#ifndef NO_BINDER
Dan Stozae77c7662016-05-13 11:37:28 -07001196 mCore->mOccupancyTracker.registerOccupancyChange(mCore->mQueue.size());
Chong Zhang62493092020-01-15 16:04:47 -08001197#endif
Dan Stoza8dc55392014-11-04 11:37:46 -08001198 // Take a ticket for the callback functions
1199 callbackTicket = mNextCallbackTicket++;
Dan Stoza0de7ea72015-04-23 13:20:51 -07001200
Pablo Ceballos9e314332016-01-12 13:49:19 -08001201 VALIDATE_CONSISTENCY();
John Reckd2c4a4a2024-02-07 10:31:09 -05001202
1203 connectedApi = mCore->mConnectedApi;
Mathias Agopianb96661f2024-09-17 11:45:38 -07001204 if (flags::bq_producer_throttles_only_async_mode()) {
1205 enableEglCpuThrottling = mCore->mAsyncMode || mCore->mDequeueBufferCannotBlock;
1206 }
John Reckd2c4a4a2024-02-07 10:31:09 -05001207 lastQueuedFence = std::move(mLastQueueBufferFence);
1208
1209 mLastQueueBufferFence = std::move(acquireFence);
1210 mLastQueuedCrop = item.mCrop;
1211 mLastQueuedTransform = item.mTransform;
Dan Stoza289ade12014-02-28 11:17:17 -08001212 } // Autolock scope
1213
Irvel468051e2016-06-13 16:44:44 -07001214 // It is okay not to clear the GraphicBuffer when the consumer is SurfaceFlinger because
1215 // it is guaranteed that the BufferQueue is inside SurfaceFlinger's process and
1216 // there will be no Binder call
1217 if (!mConsumerIsSurfaceFlinger) {
1218 item.mGraphicBuffer.clear();
1219 }
1220
JihCheng Chiu544c5222019-04-02 20:50:58 +08001221 // Update and get FrameEventHistory.
1222 nsecs_t postedTime = systemTime(SYSTEM_TIME_MONOTONIC);
1223 NewFrameEventsEntry newFrameEventsEntry = {
1224 currentFrameNumber,
1225 postedTime,
1226 requestedPresentTimestamp,
1227 std::move(acquireFenceTime)
1228 };
1229 addAndGetFrameTimestamps(&newFrameEventsEntry,
1230 getFrameTimestamps ? &output->frameTimestamps : nullptr);
1231
Dan Stoza8dc55392014-11-04 11:37:46 -08001232 // Call back without the main BufferQueue lock held, but with the callback
1233 // lock held so we can ensure that callbacks occur in order
Mathias Agopian4f6ce7c2017-04-03 17:14:31 -07001234
Mathias Agopian4f6ce7c2017-04-03 17:14:31 -07001235 { // scope for the lock
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001236 std::unique_lock<std::mutex> lock(mCallbackMutex);
Dan Stoza8dc55392014-11-04 11:37:46 -08001237 while (callbackTicket != mCurrentCallbackTicket) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001238 mCallbackCondition.wait(lock);
Dan Stoza8dc55392014-11-04 11:37:46 -08001239 }
1240
Yi Kong48a619f2018-06-05 16:34:59 -07001241 if (frameAvailableListener != nullptr) {
Dan Stoza8dc55392014-11-04 11:37:46 -08001242 frameAvailableListener->onFrameAvailable(item);
Yi Kong48a619f2018-06-05 16:34:59 -07001243 } else if (frameReplacedListener != nullptr) {
Dan Stoza8dc55392014-11-04 11:37:46 -08001244 frameReplacedListener->onFrameReplaced(item);
1245 }
1246
1247 ++mCurrentCallbackTicket;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001248 mCallbackCondition.notify_all();
Dan Stoza289ade12014-02-28 11:17:17 -08001249 }
1250
Yiwei Zhangcb7dd002019-04-16 11:03:01 -07001251 // Wait without lock held
Mathias Agopianb96661f2024-09-17 11:45:38 -07001252 if (connectedApi == NATIVE_WINDOW_API_EGL && enableEglCpuThrottling) {
Yiwei Zhangcb7dd002019-04-16 11:03:01 -07001253 // Waiting here allows for two full buffers to be queued but not a
1254 // third. In the event that frames take varying time, this makes a
1255 // small trade-off in favor of latency rather than throughput.
1256 lastQueuedFence->waitForever("Throttling EGL Production");
1257 }
1258
Dan Stoza289ade12014-02-28 11:17:17 -08001259 return NO_ERROR;
1260}
1261
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001262status_t BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
Dan Stoza289ade12014-02-28 11:17:17 -08001263 ATRACE_CALL();
1264 BQ_LOGV("cancelBuffer: slot %d", slot);
Dan Stoza289ade12014-02-28 11:17:17 -08001265
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001266 sp<IConsumerListener> listener;
1267 bool callOnFrameCancelled = false;
1268 uint64_t bufferId = 0; // Only used if callOnFrameCancelled == true
1269 {
1270 std::lock_guard<std::mutex> lock(mCore->mMutex);
1271
1272 if (mCore->mIsAbandoned) {
1273 BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
1274 return NO_INIT;
1275 }
1276
1277 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1278 BQ_LOGE("cancelBuffer: BufferQueue has no connected producer");
1279 return NO_INIT;
1280 }
1281
1282 if (mCore->mSharedBufferMode) {
1283 BQ_LOGE("cancelBuffer: cannot cancel a buffer in shared buffer mode");
1284 return BAD_VALUE;
1285 }
1286
Jim Shargo2e614a42024-10-02 19:31:53 +00001287 const int totalSlotCount = mCore->getTotalSlotCountLocked();
1288 if (slot < 0 || slot >= totalSlotCount) {
1289 BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)", slot, totalSlotCount);
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001290 return BAD_VALUE;
1291 } else if (!mSlots[slot].mBufferState.isDequeued()) {
1292 BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
1293 "(state = %s)",
1294 slot, mSlots[slot].mBufferState.string());
1295 return BAD_VALUE;
1296 } else if (fence == nullptr) {
1297 BQ_LOGE("cancelBuffer: fence is NULL");
1298 return BAD_VALUE;
1299 }
1300
1301 mSlots[slot].mBufferState.cancel();
1302
1303 // After leaving shared buffer mode, the shared buffer will still be around.
1304 // Mark it as no longer shared if this operation causes it to be free.
1305 if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) {
1306 mSlots[slot].mBufferState.mShared = false;
1307 }
1308
1309 // Don't put the shared buffer on the free list.
1310 if (!mSlots[slot].mBufferState.isShared()) {
1311 mCore->mActiveBuffers.erase(slot);
1312 mCore->mFreeBuffers.push_back(slot);
1313 }
1314
1315 auto gb = mSlots[slot].mGraphicBuffer;
1316 if (gb != nullptr) {
1317 callOnFrameCancelled = true;
1318 bufferId = gb->getId();
1319 }
1320 mSlots[slot].mFence = fence;
Patrick Williams078d7362024-08-27 10:20:39 -05001321#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1322 mCore->notifyBufferReleased();
1323#else
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001324 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001325#endif
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001326 listener = mCore->mConsumerListener;
1327 VALIDATE_CONSISTENCY();
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001328 }
1329
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001330 if (listener != nullptr && callOnFrameCancelled) {
1331 listener->onFrameCancelled(bufferId);
Dan Stoza289ade12014-02-28 11:17:17 -08001332 }
1333
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001334 return NO_ERROR;
Dan Stoza289ade12014-02-28 11:17:17 -08001335}
1336
1337int BufferQueueProducer::query(int what, int *outValue) {
1338 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001339 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -08001340
Yi Kong48a619f2018-06-05 16:34:59 -07001341 if (outValue == nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -08001342 BQ_LOGE("query: outValue was NULL");
1343 return BAD_VALUE;
1344 }
1345
1346 if (mCore->mIsAbandoned) {
1347 BQ_LOGE("query: BufferQueue has been abandoned");
1348 return NO_INIT;
1349 }
1350
1351 int value;
1352 switch (what) {
1353 case NATIVE_WINDOW_WIDTH:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001354 value = static_cast<int32_t>(mCore->mDefaultWidth);
Dan Stoza289ade12014-02-28 11:17:17 -08001355 break;
1356 case NATIVE_WINDOW_HEIGHT:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001357 value = static_cast<int32_t>(mCore->mDefaultHeight);
Dan Stoza289ade12014-02-28 11:17:17 -08001358 break;
1359 case NATIVE_WINDOW_FORMAT:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001360 value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
Dan Stoza289ade12014-02-28 11:17:17 -08001361 break;
Craig Donner6ebc46a2016-10-21 15:23:44 -07001362 case NATIVE_WINDOW_LAYER_COUNT:
1363 // All BufferQueue buffers have a single layer.
1364 value = BQ_LAYER_COUNT;
1365 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001366 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001367 value = mCore->getMinUndequeuedBufferCountLocked();
Dan Stoza289ade12014-02-28 11:17:17 -08001368 break;
Ruben Brunk1681d952014-06-27 15:51:55 -07001369 case NATIVE_WINDOW_STICKY_TRANSFORM:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001370 value = static_cast<int32_t>(mStickyTransform);
Ruben Brunk1681d952014-06-27 15:51:55 -07001371 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001372 case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
1373 value = (mCore->mQueue.size() > 1);
1374 break;
1375 case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
Chia-I Wue2786ea2017-08-07 10:36:08 -07001376 // deprecated; higher 32 bits are truncated
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001377 value = static_cast<int32_t>(mCore->mConsumerUsageBits);
Dan Stoza289ade12014-02-28 11:17:17 -08001378 break;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001379 case NATIVE_WINDOW_DEFAULT_DATASPACE:
1380 value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace);
1381 break;
Dan Stoza4afd8b62015-02-25 16:49:08 -08001382 case NATIVE_WINDOW_BUFFER_AGE:
1383 if (mCore->mBufferAge > INT32_MAX) {
1384 value = 0;
1385 } else {
1386 value = static_cast<int32_t>(mCore->mBufferAge);
1387 }
1388 break;
Jiwen 'Steve' Cai20419132017-04-21 18:49:53 -07001389 case NATIVE_WINDOW_CONSUMER_IS_PROTECTED:
1390 value = static_cast<int32_t>(mCore->mConsumerIsProtected);
1391 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001392 default:
1393 return BAD_VALUE;
1394 }
1395
1396 BQ_LOGV("query: %d? %d", what, value);
1397 *outValue = value;
1398 return NO_ERROR;
1399}
1400
Dan Stozaf0eaf252014-03-21 13:05:51 -07001401status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
Dan Stoza289ade12014-02-28 11:17:17 -08001402 int api, bool producerControlledByApp, QueueBufferOutput *output) {
1403 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001404 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballos981066c2016-02-18 12:54:37 -08001405 mConsumerName = mCore->mConsumerName;
1406 BQ_LOGV("connect: api=%d producerControlledByApp=%s", api,
1407 producerControlledByApp ? "true" : "false");
1408
1409 if (mCore->mIsAbandoned) {
1410 BQ_LOGE("connect: BufferQueue has been abandoned");
1411 return NO_INIT;
1412 }
1413
Yi Kong48a619f2018-06-05 16:34:59 -07001414 if (mCore->mConsumerListener == nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -08001415 BQ_LOGE("connect: BufferQueue has no consumer");
1416 return NO_INIT;
1417 }
1418
Yi Kong48a619f2018-06-05 16:34:59 -07001419 if (output == nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -08001420 BQ_LOGE("connect: output was NULL");
1421 return BAD_VALUE;
1422 }
1423
1424 if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
1425 BQ_LOGE("connect: already connected (cur=%d req=%d)",
1426 mCore->mConnectedApi, api);
1427 return BAD_VALUE;
1428 }
1429
1430 int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode,
1431 mDequeueTimeout < 0 ?
1432 mCore->mConsumerControlledByApp && producerControlledByApp : false,
1433 mCore->mMaxBufferCount) -
1434 mCore->getMaxBufferCountLocked();
1435 if (!mCore->adjustAvailableSlotsLocked(delta)) {
1436 BQ_LOGE("connect: BufferQueue failed to adjust the number of available "
1437 "slots. Delta = %d", delta);
1438 return BAD_VALUE;
1439 }
1440
Dan Stoza289ade12014-02-28 11:17:17 -08001441 int status = NO_ERROR;
Pablo Ceballos981066c2016-02-18 12:54:37 -08001442 switch (api) {
1443 case NATIVE_WINDOW_API_EGL:
1444 case NATIVE_WINDOW_API_CPU:
1445 case NATIVE_WINDOW_API_MEDIA:
1446 case NATIVE_WINDOW_API_CAMERA:
1447 mCore->mConnectedApi = api;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001448
1449 output->width = mCore->mDefaultWidth;
1450 output->height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001451 output->transformHint = mCore->mTransformHintInUse = mCore->mTransformHint;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001452 output->numPendingBuffers =
1453 static_cast<uint32_t>(mCore->mQueue.size());
1454 output->nextFrameNumber = mCore->mFrameCounter + 1;
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001455 output->bufferReplaced = false;
silence_dogoode9d092a2019-06-19 16:14:53 -07001456 output->maxBufferCount = mCore->mMaxBufferCount;
Jim Shargo2e614a42024-10-02 19:31:53 +00001457#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_UNLIMITED_SLOTS)
1458 output->isSlotExpansionAllowed = mCore->mAllowExtendedSlotCount;
1459#endif
Dan Stoza289ade12014-02-28 11:17:17 -08001460
Yi Kong48a619f2018-06-05 16:34:59 -07001461 if (listener != nullptr) {
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001462 // Set up a death notification so that we can disconnect
1463 // automatically if the remote producer dies
Chong Zhang62493092020-01-15 16:04:47 -08001464#ifndef NO_BINDER
Yi Kong48a619f2018-06-05 16:34:59 -07001465 if (IInterface::asBinder(listener)->remoteBinder() != nullptr) {
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001466 status = IInterface::asBinder(listener)->linkToDeath(
Anton Ivanov8ed86592025-02-20 11:52:50 -08001467 sp<IBinder::DeathRecipient>::fromExisting(this));
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001468 if (status != NO_ERROR) {
1469 BQ_LOGE("connect: linkToDeath failed: %s (%d)",
1470 strerror(-status), status);
1471 }
1472 mCore->mLinkedToDeath = listener;
1473 }
Chong Zhang62493092020-01-15 16:04:47 -08001474#endif
Shuzhen Wang067fcd32019-08-14 10:41:12 -07001475 mCore->mConnectedProducerListener = listener;
1476 mCore->mBufferReleasedCbEnabled = listener->needsReleaseNotify();
Sungtak Leecd217472024-07-19 17:17:40 +00001477#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1478 mCore->mBufferAttachedCbEnabled = listener->needsAttachNotify();
1479#endif
Pablo Ceballos981066c2016-02-18 12:54:37 -08001480 }
Pablo Ceballos981066c2016-02-18 12:54:37 -08001481 break;
1482 default:
1483 BQ_LOGE("connect: unknown API %d", api);
1484 status = BAD_VALUE;
1485 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001486 }
Jayant Chowdharyad9fe272019-03-07 22:36:06 -08001487 mCore->mConnectedPid = BufferQueueThreadState::getCallingPid();
Pablo Ceballos981066c2016-02-18 12:54:37 -08001488 mCore->mBufferHasBeenQueued = false;
1489 mCore->mDequeueBufferCannotBlock = false;
Sungtak Lee3249fb62019-03-02 16:40:47 -08001490 mCore->mQueueBufferCanDrop = false;
1491 mCore->mLegacyBufferDrop = true;
1492 if (mCore->mConsumerControlledByApp && producerControlledByApp) {
1493 mCore->mDequeueBufferCannotBlock = mDequeueTimeout < 0;
1494 mCore->mQueueBufferCanDrop = mDequeueTimeout <= 0;
Dan Stoza127fc632015-06-30 13:43:32 -07001495 }
Dan Stoza289ade12014-02-28 11:17:17 -08001496
Pablo Ceballos981066c2016-02-18 12:54:37 -08001497 mCore->mAllowAllocation = true;
John Reckdb164ff2024-04-03 16:59:28 -04001498#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1499 mCore->mAdditionalOptions.clear();
1500#endif
Pablo Ceballos981066c2016-02-18 12:54:37 -08001501 VALIDATE_CONSISTENCY();
Dan Stoza289ade12014-02-28 11:17:17 -08001502 return status;
1503}
1504
Robert Carr97b9c862016-09-08 13:54:35 -07001505status_t BufferQueueProducer::disconnect(int api, DisconnectMode mode) {
Dan Stoza289ade12014-02-28 11:17:17 -08001506 ATRACE_CALL();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001507 BQ_LOGV("disconnect: api %d", api);
Dan Stoza289ade12014-02-28 11:17:17 -08001508
1509 int status = NO_ERROR;
1510 sp<IConsumerListener> listener;
1511 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001512 std::unique_lock<std::mutex> lock(mCore->mMutex);
Robert Carr97b9c862016-09-08 13:54:35 -07001513
1514 if (mode == DisconnectMode::AllLocal) {
Jayant Chowdharyad9fe272019-03-07 22:36:06 -08001515 if (BufferQueueThreadState::getCallingPid() != mCore->mConnectedPid) {
Robert Carr97b9c862016-09-08 13:54:35 -07001516 return NO_ERROR;
1517 }
1518 api = BufferQueueCore::CURRENTLY_CONNECTED_API;
1519 }
1520
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001521 mCore->waitWhileAllocatingLocked(lock);
Dan Stoza289ade12014-02-28 11:17:17 -08001522
1523 if (mCore->mIsAbandoned) {
1524 // It's not really an error to disconnect after the surface has
1525 // been abandoned; it should just be a no-op.
1526 return NO_ERROR;
1527 }
1528
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001529 if (api == BufferQueueCore::CURRENTLY_CONNECTED_API) {
Chong Zhang5ac51482017-02-16 15:52:33 -08001530 if (mCore->mConnectedApi == NATIVE_WINDOW_API_MEDIA) {
1531 ALOGD("About to force-disconnect API_MEDIA, mode=%d", mode);
1532 }
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001533 api = mCore->mConnectedApi;
Chong Zhang26bb2b12016-03-08 12:08:33 -08001534 // If we're asked to disconnect the currently connected api but
1535 // nobody is connected, it's not really an error.
1536 if (api == BufferQueueCore::NO_CONNECTED_API) {
1537 return NO_ERROR;
1538 }
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001539 }
1540
Dan Stoza289ade12014-02-28 11:17:17 -08001541 switch (api) {
1542 case NATIVE_WINDOW_API_EGL:
1543 case NATIVE_WINDOW_API_CPU:
1544 case NATIVE_WINDOW_API_MEDIA:
1545 case NATIVE_WINDOW_API_CAMERA:
1546 if (mCore->mConnectedApi == api) {
1547 mCore->freeAllBuffersLocked();
1548
Chong Zhang62493092020-01-15 16:04:47 -08001549#ifndef NO_BINDER
Dan Stoza289ade12014-02-28 11:17:17 -08001550 // Remove our death notification callback if we have one
Yi Kong48a619f2018-06-05 16:34:59 -07001551 if (mCore->mLinkedToDeath != nullptr) {
Dan Stozaf0eaf252014-03-21 13:05:51 -07001552 sp<IBinder> token =
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001553 IInterface::asBinder(mCore->mLinkedToDeath);
Dan Stoza289ade12014-02-28 11:17:17 -08001554 // This can fail if we're here because of the death
1555 // notification, but we just ignore it
Anton Ivanov8ed86592025-02-20 11:52:50 -08001556 token->unlinkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Dan Stoza289ade12014-02-28 11:17:17 -08001557 }
Chong Zhang62493092020-01-15 16:04:47 -08001558#endif
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001559 mCore->mSharedBufferSlot =
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001560 BufferQueueCore::INVALID_BUFFER_SLOT;
Yi Kong48a619f2018-06-05 16:34:59 -07001561 mCore->mLinkedToDeath = nullptr;
1562 mCore->mConnectedProducerListener = nullptr;
Dan Stoza289ade12014-02-28 11:17:17 -08001563 mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API;
Robert Carr97b9c862016-09-08 13:54:35 -07001564 mCore->mConnectedPid = -1;
Jesse Hall399184a2014-03-03 15:42:54 -08001565 mCore->mSidebandStream.clear();
Patrick Williams078d7362024-08-27 10:20:39 -05001566#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1567 mCore->notifyBufferReleased();
1568#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001569 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001570#endif
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001571 mCore->mAutoPrerotation = false;
John Reckdb164ff2024-04-03 16:59:28 -04001572#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1573 mCore->mAdditionalOptions.clear();
1574#endif
Dan Stoza289ade12014-02-28 11:17:17 -08001575 listener = mCore->mConsumerListener;
Wonsik Kim3e198b22017-04-07 15:43:16 -07001576 } else if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1577 BQ_LOGE("disconnect: not connected (req=%d)", api);
1578 status = NO_INIT;
1579 } else {
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001580 BQ_LOGE("disconnect: still connected to another API "
Dan Stoza289ade12014-02-28 11:17:17 -08001581 "(cur=%d req=%d)", mCore->mConnectedApi, api);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001582 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001583 }
1584 break;
1585 default:
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001586 BQ_LOGE("disconnect: unknown API %d", api);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001587 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001588 break;
1589 }
1590 } // Autolock scope
1591
1592 // Call back without lock held
Yi Kong48a619f2018-06-05 16:34:59 -07001593 if (listener != nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -08001594 listener->onBuffersReleased();
Brian Anderson5ea5e592016-12-01 16:54:33 -08001595 listener->onDisconnect();
Dan Stoza289ade12014-02-28 11:17:17 -08001596 }
1597
1598 return status;
1599}
1600
Jesse Hall399184a2014-03-03 15:42:54 -08001601status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
Wonsik Kimafe30812014-03-31 23:16:08 +09001602 sp<IConsumerListener> listener;
1603 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001604 std::lock_guard<std::mutex> _l(mCore->mMutex);
Wonsik Kimafe30812014-03-31 23:16:08 +09001605 mCore->mSidebandStream = stream;
1606 listener = mCore->mConsumerListener;
1607 } // Autolock scope
1608
Yi Kong48a619f2018-06-05 16:34:59 -07001609 if (listener != nullptr) {
Wonsik Kimafe30812014-03-31 23:16:08 +09001610 listener->onSidebandStreamChanged();
1611 }
Jesse Hall399184a2014-03-03 15:42:54 -08001612 return NO_ERROR;
1613}
1614
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001615void BufferQueueProducer::allocateBuffers(uint32_t width, uint32_t height,
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001616 PixelFormat format, uint64_t usage) {
Antoine Labour78014f32014-07-15 21:17:03 -07001617 ATRACE_CALL();
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001618
1619 const bool useDefaultSize = !width && !height;
Antoine Labour78014f32014-07-15 21:17:03 -07001620 while (true) {
Antoine Labour78014f32014-07-15 21:17:03 -07001621 uint32_t allocWidth = 0;
1622 uint32_t allocHeight = 0;
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001623 PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001624 uint64_t allocUsage = 0;
Chia-I Wu1dbf0e32018-02-07 14:40:08 -08001625 std::string allocName;
John Reckdb164ff2024-04-03 16:59:28 -04001626#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1627 std::vector<gui::AdditionalOptions> allocOptions;
1628 uint32_t allocOptionsGenId = 0;
1629#endif
Antoine Labour78014f32014-07-15 21:17:03 -07001630 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001631 std::unique_lock<std::mutex> lock(mCore->mMutex);
1632 mCore->waitWhileAllocatingLocked(lock);
Dan Stoza29a3e902014-06-20 13:13:57 -07001633
Dan Stoza9de72932015-04-16 17:28:43 -07001634 if (!mCore->mAllowAllocation) {
1635 BQ_LOGE("allocateBuffers: allocation is not allowed for this "
1636 "BufferQueue");
1637 return;
1638 }
1639
Jorim Jaggi0a3e7842018-07-17 13:48:33 +02001640 // Only allocate one buffer at a time to reduce risks of overlapping an allocation from
1641 // both allocateBuffers and dequeueBuffer.
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001642 if (mCore->mFreeSlots.empty()) {
1643 BQ_LOGV("allocateBuffers: a slot was occupied while "
1644 "allocating. Dropping allocated buffer.");
Antoine Labour78014f32014-07-15 21:17:03 -07001645 return;
1646 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001647
Antoine Labour78014f32014-07-15 21:17:03 -07001648 allocWidth = width > 0 ? width : mCore->mDefaultWidth;
1649 allocHeight = height > 0 ? height : mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001650 if (useDefaultSize && mCore->mAutoPrerotation &&
1651 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
1652 std::swap(allocWidth, allocHeight);
1653 }
1654
Antoine Labour78014f32014-07-15 21:17:03 -07001655 allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
1656 allocUsage = usage | mCore->mConsumerUsageBits;
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001657 allocName.assign(mCore->mConsumerName.c_str(), mCore->mConsumerName.size());
Antoine Labour78014f32014-07-15 21:17:03 -07001658
John Reckdb164ff2024-04-03 16:59:28 -04001659#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1660 allocOptions = mCore->mAdditionalOptions;
1661 allocOptionsGenId = mCore->mAdditionalOptionsGenerationId;
1662#endif
1663
Antoine Labour78014f32014-07-15 21:17:03 -07001664 mCore->mIsAllocating = true;
John Reckdb164ff2024-04-03 16:59:28 -04001665
Antoine Labour78014f32014-07-15 21:17:03 -07001666 } // Autolock scope
1667
John Reckdb164ff2024-04-03 16:59:28 -04001668#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1669 std::vector<GraphicBufferAllocator::AdditionalOptions> tempOptions;
1670 tempOptions.reserve(allocOptions.size());
1671 for (const auto& it : allocOptions) {
1672 tempOptions.emplace_back(it.name.c_str(), it.value);
1673 }
1674 const GraphicBufferAllocator::AllocationRequest allocRequest = {
1675 .importBuffer = true,
1676 .width = allocWidth,
1677 .height = allocHeight,
1678 .format = allocFormat,
1679 .layerCount = BQ_LAYER_COUNT,
1680 .usage = allocUsage,
1681 .requestorName = allocName,
1682 .extras = std::move(tempOptions),
1683 };
1684#endif
1685
John Reckdb164ff2024-04-03 16:59:28 -04001686#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
Anton Ivanov8ed86592025-02-20 11:52:50 -08001687 sp<GraphicBuffer> graphicBuffer = sp<GraphicBuffer>::make(allocRequest);
John Reckdb164ff2024-04-03 16:59:28 -04001688#else
Anton Ivanov8ed86592025-02-20 11:52:50 -08001689 sp<GraphicBuffer> graphicBuffer =
1690 sp<GraphicBuffer>::make(allocWidth, allocHeight, allocFormat, BQ_LAYER_COUNT,
1691 allocUsage, allocName);
John Reckdb164ff2024-04-03 16:59:28 -04001692#endif
Mathias Agopian0556d792017-03-22 15:49:32 -07001693
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001694 status_t result = graphicBuffer->initCheck();
Mathias Agopian0556d792017-03-22 15:49:32 -07001695
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001696 if (result != NO_ERROR) {
1697 BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format"
1698 " %u, usage %#" PRIx64 ")", width, height, format, usage);
1699 std::lock_guard<std::mutex> lock(mCore->mMutex);
1700 mCore->mIsAllocating = false;
1701 mCore->mIsAllocatingCondition.notify_all();
1702 return;
Antoine Labour78014f32014-07-15 21:17:03 -07001703 }
1704
1705 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001706 std::unique_lock<std::mutex> lock(mCore->mMutex);
Antoine Labour78014f32014-07-15 21:17:03 -07001707 uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
1708 uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001709 if (useDefaultSize && mCore->mAutoPrerotation &&
1710 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
1711 std::swap(checkWidth, checkHeight);
1712 }
1713
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001714 PixelFormat checkFormat = format != 0 ?
1715 format : mCore->mDefaultBufferFormat;
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001716 uint64_t checkUsage = usage | mCore->mConsumerUsageBits;
John Reckdb164ff2024-04-03 16:59:28 -04001717 bool allocOptionsChanged = false;
1718#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1719 allocOptionsChanged = allocOptionsGenId != mCore->mAdditionalOptionsGenerationId;
1720#endif
Antoine Labour78014f32014-07-15 21:17:03 -07001721 if (checkWidth != allocWidth || checkHeight != allocHeight ||
John Reckdb164ff2024-04-03 16:59:28 -04001722 checkFormat != allocFormat || checkUsage != allocUsage || allocOptionsChanged) {
Antoine Labour78014f32014-07-15 21:17:03 -07001723 // Something changed while we released the lock. Retry.
1724 BQ_LOGV("allocateBuffers: size/format/usage changed while allocating. Retrying.");
1725 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001726 mCore->mIsAllocatingCondition.notify_all();
Dan Stoza29a3e902014-06-20 13:13:57 -07001727 continue;
1728 }
1729
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001730 if (mCore->mFreeSlots.empty()) {
1731 BQ_LOGV("allocateBuffers: a slot was occupied while "
1732 "allocating. Dropping allocated buffer.");
1733 } else {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001734 auto slot = mCore->mFreeSlots.begin();
1735 mCore->clearBufferSlotLocked(*slot); // Clean up the slot first
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001736 mSlots[*slot].mGraphicBuffer = graphicBuffer;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001737 mSlots[*slot].mFence = Fence::NO_FENCE;
John Reckdb164ff2024-04-03 16:59:28 -04001738#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1739 mSlots[*slot].mAdditionalOptionsGenerationId = allocOptionsGenId;
1740#endif
Dan Stoza0de7ea72015-04-23 13:20:51 -07001741
1742 // freeBufferLocked puts this slot on the free slots list. Since
1743 // we then attached a buffer, move the slot to free buffer list.
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001744 mCore->mFreeBuffers.push_front(*slot);
Dan Stoza0de7ea72015-04-23 13:20:51 -07001745
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001746 BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d",
1747 *slot);
Christopher Ferris87e94cd2016-04-26 11:29:08 -07001748
1749 // Make sure the erase is done after all uses of the slot
1750 // iterator since it will be invalid after this point.
1751 mCore->mFreeSlots.erase(slot);
Antoine Labour78014f32014-07-15 21:17:03 -07001752 }
Dan Stoza29a3e902014-06-20 13:13:57 -07001753
Antoine Labour78014f32014-07-15 21:17:03 -07001754 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001755 mCore->mIsAllocatingCondition.notify_all();
Pablo Ceballos9e314332016-01-12 13:49:19 -08001756 VALIDATE_CONSISTENCY();
Jorim Jaggi35b4e382019-03-28 00:44:03 +01001757
1758 // If dequeue is waiting for to allocate a buffer, release the lock until it's not
1759 // waiting anymore so it can use the buffer we just allocated.
1760 while (mDequeueWaitingForAllocation) {
1761 mDequeueWaitingForAllocationCondition.wait(lock);
1762 }
Antoine Labour78014f32014-07-15 21:17:03 -07001763 } // Autolock scope
Dan Stoza29a3e902014-06-20 13:13:57 -07001764 }
1765}
1766
Dan Stoza9de72932015-04-16 17:28:43 -07001767status_t BufferQueueProducer::allowAllocation(bool allow) {
1768 ATRACE_CALL();
1769 BQ_LOGV("allowAllocation: %s", allow ? "true" : "false");
1770
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001771 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza9de72932015-04-16 17:28:43 -07001772 mCore->mAllowAllocation = allow;
1773 return NO_ERROR;
1774}
1775
Dan Stoza812ed062015-06-02 15:45:22 -07001776status_t BufferQueueProducer::setGenerationNumber(uint32_t generationNumber) {
1777 ATRACE_CALL();
1778 BQ_LOGV("setGenerationNumber: %u", generationNumber);
1779
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001780 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza812ed062015-06-02 15:45:22 -07001781 mCore->mGenerationNumber = generationNumber;
1782 return NO_ERROR;
1783}
1784
Dan Stozac6f30bd2015-06-08 09:32:50 -07001785String8 BufferQueueProducer::getConsumerName() const {
1786 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001787 std::lock_guard<std::mutex> lock(mCore->mMutex);
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001788 BQ_LOGV("getConsumerName: %s", mConsumerName.c_str());
Dan Stozac6f30bd2015-06-08 09:32:50 -07001789 return mConsumerName;
1790}
1791
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001792status_t BufferQueueProducer::setSharedBufferMode(bool sharedBufferMode) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001793 ATRACE_CALL();
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001794 BQ_LOGV("setSharedBufferMode: %d", sharedBufferMode);
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001795
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001796 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001797 if (!sharedBufferMode) {
1798 mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001799 }
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001800 mCore->mSharedBufferMode = sharedBufferMode;
Dan Stoza127fc632015-06-30 13:43:32 -07001801 return NO_ERROR;
1802}
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001803
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001804status_t BufferQueueProducer::setAutoRefresh(bool autoRefresh) {
1805 ATRACE_CALL();
1806 BQ_LOGV("setAutoRefresh: %d", autoRefresh);
1807
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001808 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001809
1810 mCore->mAutoRefresh = autoRefresh;
1811 return NO_ERROR;
1812}
1813
Dan Stoza127fc632015-06-30 13:43:32 -07001814status_t BufferQueueProducer::setDequeueTimeout(nsecs_t timeout) {
1815 ATRACE_CALL();
1816 BQ_LOGV("setDequeueTimeout: %" PRId64, timeout);
1817
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001818 std::lock_guard<std::mutex> lock(mCore->mMutex);
Sungtak Lee42a94c62019-05-24 14:27:14 -07001819 bool dequeueBufferCannotBlock =
1820 timeout >= 0 ? false : mCore->mDequeueBufferCannotBlock;
1821 int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode, dequeueBufferCannotBlock,
Pablo Ceballos981066c2016-02-18 12:54:37 -08001822 mCore->mMaxBufferCount) - mCore->getMaxBufferCountLocked();
1823 if (!mCore->adjustAvailableSlotsLocked(delta)) {
1824 BQ_LOGE("setDequeueTimeout: BufferQueue failed to adjust the number of "
1825 "available slots. Delta = %d", delta);
1826 return BAD_VALUE;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001827 }
1828
Pablo Ceballos981066c2016-02-18 12:54:37 -08001829 mDequeueTimeout = timeout;
Sungtak Lee42a94c62019-05-24 14:27:14 -07001830 mCore->mDequeueBufferCannotBlock = dequeueBufferCannotBlock;
1831 if (timeout > 0) {
1832 mCore->mQueueBufferCanDrop = false;
Sungtak Lee3249fb62019-03-02 16:40:47 -08001833 }
Pablo Ceballos9e314332016-01-12 13:49:19 -08001834
Pablo Ceballos981066c2016-02-18 12:54:37 -08001835 VALIDATE_CONSISTENCY();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001836 return NO_ERROR;
1837}
1838
Sungtak Lee3249fb62019-03-02 16:40:47 -08001839status_t BufferQueueProducer::setLegacyBufferDrop(bool drop) {
1840 ATRACE_CALL();
1841 BQ_LOGV("setLegacyBufferDrop: drop = %d", drop);
1842
1843 std::lock_guard<std::mutex> lock(mCore->mMutex);
1844 mCore->mLegacyBufferDrop = drop;
1845 return NO_ERROR;
1846}
1847
Dan Stoza50101d02016-04-07 16:53:23 -07001848status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
John Reck1a61da52016-04-28 13:18:15 -07001849 sp<Fence>* outFence, float outTransformMatrix[16]) {
Dan Stoza50101d02016-04-07 16:53:23 -07001850 ATRACE_CALL();
Dan Stoza50101d02016-04-07 16:53:23 -07001851
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001852 std::lock_guard<std::mutex> lock(mCore->mMutex);
John Reckd2c4a4a2024-02-07 10:31:09 -05001853 BQ_LOGV("getLastQueuedBuffer, slot=%d", mCore->mLastQueuedSlot);
1854
Dan Stoza50101d02016-04-07 16:53:23 -07001855 if (mCore->mLastQueuedSlot == BufferItem::INVALID_BUFFER_SLOT) {
1856 *outBuffer = nullptr;
1857 *outFence = Fence::NO_FENCE;
1858 return NO_ERROR;
1859 }
1860
1861 *outBuffer = mSlots[mCore->mLastQueuedSlot].mGraphicBuffer;
1862 *outFence = mLastQueueBufferFence;
1863
John Reck1a61da52016-04-28 13:18:15 -07001864 // Currently only SurfaceFlinger internally ever changes
1865 // GLConsumer's filtering mode, so we just use 'true' here as
1866 // this is slightly specialized for the current client of this API,
1867 // which does want filtering.
1868 GLConsumer::computeTransformMatrix(outTransformMatrix,
1869 mSlots[mCore->mLastQueuedSlot].mGraphicBuffer, mLastQueuedCrop,
1870 mLastQueuedTransform, true /* filter */);
1871
Dan Stoza50101d02016-04-07 16:53:23 -07001872 return NO_ERROR;
1873}
1874
John Reckf0f13e82021-05-18 00:42:56 -04001875status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer, sp<Fence>* outFence,
1876 Rect* outRect, uint32_t* outTransform) {
1877 ATRACE_CALL();
John Reckf0f13e82021-05-18 00:42:56 -04001878
1879 std::lock_guard<std::mutex> lock(mCore->mMutex);
John Reckd2c4a4a2024-02-07 10:31:09 -05001880 BQ_LOGV("getLastQueuedBuffer, slot=%d", mCore->mLastQueuedSlot);
1881 if (mCore->mLastQueuedSlot == BufferItem::INVALID_BUFFER_SLOT ||
1882 mSlots[mCore->mLastQueuedSlot].mBufferState.isDequeued()) {
John Reckf0f13e82021-05-18 00:42:56 -04001883 *outBuffer = nullptr;
1884 *outFence = Fence::NO_FENCE;
1885 return NO_ERROR;
1886 }
1887
1888 *outBuffer = mSlots[mCore->mLastQueuedSlot].mGraphicBuffer;
1889 *outFence = mLastQueueBufferFence;
1890 *outRect = mLastQueuedCrop;
1891 *outTransform = mLastQueuedTransform;
1892
1893 return NO_ERROR;
1894}
1895
Brian Anderson3890c392016-07-25 12:48:08 -07001896void BufferQueueProducer::getFrameTimestamps(FrameEventHistoryDelta* outDelta) {
1897 addAndGetFrameTimestamps(nullptr, outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07001898}
Pablo Ceballosce796e72016-02-04 19:10:51 -08001899
Brian Anderson3890c392016-07-25 12:48:08 -07001900void BufferQueueProducer::addAndGetFrameTimestamps(
Brian Andersond6927fb2016-07-23 23:37:30 -07001901 const NewFrameEventsEntry* newTimestamps,
Brian Anderson3890c392016-07-25 12:48:08 -07001902 FrameEventHistoryDelta* outDelta) {
1903 if (newTimestamps == nullptr && outDelta == nullptr) {
1904 return;
Brian Andersond6927fb2016-07-23 23:37:30 -07001905 }
1906
1907 ATRACE_CALL();
1908 BQ_LOGV("addAndGetFrameTimestamps");
1909 sp<IConsumerListener> listener;
Pablo Ceballosce796e72016-02-04 19:10:51 -08001910 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001911 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballosce796e72016-02-04 19:10:51 -08001912 listener = mCore->mConsumerListener;
1913 }
Yi Kong48a619f2018-06-05 16:34:59 -07001914 if (listener != nullptr) {
Brian Anderson3890c392016-07-25 12:48:08 -07001915 listener->addAndGetFrameTimestamps(newTimestamps, outDelta);
Pablo Ceballosce796e72016-02-04 19:10:51 -08001916 }
Pablo Ceballosce796e72016-02-04 19:10:51 -08001917}
1918
Dan Stoza289ade12014-02-28 11:17:17 -08001919void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
1920 // If we're here, it means that a producer we were connected to died.
1921 // We're guaranteed that we are still connected to it because we remove
1922 // this callback upon disconnect. It's therefore safe to read mConnectedApi
1923 // without synchronization here.
1924 int api = mCore->mConnectedApi;
1925 disconnect(api);
1926}
1927
Pablo Ceballos8e3e92b2016-06-27 17:56:53 -07001928status_t BufferQueueProducer::getUniqueId(uint64_t* outId) const {
1929 BQ_LOGV("getUniqueId");
1930
1931 *outId = mCore->mUniqueId;
1932 return NO_ERROR;
1933}
1934
Chia-I Wue2786ea2017-08-07 10:36:08 -07001935status_t BufferQueueProducer::getConsumerUsage(uint64_t* outUsage) const {
1936 BQ_LOGV("getConsumerUsage");
1937
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001938 std::lock_guard<std::mutex> lock(mCore->mMutex);
Chia-I Wue2786ea2017-08-07 10:36:08 -07001939 *outUsage = mCore->mConsumerUsageBits;
1940 return NO_ERROR;
1941}
1942
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001943status_t BufferQueueProducer::setAutoPrerotation(bool autoPrerotation) {
1944 ATRACE_CALL();
1945 BQ_LOGV("setAutoPrerotation: %d", autoPrerotation);
1946
1947 std::lock_guard<std::mutex> lock(mCore->mMutex);
1948
1949 mCore->mAutoPrerotation = autoPrerotation;
1950 return NO_ERROR;
1951}
1952
Ady Abraham107788e2023-10-17 12:31:08 -07001953#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
Ady Abraham6cdd3fd2023-09-07 18:45:58 -07001954status_t BufferQueueProducer::setFrameRate(float frameRate, int8_t compatibility,
1955 int8_t changeFrameRateStrategy) {
1956 ATRACE_CALL();
1957 BQ_LOGV("setFrameRate: %.2f", frameRate);
1958
1959 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
1960 "BufferQueueProducer::setFrameRate")) {
1961 return BAD_VALUE;
1962 }
1963
1964 sp<IConsumerListener> listener;
1965 {
1966 std::lock_guard<std::mutex> lock(mCore->mMutex);
1967 listener = mCore->mConsumerListener;
1968 }
1969 if (listener != nullptr) {
1970 listener->onSetFrameRate(frameRate, compatibility, changeFrameRateStrategy);
1971 }
1972 return NO_ERROR;
1973}
1974#endif
1975
John Reckdb164ff2024-04-03 16:59:28 -04001976#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1977status_t BufferQueueProducer::setAdditionalOptions(
1978 const std::vector<gui::AdditionalOptions>& options) {
1979 ATRACE_CALL();
1980 BQ_LOGV("setAdditionalOptions, size = %zu", options.size());
1981
1982 if (!GraphicBufferAllocator::get().supportsAdditionalOptions()) {
1983 return INVALID_OPERATION;
1984 }
1985
1986 std::lock_guard<std::mutex> lock(mCore->mMutex);
1987
1988 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1989 BQ_LOGE("setAdditionalOptions: BufferQueue not connected, cannot set additional options");
1990 return NO_INIT;
1991 }
1992
1993 if (mCore->mAdditionalOptions != options) {
1994 mCore->mAdditionalOptions = options;
1995 mCore->mAdditionalOptionsGenerationId++;
1996 }
1997 return NO_ERROR;
1998}
1999#endif
2000
Dan Stoza289ade12014-02-28 11:17:17 -08002001} // namespace android