BufferQueueProducer.cpp 48.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17 18
#include <inttypes.h>

19 20 21 22
#define LOG_TAG "BufferQueueProducer"
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
//#define LOG_NDEBUG 0

23 24 25 26 27 28
#if DEBUG_ONLY_CODE
#define VALIDATE_CONSISTENCY() do { mCore->validateConsistencyLocked(); } while (0)
#else
#define VALIDATE_CONSISTENCY()
#endif

29 30 31 32 33 34 35
#define EGL_EGLEXT_PROTOTYPES

#include <gui/BufferItem.h>
#include <gui/BufferQueueCore.h>
#include <gui/BufferQueueProducer.h>
#include <gui/IConsumerListener.h>
#include <gui/IGraphicBufferAlloc.h>
36
#include <gui/IProducerListener.h>
37 38 39 40 41 42 43 44 45

#include <utils/Log.h>
#include <utils/Trace.h>

namespace android {

BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core) :
    mCore(core),
    mSlots(core->mSlots),
46
    mConsumerName(),
47
    mStickyTransform(0),
48 49 50 51
    mLastQueueBufferFence(Fence::NO_FENCE),
    mCallbackMutex(),
    mNextCallbackTicket(0),
    mCurrentCallbackTicket(0),
52 53
    mCallbackCondition(),
    mDequeueTimeout(-1) {}
54 55 56 57 58 59 60 61 62 63 64 65 66

BufferQueueProducer::~BufferQueueProducer() {}

status_t BufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
    ATRACE_CALL();
    BQ_LOGV("requestBuffer: slot %d", slot);
    Mutex::Autolock lock(mCore->mMutex);

    if (mCore->mIsAbandoned) {
        BQ_LOGE("requestBuffer: BufferQueue has been abandoned");
        return NO_INIT;
    }

67 68 69 70 71
    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
        BQ_LOGE("requestBuffer: BufferQueue has no connected producer");
        return NO_INIT;
    }

72
    if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
73
        BQ_LOGE("requestBuffer: slot index %d out of range [0, %d)",
74
                slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
75
        return BAD_VALUE;
76
    } else if (!mSlots[slot].mBufferState.isDequeued()) {
77
        BQ_LOGE("requestBuffer: slot %d is not owned by the producer "
78
                "(state = %s)", slot, mSlots[slot].mBufferState.string());
79 80 81 82 83 84 85 86
        return BAD_VALUE;
    }

    mSlots[slot].mRequestBufferCalled = true;
    *buf = mSlots[slot].mGraphicBuffer;
    return NO_ERROR;
}

87 88 89 90 91 92
status_t BufferQueueProducer::setMaxDequeuedBufferCount(
        int maxDequeuedBuffers) {
    ATRACE_CALL();
    BQ_LOGV("setMaxDequeuedBufferCount: maxDequeuedBuffers = %d",
            maxDequeuedBuffers);

93
    sp<IConsumerListener> listener;
94 95 96 97 98 99 100 101 102 103
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
        mCore->waitWhileAllocatingLocked();

        if (mCore->mIsAbandoned) {
            BQ_LOGE("setMaxDequeuedBufferCount: BufferQueue has been "
                    "abandoned");
            return NO_INIT;
        }

Pablo Ceballos's avatar
Pablo Ceballos committed
104 105 106
        // The new maxDequeuedBuffer count should not be violated by the number
        // of currently dequeued buffers
        int dequeuedCount = 0;
107
        for (int s : mCore->mActiveBuffers) {
108
            if (mSlots[s].mBufferState.isDequeued()) {
Pablo Ceballos's avatar
Pablo Ceballos committed
109
                dequeuedCount++;
110 111
            }
        }
Pablo Ceballos's avatar
Pablo Ceballos committed
112 113 114 115 116 117
        if (dequeuedCount > maxDequeuedBuffers) {
            BQ_LOGE("setMaxDequeuedBufferCount: the requested maxDequeuedBuffer"
                    "count (%d) exceeds the current dequeued buffer count (%d)",
                    maxDequeuedBuffers, dequeuedCount);
            return BAD_VALUE;
        }
118

119
        int bufferCount = mCore->getMinUndequeuedBufferCountLocked();
120 121 122 123 124 125 126 127
        bufferCount += maxDequeuedBuffers;

        if (bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) {
            BQ_LOGE("setMaxDequeuedBufferCount: bufferCount %d too large "
                    "(max %d)", bufferCount, BufferQueueDefs::NUM_BUFFER_SLOTS);
            return BAD_VALUE;
        }

128
        const int minBufferSlots = mCore->getMinMaxBufferCountLocked();
129 130 131 132 133 134
        if (bufferCount < minBufferSlots) {
            BQ_LOGE("setMaxDequeuedBufferCount: requested buffer count %d is "
                    "less than minimum %d", bufferCount, minBufferSlots);
            return BAD_VALUE;
        }

135 136
        if (bufferCount > mCore->mMaxBufferCount) {
            BQ_LOGE("setMaxDequeuedBufferCount: %d dequeued buffers would "
137 138 139 140
                    "exceed the maxBufferCount (%d) (maxAcquired %d async %d "
                    "mDequeuedBufferCannotBlock %d)", maxDequeuedBuffers,
                    mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
                    mCore->mAsyncMode, mCore->mDequeueBufferCannotBlock);
141 142 143
            return BAD_VALUE;
        }

Pablo Ceballos's avatar
Pablo Ceballos committed
144
        int delta = maxDequeuedBuffers - mCore->mMaxDequeuedBufferCount;
145
        if (!mCore->adjustAvailableSlotsLocked(delta)) {
146 147
            return BAD_VALUE;
        }
148
        mCore->mMaxDequeuedBufferCount = maxDequeuedBuffers;
149
        VALIDATE_CONSISTENCY();
Pablo Ceballos's avatar
Pablo Ceballos committed
150
        if (delta < 0) {
151
            listener = mCore->mConsumerListener;
Pablo Ceballos's avatar
Pablo Ceballos committed
152
        }
153 154 155 156
        mCore->mDequeueCondition.broadcast();
    } // Autolock scope

    // Call back without lock held
157 158
    if (listener != NULL) {
        listener->onBuffersReleased();
159 160 161 162 163 164 165 166 167
    }

    return NO_ERROR;
}

