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