2 * Copyright (C) 2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "BufferQueue"
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
19 //#define LOG_NDEBUG 0
21 #define GL_GLEXT_PROTOTYPES
22 #define EGL_EGLEXT_PROTOTYPES
25 #include <EGL/eglext.h>
27 #include <gui/BufferQueue.h>
28 #include <gui/ISurfaceComposer.h>
29 #include <private/gui/ComposerService.h>
31 #include <utils/Log.h>
32 #include <utils/Trace.h>
33 #include <utils/CallStack.h>
35 // Macros for including the BufferQueue name in log messages
36 #define ST_LOGV(x, ...) ALOGV("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
37 #define ST_LOGD(x, ...) ALOGD("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
38 #define ST_LOGI(x, ...) ALOGI("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
39 #define ST_LOGW(x, ...) ALOGW("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
40 #define ST_LOGE(x, ...) ALOGE("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
42 #define ATRACE_BUFFER_INDEX(index) \
43 if (ATRACE_ENABLED()) { \
44 char ___traceBuf[1024]; \
45 snprintf(___traceBuf, 1024, "%s: %d", mConsumerName.string(), \
47 android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf); \
52 // Get an ID that's unique within this process.
53 static int32_t createProcessUniqueId() {
54 static volatile int32_t globalCounter = 0;
55 return android_atomic_inc(&globalCounter);
58 static const char* scalingModeName(int scalingMode) {
59 switch (scalingMode) {
60 case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE";
61 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW";
62 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP";
63 default: return "Unknown";
67 BufferQueue::BufferQueue(const sp<IGraphicBufferAlloc>& allocator) :
70 mMaxAcquiredBufferCount(1),
71 mDefaultMaxBufferCount(2),
72 mOverrideMaxBufferCount(0),
73 mConsumerControlledByApp(false),
74 mDequeueBufferCannotBlock(false),
75 mConnectedApi(NO_CONNECTED_API),
78 mBufferHasBeenQueued(false),
79 mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),
80 mConsumerUsageBits(0),
83 // Choose a name using the PID and a process-unique ID.
84 mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
86 ST_LOGV("BufferQueue");
87 if (allocator == NULL) {
88 sp<ISurfaceComposer> composer(ComposerService::getComposerService());
89 mGraphicBufferAlloc = composer->createGraphicBufferAlloc();
90 if (mGraphicBufferAlloc == 0) {
91 ST_LOGE("createGraphicBufferAlloc() failed in BufferQueue()");
94 mGraphicBufferAlloc = allocator;
98 BufferQueue::~BufferQueue() {
99 ST_LOGV("~BufferQueue");
102 status_t BufferQueue::setDefaultMaxBufferCountLocked(int count) {
103 if (count < 2 || count > NUM_BUFFER_SLOTS)
106 mDefaultMaxBufferCount = count;
107 mDequeueCondition.broadcast();
112 void BufferQueue::setConsumerName(const String8& name) {
113 Mutex::Autolock lock(mMutex);
114 mConsumerName = name;
117 status_t BufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) {
118 Mutex::Autolock lock(mMutex);
119 mDefaultBufferFormat = defaultFormat;
123 status_t BufferQueue::setConsumerUsageBits(uint32_t usage) {
124 Mutex::Autolock lock(mMutex);
125 mConsumerUsageBits = usage;
129 status_t BufferQueue::setTransformHint(uint32_t hint) {
130 ST_LOGV("setTransformHint: %02x", hint);
131 Mutex::Autolock lock(mMutex);
132 mTransformHint = hint;
136 status_t BufferQueue::setBufferCount(int bufferCount) {
137 ST_LOGV("setBufferCount: count=%d", bufferCount);
139 sp<ConsumerListener> listener;
141 Mutex::Autolock lock(mMutex);
144 ST_LOGE("setBufferCount: BufferQueue has been abandoned!");
147 if (bufferCount > NUM_BUFFER_SLOTS) {
148 ST_LOGE("setBufferCount: bufferCount too large (max %d)",
153 // Error out if the user has dequeued buffers
154 for (int i=0 ; i<NUM_BUFFER_SLOTS; i++) {
155 if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) {
156 ST_LOGE("setBufferCount: client owns some buffers");
161 if (bufferCount == 0) {
162 mOverrideMaxBufferCount = 0;
163 mDequeueCondition.broadcast();
167 // fine to assume async to false before we're setting the buffer count
168 const int minBufferSlots = getMinMaxBufferCountLocked(false);
169 if (bufferCount < minBufferSlots) {
170 ST_LOGE("setBufferCount: requested buffer count (%d) is less than "
171 "minimum (%d)", bufferCount, minBufferSlots);
175 // here we're guaranteed that the client doesn't have dequeued buffers
176 // and will release all of its buffer references. We don't clear the
177 // queue, however, so currently queued buffers still get displayed.
178 freeAllBuffersLocked();
179 mOverrideMaxBufferCount = bufferCount;
180 mDequeueCondition.broadcast();
181 listener = mConsumerListener;
184 if (listener != NULL) {
185 listener->onBuffersReleased();
191 int BufferQueue::query(int what, int* outValue)
194 Mutex::Autolock lock(mMutex);
197 ST_LOGE("query: BufferQueue has been abandoned!");
203 case NATIVE_WINDOW_WIDTH:
204 value = mDefaultWidth;
206 case NATIVE_WINDOW_HEIGHT:
207 value = mDefaultHeight;
209 case NATIVE_WINDOW_FORMAT:
210 value = mDefaultBufferFormat;
212 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
213 value = getMinUndequeuedBufferCount(false);
215 case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
216 value = (mQueue.size() >= 2);
225 status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
227 ST_LOGV("requestBuffer: slot=%d", slot);
228 Mutex::Autolock lock(mMutex);
230 ST_LOGE("requestBuffer: BufferQueue has been abandoned!");
233 if (slot < 0 || slot >= NUM_BUFFER_SLOTS) {
234 ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d",
235 NUM_BUFFER_SLOTS, slot);
237 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
238 ST_LOGE("requestBuffer: slot %d is not owned by the client (state=%d)",
239 slot, mSlots[slot].mBufferState);
242 mSlots[slot].mRequestBufferCalled = true;
243 *buf = mSlots[slot].mGraphicBuffer;
247 status_t BufferQueue::dequeueBuffer(int *outBuf, sp<Fence>* outFence, bool async,
248 uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
250 ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);
252 if ((w && !h) || (!w && h)) {
253 ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
257 status_t returnFlags(OK);
258 EGLDisplay dpy = EGL_NO_DISPLAY;
259 EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
261 { // Scope for the lock
262 Mutex::Autolock lock(mMutex);
265 format = mDefaultBufferFormat;
267 // turn on usage bits the consumer requested
268 usage |= mConsumerUsageBits;
271 int dequeuedCount = 0;
272 bool tryAgain = true;
275 ST_LOGE("dequeueBuffer: BufferQueue has been abandoned!");
279 const int maxBufferCount = getMaxBufferCountLocked(async);
280 if (async && mOverrideMaxBufferCount) {
281 // FIXME: some drivers are manually setting the buffer-count (which they
282 // shouldn't), so we do this extra test here to handle that case.
283 // This is TEMPORARY, until we get this fixed.
284 if (mOverrideMaxBufferCount < maxBufferCount) {
285 ST_LOGE("dequeueBuffer: async mode is invalid with buffercount override");
290 // Free up any buffers that are in slots beyond the max buffer
292 for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
293 assert(mSlots[i].mBufferState == BufferSlot::FREE);
294 if (mSlots[i].mGraphicBuffer != NULL) {
296 returnFlags |= IGraphicBufferProducer::RELEASE_ALL_BUFFERS;
300 // look for a free buffer to give to the client
301 found = INVALID_BUFFER_SLOT;
303 for (int i = 0; i < maxBufferCount; i++) {
304 const int state = mSlots[i].mBufferState;
305 if (state == BufferSlot::DEQUEUED) {
309 if (state == BufferSlot::FREE) {
310 /* We return the oldest of the free buffers to avoid
311 * stalling the producer if possible. This is because
312 * the consumer may still have pending reads of the
316 mSlots[i].mFrameNumber < mSlots[found].mFrameNumber) {
322 // clients are not allowed to dequeue more than one buffer
323 // if they didn't set a buffer count.
324 if (!mOverrideMaxBufferCount && dequeuedCount) {
325 ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without "
326 "setting the buffer count");
330 // See whether a buffer has been queued since the last
331 // setBufferCount so we know whether to perform the min undequeued
332 // buffers check below.
333 if (mBufferHasBeenQueued) {
334 // make sure the client is not trying to dequeue more buffers
336 const int newUndequeuedCount = maxBufferCount - (dequeuedCount+1);
337 const int minUndequeuedCount = getMinUndequeuedBufferCount(async);
338 if (newUndequeuedCount < minUndequeuedCount) {
339 ST_LOGE("dequeueBuffer: min undequeued buffer count (%d) "
340 "exceeded (dequeued=%d undequeudCount=%d)",
341 minUndequeuedCount, dequeuedCount,
347 // If no buffer is found, wait for a buffer to be released or for
348 // the max buffer count to change.
349 tryAgain = found == INVALID_BUFFER_SLOT;
351 if (mDequeueBufferCannotBlock) {
352 ST_LOGE("dequeueBuffer: would block! returning an error instead.");
355 mDequeueCondition.wait(mMutex);
360 if (found == INVALID_BUFFER_SLOT) {
361 // This should not happen.
362 ST_LOGE("dequeueBuffer: no available buffer slots");
366 const int buf = found;
369 ATRACE_BUFFER_INDEX(buf);
371 const bool useDefaultSize = !w && !h;
372 if (useDefaultSize) {
373 // use the default size
378 mSlots[buf].mBufferState = BufferSlot::DEQUEUED;
380 const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
381 if ((buffer == NULL) ||
382 (uint32_t(buffer->width) != w) ||
383 (uint32_t(buffer->height) != h) ||
384 (uint32_t(buffer->format) != format) ||
385 ((uint32_t(buffer->usage) & usage) != usage))
387 mSlots[buf].mAcquireCalled = false;
388 mSlots[buf].mGraphicBuffer = NULL;
389 mSlots[buf].mRequestBufferCalled = false;
390 mSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
391 mSlots[buf].mFence = Fence::NO_FENCE;
392 mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
394 returnFlags |= IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION;
397 dpy = mSlots[buf].mEglDisplay;
398 eglFence = mSlots[buf].mEglFence;
399 *outFence = mSlots[buf].mFence;
400 mSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
401 mSlots[buf].mFence = Fence::NO_FENCE;
404 if (returnFlags & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
406 sp<GraphicBuffer> graphicBuffer(
407 mGraphicBufferAlloc->createGraphicBuffer(
408 w, h, format, usage, &error));
409 if (graphicBuffer == 0) {
410 ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer "
415 { // Scope for the lock
416 Mutex::Autolock lock(mMutex);
419 ST_LOGE("dequeueBuffer: BufferQueue has been abandoned!");
423 mSlots[*outBuf].mFrameNumber = ~0;
424 mSlots[*outBuf].mGraphicBuffer = graphicBuffer;
428 if (eglFence != EGL_NO_SYNC_KHR) {
429 EGLint result = eglClientWaitSyncKHR(dpy, eglFence, 0, 1000000000);
430 // If something goes wrong, log the error, but return the buffer without
431 // synchronizing access to it. It's too late at this point to abort the
432 // dequeue operation.
433 if (result == EGL_FALSE) {
434 ST_LOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError());
435 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
436 ST_LOGE("dequeueBuffer: timeout waiting for fence");
438 eglDestroySyncKHR(dpy, eglFence);
441 ST_LOGV("dequeueBuffer: returning slot=%d/%llu buf=%p flags=%#x", *outBuf,
442 mSlots[*outBuf].mFrameNumber,
443 mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);
448 status_t BufferQueue::queueBuffer(int buf,
449 const QueueBufferInput& input, QueueBufferOutput* output) {
451 ATRACE_BUFFER_INDEX(buf);
460 input.deflate(×tamp, &crop, &scalingMode, &transform, &async, &fence);
463 ST_LOGE("queueBuffer: fence is NULL");
467 switch (scalingMode) {
468 case NATIVE_WINDOW_SCALING_MODE_FREEZE:
469 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
470 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
471 case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
474 ST_LOGE("unknown scaling mode: %d", scalingMode);
478 sp<ConsumerListener> listener;
480 { // scope for the lock
481 Mutex::Autolock lock(mMutex);
484 ST_LOGE("queueBuffer: BufferQueue has been abandoned!");
488 const int maxBufferCount = getMaxBufferCountLocked(async);
489 if (async && mOverrideMaxBufferCount) {
490 // FIXME: some drivers are manually setting the buffer-count (which they
491 // shouldn't), so we do this extra test here to handle that case.
492 // This is TEMPORARY, until we get this fixed.
493 if (mOverrideMaxBufferCount < maxBufferCount) {
494 ST_LOGE("queueBuffer: async mode is invalid with buffercount override");
498 if (buf < 0 || buf >= maxBufferCount) {
499 ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d",
500 maxBufferCount, buf);
502 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
503 ST_LOGE("queueBuffer: slot %d is not owned by the client "
504 "(state=%d)", buf, mSlots[buf].mBufferState);
506 } else if (!mSlots[buf].mRequestBufferCalled) {
507 ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
512 ST_LOGV("queueBuffer: slot=%d/%llu time=%#llx crop=[%d,%d,%d,%d] "
514 buf, mFrameCounter + 1, timestamp,
515 crop.left, crop.top, crop.right, crop.bottom,
516 transform, scalingModeName(scalingMode));
518 const sp<GraphicBuffer>& graphicBuffer(mSlots[buf].mGraphicBuffer);
519 Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
521 crop.intersect(bufferRect, &croppedCrop);
522 if (croppedCrop != crop) {
523 ST_LOGE("queueBuffer: crop rect is not contained within the "
524 "buffer in slot %d", buf);
528 mSlots[buf].mFence = fence;
529 mSlots[buf].mBufferState = BufferSlot::QUEUED;
531 mSlots[buf].mFrameNumber = mFrameCounter;
534 item.mAcquireCalled = mSlots[buf].mAcquireCalled;
535 item.mGraphicBuffer = mSlots[buf].mGraphicBuffer;
537 item.mTransform = transform;
538 item.mScalingMode = scalingMode;
539 item.mTimestamp = timestamp;
540 item.mFrameNumber = mFrameCounter;
543 item.mIsDroppable = mDequeueBufferCannotBlock || async;
545 if (mQueue.empty()) {
546 // when the queue is empty, we can ignore "mDequeueBufferCannotBlock", and
547 // simply queue this buffer.
548 mQueue.push_back(item);
549 listener = mConsumerListener;
551 // when the queue is not empty, we need to look at the front buffer
552 // state and see if we need to replace it.
553 Fifo::iterator front(mQueue.begin());
554 if (front->mIsDroppable) {
555 // buffer slot currently queued is marked free if still tracked
556 if (stillTracking(front)) {
557 mSlots[front->mBuf].mBufferState = BufferSlot::FREE;
559 // and we record the new buffer in the queued list
562 mQueue.push_back(item);
563 listener = mConsumerListener;
567 mBufferHasBeenQueued = true;
568 mDequeueCondition.broadcast();
570 output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
573 ATRACE_INT(mConsumerName.string(), mQueue.size());
574 } // scope for the lock
576 // call back without lock held
578 listener->onFrameAvailable();
583 void BufferQueue::cancelBuffer(int buf, const sp<Fence>& fence) {
585 ST_LOGV("cancelBuffer: slot=%d", buf);
586 Mutex::Autolock lock(mMutex);
589 ST_LOGW("cancelBuffer: BufferQueue has been abandoned!");
593 if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
594 ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d",
595 NUM_BUFFER_SLOTS, buf);
597 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
598 ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
599 buf, mSlots[buf].mBufferState);
601 } else if (fence == NULL) {
602 ST_LOGE("cancelBuffer: fence is NULL");
605 mSlots[buf].mBufferState = BufferSlot::FREE;
606 mSlots[buf].mFrameNumber = 0;
607 mSlots[buf].mFence = fence;
608 mDequeueCondition.broadcast();
611 status_t BufferQueue::connect(int api, bool producerControlledByApp, QueueBufferOutput* output) {
613 ST_LOGV("connect: api=%d", api);
614 Mutex::Autolock lock(mMutex);
617 ST_LOGE("connect: BufferQueue has been abandoned!");
621 if (mConsumerListener == NULL) {
622 ST_LOGE("connect: BufferQueue has no consumer!");
628 case NATIVE_WINDOW_API_EGL:
629 case NATIVE_WINDOW_API_CPU:
630 case NATIVE_WINDOW_API_MEDIA:
631 case NATIVE_WINDOW_API_CAMERA:
632 if (mConnectedApi != NO_CONNECTED_API) {
633 ST_LOGE("connect: already connected (cur=%d, req=%d)",
638 output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
647 mBufferHasBeenQueued = false;
648 mDequeueBufferCannotBlock = mConsumerControlledByApp && producerControlledByApp;
653 status_t BufferQueue::disconnect(int api) {
655 ST_LOGV("disconnect: api=%d", api);
658 sp<ConsumerListener> listener;
660 { // Scope for the lock
661 Mutex::Autolock lock(mMutex);
664 // it is not really an error to disconnect after the surface
665 // has been abandoned, it should just be a no-op.
670 case NATIVE_WINDOW_API_EGL:
671 case NATIVE_WINDOW_API_CPU:
672 case NATIVE_WINDOW_API_MEDIA:
673 case NATIVE_WINDOW_API_CAMERA:
674 if (mConnectedApi == api) {
675 freeAllBuffersLocked();
676 mConnectedApi = NO_CONNECTED_API;
677 mDequeueCondition.broadcast();
678 listener = mConsumerListener;
680 ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)",
686 ST_LOGE("disconnect: unknown API %d", api);
692 if (listener != NULL) {
693 listener->onBuffersReleased();
699 void BufferQueue::dump(String8& result) const {
700 BufferQueue::dump(result, "");
703 void BufferQueue::dump(String8& result, const char* prefix) const {
704 Mutex::Autolock _l(mMutex);
708 Fifo::const_iterator i(mQueue.begin());
709 while (i != mQueue.end()) {
710 fifo.appendFormat("%02d:%p crop=[%d,%d,%d,%d], "
711 "xform=0x%02x, time=%#llx, scale=%s\n",
712 i->mBuf, i->mGraphicBuffer.get(),
713 i->mCrop.left, i->mCrop.top, i->mCrop.right,
714 i->mCrop.bottom, i->mTransform, i->mTimestamp,
715 scalingModeName(i->mScalingMode)
723 "%s-BufferQueue mMaxAcquiredBufferCount=%d, mDequeueBufferCannotBlock=%d, default-size=[%dx%d], "
724 "default-format=%d, transform-hint=%02x, FIFO(%d)={%s}\n",
725 prefix, mMaxAcquiredBufferCount, mDequeueBufferCannotBlock, mDefaultWidth,
726 mDefaultHeight, mDefaultBufferFormat, mTransformHint,
727 fifoSize, fifo.string());
730 const char * operator()(int state) const {
732 case BufferSlot::DEQUEUED: return "DEQUEUED";
733 case BufferSlot::QUEUED: return "QUEUED";
734 case BufferSlot::FREE: return "FREE";
735 case BufferSlot::ACQUIRED: return "ACQUIRED";
736 default: return "Unknown";
741 // just trim the free buffers to not spam the dump
742 int maxBufferCount = 0;
743 for (int i=NUM_BUFFER_SLOTS-1 ; i>=0 ; i--) {
744 const BufferSlot& slot(mSlots[i]);
745 if ((slot.mBufferState != BufferSlot::FREE) || (slot.mGraphicBuffer != NULL)) {
746 maxBufferCount = i+1;
751 for (int i=0 ; i<maxBufferCount ; i++) {
752 const BufferSlot& slot(mSlots[i]);
753 const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
755 "%s%s[%02d:%p] state=%-8s",
756 prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i, buf.get(),
757 stateName(slot.mBufferState)
762 ", %p [%4ux%4u:%4u,%3X]",
763 buf->handle, buf->width, buf->height, buf->stride,
770 void BufferQueue::freeBufferLocked(int slot) {
771 ST_LOGV("freeBufferLocked: slot=%d", slot);
772 mSlots[slot].mGraphicBuffer = 0;
773 if (mSlots[slot].mBufferState == BufferSlot::ACQUIRED) {
774 mSlots[slot].mNeedsCleanupOnRelease = true;
776 mSlots[slot].mBufferState = BufferSlot::FREE;
777 mSlots[slot].mFrameNumber = 0;
778 mSlots[slot].mAcquireCalled = false;
780 // destroy fence as BufferQueue now takes ownership
781 if (mSlots[slot].mEglFence != EGL_NO_SYNC_KHR) {
782 eglDestroySyncKHR(mSlots[slot].mEglDisplay, mSlots[slot].mEglFence);
783 mSlots[slot].mEglFence = EGL_NO_SYNC_KHR;
785 mSlots[slot].mFence = Fence::NO_FENCE;
788 void BufferQueue::freeAllBuffersLocked() {
789 mBufferHasBeenQueued = false;
790 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
795 status_t BufferQueue::acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) {
797 Mutex::Autolock _l(mMutex);
799 // Check that the consumer doesn't currently have the maximum number of
800 // buffers acquired. We allow the max buffer count to be exceeded by one
801 // buffer, so that the consumer can successfully set up the newly acquired
802 // buffer before releasing the old one.
803 int numAcquiredBuffers = 0;
804 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
805 if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
806 numAcquiredBuffers++;
809 if (numAcquiredBuffers >= mMaxAcquiredBufferCount+1) {
810 ST_LOGE("acquireBuffer: max acquired buffer count reached: %d (max=%d)",
811 numAcquiredBuffers, mMaxAcquiredBufferCount);
812 return INVALID_OPERATION;
815 // check if queue is empty
816 // In asynchronous mode the list is guaranteed to be one buffer
817 // deep, while in synchronous mode we use the oldest buffer.
818 if (mQueue.empty()) {
819 return NO_BUFFER_AVAILABLE;
822 Fifo::iterator front(mQueue.begin());
823 int buf = front->mBuf;
825 // Compare the buffer's desired presentation time to the predicted
826 // actual display time.
828 // The "presentWhen" argument indicates when the buffer is expected
829 // to be presented on-screen. If the buffer's desired-present time
830 // is earlier (less) than presentWhen, meaning it'll be displayed
831 // on time or possibly late, we acquire and return it. If we don't want
832 // to display it until after the presentWhen time, we return PRESENT_LATER
833 // without acquiring it.
835 // To be safe, we don't refuse to acquire the buffer if presentWhen is
836 // more than one second in the future beyond the desired present time
837 // (i.e. we'd be holding the buffer for a really long time).
838 const int MAX_FUTURE_NSEC = 1000000000ULL;
839 nsecs_t desiredPresent = front->mTimestamp;
840 if (presentWhen != 0 && desiredPresent > presentWhen &&
841 desiredPresent - presentWhen < MAX_FUTURE_NSEC)
843 ALOGV("pts defer: des=%lld when=%lld (%lld) now=%lld",
844 desiredPresent, presentWhen, desiredPresent - presentWhen,
845 systemTime(CLOCK_MONOTONIC));
846 return PRESENT_LATER;
848 if (presentWhen != 0) {
849 ALOGV("pts accept: %p[%d] sig=%lld des=%lld when=%lld (%lld)",
850 mSlots, buf, mSlots[buf].mFence->getSignalTime(),
851 desiredPresent, presentWhen, desiredPresent - presentWhen);
855 ATRACE_BUFFER_INDEX(buf);
857 ST_LOGV("acquireBuffer: acquiring { slot=%d/%llu, buffer=%p }",
858 front->mBuf, front->mFrameNumber,
859 front->mGraphicBuffer->handle);
860 // if front buffer still being tracked update slot state
861 if (stillTracking(front)) {
862 mSlots[buf].mAcquireCalled = true;
863 mSlots[buf].mNeedsCleanupOnRelease = false;
864 mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
865 mSlots[buf].mFence = Fence::NO_FENCE;
868 // If the buffer has previously been acquired by the consumer, set
869 // mGraphicBuffer to NULL to avoid unnecessarily remapping this
870 // buffer on the consumer side.
871 if (buffer->mAcquireCalled) {
872 buffer->mGraphicBuffer = NULL;
876 mDequeueCondition.broadcast();
878 ATRACE_INT(mConsumerName.string(), mQueue.size());
883 status_t BufferQueue::releaseBuffer(
884 int buf, uint64_t frameNumber, EGLDisplay display,
885 EGLSyncKHR eglFence, const sp<Fence>& fence) {
887 ATRACE_BUFFER_INDEX(buf);
889 Mutex::Autolock _l(mMutex);
891 if (buf == INVALID_BUFFER_SLOT || fence == NULL) {
895 // Check if this buffer slot is on the queue
896 bool slotQueued = false;
897 Fifo::iterator front(mQueue.begin());
898 while (front != mQueue.end() && !slotQueued) {
899 if (front->mBuf == buf)
904 // If the frame number has changed because buffer has been reallocated,
905 // we can ignore this releaseBuffer for the old buffer.
906 if (frameNumber != mSlots[buf].mFrameNumber) {
907 // This should only occur if new buffer is still in the queue
908 ALOGE_IF(!slotQueued,
909 "received old buffer(#%lld) after new buffer(#%lld) on same "
910 "slot #%d already acquired", frameNumber,
911 mSlots[buf].mFrameNumber, buf);
912 return STALE_BUFFER_SLOT;
914 // this should never happen
916 "received new buffer(#%lld) on slot #%d that has not yet been "
917 "acquired", frameNumber, buf);
919 // The buffer can now only be released if its in the acquired state
920 if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
921 mSlots[buf].mEglDisplay = display;
922 mSlots[buf].mEglFence = eglFence;
923 mSlots[buf].mFence = fence;
924 mSlots[buf].mBufferState = BufferSlot::FREE;
925 } else if (mSlots[buf].mNeedsCleanupOnRelease) {
926 ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState);
927 mSlots[buf].mNeedsCleanupOnRelease = false;
928 return STALE_BUFFER_SLOT;
930 ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState);
934 mDequeueCondition.broadcast();
938 status_t BufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener,
939 bool controlledByApp) {
940 ST_LOGV("consumerConnect");
941 Mutex::Autolock lock(mMutex);
944 ST_LOGE("consumerConnect: BufferQueue has been abandoned!");
947 if (consumerListener == NULL) {
948 ST_LOGE("consumerConnect: consumerListener may not be NULL");
952 mConsumerListener = consumerListener;
953 mConsumerControlledByApp = controlledByApp;
958 status_t BufferQueue::consumerDisconnect() {
959 ST_LOGV("consumerDisconnect");
960 Mutex::Autolock lock(mMutex);
962 if (mConsumerListener == NULL) {
963 ST_LOGE("consumerDisconnect: No consumer is connected!");
968 mConsumerListener = NULL;
970 freeAllBuffersLocked();
971 mDequeueCondition.broadcast();
975 status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) {
976 ST_LOGV("getReleasedBuffers");
977 Mutex::Autolock lock(mMutex);
980 ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!");
985 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
986 if (!mSlots[i].mAcquireCalled) {
991 // Remove buffers in flight (on the queue) from the mask where acquire has
992 // been called, as the consumer will not receive the buffer address, so
993 // it should not free these slots.
994 Fifo::iterator front(mQueue.begin());
995 while (front != mQueue.end()) {
996 if (front->mAcquireCalled)
997 mask &= ~(1 << front->mBuf);
1003 ST_LOGV("getReleasedBuffers: returning mask %#x", mask);
1007 status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h)
1009 ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
1011 ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
1016 Mutex::Autolock lock(mMutex);
1022 status_t BufferQueue::setDefaultMaxBufferCount(int bufferCount) {
1024 Mutex::Autolock lock(mMutex);
1025 return setDefaultMaxBufferCountLocked(bufferCount);
1028 status_t BufferQueue::setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
1030 Mutex::Autolock lock(mMutex);
1031 if (maxAcquiredBuffers < 1 || maxAcquiredBuffers > MAX_MAX_ACQUIRED_BUFFERS) {
1032 ST_LOGE("setMaxAcquiredBufferCount: invalid count specified: %d",
1033 maxAcquiredBuffers);
1036 if (mConnectedApi != NO_CONNECTED_API) {
1037 return INVALID_OPERATION;
1039 mMaxAcquiredBufferCount = maxAcquiredBuffers;
1043 int BufferQueue::getMinUndequeuedBufferCount(bool async) const {
1044 return (mDequeueBufferCannotBlock || async) ?
1045 mMaxAcquiredBufferCount+1 : mMaxAcquiredBufferCount;
1048 int BufferQueue::getMinMaxBufferCountLocked(bool async) const {
1049 return getMinUndequeuedBufferCount(async) + 1;
1052 int BufferQueue::getMaxBufferCountLocked(bool async) const {
1053 int minMaxBufferCount = getMinMaxBufferCountLocked(async);
1055 int maxBufferCount = mDefaultMaxBufferCount;
1056 if (maxBufferCount < minMaxBufferCount) {
1057 maxBufferCount = minMaxBufferCount;
1059 if (mOverrideMaxBufferCount != 0) {
1060 assert(mOverrideMaxBufferCount >= minMaxBufferCount);
1061 maxBufferCount = mOverrideMaxBufferCount;
1064 // Any buffers that are dequeued by the producer or sitting in the queue
1065 // waiting to be consumed need to have their slots preserved. Such
1066 // buffers will temporarily keep the max buffer count up until the slots
1067 // no longer need to be preserved.
1068 for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
1069 BufferSlot::BufferState state = mSlots[i].mBufferState;
1070 if (state == BufferSlot::QUEUED || state == BufferSlot::DEQUEUED) {
1071 maxBufferCount = i + 1;
1075 return maxBufferCount;
1078 bool BufferQueue::stillTracking(const BufferItem *item) const {
1079 const BufferSlot &slot = mSlots[item->mBuf];
1081 ST_LOGV("stillTracking?: item: { slot=%d/%llu, buffer=%p }, "
1082 "slot: { slot=%d/%llu, buffer=%p }",
1083 item->mBuf, item->mFrameNumber,
1084 (item->mGraphicBuffer.get() ? item->mGraphicBuffer->handle : 0),
1085 item->mBuf, slot.mFrameNumber,
1086 (slot.mGraphicBuffer.get() ? slot.mGraphicBuffer->handle : 0));
1088 // Compare item with its original buffer slot. We can check the slot
1089 // as the buffer would not be moved to a different slot by the producer.
1090 return (slot.mGraphicBuffer != NULL &&
1091 item->mGraphicBuffer->handle == slot.mGraphicBuffer->handle);
1094 BufferQueue::ProxyConsumerListener::ProxyConsumerListener(
1095 const wp<BufferQueue::ConsumerListener>& consumerListener):
1096 mConsumerListener(consumerListener) {}
1098 BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}
1100 void BufferQueue::ProxyConsumerListener::onFrameAvailable() {
1101 sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1102 if (listener != NULL) {
1103 listener->onFrameAvailable();
1107 void BufferQueue::ProxyConsumerListener::onBuffersReleased() {
1108 sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1109 if (listener != NULL) {
1110 listener->onBuffersReleased();
1114 }; // namespace android