status_t BufferQueueProducer::setAsyncMode(bool async) {
    ATRACE_CALL();
    BQ_LOGV("setAsyncMode: async = %d", async);

168
    sp<IConsumerListener> listener;
169 170 171 172 173 174 175 176 177
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
        mCore->waitWhileAllocatingLocked();

        if (mCore->mIsAbandoned) {
            BQ_LOGE("setAsyncMode: BufferQueue has been abandoned");
            return NO_INIT;
        }

178
        if ((mCore->mMaxAcquiredBufferCount + mCore->mMaxDequeuedBufferCount +
179 180
                (async || mCore->mDequeueBufferCannotBlock ? 1 : 0)) >
                mCore->mMaxBufferCount) {
181 182
            BQ_LOGE("setAsyncMode(%d): this call would cause the "
                    "maxBufferCount (%d) to be exceeded (maxAcquired %d "
183 184 185 186
                    "maxDequeued %d mDequeueBufferCannotBlock %d)", async,
                    mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
                    mCore->mMaxDequeuedBufferCount,
                    mCore->mDequeueBufferCannotBlock);
187 188 189
            return BAD_VALUE;
        }

190 191 192 193
        int delta = mCore->getMaxBufferCountLocked(async,
                mCore->mDequeueBufferCannotBlock, mCore->mMaxBufferCount)
                - mCore->getMaxBufferCountLocked();

194
        if (!mCore->adjustAvailableSlotsLocked(delta)) {
195 196 197 198
            BQ_LOGE("setAsyncMode: BufferQueue failed to adjust the number of "
                    "available slots. Delta = %d", delta);
            return BAD_VALUE;
        }
199
        mCore->mAsyncMode = async;
200
        VALIDATE_CONSISTENCY();
201
        mCore->mDequeueCondition.broadcast();
202
        listener = mCore->mConsumerListener;
203 204 205
    } // Autolock scope

    // Call back without lock held
206 207
    if (listener != NULL) {
        listener->onBuffersReleased();
208 209 210 211
    }
    return NO_ERROR;
}

212 213 214 215
int BufferQueueProducer::getFreeBufferLocked() const {
    if (mCore->mFreeBuffers.empty()) {
        return BufferQueueCore::INVALID_BUFFER_SLOT;
    }
216
    int slot = mCore->mFreeBuffers.front();
217 218 219 220
    mCore->mFreeBuffers.pop_front();
    return slot;
}

221
int BufferQueueProducer::getFreeSlotLocked() const {
222 223 224
    if (mCore->mFreeSlots.empty()) {
        return BufferQueueCore::INVALID_BUFFER_SLOT;
    }
Pablo Ceballos's avatar
Pablo Ceballos committed
225
    int slot = *(mCore->mFreeSlots.begin());
226
    mCore->mFreeSlots.erase(slot);
Pablo Ceballos's avatar
Pablo Ceballos committed
227
    return slot;
228 229 230
}

status_t BufferQueueProducer::waitForFreeSlotThenRelock(FreeSlotCaller caller,
231
        int* found) const {
232 233
    auto callerString = (caller == FreeSlotCaller::Dequeue) ?
            "dequeueBuffer" : "attachBuffer";
234 235 236
    bool tryAgain = true;
    while (tryAgain) {
        if (mCore->mIsAbandoned) {
237
            BQ_LOGE("%s: BufferQueue has been abandoned", callerString);
238 239 240 241 242
            return NO_INIT;
        }

        int dequeuedCount = 0;
        int acquiredCount = 0;
243
        for (int s : mCore->mActiveBuffers) {
244 245 246 247 248
            if (mSlots[s].mBufferState.isDequeued()) {
                ++dequeuedCount;
            }
            if (mSlots[s].mBufferState.isAcquired()) {
                ++acquiredCount;
249 250 251
            }
        }

252 253 254 255 256 257
        // Producers are not allowed to dequeue more than
        // mMaxDequeuedBufferCount buffers.
        // This check is only done if a buffer has already been queued
        if (mCore->mBufferHasBeenQueued &&
                dequeuedCount >= mCore->mMaxDequeuedBufferCount) {
            BQ_LOGE("%s: attempting to exceed the max dequeued buffer count "
258
                    "(%d)", callerString, mCore->mMaxDequeuedBufferCount);
259 260 261
            return INVALID_OPERATION;
        }

262 263
        *found = BufferQueueCore::INVALID_BUFFER_SLOT;

264 265 266 267
        // If we disconnect and reconnect quickly, we can be in a state where
        // our slots are empty but we have many buffers in the queue. This can
        // cause us to run out of memory if we outrun the consumer. Wait here if
        // it looks like we have too many buffers queued up.
268
        const int maxBufferCount = mCore->getMaxBufferCountLocked();
269 270
        bool tooManyBuffers = mCore->mQueue.size()
                            > static_cast<size_t>(maxBufferCount);
271
        if (tooManyBuffers) {
272
            BQ_LOGV("%s: queue size is %zu, waiting", callerString,
273
                    mCore->mQueue.size());
274
        } else {
275
            // If in shared buffer mode and a shared buffer exists, always
276
            // return it.
277
            if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot !=
278
                    BufferQueueCore::INVALID_BUFFER_SLOT) {
279
                *found = mCore->mSharedBufferSlot;
280 281 282
            } else {
                if (caller == FreeSlotCaller::Dequeue) {
                    // If we're calling this from dequeue, prefer free buffers
283
                    int slot = getFreeBufferLocked();
284 285 286
                    if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
                        *found = slot;
                    } else if (mCore->mAllowAllocation) {
287
                        *found = getFreeSlotLocked();
288 289 290
                    }
                } else {
                    // If we're calling this from attach, prefer free slots
291
                    int slot = getFreeSlotLocked();
292 293 294 295 296
                    if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
                        *found = slot;
                    } else {
                        *found = getFreeBufferLocked();
                    }
297 298
                }
            }
299 300 301 302 303 304 305
        }

        // If no buffer is found, or if the queue has too many buffers
        // outstanding, wait for a buffer to be acquired or released, or for the
        // max buffer count to change.
        tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
                   tooManyBuffers;
306 307 308 309 310 311 312
        if (tryAgain) {
            // Return an error if we're in non-blocking mode (producer and
            // consumer are controlled by the application).
            // However, the consumer is allowed to briefly acquire an extra
            // buffer (which could cause us to have to wait here), which is
            // okay, since it is only used to implement an atomic acquire +
            // release (e.g., in GLConsumer::updateTexImage())
313
            if ((mCore->mDequeueBufferCannotBlock || mCore->mAsyncMode) &&
314 315 316
                    (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
                return WOULD_BLOCK;
            }
317 318 319 320 321 322 323 324 325
            if (mDequeueTimeout >= 0) {
                status_t result = mCore->mDequeueCondition.waitRelative(
                        mCore->mMutex, mDequeueTimeout);
                if (result == TIMED_OUT) {
                    return result;
                }
            } else {
                mCore->mDequeueCondition.wait(mCore->mMutex);
            }
326 327 328 329 330 331
        }
    } // while (tryAgain)

    return NO_ERROR;
}

