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