BufferQueue.h revision 72f096fb1ad0a0deadbfac5f88627461905d38e8
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#ifndef ANDROID_GUI_BUFFERQUEUE_H 18#define ANDROID_GUI_BUFFERQUEUE_H 19 20#include <EGL/egl.h> 21#include <EGL/eglext.h> 22 23#include <gui/IGraphicBufferAlloc.h> 24#include <gui/ISurfaceTexture.h> 25 26#include <ui/Fence.h> 27#include <ui/GraphicBuffer.h> 28 29#include <utils/String8.h> 30#include <utils/Vector.h> 31#include <utils/threads.h> 32 33namespace android { 34// ---------------------------------------------------------------------------- 35 36class BufferQueue : public BnSurfaceTexture { 37public: 38 enum { MIN_UNDEQUEUED_BUFFERS = 2 }; 39 enum { NUM_BUFFER_SLOTS = 32 }; 40 enum { NO_CONNECTED_API = 0 }; 41 enum { INVALID_BUFFER_SLOT = -1 }; 42 enum { STALE_BUFFER_SLOT = 1, NO_BUFFER_AVAILABLE }; 43 44 // ConsumerListener is the interface through which the BufferQueue notifies 45 // the consumer of events that the consumer may wish to react to. Because 46 // the consumer will generally have a mutex that is locked during calls from 47 // teh consumer to the BufferQueue, these calls from the BufferQueue to the 48 // consumer *MUST* be called only when the BufferQueue mutex is NOT locked. 49 struct ConsumerListener : public virtual RefBase { 50 // onFrameAvailable is called from queueBuffer each time an additional 51 // frame becomes available for consumption. This means that frames that 52 // are queued while in asynchronous mode only trigger the callback if no 53 // previous frames are pending. Frames queued while in synchronous mode 54 // always trigger the callback. 55 // 56 // This is called without any lock held and can be called concurrently 57 // by multiple threads. 58 virtual void onFrameAvailable() = 0; 59 60 // onBuffersReleased is called to notify the buffer consumer that the 61 // BufferQueue has released its references to one or more GraphicBuffers 62 // contained in its slots. The buffer consumer should then call 63 // BufferQueue::getReleasedBuffers to retrieve the list of buffers 64 // 65 // This is called without any lock held and can be called concurrently 66 // by multiple threads. 67 virtual void onBuffersReleased() = 0; 68 }; 69 70 // ProxyConsumerListener is a ConsumerListener implementation that keeps a weak 71 // reference to the actual consumer object. It forwards all calls to that 72 // consumer object so long as it exists. 73 // 74 // This class exists to avoid having a circular reference between the 75 // BufferQueue object and the consumer object. The reason this can't be a weak 76 // reference in the BufferQueue class is because we're planning to expose the 77 // consumer side of a BufferQueue as a binder interface, which doesn't support 78 // weak references. 79 class ProxyConsumerListener : public BufferQueue::ConsumerListener { 80 public: 81 82 ProxyConsumerListener(const wp<BufferQueue::ConsumerListener>& consumerListener); 83 virtual ~ProxyConsumerListener(); 84 virtual void onFrameAvailable(); 85 virtual void onBuffersReleased(); 86 87 private: 88 89 // mConsumerListener is a weak reference to the ConsumerListener. This is 90 // the raison d'etre of ProxyConsumerListener. 91 wp<BufferQueue::ConsumerListener> mConsumerListener; 92 }; 93 94 95 // BufferQueue manages a pool of gralloc memory slots to be used by 96 // producers and consumers. allowSynchronousMode specifies whether or not 97 // synchronous mode can be enabled by the producer. allocator is used to 98 // allocate all the needed gralloc buffers. 99 BufferQueue(bool allowSynchronousMode = true, 100 const sp<IGraphicBufferAlloc>& allocator = NULL); 101 virtual ~BufferQueue(); 102 103 virtual int query(int what, int* value); 104 105 // setBufferCount updates the number of available buffer slots. After 106 // calling this all buffer slots are both unallocated and owned by the 107 // BufferQueue object (i.e. they are not owned by the client). 108 virtual status_t setBufferCount(int bufferCount); 109 110 virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf); 111 112 // dequeueBuffer gets the next buffer slot index for the client to use. If a 113 // buffer slot is available then that slot index is written to the location 114 // pointed to by the buf argument and a status of OK is returned. If no 115 // slot is available then a status of -EBUSY is returned and buf is 116 // unmodified. 117 // 118 // The fence parameter will be updated to hold the fence associated with 119 // the buffer. The contents of the buffer must not be overwritten until the 120 // fence signals. If the fence is NULL, the buffer may be written 121 // immediately. 122 // 123 // The width and height parameters must be no greater than the minimum of 124 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv). 125 // An error due to invalid dimensions might not be reported until 126 // updateTexImage() is called. 127 virtual status_t dequeueBuffer(int *buf, sp<Fence>& fence, 128 uint32_t width, uint32_t height, uint32_t format, uint32_t usage); 129 130 // queueBuffer returns a filled buffer to the BufferQueue. In addition, a 131 // timestamp must be provided for the buffer. The timestamp is in 132 // nanoseconds, and must be monotonically increasing. Its other semantics 133 // (zero point, etc) are client-dependent and should be documented by the 134 // client. 135 virtual status_t queueBuffer(int buf, 136 const QueueBufferInput& input, QueueBufferOutput* output); 137 138 virtual void cancelBuffer(int buf, sp<Fence> fence); 139 140 // setSynchronousMode set whether dequeueBuffer is synchronous or 141 // asynchronous. In synchronous mode, dequeueBuffer blocks until 142 // a buffer is available, the currently bound buffer can be dequeued and 143 // queued buffers will be retired in order. 144 // The default mode is asynchronous. 145 virtual status_t setSynchronousMode(bool enabled); 146 147 // connect attempts to connect a producer client API to the BufferQueue. 148 // This must be called before any other ISurfaceTexture methods are called 149 // except for getAllocator. 150 // 151 // This method will fail if the connect was previously called on the 152 // BufferQueue and no corresponding disconnect call was made. 153 virtual status_t connect(int api, QueueBufferOutput* output); 154 155 // disconnect attempts to disconnect a producer client API from the 156 // BufferQueue. Calling this method will cause any subsequent calls to other 157 // ISurfaceTexture methods to fail except for getAllocator and connect. 158 // Successfully calling connect after this will allow the other methods to 159 // succeed again. 160 // 161 // This method will fail if the the BufferQueue is not currently 162 // connected to the specified client API. 163 virtual status_t disconnect(int api); 164 165 // dump our state in a String 166 virtual void dump(String8& result) const; 167 virtual void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const; 168 169 // public facing structure for BufferSlot 170 struct BufferItem { 171 172 BufferItem() 173 : 174 mTransform(0), 175 mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), 176 mTimestamp(0), 177 mFrameNumber(0), 178 mBuf(INVALID_BUFFER_SLOT) { 179 mCrop.makeInvalid(); 180 } 181 // mGraphicBuffer points to the buffer allocated for this slot or is NULL 182 // if no buffer has been allocated. 183 sp<GraphicBuffer> mGraphicBuffer; 184 185 // mCrop is the current crop rectangle for this buffer slot. 186 Rect mCrop; 187 188 // mTransform is the current transform flags for this buffer slot. 189 uint32_t mTransform; 190 191 // mScalingMode is the current scaling mode for this buffer slot. 192 uint32_t mScalingMode; 193 194 // mTimestamp is the current timestamp for this buffer slot. This gets 195 // to set by queueBuffer each time this slot is queued. 196 int64_t mTimestamp; 197 198 // mFrameNumber is the number of the queued frame for this slot. 199 uint64_t mFrameNumber; 200 201 // mBuf is the slot index of this buffer 202 int mBuf; 203 204 // mFence is a fence that will signal when the buffer is idle. 205 sp<Fence> mFence; 206 }; 207 208 // The following public functions is the consumer facing interface 209 210 // acquireBuffer attempts to acquire ownership of the next pending buffer in 211 // the BufferQueue. If no buffer is pending then it returns -EINVAL. If a 212 // buffer is successfully acquired, the information about the buffer is 213 // returned in BufferItem. If the buffer returned had previously been 214 // acquired then the BufferItem::mGraphicBuffer field of buffer is set to 215 // NULL and it is assumed that the consumer still holds a reference to the 216 // buffer. 217 status_t acquireBuffer(BufferItem *buffer); 218 219 // releaseBuffer releases a buffer slot from the consumer back to the 220 // BufferQueue pending a fence sync. 221 // 222 // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free 223 // any references to the just-released buffer that it might have, as if it 224 // had received a onBuffersReleased() call with a mask set for the released 225 // buffer. 226 // 227 // Note that the dependencies on EGL will be removed once we switch to using 228 // the Android HW Sync HAL. 229 status_t releaseBuffer(int buf, EGLDisplay display, EGLSyncKHR fence, 230 const sp<Fence>& releaseFence); 231 232 // consumerConnect connects a consumer to the BufferQueue. Only one 233 // consumer may be connected, and when that consumer disconnects the 234 // BufferQueue is placed into the "abandoned" state, causing most 235 // interactions with the BufferQueue by the producer to fail. 236 status_t consumerConnect(const sp<ConsumerListener>& consumer); 237 238 // consumerDisconnect disconnects a consumer from the BufferQueue. All 239 // buffers will be freed and the BufferQueue is placed in the "abandoned" 240 // state, causing most interactions with the BufferQueue by the producer to 241 // fail. 242 status_t consumerDisconnect(); 243 244 // getReleasedBuffers sets the value pointed to by slotMask to a bit mask 245 // indicating which buffer slots the have been released by the BufferQueue 246 // but have not yet been released by the consumer. 247 status_t getReleasedBuffers(uint32_t* slotMask); 248 249 // setDefaultBufferSize is used to set the size of buffers returned by 250 // requestBuffers when a with and height of zero is requested. 251 status_t setDefaultBufferSize(uint32_t w, uint32_t h); 252 253 // setDefaultBufferCount set the buffer count. If the client has requested 254 // a buffer count using setBufferCount, the server-buffer count will 255 // take effect once the client sets the count back to zero. 256 status_t setDefaultMaxBufferCount(int bufferCount); 257 258 // setMaxAcquiredBufferCount sets the maximum number of buffers that can 259 // be acquired by the consumer at one time. This call will fail if a 260 // producer is connected to the BufferQueue. 261 status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers); 262 263 // isSynchronousMode returns whether the SurfaceTexture is currently in 264 // synchronous mode. 265 bool isSynchronousMode() const; 266 267 // setConsumerName sets the name used in logging 268 void setConsumerName(const String8& name); 269 270 // setDefaultBufferFormat allows the BufferQueue to create 271 // GraphicBuffers of a defaultFormat if no format is specified 272 // in dequeueBuffer 273 status_t setDefaultBufferFormat(uint32_t defaultFormat); 274 275 // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer 276 status_t setConsumerUsageBits(uint32_t usage); 277 278 // setTransformHint bakes in rotation to buffers so overlays can be used 279 status_t setTransformHint(uint32_t hint); 280 281private: 282 // freeBufferLocked frees the resources (both GraphicBuffer and EGLImage) 283 // for the given slot. 284 void freeBufferLocked(int index); 285 286 // freeAllBuffersLocked frees the resources (both GraphicBuffer and 287 // EGLImage) for all slots. 288 void freeAllBuffersLocked(); 289 290 // freeAllBuffersExceptHeadLocked frees the resources (both GraphicBuffer 291 // and EGLImage) for all slots except the head of mQueue 292 void freeAllBuffersExceptHeadLocked(); 293 294 // drainQueueLocked drains the buffer queue if we're in synchronous mode 295 // returns immediately otherwise. It returns NO_INIT if the BufferQueue 296 // became abandoned or disconnected during this call. 297 status_t drainQueueLocked(); 298 299 // drainQueueAndFreeBuffersLocked drains the buffer queue if we're in 300 // synchronous mode and free all buffers. In asynchronous mode, all buffers 301 // are freed except the current buffer. 302 status_t drainQueueAndFreeBuffersLocked(); 303 304 // setDefaultMaxBufferCountLocked sets the maximum number of buffer slots 305 // that will be used if the producer does not override the buffer slot 306 // count. 307 status_t setDefaultMaxBufferCountLocked(int count); 308 309 // getMinBufferCountLocked returns the minimum number of buffers allowed 310 // given the current BufferQueue state. 311 int getMinMaxBufferCountLocked() const; 312 313 // getMinUndequeuedBufferCountLocked returns the minimum number of buffers 314 // that must remain in a state other than DEQUEUED. 315 int getMinUndequeuedBufferCountLocked() const; 316 317 // getMaxBufferCountLocked returns the maximum number of buffers that can 318 // be allocated at once. This value depends upon the following member 319 // variables: 320 // 321 // mSynchronousMode 322 // mMaxAcquiredBufferCount 323 // mDefaultMaxBufferCount 324 // mOverrideMaxBufferCount 325 // 326 // Any time one of these member variables is changed while a producer is 327 // connected, mDequeueCondition must be broadcast. 328 int getMaxBufferCountLocked() const; 329 330 struct BufferSlot { 331 332 BufferSlot() 333 : mEglDisplay(EGL_NO_DISPLAY), 334 mBufferState(BufferSlot::FREE), 335 mRequestBufferCalled(false), 336 mTransform(0), 337 mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), 338 mTimestamp(0), 339 mFrameNumber(0), 340 mEglFence(EGL_NO_SYNC_KHR), 341 mAcquireCalled(false), 342 mNeedsCleanupOnRelease(false) { 343 mCrop.makeInvalid(); 344 } 345 346 // mGraphicBuffer points to the buffer allocated for this slot or is NULL 347 // if no buffer has been allocated. 348 sp<GraphicBuffer> mGraphicBuffer; 349 350 // mEglDisplay is the EGLDisplay used to create mEglImage. 351 EGLDisplay mEglDisplay; 352 353 // BufferState represents the different states in which a buffer slot 354 // can be. 355 enum BufferState { 356 // FREE indicates that the buffer is not currently being used and 357 // will not be used in the future until it gets dequeued and 358 // subsequently queued by the client. 359 // aka "owned by BufferQueue, ready to be dequeued" 360 FREE = 0, 361 362 // DEQUEUED indicates that the buffer has been dequeued by the 363 // client, but has not yet been queued or canceled. The buffer is 364 // considered 'owned' by the client, and the server should not use 365 // it for anything. 366 // 367 // Note that when in synchronous-mode (mSynchronousMode == true), 368 // the buffer that's currently attached to the texture may be 369 // dequeued by the client. That means that the current buffer can 370 // be in either the DEQUEUED or QUEUED state. In asynchronous mode, 371 // however, the current buffer is always in the QUEUED state. 372 // aka "owned by producer, ready to be queued" 373 DEQUEUED = 1, 374 375 // QUEUED indicates that the buffer has been queued by the client, 376 // and has not since been made available for the client to dequeue. 377 // Attaching the buffer to the texture does NOT transition the 378 // buffer away from the QUEUED state. However, in Synchronous mode 379 // the current buffer may be dequeued by the client under some 380 // circumstances. See the note about the current buffer in the 381 // documentation for DEQUEUED. 382 // aka "owned by BufferQueue, ready to be acquired" 383 QUEUED = 2, 384 385 // aka "owned by consumer, ready to be released" 386 ACQUIRED = 3 387 }; 388 389 // mBufferState is the current state of this buffer slot. 390 BufferState mBufferState; 391 392 // mRequestBufferCalled is used for validating that the client did 393 // call requestBuffer() when told to do so. Technically this is not 394 // needed but useful for debugging and catching client bugs. 395 bool mRequestBufferCalled; 396 397 // mCrop is the current crop rectangle for this buffer slot. 398 Rect mCrop; 399 400 // mTransform is the current transform flags for this buffer slot. 401 uint32_t mTransform; 402 403 // mScalingMode is the current scaling mode for this buffer slot. 404 uint32_t mScalingMode; 405 406 // mTimestamp is the current timestamp for this buffer slot. This gets 407 // to set by queueBuffer each time this slot is queued. 408 int64_t mTimestamp; 409 410 // mFrameNumber is the number of the queued frame for this slot. 411 uint64_t mFrameNumber; 412 413 // mEglFence is the EGL sync object that must signal before the buffer 414 // associated with this buffer slot may be dequeued. It is initialized 415 // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based 416 // on a compile-time option) set to a new sync object in updateTexImage. 417 EGLSyncKHR mEglFence; 418 419 // mFence is a fence which will signal when work initiated by the 420 // previous owner of the buffer is finished. When the buffer is FREE, 421 // the fence indicates when the consumer has finished reading 422 // from the buffer, or when the producer has finished writing if it 423 // called cancelBuffer after queueing some writes. When the buffer is 424 // QUEUED, it indicates when the producer has finished filling the 425 // buffer. When the buffer is DEQUEUED or ACQUIRED, the fence has been 426 // passed to the consumer or producer along with ownership of the 427 // buffer, and mFence is empty. 428 sp<Fence> mFence; 429 430 // Indicates whether this buffer has been seen by a consumer yet 431 bool mAcquireCalled; 432 433 // Indicates whether this buffer needs to be cleaned up by consumer 434 bool mNeedsCleanupOnRelease; 435 }; 436 437 // mSlots is the array of buffer slots that must be mirrored on the client 438 // side. This allows buffer ownership to be transferred between the client 439 // and server without sending a GraphicBuffer over binder. The entire array 440 // is initialized to NULL at construction time, and buffers are allocated 441 // for a slot when requestBuffer is called with that slot's index. 442 BufferSlot mSlots[NUM_BUFFER_SLOTS]; 443 444 // mDefaultWidth holds the default width of allocated buffers. It is used 445 // in requestBuffers() if a width and height of zero is specified. 446 uint32_t mDefaultWidth; 447 448 // mDefaultHeight holds the default height of allocated buffers. It is used 449 // in requestBuffers() if a width and height of zero is specified. 450 uint32_t mDefaultHeight; 451 452 // mMaxAcquiredBufferCount is the number of buffers that the consumer may 453 // acquire at one time. It defaults to 1 and can be changed by the 454 // consumer via the setMaxAcquiredBufferCount method, but this may only be 455 // done when no producer is connected to the BufferQueue. 456 // 457 // This value is used to derive the value returned for the 458 // MIN_UNDEQUEUED_BUFFERS query by the producer. 459 int mMaxAcquiredBufferCount; 460 461 // mDefaultMaxBufferCount is the default limit on the number of buffers 462 // that will be allocated at one time. This default limit is set by the 463 // consumer. The limit (as opposed to the default limit) may be 464 // overridden by the producer. 465 int mDefaultMaxBufferCount; 466 467 // mOverrideMaxBufferCount is the limit on the number of buffers that will 468 // be allocated at one time. This value is set by the image producer by 469 // calling setBufferCount. The default is zero, which means the producer 470 // doesn't care about the number of buffers in the pool. In that case 471 // mDefaultMaxBufferCount is used as the limit. 472 int mOverrideMaxBufferCount; 473 474 // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to 475 // allocate new GraphicBuffer objects. 476 sp<IGraphicBufferAlloc> mGraphicBufferAlloc; 477 478 // mConsumerListener is used to notify the connected consumer of 479 // asynchronous events that it may wish to react to. It is initially set 480 // to NULL and is written by consumerConnect and consumerDisconnect. 481 sp<ConsumerListener> mConsumerListener; 482 483 // mSynchronousMode whether we're in synchronous mode or not 484 bool mSynchronousMode; 485 486 // mAllowSynchronousMode whether we allow synchronous mode or not 487 const bool mAllowSynchronousMode; 488 489 // mConnectedApi indicates the API that is currently connected to this 490 // BufferQueue. It defaults to NO_CONNECTED_API (= 0), and gets updated 491 // by the connect and disconnect methods. 492 int mConnectedApi; 493 494 // mDequeueCondition condition used for dequeueBuffer in synchronous mode 495 mutable Condition mDequeueCondition; 496 497 // mQueue is a FIFO of queued buffers used in synchronous mode 498 typedef Vector<int> Fifo; 499 Fifo mQueue; 500 501 // mAbandoned indicates that the BufferQueue will no longer be used to 502 // consume images buffers pushed to it using the ISurfaceTexture interface. 503 // It is initialized to false, and set to true in the abandon method. A 504 // BufferQueue that has been abandoned will return the NO_INIT error from 505 // all ISurfaceTexture methods capable of returning an error. 506 bool mAbandoned; 507 508 // mName is a string used to identify the BufferQueue in log messages. 509 // It is set by the setName method. 510 String8 mConsumerName; 511 512 // mMutex is the mutex used to prevent concurrent access to the member 513 // variables of BufferQueue objects. It must be locked whenever the 514 // member variables are accessed. 515 mutable Mutex mMutex; 516 517 // mFrameCounter is the free running counter, incremented for every buffer queued 518 // with the surface Texture. 519 uint64_t mFrameCounter; 520 521 // mBufferHasBeenQueued is true once a buffer has been queued. It is reset 522 // by changing the buffer count. 523 bool mBufferHasBeenQueued; 524 525 // mDefaultBufferFormat can be set so it will override 526 // the buffer format when it isn't specified in dequeueBuffer 527 uint32_t mDefaultBufferFormat; 528 529 // mConsumerUsageBits contains flags the consumer wants for GraphicBuffers 530 uint32_t mConsumerUsageBits; 531 532 // mTransformHint is used to optimize for screen rotations 533 uint32_t mTransformHint; 534}; 535 536// ---------------------------------------------------------------------------- 537}; // namespace android 538 539#endif // ANDROID_GUI_BUFFERQUEUE_H 540