332
status_t BufferQueueProducer::dequeueBuffer(int *outSlot,
333 334
        sp<android::Fence> *outFence, uint32_t width, uint32_t height,
        PixelFormat format, uint32_t usage) {
335 336 337 338
    ATRACE_CALL();
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
        mConsumerName = mCore->mConsumerName;
339 340 341 342 343 344 345 346 347 348

        if (mCore->mIsAbandoned) {
            BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
            return NO_INIT;
        }

        if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
            BQ_LOGE("dequeueBuffer: BufferQueue has no connected producer");
            return NO_INIT;
        }
349 350
    } // Autolock scope

351 352
    BQ_LOGV("dequeueBuffer: w=%u h=%u format=%#x, usage=%#x", width, height,
            format, usage);
353 354 355 356 357 358 359 360 361

    if ((width && !height) || (!width && height)) {
        BQ_LOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
        return BAD_VALUE;
    }

    status_t returnFlags = NO_ERROR;
    EGLDisplay eglDisplay = EGL_NO_DISPLAY;
    EGLSyncKHR eglFence = EGL_NO_SYNC_KHR;
362
    bool attachedByConsumer = false;
363 364 365

    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
366
        mCore->waitWhileAllocatingLocked();
367 368 369 370 371 372 373 374

        if (format == 0) {
            format = mCore->mDefaultBufferFormat;
        }

        // Enable the usage bits the consumer requested
        usage |= mCore->mConsumerUsageBits;

375 376 377 378
        const bool useDefaultSize = !width && !height;
        if (useDefaultSize) {
            width = mCore->mDefaultWidth;
            height = mCore->mDefaultHeight;
379
        }
380

381
        int found = BufferItem::INVALID_BUFFER_SLOT;
382
        while (found == BufferItem::INVALID_BUFFER_SLOT) {
383
            status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Dequeue,
384
                    &found);
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
            if (status != NO_ERROR) {
                return status;
            }

            // This should not happen
            if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
                BQ_LOGE("dequeueBuffer: no available buffer slots");
                return -EBUSY;
            }

            const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);

            // If we are not allowed to allocate new buffers,
            // waitForFreeSlotThenRelock must have returned a slot containing a
            // buffer. If this buffer would require reallocation to meet the
            // requested attributes, we free it and attempt to get another one.
            if (!mCore->mAllowAllocation) {
                if (buffer->needsReallocation(width, height, format, usage)) {
403
                    if (mCore->mSharedBufferSlot == found) {
404 405 406 407
                        BQ_LOGE("dequeueBuffer: cannot re-allocate a shared"
                                "buffer");
                        return BAD_VALUE;
                    }
408 409
                    mCore->mFreeSlots.insert(found);
                    mCore->clearBufferSlotLocked(found);
410 411 412 413
                    found = BufferItem::INVALID_BUFFER_SLOT;
                    continue;
                }
            }
414 415
        }

416
        const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
417
        if (mCore->mSharedBufferSlot == found &&
418 419 420 421 422 423 424
                buffer->needsReallocation(width,  height, format, usage)) {
            BQ_LOGE("dequeueBuffer: cannot re-allocate a shared"
                    "buffer");

            return BAD_VALUE;
        }

425
        if (mCore->mSharedBufferSlot != found) {
426 427
            mCore->mActiveBuffers.insert(found);
        }
428 429 430
        *outSlot = found;
        ATRACE_BUFFER_INDEX(found);

431 432
        attachedByConsumer = mSlots[found].mNeedsReallocation;
        mSlots[found].mNeedsReallocation = false;
433

434 435
        mSlots[found].mBufferState.dequeue();

436
        // If shared buffer mode has just been enabled, cache the slot of the
437
        // first buffer that is dequeued and mark it as the shared buffer.
438
        if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
439
                BufferQueueCore::INVALID_BUFFER_SLOT) {
440
            mCore->mSharedBufferSlot = found;
441 442
            mSlots[found].mBufferState.mShared = true;
        }
443 444

        if ((buffer == NULL) ||
445
                buffer->needsReallocation(width, height, format, usage))
446 447 448 449 450 451 452
        {
            mSlots[found].mAcquireCalled = false;
            mSlots[found].mGraphicBuffer = NULL;
            mSlots[found].mRequestBufferCalled = false;
            mSlots[found].mEglDisplay = EGL_NO_DISPLAY;
            mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
            mSlots[found].mFence = Fence::NO_FENCE;
453
            mCore->mBufferAge = 0;
454
            mCore->mIsAllocating = true;
455 456

            returnFlags |= BUFFER_NEEDS_REALLOCATION;
457 458 459 460 461
        } else {
            // We add 1 because that will be the frame number when this buffer
            // is queued
            mCore->mBufferAge =
                    mCore->mFrameCounter + 1 - mSlots[found].mFrameNumber;
462 463
        }

464 465
        BQ_LOGV("dequeueBuffer: setting buffer age to %" PRIu64,
                mCore->mBufferAge);
466

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        if (CC_UNLIKELY(mSlots[found].mFence == NULL)) {
            BQ_LOGE("dequeueBuffer: about to return a NULL fence - "
                    "slot=%d w=%d h=%d format=%u",
                    found, buffer->width, buffer->height, buffer->format);
        }

        eglDisplay = mSlots[found].mEglDisplay;
        eglFence = mSlots[found].mEglFence;
        *outFence = mSlots[found].mFence;
        mSlots[found].mEglFence = EGL_NO_SYNC_KHR;
        mSlots[found].mFence = Fence::NO_FENCE;
    } // Autolock scope

    if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
        status_t error;
482
        BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
483
        sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
484
                width, height, format, usage, &error));
485 486 487
        { // Autolock scope
            Mutex::Autolock lock(mCore->mMutex);

488 489 490 491 492 493 494 495 496 497 498 499 500
            if (graphicBuffer != NULL && !mCore->mIsAbandoned) {
                graphicBuffer->setGenerationNumber(mCore->mGenerationNumber);
                mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
            }

            mCore->mIsAllocating = false;
            mCore->mIsAllocatingCondition.broadcast();

            if (graphicBuffer == NULL) {
                BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
                return error;
            }

501 502 503 504
            if (mCore->mIsAbandoned) {
                BQ_LOGE("dequeueBuffer: BufferQueue has been abandoned");
                return NO_INIT;
            }
505

506
            VALIDATE_CONSISTENCY();
507 508 509
        } // Autolock scope
    }

