BufferQueueProducer.cpp revision 0a0680945710946f3bf01ae05f933ccec4162dc8
1/*
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
17#include <inttypes.h>
18
19#define LOG_TAG "BufferQueueProducer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21//#define LOG_NDEBUG 0
22
23#if DEBUG_ONLY_CODE
24#define VALIDATE_CONSISTENCY() do { mCore->validateConsistencyLocked(); } while (0)
25#else
26#define VALIDATE_CONSISTENCY()
27#endif
28
29#define EGL_EGLEXT_PROTOTYPES
30
31#include <gui/BufferItem.h>
32#include <gui/BufferQueueCore.h>
33#include <gui/BufferQueueProducer.h>
34#include <gui/GLConsumer.h>
35#include <gui/IConsumerListener.h>
36#include <gui/IGraphicBufferAlloc.h>
37#include <gui/IProducerListener.h>
38
39#include <utils/Log.h>
40#include <utils/Trace.h>
41
42namespace android {
43
44BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core) :
45    mCore(core),
46    mSlots(core->mSlots),
47    mConsumerName(),
48    mStickyTransform(0),
49    mLastQueueBufferFence(Fence::NO_FENCE),
50    mCallbackMutex(),
51    mNextCallbackTicket(0),
52    mCurrentCallbackTicket(0),
53    mCallbackCondition(),
54    mDequeueTimeout(-1) {}
55
56BufferQueueProducer::~BufferQueueProducer() {}
57
58status_t BufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
59    ATRACE_CALL();
60    BQ_LOGV("requestBuffer: slot %d", slot);
61    Mutex::Autolock lock(mCore->mMutex);
62
63    if (mCore->mIsAbandoned) {
64        BQ_LOGE("requestBuffer: BufferQueue has been abandoned");
65        return NO_INIT;
66    }
67
68    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
69        BQ_LOGE("requestBuffer: BufferQueue has no connected producer");
70        return NO_INIT;
71    }
72
73    if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
74        BQ_LOGE("requestBuffer: slot index %d out of range [0, %d)",
75                slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
76        return BAD_VALUE;
77    } else if (!mSlots[slot].mBufferState.isDequeued()) {
78        BQ_LOGE("requestBuffer: slot %d is not owned by the producer "
79                "(state = %s)", slot, mSlots[slot].mBufferState.string());
80        return BAD_VALUE;
81    }
82
83    mSlots[slot].mRequestBufferCalled = true;
84    *buf = mSlots[slot].mGraphicBuffer;
85    return NO_ERROR;
86}
87
88status_t BufferQueueProducer::setMaxDequeuedBufferCount(
89        int maxDequeuedBuffers) {
90    ATRACE_CALL();
91    BQ_LOGV("setMaxDequeuedBufferCount: maxDequeuedBuffers = %d",
92            maxDequeuedBuffers);
93
94    sp<IConsumerListener> listener;
95    { // Autolock scope
96        Mutex::Autolock lock(mCore->mMutex);
97        mCore->waitWhileAllocatingLocked();
98
99        if (mCore->mIsAbandoned) {
100            BQ_LOGE("setMaxDequeuedBufferCount: BufferQueue has been "
101                    "abandoned");
102            return NO_INIT;
103        }
104
105        if (maxDequeuedBuffers == mCore->mMaxDequeuedBufferCount) {
106            return NO_ERROR;
107        }
108
109        // The new maxDequeuedBuffer count should not be violated by the number
110        // of currently dequeued buffers
111        int dequeuedCount = 0;
112        for (int s : mCore->mActiveBuffers) {
113            if (mSlots[s].mBufferState.isDequeued()) {
114                dequeuedCount++;
115            }
116        }
117        if (dequeuedCount > maxDequeuedBuffers) {
118            BQ_LOGE("setMaxDequeuedBufferCount: the requested maxDequeuedBuffer"
119                    "count (%d) exceeds the current dequeued buffer count (%d)",
120                    maxDequeuedBuffers, dequeuedCount);
121            return BAD_VALUE;
122        }
123
124        int bufferCount = mCore->getMinUndequeuedBufferCountLocked();
125        bufferCount += maxDequeuedBuffers;
126
127        if (bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) {
128            BQ_LOGE("setMaxDequeuedBufferCount: bufferCount %d too large "
129                    "(max %d)", bufferCount, BufferQueueDefs::NUM_BUFFER_SLOTS);
130            return BAD_VALUE;
131        }
132
133        const int minBufferSlots = mCore->getMinMaxBufferCountLocked();
134        if (bufferCount < minBufferSlots) {
135            BQ_LOGE("setMaxDequeuedBufferCount: requested buffer count %d is "
136                    "less than minimum %d", bufferCount, minBufferSlots);
137            return BAD_VALUE;
138        }
139
140        if (bufferCount > mCore->mMaxBufferCount) {
141            BQ_LOGE("setMaxDequeuedBufferCount: %d dequeued buffers would "
142                    "exceed the maxBufferCount (%d) (maxAcquired %d async %d "
143                    "mDequeuedBufferCannotBlock %d)", maxDequeuedBuffers,
144                    mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
145                    mCore->mAsyncMode, mCore->mDequeueBufferCannotBlock);
146            return BAD_VALUE;
147        }
148
149        int delta = maxDequeuedBuffers - mCore->mMaxDequeuedBufferCount;
150        if (!mCore->adjustAvailableSlotsLocked(delta)) {
151            return BAD_VALUE;
152        }
153        mCore->mMaxDequeuedBufferCount = maxDequeuedBuffers;
154        VALIDATE_CONSISTENCY();
155        if (delta < 0) {
156            listener = mCore->mConsumerListener;
157        }
158        mCore->mDequeueCondition.broadcast();
159    } // Autolock scope
160
161    // Call back without lock held
162    if (listener != NULL) {
163        listener->onBuffersReleased();
164    }
165
166    return NO_ERROR;
167}
168
169status_t BufferQueueProducer::setAsyncMode(bool async) {
170    ATRACE_CALL();
171    BQ_LOGV("setAsyncMode: async = %d", async);
172
173    sp<IConsumerListener> listener;
174    { // Autolock scope
175        Mutex::Autolock lock(mCore->mMutex);
176        mCore->waitWhileAllocatingLocked();
177
178        if (mCore->mIsAbandoned) {
179            BQ_LOGE("setAsyncMode: BufferQueue has been abandoned");
180            return NO_INIT;
181        }
182
183        if (async == mCore->mAsyncMode) {
184            return NO_ERROR;
185        }
186
187        if ((mCore->mMaxAcquiredBufferCount + mCore->mMaxDequeuedBufferCount +
188                (async || mCore->mDequeueBufferCannotBlock ? 1 : 0)) >
189                mCore->mMaxBufferCount) {
190            BQ_LOGE("setAsyncMode(%d): this call would cause the "
191                    "maxBufferCount (%d) to be exceeded (maxAcquired %d "
192                    "maxDequeued %d mDequeueBufferCannotBlock %d)", async,
193                    mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
194                    mCore->mMaxDequeuedBufferCount,
195                    mCore->mDequeueBufferCannotBlock);
196            return BAD_VALUE;
197        }
198
199        int delta = mCore->getMaxBufferCountLocked(async,
200                mCore->mDequeueBufferCannotBlock, mCore->mMaxBufferCount)
201                - mCore->getMaxBufferCountLocked();
202
203        if (!mCore->adjustAvailableSlotsLocked(delta)) {
204            BQ_LOGE("setAsyncMode: BufferQueue failed to adjust the number of "
205                    "available slots. Delta = %d", delta);
206            return BAD_VALUE;
207        }
208        mCore->mAsyncMode = async;
209        VALIDATE_CONSISTENCY();
210        mCore->mDequeueCondition.broadcast();
211        if (delta < 0) {
212            listener = mCore->mConsumerListener;
213        }
214    } // Autolock scope
215
216    // Call back without lock held
217    if (listener != NULL) {
218        listener->onBuffersReleased();
219    }
220    return NO_ERROR;
221}
222
223int BufferQueueProducer::getFreeBufferLocked() const {
224    if (mCore->mFreeBuffers.empty()) {
225        return BufferQueueCore::INVALID_BUFFER_SLOT;
226    }
227    int slot = mCore->mFreeBuffers.front();
228    mCore->mFreeBuffers.pop_front();
229    return slot;
230}
231
232int BufferQueueProducer::getFreeSlotLocked() const {
233    if (mCore->mFreeSlots.empty()) {
234        return BufferQueueCore::INVALID_BUFFER_SLOT;
235    }
236    int slot = *(mCore->mFreeSlots.begin());
237    mCore->mFreeSlots.erase(slot);
238    return slot;
239}
240
241status_t BufferQueueProducer::waitForFreeSlotThenRelock(FreeSlotCaller caller,
242        int* found) const {
243    auto callerString = (caller == FreeSlotCaller::Dequeue) ?
244            "dequeueBuffer" : "attachBuffer";
245    bool tryAgain = true;
246    while (tryAgain) {
247        if (mCore->mIsAbandoned) {
248            BQ_LOGE("%s: BufferQueue has been abandoned", callerString);
249            return NO_INIT;
250        }
251
252        int dequeuedCount = 0;
253        int acquiredCount = 0;
254        for (int s : mCore->mActiveBuffers) {
255            if (mSlots[s].mBufferState.isDequeued()) {
256                ++dequeuedCount;
257            }
258            if (mSlots[s].mBufferState.isAcquired()) {
259                ++acquiredCount;
260            }
261        }
262
263        // Producers are not allowed to dequeue more than
264        // mMaxDequeuedBufferCount buffers.
265        // This check is only done if a buffer has already been queued
266        if (mCore->mBufferHasBeenQueued &&
267                dequeuedCount >= mCore->mMaxDequeuedBufferCount) {
268            BQ_LOGE("%s: attempting to exceed the max dequeued buffer count "
269                    "(%d)", callerString, mCore->mMaxDequeuedBufferCount);
270            return INVALID_OPERATION;
271        }
272
273        *found = BufferQueueCore::INVALID_BUFFER_SLOT;
274
275        // If we disconnect and reconnect quickly, we can be in a state where
276        // our slots are empty but we have many buffers in the queue. This can
277        // cause us to run out of memory if we outrun the consumer. Wait here if
278        // it looks like we have too many buffers queued up.
279        const int maxBufferCount = mCore->getMaxBufferCountLocked();
280        bool tooManyBuffers = mCore->mQueue.size()
281                            > static_cast<size_t>(maxBufferCount);
282        if (tooManyBuffers) {
283            BQ_LOGV("%s: queue size is %zu, waiting", callerString,
284                    mCore->mQueue.size());
285        } else {
286            // If in shared buffer mode and a shared buffer exists, always
287            // return it.
288            if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot !=
289                    BufferQueueCore::INVALID_BUFFER_SLOT) {
290                *found = mCore->mSharedBufferSlot;
291            } else {
292                if (caller == FreeSlotCaller::Dequeue) {
293                    // If we're calling this from dequeue, prefer free buffers
294                    int slot = getFreeBufferLocked();
295                    if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
296                        *found = slot;
297                    } else if (mCore->mAllowAllocation) {
298                        *found = getFreeSlotLocked();
299                    }
300                } else {
301                    // If we're calling this from attach, prefer free slots
302                    int slot = getFreeSlotLocked();
303                    if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
304                        *found = slot;
305                    } else {
306                        *found = getFreeBufferLocked();
307                    }
308                }
309            }
310        }
311
312        // If no buffer is found, or if the queue has too many buffers
313        // outstanding, wait for a buffer to be acquired or released, or for the
314        // max buffer count to change.
315        tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
316                   tooManyBuffers;
317        if (tryAgain) {
318            // Return an error if we're in non-blocking mode (producer and
319            // consumer are controlled by the application).
320            // However, the consumer is allowed to briefly acquire an extra
321            // buffer (which could cause us to have to wait here), which is
322            // okay, since it is only used to implement an atomic acquire +
323            // release (e.g., in GLConsumer::updateTexImage())
324            if ((mCore->mDequeueBufferCannotBlock || mCore->mAsyncMode) &&
325                    (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
326                return WOULD_BLOCK;
327            }
328            if (mDequeueTimeout >= 0) {
329                status_t result = mCore->mDequeueCondition.waitRelative(
330                        mCore->mMutex, mDequeueTimeout);
331                if (result == TIMED_OUT) {
332                    return result;
333                }
334            } else {
335                mCore->mDequeueCondition.wait(mCore->mMutex);
336            }
337        }
338    } // while (tryAgain)
339
340    return NO_ERROR;
341}
342
343status_t BufferQueueProducer::dequeueBuffer(int *outSlot,
344        sp<android::Fence> *outFence, uint32_t width, uint32_t height,
345        PixelFormat format, uint32_t usage) {
346    ATRACE_CALL();
347    { // Autolock scope
348        Mutex::Autolock lock(mCore->mMutex);
349        mConsumerName = mCore->mConsumerName;
350
351        if (mCore->mIsAbandoned) {
352            BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
353            return NO_INIT;
354        }
355
356        if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
357            BQ_LOGE("dequeueBuffer: BufferQueue has no connected producer");
358            return NO_INIT;
359        }
360    } // Autolock scope
361
362    BQ_LOGV("dequeueBuffer: w=%u h=%u format=%#x, usage=%#x", width, height,
363            format, usage);
364
365    if ((width && !height) || (!width && height)) {
366        BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
367        return BAD_VALUE;
368    }
369
370    status_t returnFlags = NO_ERROR;
371    EGLDisplay eglDisplay = EGL_NO_DISPLAY;
372    EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
373    bool attachedByConsumer = false;
374
375    { // Autolock scope
376        Mutex::Autolock lock(mCore->mMutex);
377        mCore->waitWhileAllocatingLocked();
378
379        if (format == 0) {
380            format = mCore->mDefaultBufferFormat;
381        }
382
383        // Enable the usage bits the consumer requested
384        usage |= mCore->mConsumerUsageBits;
385
386        const bool useDefaultSize = !width && !height;
387        if (useDefaultSize) {
388            width = mCore->mDefaultWidth;
389            height = mCore->mDefaultHeight;
390        }
391
392        int found = BufferItem::INVALID_BUFFER_SLOT;
393        while (found == BufferItem::INVALID_BUFFER_SLOT) {
394            status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Dequeue,
395                    &found);
396            if (status != NO_ERROR) {
397                return status;
398            }
399
400            // This should not happen
401            if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
402                BQ_LOGE("dequeueBuffer: no available buffer slots");
403                return -EBUSY;
404            }
405
406            const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
407
408            // If we are not allowed to allocate new buffers,
409            // waitForFreeSlotThenRelock must have returned a slot containing a
410            // buffer. If this buffer would require reallocation to meet the
411            // requested attributes, we free it and attempt to get another one.
412            if (!mCore->mAllowAllocation) {
413                if (buffer->needsReallocation(width, height, format, usage)) {
414                    if (mCore->mSharedBufferSlot == found) {
415                        BQ_LOGE("dequeueBuffer: cannot re-allocate a shared"
416                                "buffer");
417                        return BAD_VALUE;
418                    }
419                    mCore->mFreeSlots.insert(found);
420                    mCore->clearBufferSlotLocked(found);
421                    found = BufferItem::INVALID_BUFFER_SLOT;
422                    continue;
423                }
424            }
425        }
426
427        const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
428        if (mCore->mSharedBufferSlot == found &&
429                buffer->needsReallocation(width,  height, format, usage)) {
430            BQ_LOGE("dequeueBuffer: cannot re-allocate a shared"
431                    "buffer");
432
433            return BAD_VALUE;
434        }
435
436        if (mCore->mSharedBufferSlot != found) {
437            mCore->mActiveBuffers.insert(found);
438        }
439        *outSlot = found;
440        ATRACE_BUFFER_INDEX(found);
441
442        attachedByConsumer = mSlots[found].mNeedsReallocation;
443        mSlots[found].mNeedsReallocation = false;
444
445        mSlots[found].mBufferState.dequeue();
446
447        if ((buffer == NULL) ||
448                buffer->needsReallocation(width, height, format, usage))
449        {
450            mSlots[found].mAcquireCalled = false;
451            mSlots[found].mGraphicBuffer = NULL;
452            mSlots[found].mRequestBufferCalled = false;
453            mSlots[found].mEglDisplay = EGL_NO_DISPLAY;
454            mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
455            mSlots[found].mFence = Fence::NO_FENCE;
456            mCore->mBufferAge = 0;
457            mCore->mIsAllocating = true;
458
459            returnFlags |= BUFFER_NEEDS_REALLOCATION;
460        } else {
461            // We add 1 because that will be the frame number when this buffer
462            // is queued
463            mCore->mBufferAge =
464                    mCore->mFrameCounter + 1 - mSlots[found].mFrameNumber;
465        }
466
467        BQ_LOGV("dequeueBuffer: setting buffer age to %" PRIu64,
468                mCore->mBufferAge);
469
470        if (CC_UNLIKELY(mSlots[found].mFence == NULL)) {
471            BQ_LOGE("dequeueBuffer: about to return a NULL fence - "
472                    "slot=%d w=%d h=%d format=%u",
473                    found, buffer->width, buffer->height, buffer->format);
474        }
475
476        eglDisplay = mSlots[found].mEglDisplay;
477        eglFence = mSlots[found].mEglFence;
478        // Don't return a fence in shared buffer mode, except for the first
479        // frame.
480        *outFence = (mCore->mSharedBufferMode &&
481                mCore->mSharedBufferSlot == found) ?
482                Fence::NO_FENCE : mSlots[found].mFence;
483        mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
484        mSlots[found].mFence = Fence::NO_FENCE;
485
486        // If shared buffer mode has just been enabled, cache the slot of the
487        // first buffer that is dequeued and mark it as the shared buffer.
488        if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
489                BufferQueueCore::INVALID_BUFFER_SLOT) {
490            mCore->mSharedBufferSlot = found;
491            mSlots[found].mBufferState.mShared = true;
492        }
493    } // Autolock scope
494
495    if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
496        status_t error;
497        BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
498        sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
499                width, height, format, usage, &error));
500        { // Autolock scope
501            Mutex::Autolock lock(mCore->mMutex);
502
503            if (graphicBuffer != NULL && !mCore->mIsAbandoned) {
504                graphicBuffer->setGenerationNumber(mCore->mGenerationNumber);
505                mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
506            }
507
508            mCore->mIsAllocating = false;
509            mCore->mIsAllocatingCondition.broadcast();
510
511            if (graphicBuffer == NULL) {
512                mCore->mFreeSlots.insert(*outSlot);
513                mCore->clearBufferSlotLocked(*outSlot);
514                BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
515                return error;
516            }
517
518            if (mCore->mIsAbandoned) {
519                mCore->mFreeSlots.insert(*outSlot);
520                mCore->clearBufferSlotLocked(*outSlot);
521                BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
522                return NO_INIT;
523            }
524
525            VALIDATE_CONSISTENCY();
526        } // Autolock scope
527    }
528
529    if (attachedByConsumer) {
530        returnFlags |= BUFFER_NEEDS_REALLOCATION;
531    }
532
533    if (eglFence != EGL_NO_SYNC_KHR) {
534        EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0,
535                1000000000);
536        // If something goes wrong, log the error, but return the buffer without
537        // synchronizing access to it. It's too late at this point to abort the
538        // dequeue operation.
539        if (result == EGL_FALSE) {
540            BQ_LOGE("dequeueBuffer: error %#x waiting for fence",
541                    eglGetError());
542        } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
543            BQ_LOGE("dequeueBuffer: timeout waiting for fence");
544        }
545        eglDestroySyncKHR(eglDisplay, eglFence);
546    }
547
548    BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
549            *outSlot,
550            mSlots[*outSlot].mFrameNumber,
551            mSlots[*outSlot].mGraphicBuffer->handle, returnFlags);
552
553    return returnFlags;
554}
555
556status_t BufferQueueProducer::detachBuffer(int slot) {
557    ATRACE_CALL();
558    ATRACE_BUFFER_INDEX(slot);
559    BQ_LOGV("detachBuffer: slot %d", slot);
560
561    sp<IConsumerListener> listener;
562    {
563        Mutex::Autolock lock(mCore->mMutex);
564
565        if (mCore->mIsAbandoned) {
566            BQ_LOGE("detachBuffer: BufferQueue has been abandoned");
567            return NO_INIT;
568        }
569
570        if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
571            BQ_LOGE("detachBuffer: BufferQueue has no connected producer");
572            return NO_INIT;
573        }
574
575        if (mCore->mSharedBufferMode || mCore->mSharedBufferSlot == slot) {
576            BQ_LOGE("detachBuffer: cannot detach a buffer in shared buffer mode");
577            return BAD_VALUE;
578        }
579
580        if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
581            BQ_LOGE("detachBuffer: slot index %d out of range [0, %d)",
582                    slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
583            return BAD_VALUE;
584        } else if (!mSlots[slot].mBufferState.isDequeued()) {
585            BQ_LOGE("detachBuffer: slot %d is not owned by the producer "
586                    "(state = %s)", slot, mSlots[slot].mBufferState.string());
587            return BAD_VALUE;
588        } else if (!mSlots[slot].mRequestBufferCalled) {
589            BQ_LOGE("detachBuffer: buffer in slot %d has not been requested",
590                    slot);
591            return BAD_VALUE;
592        }
593
594        mSlots[slot].mBufferState.detachProducer();
595        mCore->mActiveBuffers.erase(slot);
596        mCore->mFreeSlots.insert(slot);
597        mCore->clearBufferSlotLocked(slot);
598        mCore->mDequeueCondition.broadcast();
599        VALIDATE_CONSISTENCY();
600        listener = mCore->mConsumerListener;
601    }
602
603    if (listener != NULL) {
604        listener->onBuffersReleased();
605    }
606
607    return NO_ERROR;
608}
609
610status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
611        sp<Fence>* outFence) {
612    ATRACE_CALL();
613
614    if (outBuffer == NULL) {
615        BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
616        return BAD_VALUE;
617    } else if (outFence == NULL) {
618        BQ_LOGE("detachNextBuffer: outFence must not be NULL");
619        return BAD_VALUE;
620    }
621
622    Mutex::Autolock lock(mCore->mMutex);
623
624    if (mCore->mIsAbandoned) {
625        BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
626        return NO_INIT;
627    }
628
629    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
630        BQ_LOGE("detachNextBuffer: BufferQueue has no connected producer");
631        return NO_INIT;
632    }
633
634    if (mCore->mSharedBufferMode) {
635        BQ_LOGE("detachNextBuffer: cannot detach a buffer in shared buffer "
636            "mode");
637        return BAD_VALUE;
638    }
639
640    mCore->waitWhileAllocatingLocked();
641
642    if (mCore->mFreeBuffers.empty()) {
643        return NO_MEMORY;
644    }
645
646    int found = mCore->mFreeBuffers.front();
647    mCore->mFreeBuffers.remove(found);
648    mCore->mFreeSlots.insert(found);
649
650    BQ_LOGV("detachNextBuffer detached slot %d", found);
651
652    *outBuffer = mSlots[found].mGraphicBuffer;
653    *outFence = mSlots[found].mFence;
654    mCore->clearBufferSlotLocked(found);
655    VALIDATE_CONSISTENCY();
656
657    return NO_ERROR;
658}
659
660status_t BufferQueueProducer::attachBuffer(int* outSlot,
661        const sp<android::GraphicBuffer>& buffer) {
662    ATRACE_CALL();
663
664    if (outSlot == NULL) {
665        BQ_LOGE("attachBuffer: outSlot must not be NULL");
666        return BAD_VALUE;
667    } else if (buffer == NULL) {
668        BQ_LOGE("attachBuffer: cannot attach NULL buffer");
669        return BAD_VALUE;
670    }
671
672    Mutex::Autolock lock(mCore->mMutex);
673
674    if (mCore->mIsAbandoned) {
675        BQ_LOGE("attachBuffer: BufferQueue has been abandoned");
676        return NO_INIT;
677    }
678
679    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
680        BQ_LOGE("attachBuffer: BufferQueue has no connected producer");
681        return NO_INIT;
682    }
683
684    if (mCore->mSharedBufferMode) {
685        BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode");
686        return BAD_VALUE;
687    }
688
689    if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
690        BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
691                "[queue %u]", buffer->getGenerationNumber(),
692                mCore->mGenerationNumber);
693        return BAD_VALUE;
694    }
695
696    mCore->waitWhileAllocatingLocked();
697
698    status_t returnFlags = NO_ERROR;
699    int found;
700    status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Attach, &found);
701    if (status != NO_ERROR) {
702        return status;
703    }
704
705    // This should not happen
706    if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
707        BQ_LOGE("attachBuffer: no available buffer slots");
708        return -EBUSY;
709    }
710
711    *outSlot = found;
712    ATRACE_BUFFER_INDEX(*outSlot);
713    BQ_LOGV("attachBuffer: returning slot %d flags=%#x",
714            *outSlot, returnFlags);
715
716    mSlots[*outSlot].mGraphicBuffer = buffer;
717    mSlots[*outSlot].mBufferState.attachProducer();
718    mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
719    mSlots[*outSlot].mFence = Fence::NO_FENCE;
720    mSlots[*outSlot].mRequestBufferCalled = true;
721    mSlots[*outSlot].mAcquireCalled = false;
722    mCore->mActiveBuffers.insert(found);
723    VALIDATE_CONSISTENCY();
724
725    return returnFlags;
726}
727
728status_t BufferQueueProducer::queueBuffer(int slot,
729        const QueueBufferInput &input, QueueBufferOutput *output) {
730    ATRACE_CALL();
731    ATRACE_BUFFER_INDEX(slot);
732
733    int64_t timestamp;
734    bool isAutoTimestamp;
735    android_dataspace dataSpace;
736    Rect crop(Rect::EMPTY_RECT);
737    int scalingMode;
738    uint32_t transform;
739    uint32_t stickyTransform;
740    sp<Fence> fence;
741    input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop, &scalingMode,
742            &transform, &fence, &stickyTransform);
743    Region surfaceDamage = input.getSurfaceDamage();
744
745    if (fence == NULL) {
746        BQ_LOGE("queueBuffer: fence is NULL");
747        return BAD_VALUE;
748    }
749
750    switch (scalingMode) {
751        case NATIVE_WINDOW_SCALING_MODE_FREEZE:
752        case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
753        case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
754        case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
755            break;
756        default:
757            BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode);
758            return BAD_VALUE;
759    }
760
761    sp<IConsumerListener> frameAvailableListener;
762    sp<IConsumerListener> frameReplacedListener;
763    int callbackTicket = 0;
764    BufferItem item;
765    { // Autolock scope
766        Mutex::Autolock lock(mCore->mMutex);
767
768        if (mCore->mIsAbandoned) {
769            BQ_LOGE("queueBuffer: BufferQueue has been abandoned");
770            return NO_INIT;
771        }
772
773        if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
774            BQ_LOGE("queueBuffer: BufferQueue has no connected producer");
775            return NO_INIT;
776        }
777
778        if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
779            BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)",
780                    slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
781            return BAD_VALUE;
782        } else if (!mSlots[slot].mBufferState.isDequeued()) {
783            BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
784                    "(state = %s)", slot, mSlots[slot].mBufferState.string());
785            return BAD_VALUE;
786        } else if (!mSlots[slot].mRequestBufferCalled) {
787            BQ_LOGE("queueBuffer: slot %d was queued without requesting "
788                    "a buffer", slot);
789            return BAD_VALUE;
790        }
791
792        // If shared buffer mode has just been enabled, cache the slot of the
793        // first buffer that is queued and mark it as the shared buffer.
794        if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
795                BufferQueueCore::INVALID_BUFFER_SLOT) {
796            mCore->mSharedBufferSlot = slot;
797            mSlots[slot].mBufferState.mShared = true;
798        }
799
800        BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d"
801                " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
802                slot, mCore->mFrameCounter + 1, timestamp, dataSpace,
803                crop.left, crop.top, crop.right, crop.bottom, transform,
804                BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
805
806        const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
807        Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
808        Rect croppedRect(Rect::EMPTY_RECT);
809        crop.intersect(bufferRect, &croppedRect);
810        if (croppedRect != crop) {
811            BQ_LOGE("queueBuffer: crop rect is not contained within the "
812                    "buffer in slot %d", slot);
813            return BAD_VALUE;
814        }
815
816        // Override UNKNOWN dataspace with consumer default
817        if (dataSpace == HAL_DATASPACE_UNKNOWN) {
818            dataSpace = mCore->mDefaultBufferDataSpace;
819        }
820
821        mSlots[slot].mFence = fence;
822        mSlots[slot].mBufferState.queue();
823
824        ++mCore->mFrameCounter;
825        mSlots[slot].mFrameNumber = mCore->mFrameCounter;
826
827        item.mAcquireCalled = mSlots[slot].mAcquireCalled;
828        item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
829        item.mCrop = crop;
830        item.mTransform = transform &
831                ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
832        item.mTransformToDisplayInverse =
833                (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
834        item.mScalingMode = static_cast<uint32_t>(scalingMode);
835        item.mTimestamp = timestamp;
836        item.mIsAutoTimestamp = isAutoTimestamp;
837        item.mDataSpace = dataSpace;
838        item.mFrameNumber = mCore->mFrameCounter;
839        item.mSlot = slot;
840        item.mFence = fence;
841        item.mIsDroppable = mCore->mAsyncMode ||
842                mCore->mDequeueBufferCannotBlock ||
843                (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == slot);
844        item.mSurfaceDamage = surfaceDamage;
845        item.mQueuedBuffer = true;
846        item.mAutoRefresh = mCore->mSharedBufferMode && mCore->mAutoRefresh;
847
848        mStickyTransform = stickyTransform;
849
850        // Cache the shared buffer data so that the BufferItem can be recreated.
851        if (mCore->mSharedBufferMode) {
852            mCore->mSharedBufferCache.crop = crop;
853            mCore->mSharedBufferCache.transform = transform;
854            mCore->mSharedBufferCache.scalingMode = static_cast<uint32_t>(
855                    scalingMode);
856            mCore->mSharedBufferCache.dataspace = dataSpace;
857        }
858
859        if (mCore->mQueue.empty()) {
860            // When the queue is empty, we can ignore mDequeueBufferCannotBlock
861            // and simply queue this buffer
862            mCore->mQueue.push_back(item);
863            frameAvailableListener = mCore->mConsumerListener;
864        } else {
865            // When the queue is not empty, we need to look at the last buffer
866            // in the queue to see if we need to replace it
867            const BufferItem& last = mCore->mQueue.itemAt(
868                    mCore->mQueue.size() - 1);
869            if (last.mIsDroppable) {
870
871                if (!last.mIsStale) {
872                    mSlots[last.mSlot].mBufferState.freeQueued();
873
874                    // After leaving shared buffer mode, the shared buffer will
875                    // still be around. Mark it as no longer shared if this
876                    // operation causes it to be free.
877                    if (!mCore->mSharedBufferMode &&
878                            mSlots[last.mSlot].mBufferState.isFree()) {
879                        mSlots[last.mSlot].mBufferState.mShared = false;
880                    }
881                    // Don't put the shared buffer on the free list.
882                    if (!mSlots[last.mSlot].mBufferState.isShared()) {
883                        mCore->mActiveBuffers.erase(last.mSlot);
884                        mCore->mFreeBuffers.push_back(last.mSlot);
885                    }
886                }
887
888                // Overwrite the droppable buffer with the incoming one
889                mCore->mQueue.editItemAt(mCore->mQueue.size() - 1) = item;
890                frameReplacedListener = mCore->mConsumerListener;
891            } else {
892                mCore->mQueue.push_back(item);
893                frameAvailableListener = mCore->mConsumerListener;
894            }
895        }
896
897        mCore->mBufferHasBeenQueued = true;
898        mCore->mDequeueCondition.broadcast();
899        mCore->mLastQueuedSlot = slot;
900
901        output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
902                mCore->mTransformHint,
903                static_cast<uint32_t>(mCore->mQueue.size()));
904
905        ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
906        mCore->mOccupancyTracker.registerOccupancyChange(mCore->mQueue.size());
907
908        // Take a ticket for the callback functions
909        callbackTicket = mNextCallbackTicket++;
910
911        VALIDATE_CONSISTENCY();
912    } // Autolock scope
913
914    // Don't send the GraphicBuffer through the callback, and don't send
915    // the slot number, since the consumer shouldn't need it
916    item.mGraphicBuffer.clear();
917    item.mSlot = BufferItem::INVALID_BUFFER_SLOT;
918
919    // Call back without the main BufferQueue lock held, but with the callback
920    // lock held so we can ensure that callbacks occur in order
921    {
922        Mutex::Autolock lock(mCallbackMutex);
923        while (callbackTicket != mCurrentCallbackTicket) {
924            mCallbackCondition.wait(mCallbackMutex);
925        }
926
927        if (frameAvailableListener != NULL) {
928            frameAvailableListener->onFrameAvailable(item);
929        } else if (frameReplacedListener != NULL) {
930            frameReplacedListener->onFrameReplaced(item);
931        }
932
933        ++mCurrentCallbackTicket;
934        mCallbackCondition.broadcast();
935    }
936
937    // Wait without lock held
938    if (mCore->mConnectedApi == NATIVE_WINDOW_API_EGL) {
939        // Waiting here allows for two full buffers to be queued but not a
940        // third. In the event that frames take varying time, this makes a
941        // small trade-off in favor of latency rather than throughput.
942        mLastQueueBufferFence->waitForever("Throttling EGL Production");
943    }
944    mLastQueueBufferFence = fence;
945    mLastQueuedCrop = item.mCrop;
946    mLastQueuedTransform = item.mTransform;
947
948    return NO_ERROR;
949}
950
951status_t BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
952    ATRACE_CALL();
953    BQ_LOGV("cancelBuffer: slot %d", slot);
954    Mutex::Autolock lock(mCore->mMutex);
955
956    if (mCore->mIsAbandoned) {
957        BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
958        return NO_INIT;
959    }
960
961    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
962        BQ_LOGE("cancelBuffer: BufferQueue has no connected producer");
963        return NO_INIT;
964    }
965
966    if (mCore->mSharedBufferMode) {
967        BQ_LOGE("cancelBuffer: cannot cancel a buffer in shared buffer mode");
968        return BAD_VALUE;
969    }
970
971    if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
972        BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)",
973                slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
974        return BAD_VALUE;
975    } else if (!mSlots[slot].mBufferState.isDequeued()) {
976        BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
977                "(state = %s)", slot, mSlots[slot].mBufferState.string());
978        return BAD_VALUE;
979    } else if (fence == NULL) {
980        BQ_LOGE("cancelBuffer: fence is NULL");
981        return BAD_VALUE;
982    }
983
984    mSlots[slot].mBufferState.cancel();
985
986    // After leaving shared buffer mode, the shared buffer will still be around.
987    // Mark it as no longer shared if this operation causes it to be free.
988    if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) {
989        mSlots[slot].mBufferState.mShared = false;
990    }
991
992    // Don't put the shared buffer on the free list.
993    if (!mSlots[slot].mBufferState.isShared()) {
994        mCore->mActiveBuffers.erase(slot);
995        mCore->mFreeBuffers.push_back(slot);
996    }
997
998    mSlots[slot].mFence = fence;
999    mCore->mDequeueCondition.broadcast();
1000    VALIDATE_CONSISTENCY();
1001
1002    return NO_ERROR;
1003}
1004
1005int BufferQueueProducer::query(int what, int *outValue) {
1006    ATRACE_CALL();
1007    Mutex::Autolock lock(mCore->mMutex);
1008
1009    if (outValue == NULL) {
1010        BQ_LOGE("query: outValue was NULL");
1011        return BAD_VALUE;
1012    }
1013
1014    if (mCore->mIsAbandoned) {
1015        BQ_LOGE("query: BufferQueue has been abandoned");
1016        return NO_INIT;
1017    }
1018
1019    int value;
1020    switch (what) {
1021        case NATIVE_WINDOW_WIDTH:
1022            value = static_cast<int32_t>(mCore->mDefaultWidth);
1023            break;
1024        case NATIVE_WINDOW_HEIGHT:
1025            value = static_cast<int32_t>(mCore->mDefaultHeight);
1026            break;
1027        case NATIVE_WINDOW_FORMAT:
1028            value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
1029            break;
1030        case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
1031            value = mCore->getMinUndequeuedBufferCountLocked();
1032            break;
1033        case NATIVE_WINDOW_STICKY_TRANSFORM:
1034            value = static_cast<int32_t>(mStickyTransform);
1035            break;
1036        case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
1037            value = (mCore->mQueue.size() > 1);
1038            break;
1039        case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
1040            value = static_cast<int32_t>(mCore->mConsumerUsageBits);
1041            break;
1042        case NATIVE_WINDOW_DEFAULT_DATASPACE:
1043            value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace);
1044            break;
1045        case NATIVE_WINDOW_BUFFER_AGE:
1046            if (mCore->mBufferAge > INT32_MAX) {
1047                value = 0;
1048            } else {
1049                value = static_cast<int32_t>(mCore->mBufferAge);
1050            }
1051            break;
1052        default:
1053            return BAD_VALUE;
1054    }
1055
1056    BQ_LOGV("query: %d? %d", what, value);
1057    *outValue = value;
1058    return NO_ERROR;
1059}
1060
1061status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
1062        int api, bool producerControlledByApp, QueueBufferOutput *output) {
1063    ATRACE_CALL();
1064    Mutex::Autolock lock(mCore->mMutex);
1065    mConsumerName = mCore->mConsumerName;
1066    BQ_LOGV("connect: api=%d producerControlledByApp=%s", api,
1067            producerControlledByApp ? "true" : "false");
1068
1069    if (mCore->mIsAbandoned) {
1070        BQ_LOGE("connect: BufferQueue has been abandoned");
1071        return NO_INIT;
1072    }
1073
1074    if (mCore->mConsumerListener == NULL) {
1075        BQ_LOGE("connect: BufferQueue has no consumer");
1076        return NO_INIT;
1077    }
1078
1079    if (output == NULL) {
1080        BQ_LOGE("connect: output was NULL");
1081        return BAD_VALUE;
1082    }
1083
1084    if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
1085        BQ_LOGE("connect: already connected (cur=%d req=%d)",
1086                mCore->mConnectedApi, api);
1087        return BAD_VALUE;
1088    }
1089
1090    int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode,
1091            mDequeueTimeout < 0 ?
1092            mCore->mConsumerControlledByApp && producerControlledByApp : false,
1093            mCore->mMaxBufferCount) -
1094            mCore->getMaxBufferCountLocked();
1095    if (!mCore->adjustAvailableSlotsLocked(delta)) {
1096        BQ_LOGE("connect: BufferQueue failed to adjust the number of available "
1097                "slots. Delta = %d", delta);
1098        return BAD_VALUE;
1099    }
1100
1101    int status = NO_ERROR;
1102    switch (api) {
1103        case NATIVE_WINDOW_API_EGL:
1104        case NATIVE_WINDOW_API_CPU:
1105        case NATIVE_WINDOW_API_MEDIA:
1106        case NATIVE_WINDOW_API_CAMERA:
1107            mCore->mConnectedApi = api;
1108            output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
1109                    mCore->mTransformHint,
1110                    static_cast<uint32_t>(mCore->mQueue.size()));
1111
1112            // Set up a death notification so that we can disconnect
1113            // automatically if the remote producer dies
1114            if (listener != NULL &&
1115                    IInterface::asBinder(listener)->remoteBinder() != NULL) {
1116                status = IInterface::asBinder(listener)->linkToDeath(
1117                        static_cast<IBinder::DeathRecipient*>(this));
1118                if (status != NO_ERROR) {
1119                    BQ_LOGE("connect: linkToDeath failed: %s (%d)",
1120                            strerror(-status), status);
1121                }
1122            }
1123            mCore->mConnectedProducerListener = listener;
1124            break;
1125        default:
1126            BQ_LOGE("connect: unknown API %d", api);
1127            status = BAD_VALUE;
1128            break;
1129    }
1130
1131    mCore->mBufferHasBeenQueued = false;
1132    mCore->mDequeueBufferCannotBlock = false;
1133    if (mDequeueTimeout < 0) {
1134        mCore->mDequeueBufferCannotBlock =
1135                mCore->mConsumerControlledByApp && producerControlledByApp;
1136    }
1137
1138    mCore->mAllowAllocation = true;
1139    VALIDATE_CONSISTENCY();
1140    return status;
1141}
1142
1143status_t BufferQueueProducer::disconnect(int api) {
1144    ATRACE_CALL();
1145    BQ_LOGV("disconnect: api %d", api);
1146
1147    int status = NO_ERROR;
1148    sp<IConsumerListener> listener;
1149    { // Autolock scope
1150        Mutex::Autolock lock(mCore->mMutex);
1151        mCore->waitWhileAllocatingLocked();
1152
1153        if (mCore->mIsAbandoned) {
1154            // It's not really an error to disconnect after the surface has
1155            // been abandoned; it should just be a no-op.
1156            return NO_ERROR;
1157        }
1158
1159        if (api == BufferQueueCore::CURRENTLY_CONNECTED_API) {
1160            api = mCore->mConnectedApi;
1161            // If we're asked to disconnect the currently connected api but
1162            // nobody is connected, it's not really an error.
1163            if (api == BufferQueueCore::NO_CONNECTED_API) {
1164                return NO_ERROR;
1165            }
1166        }
1167
1168        switch (api) {
1169            case NATIVE_WINDOW_API_EGL:
1170            case NATIVE_WINDOW_API_CPU:
1171            case NATIVE_WINDOW_API_MEDIA:
1172            case NATIVE_WINDOW_API_CAMERA:
1173                if (mCore->mConnectedApi == api) {
1174                    mCore->freeAllBuffersLocked();
1175
1176                    // Remove our death notification callback if we have one
1177                    if (mCore->mConnectedProducerListener != NULL) {
1178                        sp<IBinder> token =
1179                                IInterface::asBinder(mCore->mConnectedProducerListener);
1180                        // This can fail if we're here because of the death
1181                        // notification, but we just ignore it
1182                        token->unlinkToDeath(
1183                                static_cast<IBinder::DeathRecipient*>(this));
1184                    }
1185                    mCore->mSharedBufferSlot =
1186                            BufferQueueCore::INVALID_BUFFER_SLOT;
1187                    mCore->mConnectedProducerListener = NULL;
1188                    mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API;
1189                    mCore->mSidebandStream.clear();
1190                    mCore->mDequeueCondition.broadcast();
1191                    listener = mCore->mConsumerListener;
1192                } else if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
1193                    BQ_LOGE("disconnect: still connected to another API "
1194                            "(cur=%d req=%d)", mCore->mConnectedApi, api);
1195                    status = BAD_VALUE;
1196                }
1197                break;
1198            default:
1199                BQ_LOGE("disconnect: unknown API %d", api);
1200                status = BAD_VALUE;
1201                break;
1202        }
1203    } // Autolock scope
1204
1205    // Call back without lock held
1206    if (listener != NULL) {
1207        listener->onBuffersReleased();
1208    }
1209
1210    return status;
1211}
1212
1213status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
1214    sp<IConsumerListener> listener;
1215    { // Autolock scope
1216        Mutex::Autolock _l(mCore->mMutex);
1217        mCore->mSidebandStream = stream;
1218        listener = mCore->mConsumerListener;
1219    } // Autolock scope
1220
1221    if (listener != NULL) {
1222        listener->onSidebandStreamChanged();
1223    }
1224    return NO_ERROR;
1225}
1226
1227void BufferQueueProducer::allocateBuffers(uint32_t width, uint32_t height,
1228        PixelFormat format, uint32_t usage) {
1229    ATRACE_CALL();
1230    while (true) {
1231        size_t newBufferCount = 0;
1232        uint32_t allocWidth = 0;
1233        uint32_t allocHeight = 0;
1234        PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
1235        uint32_t allocUsage = 0;
1236        { // Autolock scope
1237            Mutex::Autolock lock(mCore->mMutex);
1238            mCore->waitWhileAllocatingLocked();
1239
1240            if (!mCore->mAllowAllocation) {
1241                BQ_LOGE("allocateBuffers: allocation is not allowed for this "
1242                        "BufferQueue");
1243                return;
1244            }
1245
1246            newBufferCount = mCore->mFreeSlots.size();
1247            if (newBufferCount == 0) {
1248                return;
1249            }
1250
1251            allocWidth = width > 0 ? width : mCore->mDefaultWidth;
1252            allocHeight = height > 0 ? height : mCore->mDefaultHeight;
1253            allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
1254            allocUsage = usage | mCore->mConsumerUsageBits;
1255
1256            mCore->mIsAllocating = true;
1257        } // Autolock scope
1258
1259        Vector<sp<GraphicBuffer>> buffers;
1260        for (size_t i = 0; i <  newBufferCount; ++i) {
1261            status_t result = NO_ERROR;
1262            sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
1263                    allocWidth, allocHeight, allocFormat, allocUsage, &result));
1264            if (result != NO_ERROR) {
1265                BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format"
1266                        " %u, usage %u)", width, height, format, usage);
1267                Mutex::Autolock lock(mCore->mMutex);
1268                mCore->mIsAllocating = false;
1269                mCore->mIsAllocatingCondition.broadcast();
1270                return;
1271            }
1272            buffers.push_back(graphicBuffer);
1273        }
1274
1275        { // Autolock scope
1276            Mutex::Autolock lock(mCore->mMutex);
1277            uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
1278            uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
1279            PixelFormat checkFormat = format != 0 ?
1280                    format : mCore->mDefaultBufferFormat;
1281            uint32_t checkUsage = usage | mCore->mConsumerUsageBits;
1282            if (checkWidth != allocWidth || checkHeight != allocHeight ||
1283                checkFormat != allocFormat || checkUsage != allocUsage) {
1284                // Something changed while we released the lock. Retry.
1285                BQ_LOGV("allocateBuffers: size/format/usage changed while allocating. Retrying.");
1286                mCore->mIsAllocating = false;
1287                mCore->mIsAllocatingCondition.broadcast();
1288                continue;
1289            }
1290
1291            for (size_t i = 0; i < newBufferCount; ++i) {
1292                if (mCore->mFreeSlots.empty()) {
1293                    BQ_LOGV("allocateBuffers: a slot was occupied while "
1294                            "allocating. Dropping allocated buffer.");
1295                    continue;
1296                }
1297                auto slot = mCore->mFreeSlots.begin();
1298                mCore->clearBufferSlotLocked(*slot); // Clean up the slot first
1299                mSlots[*slot].mGraphicBuffer = buffers[i];
1300                mSlots[*slot].mFence = Fence::NO_FENCE;
1301
1302                // freeBufferLocked puts this slot on the free slots list. Since
1303                // we then attached a buffer, move the slot to free buffer list.
1304                mCore->mFreeBuffers.push_front(*slot);
1305
1306                BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d",
1307                        *slot);
1308
1309                // Make sure the erase is done after all uses of the slot
1310                // iterator since it will be invalid after this point.
1311                mCore->mFreeSlots.erase(slot);
1312            }
1313
1314            mCore->mIsAllocating = false;
1315            mCore->mIsAllocatingCondition.broadcast();
1316            VALIDATE_CONSISTENCY();
1317        } // Autolock scope
1318    }
1319}
1320
1321status_t BufferQueueProducer::allowAllocation(bool allow) {
1322    ATRACE_CALL();
1323    BQ_LOGV("allowAllocation: %s", allow ? "true" : "false");
1324
1325    Mutex::Autolock lock(mCore->mMutex);
1326    mCore->mAllowAllocation = allow;
1327    return NO_ERROR;
1328}
1329
1330status_t BufferQueueProducer::setGenerationNumber(uint32_t generationNumber) {
1331    ATRACE_CALL();
1332    BQ_LOGV("setGenerationNumber: %u", generationNumber);
1333
1334    Mutex::Autolock lock(mCore->mMutex);
1335    mCore->mGenerationNumber = generationNumber;
1336    return NO_ERROR;
1337}
1338
1339String8 BufferQueueProducer::getConsumerName() const {
1340    ATRACE_CALL();
1341    BQ_LOGV("getConsumerName: %s", mConsumerName.string());
1342    return mConsumerName;
1343}
1344
1345uint64_t BufferQueueProducer::getNextFrameNumber() const {
1346    ATRACE_CALL();
1347
1348    Mutex::Autolock lock(mCore->mMutex);
1349    uint64_t nextFrameNumber = mCore->mFrameCounter + 1;
1350    return nextFrameNumber;
1351}
1352
1353status_t BufferQueueProducer::setSharedBufferMode(bool sharedBufferMode) {
1354    ATRACE_CALL();
1355    BQ_LOGV("setSharedBufferMode: %d", sharedBufferMode);
1356
1357    Mutex::Autolock lock(mCore->mMutex);
1358    if (!sharedBufferMode) {
1359        mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT;
1360    }
1361    mCore->mSharedBufferMode = sharedBufferMode;
1362    return NO_ERROR;
1363}
1364
1365status_t BufferQueueProducer::setAutoRefresh(bool autoRefresh) {
1366    ATRACE_CALL();
1367    BQ_LOGV("setAutoRefresh: %d", autoRefresh);
1368
1369    Mutex::Autolock lock(mCore->mMutex);
1370
1371    mCore->mAutoRefresh = autoRefresh;
1372    return NO_ERROR;
1373}
1374
1375status_t BufferQueueProducer::setDequeueTimeout(nsecs_t timeout) {
1376    ATRACE_CALL();
1377    BQ_LOGV("setDequeueTimeout: %" PRId64, timeout);
1378
1379    Mutex::Autolock lock(mCore->mMutex);
1380    int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode, false,
1381            mCore->mMaxBufferCount) - mCore->getMaxBufferCountLocked();
1382    if (!mCore->adjustAvailableSlotsLocked(delta)) {
1383        BQ_LOGE("setDequeueTimeout: BufferQueue failed to adjust the number of "
1384                "available slots. Delta = %d", delta);
1385        return BAD_VALUE;
1386    }
1387
1388    mDequeueTimeout = timeout;
1389    mCore->mDequeueBufferCannotBlock = false;
1390
1391    VALIDATE_CONSISTENCY();
1392    return NO_ERROR;
1393}
1394
1395status_t BufferQueueProducer::getLastQueuedBuffer(sp<GraphicBuffer>* outBuffer,
1396        sp<Fence>* outFence, float outTransformMatrix[16]) {
1397    ATRACE_CALL();
1398    BQ_LOGV("getLastQueuedBuffer");
1399
1400    Mutex::Autolock lock(mCore->mMutex);
1401    if (mCore->mLastQueuedSlot == BufferItem::INVALID_BUFFER_SLOT) {
1402        *outBuffer = nullptr;
1403        *outFence = Fence::NO_FENCE;
1404        return NO_ERROR;
1405    }
1406
1407    *outBuffer = mSlots[mCore->mLastQueuedSlot].mGraphicBuffer;
1408    *outFence = mLastQueueBufferFence;
1409
1410    // Currently only SurfaceFlinger internally ever changes
1411    // GLConsumer's filtering mode, so we just use 'true' here as
1412    // this is slightly specialized for the current client of this API,
1413    // which does want filtering.
1414    GLConsumer::computeTransformMatrix(outTransformMatrix,
1415            mSlots[mCore->mLastQueuedSlot].mGraphicBuffer, mLastQueuedCrop,
1416            mLastQueuedTransform, true /* filter */);
1417
1418    return NO_ERROR;
1419}
1420
1421bool BufferQueueProducer::getFrameTimestamps(uint64_t frameNumber,
1422        FrameTimestamps* outTimestamps) const {
1423    ATRACE_CALL();
1424    BQ_LOGV("getFrameTimestamps, %" PRIu64, frameNumber);
1425    sp<IConsumerListener> listener;
1426
1427    {
1428        Mutex::Autolock lock(mCore->mMutex);
1429        listener = mCore->mConsumerListener;
1430    }
1431    if (listener != NULL) {
1432        return listener->getFrameTimestamps(frameNumber, outTimestamps);
1433    }
1434    return false;
1435}
1436
1437void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
1438    // If we're here, it means that a producer we were connected to died.
1439    // We're guaranteed that we are still connected to it because we remove
1440    // this callback upon disconnect. It's therefore safe to read mConnectedApi
1441    // without synchronization here.
1442    int api = mCore->mConnectedApi;
1443    disconnect(api);
1444}
1445
1446} // namespace android
1447