SurfaceTexture.h revision b3e518c820c7dbe35587bd45c510e4e5e7cfd9c9
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;
37
38class SurfaceTexture : public BnSurfaceTexture {
39public:
40    enum { MIN_UNDEQUEUED_BUFFERS = 2 };
41    enum { MIN_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS + 1 };
42    enum { NUM_BUFFER_SLOTS = 32 };
43
44    struct FrameAvailableListener : public virtual RefBase {
45        virtual void onFrameAvailable() = 0;
46    };
47
48    // tex indicates the name OpenGL texture to which images are to be streamed.
49    // This texture name cannot be changed once the SurfaceTexture is created.
50    SurfaceTexture(GLuint tex);
51
52    virtual ~SurfaceTexture();
53
54    // setBufferCount updates the number of available buffer slots.  After
55    // calling this all buffer slots are both unallocated and owned by the
56    // SurfaceTexture object (i.e. they are not owned by the client).
57    virtual status_t setBufferCount(int bufferCount);
58
59    virtual sp<GraphicBuffer> requestBuffer(int buf);
60
61    // dequeueBuffer gets the next buffer slot index for the client to use. If a
62    // buffer slot is available then that slot index is written to the location
63    // pointed to by the buf argument and a status of OK is returned.  If no
64    // slot is available then a status of -EBUSY is returned and buf is
65    // unmodified.
66    virtual status_t dequeueBuffer(int *buf, uint32_t w, uint32_t h,
67            uint32_t format, uint32_t usage);
68
69    // queueBuffer returns a filled buffer to the SurfaceTexture. In addition, a
70    // timestamp must be provided for the buffer. The timestamp is in
71    // nanoseconds, and must be monotonically increasing. Its other semantics
72    // (zero point, etc) are client-dependent and should be documented by the
73    // client.
74    virtual status_t queueBuffer(int buf, int64_t timestamp);
75    virtual void cancelBuffer(int buf);
76    virtual status_t setCrop(const Rect& reg);
77    virtual status_t setTransform(uint32_t transform);
78
79    virtual int query(int what, int* value);
80
81    // updateTexImage sets the image contents of the target texture to that of
82    // the most recently queued buffer.
83    //
84    // This call may only be made while the OpenGL ES context to which the
85    // target texture belongs is bound to the calling thread.
86    status_t updateTexImage();
87
88    // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
89    // associated with the texture image set by the most recent call to
90    // updateTexImage.
91    //
92    // This transform matrix maps 2D homogeneous texture coordinates of the form
93    // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
94    // coordinate that should be used to sample that location from the texture.
95    // Sampling the texture outside of the range of this transform is undefined.
96    //
97    // This transform is necessary to compensate for transforms that the stream
98    // content producer may implicitly apply to the content. By forcing users of
99    // a SurfaceTexture to apply this transform we avoid performing an extra
100    // copy of the data that would be needed to hide the transform from the
101    // user.
102    //
103    // The matrix is stored in column-major order so that it may be passed
104    // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
105    // functions.
106    void getTransformMatrix(float mtx[16]);
107
108    // getTimestamp retrieves the timestamp associated with the texture image
109    // set by the most recent call to updateTexImage.
110    //
111    // The timestamp is in nanoseconds, and is monotonically increasing. Its
112    // other semantics (zero point, etc) are source-dependent and should be
113    // documented by the source.
114    int64_t getTimestamp();
115
116    // setFrameAvailableListener sets the listener object that will be notified
117    // when a new frame becomes available.
118    void setFrameAvailableListener(const sp<FrameAvailableListener>& l);
119
120    // getAllocator retrieves the binder object that must be referenced as long
121    // as the GraphicBuffers dequeued from this SurfaceTexture are referenced.
122    // Holding this binder reference prevents SurfaceFlinger from freeing the
123    // buffers before the client is done with them.
124    sp<IBinder> getAllocator();
125
126    // setDefaultBufferSize is used to set the size of buffers returned by
127    // requestBuffers when a with and height of zero is requested.
128    // A call to setDefaultBufferSize() may trigger requestBuffers() to
129    // be called from the client.
130    status_t setDefaultBufferSize(uint32_t w, uint32_t h);
131
132    // getCurrentBuffer returns the buffer associated with the current image.
133    sp<GraphicBuffer> getCurrentBuffer() const;
134
135    // getCurrentTextureTarget returns the texture target of the current
136    // texture as returned by updateTexImage().
137    GLenum getCurrentTextureTarget() const;
138
139    // getCurrentCrop returns the cropping rectangle of the current buffer
140    Rect getCurrentCrop() const;
141
142    // getCurrentTransform returns the transform of the current buffer
143    uint32_t getCurrentTransform() const;
144
145    // setSynchronousMode set whether dequeueBuffer is synchronous or
146    // asynchronous. In synchronous mode, dequeueBuffer blocks until
147    // a buffer is available, the currently bound buffer can be dequeued and
148    // queued buffers will be retired in order.
149    // The default mode is asynchronous.
150    status_t setSynchronousMode(bool enabled);
151
152protected:
153
154    // freeAllBuffers frees the resources (both GraphicBuffer and EGLImage) for
155    // all slots.
156    void freeAllBuffers();
157    static bool isExternalFormat(uint32_t format);
158    static GLenum getTextureTarget(uint32_t format);
159
160private:
161
162    // createImage creates a new EGLImage from a GraphicBuffer.
163    EGLImageKHR createImage(EGLDisplay dpy,
164            const sp<GraphicBuffer>& graphicBuffer);
165
166    enum { INVALID_BUFFER_SLOT = -1 };
167
168    struct BufferSlot {
169
170        BufferSlot()
171            : mEglImage(EGL_NO_IMAGE_KHR),
172              mEglDisplay(EGL_NO_DISPLAY),
173              mBufferState(BufferSlot::FREE),
174              mRequestBufferCalled(false),
175              mLastQueuedTransform(0),
176              mLastQueuedTimestamp(0) {
177        }
178
179        // mGraphicBuffer points to the buffer allocated for this slot or is NULL
180        // if no buffer has been allocated.
181        sp<GraphicBuffer> mGraphicBuffer;
182
183        // mEglImage is the EGLImage created from mGraphicBuffer.
184        EGLImageKHR mEglImage;
185
186        // mEglDisplay is the EGLDisplay used to create mEglImage.
187        EGLDisplay mEglDisplay;
188
189        // mBufferState indicates whether the slot is currently accessible to a
190        // client and should not be used by the SurfaceTexture object. It gets
191        // set to true when dequeueBuffer returns the slot and is reset to false
192        // when the client calls either queueBuffer or cancelBuffer on the slot.
193        enum { DEQUEUED=-2, FREE=-1, QUEUED=0 };
194        int8_t mBufferState;
195
196
197        // mRequestBufferCalled is used for validating that the client did
198        // call requestBuffer() when told to do so. Technically this is not
199        // needed but useful for debugging and catching client bugs.
200        bool mRequestBufferCalled;
201
202        // mLastQueuedCrop is the crop rectangle for the buffer that was most
203        // recently queued. This gets set to mNextCrop each time queueBuffer gets
204        // called.
205        Rect mLastQueuedCrop;
206
207        // mLastQueuedTransform is the transform identifier for the buffer that was
208        // most recently queued. This gets set to mNextTransform each time
209        // queueBuffer gets called.
210        uint32_t mLastQueuedTransform;
211
212        // mLastQueuedTimestamp is the timestamp for the buffer that was most
213        // recently queued. This gets set by queueBuffer.
214        int64_t mLastQueuedTimestamp;
215    };
216
217    // mSlots is the array of buffer slots that must be mirrored on the client
218    // side. This allows buffer ownership to be transferred between the client
219    // and server without sending a GraphicBuffer over binder. The entire array
220    // is initialized to NULL at construction time, and buffers are allocated
221    // for a slot when requestBuffer is called with that slot's index.
222    BufferSlot mSlots[NUM_BUFFER_SLOTS];
223
224    // mDefaultWidth holds the default width of allocated buffers. It is used
225    // in requestBuffers() if a width and height of zero is specified.
226    uint32_t mDefaultWidth;
227
228    // mDefaultHeight holds the default height of allocated buffers. It is used
229    // in requestBuffers() if a width and height of zero is specified.
230    uint32_t mDefaultHeight;
231
232    // mPixelFormat holds the pixel format of allocated buffers. It is used
233    // in requestBuffers() if a format of zero is specified.
234    uint32_t mPixelFormat;
235
236    // mBufferCount is the number of buffer slots that the client and server
237    // must maintain. It defaults to MIN_BUFFER_SLOTS and can be changed by
238    // calling setBufferCount.
239    int mBufferCount;
240
241    // mCurrentTexture is the buffer slot index of the buffer that is currently
242    // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
243    // indicating that no buffer slot is currently bound to the texture. Note,
244    // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
245    // that no buffer is bound to the texture. A call to setBufferCount will
246    // reset mCurrentTexture to INVALID_BUFFER_SLOT.
247    int mCurrentTexture;
248
249    // mCurrentTextureTarget is the GLES texture target to be used with the
250    // current texture.
251    GLenum mCurrentTextureTarget;
252
253    // mCurrentTextureBuf is the graphic buffer of the current texture. It's
254    // possible that this buffer is not associated with any buffer slot, so we
255    // must track it separately in order to properly use
256    // IGraphicBufferAlloc::freeAllGraphicBuffersExcept.
257    sp<GraphicBuffer> mCurrentTextureBuf;
258
259    // mCurrentCrop is the crop rectangle that applies to the current texture.
260    // It gets set to mLastQueuedCrop each time updateTexImage is called.
261    Rect mCurrentCrop;
262
263    // mCurrentTransform is the transform identifier for the current texture. It
264    // gets set to mLastQueuedTransform each time updateTexImage is called.
265    uint32_t mCurrentTransform;
266
267    // mCurrentTimestamp is the timestamp for the current texture. It
268    // gets set to mLastQueuedTimestamp each time updateTexImage is called.
269    int64_t mCurrentTimestamp;
270
271    // mNextCrop is the crop rectangle that will be used for the next buffer
272    // that gets queued. It is set by calling setCrop.
273    Rect mNextCrop;
274
275    // mNextTransform is the transform identifier that will be used for the next
276    // buffer that gets queued. It is set by calling setTransform.
277    uint32_t mNextTransform;
278
279    // mTexName is the name of the OpenGL texture to which streamed images will
280    // be bound when updateTexImage is called. It is set at construction time
281    // changed with a call to setTexName.
282    const GLuint mTexName;
283
284    // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to
285    // allocate new GraphicBuffer objects.
286    sp<IGraphicBufferAlloc> mGraphicBufferAlloc;
287
288    // mFrameAvailableListener is the listener object that will be called when a
289    // new frame becomes available. If it is not NULL it will be called from
290    // queueBuffer.
291    sp<FrameAvailableListener> mFrameAvailableListener;
292
293    // mSynchronousMode whether we're in synchronous mode or not
294    bool mSynchronousMode;
295
296    // mDequeueCondition condition used for dequeueBuffer in synchronous mode
297    mutable Condition mDequeueCondition;
298
299    // mQueue is a FIFO of queued buffers used in synchronous mode
300    typedef Vector<int> Fifo;
301    Fifo mQueue;
302
303    // mMutex is the mutex used to prevent concurrent access to the member
304    // variables of SurfaceTexture objects. It must be locked whenever the
305    // member variables are accessed.
306    mutable Mutex mMutex;
307};
308
309// ----------------------------------------------------------------------------
310}; // namespace android
311
312#endif // ANDROID_GUI_SURFACETEXTURE_H
313