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