FFMpeg框架代碼閱讀

內容摘要:FFmpeg是一個集錄制、轉換、音/視頻編碼解碼功能爲一體的完整的開源解決方案。FFmpeg的開發是基於Linux操作系統,但是 可以在大多數操作系統中編譯和使用。FFmpeg支持MPEG、 DivX、MPEG4、AC3、DV、FLV等40多種編碼,AVI、MPEG、OGG、Matroska、ASF等90多種解碼. TCPMP, VLC, MPlayer等開源播放器都用到了FFmpeg。 FFmpeg主目錄下主要有libavcodec、libavformat和libavutil等子目錄.

1. 簡介
FFmpeg是一個集錄制、轉換、音/視頻編碼解碼功能爲一體的完整的開源解決方案。FFmpeg的
開發是基於 Linux操作系統,但是可以在大多數操作系統中編譯和使用。FFmpeg支持MPEG、
DivX、MPEG4、AC3、DV、FLV等40多種 編碼,AVI、MPEG、OGG、Matroska、ASF等90多種解碼.
TCPMP, VLC, MPlayer等開源播放器都用到了FFmpeg。
FFmpeg主目錄下主要有libavcodec、libavformat和 libavutil等子目錄。其中libavcodec用
於存放各個encode/decode模塊,libavformat用於存放muxer /demuxer模塊,libavutil用於
存放內存操作等輔助性模塊。
以flash movie的flv文件格式爲例, muxer/demuxer的flvenc.c和flvdec.c文件在
libavformat目錄下,encode/decode的 mpegvideo.c和h263de.c在libavcodec目錄下。
 
2. muxer/demuxer與encoder/decoder定義與初始化
muxer/demuxer和encoder/decoder在 FFmpeg中的實現代碼裏,有許多相同的地方,而二者最
大的差別是muxer 和demuxer分別是不同的結構AVOutputFormat與AVInputFormat,而encoder
和decoder都是用的 AVCodec 結構。
 
muxer/demuxer和encoder/decoder在FFmpeg中相同的地方有:
    二者都是在main()開始的av_register_all()函數內初始化的
    二者都是以鏈表的形式保存在全局變量中的
        muxer/demuxer是分別保存在全局變量AVOutputFormat *first_oformat與
        AVInputFormat *first_iformat中的。
        encoder/decoder都是保存在全局變量AVCodec *first_avcodec中的。
    二者都用函數指針的方式作爲開放的公共接口
   
demuxer開放的接口有:
    int (*read_probe)(AVProbeData *);
    int (*read_header)(struct AVFormatContext *, AVFormatParameters *ap);
    int (*read_packet)(struct AVFormatContext *, AVPacket *pkt);
    int (*read_close)(struct AVFormatContext *);
    int (*read_seek)(struct AVFormatContext *, int stream_index, int64_t timestamp, int flags);
   
muxer開放的接口有:
    int (*write_header)(struct AVFormatContext *);
    int (*write_packet)(struct AVFormatContext *, AVPacket *pkt);
    int (*write_trailer)(struct AVFormatContext *);
 
encoder/decoder的 接口是一樣的,只不過二者分別只實現encoder和decoder函數:
    int (*init)(AVCodecContext *);
    int (*encode)(AVCodecContext *, uint8_t *buf, int buf_size, void *data);
    int (*close)(AVCodecContext *);
    int (*decode)(AVCodecContext *, void *outdata, int *outdata_size, uint8_t *buf, int buf_size);
 
仍以flv文件爲例來說明muxer/demuxer的初始化。
在 libavformat/allformats.c文件的av_register_all(void)函數中,通過執行
REGISTER_MUXDEMUX(FLV, flv);
將支持flv 格式的flv_muxer與flv_demuxer變量分別註冊到全局變量first_oformat與first_iformat鏈表的最後位置。
其 中flv_muxer在libavformat/flvenc.c中定義如下:
AVOutputFormat flv_muxer = {
    "flv",
    "flv format",
    "video/x-flv",
    "flv",
    sizeof(FLVContext),
#ifdef CONFIG_LIBMP3LAME
    CODEC_ID_MP3,
#else // CONFIG_LIBMP3LAME
    CODEC_ID_NONE,
    CODEC_ID_FLV1,
    flv_write_header,
    flv_write_packet,
    flv_write_trailer,
    .codec_tag= (const AVCodecTag*[]){flv_video_codec_ids, flv_audio_codec_ids, 0},
}

