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