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