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