510 511 512 513
    if (attachedByConsumer) {
        returnFlags |= BUFFER_NEEDS_REALLOCATION;
    }

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    if (eglFence != EGL_NO_SYNC_KHR) {
        EGLint result = eglClientWaitSyncKHR(eglDisplay, eglFence, 0,
                1000000000);
        // If something goes wrong, log the error, but return the buffer without
        // synchronizing access to it. It's too late at this point to abort the
        // dequeue operation.
        if (result == EGL_FALSE) {
            BQ_LOGE("dequeueBuffer: error %#x waiting for fence",
                    eglGetError());
        } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
            BQ_LOGE("dequeueBuffer: timeout waiting for fence");
        }
        eglDestroySyncKHR(eglDisplay, eglFence);
    }

529 530
    BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
            *outSlot,
531 532 533 534 535 536
            mSlots[*outSlot].mFrameNumber,
            mSlots[*outSlot].mGraphicBuffer->handle, returnFlags);

    return returnFlags;
}

537 538 539
status_t BufferQueueProducer::detachBuffer(int slot) {
    ATRACE_CALL();
    ATRACE_BUFFER_INDEX(slot);
540
    BQ_LOGV("detachBuffer: slot %d", slot);
541
    Mutex::Autolock lock(mCore->mMutex);
542

543 544 545 546
    if (mCore->mIsAbandoned) {
        BQ_LOGE("detachBuffer: BufferQueue has been abandoned");
        return NO_INIT;
    }
Pablo Ceballos's avatar
Pablo Ceballos committed
547

548 549 550
    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
        BQ_LOGE("detachBuffer: BufferQueue has no connected producer");
        return NO_INIT;
551 552
    }

553 554
    if (mCore->mSharedBufferMode || mCore->mSharedBufferSlot == slot) {
        BQ_LOGE("detachBuffer: cannot detach a buffer in shared buffer mode");
555
        return BAD_VALUE;
Pablo Ceballos's avatar
Pablo Ceballos committed
556
    }
557 558 559 560 561 562 563 564 565 566 567 568 569

    if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
        BQ_LOGE("detachBuffer: slot index %d out of range [0, %d)",
                slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
        return BAD_VALUE;
    } else if (!mSlots[slot].mBufferState.isDequeued()) {
        BQ_LOGE("detachBuffer: slot %d is not owned by the producer "
                "(state = %s)", slot, mSlots[slot].mBufferState.string());
        return BAD_VALUE;
    } else if (!mSlots[slot].mRequestBufferCalled) {
        BQ_LOGE("detachBuffer: buffer in slot %d has not been requested",
                slot);
        return BAD_VALUE;
Pablo Ceballos's avatar
Pablo Ceballos committed
570
    }
571

572 573 574 575 576 577 578
    mSlots[slot].mBufferState.detachProducer();
    mCore->mActiveBuffers.erase(slot);
    mCore->mFreeSlots.insert(slot);
    mCore->clearBufferSlotLocked(slot);
    mCore->mDequeueCondition.broadcast();
    VALIDATE_CONSISTENCY();

579 580 581
    return NO_ERROR;
}

582 583 584 585 586 587 588 589 590 591 592 593
status_t BufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
        sp<Fence>* outFence) {
    ATRACE_CALL();

    if (outBuffer == NULL) {
        BQ_LOGE("detachNextBuffer: outBuffer must not be NULL");
        return BAD_VALUE;
    } else if (outFence == NULL) {
        BQ_LOGE("detachNextBuffer: outFence must not be NULL");
        return BAD_VALUE;
    }

594
    Mutex::Autolock lock(mCore->mMutex);
595

596 597 598 599
    if (mCore->mIsAbandoned) {
        BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
        return NO_INIT;
    }
600

601 602 603 604
    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
        BQ_LOGE("detachNextBuffer: BufferQueue has no connected producer");
        return NO_INIT;
    }
605

606 607 608
    if (mCore->mSharedBufferMode) {
        BQ_LOGE("detachNextBuffer: cannot detach a buffer in shared buffer "
            "mode");
609 610
        return BAD_VALUE;
    }
611

612
    mCore->waitWhileAllocatingLocked();
613

614 615 616
    if (mCore->mFreeBuffers.empty()) {
        return NO_MEMORY;
    }
617

618 619 620
    int found = mCore->mFreeBuffers.front();
    mCore->mFreeBuffers.remove(found);
    mCore->mFreeSlots.insert(found);
621

622
    BQ_LOGV("detachNextBuffer detached slot %d", found);
623

624 625 626 627
    *outBuffer = mSlots[found].mGraphicBuffer;
    *outFence = mSlots[found].mFence;
    mCore->clearBufferSlotLocked(found);
    VALIDATE_CONSISTENCY();
628 629 630 631

    return NO_ERROR;
}

632 633 634 635 636
status_t BufferQueueProducer::attachBuffer(int* outSlot,
        const sp<android::GraphicBuffer>& buffer) {
    ATRACE_CALL();

    if (outSlot == NULL) {
637
        BQ_LOGE("attachBuffer: outSlot must not be NULL");
638 639
        return BAD_VALUE;
    } else if (buffer == NULL) {
640
        BQ_LOGE("attachBuffer: cannot attach NULL buffer");
641 642 643 644
        return BAD_VALUE;
    }

    Mutex::Autolock lock(mCore->mMutex);
645 646

    if (mCore->mIsAbandoned) {
647
        BQ_LOGE("attachBuffer: BufferQueue has been abandoned");
648 649 650 651
        return NO_INIT;
    }

    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
652
        BQ_LOGE("attachBuffer: BufferQueue has no connected producer");
653 654
        return NO_INIT;
    }
655

656 657
    if (mCore->mSharedBufferMode) {
        BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode");
658 659 660
        return BAD_VALUE;
    }

661 662 663 664 665 666 667
    if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
        BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
                "[queue %u]", buffer->getGenerationNumber(),
                mCore->mGenerationNumber);
        return BAD_VALUE;
    }

668 669
    mCore->waitWhileAllocatingLocked();

670 671
    status_t returnFlags = NO_ERROR;
    int found;
672
    status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Attach, &found);
673 674 675 676 677 678
    if (status != NO_ERROR) {
        return status;
    }

    // This should not happen
    if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
679
        BQ_LOGE("attachBuffer: no available buffer slots");
680 681 682 683 684
        return -EBUSY;
    }

    *outSlot = found;
    ATRACE_BUFFER_INDEX(*outSlot);
685
    BQ_LOGV("attachBuffer: returning slot %d flags=%#x",
686 687 688
            *outSlot, returnFlags);

    mSlots[*outSlot].mGraphicBuffer = buffer;
