BufferQueue.h revision f0eaf25e9247edf4d124bedaeb863f7abdf35a3e
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 <gui/BufferQueueProducer.h>
21#include <gui/BufferQueueConsumer.h>
22#include <gui/IConsumerListener.h>
23
24// These are only required to keep other parts of the framework with incomplete
25// dependencies building successfully
26#include <gui/IGraphicBufferAlloc.h>
27
28#include <binder/IBinder.h>
29
30namespace android {
31
32// BQProducer and BQConsumer are thin shim classes to allow methods with the
33// same signature in both IGraphicBufferProducer and IGraphicBufferConsumer.
34// This will stop being an issue when we deprecate creating BufferQueues
35// directly (as opposed to using the *Producer and *Consumer interfaces).
36class BQProducer : public BnGraphicBufferProducer {
37public:
38    virtual status_t detachProducerBuffer(int slot) = 0;
39    virtual status_t attachProducerBuffer(int* slot,
40            const sp<GraphicBuffer>& buffer) = 0;
41
42    virtual status_t detachBuffer(int slot) {
43        return detachProducerBuffer(slot);
44    }
45
46    virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer) {
47        return attachProducerBuffer(slot, buffer);
48    }
49};
50
51class BQConsumer : public BnGraphicBufferConsumer {
52public:
53    virtual status_t detachConsumerBuffer(int slot) = 0;
54    virtual status_t attachConsumerBuffer(int* slot,
55            const sp<GraphicBuffer>& buffer) = 0;
56
57    virtual status_t detachBuffer(int slot) {
58        return detachConsumerBuffer(slot);
59    }
60
61    virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer) {
62        return attachConsumerBuffer(slot, buffer);
63    }
64};
65
66class BufferQueue : public BQProducer,
67                    public BQConsumer,
68                    private IBinder::DeathRecipient {
69public:
70    // BufferQueue will keep track of at most this value of buffers.
71    // Attempts at runtime to increase the number of buffers past this will fail.
72    enum { NUM_BUFFER_SLOTS = 32 };
73    // Used as a placeholder slot# when the value isn't pointing to an existing buffer.
74    enum { INVALID_BUFFER_SLOT = IGraphicBufferConsumer::BufferItem::INVALID_BUFFER_SLOT };
75    // Alias to <IGraphicBufferConsumer.h> -- please scope from there in future code!
76    enum {
77        NO_BUFFER_AVAILABLE = IGraphicBufferConsumer::NO_BUFFER_AVAILABLE,
78        PRESENT_LATER = IGraphicBufferConsumer::PRESENT_LATER,
79    };
80
81    // When in async mode we reserve two slots in order to guarantee that the
82    // producer and consumer can run asynchronously.
83    enum { MAX_MAX_ACQUIRED_BUFFERS = NUM_BUFFER_SLOTS - 2 };
84
85    // for backward source compatibility
86    typedef ::android::ConsumerListener ConsumerListener;
87
88    // ProxyConsumerListener is a ConsumerListener implementation that keeps a weak
89    // reference to the actual consumer object.  It forwards all calls to that
90    // consumer object so long as it exists.
91    //
92    // This class exists to avoid having a circular reference between the
93    // BufferQueue object and the consumer object.  The reason this can't be a weak
94    // reference in the BufferQueue class is because we're planning to expose the
95    // consumer side of a BufferQueue as a binder interface, which doesn't support
96    // weak references.
97    class ProxyConsumerListener : public BnConsumerListener {
98    public:
99        ProxyConsumerListener(const wp<ConsumerListener>& consumerListener);
100        virtual ~ProxyConsumerListener();
101        virtual void onFrameAvailable();
102        virtual void onBuffersReleased();
103        virtual void onSidebandStreamChanged();
104    private:
105        // mConsumerListener is a weak reference to the IConsumerListener.  This is
106        // the raison d'etre of ProxyConsumerListener.
107        wp<ConsumerListener> mConsumerListener;
108    };
109
110    // BufferQueue manages a pool of gralloc memory slots to be used by
111    // producers and consumers. allocator is used to allocate all the
112    // needed gralloc buffers.
113    BufferQueue(const sp<IGraphicBufferAlloc>& allocator = NULL);
114
115    static void createBufferQueue(sp<BnGraphicBufferProducer>* outProducer,
116            sp<BnGraphicBufferConsumer>* outConsumer,
117            const sp<IGraphicBufferAlloc>& allocator = NULL);
118
119    static void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
120            sp<IGraphicBufferConsumer>* outConsumer,
121            const sp<IGraphicBufferAlloc>& allocator = NULL);
122
123    virtual ~BufferQueue();
124
125    /*
126     * IBinder::DeathRecipient interface
127     */
128
129    virtual void binderDied(const wp<IBinder>& who);
130
131    /*
132     * IGraphicBufferProducer interface
133     */
134
135    // Query native window attributes.  The "what" values are enumerated in
136    // window.h (e.g. NATIVE_WINDOW_FORMAT).
137    virtual int query(int what, int* value);
138
139    // setBufferCount updates the number of available buffer slots.  If this
140    // method succeeds, buffer slots will be both unallocated and owned by
141    // the BufferQueue object (i.e. they are not owned by the producer or
142    // consumer).
143    //
144    // This will fail if the producer has dequeued any buffers, or if
145    // bufferCount is invalid.  bufferCount must generally be a value
146    // between the minimum undequeued buffer count (exclusive) and NUM_BUFFER_SLOTS
147    // (inclusive).  It may also be set to zero (the default) to indicate
148    // that the producer does not wish to set a value.  The minimum value
149    // can be obtained by calling query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
150    // ...).
151    //
152    // This may only be called by the producer.  The consumer will be told
153    // to discard buffers through the onBuffersReleased callback.
154    virtual status_t setBufferCount(int bufferCount);
155
156    // requestBuffer returns the GraphicBuffer for slot N.
157    //
158    // In normal operation, this is called the first time slot N is returned
159    // by dequeueBuffer.  It must be called again if dequeueBuffer returns
160    // flags indicating that previously-returned buffers are no longer valid.
161    virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
162
163    // dequeueBuffer gets the next buffer slot index for the producer to use.
164    // If a buffer slot is available then that slot index is written to the
165    // location pointed to by the buf argument and a status of OK is returned.
166    // If no slot is available then a status of -EBUSY is returned and buf is
167    // unmodified.
168    //
169    // The fence parameter will be updated to hold the fence associated with
170    // the buffer. The contents of the buffer must not be overwritten until the
171    // fence signals. If the fence is Fence::NO_FENCE, the buffer may be
172    // written immediately.
173    //
174    // The width and height parameters must be no greater than the minimum of
175    // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
176    // An error due to invalid dimensions might not be reported until
177    // updateTexImage() is called.  If width and height are both zero, the
178    // default values specified by setDefaultBufferSize() are used instead.
179    //
180    // The pixel formats are enumerated in graphics.h, e.g.
181    // HAL_PIXEL_FORMAT_RGBA_8888.  If the format is 0, the default format
182    // will be used.
183    //
184    // The usage argument specifies gralloc buffer usage flags.  The values
185    // are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER.  These
186    // will be merged with the usage flags specified by setConsumerUsageBits.
187    //
188    // The return value may be a negative error value or a non-negative
189    // collection of flags.  If the flags are set, the return values are
190    // valid, but additional actions must be performed.
191    //
192    // If IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION is set, the
193    // producer must discard cached GraphicBuffer references for the slot
194    // returned in buf.
195    // If IGraphicBufferProducer::RELEASE_ALL_BUFFERS is set, the producer
196    // must discard cached GraphicBuffer references for all slots.
197    //
198    // In both cases, the producer will need to call requestBuffer to get a
199    // GraphicBuffer handle for the returned slot.
200    virtual status_t dequeueBuffer(int *buf, sp<Fence>* fence, bool async,
201            uint32_t width, uint32_t height, uint32_t format, uint32_t usage);
202
203    // See IGraphicBufferProducer::detachBuffer
204    virtual status_t detachProducerBuffer(int slot);
205
206    // See IGraphicBufferProducer::attachBuffer
207    virtual status_t attachProducerBuffer(int* slot,
208            const sp<GraphicBuffer>& buffer);
209
210    // queueBuffer returns a filled buffer to the BufferQueue.
211    //
212    // Additional data is provided in the QueueBufferInput struct.  Notably,
213    // a timestamp must be provided for the buffer. The timestamp is in
214    // nanoseconds, and must be monotonically increasing. Its other semantics
215    // (zero point, etc) are producer-specific and should be documented by the
216    // producer.
217    //
218    // The caller may provide a fence that signals when all rendering
219    // operations have completed.  Alternatively, NO_FENCE may be used,
220    // indicating that the buffer is ready immediately.
221    //
222    // Some values are returned in the output struct: the current settings
223    // for default width and height, the current transform hint, and the
224    // number of queued buffers.
225    virtual status_t queueBuffer(int buf,
226            const QueueBufferInput& input, QueueBufferOutput* output);
227
228    // cancelBuffer returns a dequeued buffer to the BufferQueue, but doesn't
229    // queue it for use by the consumer.
230    //
231    // The buffer will not be overwritten until the fence signals.  The fence
232    // will usually be the one obtained from dequeueBuffer.
233    virtual void cancelBuffer(int buf, const sp<Fence>& fence);
234
235    // See IGraphicBufferProducer::connect
236    virtual status_t connect(const sp<IProducerListener>& listener,
237            int api, bool producerControlledByApp, QueueBufferOutput* output);
238
239    // disconnect attempts to disconnect a producer API from the BufferQueue.
240    // Calling this method will cause any subsequent calls to other
241    // IGraphicBufferProducer methods to fail except for getAllocator and connect.
242    // Successfully calling connect after this will allow the other methods to
243    // succeed again.
244    //
245    // This method will fail if the the BufferQueue is not currently
246    // connected to the specified producer API.
247    virtual status_t disconnect(int api);
248
249    // Attaches a sideband buffer stream to the BufferQueue.
250    //
251    // A sideband stream is a device-specific mechanism for passing buffers
252    // from the producer to the consumer without using dequeueBuffer/
253    // queueBuffer. If a sideband stream is present, the consumer can choose
254    // whether to acquire buffers from the sideband stream or from the queued
255    // buffers.
256    //
257    // Passing NULL or a different stream handle will detach the previous
258    // handle if any.
259    virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
260
261    /*
262     * IGraphicBufferConsumer interface
263     */
264
265    // acquireBuffer attempts to acquire ownership of the next pending buffer in
266    // the BufferQueue.  If no buffer is pending then it returns NO_BUFFER_AVAILABLE. If a
267    // buffer is successfully acquired, the information about the buffer is
268    // returned in BufferItem.  If the buffer returned had previously been
269    // acquired then the BufferItem::mGraphicBuffer field of buffer is set to
270    // NULL and it is assumed that the consumer still holds a reference to the
271    // buffer.
272    //
273    // If presentWhen is nonzero, it indicates the time when the buffer will
274    // be displayed on screen.  If the buffer's timestamp is farther in the
275    // future, the buffer won't be acquired, and PRESENT_LATER will be
276    // returned.  The presentation time is in nanoseconds, and the time base
277    // is CLOCK_MONOTONIC.
278    virtual status_t acquireBuffer(BufferItem* buffer, nsecs_t presentWhen);
279
280    // See IGraphicBufferConsumer::detachBuffer
281    virtual status_t detachConsumerBuffer(int slot);
282
283    // See IGraphicBufferConsumer::attachBuffer
284    virtual status_t attachConsumerBuffer(int* slot,
285            const sp<GraphicBuffer>& buffer);
286
287    // releaseBuffer releases a buffer slot from the consumer back to the
288    // BufferQueue.  This may be done while the buffer's contents are still
289    // being accessed.  The fence will signal when the buffer is no longer
290    // in use. frameNumber is used to indentify the exact buffer returned.
291    //
292    // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
293    // any references to the just-released buffer that it might have, as if it
294    // had received a onBuffersReleased() call with a mask set for the released
295    // buffer.
296    //
297    // Note that the dependencies on EGL will be removed once we switch to using
298    // the Android HW Sync HAL.
299    virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
300            EGLDisplay display, EGLSyncKHR fence,
301            const sp<Fence>& releaseFence);
302
303    // consumerConnect connects a consumer to the BufferQueue.  Only one
304    // consumer may be connected, and when that consumer disconnects the
305    // BufferQueue is placed into the "abandoned" state, causing most
306    // interactions with the BufferQueue by the producer to fail.
307    // controlledByApp indicates whether the consumer is controlled by
308    // the application.
309    //
310    // consumer may not be NULL.
311    virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp);
312
313    // consumerDisconnect disconnects a consumer from the BufferQueue. All
314    // buffers will be freed and the BufferQueue is placed in the "abandoned"
315    // state, causing most interactions with the BufferQueue by the producer to
316    // fail.
317    virtual status_t consumerDisconnect();
318
319    // getReleasedBuffers sets the value pointed to by slotMask to a bit mask
320    // indicating which buffer slots have been released by the BufferQueue
321    // but have not yet been released by the consumer.
322    //
323    // This should be called from the onBuffersReleased() callback.
324    virtual status_t getReleasedBuffers(uint32_t* slotMask);
325
326    // setDefaultBufferSize is used to set the size of buffers returned by
327    // dequeueBuffer when a width and height of zero is requested.  Default
328    // is 1x1.
329    virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h);
330
331    // setDefaultMaxBufferCount sets the default value for the maximum buffer
332    // count (the initial default is 2). If the producer has requested a
333    // buffer count using setBufferCount, the default buffer count will only
334    // take effect if the producer sets the count back to zero.
335    //
336    // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
337    virtual status_t setDefaultMaxBufferCount(int bufferCount);
338
339    // disableAsyncBuffer disables the extra buffer used in async mode
340    // (when both producer and consumer have set their "isControlledByApp"
341    // flag) and has dequeueBuffer() return WOULD_BLOCK instead.
342    //
343    // This can only be called before consumerConnect().
344    virtual status_t disableAsyncBuffer();
345
346    // setMaxAcquiredBufferCount sets the maximum number of buffers that can
347    // be acquired by the consumer at one time (default 1).  This call will
348    // fail if a producer is connected to the BufferQueue.
349    virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
350
351    // setConsumerName sets the name used in logging
352    virtual void setConsumerName(const String8& name);
353
354    // setDefaultBufferFormat allows the BufferQueue to create
355    // GraphicBuffers of a defaultFormat if no format is specified
356    // in dequeueBuffer.  Formats are enumerated in graphics.h; the
357    // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
358    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat);
359
360    // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
361    // These are merged with the bits passed to dequeueBuffer.  The values are
362    // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
363    virtual status_t setConsumerUsageBits(uint32_t usage);
364
365    // setTransformHint bakes in rotation to buffers so overlays can be used.
366    // The values are enumerated in window.h, e.g.
367    // NATIVE_WINDOW_TRANSFORM_ROT_90.  The default is 0 (no transform).
368    virtual status_t setTransformHint(uint32_t hint);
369
370    // Retrieve the BufferQueue's sideband stream, if any.
371    virtual sp<NativeHandle> getSidebandStream() const;
372
373    // dump our state in a String
374    virtual void dump(String8& result, const char* prefix) const;
375
376private:
377    sp<BufferQueueProducer> mProducer;
378    sp<BufferQueueConsumer> mConsumer;
379};
380
381// ----------------------------------------------------------------------------
382}; // namespace android
383
384#endif // ANDROID_GUI_BUFFERQUEUE_H
385