BufferQueue.cpp revision f78575400977f644cf0b12beb2fa5fc278b6ed4c
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 fence = 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].mFence = EGL_NO_SYNC_KHR; 484 mSlots[buf].mReleaseFence.clear(); 485 mSlots[buf].mEglDisplay = EGL_NO_DISPLAY; 486 487 returnFlags |= ISurfaceTexture::BUFFER_NEEDS_REALLOCATION; 488 } 489 490 dpy = mSlots[buf].mEglDisplay; 491 fence = mSlots[buf].mFence; 492 outFence = mSlots[buf].mReleaseFence; 493 mSlots[buf].mFence = EGL_NO_SYNC_KHR; 494 mSlots[buf].mReleaseFence.clear(); 495 } // end lock scope 496 497 if (fence != EGL_NO_SYNC_KHR) { 498 EGLint result = eglClientWaitSyncKHR(dpy, fence, 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, fence); 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 558 input.deflate(×tamp, &crop, &scalingMode, &transform); 559 560 ST_LOGV("queueBuffer: slot=%d time=%#llx crop=[%d,%d,%d,%d] tr=%#x " 561 "scale=%s", 562 buf, timestamp, crop.left, crop.top, crop.right, crop.bottom, 563 transform, scalingModeName(scalingMode)); 564 565 sp<ConsumerListener> listener; 566 567 { // scope for the lock 568 Mutex::Autolock lock(mMutex); 569 if (mAbandoned) { 570 ST_LOGE("queueBuffer: SurfaceTexture has been abandoned!"); 571 return NO_INIT; 572 } 573 if (buf < 0 || buf >= mBufferCount) { 574 ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d", 575 mBufferCount, buf); 576 return -EINVAL; 577 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) { 578 ST_LOGE("queueBuffer: slot %d is not owned by the client " 579 "(state=%d)", buf, mSlots[buf].mBufferState); 580 return -EINVAL; 581 } else if (!mSlots[buf].mRequestBufferCalled) { 582 ST_LOGE("queueBuffer: slot %d was enqueued without requesting a " 583 "buffer", buf); 584 return -EINVAL; 585 } 586 587 const sp<GraphicBuffer>& graphicBuffer(mSlots[buf].mGraphicBuffer); 588 Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight()); 589 Rect croppedCrop; 590 crop.intersect(bufferRect, &croppedCrop); 591 if (croppedCrop != crop) { 592 ST_LOGE("queueBuffer: crop rect is not contained within the " 593 "buffer in slot %d", buf); 594 return -EINVAL; 595 } 596 597 if (mSynchronousMode) { 598 // In synchronous mode we queue all buffers in a FIFO. 599 mQueue.push_back(buf); 600 601 // Synchronous mode always signals that an additional frame should 602 // be consumed. 603 listener = mConsumerListener; 604 } else { 605 // In asynchronous mode we only keep the most recent buffer. 606 if (mQueue.empty()) { 607 mQueue.push_back(buf); 608 609 // Asynchronous mode only signals that a frame should be 610 // consumed if no previous frame was pending. If a frame were 611 // pending then the consumer would have already been notified. 612 listener = mConsumerListener; 613 } else { 614 Fifo::iterator front(mQueue.begin()); 615 // buffer currently queued is freed 616 mSlots[*front].mBufferState = BufferSlot::FREE; 617 // and we record the new buffer index in the queued list 618 *front = buf; 619 } 620 } 621 622 mSlots[buf].mTimestamp = timestamp; 623 mSlots[buf].mCrop = crop; 624 mSlots[buf].mTransform = transform; 625 626 switch (scalingMode) { 627 case NATIVE_WINDOW_SCALING_MODE_FREEZE: 628 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: 629 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: 630 break; 631 default: 632 ST_LOGE("unknown scaling mode: %d (ignoring)", scalingMode); 633 scalingMode = mSlots[buf].mScalingMode; 634 break; 635 } 636 637 mSlots[buf].mBufferState = BufferSlot::QUEUED; 638 mSlots[buf].mScalingMode = scalingMode; 639 mFrameCounter++; 640 mSlots[buf].mFrameNumber = mFrameCounter; 641 642 mBufferHasBeenQueued = true; 643 mDequeueCondition.broadcast(); 644 645 output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint, 646 mQueue.size()); 647 648 ATRACE_INT(mConsumerName.string(), mQueue.size()); 649 } // scope for the lock 650 651 // call back without lock held 652 if (listener != 0) { 653 listener->onFrameAvailable(); 654 } 655 return OK; 656} 657 658void BufferQueue::cancelBuffer(int buf) { 659 ATRACE_CALL(); 660 ST_LOGV("cancelBuffer: slot=%d", buf); 661 Mutex::Autolock lock(mMutex); 662 663 if (mAbandoned) { 664 ST_LOGW("cancelBuffer: BufferQueue has been abandoned!"); 665 return; 666 } 667 668 if (buf < 0 || buf >= mBufferCount) { 669 ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d", 670 mBufferCount, buf); 671 return; 672 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) { 673 ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)", 674 buf, mSlots[buf].mBufferState); 675 return; 676 } 677 mSlots[buf].mBufferState = BufferSlot::FREE; 678 mSlots[buf].mFrameNumber = 0; 679 mDequeueCondition.broadcast(); 680} 681 682status_t BufferQueue::connect(int api, QueueBufferOutput* output) { 683 ATRACE_CALL(); 684 ST_LOGV("connect: api=%d", api); 685 Mutex::Autolock lock(mMutex); 686 687 if (mAbandoned) { 688 ST_LOGE("connect: BufferQueue has been abandoned!"); 689 return NO_INIT; 690 } 691 692 if (mConsumerListener == NULL) { 693 ST_LOGE("connect: BufferQueue has no consumer!"); 694 return NO_INIT; 695 } 696 697 int err = NO_ERROR; 698 switch (api) { 699 case NATIVE_WINDOW_API_EGL: 700 case NATIVE_WINDOW_API_CPU: 701 case NATIVE_WINDOW_API_MEDIA: 702 case NATIVE_WINDOW_API_CAMERA: 703 if (mConnectedApi != NO_CONNECTED_API) { 704 ST_LOGE("connect: already connected (cur=%d, req=%d)", 705 mConnectedApi, api); 706 err = -EINVAL; 707 } else { 708 mConnectedApi = api; 709 output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint, 710 mQueue.size()); 711 } 712 break; 713 default: 714 err = -EINVAL; 715 break; 716 } 717 718 mBufferHasBeenQueued = false; 719 720 return err; 721} 722 723status_t BufferQueue::disconnect(int api) { 724 ATRACE_CALL(); 725 ST_LOGV("disconnect: api=%d", api); 726 727 int err = NO_ERROR; 728 sp<ConsumerListener> listener; 729 730 { // Scope for the lock 731 Mutex::Autolock lock(mMutex); 732 733 if (mAbandoned) { 734 // it is not really an error to disconnect after the surface 735 // has been abandoned, it should just be a no-op. 736 return NO_ERROR; 737 } 738 739 switch (api) { 740 case NATIVE_WINDOW_API_EGL: 741 case NATIVE_WINDOW_API_CPU: 742 case NATIVE_WINDOW_API_MEDIA: 743 case NATIVE_WINDOW_API_CAMERA: 744 if (mConnectedApi == api) { 745 drainQueueAndFreeBuffersLocked(); 746 mConnectedApi = NO_CONNECTED_API; 747 mDequeueCondition.broadcast(); 748 listener = mConsumerListener; 749 } else { 750 ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)", 751 mConnectedApi, api); 752 err = -EINVAL; 753 } 754 break; 755 default: 756 ST_LOGE("disconnect: unknown API %d", api); 757 err = -EINVAL; 758 break; 759 } 760 } 761 762 if (listener != NULL) { 763 listener->onBuffersReleased(); 764 } 765 766 return err; 767} 768 769void BufferQueue::dump(String8& result) const 770{ 771 char buffer[1024]; 772 BufferQueue::dump(result, "", buffer, 1024); 773} 774 775void BufferQueue::dump(String8& result, const char* prefix, 776 char* buffer, size_t SIZE) const 777{ 778 Mutex::Autolock _l(mMutex); 779 780 String8 fifo; 781 int fifoSize = 0; 782 Fifo::const_iterator i(mQueue.begin()); 783 while (i != mQueue.end()) { 784 snprintf(buffer, SIZE, "%02d ", *i++); 785 fifoSize++; 786 fifo.append(buffer); 787 } 788 789 snprintf(buffer, SIZE, 790 "%s-BufferQueue mBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], " 791 "mPixelFormat=%d, FIFO(%d)={%s}\n", 792 prefix, mBufferCount, mSynchronousMode, mDefaultWidth, 793 mDefaultHeight, mPixelFormat, fifoSize, fifo.string()); 794 result.append(buffer); 795 796 797 struct { 798 const char * operator()(int state) const { 799 switch (state) { 800 case BufferSlot::DEQUEUED: return "DEQUEUED"; 801 case BufferSlot::QUEUED: return "QUEUED"; 802 case BufferSlot::FREE: return "FREE"; 803 case BufferSlot::ACQUIRED: return "ACQUIRED"; 804 default: return "Unknown"; 805 } 806 } 807 } stateName; 808 809 for (int i=0 ; i<mBufferCount ; i++) { 810 const BufferSlot& slot(mSlots[i]); 811 snprintf(buffer, SIZE, 812 "%s%s[%02d] " 813 "state=%-8s, crop=[%d,%d,%d,%d], " 814 "xform=0x%02x, time=%#llx, scale=%s", 815 prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i, 816 stateName(slot.mBufferState), 817 slot.mCrop.left, slot.mCrop.top, slot.mCrop.right, 818 slot.mCrop.bottom, slot.mTransform, slot.mTimestamp, 819 scalingModeName(slot.mScalingMode) 820 ); 821 result.append(buffer); 822 823 const sp<GraphicBuffer>& buf(slot.mGraphicBuffer); 824 if (buf != NULL) { 825 snprintf(buffer, SIZE, 826 ", %p [%4ux%4u:%4u,%3X]", 827 buf->handle, buf->width, buf->height, buf->stride, 828 buf->format); 829 result.append(buffer); 830 } 831 result.append("\n"); 832 } 833} 834 835void BufferQueue::freeBufferLocked(int i) { 836 mSlots[i].mGraphicBuffer = 0; 837 if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) { 838 mSlots[i].mNeedsCleanupOnRelease = true; 839 } 840 mSlots[i].mBufferState = BufferSlot::FREE; 841 mSlots[i].mFrameNumber = 0; 842 mSlots[i].mAcquireCalled = false; 843 844 // destroy fence as BufferQueue now takes ownership 845 if (mSlots[i].mFence != EGL_NO_SYNC_KHR) { 846 eglDestroySyncKHR(mSlots[i].mEglDisplay, mSlots[i].mFence); 847 mSlots[i].mFence = EGL_NO_SYNC_KHR; 848 } 849 mSlots[i].mReleaseFence.clear(); 850} 851 852void BufferQueue::freeAllBuffersLocked() { 853 ALOGW_IF(!mQueue.isEmpty(), 854 "freeAllBuffersLocked called but mQueue is not empty"); 855 mQueue.clear(); 856 mBufferHasBeenQueued = false; 857 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 858 freeBufferLocked(i); 859 } 860} 861 862status_t BufferQueue::acquireBuffer(BufferItem *buffer) { 863 ATRACE_CALL(); 864 Mutex::Autolock _l(mMutex); 865 // check if queue is empty 866 // In asynchronous mode the list is guaranteed to be one buffer 867 // deep, while in synchronous mode we use the oldest buffer. 868 if (!mQueue.empty()) { 869 Fifo::iterator front(mQueue.begin()); 870 int buf = *front; 871 872 ATRACE_BUFFER_INDEX(buf); 873 874 if (mSlots[buf].mAcquireCalled) { 875 buffer->mGraphicBuffer = NULL; 876 } else { 877 buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer; 878 } 879 buffer->mCrop = mSlots[buf].mCrop; 880 buffer->mTransform = mSlots[buf].mTransform; 881 buffer->mScalingMode = mSlots[buf].mScalingMode; 882 buffer->mFrameNumber = mSlots[buf].mFrameNumber; 883 buffer->mTimestamp = mSlots[buf].mTimestamp; 884 buffer->mBuf = buf; 885 mSlots[buf].mAcquireCalled = true; 886 887 mSlots[buf].mBufferState = BufferSlot::ACQUIRED; 888 mQueue.erase(front); 889 mDequeueCondition.broadcast(); 890 891 ATRACE_INT(mConsumerName.string(), mQueue.size()); 892 } else { 893 return NO_BUFFER_AVAILABLE; 894 } 895 896 return OK; 897} 898 899status_t BufferQueue::releaseBuffer(int buf, EGLDisplay display, 900 EGLSyncKHR fence, const sp<Fence>& releaseFence) { 901 ATRACE_CALL(); 902 ATRACE_BUFFER_INDEX(buf); 903 904 Mutex::Autolock _l(mMutex); 905 906 if (buf == INVALID_BUFFER_SLOT) { 907 return -EINVAL; 908 } 909 910 mSlots[buf].mEglDisplay = display; 911 mSlots[buf].mFence = fence; 912 mSlots[buf].mReleaseFence = releaseFence; 913 914 // The buffer can now only be released if its in the acquired state 915 if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) { 916 mSlots[buf].mBufferState = BufferSlot::FREE; 917 } else if (mSlots[buf].mNeedsCleanupOnRelease) { 918 ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState); 919 mSlots[buf].mNeedsCleanupOnRelease = false; 920 return STALE_BUFFER_SLOT; 921 } else { 922 ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState); 923 return -EINVAL; 924 } 925 926 mDequeueCondition.broadcast(); 927 return OK; 928} 929 930status_t BufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener) { 931 ST_LOGV("consumerConnect"); 932 Mutex::Autolock lock(mMutex); 933 934 if (mAbandoned) { 935 ST_LOGE("consumerConnect: BufferQueue has been abandoned!"); 936 return NO_INIT; 937 } 938 939 mConsumerListener = consumerListener; 940 941 return OK; 942} 943 944status_t BufferQueue::consumerDisconnect() { 945 ST_LOGV("consumerDisconnect"); 946 Mutex::Autolock lock(mMutex); 947 948 if (mConsumerListener == NULL) { 949 ST_LOGE("consumerDisconnect: No consumer is connected!"); 950 return -EINVAL; 951 } 952 953 mAbandoned = true; 954 mConsumerListener = NULL; 955 mQueue.clear(); 956 freeAllBuffersLocked(); 957 mDequeueCondition.broadcast(); 958 return OK; 959} 960 961status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) { 962 ST_LOGV("getReleasedBuffers"); 963 Mutex::Autolock lock(mMutex); 964 965 if (mAbandoned) { 966 ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!"); 967 return NO_INIT; 968 } 969 970 uint32_t mask = 0; 971 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 972 if (!mSlots[i].mAcquireCalled) { 973 mask |= 1 << i; 974 } 975 } 976 *slotMask = mask; 977 978 ST_LOGV("getReleasedBuffers: returning mask %#x", mask); 979 return NO_ERROR; 980} 981 982status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h) 983{ 984 ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h); 985 if (!w || !h) { 986 ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)", 987 w, h); 988 return BAD_VALUE; 989 } 990 991 Mutex::Autolock lock(mMutex); 992 mDefaultWidth = w; 993 mDefaultHeight = h; 994 return OK; 995} 996 997status_t BufferQueue::setBufferCountServer(int bufferCount) { 998 ATRACE_CALL(); 999 Mutex::Autolock lock(mMutex); 1000 return setBufferCountServerLocked(bufferCount); 1001} 1002 1003void BufferQueue::freeAllBuffersExceptHeadLocked() { 1004 int head = -1; 1005 if (!mQueue.empty()) { 1006 Fifo::iterator front(mQueue.begin()); 1007 head = *front; 1008 } 1009 mBufferHasBeenQueued = false; 1010 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 1011 if (i != head) { 1012 freeBufferLocked(i); 1013 } 1014 } 1015} 1016 1017status_t BufferQueue::drainQueueLocked() { 1018 while (mSynchronousMode && !mQueue.isEmpty()) { 1019 mDequeueCondition.wait(mMutex); 1020 if (mAbandoned) { 1021 ST_LOGE("drainQueueLocked: BufferQueue has been abandoned!"); 1022 return NO_INIT; 1023 } 1024 if (mConnectedApi == NO_CONNECTED_API) { 1025 ST_LOGE("drainQueueLocked: BufferQueue is not connected!"); 1026 return NO_INIT; 1027 } 1028 } 1029 return NO_ERROR; 1030} 1031 1032status_t BufferQueue::drainQueueAndFreeBuffersLocked() { 1033 status_t err = drainQueueLocked(); 1034 if (err == NO_ERROR) { 1035 if (mSynchronousMode) { 1036 freeAllBuffersLocked(); 1037 } else { 1038 freeAllBuffersExceptHeadLocked(); 1039 } 1040 } 1041 return err; 1042} 1043 1044BufferQueue::ProxyConsumerListener::ProxyConsumerListener( 1045 const wp<BufferQueue::ConsumerListener>& consumerListener): 1046 mConsumerListener(consumerListener) {} 1047 1048BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {} 1049 1050void BufferQueue::ProxyConsumerListener::onFrameAvailable() { 1051 sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote()); 1052 if (listener != NULL) { 1053 listener->onFrameAvailable(); 1054 } 1055} 1056 1057void BufferQueue::ProxyConsumerListener::onBuffersReleased() { 1058 sp<BufferQueue::ConsumerListener> listener(mConsumerListener.promote()); 1059 if (listener != NULL) { 1060 listener->onBuffersReleased(); 1061 } 1062} 1063 1064}; // namespace android 1065