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