OMXCodec.h revision a98478bfbcc0f7fb4b164d3dce40ca96df75667d
1/*
2 * Copyright (C) 2009 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 OMX_CODEC_H_
18
19#define OMX_CODEC_H_
20
21#include <android/native_window.h>
22#include <media/IOMX.h>
23#include <media/stagefright/MediaBuffer.h>
24#include <media/stagefright/MediaSource.h>
25#include <utils/threads.h>
26
27namespace android {
28
29struct MediaCodecList;
30class MemoryDealer;
31struct OMXCodecObserver;
32struct CodecProfileLevel;
33class SkipCutBuffer;
34
35struct OMXCodec : public MediaSource,
36                  public MediaBufferObserver {
37    enum CreationFlags {
38        kPreferSoftwareCodecs    = 1,
39        kIgnoreCodecSpecificData = 2,
40
41        // The client wants to access the output buffer's video
42        // data for example for thumbnail extraction.
43        kClientNeedsFramebuffer  = 4,
44
45        // Request for software or hardware codecs. If request
46        // can not be fullfilled, Create() returns NULL.
47        kSoftwareCodecsOnly      = 8,
48        kHardwareCodecsOnly      = 16,
49
50        // Store meta data in video buffers
51        kStoreMetaDataInVideoBuffers = 32,
52
53        // Only submit one input buffer at one time.
54        kOnlySubmitOneInputBufferAtOneTime = 64,
55
56        // Enable GRALLOC_USAGE_PROTECTED for output buffers from native window
57        kEnableGrallocUsageProtected = 128,
58
59        // Secure decoding mode
60        kUseSecureInputBuffers = 256,
61    };
62    static sp<MediaSource> Create(
63            const sp<IOMX> &omx,
64            const sp<MetaData> &meta, bool createEncoder,
65            const sp<MediaSource> &source,
66            const char *matchComponentName = NULL,
67            uint32_t flags = 0,
68            const sp<ANativeWindow> &nativeWindow = NULL);
69
70    static void setComponentRole(
71            const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
72            const char *mime);
73
74    virtual status_t start(MetaData *params = NULL);
75    virtual status_t stop();
76
77    virtual sp<MetaData> getFormat();
78
79    virtual status_t read(
80            MediaBuffer **buffer, const ReadOptions *options = NULL);
81
82    virtual status_t pause();
83
84    // from MediaBufferObserver
85    virtual void signalBufferReturned(MediaBuffer *buffer);
86
87    enum Quirks {
88        kNeedsFlushBeforeDisable              = 1,
89        kWantsNALFragments                    = 2,
90        kRequiresLoadedToIdleAfterAllocation  = 4,
91        kRequiresAllocateBufferOnInputPorts   = 8,
92        kRequiresFlushCompleteEmulation       = 16,
93        kRequiresAllocateBufferOnOutputPorts  = 32,
94        kRequiresFlushBeforeShutdown          = 64,
95        kDefersOutputBufferAllocation         = 128,
96        kDecoderLiesAboutNumberOfChannels     = 256,
97        kInputBufferSizesAreBogus             = 512,
98        kSupportsMultipleFramesPerInputBuffer = 1024,
99        kAvoidMemcopyInputRecordingFrames     = 2048,
100        kRequiresLargerEncoderOutputBuffer    = 4096,
101        kOutputBuffersAreUnreadable           = 8192,
102    };
103
104    // for use by ACodec
105    static void findMatchingCodecs(
106            const char *mime,
107            bool createEncoder, const char *matchComponentName,
108            uint32_t flags,
109            Vector<String8> *matchingCodecs,
110            Vector<uint32_t> *matchingCodecQuirks = NULL);
111
112    static uint32_t getComponentQuirks(
113            const MediaCodecList *list, size_t index);
114
115    static bool findCodecQuirks(const char *componentName, uint32_t *quirks);
116
117protected:
118    virtual ~OMXCodec();
119
120private:
121
122    // Make sure mLock is accessible to OMXCodecObserver
123    friend class OMXCodecObserver;
124
125    // Call this with mLock hold
126    void on_message(const omx_message &msg);
127
128    enum State {
129        DEAD,
130        LOADED,
131        LOADED_TO_IDLE,
132        IDLE_TO_EXECUTING,
133        EXECUTING,
134        EXECUTING_TO_IDLE,
135        IDLE_TO_LOADED,
136        RECONFIGURING,
137        ERROR
138    };
139
140    enum {
141        kPortIndexInput  = 0,
142        kPortIndexOutput = 1
143    };
144
145    enum PortStatus {
146        ENABLED,
147        DISABLING,
148        DISABLED,
149        ENABLING,
150        SHUTTING_DOWN,
151    };
152
153    enum BufferStatus {
154        OWNED_BY_US,
155        OWNED_BY_COMPONENT,
156        OWNED_BY_NATIVE_WINDOW,
157        OWNED_BY_CLIENT,
158    };
159
160    struct BufferInfo {
161        IOMX::buffer_id mBuffer;
162        BufferStatus mStatus;
163        sp<IMemory> mMem;
164        size_t mSize;
165        void *mData;
166        MediaBuffer *mMediaBuffer;
167    };
168
169    struct CodecSpecificData {
170        size_t mSize;
171        uint8_t mData[1];
172    };
173
174    sp<IOMX> mOMX;
175    bool mOMXLivesLocally;
176    IOMX::node_id mNode;
177    uint32_t mQuirks;
178
179    // Flags specified in the creation of the codec.
180    uint32_t mFlags;
181
182    bool mIsEncoder;
183    bool mIsVideo;
184    char *mMIME;
185    char *mComponentName;
186    sp<MetaData> mOutputFormat;
187    sp<MediaSource> mSource;
188    Vector<CodecSpecificData *> mCodecSpecificData;
189    size_t mCodecSpecificDataIndex;
190
191    sp<MemoryDealer> mDealer[2];
192
193    State mState;
194    Vector<BufferInfo> mPortBuffers[2];
195    PortStatus mPortStatus[2];
196    bool mInitialBufferSubmit;
197    bool mSignalledEOS;
198    status_t mFinalStatus;
199    bool mNoMoreOutputData;
200    bool mOutputPortSettingsHaveChanged;
201    int64_t mSeekTimeUs;
202    ReadOptions::SeekMode mSeekMode;
203    int64_t mTargetTimeUs;
204    bool mOutputPortSettingsChangedPending;
205    SkipCutBuffer *mSkipCutBuffer;
206
207    MediaBuffer *mLeftOverBuffer;
208
209    Mutex mLock;
210    Condition mAsyncCompletion;
211
212    bool mPaused;
213
214    sp<ANativeWindow> mNativeWindow;
215
216    // The index in each of the mPortBuffers arrays of the buffer that will be
217    // submitted to OMX next.  This only applies when using buffers from a
218    // native window.
219    size_t mNextNativeBufferIndex[2];
220
221    // A list of indices into mPortStatus[kPortIndexOutput] filled with data.
222    List<size_t> mFilledBuffers;
223    Condition mBufferFilled;
224
225    // Used to record the decoding time for an output picture from
226    // a video encoder.
227    List<int64_t> mDecodingTimeList;
228
229    OMXCodec(const sp<IOMX> &omx, IOMX::node_id node,
230             uint32_t quirks, uint32_t flags,
231             bool isEncoder, const char *mime, const char *componentName,
232             const sp<MediaSource> &source,
233             const sp<ANativeWindow> &nativeWindow);
234
235    void addCodecSpecificData(const void *data, size_t size);
236    void clearCodecSpecificData();
237
238    void setComponentRole();
239
240    void setAMRFormat(bool isWAMR, int32_t bitRate);
241    status_t setAACFormat(int32_t numChannels, int32_t sampleRate, int32_t bitRate);
242    void setG711Format(int32_t numChannels);
243
244    status_t setVideoPortFormatType(
245            OMX_U32 portIndex,
246            OMX_VIDEO_CODINGTYPE compressionFormat,
247            OMX_COLOR_FORMATTYPE colorFormat);
248
249    void setVideoInputFormat(
250            const char *mime, const sp<MetaData>& meta);
251
252    status_t setupBitRate(int32_t bitRate);
253    status_t setupErrorCorrectionParameters();
254    status_t setupH263EncoderParameters(const sp<MetaData>& meta);
255    status_t setupMPEG4EncoderParameters(const sp<MetaData>& meta);
256    status_t setupAVCEncoderParameters(const sp<MetaData>& meta);
257    status_t findTargetColorFormat(
258            const sp<MetaData>& meta, OMX_COLOR_FORMATTYPE *colorFormat);
259
260    status_t isColorFormatSupported(
261            OMX_COLOR_FORMATTYPE colorFormat, int portIndex);
262
263    // If profile/level is set in the meta data, its value in the meta
264    // data will be used; otherwise, the default value will be used.
265    status_t getVideoProfileLevel(const sp<MetaData>& meta,
266            const CodecProfileLevel& defaultProfileLevel,
267            CodecProfileLevel& profileLevel);
268
269    status_t setVideoOutputFormat(
270            const char *mime, OMX_U32 width, OMX_U32 height);
271
272    void setImageOutputFormat(
273            OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height);
274
275    void setJPEGInputFormat(
276            OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize);
277
278    void setMinBufferSize(OMX_U32 portIndex, OMX_U32 size);
279
280    void setRawAudioFormat(
281            OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels);
282
283    status_t allocateBuffers();
284    status_t allocateBuffersOnPort(OMX_U32 portIndex);
285    status_t allocateOutputBuffersFromNativeWindow();
286
287    status_t queueBufferToNativeWindow(BufferInfo *info);
288    status_t cancelBufferToNativeWindow(BufferInfo *info);
289    BufferInfo* dequeueBufferFromNativeWindow();
290    status_t pushBlankBuffersToNativeWindow();
291
292    status_t freeBuffersOnPort(
293            OMX_U32 portIndex, bool onlyThoseWeOwn = false);
294
295    status_t freeBuffer(OMX_U32 portIndex, size_t bufIndex);
296
297    bool drainInputBuffer(IOMX::buffer_id buffer);
298    void fillOutputBuffer(IOMX::buffer_id buffer);
299    bool drainInputBuffer(BufferInfo *info);
300    void fillOutputBuffer(BufferInfo *info);
301
302    void drainInputBuffers();
303    void fillOutputBuffers();
304
305    bool drainAnyInputBuffer();
306    BufferInfo *findInputBufferByDataPointer(void *ptr);
307    BufferInfo *findEmptyInputBuffer();
308
309    // Returns true iff a flush was initiated and a completion event is
310    // upcoming, false otherwise (A flush was not necessary as we own all
311    // the buffers on that port).
312    // This method will ONLY ever return false for a component with quirk
313    // "kRequiresFlushCompleteEmulation".
314    bool flushPortAsync(OMX_U32 portIndex);
315
316    void disablePortAsync(OMX_U32 portIndex);
317    status_t enablePortAsync(OMX_U32 portIndex);
318
319    static size_t countBuffersWeOwn(const Vector<BufferInfo> &buffers);
320    static bool isIntermediateState(State state);
321
322    void onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2);
323    void onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data);
324    void onStateChange(OMX_STATETYPE newState);
325    void onPortSettingsChanged(OMX_U32 portIndex);
326
327    void setState(State newState);
328
329    status_t init();
330    void initOutputFormat(const sp<MetaData> &inputFormat);
331    status_t initNativeWindow();
332
333    void initNativeWindowCrop();
334
335    void dumpPortStatus(OMX_U32 portIndex);
336
337    status_t configureCodec(const sp<MetaData> &meta);
338
339    void restorePatchedDataPointer(BufferInfo *info);
340
341    status_t applyRotation();
342    status_t waitForBufferFilled_l();
343
344    int64_t getDecodingTimeUs();
345
346    status_t parseAVCCodecSpecificData(
347            const void *data, size_t size,
348            unsigned *profile, unsigned *level);
349
350    OMXCodec(const OMXCodec &);
351    OMXCodec &operator=(const OMXCodec &);
352};
353
354struct CodecCapabilities {
355    String8 mComponentName;
356    Vector<CodecProfileLevel> mProfileLevels;
357    Vector<OMX_U32> mColorFormats;
358};
359
360// Return a vector of componentNames with supported profile/level pairs
361// supporting the given mime type, if queryDecoders==true, returns components
362// that decode content of the given type, otherwise returns components
363// that encode content of the given type.
364// profile and level indications only make sense for h.263, mpeg4 and avc
365// video.
366// If hwCodecOnly==true, only returns hardware-based components, software and
367// hardware otherwise.
368// The profile/level values correspond to
369// OMX_VIDEO_H263PROFILETYPE, OMX_VIDEO_MPEG4PROFILETYPE,
370// OMX_VIDEO_AVCPROFILETYPE, OMX_VIDEO_H263LEVELTYPE, OMX_VIDEO_MPEG4LEVELTYPE
371// and OMX_VIDEO_AVCLEVELTYPE respectively.
372
373status_t QueryCodecs(
374        const sp<IOMX> &omx,
375        const char *mimeType, bool queryDecoders, bool hwCodecOnly,
376        Vector<CodecCapabilities> *results);
377
378status_t QueryCodecs(
379        const sp<IOMX> &omx,
380        const char *mimeType, bool queryDecoders,
381        Vector<CodecCapabilities> *results);
382
383
384}  // namespace android
385
386#endif  // OMX_CODEC_H_
387