MediaCodec.h revision 2606b10d51c2dceb851a2ea63e803aba4134bf00
1/*
2 * Copyright 2012, 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 MEDIA_CODEC_H_
18
19#define MEDIA_CODEC_H_
20
21#include <gui/IGraphicBufferProducer.h>
22#include <media/hardware/CryptoAPI.h>
23#include <media/stagefright/foundation/AHandler.h>
24#include <utils/Vector.h>
25
26namespace android {
27
28struct ABuffer;
29struct AMessage;
30struct AString;
31struct CodecBase;
32struct ICrypto;
33struct IBatteryStats;
34struct SoftwareRenderer;
35struct Surface;
36
37struct MediaCodec : public AHandler {
38    enum ConfigureFlags {
39        CONFIGURE_FLAG_ENCODE   = 1,
40    };
41
42    enum BufferFlags {
43        BUFFER_FLAG_SYNCFRAME   = 1,
44        BUFFER_FLAG_CODECCONFIG = 2,
45        BUFFER_FLAG_EOS         = 4,
46    };
47
48    enum {
49        CB_INPUT_AVAILABLE = 1,
50        CB_OUTPUT_AVAILABLE = 2,
51        CB_ERROR = 3,
52        CB_OUTPUT_FORMAT_CHANGED = 4,
53    };
54
55    struct BatteryNotifier;
56
57    static sp<MediaCodec> CreateByType(
58            const sp<ALooper> &looper, const char *mime, bool encoder);
59
60    static sp<MediaCodec> CreateByComponentName(
61            const sp<ALooper> &looper, const char *name);
62
63    status_t configure(
64            const sp<AMessage> &format,
65            const sp<Surface> &nativeWindow,
66            const sp<ICrypto> &crypto,
67            uint32_t flags);
68
69    status_t setCallback(const sp<AMessage> &callback);
70
71    status_t createInputSurface(sp<IGraphicBufferProducer>* bufferProducer);
72
73    status_t start();
74
75    // Returns to a state in which the component remains allocated but
76    // unconfigured.
77    status_t stop();
78
79    // Resets the codec to the INITIALIZED state.  Can be called after an error
80    // has occured to make the codec usable.
81    status_t reset();
82
83    // Client MUST call release before releasing final reference to this
84    // object.
85    status_t release();
86
87    status_t flush();
88
89    status_t queueInputBuffer(
90            size_t index,
91            size_t offset,
92            size_t size,
93            int64_t presentationTimeUs,
94            uint32_t flags,
95            AString *errorDetailMsg = NULL);
96
97    status_t queueSecureInputBuffer(
98            size_t index,
99            size_t offset,
100            const CryptoPlugin::SubSample *subSamples,
101            size_t numSubSamples,
102            const uint8_t key[16],
103            const uint8_t iv[16],
104            CryptoPlugin::Mode mode,
105            int64_t presentationTimeUs,
106            uint32_t flags,
107            AString *errorDetailMsg = NULL);
108
109    status_t dequeueInputBuffer(size_t *index, int64_t timeoutUs = 0ll);
110
111    status_t dequeueOutputBuffer(
112            size_t *index,
113            size_t *offset,
114            size_t *size,
115            int64_t *presentationTimeUs,
116            uint32_t *flags,
117            int64_t timeoutUs = 0ll);
118
119    status_t renderOutputBufferAndRelease(size_t index, int64_t timestampNs);
120    status_t renderOutputBufferAndRelease(size_t index);
121    status_t releaseOutputBuffer(size_t index);
122
123    status_t signalEndOfInputStream();
124
125    status_t getOutputFormat(sp<AMessage> *format) const;
126    status_t getInputFormat(sp<AMessage> *format) const;
127
128    status_t getInputBuffers(Vector<sp<ABuffer> > *buffers) const;
129    status_t getOutputBuffers(Vector<sp<ABuffer> > *buffers) const;
130
131    status_t getOutputBuffer(size_t index, sp<ABuffer> *buffer);
132    status_t getOutputFormat(size_t index, sp<AMessage> *format);
133    status_t getInputBuffer(size_t index, sp<ABuffer> *buffer);
134
135    status_t requestIDRFrame();
136
137    // Notification will be posted once there "is something to do", i.e.
138    // an input/output buffer has become available, a format change is
139    // pending, an error is pending.
140    void requestActivityNotification(const sp<AMessage> &notify);
141
142    status_t getName(AString *componentName) const;
143
144    status_t setParameters(const sp<AMessage> &params);
145
146protected:
147    virtual ~MediaCodec();
148    virtual void onMessageReceived(const sp<AMessage> &msg);
149
150private:
151    enum State {
152        UNINITIALIZED,
153        INITIALIZING,
154        INITIALIZED,
155        CONFIGURING,
156        CONFIGURED,
157        STARTING,
158        STARTED,
159        FLUSHING,
160        STOPPING,
161        RELEASING,
162    };
163
164    enum {
165        kPortIndexInput         = 0,
166        kPortIndexOutput        = 1,
167    };
168
169    enum {
170        kWhatInit                           = 'init',
171        kWhatConfigure                      = 'conf',
172        kWhatCreateInputSurface             = 'cisf',
173        kWhatStart                          = 'strt',
174        kWhatStop                           = 'stop',
175        kWhatRelease                        = 'rele',
176        kWhatDequeueInputBuffer             = 'deqI',
177        kWhatQueueInputBuffer               = 'queI',
178        kWhatDequeueOutputBuffer            = 'deqO',
179        kWhatReleaseOutputBuffer            = 'relO',
180        kWhatSignalEndOfInputStream         = 'eois',
181        kWhatGetBuffers                     = 'getB',
182        kWhatFlush                          = 'flus',
183        kWhatGetOutputFormat                = 'getO',
184        kWhatGetInputFormat                 = 'getI',
185        kWhatDequeueInputTimedOut           = 'dITO',
186        kWhatDequeueOutputTimedOut          = 'dOTO',
187        kWhatCodecNotify                    = 'codc',
188        kWhatRequestIDRFrame                = 'ridr',
189        kWhatRequestActivityNotification    = 'racN',
190        kWhatGetName                        = 'getN',
191        kWhatSetParameters                  = 'setP',
192        kWhatSetCallback                    = 'setC',
193    };
194
195    enum {
196        kFlagIsSoftwareCodec            = 1,
197        kFlagOutputFormatChanged        = 2,
198        kFlagOutputBuffersChanged       = 4,
199        kFlagStickyError                = 8,
200        kFlagDequeueInputPending        = 16,
201        kFlagDequeueOutputPending       = 32,
202        kFlagIsSecure                   = 64,
203        kFlagSawMediaServerDie          = 128,
204        kFlagIsEncoder                  = 256,
205        kFlagGatherCodecSpecificData    = 512,
206        kFlagIsAsync                    = 1024,
207    };
208
209    struct BufferInfo {
210        uint32_t mBufferID;
211        sp<ABuffer> mData;
212        sp<ABuffer> mEncryptedData;
213        sp<AMessage> mNotify;
214        sp<AMessage> mFormat;
215        bool mOwnedByClient;
216    };
217
218    State mState;
219    sp<ALooper> mLooper;
220    sp<ALooper> mCodecLooper;
221    sp<CodecBase> mCodec;
222    AString mComponentName;
223    uint32_t mReplyID;
224    uint32_t mFlags;
225    sp<Surface> mNativeWindow;
226    SoftwareRenderer *mSoftRenderer;
227    sp<AMessage> mOutputFormat;
228    sp<AMessage> mInputFormat;
229    sp<AMessage> mCallback;
230
231    bool mBatteryStatNotified;
232    bool mIsVideo;
233
234    // initial create parameters
235    AString mInitName;
236    bool mInitNameIsType;
237    bool mInitIsEncoder;
238
239    // Used only to synchronize asynchronous getBufferAndFormat
240    // across all the other (synchronous) buffer state change
241    // operations, such as de/queueIn/OutputBuffer, start and
242    // stop/flush/reset/release.
243    Mutex mBufferLock;
244
245    List<size_t> mAvailPortBuffers[2];
246    Vector<BufferInfo> mPortBuffers[2];
247
248    int32_t mDequeueInputTimeoutGeneration;
249    uint32_t mDequeueInputReplyID;
250
251    int32_t mDequeueOutputTimeoutGeneration;
252    uint32_t mDequeueOutputReplyID;
253
254    sp<ICrypto> mCrypto;
255
256    List<sp<ABuffer> > mCSD;
257
258    sp<AMessage> mActivityNotify;
259
260    bool mHaveInputSurface;
261
262    MediaCodec(const sp<ALooper> &looper);
263
264    static status_t PostAndAwaitResponse(
265            const sp<AMessage> &msg, sp<AMessage> *response);
266
267    static void PostReplyWithError(int32_t replyID, int32_t err);
268
269    status_t init(const char *name, bool nameIsType, bool encoder);
270
271    void setState(State newState);
272    void returnBuffersToCodec();
273    void returnBuffersToCodecOnPort(int32_t portIndex);
274    size_t updateBuffers(int32_t portIndex, const sp<AMessage> &msg);
275    status_t onQueueInputBuffer(const sp<AMessage> &msg);
276    status_t onReleaseOutputBuffer(const sp<AMessage> &msg);
277    ssize_t dequeuePortBuffer(int32_t portIndex);
278
279    status_t getBufferAndFormat(
280            size_t portIndex, size_t index,
281            sp<ABuffer> *buffer, sp<AMessage> *format);
282
283    bool handleDequeueInputBuffer(uint32_t replyID, bool newRequest = false);
284    bool handleDequeueOutputBuffer(uint32_t replyID, bool newRequest = false);
285    void cancelPendingDequeueOperations();
286
287    void extractCSD(const sp<AMessage> &format);
288    status_t queueCSDInputBuffer(size_t bufferIndex);
289
290    status_t setNativeWindow(
291            const sp<Surface> &surface);
292
293    void postActivityNotificationIfPossible();
294
295    void onInputBufferAvailable();
296    void onOutputBufferAvailable();
297    void onError(status_t err, int32_t actionCode, const char *detail = NULL);
298    void onOutputFormatChanged();
299
300    status_t onSetParameters(const sp<AMessage> &params);
301
302    status_t amendOutputFormatWithCodecSpecificData(const sp<ABuffer> &buffer);
303    void updateBatteryStat();
304
305    DISALLOW_EVIL_CONSTRUCTORS(MediaCodec);
306};
307
308}  // namespace android
309
310#endif  // MEDIA_CODEC_H_
311