689
    mSlots[*outSlot].mBufferState.attachProducer();
690 691
    mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
    mSlots[*outSlot].mFence = Fence::NO_FENCE;
692
    mSlots[*outSlot].mRequestBufferCalled = true;
693 694
    mSlots[*outSlot].mAcquireCalled = false;
    mCore->mActiveBuffers.insert(found);
695
    VALIDATE_CONSISTENCY();
696

697 698 699
    return returnFlags;
}

700 701 702 703 704 705 706
status_t BufferQueueProducer::queueBuffer(int slot,
        const QueueBufferInput &input, QueueBufferOutput *output) {
    ATRACE_CALL();
    ATRACE_BUFFER_INDEX(slot);

    int64_t timestamp;
    bool isAutoTimestamp;
707
    android_dataspace dataSpace;
708
    Rect crop(Rect::EMPTY_RECT);
709 710
    int scalingMode;
    uint32_t transform;
711
    uint32_t stickyTransform;
712
    sp<Fence> fence;
713
    input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop, &scalingMode,
714
            &transform, &fence, &stickyTransform);
715
    Region surfaceDamage = input.getSurfaceDamage();
716 717 718

    if (fence == NULL) {
        BQ_LOGE("queueBuffer: fence is NULL");
719
        return BAD_VALUE;
720 721 722 723 724 725 726 727 728 729
    }

    switch (scalingMode) {
        case NATIVE_WINDOW_SCALING_MODE_FREEZE:
        case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
        case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
        case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
            break;
        default:
            BQ_LOGE("queueBuffer: unknown scaling mode %d", scalingMode);
730
            return BAD_VALUE;
731 732
    }

733 734 735 736
    sp<IConsumerListener> frameAvailableListener;
    sp<IConsumerListener> frameReplacedListener;
    int callbackTicket = 0;
    BufferItem item;
737 738 739 740 741 742 743 744
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);

        if (mCore->mIsAbandoned) {
            BQ_LOGE("queueBuffer: BufferQueue has been abandoned");
            return NO_INIT;
        }

745 746 747 748 749
        if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
            BQ_LOGE("queueBuffer: BufferQueue has no connected producer");
            return NO_INIT;
        }

750
        if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
751
            BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)",
752
                    slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
753
            return BAD_VALUE;
754
        } else if (!mSlots[slot].mBufferState.isDequeued()) {
755
            BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
756
                    "(state = %s)", slot, mSlots[slot].mBufferState.string());
757
            return BAD_VALUE;
758 759 760
        } else if (!mSlots[slot].mRequestBufferCalled) {
            BQ_LOGE("queueBuffer: slot %d was queued without requesting "
                    "a buffer", slot);
761
            return BAD_VALUE;
762 763
        }

764
        // If shared buffer mode has just been enabled, cache the slot of the
765
        // first buffer that is queued and mark it as the shared buffer.
766
        if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
767
                BufferQueueCore::INVALID_BUFFER_SLOT) {
768
            mCore->mSharedBufferSlot = slot;
769 770 771
            mSlots[slot].mBufferState.mShared = true;
        }

772
        BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d"
773
                " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
774
                slot, mCore->mFrameCounter + 1, timestamp, dataSpace,
775 776
                crop.left, crop.top, crop.right, crop.bottom, transform,
                BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
777 778 779

        const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
        Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
780
        Rect croppedRect(Rect::EMPTY_RECT);
781 782 783 784
        crop.intersect(bufferRect, &croppedRect);
        if (croppedRect != crop) {
            BQ_LOGE("queueBuffer: crop rect is not contained within the "
                    "buffer in slot %d", slot);
785
            return BAD_VALUE;
786 787
        }

788 789 790 791 792
        // Override UNKNOWN dataspace with consumer default
        if (dataSpace == HAL_DATASPACE_UNKNOWN) {
            dataSpace = mCore->mDefaultBufferDataSpace;
        }

793
        mSlots[slot].mFence = fence;
794 795
        mSlots[slot].mBufferState.queue();

796 797 798 799 800 801
        ++mCore->mFrameCounter;
        mSlots[slot].mFrameNumber = mCore->mFrameCounter;

        item.mAcquireCalled = mSlots[slot].mAcquireCalled;
        item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
        item.mCrop = crop;
802 803
        item.mTransform = transform &
                ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
804
        item.mTransformToDisplayInverse =
805 806
                (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
        item.mScalingMode = static_cast<uint32_t>(scalingMode);
807 808
        item.mTimestamp = timestamp;
        item.mIsAutoTimestamp = isAutoTimestamp;
809
        item.mDataSpace = dataSpace;
810 811 812
        item.mFrameNumber = mCore->mFrameCounter;
        item.mSlot = slot;
        item.mFence = fence;
813
        item.mIsDroppable = mCore->mAsyncMode ||
814
                mCore->mDequeueBufferCannotBlock ||
815
                (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == slot);
816
        item.mSurfaceDamage = surfaceDamage;
817
        item.mQueuedBuffer = true;
818
        item.mAutoRefresh = mCore->mSharedBufferMode && mCore->mAutoRefresh;
819

820 821
        mStickyTransform = stickyTransform;

822
        // Cache the shared buffer data so that the BufferItem can be recreated.
823 824 825 826
        if (mCore->mSharedBufferMode) {
            mCore->mSharedBufferCache.crop = crop;
            mCore->mSharedBufferCache.transform = transform;
            mCore->mSharedBufferCache.scalingMode = static_cast<uint32_t>(
827
                    scalingMode);
828
            mCore->mSharedBufferCache.dataspace = dataSpace;
829 830
        }

831 832 833 834
        if (mCore->mQueue.empty()) {
            // When the queue is empty, we can ignore mDequeueBufferCannotBlock
            // and simply queue this buffer
            mCore->mQueue.push_back(item);
835
            frameAvailableListener = mCore->mConsumerListener;
836 837 838 839 840
        } else {
            // When the queue is not empty, we need to look at the front buffer
            // state to see if we need to replace it
            BufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());
            if (front->mIsDroppable) {
841 842

                if (!front->mIsStale) {
843 844
                    mSlots[front->mSlot].mBufferState.freeQueued();

845
                    // After leaving shared buffer mode, the shared buffer will
846 847
                    // still be around. Mark it as no longer shared if this
                    // operation causes it to be free.
848
                    if (!mCore->mSharedBufferMode &&
849 850 851 852 853
                            mSlots[front->mSlot].mBufferState.isFree()) {
                        mSlots[front->mSlot].mBufferState.mShared = false;
                    }
                    // Don't put the shared buffer on the free list.
                    if (!mSlots[front->mSlot].mBufferState.isShared()) {
854 855
                        mCore->mActiveBuffers.erase(front->mSlot);
                        mCore->mFreeBuffers.push_back(front->mSlot);
856
                    }
857
                }
858

859 860
                // Overwrite the droppable buffer with the incoming one
                *front = item;
861
                frameReplacedListener = mCore->mConsumerListener;
862 863
            } else {
                mCore->mQueue.push_back(item);
864
                frameAvailableListener = mCore->mConsumerListener;
865 866 867 868 869 870 871
            }
        }

        mCore->mBufferHasBeenQueued = true;
        mCore->mDequeueCondition.broadcast();

        output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