AVOutputFormat結構的定義如下:
typedef struct AVOutputFormat {
    const char *name;
    const char *long_name;
    const char *mime_type;
    const char *extensions; /**< comma separated filename extensions */
    /** size of private data so that it can be allocated in the wrapper */
    int priv_data_size;
    /* output support */
    enum CodecID audio_codec; /**< default audio codec */
    enum CodecID video_codec; /**< default video codec */
    int (*write_header)(struct AVFormatContext *);
    int (*write_packet)(struct AVFormatContext *, AVPacket *pkt);
    int (*write_trailer)(struct AVFormatContext *);
    /** can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_GLOBALHEADER */
    int flags;
    /** currently only used to set pixel format if not YUV420P */
    int (*set_parameters)(struct AVFormatContext *, AVFormatParameters *);
    int (*interleave_packet)(struct AVFormatContext *, AVPacket *out, AVPacket *in, int flush);
 
    /**
     *list of supported codec_id-codec_tag pairs,ordered by "better choice first"
     * the arrays are all CODEC_ID_NONE terminated
     */
    const struct AVCodecTag **codec_tag;
    /* private fields */
    struct AVOutputFormat *next;
} AVOutputFormat;
由AVOutputFormat結構的定義可 知,flv_muxer變量初始化的第一、二個成員分別爲該muxer
的名稱與長名稱,第三、第四個成員爲所對應MIMIE Type和後綴名,第五個成員是所對應的
私有結構的大小,第六、第七個成員爲所對應的音頻編碼和視頻編碼類型ID,接下來就是三
個重要的 接口函數,該 muxer的功能也就是通過調用這三個接口實現的。
 
flv_demuxer在libavformat/flvdec.c 中定義如下, 與flv_muxer類似,在這兒主要也是設置
了5個接口函數,其中flv_probe接口用途是測試傳入的數據段是否是符合當前 文件格式,這
個接口在匹配當前demuxer時會用到。
AVInputFormat flv_demuxer = {
    "flv",
    "flv format",
    0,
    flv_probe,
    flv_read_header,
    flv_read_packet,
    flv_read_close,
    flv_read_seek,
    .extensions = "flv",
    .value = CODEC_ID_FLV1,
};

在上述av_register_all(void)函數中通過執行libavcodec/allcodecs.c文件裏的
avcodec_register_all(void) 函數來初始化全部的encoder/decoder。
 
