BufferQueueProducer.cpp 49 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;
        }

104 105 106 107
        if (maxDequeuedBuffers == mCore->mMaxDequeuedBufferCount) {
            return NO_ERROR;
        }

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

123
        int bufferCount = mCore->getMinUndequeuedBufferCountLocked();
124 125 126 127 128 129 130 131
        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;
        }

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

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

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

    // Call back without lock held
161 162
    if (listener != NULL) {
        listener->onBuffersReleased();
163 164 165 166 167 168 169 170 171
    }

    return NO_ERROR;
}

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

172
    sp<IConsumerListener> listener;
173 174 175 176 177 178 179 180 181
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
        mCore->waitWhileAllocatingLocked();

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

182 183 184 185
        if (async == mCore->mAsyncMode) {
            return NO_ERROR;
        }

186
        if ((mCore->mMaxAcquiredBufferCount + mCore->mMaxDequeuedBufferCount +
187 188
                (async || mCore->mDequeueBufferCannotBlock ? 1 : 0)) >
                mCore->mMaxBufferCount) {
189 190
            BQ_LOGE("setAsyncMode(%d): this call would cause the "
                    "maxBufferCount (%d) to be exceeded (maxAcquired %d "
191 192 193 194
                    "maxDequeued %d mDequeueBufferCannotBlock %d)", async,
                    mCore->mMaxBufferCount, mCore->mMaxAcquiredBufferCount,
                    mCore->mMaxDequeuedBufferCount,
                    mCore->mDequeueBufferCannotBlock);
195 196 197
            return BAD_VALUE;
        }

198 199 200 201
        int delta = mCore->getMaxBufferCountLocked(async,
                mCore->mDequeueBufferCannotBlock, mCore->mMaxBufferCount)
                - mCore->getMaxBufferCountLocked();

202
        if (!mCore->adjustAvailableSlotsLocked(delta)) {
203 204 205 206
            BQ_LOGE("setAsyncMode: BufferQueue failed to adjust the number of "
                    "available slots. Delta = %d", delta);
            return BAD_VALUE;
        }
207
        mCore->mAsyncMode = async;
208
        VALIDATE_CONSISTENCY();
209
        mCore->mDequeueCondition.broadcast();
210 211 212
        if (delta < 0) {
            listener = mCore->mConsumerListener;
        }
213 214 215
    } // Autolock scope

    // Call back without lock held
216 217
    if (listener != NULL) {
        listener->onBuffersReleased();
218 219 220 221
    }
    return NO_ERROR;
}

222 223 224 225
int BufferQueueProducer::getFreeBufferLocked() const {
    if (mCore->mFreeBuffers.empty()) {
        return BufferQueueCore::INVALID_BUFFER_SLOT;
    }
226
    int slot = mCore->mFreeBuffers.front();
227 228 229 230
    mCore->mFreeBuffers.pop_front();
    return slot;
}

231
int BufferQueueProducer::getFreeSlotLocked() const {
232 233 234
    if (mCore->mFreeSlots.empty()) {
        return BufferQueueCore::INVALID_BUFFER_SLOT;
    }
Pablo Ceballos's avatar
Pablo Ceballos committed
235
    int slot = *(mCore->mFreeSlots.begin());
236
    mCore->mFreeSlots.erase(slot);
Pablo Ceballos's avatar
Pablo Ceballos committed
237
    return slot;
238 239 240
}

status_t BufferQueueProducer::waitForFreeSlotThenRelock(FreeSlotCaller caller,
241
        int* found) const {
242 243
    auto callerString = (caller == FreeSlotCaller::Dequeue) ?
            "dequeueBuffer" : "attachBuffer";
244 245 246
    bool tryAgain = true;
    while (tryAgain) {
        if (mCore->mIsAbandoned) {
247
            BQ_LOGE("%s: BufferQueue has been abandoned", callerString);
248 249 250 251 252
            return NO_INIT;
        }

        int dequeuedCount = 0;
        int acquiredCount = 0;
253
        for (int s : mCore->mActiveBuffers) {
254 255 256 257 258
            if (mSlots[s].mBufferState.isDequeued()) {
                ++dequeuedCount;
            }
            if (mSlots[s].mBufferState.isAcquired()) {
                ++acquiredCount;
259 260 261
            }
        }

262 263 264 265 266 267
        // 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 "
268
                    "(%d)", callerString, mCore->mMaxDequeuedBufferCount);
269 270 271
            return INVALID_OPERATION;
        }

