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