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