272 273
        *found = BufferQueueCore::INVALID_BUFFER_SLOT;

274 275 276 277
        // 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.
278
        const int maxBufferCount = mCore->getMaxBufferCountLocked();
279 280
        bool tooManyBuffers = mCore->mQueue.size()
                            > static_cast<size_t>(maxBufferCount);
281
        if (tooManyBuffers) {
282
            BQ_LOGV("%s: queue size is %zu, waiting", callerString,
283
                    mCore->mQueue.size());
284
        } else {
285
            // If in shared buffer mode and a shared buffer exists, always
286
            // return it.
287
            if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot !=
288
                    BufferQueueCore::INVALID_BUFFER_SLOT) {
289
                *found = mCore->mSharedBufferSlot;
290 291 292
            } else {
                if (caller == FreeSlotCaller::Dequeue) {
                    // If we're calling this from dequeue, prefer free buffers
293
                    int slot = getFreeBufferLocked();
294 295 296
                    if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
                        *found = slot;
                    } else if (mCore->mAllowAllocation) {
297
                        *found = getFreeSlotLocked();
298 299 300
                    }
                } else {
                    // If we're calling this from attach, prefer free slots
301
                    int slot = getFreeSlotLocked();
302 303 304 305 306
                    if (slot != BufferQueueCore::INVALID_BUFFER_SLOT) {
                        *found = slot;
                    } else {
                        *found = getFreeBufferLocked();
                    }
307 308
                }
            }
309 310 311 312 313 314 315
        }

        // 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;
316 317 318 319 320 321 322
        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())
323
            if ((mCore->mDequeueBufferCannotBlock || mCore->mAsyncMode) &&
324 325 326
                    (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
                return WOULD_BLOCK;
            }
327 328 329 330 331 332 333 334 335
            if (mDequeueTimeout >= 0) {
                status_t result = mCore->mDequeueCondition.waitRelative(
                        mCore->mMutex, mDequeueTimeout);
                if (result == TIMED_OUT) {
                    return result;
                }
            } else {
                mCore->mDequeueCondition.wait(mCore->mMutex);
            }
336 337 338 339 340 341
        }
    } // while (tryAgain)

    return NO_ERROR;
}

342
status_t BufferQueueProducer::dequeueBuffer(int *outSlot,
343 344
        sp<android::Fence> *outFence, uint32_t width, uint32_t height,
        PixelFormat format, uint32_t usage) {
345 346 347 348
    ATRACE_CALL();
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
        mConsumerName = mCore->mConsumerName;
349 350 351 352 353 354 355 356 357 358

        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;
        }
359 360
    } // Autolock scope

361 362
    BQ_LOGV("dequeueBuffer: w=%u h=%u format=%#x, usage=%#x", width, height,
            format, usage);
363 364 365 366 367 368 369 370 371

    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;
372
    bool attachedByConsumer = false;
373 374 375

    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
376
        mCore->waitWhileAllocatingLocked();
377 378 379 380 381 382 383 384

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

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

385 386 387 388
        const bool useDefaultSize = !width && !height;
        if (useDefaultSize) {
            width = mCore->mDefaultWidth;
            height = mCore->mDefaultHeight;
389
        }
390

391
        int found = BufferItem::INVALID_BUFFER_SLOT;
392
        while (found == BufferItem::INVALID_BUFFER_SLOT) {
393
            status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Dequeue,
394
                    &found);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
            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)) {
413
                    if (mCore->mSharedBufferSlot == found) {
414 415 416 417
                        BQ_LOGE("dequeueBuffer: cannot re-allocate a shared"
                                "buffer");
                        return BAD_VALUE;
                    }
418 419
                    mCore->mFreeSlots.insert(found);
                    mCore->clearBufferSlotLocked(found);
420 421 422 423
                    found = BufferItem::INVALID_BUFFER_SLOT;
                    continue;
                }
            }
424 425
        }

426
        const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
