blob: 70c3ff33e880a6f35be0278cc06bf049b1678549 [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
Dan Stoza289ade12014-02-28 11:17:17 -080023#define EGL_EGLEXT_PROTOTYPES
24
25#include <gui/BufferItem.h>
26#include <gui/BufferQueueCore.h>
27#include <gui/BufferQueueProducer.h>
28#include <gui/IConsumerListener.h>
29#include <gui/IGraphicBufferAlloc.h>
Dan Stozaf0eaf252014-03-21 13:05:51 -070030#include <gui/IProducerListener.h>
Dan Stoza289ade12014-02-28 11:17:17 -080031
32#include <utils/Log.h>
33#include <utils/Trace.h>
34
35namespace android {
36
37BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core) :
38 mCore(core),
39 mSlots(core->mSlots),
40 mConsumerName() {}
41
42BufferQueueProducer::~BufferQueueProducer() {}
43
44status_t BufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
45 ATRACE_CALL();
46 BQ_LOGV("requestBuffer: slot %d", slot);
47 Mutex::Autolock lock(mCore->mMutex);
48
49 if (mCore->mIsAbandoned) {
50 BQ_LOGE("requestBuffer: BufferQueue has been abandoned");
51 return NO_INIT;
52 }
53
Dan Stoza3e96f192014-03-03 10:16:19 -080054 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
Dan Stoza289ade12014-02-28 11:17:17 -080055 BQ_LOGE("requestBuffer: slot index %d out of range [0, %d)",
Dan Stoza3e96f192014-03-03 10:16:19 -080056 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
Dan Stoza289ade12014-02-28 11:17:17 -080057 return BAD_VALUE;
58 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
59 BQ_LOGE("requestBuffer: slot %d is not owned by the producer "
60 "(state = %d)", slot, mSlots[slot].mBufferState);
61 return BAD_VALUE;
62 }
63
64 mSlots[slot].mRequestBufferCalled = true;
65 *buf = mSlots[slot].mGraphicBuffer;
66 return NO_ERROR;
67}
68
69status_t BufferQueueProducer::setBufferCount(int bufferCount) {
70 ATRACE_CALL();
71 BQ_LOGV("setBufferCount: count = %d", bufferCount);
72
73 sp<IConsumerListener> listener;
74 { // Autolock scope
75 Mutex::Autolock lock(mCore->mMutex);
76
77 if (mCore->mIsAbandoned) {
78 BQ_LOGE("setBufferCount: BufferQueue has been abandoned");
79 return NO_INIT;
80 }
81
Dan Stoza3e96f192014-03-03 10:16:19 -080082 if (bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) {
Dan Stoza289ade12014-02-28 11:17:17 -080083 BQ_LOGE("setBufferCount: bufferCount %d too large (max %d)",
Dan Stoza3e96f192014-03-03 10:16:19 -080084 bufferCount, BufferQueueDefs::NUM_BUFFER_SLOTS);
Dan Stoza289ade12014-02-28 11:17:17 -080085 return BAD_VALUE;
86 }
87
88 // There must be no dequeued buffers when changing the buffer count.
Dan Stoza3e96f192014-03-03 10:16:19 -080089 for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
Dan Stoza289ade12014-02-28 11:17:17 -080090 if (mSlots[s].mBufferState == BufferSlot::DEQUEUED) {
91 BQ_LOGE("setBufferCount: buffer owned by producer");
Dan Stoza9f3053d2014-03-06 15:14:33 -080092 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -080093 }
94 }
95
96 if (bufferCount == 0) {
97 mCore->mOverrideMaxBufferCount = 0;
98 mCore->mDequeueCondition.broadcast();
99 return NO_ERROR;
100 }
101
102 const int minBufferSlots = mCore->getMinMaxBufferCountLocked(false);
103 if (bufferCount < minBufferSlots) {
104 BQ_LOGE("setBufferCount: requested buffer count %d is less than "
105 "minimum %d", bufferCount, minBufferSlots);
106 return BAD_VALUE;
107 }
108
109 // Here we are guaranteed that the producer doesn't have any dequeued
110 // buffers and will release all of its buffer references. We don't
111 // clear the queue, however, so that currently queued buffers still
112 // get displayed.
113 mCore->freeAllBuffersLocked();
114 mCore->mOverrideMaxBufferCount = bufferCount;
115 mCore->mDequeueCondition.broadcast();
116 listener = mCore->mConsumerListener;
117 } // Autolock scope
118
119 // Call back without lock held
120 if (listener != NULL) {
121 listener->onBuffersReleased();
122 }
123
124 return NO_ERROR;
125}
126
Dan Stoza9f3053d2014-03-06 15:14:33 -0800127status_t BufferQueueProducer::waitForFreeSlotThenRelock(const char* caller,
128 bool async, int* found, status_t* returnFlags) const {
129 bool tryAgain = true;
130 while (tryAgain) {
131 if (mCore->mIsAbandoned) {
132 BQ_LOGE("%s: BufferQueue has been abandoned", caller);
133 return NO_INIT;
134 }
135
136 const int maxBufferCount = mCore->getMaxBufferCountLocked(async);
137 if (async && mCore->mOverrideMaxBufferCount) {
138 // FIXME: Some drivers are manually setting the buffer count
139 // (which they shouldn't), so we do this extra test here to
140 // handle that case. This is TEMPORARY until we get this fixed.
141 if (mCore->mOverrideMaxBufferCount < maxBufferCount) {
142 BQ_LOGE("%s: async mode is invalid with buffer count override",
143 caller);
144 return BAD_VALUE;
145 }
146 }
147
148 // Free up any buffers that are in slots beyond the max buffer count
149 for (int s = maxBufferCount; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
150 assert(mSlots[s].mBufferState == BufferSlot::FREE);
151 if (mSlots[s].mGraphicBuffer != NULL) {
152 mCore->freeBufferLocked(s);
153 *returnFlags |= RELEASE_ALL_BUFFERS;
154 }
155 }
156
157 // Look for a free buffer to give to the client
158 *found = BufferQueueCore::INVALID_BUFFER_SLOT;
159 int dequeuedCount = 0;
160 int acquiredCount = 0;
161 for (int s = 0; s < maxBufferCount; ++s) {
162 switch (mSlots[s].mBufferState) {
163 case BufferSlot::DEQUEUED:
164 ++dequeuedCount;
165 break;
166 case BufferSlot::ACQUIRED:
167 ++acquiredCount;
168 break;
169 case BufferSlot::FREE:
170 // We return the oldest of the free buffers to avoid
171 // stalling the producer if possible, since the consumer
172 // may still have pending reads of in-flight buffers
173 if (*found == BufferQueueCore::INVALID_BUFFER_SLOT ||
174 mSlots[s].mFrameNumber < mSlots[*found].mFrameNumber) {
175 *found = s;
176 }
177 break;
178 default:
179 break;
180 }
181 }
182
183 // Producers are not allowed to dequeue more than one buffer if they
184 // did not set a buffer count
185 if (!mCore->mOverrideMaxBufferCount && dequeuedCount) {
186 BQ_LOGE("%s: can't dequeue multiple buffers without setting the "
187 "buffer count", caller);
188 return INVALID_OPERATION;
189 }
190
191 // See whether a buffer has been queued since the last
192 // setBufferCount so we know whether to perform the min undequeued
193 // buffers check below
194 if (mCore->mBufferHasBeenQueued) {
195 // Make sure the producer is not trying to dequeue more buffers
196 // than allowed
197 const int newUndequeuedCount =
198 maxBufferCount - (dequeuedCount + 1);
199 const int minUndequeuedCount =
200 mCore->getMinUndequeuedBufferCountLocked(async);
201 if (newUndequeuedCount < minUndequeuedCount) {
202 BQ_LOGE("%s: min undequeued buffer count (%d) exceeded "
203 "(dequeued=%d undequeued=%d)",
204 caller, minUndequeuedCount,
205 dequeuedCount, newUndequeuedCount);
206 return INVALID_OPERATION;
207 }
208 }
209
Dan Stozaae3c3682014-04-18 15:43:35 -0700210 // If we disconnect and reconnect quickly, we can be in a state where
211 // our slots are empty but we have many buffers in the queue. This can
212 // cause us to run out of memory if we outrun the consumer. Wait here if
213 // it looks like we have too many buffers queued up.
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700214 bool tooManyBuffers = mCore->mQueue.size()
215 > static_cast<size_t>(maxBufferCount);
Dan Stozaae3c3682014-04-18 15:43:35 -0700216 if (tooManyBuffers) {
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700217 BQ_LOGV("%s: queue size is %zu, waiting", caller,
Dan Stozaae3c3682014-04-18 15:43:35 -0700218 mCore->mQueue.size());
219 }
220
221 // If no buffer is found, or if the queue has too many buffers
222 // outstanding, wait for a buffer to be acquired or released, or for the
223 // max buffer count to change.
224 tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
225 tooManyBuffers;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800226 if (tryAgain) {
227 // Return an error if we're in non-blocking mode (producer and
228 // consumer are controlled by the application).
229 // However, the consumer is allowed to briefly acquire an extra
230 // buffer (which could cause us to have to wait here), which is
231 // okay, since it is only used to implement an atomic acquire +
232 // release (e.g., in GLConsumer::updateTexImage())
233 if (mCore->mDequeueBufferCannotBlock &&
234 (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
235 return WOULD_BLOCK;
236 }
237 mCore->mDequeueCondition.wait(mCore->mMutex);
238 }
239 } // while (tryAgain)
240
241 return NO_ERROR;
242}
243
Dan Stoza289ade12014-02-28 11:17:17 -0800244status_t BufferQueueProducer::dequeueBuffer(int *outSlot,
245 sp<android::Fence> *outFence, bool async,
246 uint32_t width, uint32_t height, uint32_t format, uint32_t usage) {
247 ATRACE_CALL();
248 { // Autolock scope
249 Mutex::Autolock lock(mCore->mMutex);
250 mConsumerName = mCore->mConsumerName;
251 } // Autolock scope
252
253 BQ_LOGV("dequeueBuffer: async=%s w=%u h=%u format=%#x, usage=%#x",
254 async ? "true" : "false", width, height, format, usage);
255
256 if ((width && !height) || (!width && height)) {
257 BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
258 return BAD_VALUE;
259 }
260
261 status_t returnFlags = NO_ERROR;
262 EGLDisplay eglDisplay = EGL_NO_DISPLAY;
263 EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800264 bool attachedByConsumer = false;
Dan Stoza289ade12014-02-28 11:17:17 -0800265
266 { // Autolock scope
267 Mutex::Autolock lock(mCore->mMutex);
268
269 if (format == 0) {
270 format = mCore->mDefaultBufferFormat;
271 }
272
273 // Enable the usage bits the consumer requested
274 usage |= mCore->mConsumerUsageBits;
275
Dan Stoza9f3053d2014-03-06 15:14:33 -0800276 int found;
277 status_t status = waitForFreeSlotThenRelock("dequeueBuffer", async,
278 &found, &returnFlags);
279 if (status != NO_ERROR) {
280 return status;
281 }
Dan Stoza289ade12014-02-28 11:17:17 -0800282
283 // This should not happen
284 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
285 BQ_LOGE("dequeueBuffer: no available buffer slots");
286 return -EBUSY;
287 }
288
289 *outSlot = found;
290 ATRACE_BUFFER_INDEX(found);
291
Dan Stoza9f3053d2014-03-06 15:14:33 -0800292 attachedByConsumer = mSlots[found].mAttachedByConsumer;
293
Dan Stoza289ade12014-02-28 11:17:17 -0800294 const bool useDefaultSize = !width && !height;
295 if (useDefaultSize) {
296 width = mCore->mDefaultWidth;
297 height = mCore->mDefaultHeight;
298 }
299
300 mSlots[found].mBufferState = BufferSlot::DEQUEUED;
301
302 const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
303 if ((buffer == NULL) ||
304 (static_cast<uint32_t>(buffer->width) != width) ||
305 (static_cast<uint32_t>(buffer->height) != height) ||
306 (static_cast<uint32_t>(buffer->format) != format) ||
307 ((static_cast<uint32_t>(buffer->usage) & usage) != usage))
308 {
309 mSlots[found].mAcquireCalled = false;
310 mSlots[found].mGraphicBuffer = NULL;
311 mSlots[found].mRequestBufferCalled = false;
312 mSlots[found].mEglDisplay = EGL_NO_DISPLAY;
313 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
314 mSlots[found].mFence = Fence::NO_FENCE;
315
316 returnFlags |= BUFFER_NEEDS_REALLOCATION;
317 }
318
319 if (CC_UNLIKELY(mSlots[found].mFence == NULL)) {
320 BQ_LOGE("dequeueBuffer: about to return a NULL fence - "
321 "slot=%d w=%d h=%d format=%u",
322 found, buffer->width, buffer->height, buffer->format);
323 }
324
325 eglDisplay = mSlots[found].mEglDisplay;
326 eglFence = mSlots[found].mEglFence;
327 *outFence = mSlots[found].mFence;
328 mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
329 mSlots[found].mFence = Fence::NO_FENCE;
330 } // Autolock scope
331
332 if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
333 status_t error;
Dan Stoza29a3e902014-06-20 13:13:57 -0700334 BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
Dan Stoza289ade12014-02-28 11:17:17 -0800335 sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
336 width, height, format, usage, &error));
337 if (graphicBuffer == NULL) {
338 BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
339 return error;
340 }
341
342 { // Autolock scope
343 Mutex::Autolock lock(mCore->mMutex);
344
345 if (mCore->mIsAbandoned) {
346 BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
347 return NO_INIT;
348 }
349
Dan Stoza9f3053d2014-03-06 15:14:33 -0800350 mSlots[*outSlot].mFrameNumber = UINT32_MAX;
Dan Stoza289ade12014-02-28 11:17:17 -0800351 mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
352 } // Autolock scope
353 }
354
Dan Stoza9f3053d2014-03-06 15:14:33 -0800355 if (attachedByConsumer) {
356 returnFlags |= BUFFER_NEEDS_REALLOCATION;
357 }
358
Dan Stoza289ade12014-02-28 11:17:17 -0800359 if (eglFence != EGL_NO_SYNC_KHR) {
360 EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0,
361 1000000000);
362 // If something goes wrong, log the error, but return the buffer without
363 // synchronizing access to it. It's too late at this point to abort the
364 // dequeue operation.
365 if (result == EGL_FALSE) {
366 BQ_LOGE("dequeueBuffer: error %#x waiting for fence",
367 eglGetError());
368 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
369 BQ_LOGE("dequeueBuffer: timeout waiting for fence");
370 }
371 eglDestroySyncKHR(eglDisplay, eglFence);
372 }
373
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700374 BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
375 *outSlot,
Dan Stoza289ade12014-02-28 11:17:17 -0800376 mSlots[*outSlot].mFrameNumber,
377 mSlots[*outSlot].mGraphicBuffer->handle, returnFlags);
378
379 return returnFlags;
380}
381
Dan Stoza9f3053d2014-03-06 15:14:33 -0800382status_t BufferQueueProducer::detachBuffer(int slot) {
383 ATRACE_CALL();
384 ATRACE_BUFFER_INDEX(slot);
385 BQ_LOGV("detachBuffer(P): slot %d", slot);
386 Mutex::Autolock lock(mCore->mMutex);
387
388 if (mCore->mIsAbandoned) {
389 BQ_LOGE("detachBuffer(P): BufferQueue has been abandoned");
390 return NO_INIT;
391 }
392
393 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
394 BQ_LOGE("detachBuffer(P): slot index %d out of range [0, %d)",
395 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
396 return BAD_VALUE;
397 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
398 BQ_LOGE("detachBuffer(P): slot %d is not owned by the producer "
399 "(state = %d)", slot, mSlots[slot].mBufferState);
400 return BAD_VALUE;
401 } else if (!mSlots[slot].mRequestBufferCalled) {
402 BQ_LOGE("detachBuffer(P): buffer in slot %d has not been requested",
403 slot);
404 return BAD_VALUE;
405 }
406
407 mCore->freeBufferLocked(slot);
408 mCore->mDequeueCondition.broadcast();
409
410 return NO_ERROR;
411}
412
Dan Stozad9822a32014-03-28 15:25:31 -0700413status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
414 sp<Fence>* outFence) {
415 ATRACE_CALL();
416
417 if (outBuffer == NULL) {
418 BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
419 return BAD_VALUE;
420 } else if (outFence == NULL) {
421 BQ_LOGE("detachNextBuffer: outFence must not be NULL");
422 return BAD_VALUE;
423 }
424
425 Mutex::Autolock lock(mCore->mMutex);
426
427 if (mCore->mIsAbandoned) {
428 BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
429 return NO_INIT;
430 }
431
432 // Find the oldest valid slot
433 int found = BufferQueueCore::INVALID_BUFFER_SLOT;
434 for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
435 if (mSlots[s].mBufferState == BufferSlot::FREE &&
436 mSlots[s].mGraphicBuffer != NULL) {
437 if (found == BufferQueueCore::INVALID_BUFFER_SLOT ||
438 mSlots[s].mFrameNumber < mSlots[found].mFrameNumber) {
439 found = s;
440 }
441 }
442 }
443
444 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
445 return NO_MEMORY;
446 }
447
448 BQ_LOGV("detachNextBuffer detached slot %d", found);
449
450 *outBuffer = mSlots[found].mGraphicBuffer;
451 *outFence = mSlots[found].mFence;
452 mCore->freeBufferLocked(found);
453
454 return NO_ERROR;
455}
456
Dan Stoza9f3053d2014-03-06 15:14:33 -0800457status_t BufferQueueProducer::attachBuffer(int* outSlot,
458 const sp<android::GraphicBuffer>& buffer) {
459 ATRACE_CALL();
460
461 if (outSlot == NULL) {
462 BQ_LOGE("attachBuffer(P): outSlot must not be NULL");
463 return BAD_VALUE;
464 } else if (buffer == NULL) {
465 BQ_LOGE("attachBuffer(P): cannot attach NULL buffer");
466 return BAD_VALUE;
467 }
468
469 Mutex::Autolock lock(mCore->mMutex);
470
471 status_t returnFlags = NO_ERROR;
472 int found;
473 // TODO: Should we provide an async flag to attachBuffer? It seems
474 // unlikely that buffers which we are attaching to a BufferQueue will
475 // be asynchronous (droppable), but it may not be impossible.
476 status_t status = waitForFreeSlotThenRelock("attachBuffer(P)", false,
477 &found, &returnFlags);
478 if (status != NO_ERROR) {
479 return status;
480 }
481
482 // This should not happen
483 if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
484 BQ_LOGE("attachBuffer(P): no available buffer slots");
485 return -EBUSY;
486 }
487
488 *outSlot = found;
489 ATRACE_BUFFER_INDEX(*outSlot);
490 BQ_LOGV("attachBuffer(P): returning slot %d flags=%#x",
491 *outSlot, returnFlags);
492
493 mSlots[*outSlot].mGraphicBuffer = buffer;
494 mSlots[*outSlot].mBufferState = BufferSlot::DEQUEUED;
495 mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
496 mSlots[*outSlot].mFence = Fence::NO_FENCE;
Dan Stoza2443c792014-03-24 15:03:46 -0700497 mSlots[*outSlot].mRequestBufferCalled = true;
Dan Stoza9f3053d2014-03-06 15:14:33 -0800498
499 return returnFlags;
500}
501
Dan Stoza289ade12014-02-28 11:17:17 -0800502status_t BufferQueueProducer::queueBuffer(int slot,
503 const QueueBufferInput &input, QueueBufferOutput *output) {
504 ATRACE_CALL();
505 ATRACE_BUFFER_INDEX(slot);
506
507 int64_t timestamp;
508 bool isAutoTimestamp;
509 Rect crop;
510 int scalingMode;
511 uint32_t transform;
512 bool async;
513 sp<Fence> fence;
514 input.deflate(&timestamp, &isAutoTimestamp, &crop, &scalingMode, &transform,
515 &async, &fence);
516
517 if (fence == NULL) {
518 BQ_LOGE("queueBuffer: fence is NULL");
519 return BAD_VALUE;
520 }
521
522 switch (scalingMode) {
523 case NATIVE_WINDOW_SCALING_MODE_FREEZE:
524 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
525 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
526 case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
527 break;
528 default:
529 BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800530 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800531 }
532
533 sp<IConsumerListener> listener;
534 { // Autolock scope
535 Mutex::Autolock lock(mCore->mMutex);
536
537 if (mCore->mIsAbandoned) {
538 BQ_LOGE("queueBuffer: BufferQueue has been abandoned");
539 return NO_INIT;
540 }
541
542 const int maxBufferCount = mCore->getMaxBufferCountLocked(async);
543 if (async && mCore->mOverrideMaxBufferCount) {
544 // FIXME: Some drivers are manually setting the buffer count
545 // (which they shouldn't), so we do this extra test here to
546 // handle that case. This is TEMPORARY until we get this fixed.
547 if (mCore->mOverrideMaxBufferCount < maxBufferCount) {
548 BQ_LOGE("queueBuffer: async mode is invalid with "
549 "buffer count override");
550 return BAD_VALUE;
551 }
552 }
553
554 if (slot < 0 || slot >= maxBufferCount) {
555 BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)",
556 slot, maxBufferCount);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800557 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800558 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
559 BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
560 "(state = %d)", slot, mSlots[slot].mBufferState);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800561 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800562 } else if (!mSlots[slot].mRequestBufferCalled) {
563 BQ_LOGE("queueBuffer: slot %d was queued without requesting "
564 "a buffer", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800565 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800566 }
567
Mark Salyzyn8f515ce2014-06-09 14:32:04 -0700568 BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64
569 " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
Dan Stoza289ade12014-02-28 11:17:17 -0800570 slot, mCore->mFrameCounter + 1, timestamp,
571 crop.left, crop.top, crop.right, crop.bottom,
572 transform, BufferItem::scalingModeName(scalingMode));
573
574 const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
575 Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
576 Rect croppedRect;
577 crop.intersect(bufferRect, &croppedRect);
578 if (croppedRect != crop) {
579 BQ_LOGE("queueBuffer: crop rect is not contained within the "
580 "buffer in slot %d", slot);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800581 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800582 }
583
584 mSlots[slot].mFence = fence;
585 mSlots[slot].mBufferState = BufferSlot::QUEUED;
586 ++mCore->mFrameCounter;
587 mSlots[slot].mFrameNumber = mCore->mFrameCounter;
588
589 BufferItem item;
590 item.mAcquireCalled = mSlots[slot].mAcquireCalled;
591 item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
592 item.mCrop = crop;
593 item.mTransform = transform & ~NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
594 item.mTransformToDisplayInverse =
595 bool(transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
596 item.mScalingMode = scalingMode;
597 item.mTimestamp = timestamp;
598 item.mIsAutoTimestamp = isAutoTimestamp;
599 item.mFrameNumber = mCore->mFrameCounter;
600 item.mSlot = slot;
601 item.mFence = fence;
602 item.mIsDroppable = mCore->mDequeueBufferCannotBlock || async;
603
604 if (mCore->mQueue.empty()) {
605 // When the queue is empty, we can ignore mDequeueBufferCannotBlock
606 // and simply queue this buffer
607 mCore->mQueue.push_back(item);
608 listener = mCore->mConsumerListener;
609 } else {
610 // When the queue is not empty, we need to look at the front buffer
611 // state to see if we need to replace it
612 BufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());
613 if (front->mIsDroppable) {
614 // If the front queued buffer is still being tracked, we first
615 // mark it as freed
616 if (mCore->stillTracking(front)) {
617 mSlots[front->mSlot].mBufferState = BufferSlot::FREE;
618 // Reset the frame number of the freed buffer so that it is
619 // the first in line to be dequeued again
620 mSlots[front->mSlot].mFrameNumber = 0;
621 }
622 // Overwrite the droppable buffer with the incoming one
623 *front = item;
624 } else {
625 mCore->mQueue.push_back(item);
626 listener = mCore->mConsumerListener;
627 }
628 }
629
630 mCore->mBufferHasBeenQueued = true;
631 mCore->mDequeueCondition.broadcast();
632
633 output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
634 mCore->mTransformHint, mCore->mQueue.size());
635
636 ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
637 } // Autolock scope
638
639 // Call back without lock held
640 if (listener != NULL) {
641 listener->onFrameAvailable();
642 }
643
644 return NO_ERROR;
645}
646
647void BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
648 ATRACE_CALL();
649 BQ_LOGV("cancelBuffer: slot %d", slot);
650 Mutex::Autolock lock(mCore->mMutex);
651
652 if (mCore->mIsAbandoned) {
653 BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
654 return;
655 }
656
Dan Stoza3e96f192014-03-03 10:16:19 -0800657 if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
Dan Stoza289ade12014-02-28 11:17:17 -0800658 BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)",
Dan Stoza3e96f192014-03-03 10:16:19 -0800659 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
Dan Stoza289ade12014-02-28 11:17:17 -0800660 return;
661 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
662 BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
663 "(state = %d)", slot, mSlots[slot].mBufferState);
664 return;
665 } else if (fence == NULL) {
666 BQ_LOGE("cancelBuffer: fence is NULL");
667 return;
668 }
669
670 mSlots[slot].mBufferState = BufferSlot::FREE;
671 mSlots[slot].mFrameNumber = 0;
672 mSlots[slot].mFence = fence;
673 mCore->mDequeueCondition.broadcast();
674}
675
676int BufferQueueProducer::query(int what, int *outValue) {
677 ATRACE_CALL();
678 Mutex::Autolock lock(mCore->mMutex);
679
680 if (outValue == NULL) {
681 BQ_LOGE("query: outValue was NULL");
682 return BAD_VALUE;
683 }
684
685 if (mCore->mIsAbandoned) {
686 BQ_LOGE("query: BufferQueue has been abandoned");
687 return NO_INIT;
688 }
689
690 int value;
691 switch (what) {
692 case NATIVE_WINDOW_WIDTH:
693 value = mCore->mDefaultWidth;
694 break;
695 case NATIVE_WINDOW_HEIGHT:
696 value = mCore->mDefaultHeight;
697 break;
698 case NATIVE_WINDOW_FORMAT:
699 value = mCore->mDefaultBufferFormat;
700 break;
701 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
702 value = mCore->getMinUndequeuedBufferCountLocked(false);
703 break;
704 case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
705 value = (mCore->mQueue.size() > 1);
706 break;
707 case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
708 value = mCore->mConsumerUsageBits;
709 break;
710 default:
711 return BAD_VALUE;
712 }
713
714 BQ_LOGV("query: %d? %d", what, value);
715 *outValue = value;
716 return NO_ERROR;
717}
718
Dan Stozaf0eaf252014-03-21 13:05:51 -0700719status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
Dan Stoza289ade12014-02-28 11:17:17 -0800720 int api, bool producerControlledByApp, QueueBufferOutput *output) {
721 ATRACE_CALL();
722 Mutex::Autolock lock(mCore->mMutex);
723 mConsumerName = mCore->mConsumerName;
724 BQ_LOGV("connect(P): api=%d producerControlledByApp=%s", api,
725 producerControlledByApp ? "true" : "false");
726
Dan Stozaae3c3682014-04-18 15:43:35 -0700727 if (mCore->mIsAbandoned) {
728 BQ_LOGE("connect(P): BufferQueue has been abandoned");
729 return NO_INIT;
730 }
Dan Stoza289ade12014-02-28 11:17:17 -0800731
Dan Stozaae3c3682014-04-18 15:43:35 -0700732 if (mCore->mConsumerListener == NULL) {
733 BQ_LOGE("connect(P): BufferQueue has no consumer");
734 return NO_INIT;
735 }
Dan Stoza289ade12014-02-28 11:17:17 -0800736
Dan Stozaae3c3682014-04-18 15:43:35 -0700737 if (output == NULL) {
738 BQ_LOGE("connect(P): output was NULL");
739 return BAD_VALUE;
740 }
Dan Stoza289ade12014-02-28 11:17:17 -0800741
Dan Stozaae3c3682014-04-18 15:43:35 -0700742 if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
743 BQ_LOGE("connect(P): already connected (cur=%d req=%d)",
744 mCore->mConnectedApi, api);
745 return BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800746 }
747
748 int status = NO_ERROR;
749 switch (api) {
750 case NATIVE_WINDOW_API_EGL:
751 case NATIVE_WINDOW_API_CPU:
752 case NATIVE_WINDOW_API_MEDIA:
753 case NATIVE_WINDOW_API_CAMERA:
754 mCore->mConnectedApi = api;
755 output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
756 mCore->mTransformHint, mCore->mQueue.size());
757
758 // Set up a death notification so that we can disconnect
759 // automatically if the remote producer dies
Dan Stozaf0eaf252014-03-21 13:05:51 -0700760 if (listener != NULL &&
761 listener->asBinder()->remoteBinder() != NULL) {
762 status = listener->asBinder()->linkToDeath(
Dan Stoza289ade12014-02-28 11:17:17 -0800763 static_cast<IBinder::DeathRecipient*>(this));
Dan Stozaf0eaf252014-03-21 13:05:51 -0700764 if (status != NO_ERROR) {
Dan Stoza289ade12014-02-28 11:17:17 -0800765 BQ_LOGE("connect(P): linkToDeath failed: %s (%d)",
766 strerror(-status), status);
767 }
768 }
Dan Stozaf0eaf252014-03-21 13:05:51 -0700769 mCore->mConnectedProducerListener = listener;
Dan Stoza289ade12014-02-28 11:17:17 -0800770 break;
771 default:
772 BQ_LOGE("connect(P): unknown API %d", api);
773 status = BAD_VALUE;
774 break;
775 }
776
777 mCore->mBufferHasBeenQueued = false;
778 mCore->mDequeueBufferCannotBlock =
779 mCore->mConsumerControlledByApp && producerControlledByApp;
780
781 return status;
782}
783
784status_t BufferQueueProducer::disconnect(int api) {
785 ATRACE_CALL();
786 BQ_LOGV("disconnect(P): api %d", api);
787
788 int status = NO_ERROR;
789 sp<IConsumerListener> listener;
790 { // Autolock scope
791 Mutex::Autolock lock(mCore->mMutex);
792
793 if (mCore->mIsAbandoned) {
794 // It's not really an error to disconnect after the surface has
795 // been abandoned; it should just be a no-op.
796 return NO_ERROR;
797 }
798
799 switch (api) {
800 case NATIVE_WINDOW_API_EGL:
801 case NATIVE_WINDOW_API_CPU:
802 case NATIVE_WINDOW_API_MEDIA:
803 case NATIVE_WINDOW_API_CAMERA:
804 if (mCore->mConnectedApi == api) {
805 mCore->freeAllBuffersLocked();
806
807 // Remove our death notification callback if we have one
Dan Stozaf0eaf252014-03-21 13:05:51 -0700808 if (mCore->mConnectedProducerListener != NULL) {
809 sp<IBinder> token =
810 mCore->mConnectedProducerListener->asBinder();
Dan Stoza289ade12014-02-28 11:17:17 -0800811 // This can fail if we're here because of the death
812 // notification, but we just ignore it
813 token->unlinkToDeath(
814 static_cast<IBinder::DeathRecipient*>(this));
815 }
Dan Stozaf0eaf252014-03-21 13:05:51 -0700816 mCore->mConnectedProducerListener = NULL;
Dan Stoza289ade12014-02-28 11:17:17 -0800817 mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API;
Jesse Hall399184a2014-03-03 15:42:54 -0800818 mCore->mSidebandStream.clear();
Dan Stoza289ade12014-02-28 11:17:17 -0800819 mCore->mDequeueCondition.broadcast();
820 listener = mCore->mConsumerListener;
821 } else {
822 BQ_LOGE("disconnect(P): connected to another API "
823 "(cur=%d req=%d)", mCore->mConnectedApi, api);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800824 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800825 }
826 break;
827 default:
828 BQ_LOGE("disconnect(P): unknown API %d", api);
Dan Stoza9f3053d2014-03-06 15:14:33 -0800829 status = BAD_VALUE;
Dan Stoza289ade12014-02-28 11:17:17 -0800830 break;
831 }
832 } // Autolock scope
833
834 // Call back without lock held
835 if (listener != NULL) {
836 listener->onBuffersReleased();
837 }
838
839 return status;
840}
841
Jesse Hall399184a2014-03-03 15:42:54 -0800842status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
Wonsik Kimafe30812014-03-31 23:16:08 +0900843 sp<IConsumerListener> listener;
844 { // Autolock scope
845 Mutex::Autolock _l(mCore->mMutex);
846 mCore->mSidebandStream = stream;
847 listener = mCore->mConsumerListener;
848 } // Autolock scope
849
850 if (listener != NULL) {
851 listener->onSidebandStreamChanged();
852 }
Jesse Hall399184a2014-03-03 15:42:54 -0800853 return NO_ERROR;
854}
855
Dan Stoza29a3e902014-06-20 13:13:57 -0700856void BufferQueueProducer::allocateBuffers(bool async, uint32_t width,
857 uint32_t height, uint32_t format, uint32_t usage) {
858 Vector<int> freeSlots;
859
860 Mutex::Autolock lock(mCore->mMutex);
861
862 int currentBufferCount = 0;
863 for (int slot = 0; slot < BufferQueueDefs::NUM_BUFFER_SLOTS; ++slot) {
864 if (mSlots[slot].mGraphicBuffer != NULL) {
865 ++currentBufferCount;
866 } else {
867 if (mSlots[slot].mBufferState != BufferSlot::FREE) {
868 BQ_LOGE("allocateBuffers: slot %d without buffer is not FREE",
869 slot);
870 continue;
871 }
872
873 freeSlots.push_front(slot);
874 }
875 }
876
877 int maxBufferCount = mCore->getMaxBufferCountLocked(async);
878 BQ_LOGV("allocateBuffers: allocating from %d buffers up to %d buffers",
879 currentBufferCount, maxBufferCount);
880 for (; currentBufferCount < maxBufferCount; ++currentBufferCount) {
881 if (freeSlots.empty()) {
882 BQ_LOGE("allocateBuffers: ran out of free slots");
883 return;
884 }
885
886 width = width > 0 ? width : mCore->mDefaultWidth;
887 height = height > 0 ? height : mCore->mDefaultHeight;
888 format = format != 0 ? format : mCore->mDefaultBufferFormat;
889 usage |= mCore->mConsumerUsageBits;
890
891 status_t result = NO_ERROR;
892 sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
893 width, height, format, usage, &result));
894 if (result != NO_ERROR) {
895 BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format"
896 " %u, usage %u)", width, height, format, usage);
897 return;
898 }
899
900 int slot = freeSlots[freeSlots.size() - 1];
901 mCore->freeBufferLocked(slot); // Clean up the slot first
902 mSlots[slot].mGraphicBuffer = graphicBuffer;
903 mSlots[slot].mFrameNumber = 0;
904 mSlots[slot].mFence = Fence::NO_FENCE;
905 BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d", slot);
906 freeSlots.pop();
907 }
908}
909
Dan Stoza289ade12014-02-28 11:17:17 -0800910void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
911 // If we're here, it means that a producer we were connected to died.
912 // We're guaranteed that we are still connected to it because we remove
913 // this callback upon disconnect. It's therefore safe to read mConnectedApi
914 // without synchronization here.
915 int api = mCore->mConnectedApi;
916 disconnect(api);
917}
918
919} // namespace android