BufferQueue.cpp revision 2488b20aec097accb20a853d9876bb0a5dc04636
1/*
2 * Copyright (C) 2012 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#define LOG_TAG "BufferQueue"
18#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19//#define LOG_NDEBUG 0
20
21#define GL_GLEXT_PROTOTYPES
22#define EGL_EGLEXT_PROTOTYPES
23
24#include <EGL/egl.h>
25#include <EGL/eglext.h>
26
27#include <gui/BufferQueue.h>
28#include <gui/ISurfaceComposer.h>
29#include <private/gui/ComposerService.h>
30
31#include <utils/Log.h>
32#include <gui/SurfaceTexture.h>
33#include <utils/Trace.h>
34
35// This compile option causes SurfaceTexture to return the buffer that is currently
36// attached to the GL texture from dequeueBuffer when no other buffers are
37// available.  It requires the drivers (Gralloc, GL, OMX IL, and Camera) to do
38// implicit cross-process synchronization to prevent the buffer from being
39// written to before the buffer has (a) been detached from the GL texture and
40// (b) all GL reads from the buffer have completed.
41
42// During refactoring, do not support dequeuing the current buffer
43#undef ALLOW_DEQUEUE_CURRENT_BUFFER
44
45#ifdef ALLOW_DEQUEUE_CURRENT_BUFFER
46#define FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER    true
47#warning "ALLOW_DEQUEUE_CURRENT_BUFFER enabled"
48#else
49#define FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER    false
50#endif
51
52// Macros for including the BufferQueue name in log messages
53#define ST_LOGV(x, ...) ALOGV("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
54#define ST_LOGD(x, ...) ALOGD("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
55#define ST_LOGI(x, ...) ALOGI("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
56#define ST_LOGW(x, ...) ALOGW("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
57#define ST_LOGE(x, ...) ALOGE("[%s] "x, mConsumerName.string(), ##__VA_ARGS__)
58
59#define ATRACE_BUFFER_INDEX(index)                                            \
60    if (ATRACE_ENABLED()) {                                                   \
61        char ___traceBuf[1024];                                               \
62        snprintf(___traceBuf, 1024, "%s: %d", mConsumerName.string(),         \
63                (index));                                                     \
64        android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf);           \
65    }
66
67namespace android {
68
69// Get an ID that's unique within this process.
70static int32_t createProcessUniqueId() {
71    static volatile int32_t globalCounter = 0;
72    return android_atomic_inc(&globalCounter);
73}
74
75BufferQueue::BufferQueue(  bool allowSynchronousMode, int bufferCount ) :
76    mDefaultWidth(1),
77    mDefaultHeight(1),
78    mPixelFormat(PIXEL_FORMAT_RGBA_8888),
79    mMinUndequeuedBuffers(bufferCount),
80    mMinAsyncBufferSlots(bufferCount + 1),
81    mMinSyncBufferSlots(bufferCount),
82    mBufferCount(mMinAsyncBufferSlots),
83    mClientBufferCount(0),
84    mServerBufferCount(mMinAsyncBufferSlots),
85    mSynchronousMode(false),
86    mAllowSynchronousMode(allowSynchronousMode),
87    mConnectedApi(NO_CONNECTED_API),
88    mAbandoned(false),
89    mFrameCounter(0),
90    mBufferHasBeenQueued(false),
91    mDefaultBufferFormat(0),
92    mConsumerUsageBits(0),
93    mTransformHint(0)
94{
95    // Choose a name using the PID and a process-unique ID.
96    mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
97
98    ST_LOGV("BufferQueue");
99    sp<ISurfaceComposer> composer(ComposerService::getComposerService());
100    mGraphicBufferAlloc = composer->createGraphicBufferAlloc();
101    if (mGraphicBufferAlloc == 0) {
102        ST_LOGE("createGraphicBufferAlloc() failed in BufferQueue()");
103    }
104}
105
106BufferQueue::~BufferQueue() {
107    ST_LOGV("~BufferQueue");
108}
109
110status_t BufferQueue::setBufferCountServerLocked(int bufferCount) {
111    if (bufferCount > NUM_BUFFER_SLOTS)
112        return BAD_VALUE;
113
114    // special-case, nothing to do
115    if (bufferCount == mBufferCount)
116        return OK;
117
118    if (!mClientBufferCount &&
119        bufferCount >= mBufferCount) {
120        // easy, we just have more buffers
121        mBufferCount = bufferCount;
122        mServerBufferCount = bufferCount;
123        mDequeueCondition.broadcast();
124    } else {
125        // we're here because we're either
126        // - reducing the number of available buffers
127        // - or there is a client-buffer-count in effect
128
129        // less than 2 buffers is never allowed
130        if (bufferCount < 2)
131            return BAD_VALUE;
132
133        // when there is non client-buffer-count in effect, the client is not
134        // allowed to dequeue more than one buffer at a time,
135        // so the next time they dequeue a buffer, we know that they don't
136        // own one. the actual resizing will happen during the next
137        // dequeueBuffer.
138
139        mServerBufferCount = bufferCount;
140        mDequeueCondition.broadcast();
141    }
142    return OK;
143}
144
145bool BufferQueue::isSynchronousMode() const {
146    Mutex::Autolock lock(mMutex);
147    return mSynchronousMode;
148}
149
150void BufferQueue::setConsumerName(const String8& name) {
151    Mutex::Autolock lock(mMutex);
152    mConsumerName = name;
153}
154
155status_t BufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) {
156    Mutex::Autolock lock(mMutex);
157    mDefaultBufferFormat = defaultFormat;
158    return OK;
159}
160
161status_t BufferQueue::setConsumerUsageBits(uint32_t usage) {
162    Mutex::Autolock lock(mMutex);
163    mConsumerUsageBits = usage;
164    return OK;
165}
166
167status_t BufferQueue::setTransformHint(uint32_t hint) {
168    Mutex::Autolock lock(mMutex);
169    mTransformHint = hint;
170    return OK;
171}
172
173status_t BufferQueue::setBufferCount(int bufferCount) {
174    ST_LOGV("setBufferCount: count=%d", bufferCount);
175
176    sp<ConsumerListener> listener;
177    {
178        Mutex::Autolock lock(mMutex);
179
180        if (mAbandoned) {
181            ST_LOGE("setBufferCount: SurfaceTexture has been abandoned!");
182            return NO_INIT;
183        }
184        if (bufferCount > NUM_BUFFER_SLOTS) {
185            ST_LOGE("setBufferCount: bufferCount larger than slots available");
186            return BAD_VALUE;
187        }
188
189        // Error out if the user has dequeued buffers
190        for (int i=0 ; i<mBufferCount ; i++) {
191            if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) {
192                ST_LOGE("setBufferCount: client owns some buffers");
193                return -EINVAL;
194            }
195        }
196
197        const int minBufferSlots = mSynchronousMode ?
198            mMinSyncBufferSlots : mMinAsyncBufferSlots;
199        if (bufferCount == 0) {
200            mClientBufferCount = 0;
201            bufferCount = (mServerBufferCount >= minBufferSlots) ?
202                    mServerBufferCount : minBufferSlots;
203            return setBufferCountServerLocked(bufferCount);
204        }
205
206        if (bufferCount < minBufferSlots) {
207            ST_LOGE("setBufferCount: requested buffer count (%d) is less than "
208                    "minimum (%d)", bufferCount, minBufferSlots);
209            return BAD_VALUE;
210        }
211
212        // here we're guaranteed that the client doesn't have dequeued buffers
213        // and will release all of its buffer references.
214        freeAllBuffersLocked();
215        mBufferCount = bufferCount;
216        mClientBufferCount = bufferCount;
217        mBufferHasBeenQueued = false;
218        mQueue.clear();
219        mDequeueCondition.broadcast();
220        listener = mConsumerListener;
221    } // scope for lock
222
223    if (listener != NULL) {
224        listener->onBuffersReleased();
225    }
226
227    return OK;
228}
229
230int BufferQueue::query(int what, int* outValue)
231{
232    ATRACE_CALL();
233    Mutex::Autolock lock(mMutex);
234
235    if (mAbandoned) {
236        ST_LOGE("query: SurfaceTexture has been abandoned!");
237        return NO_INIT;
238    }
239
240    int value;
241    switch (what) {
242    case NATIVE_WINDOW_WIDTH:
243        value = mDefaultWidth;
244        break;
245    case NATIVE_WINDOW_HEIGHT:
246        value = mDefaultHeight;
247        break;
248    case NATIVE_WINDOW_FORMAT:
249        value = mPixelFormat;
250        break;
251    case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
252        value = mSynchronousMode ?
253                (mMinUndequeuedBuffers-1) : mMinUndequeuedBuffers;
254        break;
255    case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
256        value = (mQueue.size() >= 2);
257        break;
258    default:
259        return BAD_VALUE;
260    }
261    outValue[0] = value;
262    return NO_ERROR;
263}
264
265status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
266    ATRACE_CALL();
267    ST_LOGV("requestBuffer: slot=%d", slot);
268    Mutex::Autolock lock(mMutex);
269    if (mAbandoned) {
270        ST_LOGE("requestBuffer: SurfaceTexture has been abandoned!");
271        return NO_INIT;
272    }
273    if (slot < 0 || mBufferCount <= slot) {
274        ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d",
275                mBufferCount, slot);
276        return BAD_VALUE;
277    }
278    mSlots[slot].mRequestBufferCalled = true;
279    *buf = mSlots[slot].mGraphicBuffer;
280    return NO_ERROR;
281}
282
283status_t BufferQueue::dequeueBuffer(int *outBuf, uint32_t w, uint32_t h,
284        uint32_t format, uint32_t usage) {
285    ATRACE_CALL();
286    ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);
287
288    if ((w && !h) || (!w && h)) {
289        ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
290        return BAD_VALUE;
291    }
292
293    status_t returnFlags(OK);
294    EGLDisplay dpy = EGL_NO_DISPLAY;
295    EGLSyncKHR fence = EGL_NO_SYNC_KHR;
296
297    { // Scope for the lock
298        Mutex::Autolock lock(mMutex);
299
300        if (format == 0) {
301            format = mDefaultBufferFormat;
302        }
303        // turn on usage bits the consumer requested
304        usage |= mConsumerUsageBits;
305
306        int found = -1;
307        int foundSync = -1;
308        int dequeuedCount = 0;
309        bool tryAgain = true;
310        while (tryAgain) {
311            if (mAbandoned) {
312                ST_LOGE("dequeueBuffer: SurfaceTexture has been abandoned!");
313                return NO_INIT;
314            }
315
316            // We need to wait for the FIFO to drain if the number of buffer
317            // needs to change.
318            //
319            // The condition "number of buffers needs to change" is true if
320            // - the client doesn't care about how many buffers there are
321            // - AND the actual number of buffer is different from what was
322            //   set in the last setBufferCountServer()
323            //                         - OR -
324            //   setBufferCountServer() was set to a value incompatible with
325            //   the synchronization mode (for instance because the sync mode
326            //   changed since)
327            //
328            // As long as this condition is true AND the FIFO is not empty, we
329            // wait on mDequeueCondition.
330
331            const int minBufferCountNeeded = mSynchronousMode ?
332                    mMinSyncBufferSlots : mMinAsyncBufferSlots;
333
334            const bool numberOfBuffersNeedsToChange = !mClientBufferCount &&
335                    ((mServerBufferCount != mBufferCount) ||
336                            (mServerBufferCount < minBufferCountNeeded));
337
338            if (!mQueue.isEmpty() && numberOfBuffersNeedsToChange) {
339                // wait for the FIFO to drain
340                mDequeueCondition.wait(mMutex);
341                // NOTE: we continue here because we need to reevaluate our
342                // whole state (eg: we could be abandoned or disconnected)
343                continue;
344            }
345
346            if (numberOfBuffersNeedsToChange) {
347                // here we're guaranteed that mQueue is empty
348                freeAllBuffersLocked();
349                mBufferCount = mServerBufferCount;
350                if (mBufferCount < minBufferCountNeeded)
351                    mBufferCount = minBufferCountNeeded;
352                mBufferHasBeenQueued = false;
353                returnFlags |= ISurfaceTexture::RELEASE_ALL_BUFFERS;
354            }
355
356            // look for a free buffer to give to the client
357            found = INVALID_BUFFER_SLOT;
358            foundSync = INVALID_BUFFER_SLOT;
359            dequeuedCount = 0;
360            for (int i = 0; i < mBufferCount; i++) {
361                const int state = mSlots[i].mBufferState;
362                if (state == BufferSlot::DEQUEUED) {
363                    dequeuedCount++;
364                }
365
366                // this logic used to be if (FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER)
367                // but dequeuing the current buffer is disabled.
368                if (false) {
369                    // This functionality has been temporarily removed so
370                    // BufferQueue and SurfaceTexture can be refactored into
371                    // separate objects
372                } else {
373                    if (state == BufferSlot::FREE) {
374                        /* We return the oldest of the free buffers to avoid
375                         * stalling the producer if possible.  This is because
376                         * the consumer may still have pending reads of the
377                         * buffers in flight.
378                         */
379                        bool isOlder = mSlots[i].mFrameNumber <
380                                mSlots[found].mFrameNumber;
381                        if (found < 0 || isOlder) {
382                            foundSync = i;
383                            found = i;
384                        }
385                    }
386                }
387            }
388
389            // clients are not allowed to dequeue more than one buffer
390            // if they didn't set a buffer count.
391            if (!mClientBufferCount && dequeuedCount) {
392                ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without "
393                        "setting the buffer count");
394                return -EINVAL;
395            }
396
397            // See whether a buffer has been queued since the last
398            // setBufferCount so we know whether to perform the
399            // mMinUndequeuedBuffers check below.
400            if (mBufferHasBeenQueued) {
401                // make sure the client is not trying to dequeue more buffers
402                // than allowed.
403                const int avail = mBufferCount - (dequeuedCount+1);
404                if (avail < (mMinUndequeuedBuffers-int(mSynchronousMode))) {
405                    ST_LOGE("dequeueBuffer: mMinUndequeuedBuffers=%d exceeded "
406                            "(dequeued=%d)",
407                            mMinUndequeuedBuffers-int(mSynchronousMode),
408                            dequeuedCount);
409                    return -EBUSY;
410                }
411            }
412
413            // if no buffer is found, wait for a buffer to be released
414            tryAgain = found == INVALID_BUFFER_SLOT;
415            if (tryAgain) {
416                mDequeueCondition.wait(mMutex);
417            }
418        }
419
420
421        if (found == INVALID_BUFFER_SLOT) {
422            // This should not happen.
423            ST_LOGE("dequeueBuffer: no available buffer slots");
424            return -EBUSY;
425        }
426
427        const int buf = found;
428        *outBuf = found;
429
430        ATRACE_BUFFER_INDEX(buf);
431
432        const bool useDefaultSize = !w && !h;
433        if (useDefaultSize) {
434            // use the default size
435            w = mDefaultWidth;
436            h = mDefaultHeight;
437        }
438
439        const bool updateFormat = (format != 0);
440        if (!updateFormat) {
441            // keep the current (or default) format
442            format = mPixelFormat;
443        }
444
445        // buffer is now in DEQUEUED (but can also be current at the same time,
446        // if we're in synchronous mode)
447        mSlots[buf].mBufferState = BufferSlot::DEQUEUED;
448
449        const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
450        if ((buffer == NULL) ||
451            (uint32_t(buffer->width)  != w) ||
452            (uint32_t(buffer->height) != h) ||
453            (uint32_t(buffer->format) != format) ||
454            ((uint32_t(buffer->usage) & usage) != usage))
455        {
456            status_t error;
457            sp<GraphicBuffer> graphicBuffer(
458                    mGraphicBufferAlloc->createGraphicBuffer(
459                            w, h, format, usage, &error));
460            if (graphicBuffer == 0) {
461                ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer "
462                        "failed");
463                return error;
464            }
465            if (updateFormat) {
466                mPixelFormat = format;
467            }
468
469            mSlots[buf].mAcquireCalled = false;
470            mSlots[buf].mGraphicBuffer = graphicBuffer;
471            mSlots[buf].mRequestBufferCalled = false;
472            mSlots[buf].mFence = EGL_NO_SYNC_KHR;
473            mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
474
475            returnFlags |= ISurfaceTexture::BUFFER_NEEDS_REALLOCATION;
476        }
477
478        dpy = mSlots[buf].mEglDisplay;
479        fence = mSlots[buf].mFence;
480        mSlots[buf].mFence = EGL_NO_SYNC_KHR;
481    }  // end lock scope
482
483    if (fence != EGL_NO_SYNC_KHR) {
484        EGLint result = eglClientWaitSyncKHR(dpy, fence, 0, 1000000000);
485        // If something goes wrong, log the error, but return the buffer without
486        // synchronizing access to it.  It's too late at this point to abort the
487        // dequeue operation.
488        if (result == EGL_FALSE) {
489            ALOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError());
490        } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
491            ALOGE("dequeueBuffer: timeout waiting for fence");
492        }
493        eglDestroySyncKHR(dpy, fence);
494    }
495
496    ST_LOGV("dequeueBuffer: returning slot=%d buf=%p flags=%#x", *outBuf,
497            mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);
498
499    return returnFlags;
500}
501
502status_t BufferQueue::setSynchronousMode(bool enabled) {
503    ATRACE_CALL();
504    ST_LOGV("setSynchronousMode: enabled=%d", enabled);
505    Mutex::Autolock lock(mMutex);
506
507    if (mAbandoned) {
508        ST_LOGE("setSynchronousMode: SurfaceTexture has been abandoned!");
509        return NO_INIT;
510    }
511
512    status_t err = OK;
513    if (!mAllowSynchronousMode && enabled)
514        return err;
515
516    if (!enabled) {
517        // going to asynchronous mode, drain the queue
518        err = drainQueueLocked();
519        if (err != NO_ERROR)
520            return err;
521    }
522
523    if (mSynchronousMode != enabled) {
524        // - if we're going to asynchronous mode, the queue is guaranteed to be
525        // empty here
526        // - if the client set the number of buffers, we're guaranteed that
527        // we have at least 3 (because we don't allow less)
528        mSynchronousMode = enabled;
529        mDequeueCondition.broadcast();
530    }
531    return err;
532}
533
534status_t BufferQueue::queueBuffer(int buf,
535        const QueueBufferInput& input, QueueBufferOutput* output) {
536    ATRACE_CALL();
537    ATRACE_BUFFER_INDEX(buf);
538
539    ST_LOGV("queueBuffer: slot=%d time=%lld crop=[%d,%d,%d,%d]", buf,
540            mSlots[buf].mTimestamp,
541            mSlots[buf].mCrop.left,
542            mSlots[buf].mCrop.top,
543            mSlots[buf].mCrop.right,
544            mSlots[buf].mCrop.bottom);
545
546    sp<ConsumerListener> listener;
547
548    { // scope for the lock
549        Mutex::Autolock lock(mMutex);
550        if (mAbandoned) {
551            ST_LOGE("queueBuffer: SurfaceTexture has been abandoned!");
552            return NO_INIT;
553        }
554        if (buf < 0 || buf >= mBufferCount) {
555            ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d",
556                    mBufferCount, buf);
557            return -EINVAL;
558        } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
559            ST_LOGE("queueBuffer: slot %d is not owned by the client "
560                    "(state=%d)", buf, mSlots[buf].mBufferState);
561            return -EINVAL;
562        } else if (!mSlots[buf].mRequestBufferCalled) {
563            ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
564                    "buffer", buf);
565            return -EINVAL;
566        }
567
568        if (mSynchronousMode) {
569            // In synchronous mode we queue all buffers in a FIFO.
570            mQueue.push_back(buf);
571
572            // Synchronous mode always signals that an additional frame should
573            // be consumed.
574            listener = mConsumerListener;
575        } else {
576            // In asynchronous mode we only keep the most recent buffer.
577            if (mQueue.empty()) {
578                mQueue.push_back(buf);
579
580                // Asynchronous mode only signals that a frame should be
581                // consumed if no previous frame was pending. If a frame were
582                // pending then the consumer would have already been notified.
583                listener = mConsumerListener;
584            } else {
585                Fifo::iterator front(mQueue.begin());
586                // buffer currently queued is freed
587                mSlots[*front].mBufferState = BufferSlot::FREE;
588                // and we record the new buffer index in the queued list
589                *front = buf;
590            }
591        }
592
593        int scalingMode;
594
595        input.deflate(
596                &mSlots[buf].mTimestamp,
597                &mSlots[buf].mCrop,
598                &scalingMode,
599                &mSlots[buf].mTransform);
600
601
602        switch (scalingMode) {
603            case NATIVE_WINDOW_SCALING_MODE_FREEZE:
604            case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
605            case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
606                break;
607            default:
608                ST_LOGE("unknown scaling mode: %d (ignoring)", scalingMode);
609                scalingMode = mSlots[buf].mScalingMode;
610                break;
611        }
612
613        mSlots[buf].mBufferState = BufferSlot::QUEUED;
614        mSlots[buf].mScalingMode = scalingMode;
615        mFrameCounter++;
616        mSlots[buf].mFrameNumber = mFrameCounter;
617
618        mBufferHasBeenQueued = true;
619        mDequeueCondition.broadcast();
620
621        output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
622                mQueue.size());
623
624        ATRACE_INT(mConsumerName.string(), mQueue.size());
625    } // scope for the lock
626
627    // call back without lock held
628    if (listener != 0) {
629        listener->onFrameAvailable();
630    }
631    return OK;
632}
633
634void BufferQueue::cancelBuffer(int buf) {
635    ATRACE_CALL();
636    ST_LOGV("cancelBuffer: slot=%d", buf);
637    Mutex::Autolock lock(mMutex);
638
639    if (mAbandoned) {
640        ST_LOGW("cancelBuffer: BufferQueue has been abandoned!");
641        return;
642    }
643
644    if (buf < 0 || buf >= mBufferCount) {
645        ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d",
646                mBufferCount, buf);
647        return;
648    } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
649        ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
650                buf, mSlots[buf].mBufferState);
651        return;
652    }
653    mSlots[buf].mBufferState = BufferSlot::FREE;
654    mSlots[buf].mFrameNumber = 0;
655    mDequeueCondition.broadcast();
656}
657
658status_t BufferQueue::connect(int api, QueueBufferOutput* output) {
659    ATRACE_CALL();
660    ST_LOGV("connect: api=%d", api);
661    Mutex::Autolock lock(mMutex);
662
663    if (mAbandoned) {
664        ST_LOGE("connect: BufferQueue has been abandoned!");
665        return NO_INIT;
666    }
667
668    if (mConsumerListener == NULL) {
669        ST_LOGE("connect: BufferQueue has no consumer!");
670        return NO_INIT;
671    }
672
673    int err = NO_ERROR;
674    switch (api) {
675        case NATIVE_WINDOW_API_EGL:
676        case NATIVE_WINDOW_API_CPU:
677        case NATIVE_WINDOW_API_MEDIA:
678        case NATIVE_WINDOW_API_CAMERA:
679            if (mConnectedApi != NO_CONNECTED_API) {
680                ST_LOGE("connect: already connected (cur=%d, req=%d)",
681                        mConnectedApi, api);
682                err = -EINVAL;
683            } else {
684                mConnectedApi = api;
685                output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
686                        mQueue.size());
687            }
688            break;
689        default:
690            err = -EINVAL;
691            break;
692    }
693
694    mBufferHasBeenQueued = false;
695
696    return err;
697}
698
699status_t BufferQueue::disconnect(int api) {
700    ATRACE_CALL();
701    ST_LOGV("disconnect: api=%d", api);
702
703    int err = NO_ERROR;
704    sp<ConsumerListener> listener;
705
706    { // Scope for the lock
707        Mutex::Autolock lock(mMutex);
708
709        if (mAbandoned) {
710            // it is not really an error to disconnect after the surface
711            // has been abandoned, it should just be a no-op.
712            return NO_ERROR;
713        }
714
715        switch (api) {
716            case NATIVE_WINDOW_API_EGL:
717            case NATIVE_WINDOW_API_CPU:
718            case NATIVE_WINDOW_API_MEDIA:
719            case NATIVE_WINDOW_API_CAMERA:
720                if (mConnectedApi == api) {
721                    drainQueueAndFreeBuffersLocked();
722                    mConnectedApi = NO_CONNECTED_API;
723                    mDequeueCondition.broadcast();
724                    listener = mConsumerListener;
725                } else {
726                    ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)",
727                            mConnectedApi, api);
728                    err = -EINVAL;
729                }
730                break;
731            default:
732                ST_LOGE("disconnect: unknown API %d", api);
733                err = -EINVAL;
734                break;
735        }
736    }
737
738    if (listener != NULL) {
739        listener->onBuffersReleased();
740    }
741
742    return err;
743}
744
745void BufferQueue::dump(String8& result) const
746{
747    char buffer[1024];
748    BufferQueue::dump(result, "", buffer, 1024);
749}
750
751void BufferQueue::dump(String8& result, const char* prefix,
752        char* buffer, size_t SIZE) const
753{
754    Mutex::Autolock _l(mMutex);
755
756    String8 fifo;
757    int fifoSize = 0;
758    Fifo::const_iterator i(mQueue.begin());
759    while (i != mQueue.end()) {
760       snprintf(buffer, SIZE, "%02d ", *i++);
761       fifoSize++;
762       fifo.append(buffer);
763    }
764
765    snprintf(buffer, SIZE,
766            "%s-BufferQueue mBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], "
767            "mPixelFormat=%d, FIFO(%d)={%s}\n",
768            prefix, mBufferCount, mSynchronousMode, mDefaultWidth,
769            mDefaultHeight, mPixelFormat, fifoSize, fifo.string());
770    result.append(buffer);
771
772
773    struct {
774        const char * operator()(int state) const {
775            switch (state) {
776                case BufferSlot::DEQUEUED: return "DEQUEUED";
777                case BufferSlot::QUEUED: return "QUEUED";
778                case BufferSlot::FREE: return "FREE";
779                case BufferSlot::ACQUIRED: return "ACQUIRED";
780                default: return "Unknown";
781            }
782        }
783    } stateName;
784
785    for (int i=0 ; i<mBufferCount ; i++) {
786        const BufferSlot& slot(mSlots[i]);
787        snprintf(buffer, SIZE,
788                "%s%s[%02d] "
789                "state=%-8s, crop=[%d,%d,%d,%d], "
790                "transform=0x%02x, timestamp=%lld",
791                prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i,
792                stateName(slot.mBufferState),
793                slot.mCrop.left, slot.mCrop.top, slot.mCrop.right,
794                slot.mCrop.bottom, slot.mTransform, slot.mTimestamp
795        );
796        result.append(buffer);
797
798        const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
799        if (buf != NULL) {
800            snprintf(buffer, SIZE,
801                    ", %p [%4ux%4u:%4u,%3X]",
802                    buf->handle, buf->width, buf->height, buf->stride,
803                    buf->format);
804            result.append(buffer);
805        }
806        result.append("\n");
807    }
808}
809
810void BufferQueue::freeBufferLocked(int i) {
811    mSlots[i].mGraphicBuffer = 0;
812    if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
813        mSlots[i].mNeedsCleanupOnRelease = true;
814    }
815    mSlots[i].mBufferState = BufferSlot::FREE;
816    mSlots[i].mFrameNumber = 0;
817    mSlots[i].mAcquireCalled = false;
818
819    // destroy fence as BufferQueue now takes ownership
820    if (mSlots[i].mFence != EGL_NO_SYNC_KHR) {
821        eglDestroySyncKHR(mSlots[i].mEglDisplay, mSlots[i].mFence);
822        mSlots[i].mFence = EGL_NO_SYNC_KHR;
823    }
824}
825
826void BufferQueue::freeAllBuffersLocked() {
827    ALOGW_IF(!mQueue.isEmpty(),
828            "freeAllBuffersLocked called but mQueue is not empty");
829    mQueue.clear();
830    mBufferHasBeenQueued = false;
831    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
832        freeBufferLocked(i);
833    }
834}
835
836status_t BufferQueue::acquireBuffer(BufferItem *buffer) {
837    ATRACE_CALL();
838    Mutex::Autolock _l(mMutex);
839    // check if queue is empty
840    // In asynchronous mode the list is guaranteed to be one buffer
841    // deep, while in synchronous mode we use the oldest buffer.
842    if (!mQueue.empty()) {
843        Fifo::iterator front(mQueue.begin());
844        int buf = *front;
845
846        ATRACE_BUFFER_INDEX(buf);
847
848        if (mSlots[buf].mAcquireCalled) {
849            buffer->mGraphicBuffer = NULL;
850        } else {
851            buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer;
852        }
853        buffer->mCrop = mSlots[buf].mCrop;
854        buffer->mTransform = mSlots[buf].mTransform;
855        buffer->mScalingMode = mSlots[buf].mScalingMode;
856        buffer->mFrameNumber = mSlots[buf].mFrameNumber;
857        buffer->mTimestamp = mSlots[buf].mTimestamp;
858        buffer->mBuf = buf;
859        mSlots[buf].mAcquireCalled = true;
860
861        mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
862        mQueue.erase(front);
863        mDequeueCondition.broadcast();
864
865        ATRACE_INT(mConsumerName.string(), mQueue.size());
866    } else {
867        return NO_BUFFER_AVAILABLE;
868    }
869
870    return OK;
871}
872
873status_t BufferQueue::releaseBuffer(int buf, EGLDisplay display,
874        EGLSyncKHR fence) {
875    ATRACE_CALL();
876    ATRACE_BUFFER_INDEX(buf);
877
878    Mutex::Autolock _l(mMutex);
879
880    if (buf == INVALID_BUFFER_SLOT) {
881        return -EINVAL;
882    }
883
884    mSlots[buf].mEglDisplay = display;
885    mSlots[buf].mFence = fence;
886
887    // The buffer can now only be released if its in the acquired state
888    if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
889        mSlots[buf].mBufferState = BufferSlot::FREE;
890    } else if (mSlots[buf].mNeedsCleanupOnRelease) {
891        ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState);
892        mSlots[buf].mNeedsCleanupOnRelease = false;
893        return STALE_BUFFER_SLOT;
894    } else {
895        ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState);
896        return -EINVAL;
897    }
898
899    mDequeueCondition.broadcast();
900    return OK;
901}
902
903status_t BufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener) {
904    ST_LOGV("consumerConnect");
905    Mutex::Autolock lock(mMutex);
906
907    if (mAbandoned) {
908        ST_LOGE("consumerConnect: BufferQueue has been abandoned!");
909        return NO_INIT;
910    }
911
912    mConsumerListener = consumerListener;
913
914    return OK;
915}
916
917status_t BufferQueue::consumerDisconnect() {
918    ST_LOGV("consumerDisconnect");
919    Mutex::Autolock lock(mMutex);
920
921    if (mConsumerListener == NULL) {
922        ST_LOGE("consumerDisconnect: No consumer is connected!");
923        return -EINVAL;
924    }
925
926    mAbandoned = true;
927    mConsumerListener = NULL;
928    mQueue.clear();
929    freeAllBuffersLocked();
930    mDequeueCondition.broadcast();
931    return OK;
932}
933
934status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) {
935    ST_LOGV("getReleasedBuffers");
936    Mutex::Autolock lock(mMutex);
937
938    if (mAbandoned) {
939        ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!");
940        return NO_INIT;
941    }
942
943    uint32_t mask = 0;
944    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
945        if (!mSlots[i].mAcquireCalled) {
946            mask |= 1 << i;
947        }
948    }
949    *slotMask = mask;
950
951    ST_LOGV("getReleasedBuffers: returning mask %#x", mask);
952    return NO_ERROR;
953}
954
955status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h)
956{
957    ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
958    if (!w || !h) {
959        ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
960                w, h);
961        return BAD_VALUE;
962    }
963
964    Mutex::Autolock lock(mMutex);
965    mDefaultWidth = w;
966    mDefaultHeight = h;
967    return OK;
968}
969
970status_t BufferQueue::setBufferCountServer(int bufferCount) {
971    ATRACE_CALL();
972    Mutex::Autolock lock(mMutex);
973    return setBufferCountServerLocked(bufferCount);
974}
975
976void BufferQueue::freeAllBuffersExceptHeadLocked() {
977    ALOGW_IF(!mQueue.isEmpty(),
978            "freeAllBuffersExceptCurrentLocked called but mQueue is not empty");
979    int head = -1;
980    if (!mQueue.empty()) {
981        Fifo::iterator front(mQueue.begin());
982        head = *front;
983    }
984    mBufferHasBeenQueued = false;
985    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
986        if (i != head) {
987            freeBufferLocked(i);
988        }
989    }
990}
991
992status_t BufferQueue::drainQueueLocked() {
993    while (mSynchronousMode && !mQueue.isEmpty()) {
994        mDequeueCondition.wait(mMutex);
995        if (mAbandoned) {
996            ST_LOGE("drainQueueLocked: BufferQueue has been abandoned!");
997            return NO_INIT;
998        }
999        if (mConnectedApi == NO_CONNECTED_API) {
1000            ST_LOGE("drainQueueLocked: BufferQueue is not connected!");
1001            return NO_INIT;
1002        }
1003    }
1004    return NO_ERROR;
1005}
1006
1007status_t BufferQueue::drainQueueAndFreeBuffersLocked() {
1008    status_t err = drainQueueLocked();
1009    if (err == NO_ERROR) {
1010        if (mSynchronousMode) {
1011            freeAllBuffersLocked();
1012        } else {
1013            freeAllBuffersExceptHeadLocked();
1014        }
1015    }
1016    return err;
1017}
1018
1019BufferQueue::ProxyConsumerListener::ProxyConsumerListener(
1020        const wp<BufferQueue::ConsumerListener>& consumerListener):
1021        mConsumerListener(consumerListener) {}
1022
1023BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}
1024
1025void BufferQueue::ProxyConsumerListener::onFrameAvailable() {
1026    sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1027    if (listener != NULL) {
1028        listener->onFrameAvailable();
1029    }
1030}
1031
1032void BufferQueue::ProxyConsumerListener::onBuffersReleased() {
1033    sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1034    if (listener != NULL) {
1035        listener->onBuffersReleased();
1036    }
1037}
1038
1039}; // namespace android
1040