GraphicBufferSource.h revision 8dcc81a2fdb35905347cf7ef46d198afa7ae79cd
1/*
2 * Copyright (C) 2013 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 GRAPHIC_BUFFER_SOURCE_H_
18
19#define GRAPHIC_BUFFER_SOURCE_H_
20
21#include <gui/IGraphicBufferProducer.h>
22#include <gui/BufferQueue.h>
23#include <utils/RefBase.h>
24
25#include <OMX_Core.h>
26#include "../include/OMXNodeInstance.h"
27#include <media/stagefright/foundation/ABase.h>
28#include <media/stagefright/foundation/AHandlerReflector.h>
29#include <media/stagefright/foundation/ALooper.h>
30
31namespace android {
32
33/*
34 * This class is used to feed OMX codecs from a Surface via BufferQueue.
35 *
36 * Instances of the class don't run on a dedicated thread.  Instead,
37 * various events trigger data movement:
38 *
39 *  - Availability of a new frame of data from the BufferQueue (notified
40 *    via the onFrameAvailable callback).
41 *  - The return of a codec buffer (via OnEmptyBufferDone).
42 *  - Application signaling end-of-stream.
43 *  - Transition to or from "executing" state.
44 *
45 * Frames of data (and, perhaps, the end-of-stream indication) can arrive
46 * before the codec is in the "executing" state, so we need to queue
47 * things up until we're ready to go.
48 */
49class GraphicBufferSource : public BufferQueue::ConsumerListener {
50public:
51    GraphicBufferSource(OMXNodeInstance* nodeInstance,
52            uint32_t bufferWidth, uint32_t bufferHeight, uint32_t bufferCount);
53    virtual ~GraphicBufferSource();
54
55    // We can't throw an exception if the constructor fails, so we just set
56    // this and require that the caller test the value.
57    status_t initCheck() const {
58        return mInitCheck;
59    }
60
61    // Returns the handle to the producer side of the BufferQueue.  Buffers
62    // queued on this will be received by GraphicBufferSource.
63    sp<IGraphicBufferProducer> getIGraphicBufferProducer() const {
64        return mBufferQueue;
65    }
66
67    // This is called when OMX transitions to OMX_StateExecuting, which means
68    // we can start handing it buffers.  If we already have buffers of data
69    // sitting in the BufferQueue, this will send them to the codec.
70    void omxExecuting();
71
72    // This is called when OMX transitions to OMX_StateIdle, indicating that
73    // the codec is meant to return all buffers back to the client for them
74    // to be freed. Do NOT submit any more buffers to the component.
75    void omxIdle();
76
77    // This is called when OMX transitions to OMX_StateLoaded, indicating that
78    // we are shutting down.
79    void omxLoaded();
80
81    // A "codec buffer", i.e. a buffer that can be used to pass data into
82    // the encoder, has been allocated.  (This call does not call back into
83    // OMXNodeInstance.)
84    void addCodecBuffer(OMX_BUFFERHEADERTYPE* header);
85
86    // Called from OnEmptyBufferDone.  If we have a BQ buffer available,
87    // fill it with a new frame of data; otherwise, just mark it as available.
88    void codecBufferEmptied(OMX_BUFFERHEADERTYPE* header);
89
90    // Called when omx_message::FILL_BUFFER_DONE is received. (Currently the
91    // buffer source will fix timestamp in the header if needed.)
92    void codecBufferFilled(OMX_BUFFERHEADERTYPE* header);
93
94    // This is called after the last input frame has been submitted.  We
95    // need to submit an empty buffer with the EOS flag set.  If we don't
96    // have a codec buffer ready, we just set the mEndOfStream flag.
97    status_t signalEndOfInputStream();
98
99    // If suspend is true, all incoming buffers (including those currently
100    // in the BufferQueue) will be discarded until the suspension is lifted.
101    void suspend(bool suspend);
102
103    // Specifies the interval after which we requeue the buffer previously
104    // queued to the encoder. This is useful in the case of surface flinger
105    // providing the input surface if the resulting encoded stream is to
106    // be displayed "live". If we were not to push through the extra frame
107    // the decoder on the remote end would be unable to decode the latest frame.
108    // This API must be called before transitioning the encoder to "executing"
109    // state and once this behaviour is specified it cannot be reset.
110    status_t setRepeatPreviousFrameDelayUs(int64_t repeatAfterUs);
111
112    // When set, the timestamp fed to the encoder will be modified such that
113    // the gap between two adjacent frames is capped at maxGapUs. Timestamp
114    // will be restored to the original when the encoded frame is returned to
115    // the client.
116    // This is to solve a problem in certain real-time streaming case, where
117    // encoder's rate control logic produces huge frames after a long period
118    // of suspension on input.
119    status_t setMaxTimestampGapUs(int64_t maxGapUs);
120
121    // Sets the time lapse (or slow motion) parameters.
122    // data[0] is the time (us) between two frames for playback
123    // data[1] is the time (us) between two frames for capture
124    // When set, the sample's timestamp will be modified to playback framerate,
125    // and capture timestamp will be modified to capture rate.
126    status_t setTimeLapseUs(int64_t* data);
127
128    // Sets the start time us (in system time), samples before which should
129    // be dropped and not submitted to encoder
130    void setSkipFramesBeforeUs(int64_t startTimeUs);
131
132protected:
133    // BufferQueue::ConsumerListener interface, called when a new frame of
134    // data is available.  If we're executing and a codec buffer is
135    // available, we acquire the buffer, copy the GraphicBuffer reference
136    // into the codec buffer, and call Empty[This]Buffer.  If we're not yet
137    // executing or there's no codec buffer available, we just increment
138    // mNumFramesAvailable and return.
139    virtual void onFrameAvailable();
140
141    // BufferQueue::ConsumerListener interface, called when the client has
142    // released one or more GraphicBuffers.  We clear out the appropriate
143    // set of mBufferSlot entries.
144    virtual void onBuffersReleased();
145
146    // BufferQueue::ConsumerListener interface, called when the client has
147    // changed the sideband stream. GraphicBufferSource doesn't handle sideband
148    // streams so this is a no-op (and should never be called).
149    virtual void onSidebandStreamChanged();
150
151private:
152    // Keep track of codec input buffers.  They may either be available
153    // (mGraphicBuffer == NULL) or in use by the codec.
154    struct CodecBuffer {
155        OMX_BUFFERHEADERTYPE* mHeader;
156
157        // buffer producer's frame-number for buffer
158        uint64_t mFrameNumber;
159
160        // buffer producer's buffer slot for buffer
161        int mBuf;
162
163        sp<GraphicBuffer> mGraphicBuffer;
164    };
165
166    // Returns the index of an available codec buffer.  If none are
167    // available, returns -1.  Mutex must be held by caller.
168    int findAvailableCodecBuffer_l();
169
170    // Returns true if a codec buffer is available.
171    bool isCodecBufferAvailable_l() {
172        return findAvailableCodecBuffer_l() >= 0;
173    }
174
175    // Finds the mCodecBuffers entry that matches.  Returns -1 if not found.
176    int findMatchingCodecBuffer_l(const OMX_BUFFERHEADERTYPE* header);
177
178    // Fills a codec buffer with a frame from the BufferQueue.  This must
179    // only be called when we know that a frame of data is ready (i.e. we're
180    // in the onFrameAvailable callback, or if we're in codecBufferEmptied
181    // and mNumFramesAvailable is nonzero).  Returns without doing anything if
182    // we don't have a codec buffer available.
183    //
184    // Returns true if we successfully filled a codec buffer with a BQ buffer.
185    bool fillCodecBuffer_l();
186
187    // Marks the mCodecBuffers entry as in-use, copies the GraphicBuffer
188    // reference into the codec buffer, and submits the data to the codec.
189    status_t submitBuffer_l(const BufferQueue::BufferItem &item, int cbi);
190
191    // Submits an empty buffer, with the EOS flag set.   Returns without
192    // doing anything if we don't have a codec buffer available.
193    void submitEndOfInputStream_l();
194
195    void setLatestSubmittedBuffer_l(const BufferQueue::BufferItem &item);
196    bool repeatLatestSubmittedBuffer_l();
197    int64_t getTimestamp(const BufferQueue::BufferItem &item);
198
199    // Lock, covers all member variables.
200    mutable Mutex mMutex;
201
202    // Used to report constructor failure.
203    status_t mInitCheck;
204
205    // Pointer back to the object that contains us.  We send buffers here.
206    OMXNodeInstance* mNodeInstance;
207
208    // Set by omxExecuting() / omxIdling().
209    bool mExecuting;
210
211    bool mSuspended;
212
213    // We consume graphic buffers from this.
214    sp<BufferQueue> mBufferQueue;
215
216    // Number of frames pending in BufferQueue that haven't yet been
217    // forwarded to the codec.
218    size_t mNumFramesAvailable;
219
220    // Set to true if we want to send end-of-stream after we run out of
221    // frames in BufferQueue.
222    bool mEndOfStream;
223    bool mEndOfStreamSent;
224
225    // Cache of GraphicBuffers from the buffer queue.  When the codec
226    // is done processing a GraphicBuffer, we can use this to map back
227    // to a slot number.
228    sp<GraphicBuffer> mBufferSlot[BufferQueue::NUM_BUFFER_SLOTS];
229
230    // Tracks codec buffers.
231    Vector<CodecBuffer> mCodecBuffers;
232
233    ////
234    friend class AHandlerReflector<GraphicBufferSource>;
235
236    enum {
237        kWhatRepeatLastFrame,
238    };
239    enum {
240        kRepeatLastFrameCount = 10,
241    };
242
243    KeyedVector<int64_t, int64_t> mOriginalTimeUs;
244    int64_t mMaxTimestampGapUs;
245    int64_t mPrevOriginalTimeUs;
246    int64_t mPrevModifiedTimeUs;
247    int64_t mSkipFramesBeforeNs;
248
249    sp<ALooper> mLooper;
250    sp<AHandlerReflector<GraphicBufferSource> > mReflector;
251
252    int64_t mRepeatAfterUs;
253    int32_t mRepeatLastFrameGeneration;
254    int64_t mRepeatLastFrameTimestamp;
255    int32_t mRepeatLastFrameCount;
256
257    int mLatestSubmittedBufferId;
258    uint64_t mLatestSubmittedBufferFrameNum;
259    int32_t mLatestSubmittedBufferUseCount;
260
261    // The previously submitted buffer should've been repeated but
262    // no codec buffer was available at the time.
263    bool mRepeatBufferDeferred;
264
265    // Time lapse / slow motion configuration
266    int64_t mTimePerCaptureUs;
267    int64_t mTimePerFrameUs;
268    int64_t mPrevCaptureUs;
269    int64_t mPrevFrameUs;
270
271    void onMessageReceived(const sp<AMessage> &msg);
272
273    DISALLOW_EVIL_CONSTRUCTORS(GraphicBufferSource);
274};
275
276}  // namespace android
277
278#endif  // GRAPHIC_BUFFER_SOURCE_H_
279