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