427
        if (mCore->mSharedBufferSlot == found &&
428 429 430 431 432 433 434
                buffer->needsReallocation(width,  height, format, usage)) {
            BQ_LOGE("dequeueBuffer: cannot re-allocate a shared"
                    "buffer");

            return BAD_VALUE;
        }

435
        if (mCore->mSharedBufferSlot != found) {
436 437
            mCore->mActiveBuffers.insert(found);
        }
438 439 440
        *outSlot = found;
        ATRACE_BUFFER_INDEX(found);

441 442
        attachedByConsumer = mSlots[found].mNeedsReallocation;
        mSlots[found].mNeedsReallocation = false;
443

444 445
        mSlots[found].mBufferState.dequeue();

446
        // If shared buffer mode has just been enabled, cache the slot of the
447
        // first buffer that is dequeued and mark it as the shared buffer.
448
        if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
449
                BufferQueueCore::INVALID_BUFFER_SLOT) {
450
            mCore->mSharedBufferSlot = found;
451 452
            mSlots[found].mBufferState.mShared = true;
        }
453 454

        if ((buffer == NULL) ||
455
                buffer->needsReallocation(width, height, format, usage))
456 457 458 459 460 461 462
        {
            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;
463
            mCore->mBufferAge = 0;
464
            mCore->mIsAllocating = true;
465 466

            returnFlags |= BUFFER_NEEDS_REALLOCATION;
467 468 469 470 471
        } else {
            // We add 1 because that will be the frame number when this buffer
            // is queued
            mCore->mBufferAge =
                    mCore->mFrameCounter + 1 - mSlots[found].mFrameNumber;
472 473
        }

474 475
        BQ_LOGV("dequeueBuffer: setting buffer age to %" PRIu64,
                mCore->mBufferAge);
476

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
        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;
492
        BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
493
        sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
494
                width, height, format, usage, &error));
495 496 497
        { // Autolock scope
            Mutex::Autolock lock(mCore->mMutex);

498 499 500 501 502 503 504 505 506 507 508 509 510
            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;
            }

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

516
            VALIDATE_CONSISTENCY();
517 518 519
        } // Autolock scope
    }

520 521 522 523
    if (attachedByConsumer) {
        returnFlags |= BUFFER_NEEDS_REALLOCATION;
    }

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    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);
    }

539 540
    BQ_LOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
            *outSlot,
541 542 543 544 545 546
            mSlots[*outSlot].mFrameNumber,
            mSlots[*outSlot].mGraphicBuffer->handle, returnFlags);

    return returnFlags;
}

547 548 549
status_t BufferQueueProducer::detachBuffer(int slot) {
    ATRACE_CALL();
    ATRACE_BUFFER_INDEX(slot);
550
    BQ_LOGV("detachBuffer: slot %d", slot);
551
    Mutex::Autolock lock(mCore->mMutex);
552

553 554 555 556
    if (mCore->mIsAbandoned) {
        BQ_LOGE("detachBuffer: BufferQueue has been abandoned");
        return NO_INIT;
    }
Pablo Ceballos's avatar
Pablo Ceballos committed
557

558 559 560
    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
        BQ_LOGE("detachBuffer: BufferQueue has no connected producer");
        return NO_INIT;
561 562
    }

563 564
    if (mCore->mSharedBufferMode || mCore->mSharedBufferSlot == slot) {
        BQ_LOGE("detachBuffer: cannot detach a buffer in shared buffer mode");
565
        return BAD_VALUE;
Pablo Ceballos's avatar
Pablo Ceballos committed
566
    }
567 568 569 570 571 572 573 574 575 576 577 578 579

    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
580
    }
581

582 583 584 585 586 587 588
    mSlots[slot].mBufferState.detachProducer();
    mCore->mActiveBuffers.erase(slot);
    mCore->mFreeSlots.insert(slot);
    mCore->clearBufferSlotLocked(slot);
    mCore->mDequeueCondition.broadcast();
    VALIDATE_CONSISTENCY();

589 590 591
    return NO_ERROR;
}

592 593 594 595 596 597 598 599 600 601 602 603
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;
    }

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

606 607 608 609
    if (mCore->mIsAbandoned) {
        BQ_LOGE("detachNextBuffer: BufferQueue has been abandoned");
        return NO_INIT;
    }
610

