BufferQueue.h revision ef19414bd8b77a26f5751f3845be79025a8263fe
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 96 // by producers and consumers. 97 // allowSynchronousMode specifies whether or not synchronous mode can be 98 // enabled. 99 // bufferCount sets the minimum number of undequeued buffers for this queue 100 BufferQueue(bool allowSynchronousMode = true, 101 int bufferCount = MIN_UNDEQUEUED_BUFFERS, 102 const sp<IGraphicBufferAlloc>& allocator = NULL); 103 virtual ~BufferQueue(); 104 105 virtual int query(int what, int* value); 106 107 // setBufferCount updates the number of available buffer slots. After 108 // calling this all buffer slots are both unallocated and owned by the 109 // BufferQueue object (i.e. they are not owned by the client). 110 virtual status_t setBufferCount(int bufferCount); 111 112 virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf); 113 114 // dequeueBuffer gets the next buffer slot index for the client to use. If a 115 // buffer slot is available then that slot index is written to the location 116 // pointed to by the buf argument and a status of OK is returned. If no 117 // slot is available then a status of -EBUSY is returned and buf is 118 // unmodified. 119 // The width and height parameters must be no greater than the minimum of 120 // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv). 121 // An error due to invalid dimensions might not be reported until 122 // updateTexImage() is called. 123 virtual status_t dequeueBuffer(int *buf, uint32_t width, uint32_t height, 124 uint32_t format, uint32_t usage); 125 126 // queueBuffer returns a filled buffer to the BufferQueue. In addition, a 127 // timestamp must be provided for the buffer. The timestamp is in 128 // nanoseconds, and must be monotonically increasing. Its other semantics 129 // (zero point, etc) are client-dependent and should be documented by the 130 // client. 131 virtual status_t queueBuffer(int buf, 132 const QueueBufferInput& input, QueueBufferOutput* output); 133 134 virtual void cancelBuffer(int buf); 135 136 // setSynchronousMode set whether dequeueBuffer is synchronous or 137 // asynchronous. In synchronous mode, dequeueBuffer blocks until 138 // a buffer is available, the currently bound buffer can be dequeued and 139 // queued buffers will be retired in order. 140 // The default mode is asynchronous. 141 virtual status_t setSynchronousMode(bool enabled); 142 143 // connect attempts to connect a producer client API to the BufferQueue. 144 // This must be called before any other ISurfaceTexture methods are called 145 // except for getAllocator. 146 // 147 // This method will fail if the connect was previously called on the 148 // BufferQueue and no corresponding disconnect call was made. 149 virtual status_t connect(int api, QueueBufferOutput* output); 150 151 // disconnect attempts to disconnect a producer client API from the 152 // BufferQueue. Calling this method will cause any subsequent calls to other 153 // ISurfaceTexture methods to fail except for getAllocator and connect. 154 // Successfully calling connect after this will allow the other methods to 155 // succeed again. 156 // 157 // This method will fail if the the BufferQueue is not currently 158 // connected to the specified client API. 159 virtual status_t disconnect(int api); 160 161 // dump our state in a String 162 virtual void dump(String8& result) const; 163 virtual void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const; 164 165 // public facing structure for BufferSlot 166 struct BufferItem { 167 168 BufferItem() 169 : 170 mTransform(0), 171 mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), 172 mTimestamp(0), 173 mFrameNumber(0), 174 mBuf(INVALID_BUFFER_SLOT) { 175 mCrop.makeInvalid(); 176 } 177 // mGraphicBuffer points to the buffer allocated for this slot or is NULL 178 // if no buffer has been allocated. 179 sp<GraphicBuffer> mGraphicBuffer; 180 181 // mCrop is the current crop rectangle for this buffer slot. 182 Rect mCrop; 183 184 // mTransform is the current transform flags for this buffer slot. 185 uint32_t mTransform; 186 187 // mScalingMode is the current scaling mode for this buffer slot. 188 uint32_t mScalingMode; 189 190 // mTimestamp is the current timestamp for this buffer slot. This gets 191 // to set by queueBuffer each time this slot is queued. 192 int64_t mTimestamp; 193 194 // mFrameNumber is the number of the queued frame for this slot. 195 uint64_t mFrameNumber; 196 197 // mBuf is the slot index of this buffer 198 int mBuf; 199 }; 200 201 // The following public functions is the consumer facing interface 202 203 // acquireBuffer attempts to acquire ownership of the next pending buffer in 204 // the BufferQueue. If no buffer is pending then it returns -EINVAL. If a 205 // buffer is successfully acquired, the information about the buffer is 206 // returned in BufferItem. If the buffer returned had previously been 207 // acquired then the BufferItem::mGraphicBuffer field of buffer is set to 208 // NULL and it is assumed that the consumer still holds a reference to the 209 // buffer. 210 status_t acquireBuffer(BufferItem *buffer); 211 212 // releaseBuffer releases a buffer slot from the consumer back to the 213 // BufferQueue pending a fence sync. 214 // 215 // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free 216 // any references to the just-released buffer that it might have, as if it 217 // had received a onBuffersReleased() call with a mask set for the released 218 // buffer. 219 // 220 // Note that the dependencies on EGL will be removed once we switch to using 221 // the Android HW Sync HAL. 222 status_t releaseBuffer(int buf, EGLDisplay display, EGLSyncKHR fence, 223 const sp<Fence>& releaseFence = Fence::NO_FENCE); 224 225 // consumerConnect connects a consumer to the BufferQueue. Only one 226 // consumer may be connected, and when that consumer disconnects the 227 // BufferQueue is placed into the "abandoned" state, causing most 228 // interactions with the BufferQueue by the producer to fail. 229 status_t consumerConnect(const sp<ConsumerListener>& consumer); 230 231 // consumerDisconnect disconnects a consumer from the BufferQueue. All 232 // buffers will be freed and the BufferQueue is placed in the "abandoned" 233 // state, causing most interactions with the BufferQueue by the producer to 234 // fail. 235 status_t consumerDisconnect(); 236 237 // getReleasedBuffers sets the value pointed to by slotMask to a bit mask 238 // indicating which buffer slots the have been released by the BufferQueue 239 // but have not yet been released by the consumer. 240 status_t getReleasedBuffers(uint32_t* slotMask); 241 242 // setDefaultBufferSize is used to set the size of buffers returned by 243 // requestBuffers when a with and height of zero is requested. 244 status_t setDefaultBufferSize(uint32_t w, uint32_t h); 245 246 // setBufferCountServer set the buffer count. If the client has requested 247 // a buffer count using setBufferCount, the server-buffer count will 248 // take effect once the client sets the count back to zero. 249 status_t setBufferCountServer(int bufferCount); 250 251 // isSynchronousMode returns whether the SurfaceTexture is currently in 252 // synchronous mode. 253 bool isSynchronousMode() const; 254 255 // setConsumerName sets the name used in logging 256 void setConsumerName(const String8& name); 257 258 // setDefaultBufferFormat allows the BufferQueue to create 259 // GraphicBuffers of a defaultFormat if no format is specified 260 // in dequeueBuffer 261 status_t setDefaultBufferFormat(uint32_t defaultFormat); 262 263 // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer 264 status_t setConsumerUsageBits(uint32_t usage); 265 266 // setTransformHint bakes in rotation to buffers so overlays can be used 267 status_t setTransformHint(uint32_t hint); 268 269private: 270 // freeBufferLocked frees the resources (both GraphicBuffer and EGLImage) 271 // for the given slot. 272 void freeBufferLocked(int index); 273 274 // freeAllBuffersLocked frees the resources (both GraphicBuffer and 275 // EGLImage) for all slots. 276 void freeAllBuffersLocked(); 277 278 // freeAllBuffersExceptHeadLocked frees the resources (both GraphicBuffer 279 // and EGLImage) for all slots except the head of mQueue 280 void freeAllBuffersExceptHeadLocked(); 281 282 // drainQueueLocked drains the buffer queue if we're in synchronous mode 283 // returns immediately otherwise. It returns NO_INIT if the BufferQueue 284 // became abandoned or disconnected during this call. 285 status_t drainQueueLocked(); 286 287 // drainQueueAndFreeBuffersLocked drains the buffer queue if we're in 288 // synchronous mode and free all buffers. In asynchronous mode, all buffers 289 // are freed except the current buffer. 290 status_t drainQueueAndFreeBuffersLocked(); 291 292 status_t setBufferCountServerLocked(int bufferCount); 293 294 struct BufferSlot { 295 296 BufferSlot() 297 : mEglDisplay(EGL_NO_DISPLAY), 298 mBufferState(BufferSlot::FREE), 299 mRequestBufferCalled(false), 300 mTransform(0), 301 mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), 302 mTimestamp(0), 303 mFrameNumber(0), 304 mFence(EGL_NO_SYNC_KHR), 305 mAcquireCalled(false), 306 mNeedsCleanupOnRelease(false) { 307 mCrop.makeInvalid(); 308 } 309 310 // mGraphicBuffer points to the buffer allocated for this slot or is NULL 311 // if no buffer has been allocated. 312 sp<GraphicBuffer> mGraphicBuffer; 313 314 // mEglDisplay is the EGLDisplay used to create mEglImage. 315 EGLDisplay mEglDisplay; 316 317 // BufferState represents the different states in which a buffer slot 318 // can be. 319 enum BufferState { 320 // FREE indicates that the buffer is not currently being used and 321 // will not be used in the future until it gets dequeued and 322 // subsequently queued by the client. 323 // aka "owned by BufferQueue, ready to be dequeued" 324 FREE = 0, 325 326 // DEQUEUED indicates that the buffer has been dequeued by the 327 // client, but has not yet been queued or canceled. The buffer is 328 // considered 'owned' by the client, and the server should not use 329 // it for anything. 330 // 331 // Note that when in synchronous-mode (mSynchronousMode == true), 332 // the buffer that's currently attached to the texture may be 333 // dequeued by the client. That means that the current buffer can 334 // be in either the DEQUEUED or QUEUED state. In asynchronous mode, 335 // however, the current buffer is always in the QUEUED state. 336 // aka "owned by producer, ready to be queued" 337 DEQUEUED = 1, 338 339 // QUEUED indicates that the buffer has been queued by the client, 340 // and has not since been made available for the client to dequeue. 341 // Attaching the buffer to the texture does NOT transition the 342 // buffer away from the QUEUED state. However, in Synchronous mode 343 // the current buffer may be dequeued by the client under some 344 // circumstances. See the note about the current buffer in the 345 // documentation for DEQUEUED. 346 // aka "owned by BufferQueue, ready to be acquired" 347 QUEUED = 2, 348 349 // aka "owned by consumer, ready to be released" 350 ACQUIRED = 3 351 }; 352 353 // mBufferState is the current state of this buffer slot. 354 BufferState mBufferState; 355 356 // mRequestBufferCalled is used for validating that the client did 357 // call requestBuffer() when told to do so. Technically this is not 358 // needed but useful for debugging and catching client bugs. 359 bool mRequestBufferCalled; 360 361 // mCrop is the current crop rectangle for this buffer slot. 362 Rect mCrop; 363 364 // mTransform is the current transform flags for this buffer slot. 365 uint32_t mTransform; 366 367 // mScalingMode is the current scaling mode for this buffer slot. 368 uint32_t mScalingMode; 369 370 // mTimestamp is the current timestamp for this buffer slot. This gets 371 // to set by queueBuffer each time this slot is queued. 372 int64_t mTimestamp; 373 374 // mFrameNumber is the number of the queued frame for this slot. 375 uint64_t mFrameNumber; 376 377 // mFence is the EGL sync object that must signal before the buffer 378 // associated with this buffer slot may be dequeued. It is initialized 379 // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based 380 // on a compile-time option) set to a new sync object in updateTexImage. 381 EGLSyncKHR mFence; 382 383 // mReleaseFence is a fence which must signal before the contents of 384 // the buffer associated with this buffer slot may be overwritten. 385 sp<Fence> mReleaseFence; 386 387 // Indicates whether this buffer has been seen by a consumer yet 388 bool mAcquireCalled; 389 390 // Indicates whether this buffer needs to be cleaned up by consumer 391 bool mNeedsCleanupOnRelease; 392 }; 393 394 // mSlots is the array of buffer slots that must be mirrored on the client 395 // side. This allows buffer ownership to be transferred between the client 396 // and server without sending a GraphicBuffer over binder. The entire array 397 // is initialized to NULL at construction time, and buffers are allocated 398 // for a slot when requestBuffer is called with that slot's index. 399 BufferSlot mSlots[NUM_BUFFER_SLOTS]; 400 401 // mDefaultWidth holds the default width of allocated buffers. It is used 402 // in requestBuffers() if a width and height of zero is specified. 403 uint32_t mDefaultWidth; 404 405 // mDefaultHeight holds the default height of allocated buffers. It is used 406 // in requestBuffers() if a width and height of zero is specified. 407 uint32_t mDefaultHeight; 408 409 // mPixelFormat holds the pixel format of allocated buffers. It is used 410 // in requestBuffers() if a format of zero is specified. 411 uint32_t mPixelFormat; 412 413 // mMinUndequeuedBuffers is a constraint on the number of buffers 414 // not dequeued at any time 415 int mMinUndequeuedBuffers; 416 417 // mMinAsyncBufferSlots is a constraint on the minimum mBufferCount 418 // when this BufferQueue is in asynchronous mode 419 int mMinAsyncBufferSlots; 420 421 // mMinSyncBufferSlots is a constraint on the minimum mBufferCount 422 // when this BufferQueue is in synchronous mode 423 int mMinSyncBufferSlots; 424 425 // mBufferCount is the number of buffer slots that the client and server 426 // must maintain. It defaults to MIN_ASYNC_BUFFER_SLOTS and can be changed 427 // by calling setBufferCount or setBufferCountServer 428 int mBufferCount; 429 430 // mClientBufferCount is the number of buffer slots requested by the client. 431 // The default is zero, which means the client doesn't care how many buffers 432 // there is. 433 int mClientBufferCount; 434 435 // mServerBufferCount buffer count requested by the server-side 436 int mServerBufferCount; 437 438 // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to 439 // allocate new GraphicBuffer objects. 440 sp<IGraphicBufferAlloc> mGraphicBufferAlloc; 441 442 // mConsumerListener is used to notify the connected consumer of 443 // asynchronous events that it may wish to react to. It is initially set 444 // to NULL and is written by consumerConnect and consumerDisconnect. 445 sp<ConsumerListener> mConsumerListener; 446 447 // mSynchronousMode whether we're in synchronous mode or not 448 bool mSynchronousMode; 449 450 // mAllowSynchronousMode whether we allow synchronous mode or not 451 const bool mAllowSynchronousMode; 452 453 // mConnectedApi indicates the API that is currently connected to this 454 // BufferQueue. It defaults to NO_CONNECTED_API (= 0), and gets updated 455 // by the connect and disconnect methods. 456 int mConnectedApi; 457 458 // mDequeueCondition condition used for dequeueBuffer in synchronous mode 459 mutable Condition mDequeueCondition; 460 461 // mQueue is a FIFO of queued buffers used in synchronous mode 462 typedef Vector<int> Fifo; 463 Fifo mQueue; 464 465 // mAbandoned indicates that the BufferQueue will no longer be used to 466 // consume images buffers pushed to it using the ISurfaceTexture interface. 467 // It is initialized to false, and set to true in the abandon method. A 468 // BufferQueue that has been abandoned will return the NO_INIT error from 469 // all ISurfaceTexture methods capable of returning an error. 470 bool mAbandoned; 471 472 // mName is a string used to identify the BufferQueue in log messages. 473 // It is set by the setName method. 474 String8 mConsumerName; 475 476 // mMutex is the mutex used to prevent concurrent access to the member 477 // variables of BufferQueue objects. It must be locked whenever the 478 // member variables are accessed. 479 mutable Mutex mMutex; 480 481 // mFrameCounter is the free running counter, incremented for every buffer queued 482 // with the surface Texture. 483 uint64_t mFrameCounter; 484 485 // mBufferHasBeenQueued is true once a buffer has been queued. It is reset 486 // by changing the buffer count. 487 bool mBufferHasBeenQueued; 488 489 // mDefaultBufferFormat can be set so it will override 490 // the buffer format when it isn't specified in dequeueBuffer 491 uint32_t mDefaultBufferFormat; 492 493 // mConsumerUsageBits contains flags the consumer wants for GraphicBuffers 494 uint32_t mConsumerUsageBits; 495 496 // mTransformHint is used to optimize for screen rotations 497 uint32_t mTransformHint; 498}; 499 500// ---------------------------------------------------------------------------- 501}; // namespace android 502 503#endif // ANDROID_GUI_BUFFERQUEUE_H 504