BufferQueue.cpp revision f0bc2f1d8d37977bd3aef3d3326a70e9e69d4246
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define LOG_TAG "BufferQueue" 18#define ATRACE_TAG ATRACE_TAG_GRAPHICS 19//#define LOG_NDEBUG 0 20 21#define GL_GLEXT_PROTOTYPES 22#define EGL_EGLEXT_PROTOTYPES 23 24#include <EGL/egl.h> 25#include <EGL/eglext.h> 26 27#include <gui/BufferQueue.h> 28#include <gui/ISurfaceComposer.h> 29#include <private/gui/ComposerService.h> 30 31#include <utils/Log.h> 32#include <gui/SurfaceTexture.h> 33#include <utils/Trace.h> 34 35// This compile option causes SurfaceTexture to return the buffer that is currently 36// attached to the GL texture from dequeueBuffer when no other buffers are 37// available. It requires the drivers (Gralloc, GL, OMX IL, and Camera) to do 38// implicit cross-process synchronization to prevent the buffer from being 39// written to before the buffer has (a) been detached from the GL texture and 40// (b) all GL reads from the buffer have completed. 41 42// During refactoring, do not support dequeuing the current buffer 43#undef ALLOW_DEQUEUE_CURRENT_BUFFER 44 45#ifdef ALLOW_DEQUEUE_CURRENT_BUFFER 46#define FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER true 47#warning "ALLOW_DEQUEUE_CURRENT_BUFFER enabled" 48#else 49#define FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER false 50#endif 51 52// Macros for including the BufferQueue name in log messages 53#define ST_LOGV(x, ...) ALOGV("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 54#define ST_LOGD(x, ...) ALOGD("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 55#define ST_LOGI(x, ...) ALOGI("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 56#define ST_LOGW(x, ...) ALOGW("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 57#define ST_LOGE(x, ...) ALOGE("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 58 59#define ATRACE_BUFFER_INDEX(index) \ 60 char ___traceBuf[1024]; \ 61 snprintf(___traceBuf, 1024, "%s: %d", mConsumerName.string(), (index)); \ 62 android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf); 63 64namespace android { 65 66// Get an ID that's unique within this process. 67static int32_t createProcessUniqueId() { 68 static volatile int32_t globalCounter = 0; 69 return android_atomic_inc(&globalCounter); 70} 71 72BufferQueue::BufferQueue( bool allowSynchronousMode, int bufferCount ) : 73 mDefaultWidth(1), 74 mDefaultHeight(1), 75 mPixelFormat(PIXEL_FORMAT_RGBA_8888), 76 mMinUndequeuedBuffers(bufferCount), 77 mMinAsyncBufferSlots(bufferCount + 1), 78 mMinSyncBufferSlots(bufferCount), 79 mBufferCount(mMinAsyncBufferSlots), 80 mClientBufferCount(0), 81 mServerBufferCount(mMinAsyncBufferSlots), 82 mSynchronousMode(false), 83 mAllowSynchronousMode(allowSynchronousMode), 84 mConnectedApi(NO_CONNECTED_API), 85 mAbandoned(false), 86 mFrameCounter(0), 87 mBufferHasBeenQueued(false), 88 mDefaultBufferFormat(0), 89 mConsumerUsageBits(0), 90 mTransformHint(0) 91{ 92 // Choose a name using the PID and a process-unique ID. 93 mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId()); 94 95 ST_LOGV("BufferQueue"); 96 sp<ISurfaceComposer> composer(ComposerService::getComposerService()); 97 mGraphicBufferAlloc = composer->createGraphicBufferAlloc(); 98 if (mGraphicBufferAlloc == 0) { 99 ST_LOGE("createGraphicBufferAlloc() failed in BufferQueue()"); 100 } 101} 102 103BufferQueue::~BufferQueue() { 104 ST_LOGV("~BufferQueue"); 105} 106 107status_t BufferQueue::setBufferCountServerLocked(int bufferCount) { 108 if (bufferCount > NUM_BUFFER_SLOTS) 109 return BAD_VALUE; 110 111 // special-case, nothing to do 112 if (bufferCount == mBufferCount) 113 return OK; 114 115 if (!mClientBufferCount && 116 bufferCount >= mBufferCount) { 117 // easy, we just have more buffers 118 mBufferCount = bufferCount; 119 mServerBufferCount = bufferCount; 120 mDequeueCondition.broadcast(); 121 } else { 122 // we're here because we're either 123 // - reducing the number of available buffers 124 // - or there is a client-buffer-count in effect 125 126 // less than 2 buffers is never allowed 127 if (bufferCount < 2) 128 return BAD_VALUE; 129 130 // when there is non client-buffer-count in effect, the client is not 131 // allowed to dequeue more than one buffer at a time, 132 // so the next time they dequeue a buffer, we know that they don't 133 // own one. the actual resizing will happen during the next 134 // dequeueBuffer. 135 136 mServerBufferCount = bufferCount; 137 mDequeueCondition.broadcast(); 138 } 139 return OK; 140} 141 142bool BufferQueue::isSynchronousMode() const { 143 Mutex::Autolock lock(mMutex); 144 return mSynchronousMode; 145} 146 147void BufferQueue::setConsumerName(const String8& name) { 148 Mutex::Autolock lock(mMutex); 149 mConsumerName = name; 150} 151 152status_t BufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) { 153 Mutex::Autolock lock(mMutex); 154 mDefaultBufferFormat = defaultFormat; 155 return OK; 156} 157 158status_t BufferQueue::setConsumerUsageBits(uint32_t usage) { 159 Mutex::Autolock lock(mMutex); 160 mConsumerUsageBits = usage; 161 return OK; 162} 163 164status_t BufferQueue::setTransformHint(uint32_t hint) { 165 Mutex::Autolock lock(mMutex); 166 mTransformHint = hint; 167 return OK; 168} 169 170status_t BufferQueue::setBufferCount(int bufferCount) { 171 ST_LOGV("setBufferCount: count=%d", bufferCount); 172 173 sp<ConsumerListener> listener; 174 { 175 Mutex::Autolock lock(mMutex); 176 177 if (mAbandoned) { 178 ST_LOGE("setBufferCount: SurfaceTexture has been abandoned!"); 179 return NO_INIT; 180 } 181 if (bufferCount > NUM_BUFFER_SLOTS) { 182 ST_LOGE("setBufferCount: bufferCount larger than slots available"); 183 return BAD_VALUE; 184 } 185 186 // Error out if the user has dequeued buffers 187 for (int i=0 ; i<mBufferCount ; i++) { 188 if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) { 189 ST_LOGE("setBufferCount: client owns some buffers"); 190 return -EINVAL; 191 } 192 } 193 194 const int minBufferSlots = mSynchronousMode ? 195 mMinSyncBufferSlots : mMinAsyncBufferSlots; 196 if (bufferCount == 0) { 197 mClientBufferCount = 0; 198 bufferCount = (mServerBufferCount >= minBufferSlots) ? 199 mServerBufferCount : minBufferSlots; 200 return setBufferCountServerLocked(bufferCount); 201 } 202 203 if (bufferCount < minBufferSlots) { 204 ST_LOGE("setBufferCount: requested buffer count (%d) is less than " 205 "minimum (%d)", bufferCount, minBufferSlots); 206 return BAD_VALUE; 207 } 208 209 // here we're guaranteed that the client doesn't have dequeued buffers 210 // and will release all of its buffer references. 211 freeAllBuffersLocked(); 212 mBufferCount = bufferCount; 213 mClientBufferCount = bufferCount; 214 mBufferHasBeenQueued = false; 215 mQueue.clear(); 216 mDequeueCondition.broadcast(); 217 listener = mConsumerListener; 218 } // scope for lock 219 220 if (listener != NULL) { 221 listener->onBuffersReleased(); 222 } 223 224 return OK; 225} 226 227int BufferQueue::query(int what, int* outValue) 228{ 229 ATRACE_CALL(); 230 Mutex::Autolock lock(mMutex); 231 232 if (mAbandoned) { 233 ST_LOGE("query: SurfaceTexture has been abandoned!"); 234 return NO_INIT; 235 } 236 237 int value; 238 switch (what) { 239 case NATIVE_WINDOW_WIDTH: 240 value = mDefaultWidth; 241 break; 242 case NATIVE_WINDOW_HEIGHT: 243 value = mDefaultHeight; 244 break; 245 case NATIVE_WINDOW_FORMAT: 246 value = mPixelFormat; 247 break; 248 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS: 249 value = mSynchronousMode ? 250 (mMinUndequeuedBuffers-1) : mMinUndequeuedBuffers; 251 break; 252 default: 253 return BAD_VALUE; 254 } 255 outValue[0] = value; 256 return NO_ERROR; 257} 258 259status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) { 260 ATRACE_CALL(); 261 ST_LOGV("requestBuffer: slot=%d", slot); 262 Mutex::Autolock lock(mMutex); 263 if (mAbandoned) { 264 ST_LOGE("requestBuffer: SurfaceTexture has been abandoned!"); 265 return NO_INIT; 266 } 267 if (slot < 0 || mBufferCount <= slot) { 268 ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d", 269 mBufferCount, slot); 270 return BAD_VALUE; 271 } 272 mSlots[slot].mRequestBufferCalled = true; 273 *buf = mSlots[slot].mGraphicBuffer; 274 return NO_ERROR; 275} 276 277status_t BufferQueue::dequeueBuffer(int *outBuf, uint32_t w, uint32_t h, 278 uint32_t format, uint32_t usage) { 279 ATRACE_CALL(); 280 ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage); 281 282 if ((w && !h) || (!w && h)) { 283 ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h); 284 return BAD_VALUE; 285 } 286 287 status_t returnFlags(OK); 288 EGLDisplay dpy = EGL_NO_DISPLAY; 289 EGLSyncKHR fence = EGL_NO_SYNC_KHR; 290 291 { // Scope for the lock 292 Mutex::Autolock lock(mMutex); 293 294 if (format == 0) { 295 format = mDefaultBufferFormat; 296 } 297 // turn on usage bits the consumer requested 298 usage |= mConsumerUsageBits; 299 300 int found = -1; 301 int foundSync = -1; 302 int dequeuedCount = 0; 303 bool tryAgain = true; 304 while (tryAgain) { 305 if (mAbandoned) { 306 ST_LOGE("dequeueBuffer: SurfaceTexture has been abandoned!"); 307 return NO_INIT; 308 } 309 310 // We need to wait for the FIFO to drain if the number of buffer 311 // needs to change. 312 // 313 // The condition "number of buffers needs to change" is true if 314 // - the client doesn't care about how many buffers there are 315 // - AND the actual number of buffer is different from what was 316 // set in the last setBufferCountServer() 317 // - OR - 318 // setBufferCountServer() was set to a value incompatible with 319 // the synchronization mode (for instance because the sync mode 320 // changed since) 321 // 322 // As long as this condition is true AND the FIFO is not empty, we 323 // wait on mDequeueCondition. 324 325 const int minBufferCountNeeded = mSynchronousMode ? 326 mMinSyncBufferSlots : mMinAsyncBufferSlots; 327 328 const bool numberOfBuffersNeedsToChange = !mClientBufferCount && 329 ((mServerBufferCount != mBufferCount) || 330 (mServerBufferCount < minBufferCountNeeded)); 331 332 if (!mQueue.isEmpty() && numberOfBuffersNeedsToChange) { 333 // wait for the FIFO to drain 334 mDequeueCondition.wait(mMutex); 335 // NOTE: we continue here because we need to reevaluate our 336 // whole state (eg: we could be abandoned or disconnected) 337 continue; 338 } 339 340 if (numberOfBuffersNeedsToChange) { 341 // here we're guaranteed that mQueue is empty 342 freeAllBuffersLocked(); 343 mBufferCount = mServerBufferCount; 344 if (mBufferCount < minBufferCountNeeded) 345 mBufferCount = minBufferCountNeeded; 346 mBufferHasBeenQueued = false; 347 returnFlags |= ISurfaceTexture::RELEASE_ALL_BUFFERS; 348 } 349 350 // look for a free buffer to give to the client 351 found = INVALID_BUFFER_SLOT; 352 foundSync = INVALID_BUFFER_SLOT; 353 dequeuedCount = 0; 354 for (int i = 0; i < mBufferCount; i++) { 355 const int state = mSlots[i].mBufferState; 356 if (state == BufferSlot::DEQUEUED) { 357 dequeuedCount++; 358 } 359 360 // this logic used to be if (FLAG_ALLOW_DEQUEUE_CURRENT_BUFFER) 361 // but dequeuing the current buffer is disabled. 362 if (false) { 363 // This functionality has been temporarily removed so 364 // BufferQueue and SurfaceTexture can be refactored into 365 // separate objects 366 } else { 367 if (state == BufferSlot::FREE) { 368 /* We return the oldest of the free buffers to avoid 369 * stalling the producer if possible. This is because 370 * the consumer may still have pending reads of the 371 * buffers in flight. 372 */ 373 bool isOlder = mSlots[i].mFrameNumber < 374 mSlots[found].mFrameNumber; 375 if (found < 0 || isOlder) { 376 foundSync = i; 377 found = i; 378 } 379 } 380 } 381 } 382 383 // clients are not allowed to dequeue more than one buffer 384 // if they didn't set a buffer count. 385 if (!mClientBufferCount && dequeuedCount) { 386 ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without " 387 "setting the buffer count"); 388 return -EINVAL; 389 } 390 391 // See whether a buffer has been queued since the last 392 // setBufferCount so we know whether to perform the 393 // mMinUndequeuedBuffers check below. 394 if (mBufferHasBeenQueued) { 395 // make sure the client is not trying to dequeue more buffers 396 // than allowed. 397 const int avail = mBufferCount - (dequeuedCount+1); 398 if (avail < (mMinUndequeuedBuffers-int(mSynchronousMode))) { 399 ST_LOGE("dequeueBuffer: mMinUndequeuedBuffers=%d exceeded " 400 "(dequeued=%d)", 401 mMinUndequeuedBuffers-int(mSynchronousMode), 402 dequeuedCount); 403 return -EBUSY; 404 } 405 } 406 407 // if no buffer is found, wait for a buffer to be released 408 tryAgain = found == INVALID_BUFFER_SLOT; 409 if (tryAgain) { 410 mDequeueCondition.wait(mMutex); 411 } 412 } 413 414 415 if (found == INVALID_BUFFER_SLOT) { 416 // This should not happen. 417 ST_LOGE("dequeueBuffer: no available buffer slots"); 418 return -EBUSY; 419 } 420 421 const int buf = found; 422 *outBuf = found; 423 424 ATRACE_BUFFER_INDEX(buf); 425 426 const bool useDefaultSize = !w && !h; 427 if (useDefaultSize) { 428 // use the default size 429 w = mDefaultWidth; 430 h = mDefaultHeight; 431 } 432 433 const bool updateFormat = (format != 0); 434 if (!updateFormat) { 435 // keep the current (or default) format 436 format = mPixelFormat; 437 } 438 439 // buffer is now in DEQUEUED (but can also be current at the same time, 440 // if we're in synchronous mode) 441 mSlots[buf].mBufferState = BufferSlot::DEQUEUED; 442 443 const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer); 444 if ((buffer == NULL) || 445 (uint32_t(buffer->width) != w) || 446 (uint32_t(buffer->height) != h) || 447 (uint32_t(buffer->format) != format) || 448 ((uint32_t(buffer->usage) & usage) != usage)) 449 { 450 usage |= GraphicBuffer::USAGE_HW_TEXTURE; 451 status_t error; 452 sp<GraphicBuffer> graphicBuffer( 453 mGraphicBufferAlloc->createGraphicBuffer( 454 w, h, format, usage, &error)); 455 if (graphicBuffer == 0) { 456 ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer " 457 "failed"); 458 return error; 459 } 460 if (updateFormat) { 461 mPixelFormat = format; 462 } 463 464 mSlots[buf].mAcquireCalled = false; 465 mSlots[buf].mGraphicBuffer = graphicBuffer; 466 mSlots[buf].mRequestBufferCalled = false; 467 mSlots[buf].mFence = EGL_NO_SYNC_KHR; 468 mSlots[buf].mEglDisplay = EGL_NO_DISPLAY; 469 470 returnFlags |= ISurfaceTexture::BUFFER_NEEDS_REALLOCATION; 471 } 472 473 dpy = mSlots[buf].mEglDisplay; 474 fence = mSlots[buf].mFence; 475 mSlots[buf].mFence = EGL_NO_SYNC_KHR; 476 } // end lock scope 477 478 if (fence != EGL_NO_SYNC_KHR) { 479 EGLint result = eglClientWaitSyncKHR(dpy, fence, 0, 1000000000); 480 // If something goes wrong, log the error, but return the buffer without 481 // synchronizing access to it. It's too late at this point to abort the 482 // dequeue operation. 483 if (result == EGL_FALSE) { 484 ALOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError()); 485 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) { 486 ALOGE("dequeueBuffer: timeout waiting for fence"); 487 } 488 eglDestroySyncKHR(dpy, fence); 489 } 490 491 ST_LOGV("dequeueBuffer: returning slot=%d buf=%p flags=%#x", *outBuf, 492 mSlots[*outBuf].mGraphicBuffer->handle, returnFlags); 493 494 return returnFlags; 495} 496 497status_t BufferQueue::setSynchronousMode(bool enabled) { 498 ATRACE_CALL(); 499 ST_LOGV("setSynchronousMode: enabled=%d", enabled); 500 Mutex::Autolock lock(mMutex); 501 502 if (mAbandoned) { 503 ST_LOGE("setSynchronousMode: SurfaceTexture has been abandoned!"); 504 return NO_INIT; 505 } 506 507 status_t err = OK; 508 if (!mAllowSynchronousMode && enabled) 509 return err; 510 511 if (!enabled) { 512 // going to asynchronous mode, drain the queue 513 err = drainQueueLocked(); 514 if (err != NO_ERROR) 515 return err; 516 } 517 518 if (mSynchronousMode != enabled) { 519 // - if we're going to asynchronous mode, the queue is guaranteed to be 520 // empty here 521 // - if the client set the number of buffers, we're guaranteed that 522 // we have at least 3 (because we don't allow less) 523 mSynchronousMode = enabled; 524 mDequeueCondition.broadcast(); 525 } 526 return err; 527} 528 529status_t BufferQueue::queueBuffer(int buf, 530 const QueueBufferInput& input, QueueBufferOutput* output) { 531 ATRACE_CALL(); 532 ATRACE_BUFFER_INDEX(buf); 533 534 ST_LOGV("queueBuffer: slot=%d time=%lld", buf, timestamp); 535 536 sp<ConsumerListener> listener; 537 538 { // scope for the lock 539 Mutex::Autolock lock(mMutex); 540 if (mAbandoned) { 541 ST_LOGE("queueBuffer: SurfaceTexture has been abandoned!"); 542 return NO_INIT; 543 } 544 if (buf < 0 || buf >= mBufferCount) { 545 ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d", 546 mBufferCount, buf); 547 return -EINVAL; 548 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) { 549 ST_LOGE("queueBuffer: slot %d is not owned by the client " 550 "(state=%d)", buf, mSlots[buf].mBufferState); 551 return -EINVAL; 552 } else if (!mSlots[buf].mRequestBufferCalled) { 553 ST_LOGE("queueBuffer: slot %d was enqueued without requesting a " 554 "buffer", buf); 555 return -EINVAL; 556 } 557 558 if (mSynchronousMode) { 559 // In synchronous mode we queue all buffers in a FIFO. 560 mQueue.push_back(buf); 561 562 // Synchronous mode always signals that an additional frame should 563 // be consumed. 564 listener = mConsumerListener; 565 } else { 566 // In asynchronous mode we only keep the most recent buffer. 567 if (mQueue.empty()) { 568 mQueue.push_back(buf); 569 570 // Asynchronous mode only signals that a frame should be 571 // consumed if no previous frame was pending. If a frame were 572 // pending then the consumer would have already been notified. 573 listener = mConsumerListener; 574 } else { 575 Fifo::iterator front(mQueue.begin()); 576 // buffer currently queued is freed 577 mSlots[*front].mBufferState = BufferSlot::FREE; 578 // and we record the new buffer index in the queued list 579 *front = buf; 580 } 581 } 582 583 int scalingMode; 584 585 input.deflate( 586 &mSlots[buf].mTimestamp, 587 &mSlots[buf].mCrop, 588 &scalingMode, 589 &mSlots[buf].mTransform); 590 591 592 switch (scalingMode) { 593 case NATIVE_WINDOW_SCALING_MODE_FREEZE: 594 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: 595 break; 596 default: 597 ST_LOGE("unknown scaling mode: %d (ignoring)", scalingMode); 598 scalingMode = mSlots[buf].mScalingMode; 599 break; 600 } 601 602 mSlots[buf].mBufferState = BufferSlot::QUEUED; 603 mSlots[buf].mScalingMode = scalingMode; 604 mFrameCounter++; 605 mSlots[buf].mFrameNumber = mFrameCounter; 606 607 mBufferHasBeenQueued = true; 608 mDequeueCondition.broadcast(); 609 610 output->inflate(mDefaultWidth, mDefaultHeight, mDefaultHeight); 611 612 ATRACE_INT(mConsumerName.string(), mQueue.size()); 613 } // scope for the lock 614 615 // call back without lock held 616 if (listener != 0) { 617 listener->onFrameAvailable(); 618 } 619 return OK; 620} 621 622void BufferQueue::cancelBuffer(int buf) { 623 ATRACE_CALL(); 624 ST_LOGV("cancelBuffer: slot=%d", buf); 625 Mutex::Autolock lock(mMutex); 626 627 if (mAbandoned) { 628 ST_LOGW("cancelBuffer: BufferQueue has been abandoned!"); 629 return; 630 } 631 632 if (buf < 0 || buf >= mBufferCount) { 633 ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d", 634 mBufferCount, buf); 635 return; 636 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) { 637 ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)", 638 buf, mSlots[buf].mBufferState); 639 return; 640 } 641 mSlots[buf].mBufferState = BufferSlot::FREE; 642 mSlots[buf].mFrameNumber = 0; 643 mDequeueCondition.broadcast(); 644} 645 646status_t BufferQueue::connect(int api, 647 uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform) { 648 ATRACE_CALL(); 649 ST_LOGV("connect: api=%d", api); 650 Mutex::Autolock lock(mMutex); 651 652 if (mAbandoned) { 653 ST_LOGE("connect: BufferQueue has been abandoned!"); 654 return NO_INIT; 655 } 656 657 if (mConsumerListener == NULL) { 658 ST_LOGE("connect: BufferQueue has no consumer!"); 659 return NO_INIT; 660 } 661 662 int err = NO_ERROR; 663 switch (api) { 664 case NATIVE_WINDOW_API_EGL: 665 case NATIVE_WINDOW_API_CPU: 666 case NATIVE_WINDOW_API_MEDIA: 667 case NATIVE_WINDOW_API_CAMERA: 668 if (mConnectedApi != NO_CONNECTED_API) { 669 ST_LOGE("connect: already connected (cur=%d, req=%d)", 670 mConnectedApi, api); 671 err = -EINVAL; 672 } else { 673 mConnectedApi = api; 674 *outWidth = mDefaultWidth; 675 *outHeight = mDefaultHeight; 676 *outTransform = 0; 677 } 678 break; 679 default: 680 err = -EINVAL; 681 break; 682 } 683 684 mBufferHasBeenQueued = false; 685 686 return err; 687} 688 689status_t BufferQueue::disconnect(int api) { 690 ATRACE_CALL(); 691 ST_LOGV("disconnect: api=%d", api); 692 693 int err = NO_ERROR; 694 sp<ConsumerListener> listener; 695 696 { // Scope for the lock 697 Mutex::Autolock lock(mMutex); 698 699 if (mAbandoned) { 700 // it is not really an error to disconnect after the surface 701 // has been abandoned, it should just be a no-op. 702 return NO_ERROR; 703 } 704 705 switch (api) { 706 case NATIVE_WINDOW_API_EGL: 707 case NATIVE_WINDOW_API_CPU: 708 case NATIVE_WINDOW_API_MEDIA: 709 case NATIVE_WINDOW_API_CAMERA: 710 if (mConnectedApi == api) { 711 drainQueueAndFreeBuffersLocked(); 712 mConnectedApi = NO_CONNECTED_API; 713 mDequeueCondition.broadcast(); 714 listener = mConsumerListener; 715 } else { 716 ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)", 717 mConnectedApi, api); 718 err = -EINVAL; 719 } 720 break; 721 default: 722 ST_LOGE("disconnect: unknown API %d", api); 723 err = -EINVAL; 724 break; 725 } 726 } 727 728 if (listener != NULL) { 729 listener->onBuffersReleased(); 730 } 731 732 return err; 733} 734 735void BufferQueue::dump(String8& result) const 736{ 737 char buffer[1024]; 738 BufferQueue::dump(result, "", buffer, 1024); 739} 740 741void BufferQueue::dump(String8& result, const char* prefix, 742 char* buffer, size_t SIZE) const 743{ 744 Mutex::Autolock _l(mMutex); 745 746 String8 fifo; 747 int fifoSize = 0; 748 Fifo::const_iterator i(mQueue.begin()); 749 while (i != mQueue.end()) { 750 snprintf(buffer, SIZE, "%02d ", *i++); 751 fifoSize++; 752 fifo.append(buffer); 753 } 754 755 snprintf(buffer, SIZE, 756 "%s-BufferQueue mBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], " 757 "mPixelFormat=%d, FIFO(%d)={%s}\n", 758 prefix, mBufferCount, mSynchronousMode, mDefaultWidth, 759 mDefaultHeight, mPixelFormat, fifoSize, fifo.string()); 760 result.append(buffer); 761 762 763 struct { 764 const char * operator()(int state) const { 765 switch (state) { 766 case BufferSlot::DEQUEUED: return "DEQUEUED"; 767 case BufferSlot::QUEUED: return "QUEUED"; 768 case BufferSlot::FREE: return "FREE"; 769 case BufferSlot::ACQUIRED: return "ACQUIRED"; 770 default: return "Unknown"; 771 } 772 } 773 } stateName; 774 775 for (int i=0 ; i<mBufferCount ; i++) { 776 const BufferSlot& slot(mSlots[i]); 777 snprintf(buffer, SIZE, 778 "%s%s[%02d] " 779 "state=%-8s, crop=[%d,%d,%d,%d], " 780 "transform=0x%02x, timestamp=%lld", 781 prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i, 782 stateName(slot.mBufferState), 783 slot.mCrop.left, slot.mCrop.top, slot.mCrop.right, 784 slot.mCrop.bottom, slot.mTransform, slot.mTimestamp 785 ); 786 result.append(buffer); 787 788 const sp<GraphicBuffer>& buf(slot.mGraphicBuffer); 789 if (buf != NULL) { 790 snprintf(buffer, SIZE, 791 ", %p [%4ux%4u:%4u,%3X]", 792 buf->handle, buf->width, buf->height, buf->stride, 793 buf->format); 794 result.append(buffer); 795 } 796 result.append("\n"); 797 } 798} 799 800void BufferQueue::freeBufferLocked(int i) { 801 mSlots[i].mGraphicBuffer = 0; 802 if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) { 803 mSlots[i].mNeedsCleanupOnRelease = true; 804 } 805 mSlots[i].mBufferState = BufferSlot::FREE; 806 mSlots[i].mFrameNumber = 0; 807 mSlots[i].mAcquireCalled = false; 808 809 // destroy fence as BufferQueue now takes ownership 810 if (mSlots[i].mFence != EGL_NO_SYNC_KHR) { 811 eglDestroySyncKHR(mSlots[i].mEglDisplay, mSlots[i].mFence); 812 mSlots[i].mFence = EGL_NO_SYNC_KHR; 813 } 814} 815 816void BufferQueue::freeAllBuffersLocked() { 817 ALOGW_IF(!mQueue.isEmpty(), 818 "freeAllBuffersLocked called but mQueue is not empty"); 819 mQueue.clear(); 820 mBufferHasBeenQueued = false; 821 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 822 freeBufferLocked(i); 823 } 824} 825 826status_t BufferQueue::acquireBuffer(BufferItem *buffer) { 827 ATRACE_CALL(); 828 Mutex::Autolock _l(mMutex); 829 // check if queue is empty 830 // In asynchronous mode the list is guaranteed to be one buffer 831 // deep, while in synchronous mode we use the oldest buffer. 832 if (!mQueue.empty()) { 833 Fifo::iterator front(mQueue.begin()); 834 int buf = *front; 835 836 ATRACE_BUFFER_INDEX(buf); 837 838 if (mSlots[buf].mAcquireCalled) { 839 buffer->mGraphicBuffer = NULL; 840 } else { 841 buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer; 842 } 843 buffer->mCrop = mSlots[buf].mCrop; 844 buffer->mTransform = mSlots[buf].mTransform; 845 buffer->mScalingMode = mSlots[buf].mScalingMode; 846 buffer->mFrameNumber = mSlots[buf].mFrameNumber; 847 buffer->mTimestamp = mSlots[buf].mTimestamp; 848 buffer->mBuf = buf; 849 mSlots[buf].mAcquireCalled = true; 850 851 mSlots[buf].mBufferState = BufferSlot::ACQUIRED; 852 mQueue.erase(front); 853 mDequeueCondition.broadcast(); 854 855 ATRACE_INT(mConsumerName.string(), mQueue.size()); 856 } else { 857 return NO_BUFFER_AVAILABLE; 858 } 859 860 return OK; 861} 862 863status_t BufferQueue::releaseBuffer(int buf, EGLDisplay display, 864 EGLSyncKHR fence) { 865 ATRACE_CALL(); 866 ATRACE_BUFFER_INDEX(buf); 867 868 Mutex::Autolock _l(mMutex); 869 870 if (buf == INVALID_BUFFER_SLOT) { 871 return -EINVAL; 872 } 873 874 mSlots[buf].mEglDisplay = display; 875 mSlots[buf].mFence = fence; 876 877 // The buffer can now only be released if its in the acquired state 878 if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) { 879 mSlots[buf].mBufferState = BufferSlot::FREE; 880 } else if (mSlots[buf].mNeedsCleanupOnRelease) { 881 ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState); 882 mSlots[buf].mNeedsCleanupOnRelease = false; 883 return STALE_BUFFER_SLOT; 884 } else { 885 ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState); 886 return -EINVAL; 887 } 888 889 mDequeueCondition.broadcast(); 890 return OK; 891} 892 893status_t BufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener) { 894 ST_LOGV("consumerConnect"); 895 Mutex::Autolock lock(mMutex); 896 897 if (mAbandoned) { 898 ST_LOGE("consumerConnect: BufferQueue has been abandoned!"); 899 return NO_INIT; 900 } 901 902 mConsumerListener = consumerListener; 903 904 return OK; 905} 906 907status_t BufferQueue::consumerDisconnect() { 908 ST_LOGV("consumerDisconnect"); 909 Mutex::Autolock lock(mMutex); 910 911 if (mConsumerListener == NULL) { 912 ST_LOGE("consumerDisconnect: No consumer is connected!"); 913 return -EINVAL; 914 } 915 916 mAbandoned = true; 917 mConsumerListener = NULL; 918 mQueue.clear(); 919 freeAllBuffersLocked(); 920 mDequeueCondition.broadcast(); 921 return OK; 922} 923 924status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) { 925 ST_LOGV("getReleasedBuffers"); 926 Mutex::Autolock lock(mMutex); 927 928 if (mAbandoned) { 929 ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!"); 930 return NO_INIT; 931 } 932 933 uint32_t mask = 0; 934 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 935 if (!mSlots[i].mAcquireCalled) { 936 mask |= 1 << i; 937 } 938 } 939 *slotMask = mask; 940 941 ST_LOGV("getReleasedBuffers: returning mask %#x", mask); 942 return NO_ERROR; 943} 944 945status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h) 946{ 947 ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h); 948 if (!w || !h) { 949 ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)", 950 w, h); 951 return BAD_VALUE; 952 } 953 954 Mutex::Autolock lock(mMutex); 955 mDefaultWidth = w; 956 mDefaultHeight = h; 957 return OK; 958} 959 960status_t BufferQueue::setBufferCountServer(int bufferCount) { 961 ATRACE_CALL(); 962 Mutex::Autolock lock(mMutex); 963 return setBufferCountServerLocked(bufferCount); 964} 965 966void BufferQueue::freeAllBuffersExceptHeadLocked() { 967 ALOGW_IF(!mQueue.isEmpty(), 968 "freeAllBuffersExceptCurrentLocked called but mQueue is not empty"); 969 int head = -1; 970 if (!mQueue.empty()) { 971 Fifo::iterator front(mQueue.begin()); 972 head = *front; 973 } 974 mBufferHasBeenQueued = false; 975 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 976 if (i != head) { 977 freeBufferLocked(i); 978 } 979 } 980} 981 982status_t BufferQueue::drainQueueLocked() { 983 while (mSynchronousMode && !mQueue.isEmpty()) { 984 mDequeueCondition.wait(mMutex); 985 if (mAbandoned) { 986 ST_LOGE("drainQueueLocked: BufferQueue has been abandoned!"); 987 return NO_INIT; 988 } 989 if (mConnectedApi == NO_CONNECTED_API) { 990 ST_LOGE("drainQueueLocked: BufferQueue is not connected!"); 991 return NO_INIT; 992 } 993 } 994 return NO_ERROR; 995} 996 997status_t BufferQueue::drainQueueAndFreeBuffersLocked() { 998 status_t err = drainQueueLocked(); 999 if (err == NO_ERROR) { 1000 if (mSynchronousMode) { 1001 freeAllBuffersLocked(); 1002 } else { 1003 freeAllBuffersExceptHeadLocked(); 1004 } 1005 } 1006 return err; 1007} 1008 1009BufferQueue::ProxyConsumerListener::ProxyConsumerListener( 1010 const wp<BufferQueue::ConsumerListener>& consumerListener): 1011 mConsumerListener(consumerListener) {} 1012 1013BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {} 1014 1015void BufferQueue::ProxyConsumerListener::onFrameAvailable() { 1016 sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote()); 1017 if (listener != NULL) { 1018 listener->onFrameAvailable(); 1019 } 1020} 1021 1022void BufferQueue::ProxyConsumerListener::onBuffersReleased() { 1023 sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote()); 1024 if (listener != NULL) { 1025 listener->onBuffersReleased(); 1026 } 1027} 1028 1029}; // namespace android 1030