611 612 613 614
    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
        BQ_LOGE("detachNextBuffer: BufferQueue has no connected producer");
        return NO_INIT;
    }
615

616 617 618
    if (mCore->mSharedBufferMode) {
        BQ_LOGE("detachNextBuffer: cannot detach a buffer in shared buffer "
            "mode");
619 620
        return BAD_VALUE;
    }
621

622
    mCore->waitWhileAllocatingLocked();
623

624 625 626
    if (mCore->mFreeBuffers.empty()) {
        return NO_MEMORY;
    }
627

628 629 630
    int found = mCore->mFreeBuffers.front();
    mCore->mFreeBuffers.remove(found);
    mCore->mFreeSlots.insert(found);
631

632
    BQ_LOGV("detachNextBuffer detached slot %d", found);
633

634 635 636 637
    *outBuffer = mSlots[found].mGraphicBuffer;
    *outFence = mSlots[found].mFence;
    mCore->clearBufferSlotLocked(found);
    VALIDATE_CONSISTENCY();
638 639 640 641

    return NO_ERROR;
}

642 643 644 645 646
status_t BufferQueueProducer::attachBuffer(int* outSlot,
        const sp<android::GraphicBuffer>& buffer) {
    ATRACE_CALL();

    if (outSlot == NULL) {
647
        BQ_LOGE("attachBuffer: outSlot must not be NULL");
648 649
        return BAD_VALUE;
    } else if (buffer == NULL) {
650
        BQ_LOGE("attachBuffer: cannot attach NULL buffer");
651 652 653 654
        return BAD_VALUE;
    }

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

    if (mCore->mIsAbandoned) {
657
        BQ_LOGE("attachBuffer: BufferQueue has been abandoned");
658 659 660 661
        return NO_INIT;
    }

    if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
662
        BQ_LOGE("attachBuffer: BufferQueue has no connected producer");
663 664
        return NO_INIT;
    }
665

666 667
    if (mCore->mSharedBufferMode) {
        BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode");
668 669 670
        return BAD_VALUE;
    }

671 672 673 674 675 676 677
    if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
        BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
                "[queue %u]", buffer->getGenerationNumber(),
                mCore->mGenerationNumber);
        return BAD_VALUE;
    }

678 679
    mCore->waitWhileAllocatingLocked();

680 681
    status_t returnFlags = NO_ERROR;
    int found;
682
    status_t status = waitForFreeSlotThenRelock(FreeSlotCaller::Attach, &found);
683 684 685 686 687 688
    if (status != NO_ERROR) {
        return status;
    }

    // This should not happen
    if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
689
        BQ_LOGE("attachBuffer: no available buffer slots");
690 691 692 693 694
        return -EBUSY;
    }

    *outSlot = found;
    ATRACE_BUFFER_INDEX(*outSlot);
695
    BQ_LOGV("attachBuffer: returning slot %d flags=%#x",
696 697 698
            *outSlot, returnFlags);

    mSlots[*outSlot].mGraphicBuffer = buffer;
699
    mSlots[*outSlot].mBufferState.attachProducer();
700 701
    mSlots[*outSlot].mEglFence = EGL_NO_SYNC_KHR;
    mSlots[*outSlot].mFence = Fence::NO_FENCE;
702
    mSlots[*outSlot].mRequestBufferCalled = true;
703 704
    mSlots[*outSlot].mAcquireCalled = false;
    mCore->mActiveBuffers.insert(found);
705
    VALIDATE_CONSISTENCY();
706

707 708 709
    return returnFlags;
}

710 711 712 713 714 715 716
status_t BufferQueueProducer::queueBuffer(int slot,
        const QueueBufferInput &input, QueueBufferOutput *output) {
    ATRACE_CALL();
    ATRACE_BUFFER_INDEX(slot);

    int64_t timestamp;
    bool isAutoTimestamp;
717
    android_dataspace dataSpace;
718
    Rect crop(Rect::EMPTY_RECT);
719 720
    int scalingMode;
    uint32_t transform;
721
    uint32_t stickyTransform;
722
    sp<Fence> fence;
723
    input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop, &scalingMode,
724
            &transform, &fence, &stickyTransform);
725
    Region surfaceDamage = input.getSurfaceDamage();
