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