BufferQueue.cpp revision a4e19521ac4563f2ff6517bcfd63d9b8d33a6d0b
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/IConsumerListener.h> 29#include <gui/ISurfaceComposer.h> 30#include <private/gui/ComposerService.h> 31 32#include <utils/Log.h> 33#include <utils/Trace.h> 34#include <utils/CallStack.h> 35 36// Macros for including the BufferQueue name in log messages 37#define ST_LOGV(x, ...) ALOGV("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 38#define ST_LOGD(x, ...) ALOGD("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 39#define ST_LOGI(x, ...) ALOGI("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 40#define ST_LOGW(x, ...) ALOGW("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 41#define ST_LOGE(x, ...) ALOGE("[%s] "x, mConsumerName.string(), ##__VA_ARGS__) 42 43#define ATRACE_BUFFER_INDEX(index) \ 44 if (ATRACE_ENABLED()) { \ 45 char ___traceBuf[1024]; \ 46 snprintf(___traceBuf, 1024, "%s: %d", mConsumerName.string(), \ 47 (index)); \ 48 android::ScopedTrace ___bufTracer(ATRACE_TAG, ___traceBuf); \ 49 } 50 51namespace android { 52 53// Get an ID that's unique within this process. 54static int32_t createProcessUniqueId() { 55 static volatile int32_t globalCounter = 0; 56 return android_atomic_inc(&globalCounter); 57} 58 59static const char* scalingModeName(int scalingMode) { 60 switch (scalingMode) { 61 case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE"; 62 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW"; 63 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP"; 64 default: return "Unknown"; 65 } 66} 67 68BufferQueue::BufferQueue(const sp<IGraphicBufferAlloc>& allocator) : 69 mDefaultWidth(1), 70 mDefaultHeight(1), 71 mMaxAcquiredBufferCount(1), 72 mDefaultMaxBufferCount(2), 73 mOverrideMaxBufferCount(0), 74 mConsumerControlledByApp(false), 75 mDequeueBufferCannotBlock(false), 76 mUseAsyncBuffer(true), 77 mConnectedApi(NO_CONNECTED_API), 78 mAbandoned(false), 79 mFrameCounter(0), 80 mBufferHasBeenQueued(false), 81 mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888), 82 mConsumerUsageBits(0), 83 mTransformHint(0) 84{ 85 // Choose a name using the PID and a process-unique ID. 86 mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId()); 87 88 ST_LOGV("BufferQueue"); 89 if (allocator == NULL) { 90 sp<ISurfaceComposer> composer(ComposerService::getComposerService()); 91 mGraphicBufferAlloc = composer->createGraphicBufferAlloc(); 92 if (mGraphicBufferAlloc == 0) { 93 ST_LOGE("createGraphicBufferAlloc() failed in BufferQueue()"); 94 } 95 } else { 96 mGraphicBufferAlloc = allocator; 97 } 98} 99 100BufferQueue::~BufferQueue() { 101 ST_LOGV("~BufferQueue"); 102} 103 104status_t BufferQueue::setDefaultMaxBufferCountLocked(int count) { 105 const int minBufferCount = mUseAsyncBuffer ? 2 : 1; 106 if (count < minBufferCount || count > NUM_BUFFER_SLOTS) 107 return BAD_VALUE; 108 109 mDefaultMaxBufferCount = count; 110 mDequeueCondition.broadcast(); 111 112 return NO_ERROR; 113} 114 115void BufferQueue::setConsumerName(const String8& name) { 116 Mutex::Autolock lock(mMutex); 117 mConsumerName = name; 118} 119 120status_t BufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) { 121 Mutex::Autolock lock(mMutex); 122 mDefaultBufferFormat = defaultFormat; 123 return NO_ERROR; 124} 125 126status_t BufferQueue::setConsumerUsageBits(uint32_t usage) { 127 Mutex::Autolock lock(mMutex); 128 mConsumerUsageBits = usage; 129 return NO_ERROR; 130} 131 132status_t BufferQueue::setTransformHint(uint32_t hint) { 133 ST_LOGV("setTransformHint: %02x", hint); 134 Mutex::Autolock lock(mMutex); 135 mTransformHint = hint; 136 return NO_ERROR; 137} 138 139status_t BufferQueue::setBufferCount(int bufferCount) { 140 ST_LOGV("setBufferCount: count=%d", bufferCount); 141 142 sp<IConsumerListener> listener; 143 { 144 Mutex::Autolock lock(mMutex); 145 146 if (mAbandoned) { 147 ST_LOGE("setBufferCount: BufferQueue has been abandoned!"); 148 return NO_INIT; 149 } 150 if (bufferCount > NUM_BUFFER_SLOTS) { 151 ST_LOGE("setBufferCount: bufferCount too large (max %d)", 152 NUM_BUFFER_SLOTS); 153 return BAD_VALUE; 154 } 155 156 // Error out if the user has dequeued buffers 157 for (int i=0 ; i<NUM_BUFFER_SLOTS; i++) { 158 if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) { 159 ST_LOGE("setBufferCount: client owns some buffers"); 160 return -EINVAL; 161 } 162 } 163 164 if (bufferCount == 0) { 165 mOverrideMaxBufferCount = 0; 166 mDequeueCondition.broadcast(); 167 return NO_ERROR; 168 } 169 170 // fine to assume async to false before we're setting the buffer count 171 const int minBufferSlots = getMinMaxBufferCountLocked(false); 172 if (bufferCount < minBufferSlots) { 173 ST_LOGE("setBufferCount: requested buffer count (%d) is less than " 174 "minimum (%d)", bufferCount, minBufferSlots); 175 return BAD_VALUE; 176 } 177 178 // here we're guaranteed that the client doesn't have dequeued buffers 179 // and will release all of its buffer references. We don't clear the 180 // queue, however, so currently queued buffers still get displayed. 181 freeAllBuffersLocked(); 182 mOverrideMaxBufferCount = bufferCount; 183 mDequeueCondition.broadcast(); 184 listener = mConsumerListener; 185 } // scope for lock 186 187 if (listener != NULL) { 188 listener->onBuffersReleased(); 189 } 190 191 return NO_ERROR; 192} 193 194int BufferQueue::query(int what, int* outValue) 195{ 196 ATRACE_CALL(); 197 Mutex::Autolock lock(mMutex); 198 199 if (mAbandoned) { 200 ST_LOGE("query: BufferQueue has been abandoned!"); 201 return NO_INIT; 202 } 203 204 int value; 205 switch (what) { 206 case NATIVE_WINDOW_WIDTH: 207 value = mDefaultWidth; 208 break; 209 case NATIVE_WINDOW_HEIGHT: 210 value = mDefaultHeight; 211 break; 212 case NATIVE_WINDOW_FORMAT: 213 value = mDefaultBufferFormat; 214 break; 215 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS: 216 value = getMinUndequeuedBufferCount(false); 217 break; 218 case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: 219 value = (mQueue.size() >= 2); 220 break; 221 default: 222 return BAD_VALUE; 223 } 224 outValue[0] = value; 225 return NO_ERROR; 226} 227 228status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) { 229 ATRACE_CALL(); 230 ST_LOGV("requestBuffer: slot=%d", slot); 231 Mutex::Autolock lock(mMutex); 232 if (mAbandoned) { 233 ST_LOGE("requestBuffer: BufferQueue has been abandoned!"); 234 return NO_INIT; 235 } 236 if (slot < 0 || slot >= NUM_BUFFER_SLOTS) { 237 ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d", 238 NUM_BUFFER_SLOTS, slot); 239 return BAD_VALUE; 240 } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) { 241 ST_LOGE("requestBuffer: slot %d is not owned by the client (state=%d)", 242 slot, mSlots[slot].mBufferState); 243 return BAD_VALUE; 244 } 245 mSlots[slot].mRequestBufferCalled = true; 246 *buf = mSlots[slot].mGraphicBuffer; 247 return NO_ERROR; 248} 249 250status_t BufferQueue::dequeueBuffer(int *outBuf, sp<Fence>* outFence, bool async, 251 uint32_t w, uint32_t h, uint32_t format, uint32_t usage) { 252 ATRACE_CALL(); 253 ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage); 254 255 if ((w && !h) || (!w && h)) { 256 ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h); 257 return BAD_VALUE; 258 } 259 260 status_t returnFlags(OK); 261 EGLDisplay dpy = EGL_NO_DISPLAY; 262 EGLSyncKHR eglFence = EGL_NO_SYNC_KHR; 263 264 { // Scope for the lock 265 Mutex::Autolock lock(mMutex); 266 267 if (format == 0) { 268 format = mDefaultBufferFormat; 269 } 270 // turn on usage bits the consumer requested 271 usage |= mConsumerUsageBits; 272 273 int found = -1; 274 bool tryAgain = true; 275 while (tryAgain) { 276 if (mAbandoned) { 277 ST_LOGE("dequeueBuffer: BufferQueue has been abandoned!"); 278 return NO_INIT; 279 } 280 281 const int maxBufferCount = getMaxBufferCountLocked(async); 282 if (async && mOverrideMaxBufferCount) { 283 // FIXME: some drivers are manually setting the buffer-count (which they 284 // shouldn't), so we do this extra test here to handle that case. 285 // This is TEMPORARY, until we get this fixed. 286 if (mOverrideMaxBufferCount < maxBufferCount) { 287 ST_LOGE("dequeueBuffer: async mode is invalid with buffercount override"); 288 return BAD_VALUE; 289 } 290 } 291 292 // Free up any buffers that are in slots beyond the max buffer 293 // count. 294 for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) { 295 assert(mSlots[i].mBufferState == BufferSlot::FREE); 296 if (mSlots[i].mGraphicBuffer != NULL) { 297 freeBufferLocked(i); 298 returnFlags |= IGraphicBufferProducer::RELEASE_ALL_BUFFERS; 299 } 300 } 301 302 // look for a free buffer to give to the client 303 found = INVALID_BUFFER_SLOT; 304 int dequeuedCount = 0; 305 int acquiredCount = 0; 306 for (int i = 0; i < maxBufferCount; i++) { 307 const int state = mSlots[i].mBufferState; 308 switch (state) { 309 case BufferSlot::DEQUEUED: 310 dequeuedCount++; 311 break; 312 case BufferSlot::ACQUIRED: 313 acquiredCount++; 314 break; 315 case BufferSlot::FREE: 316 /* We return the oldest of the free buffers to avoid 317 * stalling the producer if possible. This is because 318 * the consumer may still have pending reads of the 319 * buffers in flight. 320 */ 321 if ((found < 0) || 322 mSlots[i].mFrameNumber < mSlots[found].mFrameNumber) { 323 found = i; 324 } 325 break; 326 } 327 } 328 329 // clients are not allowed to dequeue more than one buffer 330 // if they didn't set a buffer count. 331 if (!mOverrideMaxBufferCount && dequeuedCount) { 332 ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without " 333 "setting the buffer count"); 334 return -EINVAL; 335 } 336 337 // See whether a buffer has been queued since the last 338 // setBufferCount so we know whether to perform the min undequeued 339 // buffers check below. 340 if (mBufferHasBeenQueued) { 341 // make sure the client is not trying to dequeue more buffers 342 // than allowed. 343 const int newUndequeuedCount = maxBufferCount - (dequeuedCount+1); 344 const int minUndequeuedCount = getMinUndequeuedBufferCount(async); 345 if (newUndequeuedCount < minUndequeuedCount) { 346 ST_LOGE("dequeueBuffer: min undequeued buffer count (%d) " 347 "exceeded (dequeued=%d undequeudCount=%d)", 348 minUndequeuedCount, dequeuedCount, 349 newUndequeuedCount); 350 return -EBUSY; 351 } 352 } 353 354 // If no buffer is found, wait for a buffer to be released or for 355 // the max buffer count to change. 356 tryAgain = found == INVALID_BUFFER_SLOT; 357 if (tryAgain) { 358 // return an error if we're in "cannot block" mode (producer and consumer 359 // are controlled by the application) -- however, the consumer is allowed 360 // to acquire briefly an extra buffer (which could cause us to have to wait here) 361 // and that's okay because we know the wait will be brief (it happens 362 // if we dequeue a buffer while the consumer has acquired one but not released 363 // the old one yet -- for e.g.: see GLConsumer::updateTexImage()). 364 if (mDequeueBufferCannotBlock && (acquiredCount <= mMaxAcquiredBufferCount)) { 365 ST_LOGE("dequeueBuffer: would block! returning an error instead."); 366 return WOULD_BLOCK; 367 } 368 mDequeueCondition.wait(mMutex); 369 } 370 } 371 372 373 if (found == INVALID_BUFFER_SLOT) { 374 // This should not happen. 375 ST_LOGE("dequeueBuffer: no available buffer slots"); 376 return -EBUSY; 377 } 378 379 const int buf = found; 380 *outBuf = found; 381 382 ATRACE_BUFFER_INDEX(buf); 383 384 const bool useDefaultSize = !w && !h; 385 if (useDefaultSize) { 386 // use the default size 387 w = mDefaultWidth; 388 h = mDefaultHeight; 389 } 390 391 mSlots[buf].mBufferState = BufferSlot::DEQUEUED; 392 393 const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer); 394 if ((buffer == NULL) || 395 (uint32_t(buffer->width) != w) || 396 (uint32_t(buffer->height) != h) || 397 (uint32_t(buffer->format) != format) || 398 ((uint32_t(buffer->usage) & usage) != usage)) 399 { 400 mSlots[buf].mAcquireCalled = false; 401 mSlots[buf].mGraphicBuffer = NULL; 402 mSlots[buf].mRequestBufferCalled = false; 403 mSlots[buf].mEglFence = EGL_NO_SYNC_KHR; 404 mSlots[buf].mFence = Fence::NO_FENCE; 405 mSlots[buf].mEglDisplay = EGL_NO_DISPLAY; 406 407 returnFlags |= IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION; 408 } 409 410 411 if (CC_UNLIKELY(mSlots[buf].mFence == NULL)) { 412 ST_LOGE("dequeueBuffer: about to return a NULL fence from mSlot. " 413 "buf=%d, w=%d, h=%d, format=%d", 414 buf, buffer->width, buffer->height, buffer->format); 415 } 416 417 dpy = mSlots[buf].mEglDisplay; 418 eglFence = mSlots[buf].mEglFence; 419 *outFence = mSlots[buf].mFence; 420 mSlots[buf].mEglFence = EGL_NO_SYNC_KHR; 421 mSlots[buf].mFence = Fence::NO_FENCE; 422 } // end lock scope 423 424 if (returnFlags & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) { 425 status_t error; 426 sp<GraphicBuffer> graphicBuffer( 427 mGraphicBufferAlloc->createGraphicBuffer(w, h, format, usage, &error)); 428 if (graphicBuffer == 0) { 429 ST_LOGE("dequeueBuffer: SurfaceComposer::createGraphicBuffer failed"); 430 return error; 431 } 432 433 { // Scope for the lock 434 Mutex::Autolock lock(mMutex); 435 436 if (mAbandoned) { 437 ST_LOGE("dequeueBuffer: BufferQueue has been abandoned!"); 438 return NO_INIT; 439 } 440 441 mSlots[*outBuf].mFrameNumber = ~0; 442 mSlots[*outBuf].mGraphicBuffer = graphicBuffer; 443 } 444 } 445 446 if (eglFence != EGL_NO_SYNC_KHR) { 447 EGLint result = eglClientWaitSyncKHR(dpy, eglFence, 0, 1000000000); 448 // If something goes wrong, log the error, but return the buffer without 449 // synchronizing access to it. It's too late at this point to abort the 450 // dequeue operation. 451 if (result == EGL_FALSE) { 452 ST_LOGE("dequeueBuffer: error waiting for fence: %#x", eglGetError()); 453 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) { 454 ST_LOGE("dequeueBuffer: timeout waiting for fence"); 455 } 456 eglDestroySyncKHR(dpy, eglFence); 457 } 458 459 ST_LOGV("dequeueBuffer: returning slot=%d/%llu buf=%p flags=%#x", *outBuf, 460 mSlots[*outBuf].mFrameNumber, 461 mSlots[*outBuf].mGraphicBuffer->handle, returnFlags); 462 463 return returnFlags; 464} 465 466status_t BufferQueue::queueBuffer(int buf, 467 const QueueBufferInput& input, QueueBufferOutput* output) { 468 ATRACE_CALL(); 469 ATRACE_BUFFER_INDEX(buf); 470 471 Rect crop; 472 uint32_t transform; 473 int scalingMode; 474 int64_t timestamp; 475 bool async; 476 sp<Fence> fence; 477 478 input.deflate(×tamp, &crop, &scalingMode, &transform, &async, &fence); 479 480 if (fence == NULL) { 481 ST_LOGE("queueBuffer: fence is NULL"); 482 return BAD_VALUE; 483 } 484 485 switch (scalingMode) { 486 case NATIVE_WINDOW_SCALING_MODE_FREEZE: 487 case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: 488 case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: 489 case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP: 490 break; 491 default: 492 ST_LOGE("unknown scaling mode: %d", scalingMode); 493 return -EINVAL; 494 } 495 496 sp<IConsumerListener> listener; 497 498 { // scope for the lock 499 Mutex::Autolock lock(mMutex); 500 501 if (mAbandoned) { 502 ST_LOGE("queueBuffer: BufferQueue has been abandoned!"); 503 return NO_INIT; 504 } 505 506 const int maxBufferCount = getMaxBufferCountLocked(async); 507 if (async && mOverrideMaxBufferCount) { 508 // FIXME: some drivers are manually setting the buffer-count (which they 509 // shouldn't), so we do this extra test here to handle that case. 510 // This is TEMPORARY, until we get this fixed. 511 if (mOverrideMaxBufferCount < maxBufferCount) { 512 ST_LOGE("queueBuffer: async mode is invalid with buffercount override"); 513 return BAD_VALUE; 514 } 515 } 516 if (buf < 0 || buf >= maxBufferCount) { 517 ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d", 518 maxBufferCount, buf); 519 return -EINVAL; 520 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) { 521 ST_LOGE("queueBuffer: slot %d is not owned by the client " 522 "(state=%d)", buf, mSlots[buf].mBufferState); 523 return -EINVAL; 524 } else if (!mSlots[buf].mRequestBufferCalled) { 525 ST_LOGE("queueBuffer: slot %d was enqueued without requesting a " 526 "buffer", buf); 527 return -EINVAL; 528 } 529 530 ST_LOGV("queueBuffer: slot=%d/%llu time=%#llx crop=[%d,%d,%d,%d] " 531 "tr=%#x scale=%s", 532 buf, mFrameCounter + 1, timestamp, 533 crop.left, crop.top, crop.right, crop.bottom, 534 transform, scalingModeName(scalingMode)); 535 536 const sp<GraphicBuffer>& graphicBuffer(mSlots[buf].mGraphicBuffer); 537 Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight()); 538 Rect croppedCrop; 539 crop.intersect(bufferRect, &croppedCrop); 540 if (croppedCrop != crop) { 541 ST_LOGE("queueBuffer: crop rect is not contained within the " 542 "buffer in slot %d", buf); 543 return -EINVAL; 544 } 545 546 mSlots[buf].mFence = fence; 547 mSlots[buf].mBufferState = BufferSlot::QUEUED; 548 mFrameCounter++; 549 mSlots[buf].mFrameNumber = mFrameCounter; 550 551 BufferItem item; 552 item.mAcquireCalled = mSlots[buf].mAcquireCalled; 553 item.mGraphicBuffer = mSlots[buf].mGraphicBuffer; 554 item.mCrop = crop; 555 item.mTransform = transform; 556 item.mScalingMode = scalingMode; 557 item.mTimestamp = timestamp; 558 item.mFrameNumber = mFrameCounter; 559 item.mBuf = buf; 560 item.mFence = fence; 561 item.mIsDroppable = mDequeueBufferCannotBlock || async; 562 563 if (mQueue.empty()) { 564 // when the queue is empty, we can ignore "mDequeueBufferCannotBlock", and 565 // simply queue this buffer. 566 mQueue.push_back(item); 567 listener = mConsumerListener; 568 } else { 569 // when the queue is not empty, we need to look at the front buffer 570 // state and see if we need to replace it. 571 Fifo::iterator front(mQueue.begin()); 572 if (front->mIsDroppable) { 573 // buffer slot currently queued is marked free if still tracked 574 if (stillTracking(front)) { 575 mSlots[front->mBuf].mBufferState = BufferSlot::FREE; 576 // reset the frame number of the freed buffer so that it is the first in 577 // line to be dequeued again. 578 mSlots[front->mBuf].mFrameNumber = 0; 579 } 580 // and we record the new buffer in the queued list 581 *front = item; 582 } else { 583 mQueue.push_back(item); 584 listener = mConsumerListener; 585 } 586 } 587 588 mBufferHasBeenQueued = true; 589 mDequeueCondition.broadcast(); 590 591 output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint, 592 mQueue.size()); 593 594 ATRACE_INT(mConsumerName.string(), mQueue.size()); 595 } // scope for the lock 596 597 // call back without lock held 598 if (listener != 0) { 599 listener->onFrameAvailable(); 600 } 601 return NO_ERROR; 602} 603 604void BufferQueue::cancelBuffer(int buf, const sp<Fence>& fence) { 605 ATRACE_CALL(); 606 ST_LOGV("cancelBuffer: slot=%d", buf); 607 Mutex::Autolock lock(mMutex); 608 609 if (mAbandoned) { 610 ST_LOGW("cancelBuffer: BufferQueue has been abandoned!"); 611 return; 612 } 613 614 if (buf < 0 || buf >= NUM_BUFFER_SLOTS) { 615 ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d", 616 NUM_BUFFER_SLOTS, buf); 617 return; 618 } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) { 619 ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)", 620 buf, mSlots[buf].mBufferState); 621 return; 622 } else if (fence == NULL) { 623 ST_LOGE("cancelBuffer: fence is NULL"); 624 return; 625 } 626 mSlots[buf].mBufferState = BufferSlot::FREE; 627 mSlots[buf].mFrameNumber = 0; 628 mSlots[buf].mFence = fence; 629 mDequeueCondition.broadcast(); 630} 631 632status_t BufferQueue::connect(int api, bool producerControlledByApp, QueueBufferOutput* output) { 633 ATRACE_CALL(); 634 ST_LOGV("connect: api=%d", api); 635 Mutex::Autolock lock(mMutex); 636 637 if (mAbandoned) { 638 ST_LOGE("connect: BufferQueue has been abandoned!"); 639 return NO_INIT; 640 } 641 642 if (mConsumerListener == NULL) { 643 ST_LOGE("connect: BufferQueue has no consumer!"); 644 return NO_INIT; 645 } 646 647 int err = NO_ERROR; 648 switch (api) { 649 case NATIVE_WINDOW_API_EGL: 650 case NATIVE_WINDOW_API_CPU: 651 case NATIVE_WINDOW_API_MEDIA: 652 case NATIVE_WINDOW_API_CAMERA: 653 if (mConnectedApi != NO_CONNECTED_API) { 654 ST_LOGE("connect: already connected (cur=%d, req=%d)", 655 mConnectedApi, api); 656 err = -EINVAL; 657 } else { 658 mConnectedApi = api; 659 output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint, 660 mQueue.size()); 661 } 662 break; 663 default: 664 err = -EINVAL; 665 break; 666 } 667 668 mBufferHasBeenQueued = false; 669 mDequeueBufferCannotBlock = mConsumerControlledByApp && producerControlledByApp; 670 671 return err; 672} 673 674status_t BufferQueue::disconnect(int api) { 675 ATRACE_CALL(); 676 ST_LOGV("disconnect: api=%d", api); 677 678 int err = NO_ERROR; 679 sp<IConsumerListener> listener; 680 681 { // Scope for the lock 682 Mutex::Autolock lock(mMutex); 683 684 if (mAbandoned) { 685 // it is not really an error to disconnect after the surface 686 // has been abandoned, it should just be a no-op. 687 return NO_ERROR; 688 } 689 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 == api) { 696 freeAllBuffersLocked(); 697 mConnectedApi = NO_CONNECTED_API; 698 mDequeueCondition.broadcast(); 699 listener = mConsumerListener; 700 } else { 701 ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)", 702 mConnectedApi, api); 703 err = -EINVAL; 704 } 705 break; 706 default: 707 ST_LOGE("disconnect: unknown API %d", api); 708 err = -EINVAL; 709 break; 710 } 711 } 712 713 if (listener != NULL) { 714 listener->onBuffersReleased(); 715 } 716 717 return err; 718} 719 720void BufferQueue::dump(String8& result) const { 721 BufferQueue::dump(result, ""); 722} 723 724void BufferQueue::dump(String8& result, const char* prefix) const { 725 Mutex::Autolock _l(mMutex); 726 727 String8 fifo; 728 int fifoSize = 0; 729 Fifo::const_iterator i(mQueue.begin()); 730 while (i != mQueue.end()) { 731 fifo.appendFormat("%02d:%p crop=[%d,%d,%d,%d], " 732 "xform=0x%02x, time=%#llx, scale=%s\n", 733 i->mBuf, i->mGraphicBuffer.get(), 734 i->mCrop.left, i->mCrop.top, i->mCrop.right, 735 i->mCrop.bottom, i->mTransform, i->mTimestamp, 736 scalingModeName(i->mScalingMode) 737 ); 738 i++; 739 fifoSize++; 740 } 741 742 743 result.appendFormat( 744 "%s-BufferQueue mMaxAcquiredBufferCount=%d, mDequeueBufferCannotBlock=%d, default-size=[%dx%d], " 745 "default-format=%d, transform-hint=%02x, FIFO(%d)={%s}\n", 746 prefix, mMaxAcquiredBufferCount, mDequeueBufferCannotBlock, mDefaultWidth, 747 mDefaultHeight, mDefaultBufferFormat, mTransformHint, 748 fifoSize, fifo.string()); 749 750 struct { 751 const char * operator()(int state) const { 752 switch (state) { 753 case BufferSlot::DEQUEUED: return "DEQUEUED"; 754 case BufferSlot::QUEUED: return "QUEUED"; 755 case BufferSlot::FREE: return "FREE"; 756 case BufferSlot::ACQUIRED: return "ACQUIRED"; 757 default: return "Unknown"; 758 } 759 } 760 } stateName; 761 762 // just trim the free buffers to not spam the dump 763 int maxBufferCount = 0; 764 for (int i=NUM_BUFFER_SLOTS-1 ; i>=0 ; i--) { 765 const BufferSlot& slot(mSlots[i]); 766 if ((slot.mBufferState != BufferSlot::FREE) || (slot.mGraphicBuffer != NULL)) { 767 maxBufferCount = i+1; 768 break; 769 } 770 } 771 772 for (int i=0 ; i<maxBufferCount ; i++) { 773 const BufferSlot& slot(mSlots[i]); 774 const sp<GraphicBuffer>& buf(slot.mGraphicBuffer); 775 result.appendFormat( 776 "%s%s[%02d:%p] state=%-8s", 777 prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i, buf.get(), 778 stateName(slot.mBufferState) 779 ); 780 781 if (buf != NULL) { 782 result.appendFormat( 783 ", %p [%4ux%4u:%4u,%3X]", 784 buf->handle, buf->width, buf->height, buf->stride, 785 buf->format); 786 } 787 result.append("\n"); 788 } 789} 790 791void BufferQueue::freeBufferLocked(int slot) { 792 ST_LOGV("freeBufferLocked: slot=%d", slot); 793 mSlots[slot].mGraphicBuffer = 0; 794 if (mSlots[slot].mBufferState == BufferSlot::ACQUIRED) { 795 mSlots[slot].mNeedsCleanupOnRelease = true; 796 } 797 mSlots[slot].mBufferState = BufferSlot::FREE; 798 mSlots[slot].mFrameNumber = 0; 799 mSlots[slot].mAcquireCalled = false; 800 801 // destroy fence as BufferQueue now takes ownership 802 if (mSlots[slot].mEglFence != EGL_NO_SYNC_KHR) { 803 eglDestroySyncKHR(mSlots[slot].mEglDisplay, mSlots[slot].mEglFence); 804 mSlots[slot].mEglFence = EGL_NO_SYNC_KHR; 805 } 806 mSlots[slot].mFence = Fence::NO_FENCE; 807} 808 809void BufferQueue::freeAllBuffersLocked() { 810 mBufferHasBeenQueued = false; 811 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 812 freeBufferLocked(i); 813 } 814} 815 816status_t BufferQueue::acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) { 817 ATRACE_CALL(); 818 Mutex::Autolock _l(mMutex); 819 820 // Check that the consumer doesn't currently have the maximum number of 821 // buffers acquired. We allow the max buffer count to be exceeded by one 822 // buffer, so that the consumer can successfully set up the newly acquired 823 // buffer before releasing the old one. 824 int numAcquiredBuffers = 0; 825 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 826 if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) { 827 numAcquiredBuffers++; 828 } 829 } 830 if (numAcquiredBuffers >= mMaxAcquiredBufferCount+1) { 831 ST_LOGE("acquireBuffer: max acquired buffer count reached: %d (max=%d)", 832 numAcquiredBuffers, mMaxAcquiredBufferCount); 833 return INVALID_OPERATION; 834 } 835 836 // check if queue is empty 837 // In asynchronous mode the list is guaranteed to be one buffer 838 // deep, while in synchronous mode we use the oldest buffer. 839 if (mQueue.empty()) { 840 return NO_BUFFER_AVAILABLE; 841 } 842 843 Fifo::iterator front(mQueue.begin()); 844 int buf = front->mBuf; 845 846 // Compare the buffer's desired presentation time to the predicted 847 // actual display time. 848 // 849 // The "presentWhen" argument indicates when the buffer is expected 850 // to be presented on-screen. If the buffer's desired-present time 851 // is earlier (less) than presentWhen, meaning it'll be displayed 852 // on time or possibly late, we acquire and return it. If we don't want 853 // to display it until after the presentWhen time, we return PRESENT_LATER 854 // without acquiring it. 855 // 856 // To be safe, we don't refuse to acquire the buffer if presentWhen is 857 // more than one second in the future beyond the desired present time 858 // (i.e. we'd be holding the buffer for a really long time). 859 const int MAX_FUTURE_NSEC = 1000000000ULL; 860 nsecs_t desiredPresent = front->mTimestamp; 861 if (presentWhen != 0 && desiredPresent > presentWhen && 862 desiredPresent - presentWhen < MAX_FUTURE_NSEC) 863 { 864 ST_LOGV("pts defer: des=%lld when=%lld (%lld) now=%lld", 865 desiredPresent, presentWhen, desiredPresent - presentWhen, 866 systemTime(CLOCK_MONOTONIC)); 867 return PRESENT_LATER; 868 } 869 if (presentWhen != 0) { 870 ST_LOGV("pts accept: %p[%d] sig=%lld des=%lld when=%lld (%lld)", 871 mSlots, buf, mSlots[buf].mFence->getSignalTime(), 872 desiredPresent, presentWhen, desiredPresent - presentWhen); 873 } 874 875 *buffer = *front; 876 ATRACE_BUFFER_INDEX(buf); 877 878 ST_LOGV("acquireBuffer: acquiring { slot=%d/%llu, buffer=%p }", 879 front->mBuf, front->mFrameNumber, 880 front->mGraphicBuffer->handle); 881 // if front buffer still being tracked update slot state 882 if (stillTracking(front)) { 883 mSlots[buf].mAcquireCalled = true; 884 mSlots[buf].mNeedsCleanupOnRelease = false; 885 mSlots[buf].mBufferState = BufferSlot::ACQUIRED; 886 mSlots[buf].mFence = Fence::NO_FENCE; 887 } 888 889 // If the buffer has previously been acquired by the consumer, set 890 // mGraphicBuffer to NULL to avoid unnecessarily remapping this 891 // buffer on the consumer side. 892 if (buffer->mAcquireCalled) { 893 buffer->mGraphicBuffer = NULL; 894 } 895 896 mQueue.erase(front); 897 mDequeueCondition.broadcast(); 898 899 ATRACE_INT(mConsumerName.string(), mQueue.size()); 900 901 return NO_ERROR; 902} 903 904status_t BufferQueue::releaseBuffer( 905 int buf, uint64_t frameNumber, EGLDisplay display, 906 EGLSyncKHR eglFence, const sp<Fence>& fence) { 907 ATRACE_CALL(); 908 ATRACE_BUFFER_INDEX(buf); 909 910 if (buf == INVALID_BUFFER_SLOT || fence == NULL) { 911 return BAD_VALUE; 912 } 913 914 Mutex::Autolock _l(mMutex); 915 916 // If the frame number has changed because buffer has been reallocated, 917 // we can ignore this releaseBuffer for the old buffer. 918 if (frameNumber != mSlots[buf].mFrameNumber) { 919 return STALE_BUFFER_SLOT; 920 } 921 922 923 // Internal state consistency checks: 924 // Make sure this buffers hasn't been queued while we were owning it (acquired) 925 Fifo::iterator front(mQueue.begin()); 926 Fifo::const_iterator const end(mQueue.end()); 927 while (front != end) { 928 if (front->mBuf == buf) { 929 LOG_ALWAYS_FATAL("[%s] received new buffer(#%lld) on slot #%d that has not yet been " 930 "acquired", mConsumerName.string(), frameNumber, buf); 931 break; // never reached 932 } 933 front++; 934 } 935 936 // The buffer can now only be released if its in the acquired state 937 if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) { 938 mSlots[buf].mEglDisplay = display; 939 mSlots[buf].mEglFence = eglFence; 940 mSlots[buf].mFence = fence; 941 mSlots[buf].mBufferState = BufferSlot::FREE; 942 } else if (mSlots[buf].mNeedsCleanupOnRelease) { 943 ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState); 944 mSlots[buf].mNeedsCleanupOnRelease = false; 945 return STALE_BUFFER_SLOT; 946 } else { 947 ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState); 948 return -EINVAL; 949 } 950 951 mDequeueCondition.broadcast(); 952 return NO_ERROR; 953} 954 955status_t BufferQueue::consumerConnect(const sp<IConsumerListener>& consumerListener, 956 bool controlledByApp) { 957 ST_LOGV("consumerConnect"); 958 Mutex::Autolock lock(mMutex); 959 960 if (mAbandoned) { 961 ST_LOGE("consumerConnect: BufferQueue has been abandoned!"); 962 return NO_INIT; 963 } 964 if (consumerListener == NULL) { 965 ST_LOGE("consumerConnect: consumerListener may not be NULL"); 966 return BAD_VALUE; 967 } 968 969 mConsumerListener = consumerListener; 970 mConsumerControlledByApp = controlledByApp; 971 972 return NO_ERROR; 973} 974 975status_t BufferQueue::consumerDisconnect() { 976 ST_LOGV("consumerDisconnect"); 977 Mutex::Autolock lock(mMutex); 978 979 if (mConsumerListener == NULL) { 980 ST_LOGE("consumerDisconnect: No consumer is connected!"); 981 return -EINVAL; 982 } 983 984 mAbandoned = true; 985 mConsumerListener = NULL; 986 mQueue.clear(); 987 freeAllBuffersLocked(); 988 mDequeueCondition.broadcast(); 989 return NO_ERROR; 990} 991 992status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) { 993 ST_LOGV("getReleasedBuffers"); 994 Mutex::Autolock lock(mMutex); 995 996 if (mAbandoned) { 997 ST_LOGE("getReleasedBuffers: BufferQueue has been abandoned!"); 998 return NO_INIT; 999 } 1000 1001 uint32_t mask = 0; 1002 for (int i = 0; i < NUM_BUFFER_SLOTS; i++) { 1003 if (!mSlots[i].mAcquireCalled) { 1004 mask |= 1 << i; 1005 } 1006 } 1007 1008 // Remove buffers in flight (on the queue) from the mask where acquire has 1009 // been called, as the consumer will not receive the buffer address, so 1010 // it should not free these slots. 1011 Fifo::iterator front(mQueue.begin()); 1012 while (front != mQueue.end()) { 1013 if (front->mAcquireCalled) 1014 mask &= ~(1 << front->mBuf); 1015 front++; 1016 } 1017 1018 *slotMask = mask; 1019 1020 ST_LOGV("getReleasedBuffers: returning mask %#x", mask); 1021 return NO_ERROR; 1022} 1023 1024status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h) { 1025 ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h); 1026 if (!w || !h) { 1027 ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)", 1028 w, h); 1029 return BAD_VALUE; 1030 } 1031 1032 Mutex::Autolock lock(mMutex); 1033 mDefaultWidth = w; 1034 mDefaultHeight = h; 1035 return NO_ERROR; 1036} 1037 1038status_t BufferQueue::setDefaultMaxBufferCount(int bufferCount) { 1039 ATRACE_CALL(); 1040 Mutex::Autolock lock(mMutex); 1041 return setDefaultMaxBufferCountLocked(bufferCount); 1042} 1043 1044status_t BufferQueue::disableAsyncBuffer() { 1045 ATRACE_CALL(); 1046 Mutex::Autolock lock(mMutex); 1047 if (mConsumerListener != NULL) { 1048 ST_LOGE("disableAsyncBuffer: consumer already connected!"); 1049 return INVALID_OPERATION; 1050 } 1051 mUseAsyncBuffer = false; 1052 return NO_ERROR; 1053} 1054 1055status_t BufferQueue::setMaxAcquiredBufferCount(int maxAcquiredBuffers) { 1056 ATRACE_CALL(); 1057 Mutex::Autolock lock(mMutex); 1058 if (maxAcquiredBuffers < 1 || maxAcquiredBuffers > MAX_MAX_ACQUIRED_BUFFERS) { 1059 ST_LOGE("setMaxAcquiredBufferCount: invalid count specified: %d", 1060 maxAcquiredBuffers); 1061 return BAD_VALUE; 1062 } 1063 if (mConnectedApi != NO_CONNECTED_API) { 1064 return INVALID_OPERATION; 1065 } 1066 mMaxAcquiredBufferCount = maxAcquiredBuffers; 1067 return NO_ERROR; 1068} 1069 1070int BufferQueue::getMinUndequeuedBufferCount(bool async) const { 1071 // if dequeueBuffer is allowed to error out, we don't have to 1072 // add an extra buffer. 1073 if (!mUseAsyncBuffer) 1074 return mMaxAcquiredBufferCount; 1075 1076 // we're in async mode, or we want to prevent the app to 1077 // deadlock itself, we throw-in an extra buffer to guarantee it. 1078 if (mDequeueBufferCannotBlock || async) 1079 return mMaxAcquiredBufferCount+1; 1080 1081 return mMaxAcquiredBufferCount; 1082} 1083 1084int BufferQueue::getMinMaxBufferCountLocked(bool async) const { 1085 return getMinUndequeuedBufferCount(async) + 1; 1086} 1087 1088int BufferQueue::getMaxBufferCountLocked(bool async) const { 1089 int minMaxBufferCount = getMinMaxBufferCountLocked(async); 1090 1091 int maxBufferCount = mDefaultMaxBufferCount; 1092 if (maxBufferCount < minMaxBufferCount) { 1093 maxBufferCount = minMaxBufferCount; 1094 } 1095 if (mOverrideMaxBufferCount != 0) { 1096 assert(mOverrideMaxBufferCount >= minMaxBufferCount); 1097 maxBufferCount = mOverrideMaxBufferCount; 1098 } 1099 1100 // Any buffers that are dequeued by the producer or sitting in the queue 1101 // waiting to be consumed need to have their slots preserved. Such 1102 // buffers will temporarily keep the max buffer count up until the slots 1103 // no longer need to be preserved. 1104 for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) { 1105 BufferSlot::BufferState state = mSlots[i].mBufferState; 1106 if (state == BufferSlot::QUEUED || state == BufferSlot::DEQUEUED) { 1107 maxBufferCount = i + 1; 1108 } 1109 } 1110 1111 return maxBufferCount; 1112} 1113 1114bool BufferQueue::stillTracking(const BufferItem *item) const { 1115 const BufferSlot &slot = mSlots[item->mBuf]; 1116 1117 ST_LOGV("stillTracking?: item: { slot=%d/%llu, buffer=%p }, " 1118 "slot: { slot=%d/%llu, buffer=%p }", 1119 item->mBuf, item->mFrameNumber, 1120 (item->mGraphicBuffer.get() ? item->mGraphicBuffer->handle : 0), 1121 item->mBuf, slot.mFrameNumber, 1122 (slot.mGraphicBuffer.get() ? slot.mGraphicBuffer->handle : 0)); 1123 1124 // Compare item with its original buffer slot. We can check the slot 1125 // as the buffer would not be moved to a different slot by the producer. 1126 return (slot.mGraphicBuffer != NULL && 1127 item->mGraphicBuffer->handle == slot.mGraphicBuffer->handle); 1128} 1129 1130BufferQueue::ProxyConsumerListener::ProxyConsumerListener( 1131 const wp<ConsumerListener>& consumerListener): 1132 mConsumerListener(consumerListener) {} 1133 1134BufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {} 1135 1136void BufferQueue::ProxyConsumerListener::onFrameAvailable() { 1137 sp<ConsumerListener> listener(mConsumerListener.promote()); 1138 if (listener != NULL) { 1139 listener->onFrameAvailable(); 1140 } 1141} 1142 1143void BufferQueue::ProxyConsumerListener::onBuffersReleased() { 1144 sp<ConsumerListener> listener(mConsumerListener.promote()); 1145 if (listener != NULL) { 1146 listener->onBuffersReleased(); 1147 } 1148} 1149 1150}; // namespace android 1151