726 727 728

    if (fence == NULL) {
        BQ_LOGE("queueBuffer: fence is NULL");
729
        return BAD_VALUE;
730 731 732 733 734 735 736 737 738 739
    }

    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);
740
            return BAD_VALUE;
741 742
    }

743 744 745 746
    sp<IConsumerListener> frameAvailableListener;
    sp<IConsumerListener> frameReplacedListener;
    int callbackTicket = 0;
    BufferItem item;
747 748 749 750 751 752 753 754
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);

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

755 756 757 758 759
        if (mCore->mConnectedApi == BufferQueueCore::NO_CONNECTED_API) {
            BQ_LOGE("queueBuffer: BufferQueue has no connected producer");
            return NO_INIT;
        }

760
        if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
761
            BQ_LOGE("queueBuffer: slot index %d out of range [0, %d)",
762
                    slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
763
            return BAD_VALUE;
764
        } else if (!mSlots[slot].mBufferState.isDequeued()) {
765
            BQ_LOGE("queueBuffer: slot %d is not owned by the producer "
766
                    "(state = %s)", slot, mSlots[slot].mBufferState.string());
767
            return BAD_VALUE;
768 769 770
        } else if (!mSlots[slot].mRequestBufferCalled) {
            BQ_LOGE("queueBuffer: slot %d was queued without requesting "
                    "a buffer", slot);
771
            return BAD_VALUE;
772 773
        }

774
        // If shared buffer mode has just been enabled, cache the slot of the
775
        // first buffer that is queued and mark it as the shared buffer.
776
        if (mCore->mSharedBufferMode && mCore->mSharedBufferSlot ==
777
                BufferQueueCore::INVALID_BUFFER_SLOT) {
778
            mCore->mSharedBufferSlot = slot;
779 780 781
            mSlots[slot].mBufferState.mShared = true;
        }

782
        BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d"
783
                " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
784
                slot, mCore->mFrameCounter + 1, timestamp, dataSpace,
785 786
                crop.left, crop.top, crop.right, crop.bottom, transform,
                BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
787 788 789

        const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
        Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
790
        Rect croppedRect(Rect::EMPTY_RECT);
791 792 793 794
        crop.intersect(bufferRect, &croppedRect);
        if (croppedRect != crop) {
            BQ_LOGE("queueBuffer: crop rect is not contained within the "
                    "buffer in slot %d", slot);
795
            return BAD_VALUE;
796 797
        }

798 799 800 801 802
        // Override UNKNOWN dataspace with consumer default
        if (dataSpace == HAL_DATASPACE_UNKNOWN) {
            dataSpace = mCore->mDefaultBufferDataSpace;
        }

803
        mSlots[slot].mFence = fence;
804 805
        mSlots[slot].mBufferState.queue();

806 807 808 809 810 811
        ++mCore->mFrameCounter;
        mSlots[slot].mFrameNumber = mCore->mFrameCounter;

        item.mAcquireCalled = mSlots[slot].mAcquireCalled;
        item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
        item.mCrop = crop;
812 813
        item.mTransform = transform &
                ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
814
        item.mTransformToDisplayInverse =
815 816
                (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
        item.mScalingMode = static_cast<uint32_t>(scalingMode);
817 818
        item.mTimestamp = timestamp;
        item.mIsAutoTimestamp = isAutoTimestamp;
819
        item.mDataSpace = dataSpace;
820 821 822
        item.mFrameNumber = mCore->mFrameCounter;
        item.mSlot = slot;
        item.mFence = fence;
823
        item.mIsDroppable = mCore->mAsyncMode ||
824
                mCore->mDequeueBufferCannotBlock ||
825
                (mCore->mSharedBufferMode && mCore->mSharedBufferSlot == slot);
826
        item.mSurfaceDamage = surfaceDamage;
827
        item.mQueuedBuffer = true;
828
        item.mAutoRefresh = mCore->mSharedBufferMode && mCore->mAutoRefresh;
829

830 831
        mStickyTransform = stickyTransform;

832
        // Cache the shared buffer data so that the BufferItem can be recreated.
833 834 835 836
        if (mCore->mSharedBufferMode) {
            mCore->mSharedBufferCache.crop = crop;
            mCore->mSharedBufferCache.transform = transform;
            mCore->mSharedBufferCache.scalingMode = static_cast<uint32_t>(
837
                    scalingMode);
838
            mCore->mSharedBufferCache.dataspace = dataSpace;
839 840
        }

841 842 843 844
        if (mCore->mQueue.empty()) {
            // When the queue is empty, we can ignore mDequeueBufferCannotBlock
            // and simply queue this buffer
            mCore->mQueue.push_back(item);
845
            frameAvailableListener = mCore->mConsumerListener;
846 847 848 849 850
        } 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) {
851 852

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

855
                    // After leaving shared buffer mode, the shared buffer will
856 857
                    // still be around. Mark it as no longer shared if this
                    // operation causes it to be free.
858
                    if (!mCore->mSharedBufferMode &&
859 860 861 862 863
                            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()) {
864 865
                        mCore->mActiveBuffers.erase(front->mSlot);
                        mCore->mFreeBuffers.push_back(front->mSlot);
866
                    }
867
                }
