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