SurfaceMediaSource.h revision b33f3407bab0970a7f9241680723a1140b177c50
1/*
2 * Copyright (C) 2011 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_SURFACEMEDIASOURCE_H
18#define ANDROID_GUI_SURFACEMEDIASOURCE_H
19
20#include <gui/ISurfaceTexture.h>
21
22#include <utils/threads.h>
23#include <utils/Vector.h>
24#include <media/stagefright/MediaSource.h>
25#include <media/stagefright/MediaBuffer.h>
26
27namespace android {
28// ----------------------------------------------------------------------------
29
30class IGraphicBufferAlloc;
31class String8;
32class GraphicBuffer;
33
34class SurfaceMediaSource : public BnSurfaceTexture, public MediaSource,
35                                            public MediaBufferObserver {
36public:
37    enum { MIN_UNDEQUEUED_BUFFERS = 3 };
38    enum {
39        MIN_ASYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS + 1,
40        MIN_SYNC_BUFFER_SLOTS  = MIN_UNDEQUEUED_BUFFERS
41    };
42    enum { NUM_BUFFER_SLOTS = 32 };
43    enum { NO_CONNECTED_API = 0 };
44
45    struct FrameAvailableListener : public virtual RefBase {
46        // onFrameAvailable() is called from queueBuffer() is the FIFO is
47        // empty. You can use SurfaceMediaSource::getQueuedCount() to
48        // figure out if there are more frames waiting.
49        // This is called without any lock held can be called concurrently by
50        // multiple threads.
51        virtual void onFrameAvailable() = 0;
52    };
53
54    SurfaceMediaSource(uint32_t bufW, uint32_t bufH);
55
56    virtual ~SurfaceMediaSource();
57
58
59    // For the MediaSource interface for use by StageFrightRecorder:
60    virtual status_t start(MetaData *params = NULL);
61    virtual status_t stop();
62    virtual status_t read(
63            MediaBuffer **buffer, const ReadOptions *options = NULL);
64    virtual sp<MetaData> getFormat();
65
66    // Get / Set the frame rate used for encoding. Default fps = 30
67    status_t setFrameRate(int32_t fps) ;
68    int32_t getFrameRate( ) const;
69
70    // The call for the StageFrightRecorder to tell us that
71    // it is done using the MediaBuffer data so that its state
72    // can be set to FREE for dequeuing
73    virtual void signalBufferReturned(MediaBuffer* buffer);
74    // end of MediaSource interface
75
76    uint32_t getBufferCount( ) const { return mBufferCount;}
77
78
79    // setBufferCount updates the number of available buffer slots.  After
80    // calling this all buffer slots are both unallocated and owned by the
81    // SurfaceMediaSource object (i.e. they are not owned by the client).
82    virtual status_t setBufferCount(int bufferCount);
83
84    virtual sp<GraphicBuffer> requestBuffer(int buf);
85
86    // dequeueBuffer gets the next buffer slot index for the client to use. If a
87    // buffer slot is available then that slot index is written to the location
88    // pointed to by the buf argument and a status of OK is returned.  If no
89    // slot is available then a status of -EBUSY is returned and buf is
90    // unmodified.
91    virtual status_t dequeueBuffer(int *buf, uint32_t w, uint32_t h,
92            uint32_t format, uint32_t usage);
93
94    // queueBuffer returns a filled buffer to the SurfaceMediaSource. In addition, a
95    // timestamp must be provided for the buffer. The timestamp is in
96    // nanoseconds, and must be monotonically increasing. Its other semantics
97    // (zero point, etc) are client-dependent and should be documented by the
98    // client.
99    virtual status_t queueBuffer(int buf, int64_t timestamp,
100            uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform);
101    virtual void cancelBuffer(int buf);
102
103    // onFrameReceivedLocked informs the buffer consumers (StageFrightRecorder)
104    // or listeners that a frame has been received
105    // The buffer is not made available for dequeueing immediately. We need to
106    // wait to hear from StageFrightRecorder to set the buffer FREE
107    // Make sure this is called when the mutex is locked
108    virtual status_t onFrameReceivedLocked();
109
110    virtual status_t setScalingMode(int mode) { } // no op for encoding
111    virtual int query(int what, int* value);
112
113    // Just confirming to the ISurfaceTexture interface as of now
114    virtual status_t setCrop(const Rect& reg) { return OK; }
115    virtual status_t setTransform(uint32_t transform) {return OK;}
116
117    // setSynchronousMode set whether dequeueBuffer is synchronous or
118    // asynchronous. In synchronous mode, dequeueBuffer blocks until
119    // a buffer is available, the currently bound buffer can be dequeued and
120    // queued buffers will be retired in order.
121    // The default mode is synchronous.
122    // TODO: Clarify the minute differences bet sycn /async
123    // modes (S.Encoder vis-a-vis SurfaceTexture)
124    virtual status_t setSynchronousMode(bool enabled);
125
126    // connect attempts to connect a client API to the SurfaceMediaSource.  This
127    // must be called before any other ISurfaceTexture methods are called except
128    // for getAllocator.
129    //
130    // This method will fail if the connect was previously called on the
131    // SurfaceMediaSource and no corresponding disconnect call was made.
132    virtual status_t connect(int api);
133
134    // disconnect attempts to disconnect a client API from the SurfaceMediaSource.
135    // Calling this method will cause any subsequent calls to other
136    // ISurfaceTexture methods to fail except for getAllocator and connect.
137    // Successfully calling connect after this will allow the other methods to
138    // succeed again.
139    //
140    // This method will fail if the the SurfaceMediaSource is not currently
141    // connected to the specified client API.
142    virtual status_t disconnect(int api);
143
144    // getqueuedCount returns the number of queued frames waiting in the
145    // FIFO. In asynchronous mode, this always returns 0 or 1 since
146    // frames are not accumulating in the FIFO.
147    size_t getQueuedCount() const;
148
149    // setBufferCountServer set the buffer count. If the client has requested
150    // a buffer count using setBufferCount, the server-buffer count will
151    // take effect once the client sets the count back to zero.
152    status_t setBufferCountServer(int bufferCount);
153
154    // getTimestamp retrieves the timestamp associated with the image
155    // set by the most recent call to updateFrameInfoLocked().
156    //
157    // The timestamp is in nanoseconds, and is monotonically increasing. Its
158    // other semantics (zero point, etc) are source-dependent and should be
159    // documented by the source.
160    int64_t getTimestamp();
161
162    // setFrameAvailableListener sets the listener object that will be notified
163    // when a new frame becomes available.
164    void setFrameAvailableListener(const sp<FrameAvailableListener>& listener);
165
166    // getAllocator retrieves the binder object that must be referenced as long
167    // as the GraphicBuffers dequeued from this SurfaceMediaSource are referenced.
168    // Holding this binder reference prevents SurfaceFlinger from freeing the
169    // buffers before the client is done with them.
170    sp<IBinder> getAllocator();
171
172
173    // getCurrentBuffer returns the buffer associated with the current image.
174    sp<GraphicBuffer> getCurrentBuffer() const;
175
176    // dump our state in a String
177    void dump(String8& result) const;
178    void dump(String8& result, const char* prefix, char* buffer,
179                                                    size_t SIZE) const;
180
181    // isMetaDataStoredInVideoBuffers tells the encoder whether we will
182    // pass metadata through the buffers. Currently, it is force set to true
183    bool isMetaDataStoredInVideoBuffers() const;
184
185protected:
186
187    // freeAllBuffers frees the resources (both GraphicBuffer and EGLImage) for
188    // all slots.
189    void freeAllBuffers();
190    static bool isExternalFormat(uint32_t format);
191
192private:
193
194    status_t setBufferCountServerLocked(int bufferCount);
195
196    enum { INVALID_BUFFER_SLOT = -1 };
197
198    struct BufferSlot {
199
200        BufferSlot()
201            : mBufferState(BufferSlot::FREE),
202              mRequestBufferCalled(false),
203              mTimestamp(0) {
204        }
205
206        // mGraphicBuffer points to the buffer allocated for this slot or is
207        // NULL if no buffer has been allocated.
208        sp<GraphicBuffer> mGraphicBuffer;
209
210        // BufferState represents the different states in which a buffer slot
211        // can be.
212        enum BufferState {
213            // FREE indicates that the buffer is not currently being used and
214            // will not be used in the future until it gets dequeued and
215            // subseqently queued by the client.
216            FREE = 0,
217
218            // DEQUEUED indicates that the buffer has been dequeued by the
219            // client, but has not yet been queued or canceled. The buffer is
220            // considered 'owned' by the client, and the server should not use
221            // it for anything.
222            //
223            // Note that when in synchronous-mode (mSynchronousMode == true),
224            // the buffer that's currently attached to the texture may be
225            // dequeued by the client.  That means that the current buffer can
226            // be in either the DEQUEUED or QUEUED state.  In asynchronous mode,
227            // however, the current buffer is always in the QUEUED state.
228            DEQUEUED = 1,
229
230            // QUEUED indicates that the buffer has been queued by the client,
231            // and has not since been made available for the client to dequeue.
232            // Attaching the buffer to the texture does NOT transition the
233            // buffer away from the QUEUED state. However, in Synchronous mode
234            // the current buffer may be dequeued by the client under some
235            // circumstances. See the note about the current buffer in the
236            // documentation for DEQUEUED.
237            QUEUED = 2,
238        };
239
240        // mBufferState is the current state of this buffer slot.
241        BufferState mBufferState;
242
243        // mRequestBufferCalled is used for validating that the client did
244        // call requestBuffer() when told to do so. Technically this is not
245        // needed but useful for debugging and catching client bugs.
246        bool mRequestBufferCalled;
247
248        // mTimestamp is the current timestamp for this buffer slot. This gets
249        // to set by queueBuffer each time this slot is queued.
250        int64_t mTimestamp;
251    };
252
253    // mSlots is the array of buffer slots that must be mirrored on the client
254    // side. This allows buffer ownership to be transferred between the client
255    // and server without sending a GraphicBuffer over binder. The entire array
256    // is initialized to NULL at construction time, and buffers are allocated
257    // for a slot when requestBuffer is called with that slot's index.
258    BufferSlot mSlots[NUM_BUFFER_SLOTS];
259
260    // mDefaultWidth holds the default width of allocated buffers. It is used
261    // in requestBuffers() if a width and height of zero is specified.
262    uint32_t mDefaultWidth;
263
264    // mDefaultHeight holds the default height of allocated buffers. It is used
265    // in requestBuffers() if a width and height of zero is specified.
266    uint32_t mDefaultHeight;
267
268    // mPixelFormat holds the pixel format of allocated buffers. It is used
269    // in requestBuffers() if a format of zero is specified.
270    uint32_t mPixelFormat;
271
272    // mBufferCount is the number of buffer slots that the client and server
273    // must maintain. It defaults to MIN_ASYNC_BUFFER_SLOTS and can be changed
274    // by calling setBufferCount or setBufferCountServer
275    int mBufferCount;
276
277    // mClientBufferCount is the number of buffer slots requested by the
278    // client. The default is zero, which means the client doesn't care how
279    // many buffers there are
280    int mClientBufferCount;
281
282    // mServerBufferCount buffer count requested by the server-side
283    int mServerBufferCount;
284
285    // mCurrentSlot is the buffer slot index of the buffer that is currently
286    // being used by buffer consumer
287    // (e.g. StageFrightRecorder in the case of SurfaceMediaSource or GLTexture
288    // in the case of SurfaceTexture).
289    // It is initialized to INVALID_BUFFER_SLOT,
290    // indicating that no buffer slot is currently bound to the texture. Note,
291    // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
292    // that no buffer is bound to the texture. A call to setBufferCount will
293    // reset mCurrentTexture to INVALID_BUFFER_SLOT.
294    int mCurrentSlot;
295
296
297    // mCurrentBuf is the graphic buffer of the current slot to be used by
298    // buffer consumer. It's possible that this buffer is not associated
299    // with any buffer slot, so we must track it separately in order to
300    // properly use IGraphicBufferAlloc::freeAllGraphicBuffersExcept.
301    sp<GraphicBuffer> mCurrentBuf;
302
303
304    // mCurrentTimestamp is the timestamp for the current texture. It
305    // gets set to mLastQueuedTimestamp each time updateTexImage is called.
306    int64_t mCurrentTimestamp;
307
308    // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to
309    // allocate new GraphicBuffer objects.
310    sp<IGraphicBufferAlloc> mGraphicBufferAlloc;
311
312    // mFrameAvailableListener is the listener object that will be called when a
313    // new frame becomes available. If it is not NULL it will be called from
314    // queueBuffer.
315    sp<FrameAvailableListener> mFrameAvailableListener;
316
317    // mSynchronousMode whether we're in synchronous mode or not
318    bool mSynchronousMode;
319
320    // mConnectedApi indicates the API that is currently connected to this
321    // SurfaceTexture.  It defaults to NO_CONNECTED_API (= 0), and gets updated
322    // by the connect and disconnect methods.
323    int mConnectedApi;
324
325    // mDequeueCondition condition used for dequeueBuffer in synchronous mode
326    mutable Condition mDequeueCondition;
327
328
329    // mQueue is a FIFO of queued buffers used in synchronous mode
330    typedef Vector<int> Fifo;
331    Fifo mQueue;
332
333    // mMutex is the mutex used to prevent concurrent access to the member
334    // variables of SurfaceMediaSource objects. It must be locked whenever the
335    // member variables are accessed.
336    mutable Mutex mMutex;
337
338    ////////////////////////// For MediaSource
339    // Set to a default of 30 fps if not specified by the client side
340    int32_t mFrameRate;
341
342    // mStarted is a flag to check if the recording has started
343    bool mStarted;
344
345    // mFrameAvailableCondition condition used to indicate whether there
346    // is a frame available for dequeuing
347    Condition mFrameAvailableCondition;
348    Condition mFrameCompleteCondition;
349
350    // Avoid copying and equating and default constructor
351    DISALLOW_IMPLICIT_CONSTRUCTORS(SurfaceMediaSource);
352};
353
354// ----------------------------------------------------------------------------
355}; // namespace android
356
357#endif // ANDROID_GUI_SURFACEMEDIASOURCE_H
358