868

869 870
                // Overwrite the droppable buffer with the incoming one
                *front = item;
871
                frameReplacedListener = mCore->mConsumerListener;
872 873
            } else {
                mCore->mQueue.push_back(item);
874
                frameAvailableListener = mCore->mConsumerListener;
875 876 877 878 879 880 881
            }
        }

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

        output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
882 883
                mCore->mTransformHint,
                static_cast<uint32_t>(mCore->mQueue.size()));
884 885

        ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
886 887 888

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

890
        VALIDATE_CONSISTENCY();
891 892
    } // Autolock scope

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    // 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();
914 915
    }

916 917 918 919 920 921 922 923 924
    // 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;
    }

925 926 927
    return NO_ERROR;
}

928
status_t BufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
929 930 931 932 933 934
    ATRACE_CALL();
    BQ_LOGV("cancelBuffer: slot %d", slot);
    Mutex::Autolock lock(mCore->mMutex);

    if (mCore->mIsAbandoned) {
        BQ_LOGE("cancelBuffer: BufferQueue has been abandoned");
935 936 937 938 939 940
        return NO_INIT;
    }

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

943 944
    if (mCore->mSharedBufferMode) {
        BQ_LOGE("cancelBuffer: cannot cancel a buffer in shared buffer mode");
945 946 947
        return BAD_VALUE;
    }

948
    if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
949
        BQ_LOGE("cancelBuffer: slot index %d out of range [0, %d)",
950
                slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
951
        return BAD_VALUE;
952
    } else if (!mSlots[slot].mBufferState.isDequeued()) {
953
        BQ_LOGE("cancelBuffer: slot %d is not owned by the producer "
954
                "(state = %s)", slot, mSlots[slot].mBufferState.string());
955
        return BAD_VALUE;
956 957
    } else if (fence == NULL) {
        BQ_LOGE("cancelBuffer: fence is NULL");
958
        return BAD_VALUE;
959 960
    }

961 962
    mSlots[slot].mBufferState.cancel();

963
    // After leaving shared buffer mode, the shared buffer will still be around.
964
    // Mark it as no longer shared if this operation causes it to be free.
965
    if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) {
966 967 968 969 970
        mSlots[slot].mBufferState.mShared = false;
    }

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

975 976
    mSlots[slot].mFence = fence;
    mCore->mDequeueCondition.broadcast();
977
    VALIDATE_CONSISTENCY();
978 979

    return NO_ERROR;
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
}

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:
999
            value = static_cast<int32_t>(mCore->mDefaultWidth);
1000 1001
            break;
        case NATIVE_WINDOW_HEIGHT:
1002
            value = static_cast<int32_t>(mCore->mDefaultHeight);
1003 1004
            break;
        case NATIVE_WINDOW_FORMAT:
1005
            value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
1006 1007
            break;
        case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
1008
            value = mCore->getMinUndequeuedBufferCountLocked();
1009
            break;
1010
        case NATIVE_WINDOW_STICKY_TRANSFORM:
1011
            value = static_cast<int32_t>(mStickyTransform);
1012
            break;
1013 1014 1015 1016
        case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
            value = (mCore->mQueue.size() > 1);
            break;
        case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
1017
            value = static_cast<int32_t>(mCore->mConsumerUsageBits);
1018
            break;
