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