blob: bcf61e45ded7aa4c30dc6c63c7c50113c660bfe9 [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
Jim Shargoa62f0512025-02-27 22:58:38 +0000367 using namespace com::android::graphics::libgui::flags;
368 bool flagGatedBufferHasBeenQueued =
369 bq_always_use_max_dequeued_buffer_count() || mCore->mBufferHasBeenQueued;
370 if (flagGatedBufferHasBeenQueued && dequeuedCount >= mCore->mMaxDequeuedBufferCount) {
Sungtak Leeaf141242019-04-24 16:36:44 -0700371 // Supress error logs when timeout is non-negative.
372 if (mDequeueTimeout < 0) {
373 BQ_LOGE("%s: attempting to exceed the max dequeued buffer "
374 "count (%d)", callerString,
375 mCore->mMaxDequeuedBufferCount);
376 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800377 return INVALID_OPERATION;
378 }
379
Dan Stoza0de7ea72015-04-23 13:20:51 -0700380 *found = BufferQueueCore::INVALID_BUFFER_SLOT;
381
Dan Stozaae3c3682014-04-18 15:43:35 -0700382 // If we disconnect and reconnect quickly, we can be in a state where
383 // our slots are empty but we have many buffers in the queue. This can
384 // cause us to run out of memory if we outrun the consumer. Wait here if
385 // it looks like we have too many buffers queued up.
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800386 const int maxBufferCount = mCore->getMaxBufferCountLocked();
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700387 bool tooManyBuffers = mCore->mQueue.size()
388 > static_cast<size_t>(maxBufferCount);
Dan Stozaae3c3682014-04-18 15:43:35 -0700389 if (tooManyBuffers) {
Dan Stoza5ecfb682016-01-04 17:01:02 -0800390 BQ_LOGV("%s: queue size is %zu, waiting", callerString,
Dan Stozaae3c3682014-04-18 15:43:35 -0700391 mCore->mQueue.size());
Dan Stoza0de7ea72015-04-23 13:20:51 -0700392 } else {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700393 // If in shared buffer mode and a shared buffer exists, always
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700394 // return it.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700395 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot !=
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700396 BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700397 *found = mCore->mSharedBufferSlot;
Dan Stoza5ecfb682016-01-04 17:01:02 -0800398 } else {
399 if (caller == FreeSlotCaller::Dequeue) {
400 // If we're calling this from dequeue, prefer free buffers
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800401 int slot = getFreeBufferLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800402 if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
403 *found = slot;
404 } else if (mCore->mAllowAllocation) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800405 *found = getFreeSlotLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800406 }
407 } else {
408 // If we're calling this from attach, prefer free slots
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800409 int slot = getFreeSlotLocked();
Dan Stoza5ecfb682016-01-04 17:01:02 -0800410 if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
411 *found = slot;
412 } else {
413 *found = getFreeBufferLocked();
414 }
Dan Stoza0de7ea72015-04-23 13:20:51 -0700415 }
416 }
Dan Stozaae3c3682014-04-18 15:43:35 -0700417 }
418
419 // If no buffer is found, or if the queue has too many buffers
420 // outstanding, wait for a buffer to be acquired or released, or for the
421 // max buffer count to change.
422 tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
423 tooManyBuffers;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800424 if (tryAgain) {
425 // Return an error if we're in non-blocking mode (producer and
426 // consumer are controlled by the application).
427 // However, the consumer is allowed to briefly acquire an extra
428 // buffer (which could cause us to have to wait here), which is
429 // okay, since it is only used to implement an atomic acquire +
430 // release (e.g., in GLConsumer::updateTexImage())
Pablo Ceballosfa455352015-08-12 17:47:47 -0700431 if ((mCore->mDequeueBufferCannotBlock || mCore->mAsyncMode) &&
Dan Stoza9f3053d2014-03-06 15:14:33 -0800432 (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
433 return WOULD_BLOCK;
434 }
Patrick Williams078d7362024-08-27 10:20:39 -0500435#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
436 if (status_t status = waitForBufferRelease(lock, mDequeueTimeout);
437 status == TIMED_OUT) {
438 return TIMED_OUT;
439 }
440#else
Dan Stoza127fc632015-06-30 13:43:32 -0700441 if (mDequeueTimeout >= 0) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200442 std::cv_status result = mCore->mDequeueCondition.wait_for(lock,
443 std::chrono::nanoseconds(mDequeueTimeout));
444 if (result == std::cv_status::timeout) {
445 return TIMED_OUT;
Dan Stoza127fc632015-06-30 13:43:32 -0700446 }
447 } else {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200448 mCore->mDequeueCondition.wait(lock);
Dan Stoza127fc632015-06-30 13:43:32 -0700449 }
Patrick Williams078d7362024-08-27 10:20:39 -0500450#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800451 }
452 } // while (tryAgain)
453
454 return NO_ERROR;
455}
456
Patrick Williams078d7362024-08-27 10:20:39 -0500457#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
458status_t BufferQueueProducer::waitForBufferRelease(std::unique_lock<std::mutex>& lock,
459 nsecs_t timeout) const {
460 if (mDequeueTimeout >= 0) {
461 std::cv_status result =
462 mCore->mDequeueCondition.wait_for(lock, std::chrono::nanoseconds(timeout));
463 if (result == std::cv_status::timeout) {
464 return TIMED_OUT;
465 }
466 } else {
467 mCore->mDequeueCondition.wait(lock);
468 }
469 return OK;
470}
471#endif
472
Ian Elliottd11b0442017-07-18 11:05:49 -0600473status_t BufferQueueProducer::dequeueBuffer(int* outSlot, sp<android::Fence>* outFence,
474 uint32_t width, uint32_t height, PixelFormat format,
475 uint64_t usage, uint64_t* outBufferAge,
476 FrameEventHistoryDelta* outTimestamps) {
Dan Stoza289ade12014-02-28 11:17:17 -0800477 ATRACE_CALL();
478 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200479 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800480 mConsumerName = mCore->mConsumerName;
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700481
482 if (mCore->mIsAbandoned) {
483 BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
484 return NO_INIT;
485 }
486
487 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
488 BQ_LOGE("dequeueBuffer: BufferQueue has no connected producer");
489 return NO_INIT;
490 }
Dan Stoza289ade12014-02-28 11:17:17 -0800491 } // Autolock scope
492
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700493 BQ_LOGV("dequeueBuffer: w=%u h=%u format=%#x, usage=%#" PRIx64, width, height, format, usage);
Dan Stoza289ade12014-02-28 11:17:17 -0800494
495 if ((width && !height) || (!width && height)) {
496 BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
497 return BAD_VALUE;
498 }
499
500 status_t returnFlags = NO_ERROR;
Jim Shargo90842182024-11-14 00:49:27 +0000501#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800502 EGLDisplay eglDisplay = EGL_NO_DISPLAY;
503 EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000504#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800505 bool attachedByConsumer = false;
Dan Stoza289ade12014-02-28 11:17:17 -0800506
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000507 sp<IConsumerListener> listener;
508 bool callOnFrameDequeued = false;
509 uint64_t bufferId = 0; // Only used if callOnFrameDequeued == true
John Reckdb164ff2024-04-03 16:59:28 -0400510#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
511 std::vector<gui::AdditionalOptions> allocOptions;
512 uint32_t allocOptionsGenId = 0;
513#endif
514
Dan Stoza289ade12014-02-28 11:17:17 -0800515 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200516 std::unique_lock<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800517
Jorim Jaggi35b4e382019-03-28 00:44:03 +0100518 // If we don't have a free buffer, but we are currently allocating, we wait until allocation
519 // is finished such that we don't allocate in parallel.
520 if (mCore->mFreeBuffers.empty() && mCore->mIsAllocating) {
521 mDequeueWaitingForAllocation = true;
522 mCore->waitWhileAllocatingLocked(lock);
523 mDequeueWaitingForAllocation = false;
524 mDequeueWaitingForAllocationCondition.notify_all();
525 }
Dan Stoza289ade12014-02-28 11:17:17 -0800526
527 if (format == 0) {
528 format = mCore->mDefaultBufferFormat;
529 }
530
531 // Enable the usage bits the consumer requested
532 usage |= mCore->mConsumerUsageBits;
533
Dan Stoza9de72932015-04-16 17:28:43 -0700534 const bool useDefaultSize = !width && !height;
535 if (useDefaultSize) {
536 width = mCore->mDefaultWidth;
537 height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -0700538 if (mCore->mAutoPrerotation &&
539 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
540 std::swap(width, height);
541 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800542 }
Dan Stoza289ade12014-02-28 11:17:17 -0800543
Pablo Ceballos981066c2016-02-18 12:54:37 -0800544 int found = BufferItem::INVALID_BUFFER_SLOT;
Dan Stoza9de72932015-04-16 17:28:43 -0700545 while (found == BufferItem::INVALID_BUFFER_SLOT) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200546 status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Dequeue, lock, &found);
Dan Stoza9de72932015-04-16 17:28:43 -0700547 if (status != NO_ERROR) {
548 return status;
549 }
550
551 // This should not happen
552 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
553 BQ_LOGE("dequeueBuffer: no available buffer slots");
554 return -EBUSY;
555 }
556
557 const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
558
559 // If we are not allowed to allocate new buffers,
560 // waitForFreeSlotThenRelock must have returned a slot containing a
561 // buffer. If this buffer would require reallocation to meet the
562 // requested attributes, we free it and attempt to get another one.
563 if (!mCore->mAllowAllocation) {
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700564 if (buffer->needsReallocation(width, height, format, BQ_LAYER_COUNT, usage)) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700565 if (mCore->mSharedBufferSlot == found) {
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700566 BQ_LOGE("dequeueBuffer: cannot re-allocate a sharedbuffer");
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700567 return BAD_VALUE;
568 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800569 mCore->mFreeSlots.insert(found);
570 mCore->clearBufferSlotLocked(found);
Dan Stoza9de72932015-04-16 17:28:43 -0700571 found = BufferItem::INVALID_BUFFER_SLOT;
572 continue;
573 }
574 }
Dan Stoza289ade12014-02-28 11:17:17 -0800575 }
576
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800577 const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800578
John Reckdb164ff2024-04-03 16:59:28 -0400579 bool needsReallocation = buffer == nullptr ||
580 buffer->needsReallocation(width, height, format, BQ_LAYER_COUNT, usage);
581
582#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
583 needsReallocation |= mSlots[found].mAdditionalOptionsGenerationId !=
584 mCore->mAdditionalOptionsGenerationId;
585#endif
586
587 if (mCore->mSharedBufferSlot == found && needsReallocation) {
588 BQ_LOGE("dequeueBuffer: cannot re-allocate a shared buffer");
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800589 return BAD_VALUE;
590 }
591
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700592 if (mCore->mSharedBufferSlot != found) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800593 mCore->mActiveBuffers.insert(found);
594 }
Dan Stoza289ade12014-02-28 11:17:17 -0800595 *outSlot = found;
596 ATRACE_BUFFER_INDEX(found);
597
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800598 attachedByConsumer = mSlots[found].mNeedsReallocation;
599 mSlots[found].mNeedsReallocation = false;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800600
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700601 mSlots[found].mBufferState.dequeue();
602
John Reckdb164ff2024-04-03 16:59:28 -0400603 if (needsReallocation) {
Vishnu Nair14a3c112023-04-21 14:49:47 -0700604 if (CC_UNLIKELY(ATRACE_ENABLED())) {
605 if (buffer == nullptr) {
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +0000606 ATRACE_FORMAT_INSTANT("%s buffer reallocation: null", mConsumerName.c_str());
Vishnu Nair14a3c112023-04-21 14:49:47 -0700607 } else {
608 ATRACE_FORMAT_INSTANT("%s buffer reallocation actual %dx%d format:%d "
609 "layerCount:%d "
610 "usage:%d requested: %dx%d format:%d layerCount:%d "
611 "usage:%d ",
Tomasz Wasilczyk02fd95c2023-08-30 17:51:31 +0000612 mConsumerName.c_str(), width, height, format,
Vishnu Nair14a3c112023-04-21 14:49:47 -0700613 BQ_LAYER_COUNT, usage, buffer->getWidth(),
614 buffer->getHeight(), buffer->getPixelFormat(),
615 buffer->getLayerCount(), buffer->getUsage());
616 }
617 }
Dan Stoza289ade12014-02-28 11:17:17 -0800618 mSlots[found].mAcquireCalled = false;
Yi Kong48a619f2018-06-05 16:34:59 -0700619 mSlots[found].mGraphicBuffer = nullptr;
Dan Stoza289ade12014-02-28 11:17:17 -0800620 mSlots[found].mRequestBufferCalled = false;
Jim Shargo90842182024-11-14 00:49:27 +0000621#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800622 mSlots[found].mEglDisplay = EGL_NO_DISPLAY;
623 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000624#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800625 mSlots[found].mFence = Fence::NO_FENCE;
Dan Stoza4afd8b62015-02-25 16:49:08 -0800626 mCore->mBufferAge = 0;
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700627 mCore->mIsAllocating = true;
John Reckdb164ff2024-04-03 16:59:28 -0400628#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
629 allocOptions = mCore->mAdditionalOptions;
630 allocOptionsGenId = mCore->mAdditionalOptionsGenerationId;
631#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800632
633 returnFlags |= BUFFER_NEEDS_REALLOCATION;
Dan Stoza4afd8b62015-02-25 16:49:08 -0800634 } else {
635 // We add 1 because that will be the frame number when this buffer
636 // is queued
Mathias Agopiancb496ac2017-05-22 14:21:00 -0700637 mCore->mBufferAge = mCore->mFrameCounter + 1 - mSlots[found].mFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -0800638 }
639
Dan Stoza800b41a2015-04-28 14:20:04 -0700640 BQ_LOGV("dequeueBuffer: setting buffer age to %" PRIu64,
641 mCore->mBufferAge);
Dan Stoza4afd8b62015-02-25 16:49:08 -0800642
Yi Kong48a619f2018-06-05 16:34:59 -0700643 if (CC_UNLIKELY(mSlots[found].mFence == nullptr)) {
Dan Stoza289ade12014-02-28 11:17:17 -0800644 BQ_LOGE("dequeueBuffer: about to return a NULL fence - "
645 "slot=%d w=%d h=%d format=%u",
646 found, buffer->width, buffer->height, buffer->format);
647 }
648
Jim Shargo90842182024-11-14 00:49:27 +0000649#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800650 eglDisplay = mSlots[found].mEglDisplay;
651 eglFence = mSlots[found].mEglFence;
Jim Shargo90842182024-11-14 00:49:27 +0000652#endif
Pablo Ceballos28c65ad2016-06-01 15:03:21 -0700653 // Don't return a fence in shared buffer mode, except for the first
654 // frame.
655 *outFence = (mCore->mSharedBufferMode &&
656 mCore->mSharedBufferSlot == found) ?
657 Fence::NO_FENCE : mSlots[found].mFence;
Jim Shargo90842182024-11-14 00:49:27 +0000658#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800659 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000660#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800661 mSlots[found].mFence = Fence::NO_FENCE;
Pablo Ceballos28c65ad2016-06-01 15:03:21 -0700662
663 // If shared buffer mode has just been enabled, cache the slot of the
664 // first buffer that is dequeued and mark it as the shared buffer.
665 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
666 BufferQueueCore::INVALID_BUFFER_SLOT) {
667 mCore->mSharedBufferSlot = found;
668 mSlots[found].mBufferState.mShared = true;
669 }
Adithya Srinivasana820af92019-11-01 13:55:17 -0700670
671 if (!(returnFlags & BUFFER_NEEDS_REALLOCATION)) {
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000672 callOnFrameDequeued = true;
673 bufferId = mSlots[*outSlot].mGraphicBuffer->getId();
Adithya Srinivasana820af92019-11-01 13:55:17 -0700674 }
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000675
676 listener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -0800677 } // Autolock scope
678
679 if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
Dan Stoza29a3e902014-06-20 13:13:57 -0700680 BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
John Reckdb164ff2024-04-03 16:59:28 -0400681
682#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
683 std::vector<GraphicBufferAllocator::AdditionalOptions> tempOptions;
684 tempOptions.reserve(allocOptions.size());
685 for (const auto& it : allocOptions) {
686 tempOptions.emplace_back(it.name.c_str(), it.value);
687 }
688 const GraphicBufferAllocator::AllocationRequest allocRequest = {
689 .importBuffer = true,
690 .width = width,
691 .height = height,
692 .format = format,
693 .layerCount = BQ_LAYER_COUNT,
694 .usage = usage,
695 .requestorName = {mConsumerName.c_str(), mConsumerName.size()},
696 .extras = std::move(tempOptions),
697 };
Anton Ivanov8ed86592025-02-20 11:52:50 -0800698 sp<GraphicBuffer> graphicBuffer = sp<GraphicBuffer>::make(allocRequest);
John Reckdb164ff2024-04-03 16:59:28 -0400699#else
Tomasz Wasilczykf2add402023-08-11 00:06:51 +0000700 sp<GraphicBuffer> graphicBuffer =
Anton Ivanov8ed86592025-02-20 11:52:50 -0800701 sp<GraphicBuffer>::make(width, height, format, BQ_LAYER_COUNT, usage,
702 std::string{mConsumerName.c_str(), mConsumerName.size()});
John Reckdb164ff2024-04-03 16:59:28 -0400703#endif
Mathias Agopian0556d792017-03-22 15:49:32 -0700704
705 status_t error = graphicBuffer->initCheck();
706
Dan Stoza289ade12014-02-28 11:17:17 -0800707 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200708 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -0800709
Chia-I Wufeec3b12017-05-25 09:34:56 -0700710 if (error == NO_ERROR && !mCore->mIsAbandoned) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700711 graphicBuffer->setGenerationNumber(mCore->mGenerationNumber);
712 mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
John Reckdb164ff2024-04-03 16:59:28 -0400713#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
714 mSlots[*outSlot].mAdditionalOptionsGenerationId = allocOptionsGenId;
715#endif
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000716 callOnFrameDequeued = true;
717 bufferId = mSlots[*outSlot].mGraphicBuffer->getId();
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700718 }
719
720 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200721 mCore->mIsAllocatingCondition.notify_all();
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700722
Chia-I Wufeec3b12017-05-25 09:34:56 -0700723 if (error != NO_ERROR) {
Pablo Ceballos0a068092016-06-29 15:08:33 -0700724 mCore->mFreeSlots.insert(*outSlot);
725 mCore->clearBufferSlotLocked(*outSlot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700726 BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
727 return error;
728 }
729
Dan Stoza289ade12014-02-28 11:17:17 -0800730 if (mCore->mIsAbandoned) {
Pablo Ceballos0a068092016-06-29 15:08:33 -0700731 mCore->mFreeSlots.insert(*outSlot);
732 mCore->clearBufferSlotLocked(*outSlot);
Dan Stoza289ade12014-02-28 11:17:17 -0800733 BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
734 return NO_INIT;
735 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800736
Pablo Ceballos9e314332016-01-12 13:49:19 -0800737 VALIDATE_CONSISTENCY();
Dan Stoza289ade12014-02-28 11:17:17 -0800738 } // Autolock scope
739 }
740
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000741 if (listener != nullptr && callOnFrameDequeued) {
742 listener->onFrameDequeued(bufferId);
743 }
744
Dan Stoza9f3053d2014-03-06 15:14:33 -0800745 if (attachedByConsumer) {
746 returnFlags |= BUFFER_NEEDS_REALLOCATION;
747 }
748
Jim Shargo90842182024-11-14 00:49:27 +0000749#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza289ade12014-02-28 11:17:17 -0800750 if (eglFence != EGL_NO_SYNC_KHR) {
751 EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0,
752 1000000000);
753 // If something goes wrong, log the error, but return the buffer without
754 // synchronizing access to it. It's too late at this point to abort the
755 // dequeue operation.
756 if (result == EGL_FALSE) {
757 BQ_LOGE("dequeueBuffer: error %#x waiting for fence",
758 eglGetError());
759 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
760 BQ_LOGE("dequeueBuffer: timeout waiting for fence");
761 }
762 eglDestroySyncKHR(eglDisplay, eglFence);
763 }
Jim Shargo90842182024-11-14 00:49:27 +0000764#endif
Dan Stoza289ade12014-02-28 11:17:17 -0800765
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700766 BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
767 *outSlot,
Dan Stoza289ade12014-02-28 11:17:17 -0800768 mSlots[*outSlot].mFrameNumber,
tangcheng5614ca02022-04-07 14:26:05 +0800769 mSlots[*outSlot].mGraphicBuffer != nullptr ?
770 mSlots[*outSlot].mGraphicBuffer->handle : nullptr, returnFlags);
Dan Stoza289ade12014-02-28 11:17:17 -0800771
Ian Elliottd11b0442017-07-18 11:05:49 -0600772 if (outBufferAge) {
773 *outBufferAge = mCore->mBufferAge;
774 }
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700775 addAndGetFrameTimestamps(nullptr, outTimestamps);
776
Dan Stoza289ade12014-02-28 11:17:17 -0800777 return returnFlags;
778}
779
Dan Stoza9f3053d2014-03-06 15:14:33 -0800780status_t BufferQueueProducer::detachBuffer(int slot) {
781 ATRACE_CALL();
782 ATRACE_BUFFER_INDEX(slot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700783 BQ_LOGV("detachBuffer: slot %d", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800784
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700785 sp<IConsumerListener> listener;
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000786 bool callOnFrameDetached = false;
787 uint64_t bufferId = 0; // Only used if callOnFrameDetached is true
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700788 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200789 std::lock_guard<std::mutex> lock(mCore->mMutex);
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700790
791 if (mCore->mIsAbandoned) {
792 BQ_LOGE("detachBuffer: BufferQueue has been abandoned");
793 return NO_INIT;
794 }
795
796 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
797 BQ_LOGE("detachBuffer: BufferQueue has no connected producer");
798 return NO_INIT;
799 }
800
801 if (mCore->mSharedBufferMode || mCore->mSharedBufferSlot == slot) {
802 BQ_LOGE("detachBuffer: cannot detach a buffer in shared buffer mode");
803 return BAD_VALUE;
804 }
805
Jim Shargo2e614a42024-10-02 19:31:53 +0000806 const int totalSlotCount = mCore->getTotalSlotCountLocked();
807 if (slot < 0 || slot >= totalSlotCount) {
808 BQ_LOGE("detachBuffer: slot index %d out of range [0, %d)", slot, totalSlotCount);
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700809 return BAD_VALUE;
810 } else if (!mSlots[slot].mBufferState.isDequeued()) {
Darwin Huang29936fa2021-09-08 18:29:18 +0000811 // TODO(http://b/140581935): This message is BQ_LOGW because it
812 // often logs when no actionable errors are present. Return to
813 // using BQ_LOGE after ensuring this only logs during errors.
814 BQ_LOGW("detachBuffer: slot %d is not owned by the producer "
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700815 "(state = %s)", slot, mSlots[slot].mBufferState.string());
816 return BAD_VALUE;
817 } else if (!mSlots[slot].mRequestBufferCalled) {
818 BQ_LOGE("detachBuffer: buffer in slot %d has not been requested",
819 slot);
820 return BAD_VALUE;
821 }
822
Adithya Srinivasan2e434382019-10-09 11:43:01 -0700823 listener = mCore->mConsumerListener;
Robert Carrfc069ba2020-04-20 13:26:31 -0700824 auto gb = mSlots[slot].mGraphicBuffer;
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000825 if (gb != nullptr) {
826 callOnFrameDetached = true;
827 bufferId = gb->getId();
Adithya Srinivasan2e434382019-10-09 11:43:01 -0700828 }
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700829 mSlots[slot].mBufferState.detachProducer();
830 mCore->mActiveBuffers.erase(slot);
831 mCore->mFreeSlots.insert(slot);
832 mCore->clearBufferSlotLocked(slot);
Patrick Williams078d7362024-08-27 10:20:39 -0500833#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
834 mCore->notifyBufferReleased();
835#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200836 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -0500837#endif
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700838 VALIDATE_CONSISTENCY();
Dan Stoza9f3053d2014-03-06 15:14:33 -0800839 }
840
Shuzhen Wang266f31a2023-07-24 22:45:44 +0000841 if (listener != nullptr && callOnFrameDetached) {
842 listener->onFrameDetached(bufferId);
843 }
844
Yi Kong48a619f2018-06-05 16:34:59 -0700845 if (listener != nullptr) {
Eino-Ville Talvala93dd0512016-06-10 14:21:02 -0700846 listener->onBuffersReleased();
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700847 }
Pablo Ceballos981066c2016-02-18 12:54:37 -0800848
Dan Stoza9f3053d2014-03-06 15:14:33 -0800849 return NO_ERROR;
850}
851
Dan Stozad9822a32014-03-28 15:25:31 -0700852status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
853 sp<Fence>* outFence) {
854 ATRACE_CALL();
855
Yi Kong48a619f2018-06-05 16:34:59 -0700856 if (outBuffer == nullptr) {
Dan Stozad9822a32014-03-28 15:25:31 -0700857 BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
858 return BAD_VALUE;
Yi Kong48a619f2018-06-05 16:34:59 -0700859 } else if (outFence == nullptr) {
Dan Stozad9822a32014-03-28 15:25:31 -0700860 BQ_LOGE("detachNextBuffer: outFence must not be NULL");
861 return BAD_VALUE;
862 }
863
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700864 sp<IConsumerListener> listener;
865 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200866 std::unique_lock<std::mutex> lock(mCore->mMutex);
Dan Stozad9822a32014-03-28 15:25:31 -0700867
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700868 if (mCore->mIsAbandoned) {
869 BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
870 return NO_INIT;
871 }
872
873 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
874 BQ_LOGE("detachNextBuffer: BufferQueue has no connected producer");
875 return NO_INIT;
876 }
877
878 if (mCore->mSharedBufferMode) {
879 BQ_LOGE("detachNextBuffer: cannot detach a buffer in shared buffer "
880 "mode");
881 return BAD_VALUE;
882 }
883
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200884 mCore->waitWhileAllocatingLocked(lock);
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700885
886 if (mCore->mFreeBuffers.empty()) {
887 return NO_MEMORY;
888 }
889
890 int found = mCore->mFreeBuffers.front();
891 mCore->mFreeBuffers.remove(found);
892 mCore->mFreeSlots.insert(found);
893
894 BQ_LOGV("detachNextBuffer detached slot %d", found);
895
896 *outBuffer = mSlots[found].mGraphicBuffer;
897 *outFence = mSlots[found].mFence;
898 mCore->clearBufferSlotLocked(found);
899 VALIDATE_CONSISTENCY();
900 listener = mCore->mConsumerListener;
Dan Stozad9822a32014-03-28 15:25:31 -0700901 }
902
Yi Kong48a619f2018-06-05 16:34:59 -0700903 if (listener != nullptr) {
Eino-Ville Talvala2672dec2017-06-13 16:39:11 -0700904 listener->onBuffersReleased();
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700905 }
Pablo Ceballos981066c2016-02-18 12:54:37 -0800906
Dan Stozad9822a32014-03-28 15:25:31 -0700907 return NO_ERROR;
908}
909
Dan Stoza9f3053d2014-03-06 15:14:33 -0800910status_t BufferQueueProducer::attachBuffer(int* outSlot,
911 const sp<android::GraphicBuffer>& buffer) {
912 ATRACE_CALL();
913
Yi Kong48a619f2018-06-05 16:34:59 -0700914 if (outSlot == nullptr) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700915 BQ_LOGE("attachBuffer: outSlot must not be NULL");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800916 return BAD_VALUE;
Yi Kong48a619f2018-06-05 16:34:59 -0700917 } else if (buffer == nullptr) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700918 BQ_LOGE("attachBuffer: cannot attach NULL buffer");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800919 return BAD_VALUE;
920 }
921
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200922 std::unique_lock<std::mutex> lock(mCore->mMutex);
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700923
924 if (mCore->mIsAbandoned) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700925 BQ_LOGE("attachBuffer: BufferQueue has been abandoned");
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700926 return NO_INIT;
927 }
928
929 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700930 BQ_LOGE("attachBuffer: BufferQueue has no connected producer");
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700931 return NO_INIT;
932 }
Dan Stoza9f3053d2014-03-06 15:14:33 -0800933
Pablo Ceballos3559fbf2016-03-17 15:50:23 -0700934 if (mCore->mSharedBufferMode) {
935 BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode");
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700936 return BAD_VALUE;
937 }
938
Dan Stoza812ed062015-06-02 15:45:22 -0700939 if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
940 BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
941 "[queue %u]", buffer->getGenerationNumber(),
942 mCore->mGenerationNumber);
943 return BAD_VALUE;
944 }
945
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200946 mCore->waitWhileAllocatingLocked(lock);
Pablo Ceballos583b1b32015-09-03 18:23:52 -0700947
Dan Stoza9f3053d2014-03-06 15:14:33 -0800948 status_t returnFlags = NO_ERROR;
949 int found;
Jorim Jaggi6ae55032019-04-02 02:27:44 +0200950 status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Attach, lock, &found);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800951 if (status != NO_ERROR) {
952 return status;
953 }
954
955 // This should not happen
956 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700957 BQ_LOGE("attachBuffer: no available buffer slots");
Dan Stoza9f3053d2014-03-06 15:14:33 -0800958 return -EBUSY;
959 }
960
961 *outSlot = found;
962 ATRACE_BUFFER_INDEX(*outSlot);
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700963 BQ_LOGV("attachBuffer: returning slot %d flags=%#x",
Dan Stoza9f3053d2014-03-06 15:14:33 -0800964 *outSlot, returnFlags);
965
966 mSlots[*outSlot].mGraphicBuffer = buffer;
Pablo Ceballosccdfd602015-10-07 15:05:45 -0700967 mSlots[*outSlot].mBufferState.attachProducer();
Jim Shargo90842182024-11-14 00:49:27 +0000968#if !COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_GL_FENCE_CLEANUP)
Dan Stoza9f3053d2014-03-06 15:14:33 -0800969 mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
Jim Shargo90842182024-11-14 00:49:27 +0000970#endif
Dan Stoza9f3053d2014-03-06 15:14:33 -0800971 mSlots[*outSlot].mFence = Fence::NO_FENCE;
Dan Stoza2443c792014-03-24 15:03:46 -0700972 mSlots[*outSlot].mRequestBufferCalled = true;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800973 mSlots[*outSlot].mAcquireCalled = false;
Jammy Yu69958b82017-02-22 16:41:38 -0800974 mSlots[*outSlot].mNeedsReallocation = false;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -0800975 mCore->mActiveBuffers.insert(found);
Pablo Ceballos9e314332016-01-12 13:49:19 -0800976 VALIDATE_CONSISTENCY();
Dan Stoza0de7ea72015-04-23 13:20:51 -0700977
Dan Stoza9f3053d2014-03-06 15:14:33 -0800978 return returnFlags;
979}
980
Dan Stoza289ade12014-02-28 11:17:17 -0800981status_t BufferQueueProducer::queueBuffer(int slot,
982 const QueueBufferInput &input, QueueBufferOutput *output) {
983 ATRACE_CALL();
984 ATRACE_BUFFER_INDEX(slot);
985
Brian Andersond6927fb2016-07-23 23:37:30 -0700986 int64_t requestedPresentTimestamp;
Dan Stoza289ade12014-02-28 11:17:17 -0800987 bool isAutoTimestamp;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -0800988 android_dataspace dataSpace;
Pablo Ceballos60d69222015-08-07 14:47:20 -0700989 Rect crop(Rect::EMPTY_RECT);
Dan Stoza289ade12014-02-28 11:17:17 -0800990 int scalingMode;
991 uint32_t transform;
Ruben Brunk1681d952014-06-27 15:51:55 -0700992 uint32_t stickyTransform;
Brian Andersond6927fb2016-07-23 23:37:30 -0700993 sp<Fence> acquireFence;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700994 bool getFrameTimestamps = false;
Brian Andersond6927fb2016-07-23 23:37:30 -0700995 input.deflate(&requestedPresentTimestamp, &isAutoTimestamp, &dataSpace,
Brian Anderson7c3ba8a2016-07-25 12:48:08 -0700996 &crop, &scalingMode, &transform, &acquireFence, &stickyTransform,
997 &getFrameTimestamps);
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700998 const Region& surfaceDamage = input.getSurfaceDamage();
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -0700999 const HdrMetadata& hdrMetadata = input.getHdrMetadata();
Brian Lindahl628cff42024-10-30 11:50:28 -06001000 const std::optional<PictureProfileHandle>& pictureProfileHandle =
1001 input.getPictureProfileHandle();
Dan Stoza289ade12014-02-28 11:17:17 -08001002
Yi Kong48a619f2018-06-05 16:34:59 -07001003 if (acquireFence == nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -08001004 BQ_LOGE("queueBuffer: fence is NULL");
Jesse Hallde288fe2014-11-04 08:30:48 -08001005 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001006 }
1007
Brian Anderson3d4039d2016-09-23 16:31:30 -07001008 auto acquireFenceTime = std::make_shared<FenceTime>(acquireFence);
1009
Dan Stoza289ade12014-02-28 11:17:17 -08001010 switch (scalingMode) {
1011 case NATIVE_WINDOW_SCALING_MODE_FREEZE:
1012 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
1013 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
1014 case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
1015 break;
1016 default:
1017 BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001018 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001019 }
1020
Dan Stoza8dc55392014-11-04 11:37:46 -08001021 sp<IConsumerListener> frameAvailableListener;
1022 sp<IConsumerListener> frameReplacedListener;
1023 int callbackTicket = 0;
Brian Andersond6927fb2016-07-23 23:37:30 -07001024 uint64_t currentFrameNumber = 0;
Dan Stoza8dc55392014-11-04 11:37:46 -08001025 BufferItem item;
John Reckd2c4a4a2024-02-07 10:31:09 -05001026 int connectedApi;
Mathias Agopianb96661f2024-09-17 11:45:38 -07001027 bool enableEglCpuThrottling = true;
John Reckd2c4a4a2024-02-07 10:31:09 -05001028 sp<Fence> lastQueuedFence;
1029
Dan Stoza289ade12014-02-28 11:17:17 -08001030 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001031 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -08001032
1033 if (mCore->mIsAbandoned) {
1034 BQ_LOGE("queueBuffer: BufferQueue has been abandoned");
1035 return NO_INIT;
1036 }
1037
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001038 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1039 BQ_LOGE("queueBuffer: BufferQueue has no connected producer");
1040 return NO_INIT;
1041 }
1042
Jim Shargo2e614a42024-10-02 19:31:53 +00001043 const int totalSlotCount = mCore->getTotalSlotCountLocked();
1044 if (slot < 0 || slot >= totalSlotCount) {
1045 BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)", slot, totalSlotCount);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001046 return BAD_VALUE;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001047 } else if (!mSlots[slot].mBufferState.isDequeued()) {
Dan Stoza289ade12014-02-28 11:17:17 -08001048 BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001049 "(state = %s)", slot, mSlots[slot].mBufferState.string());
Dan Stoza9f3053d2014-03-06 15:14:33 -08001050 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001051 } else if (!mSlots[slot].mRequestBufferCalled) {
1052 BQ_LOGE("queueBuffer: slot %d was queued without requesting "
1053 "a buffer", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001054 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001055 }
1056
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001057 // If shared buffer mode has just been enabled, cache the slot of the
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001058 // first buffer that is queued and mark it as the shared buffer.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001059 if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001060 BufferQueueCore::INVALID_BUFFER_SLOT) {
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001061 mCore->mSharedBufferSlot = slot;
Pablo Ceballos295a9fc2016-03-14 16:02:19 -07001062 mSlots[slot].mBufferState.mShared = true;
1063 }
1064
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001065 BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d"
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -07001066 " validHdrMetadataTypes=0x%x crop=[%d,%d,%d,%d] transform=%#x scale=%s",
1067 slot, mCore->mFrameCounter + 1, requestedPresentTimestamp, dataSpace,
1068 hdrMetadata.validTypes, crop.left, crop.top, crop.right, crop.bottom,
Brian Andersond6927fb2016-07-23 23:37:30 -07001069 transform,
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001070 BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
Dan Stoza289ade12014-02-28 11:17:17 -08001071
1072 const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
1073 Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
Pablo Ceballos60d69222015-08-07 14:47:20 -07001074 Rect croppedRect(Rect::EMPTY_RECT);
Dan Stoza289ade12014-02-28 11:17:17 -08001075 crop.intersect(bufferRect, &croppedRect);
1076 if (croppedRect != crop) {
1077 BQ_LOGE("queueBuffer: crop rect is not contained within the "
1078 "buffer in slot %d", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001079 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001080 }
1081
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001082 // Override UNKNOWN dataspace with consumer default
1083 if (dataSpace == HAL_DATASPACE_UNKNOWN) {
1084 dataSpace = mCore->mDefaultBufferDataSpace;
1085 }
1086
Brian Andersond6927fb2016-07-23 23:37:30 -07001087 mSlots[slot].mFence = acquireFence;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001088 mSlots[slot].mBufferState.queue();
1089
Brian Andersond6927fb2016-07-23 23:37:30 -07001090 // Increment the frame counter and store a local version of it
1091 // for use outside the lock on mCore->mMutex.
Dan Stoza289ade12014-02-28 11:17:17 -08001092 ++mCore->mFrameCounter;
Brian Andersond6927fb2016-07-23 23:37:30 -07001093 currentFrameNumber = mCore->mFrameCounter;
1094 mSlots[slot].mFrameNumber = currentFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -08001095
Dan Stoza289ade12014-02-28 11:17:17 -08001096 item.mAcquireCalled = mSlots[slot].mAcquireCalled;
1097 item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
1098 item.mCrop = crop;
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001099 item.mTransform = transform &
1100 ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
Dan Stoza289ade12014-02-28 11:17:17 -08001101 item.mTransformToDisplayInverse =
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001102 (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
1103 item.mScalingMode = static_cast<uint32_t>(scalingMode);
Brian Andersond6927fb2016-07-23 23:37:30 -07001104 item.mTimestamp = requestedPresentTimestamp;
Dan Stoza289ade12014-02-28 11:17:17 -08001105 item.mIsAutoTimestamp = isAutoTimestamp;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001106 item.mDataSpace = dataSpace;
Courtney Goeltzenleuchter9bad0d72017-12-19 12:34:34 -07001107 item.mHdrMetadata = hdrMetadata;
Brian Lindahl628cff42024-10-30 11:50:28 -06001108 item.mPictureProfileHandle = pictureProfileHandle;
Brian Andersond6927fb2016-07-23 23:37:30 -07001109 item.mFrameNumber = currentFrameNumber;
Dan Stoza289ade12014-02-28 11:17:17 -08001110 item.mSlot = slot;
Brian Andersond6927fb2016-07-23 23:37:30 -07001111 item.mFence = acquireFence;
Brian Anderson3d4039d2016-09-23 16:31:30 -07001112 item.mFenceTime = acquireFenceTime;
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001113 item.mIsDroppable = mCore->mAsyncMode ||
Sungtak Lee45e9e0b2019-05-28 13:38:23 -07001114 (mConsumerIsSurfaceFlinger && mCore->mQueueBufferCanDrop) ||
Sungtak Lee3249fb62019-03-02 16:40:47 -08001115 (mCore->mLegacyBufferDrop && mCore->mQueueBufferCanDrop) ||
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001116 (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == slot);
Dan Stoza5065a552015-03-17 16:23:42 -07001117 item.mSurfaceDamage = surfaceDamage;
Pablo Ceballos06312182015-10-07 16:32:12 -07001118 item.mQueuedBuffer = true;
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001119 item.mAutoRefresh = mCore->mSharedBufferMode && mCore->mAutoRefresh;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001120 item.mApi = mCore->mConnectedApi;
Dan Stoza289ade12014-02-28 11:17:17 -08001121
Ruben Brunk1681d952014-06-27 15:51:55 -07001122 mStickyTransform = stickyTransform;
1123
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001124 // Cache the shared buffer data so that the BufferItem can be recreated.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001125 if (mCore->mSharedBufferMode) {
1126 mCore->mSharedBufferCache.crop = crop;
1127 mCore->mSharedBufferCache.transform = transform;
1128 mCore->mSharedBufferCache.scalingMode = static_cast<uint32_t>(
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001129 scalingMode);
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001130 mCore->mSharedBufferCache.dataspace = dataSpace;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001131 }
1132
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001133 output->bufferReplaced = false;
Dan Stoza289ade12014-02-28 11:17:17 -08001134 if (mCore->mQueue.empty()) {
1135 // When the queue is empty, we can ignore mDequeueBufferCannotBlock
1136 // and simply queue this buffer
1137 mCore->mQueue.push_back(item);
Dan Stoza8dc55392014-11-04 11:37:46 -08001138 frameAvailableListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001139 } else {
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001140 // When the queue is not empty, we need to look at the last buffer
1141 // in the queue to see if we need to replace it
1142 const BufferItem& last = mCore->mQueue.itemAt(
1143 mCore->mQueue.size() - 1);
1144 if (last.mIsDroppable) {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001145
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001146 if (!last.mIsStale) {
1147 mSlots[last.mSlot].mBufferState.freeQueued();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001148
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001149 // After leaving shared buffer mode, the shared buffer will
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001150 // still be around. Mark it as no longer shared if this
1151 // operation causes it to be free.
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001152 if (!mCore->mSharedBufferMode &&
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001153 mSlots[last.mSlot].mBufferState.isFree()) {
1154 mSlots[last.mSlot].mBufferState.mShared = false;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001155 }
1156 // Don't put the shared buffer on the free list.
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001157 if (!mSlots[last.mSlot].mBufferState.isShared()) {
1158 mCore->mActiveBuffers.erase(last.mSlot);
1159 mCore->mFreeBuffers.push_back(last.mSlot);
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001160 output->bufferReplaced = true;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001161 }
Dan Stoza289ade12014-02-28 11:17:17 -08001162 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001163
Steven Thomas862e7532019-07-10 19:21:03 -07001164 // Make sure to merge the damage rect from the frame we're about
1165 // to drop into the new frame's damage rect.
1166 if (last.mSurfaceDamage.bounds() == Rect::INVALID_RECT ||
1167 item.mSurfaceDamage.bounds() == Rect::INVALID_RECT) {
1168 item.mSurfaceDamage = Region::INVALID_REGION;
1169 } else {
1170 item.mSurfaceDamage |= last.mSurfaceDamage;
1171 }
1172
Dan Stoza289ade12014-02-28 11:17:17 -08001173 // Overwrite the droppable buffer with the incoming one
Pablo Ceballos4d85da42016-04-19 20:11:56 -07001174 mCore->mQueue.editItemAt(mCore->mQueue.size() - 1) = item;
Dan Stoza8dc55392014-11-04 11:37:46 -08001175 frameReplacedListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001176 } else {
1177 mCore->mQueue.push_back(item);
Dan Stoza8dc55392014-11-04 11:37:46 -08001178 frameAvailableListener = mCore->mConsumerListener;
Dan Stoza289ade12014-02-28 11:17:17 -08001179 }
1180 }
1181
1182 mCore->mBufferHasBeenQueued = true;
Patrick Williams078d7362024-08-27 10:20:39 -05001183#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1184 mCore->notifyBufferReleased();
1185#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001186 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001187#endif
Dan Stoza50101d02016-04-07 16:53:23 -07001188 mCore->mLastQueuedSlot = slot;
Dan Stoza289ade12014-02-28 11:17:17 -08001189
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001190 output->width = mCore->mDefaultWidth;
1191 output->height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001192 output->transformHint = mCore->mTransformHintInUse = mCore->mTransformHint;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001193 output->numPendingBuffers = static_cast<uint32_t>(mCore->mQueue.size());
1194 output->nextFrameNumber = mCore->mFrameCounter + 1;
Dan Stoza289ade12014-02-28 11:17:17 -08001195
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001196 ATRACE_INT(mCore->mConsumerName.c_str(), static_cast<int32_t>(mCore->mQueue.size()));
Chong Zhang62493092020-01-15 16:04:47 -08001197#ifndef NO_BINDER
Dan Stozae77c7662016-05-13 11:37:28 -07001198 mCore->mOccupancyTracker.registerOccupancyChange(mCore->mQueue.size());
Chong Zhang62493092020-01-15 16:04:47 -08001199#endif
Dan Stoza8dc55392014-11-04 11:37:46 -08001200 // Take a ticket for the callback functions
1201 callbackTicket = mNextCallbackTicket++;
Dan Stoza0de7ea72015-04-23 13:20:51 -07001202
Pablo Ceballos9e314332016-01-12 13:49:19 -08001203 VALIDATE_CONSISTENCY();
John Reckd2c4a4a2024-02-07 10:31:09 -05001204
1205 connectedApi = mCore->mConnectedApi;
Mathias Agopianb96661f2024-09-17 11:45:38 -07001206 if (flags::bq_producer_throttles_only_async_mode()) {
1207 enableEglCpuThrottling = mCore->mAsyncMode || mCore->mDequeueBufferCannotBlock;
1208 }
John Reckd2c4a4a2024-02-07 10:31:09 -05001209 lastQueuedFence = std::move(mLastQueueBufferFence);
1210
1211 mLastQueueBufferFence = std::move(acquireFence);
1212 mLastQueuedCrop = item.mCrop;
1213 mLastQueuedTransform = item.mTransform;
Dan Stoza289ade12014-02-28 11:17:17 -08001214 } // Autolock scope
1215
Irvel468051e2016-06-13 16:44:44 -07001216 // It is okay not to clear the GraphicBuffer when the consumer is SurfaceFlinger because
1217 // it is guaranteed that the BufferQueue is inside SurfaceFlinger's process and
1218 // there will be no Binder call
1219 if (!mConsumerIsSurfaceFlinger) {
1220 item.mGraphicBuffer.clear();
1221 }
1222
JihCheng Chiu544c5222019-04-02 20:50:58 +08001223 // Update and get FrameEventHistory.
1224 nsecs_t postedTime = systemTime(SYSTEM_TIME_MONOTONIC);
1225 NewFrameEventsEntry newFrameEventsEntry = {
1226 currentFrameNumber,
1227 postedTime,
1228 requestedPresentTimestamp,
1229 std::move(acquireFenceTime)
1230 };
1231 addAndGetFrameTimestamps(&newFrameEventsEntry,
1232 getFrameTimestamps ? &output->frameTimestamps : nullptr);
1233
Dan Stoza8dc55392014-11-04 11:37:46 -08001234 // Call back without the main BufferQueue lock held, but with the callback
1235 // lock held so we can ensure that callbacks occur in order
Mathias Agopian4f6ce7c2017-04-03 17:14:31 -07001236
Mathias Agopian4f6ce7c2017-04-03 17:14:31 -07001237 { // scope for the lock
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001238 std::unique_lock<std::mutex> lock(mCallbackMutex);
Dan Stoza8dc55392014-11-04 11:37:46 -08001239 while (callbackTicket != mCurrentCallbackTicket) {
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001240 mCallbackCondition.wait(lock);
Dan Stoza8dc55392014-11-04 11:37:46 -08001241 }
1242
Yi Kong48a619f2018-06-05 16:34:59 -07001243 if (frameAvailableListener != nullptr) {
Dan Stoza8dc55392014-11-04 11:37:46 -08001244 frameAvailableListener->onFrameAvailable(item);
Yi Kong48a619f2018-06-05 16:34:59 -07001245 } else if (frameReplacedListener != nullptr) {
Dan Stoza8dc55392014-11-04 11:37:46 -08001246 frameReplacedListener->onFrameReplaced(item);
1247 }
1248
1249 ++mCurrentCallbackTicket;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001250 mCallbackCondition.notify_all();
Dan Stoza289ade12014-02-28 11:17:17 -08001251 }
1252
Yiwei Zhangcb7dd002019-04-16 11:03:01 -07001253 // Wait without lock held
Mathias Agopianb96661f2024-09-17 11:45:38 -07001254 if (connectedApi == NATIVE_WINDOW_API_EGL && enableEglCpuThrottling) {
Yiwei Zhangcb7dd002019-04-16 11:03:01 -07001255 // Waiting here allows for two full buffers to be queued but not a
1256 // third. In the event that frames take varying time, this makes a
1257 // small trade-off in favor of latency rather than throughput.
1258 lastQueuedFence->waitForever("Throttling EGL Production");
1259 }
1260
Dan Stoza289ade12014-02-28 11:17:17 -08001261 return NO_ERROR;
1262}
1263
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001264status_t BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
Dan Stoza289ade12014-02-28 11:17:17 -08001265 ATRACE_CALL();
1266 BQ_LOGV("cancelBuffer: slot %d", slot);
Dan Stoza289ade12014-02-28 11:17:17 -08001267
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001268 sp<IConsumerListener> listener;
1269 bool callOnFrameCancelled = false;
1270 uint64_t bufferId = 0; // Only used if callOnFrameCancelled == true
1271 {
1272 std::lock_guard<std::mutex> lock(mCore->mMutex);
1273
1274 if (mCore->mIsAbandoned) {
1275 BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
1276 return NO_INIT;
1277 }
1278
1279 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1280 BQ_LOGE("cancelBuffer: BufferQueue has no connected producer");
1281 return NO_INIT;
1282 }
1283
1284 if (mCore->mSharedBufferMode) {
1285 BQ_LOGE("cancelBuffer: cannot cancel a buffer in shared buffer mode");
1286 return BAD_VALUE;
1287 }
1288
Jim Shargo2e614a42024-10-02 19:31:53 +00001289 const int totalSlotCount = mCore->getTotalSlotCountLocked();
1290 if (slot < 0 || slot >= totalSlotCount) {
1291 BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)", slot, totalSlotCount);
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001292 return BAD_VALUE;
1293 } else if (!mSlots[slot].mBufferState.isDequeued()) {
1294 BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
1295 "(state = %s)",
1296 slot, mSlots[slot].mBufferState.string());
1297 return BAD_VALUE;
1298 } else if (fence == nullptr) {
1299 BQ_LOGE("cancelBuffer: fence is NULL");
1300 return BAD_VALUE;
1301 }
1302
1303 mSlots[slot].mBufferState.cancel();
1304
1305 // After leaving shared buffer mode, the shared buffer will still be around.
1306 // Mark it as no longer shared if this operation causes it to be free.
1307 if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) {
1308 mSlots[slot].mBufferState.mShared = false;
1309 }
1310
1311 // Don't put the shared buffer on the free list.
1312 if (!mSlots[slot].mBufferState.isShared()) {
1313 mCore->mActiveBuffers.erase(slot);
1314 mCore->mFreeBuffers.push_back(slot);
1315 }
1316
1317 auto gb = mSlots[slot].mGraphicBuffer;
1318 if (gb != nullptr) {
1319 callOnFrameCancelled = true;
1320 bufferId = gb->getId();
1321 }
1322 mSlots[slot].mFence = fence;
Patrick Williams078d7362024-08-27 10:20:39 -05001323#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1324 mCore->notifyBufferReleased();
1325#else
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001326 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001327#endif
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001328 listener = mCore->mConsumerListener;
1329 VALIDATE_CONSISTENCY();
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001330 }
1331
Shuzhen Wang266f31a2023-07-24 22:45:44 +00001332 if (listener != nullptr && callOnFrameCancelled) {
1333 listener->onFrameCancelled(bufferId);
Dan Stoza289ade12014-02-28 11:17:17 -08001334 }
1335
Pablo Ceballos583b1b32015-09-03 18:23:52 -07001336 return NO_ERROR;
Dan Stoza289ade12014-02-28 11:17:17 -08001337}
1338
1339int BufferQueueProducer::query(int what, int *outValue) {
1340 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001341 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza289ade12014-02-28 11:17:17 -08001342
Yi Kong48a619f2018-06-05 16:34:59 -07001343 if (outValue == nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -08001344 BQ_LOGE("query: outValue was NULL");
1345 return BAD_VALUE;
1346 }
1347
1348 if (mCore->mIsAbandoned) {
1349 BQ_LOGE("query: BufferQueue has been abandoned");
1350 return NO_INIT;
1351 }
1352
1353 int value;
1354 switch (what) {
1355 case NATIVE_WINDOW_WIDTH:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001356 value = static_cast<int32_t>(mCore->mDefaultWidth);
Dan Stoza289ade12014-02-28 11:17:17 -08001357 break;
1358 case NATIVE_WINDOW_HEIGHT:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001359 value = static_cast<int32_t>(mCore->mDefaultHeight);
Dan Stoza289ade12014-02-28 11:17:17 -08001360 break;
1361 case NATIVE_WINDOW_FORMAT:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001362 value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
Dan Stoza289ade12014-02-28 11:17:17 -08001363 break;
Craig Donner6ebc46a2016-10-21 15:23:44 -07001364 case NATIVE_WINDOW_LAYER_COUNT:
1365 // All BufferQueue buffers have a single layer.
1366 value = BQ_LAYER_COUNT;
1367 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001368 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001369 value = mCore->getMinUndequeuedBufferCountLocked();
Dan Stoza289ade12014-02-28 11:17:17 -08001370 break;
Ruben Brunk1681d952014-06-27 15:51:55 -07001371 case NATIVE_WINDOW_STICKY_TRANSFORM:
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001372 value = static_cast<int32_t>(mStickyTransform);
Ruben Brunk1681d952014-06-27 15:51:55 -07001373 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001374 case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
1375 value = (mCore->mQueue.size() > 1);
1376 break;
1377 case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
Chia-I Wue2786ea2017-08-07 10:36:08 -07001378 // deprecated; higher 32 bits are truncated
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001379 value = static_cast<int32_t>(mCore->mConsumerUsageBits);
Dan Stoza289ade12014-02-28 11:17:17 -08001380 break;
Eino-Ville Talvala82c6bcc2015-02-19 16:10:43 -08001381 case NATIVE_WINDOW_DEFAULT_DATASPACE:
1382 value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace);
1383 break;
Dan Stoza4afd8b62015-02-25 16:49:08 -08001384 case NATIVE_WINDOW_BUFFER_AGE:
1385 if (mCore->mBufferAge > INT32_MAX) {
1386 value = 0;
1387 } else {
1388 value = static_cast<int32_t>(mCore->mBufferAge);
1389 }
1390 break;
Jiwen 'Steve' Cai20419132017-04-21 18:49:53 -07001391 case NATIVE_WINDOW_CONSUMER_IS_PROTECTED:
1392 value = static_cast<int32_t>(mCore->mConsumerIsProtected);
1393 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001394 default:
1395 return BAD_VALUE;
1396 }
1397
1398 BQ_LOGV("query: %d? %d", what, value);
1399 *outValue = value;
1400 return NO_ERROR;
1401}
1402
Dan Stozaf0eaf252014-03-21 13:05:51 -07001403status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
Dan Stoza289ade12014-02-28 11:17:17 -08001404 int api, bool producerControlledByApp, QueueBufferOutput *output) {
1405 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001406 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballos981066c2016-02-18 12:54:37 -08001407 mConsumerName = mCore->mConsumerName;
1408 BQ_LOGV("connect: api=%d producerControlledByApp=%s", api,
1409 producerControlledByApp ? "true" : "false");
1410
1411 if (mCore->mIsAbandoned) {
1412 BQ_LOGE("connect: BufferQueue has been abandoned");
1413 return NO_INIT;
1414 }
1415
Yi Kong48a619f2018-06-05 16:34:59 -07001416 if (mCore->mConsumerListener == nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -08001417 BQ_LOGE("connect: BufferQueue has no consumer");
1418 return NO_INIT;
1419 }
1420
Yi Kong48a619f2018-06-05 16:34:59 -07001421 if (output == nullptr) {
Pablo Ceballos981066c2016-02-18 12:54:37 -08001422 BQ_LOGE("connect: output was NULL");
1423 return BAD_VALUE;
1424 }
1425
1426 if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
1427 BQ_LOGE("connect: already connected (cur=%d req=%d)",
1428 mCore->mConnectedApi, api);
1429 return BAD_VALUE;
1430 }
1431
1432 int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode,
1433 mDequeueTimeout < 0 ?
1434 mCore->mConsumerControlledByApp && producerControlledByApp : false,
1435 mCore->mMaxBufferCount) -
1436 mCore->getMaxBufferCountLocked();
1437 if (!mCore->adjustAvailableSlotsLocked(delta)) {
1438 BQ_LOGE("connect: BufferQueue failed to adjust the number of available "
1439 "slots. Delta = %d", delta);
1440 return BAD_VALUE;
1441 }
1442
Dan Stoza289ade12014-02-28 11:17:17 -08001443 int status = NO_ERROR;
Pablo Ceballos981066c2016-02-18 12:54:37 -08001444 switch (api) {
1445 case NATIVE_WINDOW_API_EGL:
1446 case NATIVE_WINDOW_API_CPU:
1447 case NATIVE_WINDOW_API_MEDIA:
1448 case NATIVE_WINDOW_API_CAMERA:
1449 mCore->mConnectedApi = api;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001450
1451 output->width = mCore->mDefaultWidth;
1452 output->height = mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001453 output->transformHint = mCore->mTransformHintInUse = mCore->mTransformHint;
Brian Anderson7c3ba8a2016-07-25 12:48:08 -07001454 output->numPendingBuffers =
1455 static_cast<uint32_t>(mCore->mQueue.size());
1456 output->nextFrameNumber = mCore->mFrameCounter + 1;
Shuzhen Wang22f842b2017-01-18 23:02:36 -08001457 output->bufferReplaced = false;
silence_dogoode9d092a2019-06-19 16:14:53 -07001458 output->maxBufferCount = mCore->mMaxBufferCount;
Jim Shargo2e614a42024-10-02 19:31:53 +00001459#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_UNLIMITED_SLOTS)
1460 output->isSlotExpansionAllowed = mCore->mAllowExtendedSlotCount;
1461#endif
Dan Stoza289ade12014-02-28 11:17:17 -08001462
Yi Kong48a619f2018-06-05 16:34:59 -07001463 if (listener != nullptr) {
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001464 // Set up a death notification so that we can disconnect
1465 // automatically if the remote producer dies
Chong Zhang62493092020-01-15 16:04:47 -08001466#ifndef NO_BINDER
Yi Kong48a619f2018-06-05 16:34:59 -07001467 if (IInterface::asBinder(listener)->remoteBinder() != nullptr) {
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001468 status = IInterface::asBinder(listener)->linkToDeath(
Anton Ivanov8ed86592025-02-20 11:52:50 -08001469 sp<IBinder::DeathRecipient>::fromExisting(this));
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001470 if (status != NO_ERROR) {
1471 BQ_LOGE("connect: linkToDeath failed: %s (%d)",
1472 strerror(-status), status);
1473 }
1474 mCore->mLinkedToDeath = listener;
1475 }
Chong Zhang62493092020-01-15 16:04:47 -08001476#endif
Shuzhen Wang067fcd32019-08-14 10:41:12 -07001477 mCore->mConnectedProducerListener = listener;
1478 mCore->mBufferReleasedCbEnabled = listener->needsReleaseNotify();
Sungtak Leecd217472024-07-19 17:17:40 +00001479#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_CONSUMER_ATTACH_CALLBACK)
1480 mCore->mBufferAttachedCbEnabled = listener->needsAttachNotify();
1481#endif
Pablo Ceballos981066c2016-02-18 12:54:37 -08001482 }
Pablo Ceballos981066c2016-02-18 12:54:37 -08001483 break;
1484 default:
1485 BQ_LOGE("connect: unknown API %d", api);
1486 status = BAD_VALUE;
1487 break;
Dan Stoza289ade12014-02-28 11:17:17 -08001488 }
Jayant Chowdharyad9fe272019-03-07 22:36:06 -08001489 mCore->mConnectedPid = BufferQueueThreadState::getCallingPid();
Pablo Ceballos981066c2016-02-18 12:54:37 -08001490 mCore->mBufferHasBeenQueued = false;
1491 mCore->mDequeueBufferCannotBlock = false;
Sungtak Lee3249fb62019-03-02 16:40:47 -08001492 mCore->mQueueBufferCanDrop = false;
1493 mCore->mLegacyBufferDrop = true;
1494 if (mCore->mConsumerControlledByApp && producerControlledByApp) {
1495 mCore->mDequeueBufferCannotBlock = mDequeueTimeout < 0;
1496 mCore->mQueueBufferCanDrop = mDequeueTimeout <= 0;
Dan Stoza127fc632015-06-30 13:43:32 -07001497 }
Dan Stoza289ade12014-02-28 11:17:17 -08001498
Pablo Ceballos981066c2016-02-18 12:54:37 -08001499 mCore->mAllowAllocation = true;
John Reckdb164ff2024-04-03 16:59:28 -04001500#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1501 mCore->mAdditionalOptions.clear();
1502#endif
Pablo Ceballos981066c2016-02-18 12:54:37 -08001503 VALIDATE_CONSISTENCY();
Dan Stoza289ade12014-02-28 11:17:17 -08001504 return status;
1505}
1506
Robert Carr97b9c862016-09-08 13:54:35 -07001507status_t BufferQueueProducer::disconnect(int api, DisconnectMode mode) {
Dan Stoza289ade12014-02-28 11:17:17 -08001508 ATRACE_CALL();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001509 BQ_LOGV("disconnect: api %d", api);
Dan Stoza289ade12014-02-28 11:17:17 -08001510
1511 int status = NO_ERROR;
1512 sp<IConsumerListener> listener;
1513 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001514 std::unique_lock<std::mutex> lock(mCore->mMutex);
Robert Carr97b9c862016-09-08 13:54:35 -07001515
1516 if (mode == DisconnectMode::AllLocal) {
Jayant Chowdharyad9fe272019-03-07 22:36:06 -08001517 if (BufferQueueThreadState::getCallingPid() != mCore->mConnectedPid) {
Robert Carr97b9c862016-09-08 13:54:35 -07001518 return NO_ERROR;
1519 }
1520 api = BufferQueueCore::CURRENTLY_CONNECTED_API;
1521 }
1522
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001523 mCore->waitWhileAllocatingLocked(lock);
Dan Stoza289ade12014-02-28 11:17:17 -08001524
1525 if (mCore->mIsAbandoned) {
1526 // It's not really an error to disconnect after the surface has
1527 // been abandoned; it should just be a no-op.
1528 return NO_ERROR;
1529 }
1530
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001531 if (api == BufferQueueCore::CURRENTLY_CONNECTED_API) {
Chong Zhang5ac51482017-02-16 15:52:33 -08001532 if (mCore->mConnectedApi == NATIVE_WINDOW_API_MEDIA) {
1533 ALOGD("About to force-disconnect API_MEDIA, mode=%d", mode);
1534 }
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001535 api = mCore->mConnectedApi;
Chong Zhang26bb2b12016-03-08 12:08:33 -08001536 // If we're asked to disconnect the currently connected api but
1537 // nobody is connected, it's not really an error.
1538 if (api == BufferQueueCore::NO_CONNECTED_API) {
1539 return NO_ERROR;
1540 }
Chong Zhang1b3a9ac2016-02-29 16:47:47 -08001541 }
1542
Dan Stoza289ade12014-02-28 11:17:17 -08001543 switch (api) {
1544 case NATIVE_WINDOW_API_EGL:
1545 case NATIVE_WINDOW_API_CPU:
1546 case NATIVE_WINDOW_API_MEDIA:
1547 case NATIVE_WINDOW_API_CAMERA:
1548 if (mCore->mConnectedApi == api) {
1549 mCore->freeAllBuffersLocked();
1550
Chong Zhang62493092020-01-15 16:04:47 -08001551#ifndef NO_BINDER
Dan Stoza289ade12014-02-28 11:17:17 -08001552 // Remove our death notification callback if we have one
Yi Kong48a619f2018-06-05 16:34:59 -07001553 if (mCore->mLinkedToDeath != nullptr) {
Dan Stozaf0eaf252014-03-21 13:05:51 -07001554 sp<IBinder> token =
Matthew Bouyack3b8e6b22016-10-03 16:24:26 -07001555 IInterface::asBinder(mCore->mLinkedToDeath);
Dan Stoza289ade12014-02-28 11:17:17 -08001556 // This can fail if we're here because of the death
1557 // notification, but we just ignore it
Anton Ivanov8ed86592025-02-20 11:52:50 -08001558 token->unlinkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Dan Stoza289ade12014-02-28 11:17:17 -08001559 }
Chong Zhang62493092020-01-15 16:04:47 -08001560#endif
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001561 mCore->mSharedBufferSlot =
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001562 BufferQueueCore::INVALID_BUFFER_SLOT;
Yi Kong48a619f2018-06-05 16:34:59 -07001563 mCore->mLinkedToDeath = nullptr;
1564 mCore->mConnectedProducerListener = nullptr;
Dan Stoza289ade12014-02-28 11:17:17 -08001565 mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API;
Robert Carr97b9c862016-09-08 13:54:35 -07001566 mCore->mConnectedPid = -1;
Jesse Hall399184a2014-03-03 15:42:54 -08001567 mCore->mSidebandStream.clear();
Patrick Williams078d7362024-08-27 10:20:39 -05001568#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BUFFER_RELEASE_CHANNEL)
1569 mCore->notifyBufferReleased();
1570#else
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001571 mCore->mDequeueCondition.notify_all();
Patrick Williams078d7362024-08-27 10:20:39 -05001572#endif
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001573 mCore->mAutoPrerotation = false;
John Reckdb164ff2024-04-03 16:59:28 -04001574#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1575 mCore->mAdditionalOptions.clear();
1576#endif
Dan Stoza289ade12014-02-28 11:17:17 -08001577 listener = mCore->mConsumerListener;
Wonsik Kim3e198b22017-04-07 15:43:16 -07001578 } else if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1579 BQ_LOGE("disconnect: not connected (req=%d)", api);
1580 status = NO_INIT;
1581 } else {
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001582 BQ_LOGE("disconnect: still connected to another API "
Dan Stoza289ade12014-02-28 11:17:17 -08001583 "(cur=%d req=%d)", mCore->mConnectedApi, api);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001584 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001585 }
1586 break;
1587 default:
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001588 BQ_LOGE("disconnect: unknown API %d", api);
Dan Stoza9f3053d2014-03-06 15:14:33 -08001589 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -08001590 break;
1591 }
1592 } // Autolock scope
1593
1594 // Call back without lock held
Yi Kong48a619f2018-06-05 16:34:59 -07001595 if (listener != nullptr) {
Dan Stoza289ade12014-02-28 11:17:17 -08001596 listener->onBuffersReleased();
Brian Anderson5ea5e592016-12-01 16:54:33 -08001597 listener->onDisconnect();
Dan Stoza289ade12014-02-28 11:17:17 -08001598 }
1599
1600 return status;
1601}
1602
Jesse Hall399184a2014-03-03 15:42:54 -08001603status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
Wonsik Kimafe30812014-03-31 23:16:08 +09001604 sp<IConsumerListener> listener;
1605 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001606 std::lock_guard<std::mutex> _l(mCore->mMutex);
Wonsik Kimafe30812014-03-31 23:16:08 +09001607 mCore->mSidebandStream = stream;
1608 listener = mCore->mConsumerListener;
1609 } // Autolock scope
1610
Yi Kong48a619f2018-06-05 16:34:59 -07001611 if (listener != nullptr) {
Wonsik Kimafe30812014-03-31 23:16:08 +09001612 listener->onSidebandStreamChanged();
1613 }
Jesse Hall399184a2014-03-03 15:42:54 -08001614 return NO_ERROR;
1615}
1616
Pablo Ceballos567dbbb2015-08-26 18:59:08 -07001617void BufferQueueProducer::allocateBuffers(uint32_t width, uint32_t height,
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001618 PixelFormat format, uint64_t usage) {
Antoine Labour78014f32014-07-15 21:17:03 -07001619 ATRACE_CALL();
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001620
1621 const bool useDefaultSize = !width && !height;
Antoine Labour78014f32014-07-15 21:17:03 -07001622 while (true) {
Antoine Labour78014f32014-07-15 21:17:03 -07001623 uint32_t allocWidth = 0;
1624 uint32_t allocHeight = 0;
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001625 PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001626 uint64_t allocUsage = 0;
Chia-I Wu1dbf0e32018-02-07 14:40:08 -08001627 std::string allocName;
John Reckdb164ff2024-04-03 16:59:28 -04001628#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1629 std::vector<gui::AdditionalOptions> allocOptions;
1630 uint32_t allocOptionsGenId = 0;
1631#endif
Antoine Labour78014f32014-07-15 21:17:03 -07001632 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001633 std::unique_lock<std::mutex> lock(mCore->mMutex);
1634 mCore->waitWhileAllocatingLocked(lock);
Dan Stoza29a3e902014-06-20 13:13:57 -07001635
Dan Stoza9de72932015-04-16 17:28:43 -07001636 if (!mCore->mAllowAllocation) {
1637 BQ_LOGE("allocateBuffers: allocation is not allowed for this "
1638 "BufferQueue");
1639 return;
1640 }
1641
Jorim Jaggi0a3e7842018-07-17 13:48:33 +02001642 // Only allocate one buffer at a time to reduce risks of overlapping an allocation from
1643 // both allocateBuffers and dequeueBuffer.
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001644 if (mCore->mFreeSlots.empty()) {
1645 BQ_LOGV("allocateBuffers: a slot was occupied while "
1646 "allocating. Dropping allocated buffer.");
Antoine Labour78014f32014-07-15 21:17:03 -07001647 return;
1648 }
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001649
Antoine Labour78014f32014-07-15 21:17:03 -07001650 allocWidth = width > 0 ? width : mCore->mDefaultWidth;
1651 allocHeight = height > 0 ? height : mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001652 if (useDefaultSize && mCore->mAutoPrerotation &&
1653 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
1654 std::swap(allocWidth, allocHeight);
1655 }
1656
Antoine Labour78014f32014-07-15 21:17:03 -07001657 allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
1658 allocUsage = usage | mCore->mConsumerUsageBits;
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001659 allocName.assign(mCore->mConsumerName.c_str(), mCore->mConsumerName.size());
Antoine Labour78014f32014-07-15 21:17:03 -07001660
John Reckdb164ff2024-04-03 16:59:28 -04001661#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1662 allocOptions = mCore->mAdditionalOptions;
1663 allocOptionsGenId = mCore->mAdditionalOptionsGenerationId;
1664#endif
1665
Antoine Labour78014f32014-07-15 21:17:03 -07001666 mCore->mIsAllocating = true;
John Reckdb164ff2024-04-03 16:59:28 -04001667
Antoine Labour78014f32014-07-15 21:17:03 -07001668 } // Autolock scope
1669
John Reckdb164ff2024-04-03 16:59:28 -04001670#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1671 std::vector<GraphicBufferAllocator::AdditionalOptions> tempOptions;
1672 tempOptions.reserve(allocOptions.size());
1673 for (const auto& it : allocOptions) {
1674 tempOptions.emplace_back(it.name.c_str(), it.value);
1675 }
1676 const GraphicBufferAllocator::AllocationRequest allocRequest = {
1677 .importBuffer = true,
1678 .width = allocWidth,
1679 .height = allocHeight,
1680 .format = allocFormat,
1681 .layerCount = BQ_LAYER_COUNT,
1682 .usage = allocUsage,
1683 .requestorName = allocName,
1684 .extras = std::move(tempOptions),
1685 };
1686#endif
1687
John Reckdb164ff2024-04-03 16:59:28 -04001688#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
Anton Ivanov8ed86592025-02-20 11:52:50 -08001689 sp<GraphicBuffer> graphicBuffer = sp<GraphicBuffer>::make(allocRequest);
John Reckdb164ff2024-04-03 16:59:28 -04001690#else
Anton Ivanov8ed86592025-02-20 11:52:50 -08001691 sp<GraphicBuffer> graphicBuffer =
1692 sp<GraphicBuffer>::make(allocWidth, allocHeight, allocFormat, BQ_LAYER_COUNT,
1693 allocUsage, allocName);
John Reckdb164ff2024-04-03 16:59:28 -04001694#endif
Mathias Agopian0556d792017-03-22 15:49:32 -07001695
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001696 status_t result = graphicBuffer->initCheck();
Mathias Agopian0556d792017-03-22 15:49:32 -07001697
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001698 if (result != NO_ERROR) {
1699 BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format"
1700 " %u, usage %#" PRIx64 ")", width, height, format, usage);
1701 std::lock_guard<std::mutex> lock(mCore->mMutex);
1702 mCore->mIsAllocating = false;
1703 mCore->mIsAllocatingCondition.notify_all();
1704 return;
Antoine Labour78014f32014-07-15 21:17:03 -07001705 }
1706
1707 { // Autolock scope
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001708 std::unique_lock<std::mutex> lock(mCore->mMutex);
Antoine Labour78014f32014-07-15 21:17:03 -07001709 uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
1710 uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001711 if (useDefaultSize && mCore->mAutoPrerotation &&
1712 (mCore->mTransformHintInUse & NATIVE_WINDOW_TRANSFORM_ROT_90)) {
1713 std::swap(checkWidth, checkHeight);
1714 }
1715
Dan Stoza3be1c6b2014-11-18 10:24:03 -08001716 PixelFormat checkFormat = format != 0 ?
1717 format : mCore->mDefaultBufferFormat;
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001718 uint64_t checkUsage = usage | mCore->mConsumerUsageBits;
John Reckdb164ff2024-04-03 16:59:28 -04001719 bool allocOptionsChanged = false;
1720#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1721 allocOptionsChanged = allocOptionsGenId != mCore->mAdditionalOptionsGenerationId;
1722#endif
Antoine Labour78014f32014-07-15 21:17:03 -07001723 if (checkWidth != allocWidth || checkHeight != allocHeight ||
John Reckdb164ff2024-04-03 16:59:28 -04001724 checkFormat != allocFormat || checkUsage != allocUsage || allocOptionsChanged) {
Antoine Labour78014f32014-07-15 21:17:03 -07001725 // Something changed while we released the lock. Retry.
1726 BQ_LOGV("allocateBuffers: size/format/usage changed while allocating. Retrying.");
1727 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001728 mCore->mIsAllocatingCondition.notify_all();
Dan Stoza29a3e902014-06-20 13:13:57 -07001729 continue;
1730 }
1731
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001732 if (mCore->mFreeSlots.empty()) {
1733 BQ_LOGV("allocateBuffers: a slot was occupied while "
1734 "allocating. Dropping allocated buffer.");
1735 } else {
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001736 auto slot = mCore->mFreeSlots.begin();
1737 mCore->clearBufferSlotLocked(*slot); // Clean up the slot first
Shuangxi Xiang045a30e2024-10-14 09:38:32 +00001738 mSlots[*slot].mGraphicBuffer = graphicBuffer;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001739 mSlots[*slot].mFence = Fence::NO_FENCE;
John Reckdb164ff2024-04-03 16:59:28 -04001740#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1741 mSlots[*slot].mAdditionalOptionsGenerationId = allocOptionsGenId;
1742#endif
Dan Stoza0de7ea72015-04-23 13:20:51 -07001743
1744 // freeBufferLocked puts this slot on the free slots list. Since
1745 // we then attached a buffer, move the slot to free buffer list.
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001746 mCore->mFreeBuffers.push_front(*slot);
Dan Stoza0de7ea72015-04-23 13:20:51 -07001747
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001748 BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d",
1749 *slot);
Christopher Ferris87e94cd2016-04-26 11:29:08 -07001750
1751 // Make sure the erase is done after all uses of the slot
1752 // iterator since it will be invalid after this point.
1753 mCore->mFreeSlots.erase(slot);
Antoine Labour78014f32014-07-15 21:17:03 -07001754 }
Dan Stoza29a3e902014-06-20 13:13:57 -07001755
Antoine Labour78014f32014-07-15 21:17:03 -07001756 mCore->mIsAllocating = false;
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001757 mCore->mIsAllocatingCondition.notify_all();
Pablo Ceballos9e314332016-01-12 13:49:19 -08001758 VALIDATE_CONSISTENCY();
Jorim Jaggi35b4e382019-03-28 00:44:03 +01001759
1760 // If dequeue is waiting for to allocate a buffer, release the lock until it's not
1761 // waiting anymore so it can use the buffer we just allocated.
1762 while (mDequeueWaitingForAllocation) {
1763 mDequeueWaitingForAllocationCondition.wait(lock);
1764 }
Antoine Labour78014f32014-07-15 21:17:03 -07001765 } // Autolock scope
Dan Stoza29a3e902014-06-20 13:13:57 -07001766 }
1767}
1768
Dan Stoza9de72932015-04-16 17:28:43 -07001769status_t BufferQueueProducer::allowAllocation(bool allow) {
1770 ATRACE_CALL();
1771 BQ_LOGV("allowAllocation: %s", allow ? "true" : "false");
1772
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001773 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza9de72932015-04-16 17:28:43 -07001774 mCore->mAllowAllocation = allow;
1775 return NO_ERROR;
1776}
1777
Dan Stoza812ed062015-06-02 15:45:22 -07001778status_t BufferQueueProducer::setGenerationNumber(uint32_t generationNumber) {
1779 ATRACE_CALL();
1780 BQ_LOGV("setGenerationNumber: %u", generationNumber);
1781
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001782 std::lock_guard<std::mutex> lock(mCore->mMutex);
Dan Stoza812ed062015-06-02 15:45:22 -07001783 mCore->mGenerationNumber = generationNumber;
1784 return NO_ERROR;
1785}
1786
Dan Stozac6f30bd2015-06-08 09:32:50 -07001787String8 BufferQueueProducer::getConsumerName() const {
1788 ATRACE_CALL();
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001789 std::lock_guard<std::mutex> lock(mCore->mMutex);
Tomasz Wasilczykf2add402023-08-11 00:06:51 +00001790 BQ_LOGV("getConsumerName: %s", mConsumerName.c_str());
Dan Stozac6f30bd2015-06-08 09:32:50 -07001791 return mConsumerName;
1792}
1793
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001794status_t BufferQueueProducer::setSharedBufferMode(bool sharedBufferMode) {
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001795 ATRACE_CALL();
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001796 BQ_LOGV("setSharedBufferMode: %d", sharedBufferMode);
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001797
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001798 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001799 if (!sharedBufferMode) {
1800 mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT;
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001801 }
Pablo Ceballos3559fbf2016-03-17 15:50:23 -07001802 mCore->mSharedBufferMode = sharedBufferMode;
Dan Stoza127fc632015-06-30 13:43:32 -07001803 return NO_ERROR;
1804}
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001805
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001806status_t BufferQueueProducer::setAutoRefresh(bool autoRefresh) {
1807 ATRACE_CALL();
1808 BQ_LOGV("setAutoRefresh: %d", autoRefresh);
1809
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001810 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001811
1812 mCore->mAutoRefresh = autoRefresh;
1813 return NO_ERROR;
1814}
1815
Dan Stoza127fc632015-06-30 13:43:32 -07001816status_t BufferQueueProducer::setDequeueTimeout(nsecs_t timeout) {
1817 ATRACE_CALL();
1818 BQ_LOGV("setDequeueTimeout: %" PRId64, timeout);
1819
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001820 std::lock_guard<std::mutex> lock(mCore->mMutex);
Sungtak Lee42a94c62019-05-24 14:27:14 -07001821 bool dequeueBufferCannotBlock =
1822 timeout >= 0 ? false : mCore->mDequeueBufferCannotBlock;
1823 int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode, dequeueBufferCannotBlock,
Pablo Ceballos981066c2016-02-18 12:54:37 -08001824 mCore->mMaxBufferCount) - mCore->getMaxBufferCountLocked();
1825 if (!mCore->adjustAvailableSlotsLocked(delta)) {
1826 BQ_LOGE("setDequeueTimeout: BufferQueue failed to adjust the number of "
1827 "available slots. Delta = %d", delta);
1828 return BAD_VALUE;
Pablo Ceballos23b4abe2016-01-08 12:15:22 -08001829 }
1830
Pablo Ceballos981066c2016-02-18 12:54:37 -08001831 mDequeueTimeout = timeout;
Sungtak Lee42a94c62019-05-24 14:27:14 -07001832 mCore->mDequeueBufferCannotBlock = dequeueBufferCannotBlock;
1833 if (timeout > 0) {
1834 mCore->mQueueBufferCanDrop = false;
Sungtak Lee3249fb62019-03-02 16:40:47 -08001835 }
Pablo Ceballos9e314332016-01-12 13:49:19 -08001836
Pablo Ceballos981066c2016-02-18 12:54:37 -08001837 VALIDATE_CONSISTENCY();
Pablo Ceballosccdfd602015-10-07 15:05:45 -07001838 return NO_ERROR;
1839}
1840
Sungtak Lee3249fb62019-03-02 16:40:47 -08001841status_t BufferQueueProducer::setLegacyBufferDrop(bool drop) {
1842 ATRACE_CALL();
1843 BQ_LOGV("setLegacyBufferDrop: drop = %d", drop);
1844
1845 std::lock_guard<std::mutex> lock(mCore->mMutex);
1846 mCore->mLegacyBufferDrop = drop;
1847 return NO_ERROR;
1848}
1849
Dan Stoza50101d02016-04-07 16:53:23 -07001850status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
John Reck1a61da52016-04-28 13:18:15 -07001851 sp<Fence>* outFence, float outTransformMatrix[16]) {
Dan Stoza50101d02016-04-07 16:53:23 -07001852 ATRACE_CALL();
Dan Stoza50101d02016-04-07 16:53:23 -07001853
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001854 std::lock_guard<std::mutex> lock(mCore->mMutex);
John Reckd2c4a4a2024-02-07 10:31:09 -05001855 BQ_LOGV("getLastQueuedBuffer, slot=%d", mCore->mLastQueuedSlot);
1856
Dan Stoza50101d02016-04-07 16:53:23 -07001857 if (mCore->mLastQueuedSlot == BufferItem::INVALID_BUFFER_SLOT) {
1858 *outBuffer = nullptr;
1859 *outFence = Fence::NO_FENCE;
1860 return NO_ERROR;
1861 }
1862
1863 *outBuffer = mSlots[mCore->mLastQueuedSlot].mGraphicBuffer;
1864 *outFence = mLastQueueBufferFence;
1865
John Reck1a61da52016-04-28 13:18:15 -07001866 // Currently only SurfaceFlinger internally ever changes
1867 // GLConsumer's filtering mode, so we just use 'true' here as
1868 // this is slightly specialized for the current client of this API,
1869 // which does want filtering.
1870 GLConsumer::computeTransformMatrix(outTransformMatrix,
1871 mSlots[mCore->mLastQueuedSlot].mGraphicBuffer, mLastQueuedCrop,
1872 mLastQueuedTransform, true /* filter */);
1873
Dan Stoza50101d02016-04-07 16:53:23 -07001874 return NO_ERROR;
1875}
1876
John Reckf0f13e82021-05-18 00:42:56 -04001877status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer, sp<Fence>* outFence,
1878 Rect* outRect, uint32_t* outTransform) {
1879 ATRACE_CALL();
John Reckf0f13e82021-05-18 00:42:56 -04001880
1881 std::lock_guard<std::mutex> lock(mCore->mMutex);
John Reckd2c4a4a2024-02-07 10:31:09 -05001882 BQ_LOGV("getLastQueuedBuffer, slot=%d", mCore->mLastQueuedSlot);
1883 if (mCore->mLastQueuedSlot == BufferItem::INVALID_BUFFER_SLOT ||
1884 mSlots[mCore->mLastQueuedSlot].mBufferState.isDequeued()) {
John Reckf0f13e82021-05-18 00:42:56 -04001885 *outBuffer = nullptr;
1886 *outFence = Fence::NO_FENCE;
1887 return NO_ERROR;
1888 }
1889
1890 *outBuffer = mSlots[mCore->mLastQueuedSlot].mGraphicBuffer;
1891 *outFence = mLastQueueBufferFence;
1892 *outRect = mLastQueuedCrop;
1893 *outTransform = mLastQueuedTransform;
1894
1895 return NO_ERROR;
1896}
1897
Brian Anderson3890c392016-07-25 12:48:08 -07001898void BufferQueueProducer::getFrameTimestamps(FrameEventHistoryDelta* outDelta) {
1899 addAndGetFrameTimestamps(nullptr, outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07001900}
Pablo Ceballosce796e72016-02-04 19:10:51 -08001901
Brian Anderson3890c392016-07-25 12:48:08 -07001902void BufferQueueProducer::addAndGetFrameTimestamps(
Brian Andersond6927fb2016-07-23 23:37:30 -07001903 const NewFrameEventsEntry* newTimestamps,
Brian Anderson3890c392016-07-25 12:48:08 -07001904 FrameEventHistoryDelta* outDelta) {
1905 if (newTimestamps == nullptr && outDelta == nullptr) {
1906 return;
Brian Andersond6927fb2016-07-23 23:37:30 -07001907 }
1908
1909 ATRACE_CALL();
1910 BQ_LOGV("addAndGetFrameTimestamps");
1911 sp<IConsumerListener> listener;
Pablo Ceballosce796e72016-02-04 19:10:51 -08001912 {
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001913 std::lock_guard<std::mutex> lock(mCore->mMutex);
Pablo Ceballosce796e72016-02-04 19:10:51 -08001914 listener = mCore->mConsumerListener;
1915 }
Yi Kong48a619f2018-06-05 16:34:59 -07001916 if (listener != nullptr) {
Brian Anderson3890c392016-07-25 12:48:08 -07001917 listener->addAndGetFrameTimestamps(newTimestamps, outDelta);
Pablo Ceballosce796e72016-02-04 19:10:51 -08001918 }
Pablo Ceballosce796e72016-02-04 19:10:51 -08001919}
1920
Dan Stoza289ade12014-02-28 11:17:17 -08001921void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
1922 // If we're here, it means that a producer we were connected to died.
1923 // We're guaranteed that we are still connected to it because we remove
1924 // this callback upon disconnect. It's therefore safe to read mConnectedApi
1925 // without synchronization here.
1926 int api = mCore->mConnectedApi;
1927 disconnect(api);
1928}
1929
Pablo Ceballos8e3e92b2016-06-27 17:56:53 -07001930status_t BufferQueueProducer::getUniqueId(uint64_t* outId) const {
1931 BQ_LOGV("getUniqueId");
1932
1933 *outId = mCore->mUniqueId;
1934 return NO_ERROR;
1935}
1936
Chia-I Wue2786ea2017-08-07 10:36:08 -07001937status_t BufferQueueProducer::getConsumerUsage(uint64_t* outUsage) const {
1938 BQ_LOGV("getConsumerUsage");
1939
Jorim Jaggi6ae55032019-04-02 02:27:44 +02001940 std::lock_guard<std::mutex> lock(mCore->mMutex);
Chia-I Wue2786ea2017-08-07 10:36:08 -07001941 *outUsage = mCore->mConsumerUsageBits;
1942 return NO_ERROR;
1943}
1944
Yiwei Zhang538cedc2019-06-24 19:35:03 -07001945status_t BufferQueueProducer::setAutoPrerotation(bool autoPrerotation) {
1946 ATRACE_CALL();
1947 BQ_LOGV("setAutoPrerotation: %d", autoPrerotation);
1948
1949 std::lock_guard<std::mutex> lock(mCore->mMutex);
1950
1951 mCore->mAutoPrerotation = autoPrerotation;
1952 return NO_ERROR;
1953}
1954
Ady Abraham107788e2023-10-17 12:31:08 -07001955#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_SETFRAMERATE)
Ady Abraham6cdd3fd2023-09-07 18:45:58 -07001956status_t BufferQueueProducer::setFrameRate(float frameRate, int8_t compatibility,
1957 int8_t changeFrameRateStrategy) {
1958 ATRACE_CALL();
1959 BQ_LOGV("setFrameRate: %.2f", frameRate);
1960
1961 if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy,
1962 "BufferQueueProducer::setFrameRate")) {
1963 return BAD_VALUE;
1964 }
1965
1966 sp<IConsumerListener> listener;
1967 {
1968 std::lock_guard<std::mutex> lock(mCore->mMutex);
1969 listener = mCore->mConsumerListener;
1970 }
1971 if (listener != nullptr) {
1972 listener->onSetFrameRate(frameRate, compatibility, changeFrameRateStrategy);
1973 }
1974 return NO_ERROR;
1975}
1976#endif
1977
John Reckdb164ff2024-04-03 16:59:28 -04001978#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(BQ_EXTENDEDALLOCATE)
1979status_t BufferQueueProducer::setAdditionalOptions(
1980 const std::vector<gui::AdditionalOptions>& options) {
1981 ATRACE_CALL();
1982 BQ_LOGV("setAdditionalOptions, size = %zu", options.size());
1983
1984 if (!GraphicBufferAllocator::get().supportsAdditionalOptions()) {
1985 return INVALID_OPERATION;
1986 }
1987
1988 std::lock_guard<std::mutex> lock(mCore->mMutex);
1989
1990 if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
1991 BQ_LOGE("setAdditionalOptions: BufferQueue not connected, cannot set additional options");
1992 return NO_INIT;
1993 }
1994
1995 if (mCore->mAdditionalOptions != options) {
1996 mCore->mAdditionalOptions = options;
1997 mCore->mAdditionalOptionsGenerationId++;
1998 }
1999 return NO_ERROR;
2000}
2001#endif
2002
Dan Stoza289ade12014-02-28 11:17:17 -08002003} // namespace android