1019 1020 1021
        case NATIVE_WINDOW_DEFAULT_DATASPACE:
            value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace);
            break;
1022 1023 1024 1025 1026 1027 1028
        case NATIVE_WINDOW_BUFFER_AGE:
            if (mCore->mBufferAge > INT32_MAX) {
                value = 0;
            } else {
                value = static_cast<int32_t>(mCore->mBufferAge);
            }
            break;
1029 1030 1031 1032 1033 1034 1035 1036 1037
        default:
            return BAD_VALUE;
    }

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

1038
status_t BufferQueueProducer::connect(const sp<IProducerListener>& listener,
1039 1040
        int api, bool producerControlledByApp, QueueBufferOutput *output) {
    ATRACE_CALL();
1041 1042 1043 1044
    Mutex::Autolock lock(mCore->mMutex);
    mConsumerName = mCore->mConsumerName;
    BQ_LOGV("connect: api=%d producerControlledByApp=%s", api,
            producerControlledByApp ? "true" : "false");
1045

1046 1047 1048 1049
    if (mCore->mIsAbandoned) {
        BQ_LOGE("connect: BufferQueue has been abandoned");
        return NO_INIT;
    }
1050

1051 1052 1053 1054
    if (mCore->mConsumerListener == NULL) {
        BQ_LOGE("connect: BufferQueue has no consumer");
        return NO_INIT;
    }
1055

1056 1057 1058 1059
    if (output == NULL) {
        BQ_LOGE("connect: output was NULL");
        return BAD_VALUE;
    }
1060

1061 1062 1063 1064 1065
    if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
        BQ_LOGE("connect: already connected (cur=%d req=%d)",
                mCore->mConnectedApi, api);
        return BAD_VALUE;
    }
1066

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    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
1077

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    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);
1098
                }
1099 1100 1101 1102 1103 1104 1105
            }
            mCore->mConnectedProducerListener = listener;
            break;
        default:
            BQ_LOGE("connect: unknown API %d", api);
            status = BAD_VALUE;
            break;
1106 1107
    }

1108 1109 1110 1111 1112
    mCore->mBufferHasBeenQueued = false;
    mCore->mDequeueBufferCannotBlock = false;
    if (mDequeueTimeout < 0) {
        mCore->mDequeueBufferCannotBlock =
                mCore->mConsumerControlledByApp && producerControlledByApp;
1113
    }
1114

1115 1116
    mCore->mAllowAllocation = true;
    VALIDATE_CONSISTENCY();
1117 1118 1119 1120 1121
    return status;
}

status_t BufferQueueProducer::disconnect(int api) {
    ATRACE_CALL();
1122
    BQ_LOGV("disconnect: api %d", api);
1123 1124 1125 1126 1127

    int status = NO_ERROR;
    sp<IConsumerListener> listener;
    { // Autolock scope
        Mutex::Autolock lock(mCore->mMutex);
1128
        mCore->waitWhileAllocatingLocked();
1129 1130 1131 1132 1133 1134 1135

        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;
        }

1136 1137
        if (api == BufferQueueCore::CURRENTLY_CONNECTED_API) {
            api = mCore->mConnectedApi;
1138 1139 1140 1141 1142
            // 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;
            }
1143 1144
        }

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

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

    return status;
}

1190
status_t BufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
Wonsik Kim's avatar
Wonsik Kim committed
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    sp<IConsumerListener> listener;
    { // Autolock scope
        Mutex::Autolock _l(mCore->mMutex);
        mCore->mSidebandStream = stream;
        listener = mCore->mConsumerListener;
    } // Autolock scope

    if (listener != NULL) {
        listener->onSidebandStreamChanged();
    }
1201 1202 1203
    return NO_ERROR;
}