872 873
                mCore->mTransformHint,
                static_cast<uint32_t>(mCore->mQueue.size()));
874 875

        ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
876 877 878

        // Take a ticket for the callback functions
        callbackTicket = mNextCallbackTicket++;
879

880
        VALIDATE_CONSISTENCY();
881 882
    } // Autolock scope

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    // Don't send the GraphicBuffer through the callback, and don't send
    // the slot number, since the consumer shouldn't need it
    item.mGraphicBuffer.clear();
    item.mSlot = BufferItem::INVALID_BUFFER_SLOT;

    // Call back without the main BufferQueue lock held, but with the callback
    // lock held so we can ensure that callbacks occur in order
    {
        Mutex::Autolock lock(mCallbackMutex);
        while (callbackTicket != mCurrentCallbackTicket) {
            mCallbackCondition.wait(mCallbackMutex);
        }

        if (frameAvailableListener != NULL) {
            frameAvailableListener->onFrameAvailable(item);
        } else if (frameReplacedListener != NULL) {
            frameReplacedListener->onFrameReplaced(item);
        }

        ++mCurrentCallbackTicket;
        mCallbackCondition.broadcast();
904 905
    }

906 907 908 909 910 911 912 913 914
    // Wait without lock held
    if (mCore->mConnectedApi == NATIVE_WINDOW_API_EGL) {
        // Waiting here allows for two full buffers to be queued but not a
        // third. In the event that frames take varying time, this makes a
        // small trade-off in favor of latency rather than throughput.
        mLastQueueBufferFence->waitForever("Throttling EGL Production");
        mLastQueueBufferFence = fence;
    }

915 916 917
    return NO_ERROR;
}

918
status_t BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
919 920 921 922 923 924
    ATRACE_CALL();
    BQ_LOGV("cancelBuffer: slot %d", slot);
    Mutex::Autolock lock(mCore->mMutex);

    if (mCore->mIsAbandoned) {
        BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
925 926 927 928 929 930
        return NO_INIT;
    }

    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
        BQ_LOGE("cancelBuffer: BufferQueue has no connected producer");
        return NO_INIT;
931 932
    }

933 934
    if (mCore->mSharedBufferMode) {
        BQ_LOGE("cancelBuffer: cannot cancel a buffer in shared buffer mode");
935 936 937
        return BAD_VALUE;
    }

938
    if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
939
        BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)",
940
                slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
941
        return BAD_VALUE;
942
    } else if (!mSlots[slot].mBufferState.isDequeued()) {
943
        BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
944
                "(state = %s)", slot, mSlots[slot].mBufferState.string());
945
        return BAD_VALUE;
946 947
    } else if (fence == NULL) {
        BQ_LOGE("cancelBuffer: fence is NULL");
948
        return BAD_VALUE;
949 950
    }

951 952
    mSlots[slot].mBufferState.cancel();

953
    // After leaving shared buffer mode, the shared buffer will still be around.
954
    // Mark it as no longer shared if this operation causes it to be free.
955
    if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) {
956 957 958 959 960
        mSlots[slot].mBufferState.mShared = false;
    }

    // Don't put the shared buffer on the free list.
    if (!mSlots[slot].mBufferState.isShared()) {
961 962
        mCore->mActiveBuffers.erase(slot);
        mCore->mFreeBuffers.push_back(slot);
963
    }
964

965 966
    mSlots[slot].mFence = fence;
    mCore->mDequeueCondition.broadcast();
967
    VALIDATE_CONSISTENCY();
968 969

    return NO_ERROR;
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
}

int BufferQueueProducer::query(int what, int *outValue) {
    ATRACE_CALL();
    Mutex::Autolock lock(mCore->mMutex);

    if (outValue == NULL) {
        BQ_LOGE("query: outValue was NULL");
        return BAD_VALUE;
    }

    if (mCore->mIsAbandoned) {
        BQ_LOGE("query: BufferQueue has been abandoned");
        return NO_INIT;
    }

    int value;
    switch (what) {
        case NATIVE_WINDOW_WIDTH:
989
            value = static_cast<int32_t>(mCore->mDefaultWidth);
990 991
            break;
        case NATIVE_WINDOW_HEIGHT:
992
            value = static_cast<int32_t>(mCore->mDefaultHeight);
993 994
            break;
        case NATIVE_WINDOW_FORMAT:
995
            value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
996 997
            break;
        case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
998
            value = mCore->getMinUndequeuedBufferCountLocked();
999
            break;
1000
        case NATIVE_WINDOW_STICKY_TRANSFORM:
1001
            value = static_cast<int32_t>(mStickyTransform);
1002
            break;
1003 1004 1005 1006
        case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
            value = (mCore->mQueue.size() > 1);
            break;
        case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
1007
            value = static_cast<int32_t>(mCore->mConsumerUsageBits);
1008
            break;
1009 1010 1011
        case NATIVE_WINDOW_DEFAULT_DATASPACE:
            value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace);
            break;
1012 1013 1014 1015 1016 1017 1018
        case NATIVE_WINDOW_BUFFER_AGE:
            if (mCore->mBufferAge > INT32_MAX) {
                value = 0;
            } else {
                value = static_cast<int32_t>(mCore->mBufferAge);
            }
            break;
1019 1020 1021 1022 1023 1024 1025 1026 1027
        default:
            return BAD_VALUE;
    }

    BQ_LOGV("query: %d? %d", what, value);
    *outValue = value;
    return NO_ERROR;
}

1028
status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
1029 1030
        int api, bool producerControlledByApp, QueueBufferOutput *output) {
    ATRACE_CALL();
1031 1032 1033 1034
    Mutex::Autolock lock(mCore->mMutex);
    mConsumerName = mCore->mConsumerName;
    BQ_LOGV("connect: api=%d producerControlledByApp=%s", api,
            producerControlledByApp ? "true" : "false");
1035

1036 1037 1038 1039
    if (mCore->mIsAbandoned) {
        BQ_LOGE("connect: BufferQueue has been abandoned");
        return NO_INIT;
    }
1040

1041 1042 1043 1044
    if (mCore->mConsumerListener == NULL) {
        BQ_LOGE("connect: BufferQueue has no consumer");
        return NO_INIT;
    }
1045

1046 1047 1048 1049
    if (output == NULL) {
        BQ_LOGE("connect: output was NULL");
        return BAD_VALUE;
    }
1050

1051 1052 1053 1054 1055
    if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
        BQ_LOGE("connect: already connected (cur=%d req=%d)",
                mCore->mConnectedApi, api);
        return BAD_VALUE;
    }
