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