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