1056

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode,
            mDequeueTimeout < 0 ?
            mCore->mConsumerControlledByApp && producerControlledByApp : false,
            mCore->mMaxBufferCount) -
            mCore->getMaxBufferCountLocked();
    if (!mCore->adjustAvailableSlotsLocked(delta)) {
        BQ_LOGE("connect: BufferQueue failed to adjust the number of available "
                "slots. Delta = %d", delta);
        return BAD_VALUE;
    }
Pablo Ceballos's avatar
Pablo Ceballos committed
1067

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    int status = NO_ERROR;
    switch (api) {
        case NATIVE_WINDOW_API_EGL:
        case NATIVE_WINDOW_API_CPU:
        case NATIVE_WINDOW_API_MEDIA:
        case NATIVE_WINDOW_API_CAMERA:
            mCore->mConnectedApi = api;
            output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
                    mCore->mTransformHint,
                    static_cast<uint32_t>(mCore->mQueue.size()));

            // Set up a death notification so that we can disconnect
            // automatically if the remote producer dies
            if (listener != NULL &&
                    IInterface::asBinder(listener)->remoteBinder() != NULL) {
                status = IInterface::asBinder(listener)->linkToDeath(
                        static_cast<IBinder::DeathRecipient*>(this));
                if (status != NO_ERROR) {
                    BQ_LOGE("connect: linkToDeath failed: %s (%d)",
                            strerror(-status), status);
1088
                }
1089 1090 1091 1092 1093 1094 1095
            }
            mCore->mConnectedProducerListener = listener;
            break;
        default:
            BQ_LOGE("connect: unknown API %d", api);
            status = BAD_VALUE;
            break;
1096 1097
    }

1098 1099 1100 1101 1102
    mCore->mBufferHasBeenQueued = false;
    mCore->mDequeueBufferCannotBlock = false;
    if (mDequeueTimeout < 0) {
        mCore->mDequeueBufferCannotBlock =
                mCore->mConsumerControlledByApp && producerControlledByApp;
1103
    }
1104

1105 1106
    mCore->mAllowAllocation = true;
    VALIDATE_CONSISTENCY();
1107 1108 1109 1110 1111
    return status;
}

status_t BufferQueueProducer::disconnect(int api) {
    ATRACE_CALL();
1112
    BQ_LOGV("disconnect: api %d", api);
1113 1114 1115 1116 1117

    int status = NO_ERROR;
    sp<IConsumerListener> listener;
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
1118
        mCore->waitWhileAllocatingLocked();
1119 1120 1121 1122 1123 1124 1125

        if (mCore->mIsAbandoned) {
            // It's not really an error to disconnect after the surface has
            // been abandoned; it should just be a no-op.
            return NO_ERROR;
        }

1126 1127
        if (api == BufferQueueCore::CURRENTLY_CONNECTED_API) {
            api = mCore->mConnectedApi;
1128 1129 1130 1131 1132
            // If we're asked to disconnect the currently connected api but
            // nobody is connected, it's not really an error.
            if (api == BufferQueueCore::NO_CONNECTED_API) {
                return NO_ERROR;
            }
1133 1134
        }

1135 1136 1137 1138 1139 1140 1141 1142 1143
        switch (api) {
            case NATIVE_WINDOW_API_EGL:
            case NATIVE_WINDOW_API_CPU:
            case NATIVE_WINDOW_API_MEDIA:
            case NATIVE_WINDOW_API_CAMERA:
                if (mCore->mConnectedApi == api) {
                    mCore->freeAllBuffersLocked();

                    // Remove our death notification callback if we have one
1144 1145
                    if (mCore->mConnectedProducerListener != NULL) {
                        sp<IBinder> token =
1146
                                IInterface::asBinder(mCore->mConnectedProducerListener);
1147 1148 1149 1150 1151
                        // This can fail if we're here because of the death
                        // notification, but we just ignore it
                        token->unlinkToDeath(
                                static_cast<IBinder::DeathRecipient*>(this));
                    }
1152
                    mCore->mSharedBufferSlot =
1153
                            BufferQueueCore::INVALID_BUFFER_SLOT;
1154
                    mCore->mConnectedProducerListener = NULL;
1155
                    mCore->mConnectedApi = BufferQueueCore::NO_CONNECTED_API;
1156
                    mCore->mSidebandStream.clear();
1157 1158
                    mCore->mDequeueCondition.broadcast();
                    listener = mCore->mConsumerListener;
1159
                } else if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
1160
                    BQ_LOGE("disconnect: still connected to another API "
1161
                            "(cur=%d req=%d)", mCore->mConnectedApi, api);
1162
                    status = BAD_VALUE;
1163 1164 1165
                }
                break;
            default:
1166
                BQ_LOGE("disconnect: unknown API %d", api);
1167
                status = BAD_VALUE;
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
                break;
        }
    } // Autolock scope

    // Call back without lock held
    if (listener != NULL) {
        listener->onBuffersReleased();
    }

    return status;
}

1180
status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
Wonsik Kim's avatar
Wonsik Kim committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    sp<IConsumerListener> listener;
    { // Autolock scope
        Mutex::Autolock _l(mCore->mMutex);
        mCore->mSidebandStream = stream;
        listener = mCore->mConsumerListener;
    } // Autolock scope

    if (listener != NULL) {
        listener->onSidebandStreamChanged();
    }
1191 1192 1193
    return NO_ERROR;
}