因爲不是每種編碼方式都支持encode和decode,所以有以下三種註冊方 式:
#define REGISTER_ENCODER(X,x) /
    if(ENABLE_##X##_ENCODER) register_avcodec(&x##_encoder)
#define REGISTER_DECODER(X,x) /
    if(ENABLE_##X##_DECODER) register_avcodec(&x##_decoder)
#define REGISTER_ENCDEC(X,x) REGISTER_ENCODER(X,x); REGISTER_DECODER(X,x)
 
如 支持flv的flv_encoder和flv_decoder變量就分別是在libavcodec/mpegvideo.c和
libavcodec/h263de.c 中創建的。
 
3. 當前muxer/demuxer的匹配
在FFmpeg的文件轉換過程中,首先要做的就是根據傳入文件和傳出文 件的後綴名[FIXME]匹配
合適的demuxer和muxer。匹配上的demuxer和muxer都保存在如下所示,定義在ffmpeg.c 裏的
全局變量file_iformat和file_oformat中:
    static AVInputFormat *file_iformat;
    static AVOutputFormat *file_oformat;
 
3.1 demuxer匹配
在libavformat/utils.c中的static AVInputFormat *av_probe_input_format2(
AVProbeData *pd, int is_opened, int *score_max)函數用途是根據傳入的probe data數據
,依次調用每個demuxer的read_probe接口,來進行該 demuxer是否和傳入的文件內容匹配的
判斷。其調用順序如下:
void parse_options(int argc, char **argv, const OptionDef *options,
           void (* parse_arg_function)(const char *));
    static void opt_input_file(const char *filename)
        int av_open_input_file(…… )
            AVInputFormat *av_probe_input_format(AVProbeData *pd,
                                int is_opened)
                static AVInputFormat *av_probe_input_format2(……)
opt_input_file函數是在保存在const OptionDef options[]數組中,用於
void parse_options(int argc, char **argv, const OptionDef *options)中解析argv裏的
“-i” 參數,也就是輸入文件名時調用的。
 
3.2 muxer匹配
與demuxer的匹配不同,muxer的匹配是調用guess_format函數,根據main() 函數的argv裏的
輸 出文件後綴名來進行的。
void parse_options(int argc, char **argv, const OptionDef *options,
           void (* parse_arg_function)(const char *));
    void parse_arg_file(const char *filename)
        static void opt_output_file(const char *filename)
            AVOutputFormat *guess_format(const char *short_name,
                            const char *filename,
                            const char *mime_type)
 
3.3 當前encoder/decoder的匹配
在main()函數中除了解析傳入參數並初始化 demuxer與muxer的parse_options( )函數以外,
其他的功能都是在av_encode( )函數裏完成的。
在 libavcodec/utils.c中有如下二個函數:
    AVCodec *avcodec_find_encoder(enum CodecID id)
    AVCodec *avcodec_find_decoder(enum CodecID id)
他們的 功能就是根據傳入的CodecID,找到匹配的encoder和decoder。
 
在av_encode( )函數的開頭,首先初始化各個AVInputStream和AVOutputStream,然後分別調
用上述二個函數,並將匹配上的 encoder與decoder分別保存在:
AVInputStream->AVStream *st->AVCodecContext *codec->struct AVCodec *codec與
AVOutputStream->AVStream *st->AVCodecContext *codec->struct AVCodec *codec變量。

4. 其他主要數據結構
4.1 AVFormatContext
AVFormatContext是FFMpeg格式轉換過程中實現 輸入和輸出功能、保存相關數據的主要結構。
每一個輸入和輸出文件,都在如下定義的指針數組全局變量中有對應的實體。
    static AVFormatContext *output_files[MAX_FILES];
    static AVFormatContext *input_files[MAX_FILES];
對於輸入和輸出,因爲共用的是同一個結構體,所以需要分別對該結構中如下定義的 iformat
或oformat成員賦值。
    struct AVInputFormat *iformat;
    struct AVOutputFormat *oformat;
對一個AVFormatContext來說,這二個成員不能同時有值,即一個 AVFormatContext不能同時
含有demuxer和muxer。在main( )函數開頭的parse_options( )函數中找到了匹配的muxer和
demuxer之後,根據傳入的argv參數,初始化每個輸入和輸出的AVFormatContext結構,並 保
存在相應的output_files和input_files指針數組中。在av_encode( )函數中,output_files
和 input_files是作爲函數參數傳入後,在其他地方就沒有用到了。
 
4.2 AVCodecContext
保存 AVCodec指針和與codec相關數據,如video的width、height,audio的sample rate等。
AVCodecContext 中的codec_type,codec_id二個變量對於encoder/decoder的匹配來說,最爲
重要。
    enum CodecType codec_type;     /* see CODEC_TYPE_xxx */
    enum CodecID codec_id;         /* see CODEC_ID_xxx */

如上所示,codec_type保存的是CODEC_TYPE_VIDEO,CODEC_TYPE_AUDIO等媒體類型,
codec_id 保存的是CODEC_ID_FLV1,CODEC_ID_VP6F等編碼方式。
 
以支持flv格式爲例,在前述的 av_open_input_file(…… ) 函數中,匹配到正確的
AVInputFormat demuxer後,通過av_open_input_stream( )函數中調用AVInputFormat的
read_header接口來執 行flvdec.c中的flv_read_header( )函數。在flv_read_header( )函數
內,根據文件頭中的數據,創建相 應的視頻或音頻AVStream,並設置AVStream中
AVCodecContext的正確的codec_type值。codec_id值是 在解碼過程中flv_read_packet( )函
數執行時根據每一個packet頭中的數據來設置的。
 
4.3 AVStream
AVStream結構保存與數據流相關的編解碼器,數據段等信息。比較重要的有如下二個成員:
    AVCodecContext *codec; /**< codec context */
    void *priv_data;
其 中codec指針保存的就是上節所述的encoder或decoder結構。priv_data指針保存的是和具
體編解碼流相關的數據,如下代碼 所示,在ASF的解碼過程中,priv_data保存的就是
ASFStream結構的數據。
    AVStream *st;
    ASFStream *asf_st;  
    … …
    st->priv_data = asf_st;

4.4 AVInputStream/ AVOutputStream
根據輸入和輸出流的不同,前述的AVStream結構都是封裝在 AVInputStream和AVOutputStream
結構中,在av_encode( )函數中使用。AVInputStream中還保存的有與時間有關的信息。
AVOutputStream中還保存有與音視頻同步等相關的信息。
 
4.5 AVPacket
AVPacket結構定義如下,其是用於保存讀取的packet數據。
typedef struct AVPacket {
    int64_t pts;            ///< presentation time stamp in time_base units
    int64_t dts;            ///< decompression time stamp in time_base units
    uint8_t *data;
    int   size;
    int   stream_index;
    int   flags;
    int   duration;        ///< presentation duration in time_base units (0 if not available)
    void (*destruct)(struct AVPacket *);
    void *priv;
    int64_t pos;           ///< byte position in stream, -1 if unknown
} AVPacket;
 
在av_encode()函數中,調用AVInputFormat的
(*read_packet)(struct AVFormatContext *, AVPacket *pkt)接口,讀取輸入文件的一幀數
據保存在當前輸入 AVFormatContext的AVPacket成員中。
 
5. av_encode函數主要流程
av_encode()函數 是FFMpeg中最重要的函數,編解碼和輸出等大部分功能都在此函數完成,
因此有必要詳細描述一下這個函數的主要流程。
1).input streams initializing
2).output streams initializing
3).encoders and decoders initializing
4).set meta data information from input file if required.
5).write output files header
6).loop of handling each frame
    a.read frame from input file:
    b.decode frame data
    c.encode new frame data
    d.write new frame to output file
7).write output files trailer
8).close each encoder and decoder

本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/xxxluozhen/archive/2010/02/24/5321772.aspx

發佈了26 篇原創文章 · 獲贊 5 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章