1204 1205
void BufferQueueProducer::allocateBuffers(uint32_t width, uint32_t height,
        PixelFormat format, uint32_t usage) {
1206 1207 1208 1209 1210
    ATRACE_CALL();
    while (true) {
        size_t newBufferCount = 0;
        uint32_t allocWidth = 0;
        uint32_t allocHeight = 0;
1211
        PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
1212 1213 1214 1215
        uint32_t allocUsage = 0;
        { // Autolock scope
            Mutex::Autolock lock(mCore->mMutex);
            mCore->waitWhileAllocatingLocked();
1216

1217 1218 1219 1220 1221 1222
            if (!mCore->mAllowAllocation) {
                BQ_LOGE("allocateBuffers: allocation is not allowed for this "
                        "BufferQueue");
                return;
            }

1223 1224
            newBufferCount = mCore->mFreeSlots.size();
            if (newBufferCount == 0) {
1225 1226
                return;
            }
1227

1228 1229 1230 1231
            allocWidth = width > 0 ? width : mCore->mDefaultWidth;
            allocHeight = height > 0 ? height : mCore->mDefaultHeight;
            allocFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
            allocUsage = usage | mCore->mConsumerUsageBits;
1232

1233 1234 1235
            mCore->mIsAllocating = true;
        } // Autolock scope

1236
        Vector<sp<GraphicBuffer>> buffers;
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
        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);
1250 1251
        }

1252 1253 1254 1255
        { // Autolock scope
            Mutex::Autolock lock(mCore->mMutex);
            uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
            uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
1256 1257
            PixelFormat checkFormat = format != 0 ?
                    format : mCore->mDefaultBufferFormat;
1258 1259 1260 1261 1262 1263 1264 1265 1266
            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;
            }
1267

1268
            for (size_t i = 0; i < newBufferCount; ++i) {
1269 1270 1271
                if (mCore->mFreeSlots.empty()) {
                    BQ_LOGV("allocateBuffers: a slot was occupied while "
                            "allocating. Dropping allocated buffer.");
1272 1273
                    continue;
                }
1274 1275 1276 1277
                auto slot = mCore->mFreeSlots.begin();
                mCore->clearBufferSlotLocked(*slot); // Clean up the slot first
                mSlots[*slot].mGraphicBuffer = buffers[i];
                mSlots[*slot].mFence = Fence::NO_FENCE;
1278 1279 1280 1281

                // 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);
1282
                mCore->mFreeBuffers.push_front(*slot);
1283

1284 1285
                BQ_LOGV("allocateBuffers: allocated a new buffer in slot %d",
                        *slot);
1286
            }
1287

1288 1289
            mCore->mIsAllocating = false;
            mCore->mIsAllocatingCondition.broadcast();
1290
            VALIDATE_CONSISTENCY();
1291
        } // Autolock scope
1292 1293 1294
    }
}

1295 1296 1297 1298 1299 1300 1301 1302 1303
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;
}

1304 1305 1306 1307 1308 1309 1310 1311 1312
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;
}

1313 1314 1315 1316 1317 1318
String8 BufferQueueProducer::getConsumerName() const {
    ATRACE_CALL();
    BQ_LOGV("getConsumerName: %s", mConsumerName.string());
    return mConsumerName;
}

1319 1320 1321 1322 1323 1324 1325 1326
uint64_t BufferQueueProducer::getNextFrameNumber() const {
    ATRACE_CALL();

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

1327
status_t BufferQueueProducer::setSharedBufferMode(bool sharedBufferMode) {
1328
    ATRACE_CALL();
1329
    BQ_LOGV("setSharedBufferMode: %d", sharedBufferMode);
1330 1331

    Mutex::Autolock lock(mCore->mMutex);
1332 1333
    if (!sharedBufferMode) {
        mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT;
1334
    }
1335
    mCore->mSharedBufferMode = sharedBufferMode;
1336 1337 1338
    return NO_ERROR;
}

1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
status_t BufferQueueProducer::setAutoRefresh(bool autoRefresh) {
    ATRACE_CALL();
    BQ_LOGV("setAutoRefresh: %d", autoRefresh);

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

    mCore->mAutoRefresh = autoRefresh;
    return NO_ERROR;
}

1349 1350 1351
status_t BufferQueueProducer::setDequeueTimeout(nsecs_t timeout) {
    ATRACE_CALL();
    BQ_LOGV("setDequeueTimeout: %" PRId64, timeout);
1352

1353 1354 1355 1356 1357 1358 1359
    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;
1360 1361
    }

1362 1363
    mDequeueTimeout = timeout;
    mCore->mDequeueBufferCannotBlock = false;
1364

1365
    VALIDATE_CONSISTENCY();
1366 1367 1368
    return NO_ERROR;
}

1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
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