BufferQueue.cpp revision f7c6087bcc6a85cc82fd8dd83566550f880600ec
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#include <utils/CallStack.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(const sp<IGraphicBufferAlloc>& allocator) :
68    mDefaultWidth(1),
69    mDefaultHeight(1),
70    mMaxAcquiredBufferCount(1),
71    mDefaultMaxBufferCount(2),
72    mOverrideMaxBufferCount(0),
73    mConsumerControlledByApp(false),
74    mDequeueBufferCannotBlock(false),
75    mUseAsyncBuffer(true),
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    const int minBufferCount = mUseAsyncBuffer ? 2 : 1;
105    if (count < minBufferCount || count > NUM_BUFFER_SLOTS)
106        return BAD_VALUE;
107
108    mDefaultMaxBufferCount = count;
109    mDequeueCondition.broadcast();
110
111    return NO_ERROR;
112}
113
114void BufferQueue::setConsumerName(const String8& name) {
115    Mutex::Autolock lock(mMutex);
116    mConsumerName = name;
117}
118
119status_t BufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) {
120    Mutex::Autolock lock(mMutex);
121    mDefaultBufferFormat = defaultFormat;
122    return NO_ERROR;
123}
124
125status_t BufferQueue::setConsumerUsageBits(uint32_t usage) {
126    Mutex::Autolock lock(mMutex);
127    mConsumerUsageBits = usage;
128    return NO_ERROR;
129}
130
131status_t BufferQueue::setTransformHint(uint32_t hint) {
132    ST_LOGV("setTransformHint: %02x", hint);
133    Mutex::Autolock lock(mMutex);
134    mTransformHint = hint;
135    return NO_ERROR;
136}
137
138status_t BufferQueue::setBufferCount(int bufferCount) {
139    ST_LOGV("setBufferCount: count=%d", bufferCount);
140
141    sp<ConsumerListener> listener;
142    {
143        Mutex::Autolock lock(mMutex);
144
145        if (mAbandoned) {
146            ST_LOGE("setBufferCount: BufferQueue has been abandoned!");
147            return NO_INIT;
148        }
149        if (bufferCount > NUM_BUFFER_SLOTS) {
150            ST_LOGE("setBufferCount: bufferCount too large (max %d)",
151                    NUM_BUFFER_SLOTS);
152            return BAD_VALUE;
153        }
154
155        // Error out if the user has dequeued buffers
156        for (int i=0 ; i<NUM_BUFFER_SLOTS; i++) {
157            if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) {
158                ST_LOGE("setBufferCount: client owns some buffers");
159                return -EINVAL;
160            }
161        }
162
163        if (bufferCount == 0) {
164            mOverrideMaxBufferCount = 0;
165            mDequeueCondition.broadcast();
166            return NO_ERROR;
167        }
168
169        // fine to assume async to false before we're setting the buffer count
170        const int minBufferSlots = getMinMaxBufferCountLocked(false);
171        if (bufferCount < minBufferSlots) {
172            ST_LOGE("setBufferCount: requested buffer count (%d) is less than "
173                    "minimum (%d)", bufferCount, minBufferSlots);
174            return BAD_VALUE;
175        }
176
177        // here we're guaranteed that the client doesn't have dequeued buffers
178        // and will release all of its buffer references.  We don't clear the
179        // queue, however, so currently queued buffers still get displayed.
180        freeAllBuffersLocked();
181        mOverrideMaxBufferCount = bufferCount;
182        mDequeueCondition.broadcast();
183        listener = mConsumerListener;
184    } // scope for lock
185
186    if (listener != NULL) {
187        listener->onBuffersReleased();
188    }
189
190    return NO_ERROR;
191}
192
193int BufferQueue::query(int what, int* outValue)
194{
195    ATRACE_CALL();
196    Mutex::Autolock lock(mMutex);
197
198    if (mAbandoned) {
199        ST_LOGE("query: BufferQueue has been abandoned!");
200        return NO_INIT;
201    }
202
203    int value;
204    switch (what) {
205    case NATIVE_WINDOW_WIDTH:
206        value = mDefaultWidth;
207        break;
208    case NATIVE_WINDOW_HEIGHT:
209        value = mDefaultHeight;
210        break;
211    case NATIVE_WINDOW_FORMAT:
212        value = mDefaultBufferFormat;
213        break;
214    case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
215        value = getMinUndequeuedBufferCount(false);
216        break;
217    case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
218        value = (mQueue.size() >= 2);
219        break;
220    case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
221        value = mConsumerUsageBits;
222        break;
223    default:
224        return BAD_VALUE;
225    }
226    outValue[0] = value;
227    return NO_ERROR;
228}
229
230status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
231    ATRACE_CALL();
232    ST_LOGV("requestBuffer: slot=%d", slot);
233    Mutex::Autolock lock(mMutex);
234    if (mAbandoned) {
235        ST_LOGE("requestBuffer: BufferQueue has been abandoned!");
236        return NO_INIT;
237    }
238    if (slot < 0 || slot >= NUM_BUFFER_SLOTS) {
239        ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d",
240                NUM_BUFFER_SLOTS, slot);
241        return BAD_VALUE;
242    } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
243        ST_LOGE("requestBuffer: slot %d is not owned by the client (state=%d)",
244                slot, mSlots[slot].mBufferState);
245        return BAD_VALUE;
246    }
247    mSlots[slot].mRequestBufferCalled = true;
248    *buf = mSlots[slot].mGraphicBuffer;
249    return NO_ERROR;
250}
251
252status_t BufferQueue::dequeueBuffer(int *outBuf, sp<Fence>* outFence, bool async,
253        uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
254    ATRACE_CALL();
255    ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);
256
257    if ((w && !h) || (!w && h)) {
258        ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
259        return BAD_VALUE;
260    }
261
262    status_t returnFlags(OK);
263    EGLDisplay dpy = EGL_NO_DISPLAY;
264    EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
265
266    { // Scope for the lock
267        Mutex::Autolock lock(mMutex);
268
269        if (format == 0) {
270            format = mDefaultBufferFormat;
271        }
272        // turn on usage bits the consumer requested
273        usage |= mConsumerUsageBits;
274
275        int found = -1;
276        bool tryAgain = true;
277        while (tryAgain) {
278            if (mAbandoned) {
279                ST_LOGE("dequeueBuffer: BufferQueue has been abandoned!");
280                return NO_INIT;
281            }
282
283            const int maxBufferCount = getMaxBufferCountLocked(async);
284            if (async && mOverrideMaxBufferCount) {
285                // FIXME: some drivers are manually setting the buffer-count (which they
286                // shouldn't), so we do this extra test here to handle that case.
287                // This is TEMPORARY, until we get this fixed.
288                if (mOverrideMaxBufferCount < maxBufferCount) {
289                    ST_LOGE("dequeueBuffer: async mode is invalid with buffercount override");
290                    return BAD_VALUE;
291                }
292            }
293
294            // Free up any buffers that are in slots beyond the max buffer
295            // count.
296            for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
297                assert(mSlots[i].mBufferState == BufferSlot::FREE);
298                if (mSlots[i].mGraphicBuffer != NULL) {
299                    freeBufferLocked(i);
300                    returnFlags |= IGraphicBufferProducer::RELEASE_ALL_BUFFERS;
301                }
302            }
303
304            // look for a free buffer to give to the client
305            found = INVALID_BUFFER_SLOT;
306            int dequeuedCount = 0;
307            int acquiredCount = 0;
308            for (int i = 0; i < maxBufferCount; i++) {
309                const int state = mSlots[i].mBufferState;
310                switch (state) {
311                    case BufferSlot::DEQUEUED:
312                        dequeuedCount++;
313                        break;
314                    case BufferSlot::ACQUIRED:
315                        acquiredCount++;
316                        break;
317                    case BufferSlot::FREE:
318                        /* We return the oldest of the free buffers to avoid
319                         * stalling the producer if possible.  This is because
320                         * the consumer may still have pending reads of the
321                         * buffers in flight.
322                         */
323                        if ((found < 0) ||
324                                mSlots[i].mFrameNumber < mSlots[found].mFrameNumber) {
325                            found = i;
326                        }
327                        break;
328                }
329            }
330
331            // clients are not allowed to dequeue more than one buffer
332            // if they didn't set a buffer count.
333            if (!mOverrideMaxBufferCount && dequeuedCount) {
334                ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without "
335                        "setting the buffer count");
336                return -EINVAL;
337            }
338
339            // See whether a buffer has been queued since the last
340            // setBufferCount so we know whether to perform the min undequeued
341            // buffers check below.
342            if (mBufferHasBeenQueued) {
343                // make sure the client is not trying to dequeue more buffers
344                // than allowed.
345                const int newUndequeuedCount = maxBufferCount - (dequeuedCount+1);
346                const int minUndequeuedCount = getMinUndequeuedBufferCount(async);
347                if (newUndequeuedCount < minUndequeuedCount) {
348                    ST_LOGE("dequeueBuffer: min undequeued buffer count (%d) "
349                            "exceeded (dequeued=%d undequeudCount=%d)",
350                            minUndequeuedCount, dequeuedCount,
351                            newUndequeuedCount);
352                    return -EBUSY;
353                }
354            }
355
356            // If no buffer is found, wait for a buffer to be released or for
357            // the max buffer count to change.
358            tryAgain = found == INVALID_BUFFER_SLOT;
359            if (tryAgain) {
360                // return an error if we're in "cannot block" mode (producer and consumer
361                // are controlled by the application) -- however, the consumer is allowed
362                // to acquire briefly an extra buffer (which could cause us to have to wait here)
363                // and that's okay because we know the wait will be brief (it happens
364                // if we dequeue a buffer while the consumer has acquired one but not released
365                // the old one yet -- for e.g.: see GLConsumer::updateTexImage()).
366                if (mDequeueBufferCannotBlock && (acquiredCount <= mMaxAcquiredBufferCount)) {
367                    ST_LOGE("dequeueBuffer: would block! returning an error instead.");
368                    return WOULD_BLOCK;
369                }
370                mDequeueCondition.wait(mMutex);
371            }
372        }
373
374
375        if (found == INVALID_BUFFER_SLOT) {
376            // This should not happen.
377            ST_LOGE("dequeueBuffer: no available buffer slots");
378            return -EBUSY;
379        }
380
381        const int buf = found;
382        *outBuf = found;
383
384        ATRACE_BUFFER_INDEX(buf);
385
386        const bool useDefaultSize = !w && !h;
387        if (useDefaultSize) {
388            // use the default size
389            w = mDefaultWidth;
390            h = mDefaultHeight;
391        }
392
393        mSlots[buf].mBufferState = BufferSlot::DEQUEUED;
394
395        const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
396        if ((buffer == NULL) ||
397            (uint32_t(buffer->width)  != w) ||
398            (uint32_t(buffer->height) != h) ||
399            (uint32_t(buffer->format) != format) ||
400            ((uint32_t(buffer->usage) & usage) != usage))
401        {
402            mSlots[buf].mAcquireCalled = false;
403            mSlots[buf].mGraphicBuffer = NULL;
404            mSlots[buf].mRequestBufferCalled = false;
405            mSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
406            mSlots[buf].mFence = Fence::NO_FENCE;
407            mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
408
409            returnFlags |= IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION;
410        }
411
412        dpy = mSlots[buf].mEglDisplay;
413        eglFence = mSlots[buf].mEglFence;
414        *outFence = mSlots[buf].mFence;
415        mSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
416        mSlots[buf].mFence = Fence::NO_FENCE;
417    }  // end lock scope
418
419    if (returnFlags & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
420        status_t error;
421        sp<GraphicBuffer> graphicBuffer(
422                mGraphicBufferAlloc->createGraphicBuffer(
423                        w, h, format, usage, &error));
424        if (graphicBuffer == 0) {
425            ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer "
426                    "failed");
427            return error;
428        }
429
430        { // Scope for the lock
431            Mutex::Autolock lock(mMutex);
432
433            if (mAbandoned) {
434                ST_LOGE("dequeueBuffer: BufferQueue has been abandoned!");
435                return NO_INIT;
436            }
437
438            mSlots[*outBuf].mFrameNumber = ~0;
439            mSlots[*outBuf].mGraphicBuffer = graphicBuffer;
440        }
441    }
442
443    if (eglFence != EGL_NO_SYNC_KHR) {
444        EGLint result = eglClientWaitSyncKHR(dpy, eglFence, 0, 1000000000);
445        // If something goes wrong, log the error, but return the buffer without
446        // synchronizing access to it.  It's too late at this point to abort the
447        // dequeue operation.
448        if (result == EGL_FALSE) {
449            ST_LOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError());
450        } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
451            ST_LOGE("dequeueBuffer: timeout waiting for fence");
452        }
453        eglDestroySyncKHR(dpy, eglFence);
454    }
455
456    ST_LOGV("dequeueBuffer: returning slot=%d/%llu buf=%p flags=%#x", *outBuf,
457            mSlots[*outBuf].mFrameNumber,
458            mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);
459
460    return returnFlags;
461}
462
463status_t BufferQueue::queueBuffer(int buf,
464        const QueueBufferInput& input, QueueBufferOutput* output) {
465    ATRACE_CALL();
466    ATRACE_BUFFER_INDEX(buf);
467
468    Rect crop;
469    uint32_t transform;
470    int scalingMode;
471    int64_t timestamp;
472    bool async;
473    sp<Fence> fence;
474
475    input.deflate(&timestamp, &crop, &scalingMode, &transform, &async, &fence);
476
477    if (fence == NULL) {
478        ST_LOGE("queueBuffer: fence is NULL");
479        return BAD_VALUE;
480    }
481
482    switch (scalingMode) {
483        case NATIVE_WINDOW_SCALING_MODE_FREEZE:
484        case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
485        case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
486        case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
487            break;
488        default:
489            ST_LOGE("unknown scaling mode: %d", scalingMode);
490            return -EINVAL;
491    }
492
493    sp<ConsumerListener> listener;
494
495    { // scope for the lock
496        Mutex::Autolock lock(mMutex);
497
498        if (mAbandoned) {
499            ST_LOGE("queueBuffer: BufferQueue has been abandoned!");
500            return NO_INIT;
501        }
502
503        const int maxBufferCount = getMaxBufferCountLocked(async);
504        if (async && mOverrideMaxBufferCount) {
505            // FIXME: some drivers are manually setting the buffer-count (which they
506            // shouldn't), so we do this extra test here to handle that case.
507            // This is TEMPORARY, until we get this fixed.
508            if (mOverrideMaxBufferCount < maxBufferCount) {
509                ST_LOGE("queueBuffer: async mode is invalid with buffercount override");
510                return BAD_VALUE;
511            }
512        }
513        if (buf < 0 || buf >= maxBufferCount) {
514            ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d",
515                    maxBufferCount, buf);
516            return -EINVAL;
517        } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
518            ST_LOGE("queueBuffer: slot %d is not owned by the client "
519                    "(state=%d)", buf, mSlots[buf].mBufferState);
520            return -EINVAL;
521        } else if (!mSlots[buf].mRequestBufferCalled) {
522            ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
523                    "buffer", buf);
524            return -EINVAL;
525        }
526
527        ST_LOGV("queueBuffer: slot=%d/%llu time=%#llx crop=[%d,%d,%d,%d] "
528                "tr=%#x scale=%s",
529                buf, mFrameCounter + 1, timestamp,
530                crop.left, crop.top, crop.right, crop.bottom,
531                transform, scalingModeName(scalingMode));
532
533        const sp<GraphicBuffer>& graphicBuffer(mSlots[buf].mGraphicBuffer);
534        Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
535        Rect croppedCrop;
536        crop.intersect(bufferRect, &croppedCrop);
537        if (croppedCrop != crop) {
538            ST_LOGE("queueBuffer: crop rect is not contained within the "
539                    "buffer in slot %d", buf);
540            return -EINVAL;
541        }
542
543        mSlots[buf].mFence = fence;
544        mSlots[buf].mBufferState = BufferSlot::QUEUED;
545        mFrameCounter++;
546        mSlots[buf].mFrameNumber = mFrameCounter;
547
548        BufferItem item;
549        item.mAcquireCalled = mSlots[buf].mAcquireCalled;
550        item.mGraphicBuffer = mSlots[buf].mGraphicBuffer;
551        item.mCrop = crop;
552        item.mTransform = transform;
553        item.mScalingMode = scalingMode;
554        item.mTimestamp = timestamp;
555        item.mFrameNumber = mFrameCounter;
556        item.mBuf = buf;
557        item.mFence = fence;
558        item.mIsDroppable = mDequeueBufferCannotBlock || async;
559
560        if (mQueue.empty()) {
561            // when the queue is empty, we can ignore "mDequeueBufferCannotBlock", and
562            // simply queue this buffer.
563            mQueue.push_back(item);
564            listener = mConsumerListener;
565        } else {
566            // when the queue is not empty, we need to look at the front buffer
567            // state and see if we need to replace it.
568            Fifo::iterator front(mQueue.begin());
569            if (front->mIsDroppable) {
570                // buffer slot currently queued is marked free if still tracked
571                if (stillTracking(front)) {
572                    mSlots[front->mBuf].mBufferState = BufferSlot::FREE;
573                    // reset the frame number of the freed buffer so that it is the first in
574                    // line to be dequeued again.
575                    mSlots[front->mBuf].mFrameNumber = 0;
576                }
577                // and we record the new buffer in the queued list
578                *front = item;
579            } else {
580                mQueue.push_back(item);
581                listener = mConsumerListener;
582            }
583        }
584
585        mBufferHasBeenQueued = true;
586        mDequeueCondition.broadcast();
587
588        output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
589                mQueue.size());
590
591        ATRACE_INT(mConsumerName.string(), mQueue.size());
592    } // scope for the lock
593
594    // call back without lock held
595    if (listener != 0) {
596        listener->onFrameAvailable();
597    }
598    return NO_ERROR;
599}
600
601void BufferQueue::cancelBuffer(int buf, const sp<Fence>& fence) {
602    ATRACE_CALL();
603    ST_LOGV("cancelBuffer: slot=%d", buf);
604    Mutex::Autolock lock(mMutex);
605
606    if (mAbandoned) {
607        ST_LOGW("cancelBuffer: BufferQueue has been abandoned!");
608        return;
609    }
610
611    if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
612        ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d",
613                NUM_BUFFER_SLOTS, buf);
614        return;
615    } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
616        ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
617                buf, mSlots[buf].mBufferState);
618        return;
619    } else if (fence == NULL) {
620        ST_LOGE("cancelBuffer: fence is NULL");
621        return;
622    }
623    mSlots[buf].mBufferState = BufferSlot::FREE;
624    mSlots[buf].mFrameNumber = 0;
625    mSlots[buf].mFence = fence;
626    mDequeueCondition.broadcast();
627}
628
629status_t BufferQueue::connect(int api, bool producerControlledByApp, QueueBufferOutput* output) {
630    ATRACE_CALL();
631    ST_LOGV("connect: api=%d", api);
632    Mutex::Autolock lock(mMutex);
633
634    if (mAbandoned) {
635        ST_LOGE("connect: BufferQueue has been abandoned!");
636        return NO_INIT;
637    }
638
639    if (mConsumerListener == NULL) {
640        ST_LOGE("connect: BufferQueue has no consumer!");
641        return NO_INIT;
642    }
643
644    int err = NO_ERROR;
645    switch (api) {
646        case NATIVE_WINDOW_API_EGL:
647        case NATIVE_WINDOW_API_CPU:
648        case NATIVE_WINDOW_API_MEDIA:
649        case NATIVE_WINDOW_API_CAMERA:
650            if (mConnectedApi != NO_CONNECTED_API) {
651                ST_LOGE("connect: already connected (cur=%d, req=%d)",
652                        mConnectedApi, api);
653                err = -EINVAL;
654            } else {
655                mConnectedApi = api;
656                output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
657                        mQueue.size());
658            }
659            break;
660        default:
661            err = -EINVAL;
662            break;
663    }
664
665    mBufferHasBeenQueued = false;
666    mDequeueBufferCannotBlock = mConsumerControlledByApp && producerControlledByApp;
667
668    return err;
669}
670
671status_t BufferQueue::disconnect(int api) {
672    ATRACE_CALL();
673    ST_LOGV("disconnect: api=%d", api);
674
675    int err = NO_ERROR;
676    sp<ConsumerListener> listener;
677
678    { // Scope for the lock
679        Mutex::Autolock lock(mMutex);
680
681        if (mAbandoned) {
682            // it is not really an error to disconnect after the surface
683            // has been abandoned, it should just be a no-op.
684            return NO_ERROR;
685        }
686
687        switch (api) {
688            case NATIVE_WINDOW_API_EGL:
689            case NATIVE_WINDOW_API_CPU:
690            case NATIVE_WINDOW_API_MEDIA:
691            case NATIVE_WINDOW_API_CAMERA:
692                if (mConnectedApi == api) {
693                    freeAllBuffersLocked();
694                    mConnectedApi = NO_CONNECTED_API;
695                    mDequeueCondition.broadcast();
696                    listener = mConsumerListener;
697                } else {
698                    ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)",
699                            mConnectedApi, api);
700                    err = -EINVAL;
701                }
702                break;
703            default:
704                ST_LOGE("disconnect: unknown API %d", api);
705                err = -EINVAL;
706                break;
707        }
708    }
709
710    if (listener != NULL) {
711        listener->onBuffersReleased();
712    }
713
714    return err;
715}
716
717void BufferQueue::dump(String8& result) const {
718    BufferQueue::dump(result, "");
719}
720
721void BufferQueue::dump(String8& result, const char* prefix) const {
722    Mutex::Autolock _l(mMutex);
723
724    String8 fifo;
725    int fifoSize = 0;
726    Fifo::const_iterator i(mQueue.begin());
727    while (i != mQueue.end()) {
728        fifo.appendFormat("%02d:%p crop=[%d,%d,%d,%d], "
729                "xform=0x%02x, time=%#llx, scale=%s\n",
730                i->mBuf, i->mGraphicBuffer.get(),
731                i->mCrop.left, i->mCrop.top, i->mCrop.right,
732                i->mCrop.bottom, i->mTransform, i->mTimestamp,
733                scalingModeName(i->mScalingMode)
734                );
735        i++;
736        fifoSize++;
737    }
738
739
740    result.appendFormat(
741            "%s-BufferQueue mMaxAcquiredBufferCount=%d, mDequeueBufferCannotBlock=%d, default-size=[%dx%d], "
742            "default-format=%d, transform-hint=%02x, FIFO(%d)={%s}\n",
743            prefix, mMaxAcquiredBufferCount, mDequeueBufferCannotBlock, mDefaultWidth,
744            mDefaultHeight, mDefaultBufferFormat, mTransformHint,
745            fifoSize, fifo.string());
746
747    struct {
748        const char * operator()(int state) const {
749            switch (state) {
750                case BufferSlot::DEQUEUED: return "DEQUEUED";
751                case BufferSlot::QUEUED: return "QUEUED";
752                case BufferSlot::FREE: return "FREE";
753                case BufferSlot::ACQUIRED: return "ACQUIRED";
754                default: return "Unknown";
755            }
756        }
757    } stateName;
758
759    // just trim the free buffers to not spam the dump
760    int maxBufferCount = 0;
761    for (int i=NUM_BUFFER_SLOTS-1 ; i>=0 ; i--) {
762        const BufferSlot& slot(mSlots[i]);
763        if ((slot.mBufferState != BufferSlot::FREE) || (slot.mGraphicBuffer != NULL)) {
764            maxBufferCount = i+1;
765            break;
766        }
767    }
768
769    for (int i=0 ; i<maxBufferCount ; i++) {
770        const BufferSlot& slot(mSlots[i]);
771        const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
772        result.appendFormat(
773            "%s%s[%02d:%p] state=%-8s",
774                prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i, buf.get(),
775                stateName(slot.mBufferState)
776        );
777
778        if (buf != NULL) {
779            result.appendFormat(
780                    ", %p [%4ux%4u:%4u,%3X]",
781                    buf->handle, buf->width, buf->height, buf->stride,
782                    buf->format);
783        }
784        result.append("\n");
785    }
786}
787
788void BufferQueue::freeBufferLocked(int slot) {
789    ST_LOGV("freeBufferLocked: slot=%d", slot);
790    mSlots[slot].mGraphicBuffer = 0;
791    if (mSlots[slot].mBufferState == BufferSlot::ACQUIRED) {
792        mSlots[slot].mNeedsCleanupOnRelease = true;
793    }
794    mSlots[slot].mBufferState = BufferSlot::FREE;
795    mSlots[slot].mFrameNumber = 0;
796    mSlots[slot].mAcquireCalled = false;
797
798    // destroy fence as BufferQueue now takes ownership
799    if (mSlots[slot].mEglFence != EGL_NO_SYNC_KHR) {
800        eglDestroySyncKHR(mSlots[slot].mEglDisplay, mSlots[slot].mEglFence);
801        mSlots[slot].mEglFence = EGL_NO_SYNC_KHR;
802    }
803    mSlots[slot].mFence = Fence::NO_FENCE;
804}
805
806void BufferQueue::freeAllBuffersLocked() {
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, nsecs_t presentWhen) {
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        return NO_BUFFER_AVAILABLE;
838    }
839
840    Fifo::iterator front(mQueue.begin());
841    int buf = front->mBuf;
842
843    // Compare the buffer's desired presentation time to the predicted
844    // actual display time.
845    //
846    // The "presentWhen" argument indicates when the buffer is expected
847    // to be presented on-screen.  If the buffer's desired-present time
848    // is earlier (less) than presentWhen, meaning it'll be displayed
849    // on time or possibly late, we acquire and return it.  If we don't want
850    // to display it until after the presentWhen time, we return PRESENT_LATER
851    // without acquiring it.
852    //
853    // To be safe, we don't refuse to acquire the buffer if presentWhen is
854    // more than one second in the future beyond the desired present time
855    // (i.e. we'd be holding the buffer for a really long time).
856    const int MAX_FUTURE_NSEC = 1000000000ULL;
857    nsecs_t desiredPresent = front->mTimestamp;
858    if (presentWhen != 0 && desiredPresent > presentWhen &&
859            desiredPresent - presentWhen < MAX_FUTURE_NSEC)
860    {
861        ST_LOGV("pts defer: des=%lld when=%lld (%lld) now=%lld",
862                desiredPresent, presentWhen, desiredPresent - presentWhen,
863                systemTime(CLOCK_MONOTONIC));
864        return PRESENT_LATER;
865    }
866    if (presentWhen != 0) {
867        ST_LOGV("pts accept: %p[%d] sig=%lld des=%lld when=%lld (%lld)",
868                mSlots, buf, mSlots[buf].mFence->getSignalTime(),
869                desiredPresent, presentWhen, desiredPresent - presentWhen);
870    }
871
872    *buffer = *front;
873    ATRACE_BUFFER_INDEX(buf);
874
875    ST_LOGV("acquireBuffer: acquiring { slot=%d/%llu, buffer=%p }",
876            front->mBuf, front->mFrameNumber,
877            front->mGraphicBuffer->handle);
878    // if front buffer still being tracked update slot state
879    if (stillTracking(front)) {
880        mSlots[buf].mAcquireCalled = true;
881        mSlots[buf].mNeedsCleanupOnRelease = false;
882        mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
883        mSlots[buf].mFence = Fence::NO_FENCE;
884    }
885
886    // If the buffer has previously been acquired by the consumer, set
887    // mGraphicBuffer to NULL to avoid unnecessarily remapping this
888    // buffer on the consumer side.
889    if (buffer->mAcquireCalled) {
890        buffer->mGraphicBuffer = NULL;
891    }
892
893    mQueue.erase(front);
894    mDequeueCondition.broadcast();
895
896    ATRACE_INT(mConsumerName.string(), mQueue.size());
897
898    return NO_ERROR;
899}
900
901status_t BufferQueue::releaseBuffer(
902        int buf, uint64_t frameNumber, EGLDisplay display,
903        EGLSyncKHR eglFence, const sp<Fence>& fence) {
904    ATRACE_CALL();
905    ATRACE_BUFFER_INDEX(buf);
906
907    if (buf == INVALID_BUFFER_SLOT || fence == NULL) {
908        return BAD_VALUE;
909    }
910
911    Mutex::Autolock _l(mMutex);
912
913    // If the frame number has changed because buffer has been reallocated,
914    // we can ignore this releaseBuffer for the old buffer.
915    if (frameNumber != mSlots[buf].mFrameNumber) {
916        return STALE_BUFFER_SLOT;
917    }
918
919
920    // Internal state consistency checks:
921    // Make sure this buffers hasn't been queued while we were owning it (acquired)
922    Fifo::iterator front(mQueue.begin());
923    Fifo::const_iterator const end(mQueue.end());
924    while (front != end) {
925        if (front->mBuf == buf) {
926            LOG_ALWAYS_FATAL("[%s] received new buffer(#%lld) on slot #%d that has not yet been "
927                    "acquired", mConsumerName.string(), frameNumber, buf);
928            break; // never reached
929        }
930        front++;
931    }
932
933    // The buffer can now only be released if its in the acquired state
934    if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
935        mSlots[buf].mEglDisplay = display;
936        mSlots[buf].mEglFence = eglFence;
937        mSlots[buf].mFence = fence;
938        mSlots[buf].mBufferState = BufferSlot::FREE;
939    } else if (mSlots[buf].mNeedsCleanupOnRelease) {
940        ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState);
941        mSlots[buf].mNeedsCleanupOnRelease = false;
942        return STALE_BUFFER_SLOT;
943    } else {
944        ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState);
945        return -EINVAL;
946    }
947
948    mDequeueCondition.broadcast();
949    return NO_ERROR;
950}
951
952status_t BufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener,
953        bool controlledByApp) {
954    ST_LOGV("consumerConnect");
955    Mutex::Autolock lock(mMutex);
956
957    if (mAbandoned) {
958        ST_LOGE("consumerConnect: BufferQueue has been abandoned!");
959        return NO_INIT;
960    }
961    if (consumerListener == NULL) {
962        ST_LOGE("consumerConnect: consumerListener may not be NULL");
963        return BAD_VALUE;
964    }
965
966    mConsumerListener = consumerListener;
967    mConsumerControlledByApp = controlledByApp;
968
969    return NO_ERROR;
970}
971
972status_t BufferQueue::consumerDisconnect() {
973    ST_LOGV("consumerDisconnect");
974    Mutex::Autolock lock(mMutex);
975
976    if (mConsumerListener == NULL) {
977        ST_LOGE("consumerDisconnect: No consumer is connected!");
978        return -EINVAL;
979    }
980
981    mAbandoned = true;
982    mConsumerListener = NULL;
983    mQueue.clear();
984    freeAllBuffersLocked();
985    mDequeueCondition.broadcast();
986    return NO_ERROR;
987}
988
989status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) {
990    ST_LOGV("getReleasedBuffers");
991    Mutex::Autolock lock(mMutex);
992
993    if (mAbandoned) {
994        ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!");
995        return NO_INIT;
996    }
997
998    uint32_t mask = 0;
999    for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
1000        if (!mSlots[i].mAcquireCalled) {
1001            mask |= 1 << i;
1002        }
1003    }
1004
1005    // Remove buffers in flight (on the queue) from the mask where acquire has
1006    // been called, as the consumer will not receive the buffer address, so
1007    // it should not free these slots.
1008    Fifo::iterator front(mQueue.begin());
1009    while (front != mQueue.end()) {
1010        if (front->mAcquireCalled)
1011            mask &= ~(1 << front->mBuf);
1012        front++;
1013    }
1014
1015    *slotMask = mask;
1016
1017    ST_LOGV("getReleasedBuffers: returning mask %#x", mask);
1018    return NO_ERROR;
1019}
1020
1021status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h) {
1022    ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
1023    if (!w || !h) {
1024        ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
1025                w, h);
1026        return BAD_VALUE;
1027    }
1028
1029    Mutex::Autolock lock(mMutex);
1030    mDefaultWidth = w;
1031    mDefaultHeight = h;
1032    return NO_ERROR;
1033}
1034
1035status_t BufferQueue::setDefaultMaxBufferCount(int bufferCount) {
1036    ATRACE_CALL();
1037    Mutex::Autolock lock(mMutex);
1038    return setDefaultMaxBufferCountLocked(bufferCount);
1039}
1040
1041status_t BufferQueue::disableAsyncBuffer() {
1042    ATRACE_CALL();
1043    Mutex::Autolock lock(mMutex);
1044    if (mConsumerListener != NULL) {
1045        ST_LOGE("disableAsyncBuffer: consumer already connected!");
1046        return INVALID_OPERATION;
1047    }
1048    mUseAsyncBuffer = false;
1049    return NO_ERROR;
1050}
1051
1052status_t BufferQueue::setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
1053    ATRACE_CALL();
1054    Mutex::Autolock lock(mMutex);
1055    if (maxAcquiredBuffers < 1 || maxAcquiredBuffers > MAX_MAX_ACQUIRED_BUFFERS) {
1056        ST_LOGE("setMaxAcquiredBufferCount: invalid count specified: %d",
1057                maxAcquiredBuffers);
1058        return BAD_VALUE;
1059    }
1060    if (mConnectedApi != NO_CONNECTED_API) {
1061        return INVALID_OPERATION;
1062    }
1063    mMaxAcquiredBufferCount = maxAcquiredBuffers;
1064    return NO_ERROR;
1065}
1066
1067int BufferQueue::getMinUndequeuedBufferCount(bool async) const {
1068    // if dequeueBuffer is allowed to error out, we don't have to
1069    // add an extra buffer.
1070    if (!mUseAsyncBuffer)
1071        return mMaxAcquiredBufferCount;
1072
1073    // we're in async mode, or we want to prevent the app to
1074    // deadlock itself, we throw-in an extra buffer to guarantee it.
1075    if (mDequeueBufferCannotBlock || async)
1076        return mMaxAcquiredBufferCount+1;
1077
1078    return mMaxAcquiredBufferCount;
1079}
1080
1081int BufferQueue::getMinMaxBufferCountLocked(bool async) const {
1082    return getMinUndequeuedBufferCount(async) + 1;
1083}
1084
1085int BufferQueue::getMaxBufferCountLocked(bool async) const {
1086    int minMaxBufferCount = getMinMaxBufferCountLocked(async);
1087
1088    int maxBufferCount = mDefaultMaxBufferCount;
1089    if (maxBufferCount < minMaxBufferCount) {
1090        maxBufferCount = minMaxBufferCount;
1091    }
1092    if (mOverrideMaxBufferCount != 0) {
1093        assert(mOverrideMaxBufferCount >= minMaxBufferCount);
1094        maxBufferCount = mOverrideMaxBufferCount;
1095    }
1096
1097    // Any buffers that are dequeued by the producer or sitting in the queue
1098    // waiting to be consumed need to have their slots preserved.  Such
1099    // buffers will temporarily keep the max buffer count up until the slots
1100    // no longer need to be preserved.
1101    for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
1102        BufferSlot::BufferState state = mSlots[i].mBufferState;
1103        if (state == BufferSlot::QUEUED || state == BufferSlot::DEQUEUED) {
1104            maxBufferCount = i + 1;
1105        }
1106    }
1107
1108    return maxBufferCount;
1109}
1110
1111bool BufferQueue::stillTracking(const BufferItem *item) const {
1112    const BufferSlot &slot = mSlots[item->mBuf];
1113
1114    ST_LOGV("stillTracking?: item: { slot=%d/%llu, buffer=%p }, "
1115            "slot: { slot=%d/%llu, buffer=%p }",
1116            item->mBuf, item->mFrameNumber,
1117            (item->mGraphicBuffer.get() ? item->mGraphicBuffer->handle : 0),
1118            item->mBuf, slot.mFrameNumber,
1119            (slot.mGraphicBuffer.get() ? slot.mGraphicBuffer->handle : 0));
1120
1121    // Compare item with its original buffer slot.  We can check the slot
1122    // as the buffer would not be moved to a different slot by the producer.
1123    return (slot.mGraphicBuffer != NULL &&
1124            item->mGraphicBuffer->handle == slot.mGraphicBuffer->handle);
1125}
1126
1127BufferQueue::ProxyConsumerListener::ProxyConsumerListener(
1128        const wp<BufferQueue::ConsumerListener>& consumerListener):
1129        mConsumerListener(consumerListener) {}
1130
1131BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}
1132
1133void BufferQueue::ProxyConsumerListener::onFrameAvailable() {
1134    sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1135    if (listener != NULL) {
1136        listener->onFrameAvailable();
1137    }
1138}
1139
1140void BufferQueue::ProxyConsumerListener::onBuffersReleased() {
1141    sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote());
1142    if (listener != NULL) {
1143        listener->onBuffersReleased();
1144    }
1145}
1146
1147}; // namespace android
1148