BufferQueue.cpp revision 695e331f01b136155b1559b3c878b7c5bb631bc1
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    default:
256        return BAD_VALUE;
257    }
258    outValue[0] = value;
259    return NO_ERROR;
260}
261
262status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
263    ATRACE_CALL();
264    ST_LOGV("requestBuffer: slot=%d", slot);
265    Mutex::Autolock lock(mMutex);
266    if (mAbandoned) {
267        ST_LOGE("requestBuffer: SurfaceTexture has been abandoned!");
268        return NO_INIT;
269    }
270    if (slot < 0 || mBufferCount <= slot) {
271        ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d",
272                mBufferCount, slot);
273        return BAD_VALUE;
274    }
275    mSlots[slot].mRequestBufferCalled = true;
276    *buf = mSlots[slot].mGraphicBuffer;
277    return NO_ERROR;
278}
279
280status_t BufferQueue::dequeueBuffer(int *outBuf, uint32_t w, uint32_t h,
281        uint32_t format, uint32_t usage) {
282    ATRACE_CALL();
283    ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);
284
285    if ((w && !h) || (!w && h)) {
286        ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
287        return BAD_VALUE;
288    }
289
290    status_t returnFlags(OK);
291    EGLDisplay dpy = EGL_NO_DISPLAY;
292    EGLSyncKHR fence = EGL_NO_SYNC_KHR;
293
294    { // Scope for the lock
295        Mutex::Autolock lock(mMutex);
296
297        if (format == 0) {
298            format = mDefaultBufferFormat;
299        }
300        // turn on usage bits the consumer requested
301        usage |= mConsumerUsageBits;
302
303        int found = -1;
304        int foundSync = -1;
305        int dequeuedCount = 0;
306        bool tryAgain = true;
307        while (tryAgain) {
308            if (mAbandoned) {
309                ST_LOGE("dequeueBuffer: SurfaceTexture has been abandoned!");
310                return NO_INIT;
311            }
312
313            // We need to wait for the FIFO to drain if the number of buffer
314            // needs to change.
315            //
316            // The condition "number of buffers needs to change" is true if
317            // - the client doesn't care about how many buffers there are
318            // - AND the actual number of buffer is different from what was
319            //   set in the last setBufferCountServer()
320            //                         - OR -
321            //   setBufferCountServer() was set to a value incompatible with
322            //   the synchronization mode (for instance because the sync mode
323            //   changed since)
324            //
325            // As long as this condition is true AND the FIFO is not empty, we
326            // wait on mDequeueCondition.
327
328            const int minBufferCountNeeded = mSynchronousMode ?
329                    mMinSyncBufferSlots : mMinAsyncBufferSlots;
330
331            const bool numberOfBuffersNeedsToChange = !mClientBufferCount &&
332                    ((mServerBufferCount != mBufferCount) ||
333                            (mServerBufferCount < minBufferCountNeeded));
334
335            if (!mQueue.isEmpty() && numberOfBuffersNeedsToChange) {
336                // wait for the FIFO to drain
337                mDequeueCondition.wait(mMutex);
338                // NOTE: we continue here because we need to reevaluate our
339                // whole state (eg: we could be abandoned or disconnected)
340                continue;
341            }
342
343            if (numberOfBuffersNeedsToChange) {
344                // here we're guaranteed that mQueue is empty
345                freeAllBuffersLocked();
346                mBufferCount = mServerBufferCount;
347                if (mBufferCount < minBufferCountNeeded)
348                    mBufferCount = minBufferCountNeeded;
349                mBufferHasBeenQueued = false;
350                returnFlags |= ISurfaceTexture::RELEASE_ALL_BUFFERS;
351            }
352
353            // look for a free buffer to give to the client
354            found = INVALID_BUFFER_SLOT;
355            foundSync = INVALID_BUFFER_SLOT;
356            dequeuedCount = 0;
357            for (int i = 0; i < mBufferCount; i++) {
358                const int state = mSlots[i].mBufferState;
359                if (state == BufferSlot::DEQUEUED) {
360                    dequeuedCount++;
361                }
362
363                // this logic used to be if (FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER)
364                // but dequeuing the current buffer is disabled.
365                if (false) {
366                    // This functionality has been temporarily removed so
367                    // BufferQueue and SurfaceTexture can be refactored into
368                    // separate objects
369                } else {
370                    if (state == BufferSlot::FREE) {
371                        /* We return the oldest of the free buffers to avoid
372                         * stalling the producer if possible.  This is because
373                         * the consumer may still have pending reads of the
374                         * buffers in flight.
375                         */
376                        bool isOlder = mSlots[i].mFrameNumber <
377                                mSlots[found].mFrameNumber;
378                        if (found < 0 || isOlder) {
379                            foundSync = i;
380                            found = i;
381                        }
382                    }
383                }
384            }
385
386            // clients are not allowed to dequeue more than one buffer
387            // if they didn't set a buffer count.
388            if (!mClientBufferCount && dequeuedCount) {
389                ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without "
390                        "setting the buffer count");
391                return -EINVAL;
392            }
393
394            // See whether a buffer has been queued since the last
395            // setBufferCount so we know whether to perform the
396            // mMinUndequeuedBuffers check below.
397            if (mBufferHasBeenQueued) {
398                // make sure the client is not trying to dequeue more buffers
399                // than allowed.
400                const int avail = mBufferCount - (dequeuedCount+1);
401                if (avail < (mMinUndequeuedBuffers-int(mSynchronousMode))) {
402                    ST_LOGE("dequeueBuffer: mMinUndequeuedBuffers=%d exceeded "
403                            "(dequeued=%d)",
404                            mMinUndequeuedBuffers-int(mSynchronousMode),
405                            dequeuedCount);
406                    return -EBUSY;
407                }
408            }
409
410            // if no buffer is found, wait for a buffer to be released
411            tryAgain = found == INVALID_BUFFER_SLOT;
412            if (tryAgain) {
413                mDequeueCondition.wait(mMutex);
414            }
415        }
416
417
418        if (found == INVALID_BUFFER_SLOT) {
419            // This should not happen.
420            ST_LOGE("dequeueBuffer: no available buffer slots");
421            return -EBUSY;
422        }
423
424        const int buf = found;
425        *outBuf = found;
426
427        ATRACE_BUFFER_INDEX(buf);
428
429        const bool useDefaultSize = !w && !h;
430        if (useDefaultSize) {
431            // use the default size
432            w = mDefaultWidth;
433            h = mDefaultHeight;
434        }
435
436        const bool updateFormat = (format != 0);
437        if (!updateFormat) {
438            // keep the current (or default) format
439            format = mPixelFormat;
440        }
441
442        // buffer is now in DEQUEUED (but can also be current at the same time,
443        // if we're in synchronous mode)
444        mSlots[buf].mBufferState = BufferSlot::DEQUEUED;
445
446        const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
447        if ((buffer == NULL) ||
448            (uint32_t(buffer->width)  != w) ||
449            (uint32_t(buffer->height) != h) ||
450            (uint32_t(buffer->format) != format) ||
451            ((uint32_t(buffer->usage) & usage) != usage))
452        {
453            usage |= GraphicBuffer::USAGE_HW_TEXTURE;
454            status_t error;
455            sp<GraphicBuffer> graphicBuffer(
456                    mGraphicBufferAlloc->createGraphicBuffer(
457                            w, h, format, usage, &error));
458            if (graphicBuffer == 0) {
459                ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer "
460                        "failed");
461                return error;
462            }
463            if (updateFormat) {
464                mPixelFormat = format;
465            }
466
467            mSlots[buf].mAcquireCalled = false;
468            mSlots[buf].mGraphicBuffer = graphicBuffer;
469            mSlots[buf].mRequestBufferCalled = false;
470            mSlots[buf].mFence = EGL_NO_SYNC_KHR;
471            mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
472
473            returnFlags |= ISurfaceTexture::BUFFER_NEEDS_REALLOCATION;
474        }
475
476        dpy = mSlots[buf].mEglDisplay;
477        fence = mSlots[buf].mFence;
478        mSlots[buf].mFence = EGL_NO_SYNC_KHR;
479    }  // end lock scope
480
481    if (fence != EGL_NO_SYNC_KHR) {
482        EGLint result = eglClientWaitSyncKHR(dpy, fence, 0, 1000000000);
483        // If something goes wrong, log the error, but return the buffer without
484        // synchronizing access to it.  It's too late at this point to abort the
485        // dequeue operation.
486        if (result == EGL_FALSE) {
487            ALOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError());
488        } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
489            ALOGE("dequeueBuffer: timeout waiting for fence");
490        }
491        eglDestroySyncKHR(dpy, fence);
492    }
493
494    ST_LOGV("dequeueBuffer: returning slot=%d buf=%p flags=%#x", *outBuf,
495            mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);
496
497    return returnFlags;
498}
499
500status_t BufferQueue::setSynchronousMode(bool enabled) {
501    ATRACE_CALL();
502    ST_LOGV("setSynchronousMode: enabled=%d", enabled);
503    Mutex::Autolock lock(mMutex);
504
505    if (mAbandoned) {
506        ST_LOGE("setSynchronousMode: SurfaceTexture has been abandoned!");
507        return NO_INIT;
508    }
509
510    status_t err = OK;
511    if (!mAllowSynchronousMode && enabled)
512        return err;
513
514    if (!enabled) {
515        // going to asynchronous mode, drain the queue
516        err = drainQueueLocked();
517        if (err != NO_ERROR)
518            return err;
519    }
520
521    if (mSynchronousMode != enabled) {
522        // - if we're going to asynchronous mode, the queue is guaranteed to be
523        // empty here
524        // - if the client set the number of buffers, we're guaranteed that
525        // we have at least 3 (because we don't allow less)
526        mSynchronousMode = enabled;
527        mDequeueCondition.broadcast();
528    }
529    return err;
530}
531
532status_t BufferQueue::queueBuffer(int buf,
533        const QueueBufferInput& input, QueueBufferOutput* output) {
534    ATRACE_CALL();
535    ATRACE_BUFFER_INDEX(buf);
536
537    ST_LOGV("queueBuffer: slot=%d time=%lld crop=[%d,%d,%d,%d]", buf, timestamp,
538        crop.left, crop.top, crop.right, crop.bottom);
539
540    sp<ConsumerListener> listener;
541
542    { // scope for the lock
543        Mutex::Autolock lock(mMutex);
544        if (mAbandoned) {
545            ST_LOGE("queueBuffer: SurfaceTexture has been abandoned!");
546            return NO_INIT;
547        }
548        if (buf < 0 || buf >= mBufferCount) {
549            ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d",
550                    mBufferCount, buf);
551            return -EINVAL;
552        } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
553            ST_LOGE("queueBuffer: slot %d is not owned by the client "
554                    "(state=%d)", buf, mSlots[buf].mBufferState);
555            return -EINVAL;
556        } else if (!mSlots[buf].mRequestBufferCalled) {
557            ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
558                    "buffer", buf);
559            return -EINVAL;
560        }
561
562        if (mSynchronousMode) {
563            // In synchronous mode we queue all buffers in a FIFO.
564            mQueue.push_back(buf);
565
566            // Synchronous mode always signals that an additional frame should
567            // be consumed.
568            listener = mConsumerListener;
569        } else {
570            // In asynchronous mode we only keep the most recent buffer.
571            if (mQueue.empty()) {
572                mQueue.push_back(buf);
573
574                // Asynchronous mode only signals that a frame should be
575                // consumed if no previous frame was pending. If a frame were
576                // pending then the consumer would have already been notified.
577                listener = mConsumerListener;
578            } else {
579                Fifo::iterator front(mQueue.begin());
580                // buffer currently queued is freed
581                mSlots[*front].mBufferState = BufferSlot::FREE;
582                // and we record the new buffer index in the queued list
583                *front = buf;
584            }
585        }
586
587        int scalingMode;
588
589        input.deflate(
590                &mSlots[buf].mTimestamp,
591                &mSlots[buf].mCrop,
592                &scalingMode,
593                &mSlots[buf].mTransform);
594
595
596        switch (scalingMode) {
597            case NATIVE_WINDOW_SCALING_MODE_FREEZE:
598            case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
599            case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
600                break;
601            default:
602                ST_LOGE("unknown scaling mode: %d (ignoring)", scalingMode);
603                scalingMode = mSlots[buf].mScalingMode;
604                break;
605        }
606
607        mSlots[buf].mBufferState = BufferSlot::QUEUED;
608        mSlots[buf].mScalingMode = scalingMode;
609        mFrameCounter++;
610        mSlots[buf].mFrameNumber = mFrameCounter;
611
612        mBufferHasBeenQueued = true;
613        mDequeueCondition.broadcast();
614
615        output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint);
616
617        ATRACE_INT(mConsumerName.string(), mQueue.size());
618    } // scope for the lock
619
620    // call back without lock held
621    if (listener != 0) {
622        listener->onFrameAvailable();
623    }
624    return OK;
625}
626
627void BufferQueue::cancelBuffer(int buf) {
628    ATRACE_CALL();
629    ST_LOGV("cancelBuffer: slot=%d", buf);
630    Mutex::Autolock lock(mMutex);
631
632    if (mAbandoned) {
633        ST_LOGW("cancelBuffer: BufferQueue has been abandoned!");
634        return;
635    }
636
637    if (buf < 0 || buf >= mBufferCount) {
638        ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d",
639                mBufferCount, buf);
640        return;
641    } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
642        ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
643                buf, mSlots[buf].mBufferState);
644        return;
645    }
646    mSlots[buf].mBufferState = BufferSlot::FREE;
647    mSlots[buf].mFrameNumber = 0;
648    mDequeueCondition.broadcast();
649}
650
651status_t BufferQueue::connect(int api,
652        uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform) {
653    ATRACE_CALL();
654    ST_LOGV("connect: api=%d", api);
655    Mutex::Autolock lock(mMutex);
656
657    if (mAbandoned) {
658        ST_LOGE("connect: BufferQueue has been abandoned!");
659        return NO_INIT;
660    }
661
662    if (mConsumerListener == NULL) {
663        ST_LOGE("connect: BufferQueue has no consumer!");
664        return NO_INIT;
665    }
666
667    int err = NO_ERROR;
668    switch (api) {
669        case NATIVE_WINDOW_API_EGL:
670        case NATIVE_WINDOW_API_CPU:
671        case NATIVE_WINDOW_API_MEDIA:
672        case NATIVE_WINDOW_API_CAMERA:
673            if (mConnectedApi != NO_CONNECTED_API) {
674                ST_LOGE("connect: already connected (cur=%d, req=%d)",
675                        mConnectedApi, api);
676                err = -EINVAL;
677            } else {
678                mConnectedApi = api;
679                *outWidth = mDefaultWidth;
680                *outHeight = mDefaultHeight;
681                *outTransform = mTransformHint;
682            }
683            break;
684        default:
685            err = -EINVAL;
686            break;
687    }
688
689    mBufferHasBeenQueued = false;
690
691    return err;
692}
693
694status_t BufferQueue::disconnect(int api) {
695    ATRACE_CALL();
696    ST_LOGV("disconnect: api=%d", api);
697
698    int err = NO_ERROR;
699    sp<ConsumerListener> listener;
700
701    { // Scope for the lock
702        Mutex::Autolock lock(mMutex);
703
704        if (mAbandoned) {
705            // it is not really an error to disconnect after the surface
706            // has been abandoned, it should just be a no-op.
707            return NO_ERROR;
708        }
709
710        switch (api) {
711            case NATIVE_WINDOW_API_EGL:
712            case NATIVE_WINDOW_API_CPU:
713            case NATIVE_WINDOW_API_MEDIA:
714            case NATIVE_WINDOW_API_CAMERA:
715                if (mConnectedApi == api) {
716                    drainQueueAndFreeBuffersLocked();
717                    mConnectedApi = NO_CONNECTED_API;
718                    mDequeueCondition.broadcast();
719                    listener = mConsumerListener;
720                } else {
721                    ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)",
722                            mConnectedApi, api);
723                    err = -EINVAL;
724                }
725                break;
726            default:
727                ST_LOGE("disconnect: unknown API %d", api);
728                err = -EINVAL;
729                break;
730        }
731    }
732
733    if (listener != NULL) {
734        listener->onBuffersReleased();
735    }
736
737    return err;
738}
739
740void BufferQueue::dump(String8& result) const
741{
742    char buffer[1024];
743    BufferQueue::dump(result, "", buffer, 1024);
744}
745
746void BufferQueue::dump(String8& result, const char* prefix,
747        char* buffer, size_t SIZE) const
748{
749    Mutex::Autolock _l(mMutex);
750
751    String8 fifo;
752    int fifoSize = 0;
753    Fifo::const_iterator i(mQueue.begin());
754    while (i != mQueue.end()) {
755       snprintf(buffer, SIZE, "%02d ", *i++);
756       fifoSize++;
757       fifo.append(buffer);
758    }
759
760    snprintf(buffer, SIZE,
761            "%s-BufferQueue mBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], "
762            "mPixelFormat=%d, FIFO(%d)={%s}\n",
763            prefix, mBufferCount, mSynchronousMode, mDefaultWidth,
764            mDefaultHeight, mPixelFormat, fifoSize, fifo.string());
765    result.append(buffer);
766
767
768    struct {
769        const char * operator()(int state) const {
770            switch (state) {
771                case BufferSlot::DEQUEUED: return "DEQUEUED";
772                case BufferSlot::QUEUED: return "QUEUED";
773                case BufferSlot::FREE: return "FREE";
774                case BufferSlot::ACQUIRED: return "ACQUIRED";
775                default: return "Unknown";
776            }
777        }
778    } stateName;
779
780    for (int i=0 ; i<mBufferCount ; i++) {
781        const BufferSlot& slot(mSlots[i]);
782        snprintf(buffer, SIZE,
783                "%s%s[%02d] "
784                "state=%-8s, crop=[%d,%d,%d,%d], "
785                "transform=0x%02x, timestamp=%lld",
786                prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i,
787                stateName(slot.mBufferState),
788                slot.mCrop.left, slot.mCrop.top, slot.mCrop.right,
789                slot.mCrop.bottom, slot.mTransform, slot.mTimestamp
790        );
791        result.append(buffer);
792
793        const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
794        if (buf != NULL) {
795            snprintf(buffer, SIZE,
796                    ", %p [%4ux%4u:%4u,%3X]",
797                    buf->handle, buf->width, buf->height, buf->stride,
798                    buf->format);
799            result.append(buffer);
800        }
801        result.append("\n");
802    }
803}
804
805void BufferQueue::freeBufferLocked(int i) {
806    mSlots[i].mGraphicBuffer = 0;
807    if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
808        mSlots[i].mNeedsCleanupOnRelease = true;
809    }
810    mSlots[i].mBufferState = BufferSlot::FREE;
811    mSlots[i].mFrameNumber = 0;
812    mSlots[i].mAcquireCalled = false;
813
814    // destroy fence as BufferQueue now takes ownership
815    if (mSlots[i].mFence != EGL_NO_SYNC_KHR) {
816        eglDestroySyncKHR(mSlots[i].mEglDisplay, mSlots[i].mFence);
817        mSlots[i].mFence = EGL_NO_SYNC_KHR;
818    }
819}
820
821void BufferQueue::freeAllBuffersLocked() {
822    ALOGW_IF(!mQueue.isEmpty(),
823            "freeAllBuffersLocked called but mQueue is not empty");
824    mQueue.clear();
825    mBufferHasBeenQueued = false;
826    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
827        freeBufferLocked(i);
828    }
829}
830
831status_t BufferQueue::acquireBuffer(BufferItem *buffer) {
832    ATRACE_CALL();
833    Mutex::Autolock _l(mMutex);
834    // check if queue is empty
835    // In asynchronous mode the list is guaranteed to be one buffer
836    // deep, while in synchronous mode we use the oldest buffer.
837    if (!mQueue.empty()) {
838        Fifo::iterator front(mQueue.begin());
839        int buf = *front;
840
841        ATRACE_BUFFER_INDEX(buf);
842
843        if (mSlots[buf].mAcquireCalled) {
844            buffer->mGraphicBuffer = NULL;
845        } else {
846            buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer;
847        }
848        buffer->mCrop = mSlots[buf].mCrop;
849        buffer->mTransform = mSlots[buf].mTransform;
850        buffer->mScalingMode = mSlots[buf].mScalingMode;
851        buffer->mFrameNumber = mSlots[buf].mFrameNumber;
852        buffer->mTimestamp = mSlots[buf].mTimestamp;
853        buffer->mBuf = buf;
854        mSlots[buf].mAcquireCalled = true;
855
856        mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
857        mQueue.erase(front);
858        mDequeueCondition.broadcast();
859
860        ATRACE_INT(mConsumerName.string(), mQueue.size());
861    } else {
862        return NO_BUFFER_AVAILABLE;
863    }
864
865    return OK;
866}
867
868status_t BufferQueue::releaseBuffer(int buf, EGLDisplay display,
869        EGLSyncKHR fence) {
870    ATRACE_CALL();
871    ATRACE_BUFFER_INDEX(buf);
872
873    Mutex::Autolock _l(mMutex);
874
875    if (buf == INVALID_BUFFER_SLOT) {
876        return -EINVAL;
877    }
878
879    mSlots[buf].mEglDisplay = display;
880    mSlots[buf].mFence = fence;
881
882    // The buffer can now only be released if its in the acquired state
883    if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
884        mSlots[buf].mBufferState = BufferSlot::FREE;
885    } else if (mSlots[buf].mNeedsCleanupOnRelease) {
886        ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState);
887        mSlots[buf].mNeedsCleanupOnRelease = false;
888        return STALE_BUFFER_SLOT;
889    } else {
890        ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState);
891        return -EINVAL;
892    }
893
894    mDequeueCondition.broadcast();
895    return OK;
896}
897
898status_t BufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener) {
899    ST_LOGV("consumerConnect");
900    Mutex::Autolock lock(mMutex);
901
902    if (mAbandoned) {
903        ST_LOGE("consumerConnect: BufferQueue has been abandoned!");
904        return NO_INIT;
905    }
906
907    mConsumerListener = consumerListener;
908
909    return OK;
910}
911
912status_t BufferQueue::consumerDisconnect() {
913    ST_LOGV("consumerDisconnect");
914    Mutex::Autolock lock(mMutex);
915
916    if (mConsumerListener == NULL) {
917        ST_LOGE("consumerDisconnect: No consumer is connected!");
918        return -EINVAL;
919    }
920
921    mAbandoned = true;
922    mConsumerListener = NULL;
923    mQueue.clear();
924    freeAllBuffersLocked();
925    mDequeueCondition.broadcast();
926    return OK;
927}
928
929status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) {
930    ST_LOGV("getReleasedBuffers");
931    Mutex::Autolock lock(mMutex);
932
933    if (mAbandoned) {
934        ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!");
935        return NO_INIT;
936    }
937
938    uint32_t mask = 0;
939    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
940        if (!mSlots[i].mAcquireCalled) {
941            mask |= 1 << i;
942        }
943    }
944    *slotMask = mask;
945
946    ST_LOGV("getReleasedBuffers: returning mask %#x", mask);
947    return NO_ERROR;
948}
949
950status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h)
951{
952    ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
953    if (!w || !h) {
954        ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
955                w, h);
956        return BAD_VALUE;
957    }
958
959    Mutex::Autolock lock(mMutex);
960    mDefaultWidth = w;
961    mDefaultHeight = h;
962    return OK;
963}
964
965status_t BufferQueue::setBufferCountServer(int bufferCount) {
966    ATRACE_CALL();
967    Mutex::Autolock lock(mMutex);
968    return setBufferCountServerLocked(bufferCount);
969}
970
971void BufferQueue::freeAllBuffersExceptHeadLocked() {
972    ALOGW_IF(!mQueue.isEmpty(),
973            "freeAllBuffersExceptCurrentLocked called but mQueue is not empty");
974    int head = -1;
975    if (!mQueue.empty()) {
976        Fifo::iterator front(mQueue.begin());
977        head = *front;
978    }
979    mBufferHasBeenQueued = false;
980    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
981        if (i != head) {
982            freeBufferLocked(i);
983        }
984    }
985}
986
987status_t BufferQueue::drainQueueLocked() {
988    while (mSynchronousMode && !mQueue.isEmpty()) {
989        mDequeueCondition.wait(mMutex);
990        if (mAbandoned) {
991            ST_LOGE("drainQueueLocked: BufferQueue has been abandoned!");
992            return NO_INIT;
993        }
994        if (mConnectedApi == NO_CONNECTED_API) {
995            ST_LOGE("drainQueueLocked: BufferQueue is not connected!");
996            return NO_INIT;
997        }
998    }
999    return NO_ERROR;
1000}
1001
1002status_t BufferQueue::drainQueueAndFreeBuffersLocked() {
1003    status_t err = drainQueueLocked();
1004    if (err == NO_ERROR) {
1005        if (mSynchronousMode) {
1006            freeAllBuffersLocked();
1007        } else {
1008            freeAllBuffersExceptHeadLocked();
1009        }
1010    }
1011    return err;
1012}
1013
1014BufferQueue::ProxyConsumerListener::ProxyConsumerListener(
1015        const wp<BufferQueue::ConsumerListener>& consumerListener):
1016        mConsumerListener(consumerListener) {}
1017
1018BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}
1019
1020void BufferQueue::ProxyConsumerListener::onFrameAvailable() {
1021    sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1022    if (listener != NULL) {
1023        listener->onFrameAvailable();
1024    }
1025}
1026
1027void BufferQueue::ProxyConsumerListener::onBuffersReleased() {
1028    sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1029    if (listener != NULL) {
1030        listener->onBuffersReleased();
1031    }
1032}
1033
1034}; // namespace android
1035