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