SurfaceTexture.h revision ce561372186c7549a8a5fe996ac5965cda087007
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#include <GLES2/gl2ext.h>
24
25#include <gui/ISurfaceTexture.h>
26#include <gui/BufferQueue.h>
27
28#include <ui/GraphicBuffer.h>
29
30#include <utils/String8.h>
31#include <utils/Vector.h>
32#include <utils/threads.h>
33
34#define ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID "mSurfaceTexture"
35
36namespace android {
37// ----------------------------------------------------------------------------
38
39
40class String8;
41
42class SurfaceTexture : public virtual RefBase,
43        protected BufferQueue::ConsumerListener {
44public:
45    struct FrameAvailableListener : public virtual RefBase {
46        // onFrameAvailable() is called each time an additional frame becomes
47        // available for consumption. This means that frames that are queued
48        // while in asynchronous mode only trigger the callback if no previous
49        // frames are pending. Frames queued while in synchronous mode always
50        // trigger the callback.
51        //
52        // This is called without any lock held and can be called concurrently
53        // by multiple threads.
54        virtual void onFrameAvailable() = 0;
55    };
56
57    // SurfaceTexture constructs a new SurfaceTexture object. tex indicates the
58    // name of the OpenGL ES texture to which images are to be streamed. This
59    // texture name cannot be changed once the SurfaceTexture is created.
60    // allowSynchronousMode specifies whether or not synchronous mode can be
61    // enabled. texTarget specifies the OpenGL ES texture target to which the
62    // texture will be bound in updateTexImage. useFenceSync specifies whether
63    // fences should be used to synchronize access to buffers if that behavior
64    // is enabled at compile-time. A custom bufferQueue can be specified
65    // if behavior for queue/dequeue/connect etc needs to be customized.
66    // Otherwise a default BufferQueue will be created and used.
67    SurfaceTexture(GLuint tex, bool allowSynchronousMode = true,
68            GLenum texTarget = GL_TEXTURE_EXTERNAL_OES, bool useFenceSync = true,
69            const sp<BufferQueue> &bufferQueue = 0);
70
71    virtual ~SurfaceTexture();
72
73    // updateTexImage sets the image contents of the target texture to that of
74    // the most recently queued buffer.
75    //
76    // This call may only be made while the OpenGL ES context to which the
77    // target texture belongs is bound to the calling thread.
78    status_t updateTexImage();
79
80    // setBufferCountServer set the buffer count. If the client has requested
81    // a buffer count using setBufferCount, the server-buffer count will
82    // take effect once the client sets the count back to zero.
83    status_t setBufferCountServer(int bufferCount);
84
85    // getTransformMatrix retrieves the 4x4 texture coordinate transform matrix
86    // associated with the texture image set by the most recent call to
87    // updateTexImage.
88    //
89    // This transform matrix maps 2D homogeneous texture coordinates of the form
90    // (s, t, 0, 1) with s and t in the inclusive range [0, 1] to the texture
91    // coordinate that should be used to sample that location from the texture.
92    // Sampling the texture outside of the range of this transform is undefined.
93    //
94    // This transform is necessary to compensate for transforms that the stream
95    // content producer may implicitly apply to the content. By forcing users of
96    // a SurfaceTexture to apply this transform we avoid performing an extra
97    // copy of the data that would be needed to hide the transform from the
98    // user.
99    //
100    // The matrix is stored in column-major order so that it may be passed
101    // directly to OpenGL ES via the glLoadMatrixf or glUniformMatrix4fv
102    // functions.
103    void getTransformMatrix(float mtx[16]);
104
105    // getTimestamp retrieves the timestamp associated with the texture image
106    // set by the most recent call to updateTexImage.
107    //
108    // The timestamp is in nanoseconds, and is monotonically increasing. Its
109    // other semantics (zero point, etc) are source-dependent and should be
110    // documented by the source.
111    int64_t getTimestamp();
112
113    // setFrameAvailableListener sets the listener object that will be notified
114    // when a new frame becomes available.
115    void setFrameAvailableListener(const sp<FrameAvailableListener>& listener);
116
117    // getAllocator retrieves the binder object that must be referenced as long
118    // as the GraphicBuffers dequeued from this SurfaceTexture are referenced.
119    // Holding this binder reference prevents SurfaceFlinger from freeing the
120    // buffers before the client is done with them.
121    sp<IBinder> getAllocator();
122
123    // setDefaultBufferSize is used to set the size of buffers returned by
124    // requestBuffers when a with and height of zero is requested.
125    // A call to setDefaultBufferSize() may trigger requestBuffers() to
126    // be called from the client.
127    // The width and height parameters must be no greater than the minimum of
128    // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
129    // An error due to invalid dimensions might not be reported until
130    // updateTexImage() is called.
131    status_t setDefaultBufferSize(uint32_t width, uint32_t height);
132
133    // getCurrentBuffer returns the buffer associated with the current image.
134    sp<GraphicBuffer> getCurrentBuffer() const;
135
136    // getCurrentTextureTarget returns the texture target of the current
137    // texture as returned by updateTexImage().
138    GLenum getCurrentTextureTarget() const;
139
140    // getCurrentCrop returns the cropping rectangle of the current buffer
141    Rect getCurrentCrop() const;
142
143    // getCurrentTransform returns the transform of the current buffer
144    uint32_t getCurrentTransform() const;
145
146    // getCurrentScalingMode returns the scaling mode of the current buffer
147    uint32_t getCurrentScalingMode() const;
148
149    // isSynchronousMode returns whether the SurfaceTexture is currently in
150    // synchronous mode.
151    bool isSynchronousMode() const;
152
153    // abandon frees all the buffers and puts the SurfaceTexture into the
154    // 'abandoned' state.  Once put in this state the SurfaceTexture can never
155    // leave it.  When in the 'abandoned' state, all methods of the
156    // ISurfaceTexture interface will fail with the NO_INIT error.
157    //
158    // Note that while calling this method causes all the buffers to be freed
159    // from the perspective of the the SurfaceTexture, if there are additional
160    // references on the buffers (e.g. if a buffer is referenced by a client or
161    // by OpenGL ES as a texture) then those buffer will remain allocated.
162    void abandon();
163
164    // set the name of the SurfaceTexture that will be used to identify it in
165    // log messages.
166    void setName(const String8& name);
167
168    // These functions call the corresponding BufferQueue implementation
169    // so the refactoring can proceed smoothly
170    status_t setDefaultBufferFormat(uint32_t defaultFormat);
171    status_t setConsumerUsageBits(uint32_t usage);
172    status_t setTransformHint(uint32_t hint);
173    virtual status_t setSynchronousMode(bool enabled);
174    virtual status_t setBufferCount(int bufferCount);
175    virtual status_t connect(int api,
176                uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform);
177
178    sp<BufferQueue> getBufferQueue() const;
179
180    // dump our state in a String
181    virtual void dump(String8& result) const;
182    virtual void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
183
184protected:
185
186    // Implementation of the BufferQueue::ConsumerListener interface.  These
187    // calls are used to notify the SurfaceTexture of asynchronous events in the
188    // BufferQueue.
189    virtual void onFrameAvailable();
190    virtual void onBuffersReleased();
191
192    static bool isExternalFormat(uint32_t format);
193
194private:
195
196    // createImage creates a new EGLImage from a GraphicBuffer.
197    EGLImageKHR createImage(EGLDisplay dpy,
198            const sp<GraphicBuffer>& graphicBuffer);
199
200    // freeBufferLocked frees up the given buffer slot.  If the slot has been
201    // initialized this will release the reference to the GraphicBuffer in that
202    // slot and destroy the EGLImage in that slot.  Otherwise it has no effect.
203    //
204    // This method must be called with mMutex locked.
205    void freeBufferLocked(int slotIndex);
206
207    // computeCurrentTransformMatrix computes the transform matrix for the
208    // current texture.  It uses mCurrentTransform and the current GraphicBuffer
209    // to compute this matrix and stores it in mCurrentTransformMatrix.
210    void computeCurrentTransformMatrix();
211
212    // mCurrentTextureBuf is the graphic buffer of the current texture. It's
213    // possible that this buffer is not associated with any buffer slot, so we
214    // must track it separately in order to support the getCurrentBuffer method.
215    sp<GraphicBuffer> mCurrentTextureBuf;
216
217    // mCurrentCrop is the crop rectangle that applies to the current texture.
218    // It gets set each time updateTexImage is called.
219    Rect mCurrentCrop;
220
221    // mCurrentTransform is the transform identifier for the current texture. It
222    // gets set each time updateTexImage is called.
223    uint32_t mCurrentTransform;
224
225    // mCurrentScalingMode is the scaling mode for the current texture. It gets
226    // set to each time updateTexImage is called.
227    uint32_t mCurrentScalingMode;
228
229    // mCurrentTransformMatrix is the transform matrix for the current texture.
230    // It gets computed by computeTransformMatrix each time updateTexImage is
231    // called.
232    float mCurrentTransformMatrix[16];
233
234    // mCurrentTimestamp is the timestamp for the current texture. It
235    // gets set each time updateTexImage is called.
236    int64_t mCurrentTimestamp;
237
238    // mTexName is the name of the OpenGL texture to which streamed images will
239    // be bound when updateTexImage is called. It is set at construction time
240    // changed with a call to setTexName.
241    const GLuint mTexName;
242
243    // mUseFenceSync indicates whether creation of the EGL_KHR_fence_sync
244    // extension should be used to prevent buffers from being dequeued before
245    // it's safe for them to be written. It gets set at construction time and
246    // never changes.
247    const bool mUseFenceSync;
248
249    // mTexTarget is the GL texture target with which the GL texture object is
250    // associated.  It is set in the constructor and never changed.  It is
251    // almost always GL_TEXTURE_EXTERNAL_OES except for one use case in Android
252    // Browser.  In that case it is set to GL_TEXTURE_2D to allow
253    // glCopyTexSubImage to read from the texture.  This is a hack to work
254    // around a GL driver limitation on the number of FBO attachments, which the
255    // browser's tile cache exceeds.
256    const GLenum mTexTarget;
257
258    // EGLSlot contains the information and object references that
259    // SurfaceTexture maintains about a BufferQueue buffer slot.
260    struct EGLSlot {
261        EGLSlot()
262        : mEglImage(EGL_NO_IMAGE_KHR),
263          mFence(EGL_NO_SYNC_KHR) {
264        }
265
266        sp<GraphicBuffer> mGraphicBuffer;
267
268        // mEglImage is the EGLImage created from mGraphicBuffer.
269        EGLImageKHR mEglImage;
270
271        // mFence is the EGL sync object that must signal before the buffer
272        // associated with this buffer slot may be dequeued. It is initialized
273        // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
274        // on a compile-time option) set to a new sync object in updateTexImage.
275        EGLSyncKHR mFence;
276    };
277
278    // mEglDisplay is the EGLDisplay with which this SurfaceTexture is currently
279    // associated.  It is intialized to EGL_NO_DISPLAY and gets set to the
280    // current display when updateTexImage is called for the first time.
281    EGLDisplay mEglDisplay;
282
283    // mEglContext is the OpenGL ES context with which this SurfaceTexture is
284    // currently associated.  It is initialized to EGL_NO_CONTEXT and gets set
285    // to the current GL context when updateTexImage is called for the first
286    // time.
287    EGLContext mEglContext;
288
289    // mEGLSlots stores the buffers that have been allocated by the BufferQueue
290    // for each buffer slot.  It is initialized to null pointers, and gets
291    // filled in with the result of BufferQueue::acquire when the
292    // client dequeues a buffer from a
293    // slot that has not yet been used. The buffer allocated to a slot will also
294    // be replaced if the requested buffer usage or geometry differs from that
295    // of the buffer allocated to a slot.
296    EGLSlot mEGLSlots[BufferQueue::NUM_BUFFER_SLOTS];
297
298    // mAbandoned indicates that the BufferQueue will no longer be used to
299    // consume images buffers pushed to it using the ISurfaceTexture interface.
300    // It is initialized to false, and set to true in the abandon method.  A
301    // BufferQueue that has been abandoned will return the NO_INIT error from
302    // all ISurfaceTexture methods capable of returning an error.
303    bool mAbandoned;
304
305    // mName is a string used to identify the SurfaceTexture in log messages.
306    // It can be set by the setName method.
307    String8 mName;
308
309    // mFrameAvailableListener is the listener object that will be called when a
310    // new frame becomes available. If it is not NULL it will be called from
311    // queueBuffer.
312    sp<FrameAvailableListener> mFrameAvailableListener;
313
314    // mCurrentTexture is the buffer slot index of the buffer that is currently
315    // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
316    // indicating that no buffer slot is currently bound to the texture. Note,
317    // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
318    // that no buffer is bound to the texture. A call to setBufferCount will
319    // reset mCurrentTexture to INVALID_BUFFER_SLOT.
320    int mCurrentTexture;
321
322    // The SurfaceTexture has-a BufferQueue and is responsible for creating this object
323    // if none is supplied
324    sp<BufferQueue> mBufferQueue;
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