1194 1195
void BufferQueueProducer::allocateBuffers(uint32_t width, uint32_t height,
        PixelFormat format, uint32_t usage) {
1196 1197 1198 1199 1200
    ATRACE_CALL();
    while (true) {
        size_t newBufferCount = 0;
        uint32_t allocWidth = 0;
        uint32_t allocHeight = 0;
1201
        PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
1202 1203 1204 1205
        uint32_t allocUsage = 0;
        { // Autolock scope
            Mutex::Autolock lock(mCore->mMutex);
            mCore->waitWhileAllocatingLocked();
1206

1207 1208 1209 1210 1211 1212
            if (!mCore->mAllowAllocation) {
                BQ_LOGE("allocateBuffers: allocation is not allowed for this "
                        "BufferQueue");
                return;
            }

1213 1214
            newBufferCount = mCore->mFreeSlots.size();
            if (newBufferCount == 0) {
1215 1216
                return;
            }
1217

1218 1219 1220 1221
            allocWidth = width > 0 ? width : mCore->mDefaultWidth;
            allocHeight = height > 0 ? height : mCore->mDefaultHeight;
            allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
            allocUsage = usage | mCore->mConsumerUsageBits;
1222

1223 1224 1225
            mCore->mIsAllocating = true;
        } // Autolock scope

1226
        Vector<sp<GraphicBuffer>> buffers;
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        for (size_t i = 0; i <  newBufferCount; ++i) {
            status_t result = NO_ERROR;
            sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
                    allocWidth, allocHeight, allocFormat, allocUsage, &result));
            if (result != NO_ERROR) {
                BQ_LOGE("allocateBuffers: failed to allocate buffer (%u x %u, format"
                        " %u, usage %u)", width, height, format, usage);
                Mutex::Autolock lock(mCore->mMutex);
                mCore->mIsAllocating = false;
                mCore->mIsAllocatingCondition.broadcast();
                return;
            }
            buffers.push_back(graphicBuffer);
1240 1241
        }

1242 1243 1244 1245
        { // Autolock scope
            Mutex::Autolock lock(mCore->mMutex);
            uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
            uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
1246 1247
            PixelFormat checkFormat = format != 0 ?
                    format : mCore->mDefaultBufferFormat;
1248 1249 1250 1251 1252 1253 1254 1255 1256
            uint32_t checkUsage = usage | mCore->mConsumerUsageBits;
            if (checkWidth != allocWidth || checkHeight != allocHeight ||
                checkFormat != allocFormat || checkUsage != allocUsage) {
                // Something changed while we released the lock. Retry.
                BQ_LOGV("allocateBuffers: size/format/usage changed while allocating. Retrying.");
                mCore->mIsAllocating = false;
                mCore->mIsAllocatingCondition.broadcast();
                continue;
            }
1257

1258
            for (size_t i = 0; i < newBufferCount; ++i) {
1259 1260 1261
                if (mCore->mFreeSlots.empty()) {
                    BQ_LOGV("allocateBuffers: a slot was occupied while "
                            "allocating. Dropping allocated buffer.");
1262 1263
                    continue;
                }
1264 1265 1266 1267
                auto slot = mCore->mFreeSlots.begin();
                mCore->clearBufferSlotLocked(*slot); // Clean up the slot first
                mSlots[*slot].mGraphicBuffer = buffers[i];
                mSlots[*slot].mFence = Fence::NO_FENCE;
1268 1269 1270 1271

                // freeBufferLocked puts this slot on the free slots list. Since
                // we then attached a buffer, move the slot to free buffer list.
                mCore->mFreeSlots.erase(slot);
1272
                mCore->mFreeBuffers.push_front(*slot);
1273

1274 1275
                BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d",
                        *slot);
1276
            }
1277

1278 1279
            mCore->mIsAllocating = false;
            mCore->mIsAllocatingCondition.broadcast();
1280
            VALIDATE_CONSISTENCY();
1281
        } // Autolock scope
1282 1283 1284
    }
}

1285 1286 1287 1288 1289 1290 1291 1292 1293
status_t BufferQueueProducer::allowAllocation(bool allow) {
    ATRACE_CALL();
    BQ_LOGV("allowAllocation: %s", allow ? "true" : "false");

    Mutex::Autolock lock(mCore->mMutex);
    mCore->mAllowAllocation = allow;
    return NO_ERROR;
}

1294 1295 1296 1297 1298 1299 1300 1301 1302
status_t BufferQueueProducer::setGenerationNumber(uint32_t generationNumber) {
    ATRACE_CALL();
    BQ_LOGV("setGenerationNumber: %u", generationNumber);

    Mutex::Autolock lock(mCore->mMutex);
    mCore->mGenerationNumber = generationNumber;
    return NO_ERROR;
}

1303 1304 1305 1306 1307 1308
String8 BufferQueueProducer::getConsumerName() const {
    ATRACE_CALL();
    BQ_LOGV("getConsumerName: %s", mConsumerName.string());
    return mConsumerName;
}

1309 1310 1311 1312 1313 1314 1315 1316
uint64_t BufferQueueProducer::getNextFrameNumber() const {
    ATRACE_CALL();

    Mutex::Autolock lock(mCore->mMutex);
    uint64_t nextFrameNumber = mCore->mFrameCounter + 1;
    return nextFrameNumber;
}

1317
status_t BufferQueueProducer::setSharedBufferMode(bool sharedBufferMode) {
1318
    ATRACE_CALL();
1319
    BQ_LOGV("setSharedBufferMode: %d", sharedBufferMode);
1320 1321

    Mutex::Autolock lock(mCore->mMutex);
1322 1323
    if (!sharedBufferMode) {
        mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT;
1324
    }
1325
    mCore->mSharedBufferMode = sharedBufferMode;
1326 1327 1328
    return NO_ERROR;
}

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
status_t BufferQueueProducer::setAutoRefresh(bool autoRefresh) {
    ATRACE_CALL();
    BQ_LOGV("setAutoRefresh: %d", autoRefresh);

    Mutex::Autolock lock(mCore->mMutex);

    mCore->mAutoRefresh = autoRefresh;
    return NO_ERROR;
}

1339 1340 1341
status_t BufferQueueProducer::setDequeueTimeout(nsecs_t timeout) {
    ATRACE_CALL();
    BQ_LOGV("setDequeueTimeout: %" PRId64, timeout);
1342

1343 1344 1345 1346 1347 1348 1349
    Mutex::Autolock lock(mCore->mMutex);
    int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode, false,
            mCore->mMaxBufferCount) - mCore->getMaxBufferCountLocked();
    if (!mCore->adjustAvailableSlotsLocked(delta)) {
        BQ_LOGE("setDequeueTimeout: BufferQueue failed to adjust the number of "
                "available slots. Delta = %d", delta);
        return BAD_VALUE;
1350 1351
    }

1352 1353
    mDequeueTimeout = timeout;
    mCore->mDequeueBufferCannotBlock = false;
1354

1355
    VALIDATE_CONSISTENCY();
1356 1357 1358
    return NO_ERROR;
}

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
void BufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
    // If we're here, it means that a producer we were connected to died.
    // We're guaranteed that we are still connected to it because we remove
    // this callback upon disconnect. It's therefore safe to read mConnectedApi
    // without synchronization here.
    int api = mCore->mConnectedApi;
    disconnect(api);
}

} // namespace android