SurfaceTexture.h revision 292a31a4c2ae2f6faf134e8e4a726583017dad06
1/*
2 * Copyright (C) 2010 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_SURFACETEXTURE_H
18#define ANDROID_GUI_SURFACETEXTURE_H
19
20#include <EGL/egl.h>
21#include <EGL/eglext.h>
22#include <GLES2/gl2.h>
23
24#include <gui/ISurfaceTexture.h>
25
26#include <ui/GraphicBuffer.h>
27
28#include <utils/threads.h>
29#include <utils/Vector.h>
30
31#define ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID "mSurfaceTexture"
32
33namespace android {
34// ----------------------------------------------------------------------------
35
36class IGraphicBufferAlloc;
37class String8;
38
39class SurfaceTexture : public BnSurfaceTexture {
40public:
41    enum { MIN_UNDEQUEUED_BUFFERS = 2 };
42    enum {
43        MIN_ASYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS + 1,
44        MIN_SYNC_BUFFER_SLOTS  = MIN_UNDEQUEUED_BUFFERS
45    };
46    enum { NUM_BUFFER_SLOTS = 32 };
47
48    struct FrameAvailableListener : public virtual RefBase {
49        // onFrameAvailable() is called from queueBuffer() is the FIFO is
50        // empty. You can use SurfaceTexture::getQueuedCount() to
51        // figure out if there are more frames waiting.
52        // This is called without any lock held can be called concurrently by
53        // multiple threads.
54        virtual void onFrameAvailable() = 0;
55    };
56
57    // tex indicates the name OpenGL texture to which images are to be streamed.
58    // This texture name cannot be changed once the SurfaceTexture is created.
59    SurfaceTexture(GLuint tex, bool allowSynchronousMode = true);
60
61    virtual ~SurfaceTexture();
62
63    // setBufferCount updates the number of available buffer slots.  After
64    // calling this all buffer slots are both unallocated and owned by the
65    // SurfaceTexture object (i.e. they are not owned by the client).
66    virtual status_t setBufferCount(int bufferCount);
67
68    virtual sp<GraphicBuffer> requestBuffer(int buf);
69
70    // dequeueBuffer gets the next buffer slot index for the client to use. If a
71    // buffer slot is available then that slot index is written to the location
72    // pointed to by the buf argument and a status of OK is returned.  If no
73    // slot is available then a status of -EBUSY is returned and buf is
74    // unmodified.
75    virtual status_t dequeueBuffer(int *buf, uint32_t w, uint32_t h,
76            uint32_t format, uint32_t usage);
77
78    // queueBuffer returns a filled buffer to the SurfaceTexture. In addition, a
79    // timestamp must be provided for the buffer. The timestamp is in
80    // nanoseconds, and must be monotonically increasing. Its other semantics
81    // (zero point, etc) are client-dependent and should be documented by the
82    // client.
83    virtual status_t queueBuffer(int buf, int64_t timestamp);
84    virtual void cancelBuffer(int buf);
85    virtual status_t setCrop(const Rect& reg);
86    virtual status_t setTransform(uint32_t transform);
87
88    virtual int query(int what, int* value);
89
90    // setSynchronousMode set whether dequeueBuffer is synchronous or
91    // asynchronous. In synchronous mode, dequeueBuffer blocks until
92    // a buffer is available, the currently bound buffer can be dequeued and
93    // queued buffers will be retired in order.
94    // The default mode is asynchronous.
95    virtual status_t setSynchronousMode(bool enabled);
96
97    // updateTexImage sets the image contents of the target texture to that of
98    // the most recently queued buffer.
99    //
100    // This call may only be made while the OpenGL ES context to which the
101    // target texture belongs is bound to the calling thread.
102    status_t updateTexImage();
103
104    // getqueuedCount returns the number of queued frames waiting in the
105    // FIFO. In asynchronous mode, this always returns 0 or 1 since
106    // frames are not accumulating in the FIFO.
107    size_t getQueuedCount() const;
108
109    // setBufferCountServer set the buffer count. If the client has requested
110    // a buffer count using setBufferCount, the server-buffer count will
111    // take effect once the client sets the count back to zero.
112    status_t setBufferCountServer(int bufferCount);
113
114    // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
115    // associated with the texture image set by the most recent call to
116    // updateTexImage.
117    //
118    // This transform matrix maps 2D homogeneous texture coordinates of the form
119    // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
120    // coordinate that should be used to sample that location from the texture.
121    // Sampling the texture outside of the range of this transform is undefined.
122    //
123    // This transform is necessary to compensate for transforms that the stream
124    // content producer may implicitly apply to the content. By forcing users of
125    // a SurfaceTexture to apply this transform we avoid performing an extra
126    // copy of the data that would be needed to hide the transform from the
127    // user.
128    //
129    // The matrix is stored in column-major order so that it may be passed
130    // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
131    // functions.
132    void getTransformMatrix(float mtx[16]);
133
134    // getTimestamp retrieves the timestamp associated with the texture image
135    // set by the most recent call to updateTexImage.
136    //
137    // The timestamp is in nanoseconds, and is monotonically increasing. Its
138    // other semantics (zero point, etc) are source-dependent and should be
139    // documented by the source.
140    int64_t getTimestamp();
141
142    // setFrameAvailableListener sets the listener object that will be notified
143    // when a new frame becomes available.
144    void setFrameAvailableListener(const sp<FrameAvailableListener>& listener);
145
146    // getAllocator retrieves the binder object that must be referenced as long
147    // as the GraphicBuffers dequeued from this SurfaceTexture are referenced.
148    // Holding this binder reference prevents SurfaceFlinger from freeing the
149    // buffers before the client is done with them.
150    sp<IBinder> getAllocator();
151
152    // setDefaultBufferSize is used to set the size of buffers returned by
153    // requestBuffers when a with and height of zero is requested.
154    // A call to setDefaultBufferSize() may trigger requestBuffers() to
155    // be called from the client.
156    status_t setDefaultBufferSize(uint32_t w, uint32_t h);
157
158    // getCurrentBuffer returns the buffer associated with the current image.
159    sp<GraphicBuffer> getCurrentBuffer() const;
160
161    // getCurrentTextureTarget returns the texture target of the current
162    // texture as returned by updateTexImage().
163    GLenum getCurrentTextureTarget() const;
164
165    // getCurrentCrop returns the cropping rectangle of the current buffer
166    Rect getCurrentCrop() const;
167
168    // getCurrentTransform returns the transform of the current buffer
169    uint32_t getCurrentTransform() const;
170
171    // dump our state in a String
172    void dump(String8& result) const;
173    void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
174
175protected:
176
177    // freeAllBuffers frees the resources (both GraphicBuffer and EGLImage) for
178    // all slots.
179    void freeAllBuffers();
180    static bool isExternalFormat(uint32_t format);
181    static GLenum getTextureTarget(uint32_t format);
182
183private:
184
185    // createImage creates a new EGLImage from a GraphicBuffer.
186    EGLImageKHR createImage(EGLDisplay dpy,
187            const sp<GraphicBuffer>& graphicBuffer);
188
189    status_t setBufferCountServerLocked(int bufferCount);
190
191    // computeCurrentTransformMatrix computes the transform matrix for the
192    // current texture.  It uses mCurrentTransform and the current GraphicBuffer
193    // to compute this matrix and stores it in mCurrentTransformMatrix.
194    void computeCurrentTransformMatrix();
195
196    enum { INVALID_BUFFER_SLOT = -1 };
197
198    struct BufferSlot {
199
200        BufferSlot()
201            : mEglImage(EGL_NO_IMAGE_KHR),
202              mEglDisplay(EGL_NO_DISPLAY),
203              mBufferState(BufferSlot::FREE),
204              mRequestBufferCalled(false),
205              mTransform(0),
206              mTimestamp(0) {
207            mCrop.makeInvalid();
208        }
209
210        // mGraphicBuffer points to the buffer allocated for this slot or is NULL
211        // if no buffer has been allocated.
212        sp<GraphicBuffer> mGraphicBuffer;
213
214        // mEglImage is the EGLImage created from mGraphicBuffer.
215        EGLImageKHR mEglImage;
216
217        // mEglDisplay is the EGLDisplay used to create mEglImage.
218        EGLDisplay mEglDisplay;
219
220        // BufferState represents the different states in which a buffer slot
221        // can be.
222        enum BufferState {
223            // FREE indicates that the buffer is not currently being used and
224            // will not be used in the future until it gets dequeued and
225            // subseqently queued by the client.
226            FREE = 0,
227
228            // DEQUEUED indicates that the buffer has been dequeued by the
229            // client, but has not yet been queued or canceled. The buffer is
230            // considered 'owned' by the client, and the server should not use
231            // it for anything.
232            //
233            // Note that when in synchronous-mode (mSynchronousMode == true),
234            // the buffer that's currently attached to the texture may be
235            // dequeued by the client.  That means that the current buffer can
236            // be in either the DEQUEUED or QUEUED state.  In asynchronous mode,
237            // however, the current buffer is always in the QUEUED state.
238            DEQUEUED = 1,
239
240            // QUEUED indicates that the buffer has been queued by the client,
241            // and has not since been made available for the client to dequeue.
242            // Attaching the buffer to the texture does NOT transition the
243            // buffer away from the QUEUED state. However, in Synchronous mode
244            // the current buffer may be dequeued by the client under some
245            // circumstances. See the note about the current buffer in the
246            // documentation for DEQUEUED.
247            QUEUED = 2,
248        };
249
250        // mBufferState is the current state of this buffer slot.
251        BufferState mBufferState;
252
253        // mRequestBufferCalled is used for validating that the client did
254        // call requestBuffer() when told to do so. Technically this is not
255        // needed but useful for debugging and catching client bugs.
256        bool mRequestBufferCalled;
257
258        // mCrop is the current crop rectangle for this buffer slot. This gets
259        // set to mNextCrop each time queueBuffer gets called for this buffer.
260        Rect mCrop;
261
262        // mTransform is the current transform flags for this buffer slot. This
263        // gets set to mNextTransform each time queueBuffer gets called for this
264        // slot.
265        uint32_t mTransform;
266
267        // mTimestamp is the current timestamp for this buffer slot. This gets
268        // to set by queueBuffer each time this slot is queued.
269        int64_t mTimestamp;
270    };
271
272    // mSlots is the array of buffer slots that must be mirrored on the client
273    // side. This allows buffer ownership to be transferred between the client
274    // and server without sending a GraphicBuffer over binder. The entire array
275    // is initialized to NULL at construction time, and buffers are allocated
276    // for a slot when requestBuffer is called with that slot's index.
277    BufferSlot mSlots[NUM_BUFFER_SLOTS];
278
279    // mDefaultWidth holds the default width of allocated buffers. It is used
280    // in requestBuffers() if a width and height of zero is specified.
281    uint32_t mDefaultWidth;
282
283    // mDefaultHeight holds the default height of allocated buffers. It is used
284    // in requestBuffers() if a width and height of zero is specified.
285    uint32_t mDefaultHeight;
286
287    // mPixelFormat holds the pixel format of allocated buffers. It is used
288    // in requestBuffers() if a format of zero is specified.
289    uint32_t mPixelFormat;
290
291    // mBufferCount is the number of buffer slots that the client and server
292    // must maintain. It defaults to MIN_ASYNC_BUFFER_SLOTS and can be changed
293    // by calling setBufferCount or setBufferCountServer
294    int mBufferCount;
295
296    // mClientBufferCount is the number of buffer slots requested by the client.
297    // The default is zero, which means the client doesn't care how many buffers
298    // there is.
299    int mClientBufferCount;
300
301    // mServerBufferCount buffer count requested by the server-side
302    int mServerBufferCount;
303
304    // mCurrentTexture is the buffer slot index of the buffer that is currently
305    // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
306    // indicating that no buffer slot is currently bound to the texture. Note,
307    // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
308    // that no buffer is bound to the texture. A call to setBufferCount will
309    // reset mCurrentTexture to INVALID_BUFFER_SLOT.
310    int mCurrentTexture;
311
312    // mCurrentTextureTarget is the GLES texture target to be used with the
313    // current texture.
314    GLenum mCurrentTextureTarget;
315
316    // mCurrentTextureBuf is the graphic buffer of the current texture. It's
317    // possible that this buffer is not associated with any buffer slot, so we
318    // must track it separately in order to properly use
319    // IGraphicBufferAlloc::freeAllGraphicBuffersExcept.
320    sp<GraphicBuffer> mCurrentTextureBuf;
321
322    // mCurrentCrop is the crop rectangle that applies to the current texture.
323    // It gets set to mLastQueuedCrop each time updateTexImage is called.
324    Rect mCurrentCrop;
325
326    // mCurrentTransform is the transform identifier for the current texture. It
327    // gets set to mLastQueuedTransform each time updateTexImage is called.
328    uint32_t mCurrentTransform;
329
330    // mCurrentTransformMatrix is the transform matrix for the current texture.
331    // It gets computed by computeTransformMatrix each time updateTexImage is
332    // called.
333    float mCurrentTransformMatrix[16];
334
335    // mCurrentTimestamp is the timestamp for the current texture. It
336    // gets set to mLastQueuedTimestamp each time updateTexImage is called.
337    int64_t mCurrentTimestamp;
338
339    // mNextCrop is the crop rectangle that will be used for the next buffer
340    // that gets queued. It is set by calling setCrop.
341    Rect mNextCrop;
342
343    // mNextTransform is the transform identifier that will be used for the next
344    // buffer that gets queued. It is set by calling setTransform.
345    uint32_t mNextTransform;
346
347    // mTexName is the name of the OpenGL texture to which streamed images will
348    // be bound when updateTexImage is called. It is set at construction time
349    // changed with a call to setTexName.
350    const GLuint mTexName;
351
352    // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to
353    // allocate new GraphicBuffer objects.
354    sp<IGraphicBufferAlloc> mGraphicBufferAlloc;
355
356    // mFrameAvailableListener is the listener object that will be called when a
357    // new frame becomes available. If it is not NULL it will be called from
358    // queueBuffer.
359    sp<FrameAvailableListener> mFrameAvailableListener;
360
361    // mSynchronousMode whether we're in synchronous mode or not
362    bool mSynchronousMode;
363
364    // mAllowSynchronousMode whether we allow synchronous mode or not
365    const bool mAllowSynchronousMode;
366
367    // mDequeueCondition condition used for dequeueBuffer in synchronous mode
368    mutable Condition mDequeueCondition;
369
370    // mQueue is a FIFO of queued buffers used in synchronous mode
371    typedef Vector<int> Fifo;
372    Fifo mQueue;
373
374    // mMutex is the mutex used to prevent concurrent access to the member
375    // variables of SurfaceTexture objects. It must be locked whenever the
376    // member variables are accessed.
377    mutable Mutex mMutex;
378
379};
380
381// ----------------------------------------------------------------------------
382}; // namespace android
383
384#endif // ANDROID_GUI_SURFACETEXTURE_H
385