ffmpeg架構和解碼流程分析


 

一,ffmpeg架構

1. 簡介

FFmpeg是一個集錄制、轉換、音/視頻編碼解碼功能為一體的完整的開源解決方案。FFmpeg

開發是基於Linux操作系統,但是可以在大多數操作系統中編譯和使用。FFmpeg支持MPEG

DivXMPEG4AC3DVFLV40多種編碼,AVIMPEGOGGMatroskaASF90多種解碼.

TCPMP, VLC, MPlayer等開源播放器都用到了FFmpeg

FFmpeg主目錄下主要有libavcodeclibavformatlibavutil等子目錄。其中libavcodec

於存放各個encode/decode模塊,libavformat用於存放muxer/demuxer模塊,libavutil用於

存放內存操作等輔助性模塊。

flash movieflv文件格式為例, muxer/demuxerflvenc.cflvdec.c文件在

libavformat目錄下,encode/decodempegvideo.ch263de.clibavcodec目錄下。

 

2. muxer/demuxerencoder/decoder定義與初始化

muxer/demuxerencoder/decoderFFmpeg中的實現代碼里,有許多相同的地方,而二者最

大的差別是muxerdemuxer分別是不同的結構AVOutputFormatAVInputFormat,而encoder

decoder都是用的AVCodec 結構。

 

muxer/demuxerencoder/decoderFFmpeg中相同的地方有:

    二者都是在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的接口是一樣的,只不過二者分別只實現encoderdecoder函數:

    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_muxerflv_demuxer變量分別注冊到全局變量first_oformatfirst_iformat鏈表的最后位置。

其中flv_muxerlibavformat\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;

   

    int priv_data_size;

   

    enum CodecID audio_codec;

    enum CodecID video_codec;

    int (*write_header)(struct AVFormatContext *);

    int (*write_packet)(struct AVFormatContext *, AVPacket *pkt);

    int (*write_trailer)(struct AVFormatContext *);

   

    int flags;

   

    int (*set_parameters)(struct AVFormatContext *, AVFormatParameters *);

    int (*interleave_packet)(struct AVFormatContext *, AVPacket *out, AVPacket *in, int flush);

 

   

    const struct AVCodecTag **codec_tag;

   

    struct AVOutputFormat *next;

} AVOutputFormat;

AVOutputFormat結構的定義可知,flv_muxer變量初始化的第一、二個成員分別為該muxer

的名稱與長名稱,第三、第四個成員為所對應MIMIE Type和后綴名,第五個成員是所對應的

私有結構的大小,第六、第七個成員為所對應的音頻編碼和視頻編碼類型ID,接下來就是三

個重要的接口函數,該 muxer的功能也就是通過調用這三個接口實現的。

 

flv_demuxerlibavformat\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

 

因為不是每種編碼方式都支持encodedecode,所以有以下三種注冊方式:

#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)

 

如支持flvflv_encoderflv_decoder變量就分別是在libavcodec\mpegvideo.clibavcodec\h263de.c中創建的。

3. 當前muxer/demuxer的匹配

FFmpeg的文件轉換過程中,首先要做的就是根據傳入文件和傳出文件的后綴名[FIXME]匹配

合適的demuxermuxer。匹配上的demuxermuxer都保存在如下所示,定義在ffmpeg.c里的

全局變量file_iformatfile_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數據

,依次調用每個demuxerread_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()函數中除了解析傳入參數並初始化demuxermuxerparse_options( )函數以外,

其他的功能都是在av_encode( )函數里完成的。

libavcodec\utils.c中有如下二個函數:

    AVCodec *avcodec_find_encoder(enum CodecID id)

    AVCodec *avcodec_find_decoder(enum CodecID id)

他們的功能就是根據傳入的CodecID,找到匹配的encoderdecoder

av_encode( )函數的開頭,首先初始化各個AVInputStreamAVOutputStream,然后分別調

用上述二個函數,並將匹配上的encoderdecoder分別保存在:

AVInputStream->AVStream *st->AVCodecContext *codec->struct AVCodec *codec

AVOutputStream->AVStream *st->AVCodecContext *codec->struct AVCodec *codec變量。

4. 其他主要數據結構

4.1 AVFormatContext

AVFormatContextFFMpeg格式轉換過程中實現輸入和輸出功能、保存相關數據的主要結構。

每一個輸入和輸出文件,都在如下定義的指針數組全局變量中有對應的實體。

    static AVFormatContext *output_files[MAX_FILES];

    static AVFormatContext *input_files[MAX_FILES];

對於輸入和輸出,因為共用的是同一個結構體,所以需要分別對該結構中如下定義的iformat

oformat成員賦值。

    struct AVInputFormat *iformat;

    struct AVOutputFormat *oformat;

對一個AVFormatContext來說,這二個成員不能同時有值,即一個AVFormatContext不能同時

含有demuxermuxer。在main( )函數開頭的parse_options( )函數中找到了匹配的muxer

demuxer之后,根據傳入的argv參數,初始化每個輸入和輸出的AVFormatContext結構,並保

存在相應的output_filesinput_files指針數組中。在av_encode( )函數中,output_files

input_files是作為函數參數傳入后,在其他地方就沒有用到了。

4.2 AVCodecContext

保存AVCodec指針和與codec相關數據,如videowidthheightaudiosample rate等。

AVCodecContext中的codec_typecodec_id二個變量對於encoder/decoder的匹配來說,最為

重要。

    enum CodecType codec_type;   

    enum CodecID codec_id;       

如上所示,codec_type保存的是CODEC_TYPE_VIDEOCODEC_TYPE_AUDIO等媒體類型,

codec_id保存的是CODEC_ID_FLV1CODEC_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;

    void *priv_data;

其中codec指針保存的就是上節所述的encoderdecoder結構。priv_data指針保存的是和具

體編解碼流相關的數據,如下代碼所示,在ASF的解碼過程中,priv_data保存的就是

ASFStream結構的數據。

    AVStream *st;

    ASFStream *asf_st; 

    … …

    st->priv_data = asf_st;

4.4 AVInputStream/ AVOutputStream

根據輸入和輸出流的不同,前述的AVStream結構都是封裝在AVInputStreamAVOutputStream

結構中,在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)接口,讀取輸入文件的一幀數

據保存在當前輸入AVFormatContextAVPacket成員中。

---------------------------------------------------------------------

FFMPEG是目前被應用最廣泛的編解碼軟件庫,支持多種流行的編解碼器,它是C語言實現的,不僅被集成到各種PC軟件,也經常被移植到多種嵌入式設備中。使用面向對象的辦法來設想這樣一個編解碼庫,首先讓人想到的是構造各種編解碼器的類,然后對於它們的抽象基類確定運行數據流的規則,根據算法轉換輸入輸出對象。

在實際的代碼,將這些編解碼器分成encoder/decodermuxer/demuxerdevice三種對象,分別對應於編解碼,輸入輸 出格式和設備。在main函數的開始,就是初始化這三類對象。在avcodec_register_all中,很多編解碼器被注冊,包括視頻的H.264 解碼器和X264編碼器等,

REGISTER_DECODER (H264, h264);

REGISTER_ENCODER (LIBX264, libx264);

找到相關的宏代碼如下

#define REGISTER_ENCODER(X,x) { \

          extern AVCodec x##_encoder; \

          if(CONFIG_##X##_ENCODER)  avcodec_register(&x##_encoder); }

#define REGISTER_DECODER(X,x) { \

          extern AVCodec x##_decoder; \

          if(CONFIG_##X##_DECODER)  avcodec_register(&x##_decoder); }

這樣就實際在代碼中根據CONFIG_##X##_ENCODER這樣的編譯選項來注冊libx264_encoderh264_decoder,注冊的過程發生在avcodec_register(AVCodec *codec)函數中,實際上就是向全局鏈表first_avcodec中加入libx264_encoderh264_decoder特定的編解碼 器,輸入參數AVCodec是一個結構體,可以理解為編解碼器的基類,其中不僅包含了名稱,id等屬性,而且包含了如下函數指針,讓每個具體的編解碼器擴展類實現。

    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,

                  const uint8_t *buf, int buf_size);

    void (*flush)(AVCodecContext *);

繼續追蹤libx264,也就是X264的靜態編碼庫,它在FFMPEG編譯的時候被引入作為H.264編碼器。在libx264.c中有如下代碼

AVCodec libx264_encoder = {

    .name = "libx264",

    .type = CODEC_TYPE_VIDEO,

    .id = CODEC_ID_H264,

    .priv_data_size = sizeof(X264Context),

    .init = X264_init,

    .encode = X264_frame,

    .close = X264_close,

    .capabilities = CODEC_CAP_DELAY,

    .pix_fmts = (enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_NONE },

    .long_name = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),

};

這里具體對來自AVCodec得屬性和方法賦值。其中

    .init = X264_init,

    .encode = X264_frame,

    .close = X264_close,

將函數指針指向了具體函數,這三個函數將使用libx264靜態庫中提供的API,也就是X264的主要接口函數進行具體實現。pix_fmts定義了所支持的輸入格式,這里420

PIX_FMT_YUV420P,   ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)

上面看到的X264Context封裝了X264所需要的上下文管理數據,

typedef struct X264Context {

    x264_param_t params;

    x264_t *enc;

    x264_picture_t pic;

    AVFrame out_pic;

} X264Context;

它 屬於結構體AVCodecContextvoid *priv_data變量,定義了每種編解碼器私有的上下文屬性,AVCodecContext也類似上下文基類一樣,還提供其他表示屏幕解析率、量化范圍等的上下文屬性和rtp_callback等函數指針供編解碼使用。

回到main函數,可以看到完成了各類編解碼器,輸入輸出格式和設備注冊以后,將進行上下文初始化和編解碼參數讀入,然后調用av_encode()函數進行具體的編解碼工作。根據該函數的注釋一路查看其過程:

1. 輸入輸出流初始化。

2. 根據輸入輸出流確定需要的編解碼器,並初始化。

3. 寫輸出文件的各部分

重點關注一下step23,看看怎么利用前面分析的編解碼器基類來實現多態。大概查看一下這段代碼的關系,發現在FFMPEG里,可以用類圖來表示大概的編解碼器組合。

http://1824.img.pp.sohu.com.cn/images/blog/2009/7/22/15/29/1234e7d516dg215.jpg

可以參考【3】來了解這些結構的含義(見附錄)。在這里會調用一系列來自utils.c的函數,這里的avcodec_open()函數,在打開編解碼器都會調用到,它將運行如下代碼:

    avctx->codec = codec;

    avctx->codec_id = codec->id;

    avctx->frame_number = 0;

    if(avctx->codec->init){

        ret = avctx->codec->init(avctx);

進行具體適配的編解碼器初始化,而這里的avctx->codec->init(avctx)就是調用AVCodec中函數指針定義的具體初始化函數,例如X264_init

avcodec_encode_video()和avcodec_encode_audio()被output_packet()調用進行音視頻編碼,將 同樣利用函數指針avctx->codec->encode()調用適配編碼器的編碼函數,如X264_frame進行具體工作。

從上面的分析,我們可以看到FFMPEG怎么利用面向對象來抽象編解碼器行為,通過組合和繼承關系具體化每個編解碼器實體。設想要在FFMPEG中加入新的解碼器H265,要做的事情如下:

1. config編譯配置中加入CONFIG_H265_DECODER

2. 利用宏注冊H265解碼器

3. 定義AVCodec 265_decoder變量,初始化屬性和函數指針

4. 利用解碼器API具體化265_decoderinit等函數指針

完成以上步驟,就可以把新的解碼器放入FFMPEG,外部的匹配和運行規則由基類的多態實現了。

4. X264架構分析

X264 是一款從2004年有法國大學生發起的開源H.264編碼器,對PC進行匯編級代碼優化,舍棄了片組和多參考幀等性能效率比不高的功能來提高編碼效率,它被FFMPEG作為引入的.264編碼庫,也被移植到很多DSP嵌入平台。前面第三節已經對FFMPEG中的X264進行舉例分析,這里將繼續結合 X264框架加深相關內容的了解。

查看代碼前,還是思考一下對於一款具體的編碼器,怎么面向對象分析呢?對熵編碼部分對不同算法的抽象,還有幀內或幀間編碼各種估計算法的抽象,都可以作為類來構建。

X264中,我們看到的對外API和上下文變量都聲明在X264.h中,API函數中,關於輔助功能的函數在common.c中定義

void x264_picture_alloc( x264_picture_t *pic, int i_csp, int i_width, int i_height );

void x264_picture_clean( x264_picture_t *pic );

int x264_nal_encode( void *, int *, int b_annexeb, x264_nal_t *nal );

而編碼功能函數定義在encoder.c

x264_t *x264_encoder_open   ( x264_param_t * );

int     x264_encoder_reconfig( x264_t *, x264_param_t * );

int     x264_encoder_headers( x264_t *, x264_nal_t **, int * );

int     x264_encoder_encode ( x264_t *, x264_nal_t **, int *, x264_picture_t *, x264_picture_t * );

void    x264_encoder_close  ( x264_t * );

x264.c文件中,有程序的main函數,可以看作做API使用的例子,它也是通過調用X264.h中的API和上下文變量來實現實際功能。

X264最重要的記錄上下文數據的結構體x264_t定義在common.h中,它包含了從線程控制變量到具體的SPSPPS、量化矩陣、cabac上下文等所有的H.264編碼相關變量。其中包含如下的結構體

    x264_predict_t      predict_16x16[4+3];

    x264_predict_t      predict_8x8c[4+3];

    x264_predict8x8_t   predict_8x8[9+3];

    x264_predict_t      predict_4x4[9+3];

    x264_predict_8x8_filter_t predict_8x8_filter;

    x264_pixel_function_t pixf;

    x264_mc_functions_t   mc;

    x264_dct_function_t   dctf;

    x264_zigzag_function_t zigzagf;

    x264_quant_function_t quantf;

    x264_deblock_function_t loopf;

跟蹤查看可以看到它們或是一個函數指針,或是由函數指針組成的結構,這樣的用法很想面向對象中的interface接口聲明。這些函數指針將在 x264_encoder_open()函數中被初始化,這里的初始化首先根據CPU的不同提供不同的函數實現代碼段,很多與可能是匯編實現,以提高代碼運行效率。其次把功能相似的函數集中管理,例如類似intra164種和intra4的九種預測函數都被用函數指針數組管理起來。

x264_encoder_encode()是負責編碼的主要函數,而其內包含的x264_slice_write()負責片層一下的具體編碼,包括了幀內和幀間宏塊編碼。在這里,cabaccavlc的行為是根據h->param.b_cabac來區別的,分別運行x264_macroblock_write_cabac()和x264_macroblock_write_cavlc()來寫碼流,在這一部分,功能函數按文件定義歸類,基本按照編碼流程圖運行,看起來更像面向過程的寫法,在已經初始化了具體的函數指針,程序就一直按編碼過程的邏輯實現。如果從整體架構來看,x264利用這種類似接口的形式實現了弱耦合和可重用, 利用x264_t這個貫穿始終的上下文,實現信息封裝和多態。

本文大概分析了FFMPEG/X264的代碼架構,重點探討用C語言來實現面向對象編碼,雖不至於強行向C++靠攏,但是也各有實現特色,保證實用性。值得規划C語言軟件項目所借鑒。 

 

【參考文獻】

1.“用例子說明面向對象和面向過程的區別

2. liyuming1978liyuming1978的專欄

3. “FFMpeg框架代碼閱讀

 

Using libavformat and libavcodec

Martin Böhme (boehme@inb.uni-luebeckREMOVETHIS.de)

February 18, 2004

Update (January 23 2009): By now, these articles are quite out of date... unfortunately, I haven't found the time to update them, but thankfully, others have jumped in. Stephen Dranger has a more recent tutorial, ryanfb of cryptosystem.org has an updated version of the code, and David Hoerl has a more recent update.

Update (July 22 2004): I discovered that the code I originally presented contained a memory leak (av_free_packet() wasn't being called). My apologies - I've updated the demo program and the code in the article to eliminate the leak.

Update (July 21 2004): There's a new prerelease of ffmpeg (0.4.9-pre1). I describe the changes to the libavformat / libavcodec API in this article.

The libavformat and libavcodec libraries that come with ffmpeg are a great way of accessing a large variety of video file formats. Unfortunately, there is no real documentation on using these libraries in your own programs (at least I couldn't find any), and the example programs aren't really very helpful either.

This situation meant that, when I used libavformat/libavcodec on a recent project, it took quite a lot of experimentation to find out how to use them. Here's what I learned - hopefully I'll be able to save others from having to go through the same trial-and-error process. There's also a small demo program that you can download. The code I'll present works with libavformat/libavcodec as included in version 0.4.8 of ffmpeg (the most recent version as I'm writing this). If you find that later versions break the code, please let me know.

In this document, I'll only cover how to read video streams from a file; audio streams work pretty much the same way, but I haven't actually used them, so I can't present any example code.

In case you're wondering why there are two libraries, libavformat and libavcodec: Many video file formats (AVI being a prime example) don't actually specify which codec(s) should be used to encode audio and video data; they merely define how an audio and a video stream (or, potentially, several audio/video streams) should be combined into a single file. This is why sometimes, when you open an AVI file, you get only sound, but no picture - because the right video codec isn't installed on your system. Thus, libavformat deals with parsing video files and separating the streams contained in them, and libavcodec deals with decoding raw audio and video streams.

Opening a Video File

First things first - let's look at how to open a video file and get at the streams contained in it. The first thing we need to do is to initialize libavformat/libavcodec:

av_register_all();

This registers all available file formats and codecs with the library so they will be used automatically when a file with the corresponding format/codec is opened. Note that you only need to call av_register_all() once, so it's probably best to do this somewhere in your startup code. If you like, it's possible to register only certain individual file formats and codecs, but there's usually no reason why you would have to do that.

Next off, opening the file:

AVFormatContext *pFormatCtx;

const char      *filename="myvideo.mpg";

// Open video file

if(av_open_input_file(&pFormatCtx, filename, NULL, 0, NULL)!=0)

    handle_error(); // Couldn't open file

The last three parameters specify the file format, buffer size and format parameters; by simply specifying NULL or 0 we ask libavformat to auto-detect the format and use a default buffer size. Replace handle_error() with appropriate error handling code for your application.

Next, we need to retrieve information about the streams contained in the file:

// Retrieve stream information

if(av_find_stream_info(pFormatCtx)<0)

    handle_error(); // Couldn't find stream information

This fills the streams field of the AVFormatContext with valid information. As a debugging aid, we'll dump this information onto standard error, but of course you don't have to do this in a production application:

dump_format(pFormatCtx, 0, filename, false);

As mentioned in the introduction, we'll handle only video streams, not audio streams. To make things nice and easy, we simply use the first video stream we find:

int            i, videoStream;

AVCodecContext *pCodecCtx;

// Find the first video stream

videoStream=-1;

for(i=0; i<pFormatCtx->nb_streams; i++)

    if(pFormatCtx->streams[i]->codec.codec_type==CODEC_TYPE_VIDEO)

    {

        videoStream=i;

        break;

    }

if(videoStream==-1)

    handle_error(); // Didn't find a video stream

// Get a pointer to the codec context for the video stream

pCodecCtx=&pFormatCtx->streams[videoStream]->codec;

OK, so now we've got a pointer to the so-called codec context for our video stream, but we still have to find the actual codec and open it:

AVCodec *pCodec;

// Find the decoder for the video stream

pCodec=avcodec_find_decoder(pCodecCtx->codec_id);

if(pCodec==NULL)

    handle_error(); // Codec not found

// Inform the codec that we can handle truncated bitstreams -- i.e.,

// bitstreams where frame boundaries can fall in the middle of packets

if(pCodec->capabilities & CODEC_CAP_TRUNCATED)

    pCodecCtx->flags|=CODEC_FLAG_TRUNCATED;

// Open codec

if(avcodec_open(pCodecCtx, pCodec)<0)

    handle_error(); // Could not open codec

(So what's up with those "truncated bitstreams"? Well, as we'll see in a moment, the data in a video stream is split up into packets. Since the amount of data per video frame can vary, the boundary between two video frames need not coincide with a packet boundary. Here, we're telling the codec that we can handle this situation.)

One important piece of information that is stored in the AVCodecContext structure is the frame rate of the video. To allow for non-integer frame rates (like NTSC's 29.97 fps), the rate is stored as a fraction, with the numerator in pCodecCtx->frame_rate and the denominator in pCodecCtx->frame_rate_base. While testing the library with different video files, I noticed that some codecs (notably ASF) seem to fill these fields incorrectly (frame_rate_base contains 1 instead of 1000). The following hack fixes this:

// Hack to correct wrong frame rates that seem to be generated by some

// codecs

if(pCodecCtx->frame_rate>1000 && pCodecCtx->frame_rate_base==1)

    pCodecCtx->frame_rate_base=1000;

Note that it shouldn't be a problem to leave this fix in place even if the bug is corrected some day - it's unlikely that a video would have a frame rate of more than 1000 fps.

One more thing left to do: Allocate a video frame to store the decoded images in:

AVFrame *pFrame;

pFrame=avcodec_alloc_frame();

That's it! Now let's start decoding some video.

Decoding Video Frames

As I've already mentioned, a video file can contain several audio and video streams, and each of those streams is split up into packets of a particular size. Our job is to read these packets one by one using libavformat, filter out all those that aren't part of the video stream we're interested in, and hand them on to libavcodec for decoding. In doing this, we'll have to take care of the fact that the boundary between two frames can occur in the middle of a packet.

Sound complicated? Lucikly, we can encapsulate this whole process in a routine that simply returns the next video frame:

bool GetNextFrame(AVFormatContext *pFormatCtx, AVCodecContext *pCodecCtx,

    int videoStream, AVFrame *pFrame)

{

    static AVPacket packet;

    static int      bytesRemaining=0;

    static uint8_t  *rawData;

    static bool     fFirstTime=true;

    int             bytesDecoded;

    int             frameFinished;

    // First time we're called, set packet.data to NULL to indicate it

    // doesn't have to be freed

    if(fFirstTime)

    {

        fFirstTime=false;

        packet.data=NULL;

    }

    // Decode packets until we have decoded a complete frame

    while(true)

    {

        // Work on the current packet until we have decoded all of it

        while(bytesRemaining > 0)

        {

            // Decode the next chunk of data

            bytesDecoded=avcodec_decode_video(pCodecCtx, pFrame,

                &frameFinished, rawData, bytesRemaining);

            // Was there an error?

            if(bytesDecoded < 0)

            {

                fprintf(stderr, "Error while decoding frame\n");

                return false;

            }

            bytesRemaining-=bytesDecoded;

            rawData+=bytesDecoded;

            // Did we finish the current frame? Then we can return

            if(frameFinished)

                return true;

        }

        // Read the next packet, skipping all packets that aren't for this

        // stream

        do

        {

            // Free old packet

            if(packet.data!=NULL)

                av_free_packet(&packet);

            // Read new packet

            if(av_read_packet(pFormatCtx, &packet)<0)

                goto loop_exit;

        } while(packet.stream_index!=videoStream);

        bytesRemaining=packet.size;

        rawData=packet.data;

    }

loop_exit:

    // Decode the rest of the last frame

    bytesDecoded=avcodec_decode_video(pCodecCtx, pFrame, &frameFinished,

        rawData, bytesRemaining);

    // Free last packet

    if(packet.data!=NULL)

        av_free_packet(&packet);

    return frameFinished!=0;

}

Now, all we have to do is sit in a loop, calling GetNextFrame() until it returns false. Just one more thing to take care of: Most codecs return images in YUV 420 format (one luminance and two chrominance channels, with the chrominance channels samples at half the spatial resolution of the luminance channel). Depending on what you want to do with the video data, you may want to convert this to RGB. (Note, though, that this is not necessary if all you want to do is display the video data; take a look at the X11 Xvideo extension, which does YUV-to-RGB and scaling in hardware.) Fortunately, libavcodec provides a conversion routine called img_convert, which does conversion between YUV and RGB as well as a variety of other image formats. The loop that decodes the video thus becomes:

while(GetNextFrame(pFormatCtx, pCodecCtx, videoStream, pFrame))

{

    img_convert((AVPicture *)pFrameRGB, PIX_FMT_RGB24, (AVPicture*)pFrame,

        pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);

    // Process the video frame (save to disk etc.)

    DoSomethingWithTheImage(pFrameRGB);

}

The RGB image pFrameRGB (of type AVFrame *) is allocated like this:

AVFrame *pFrameRGB;

int     numBytes;

uint8_t *buffer;

// Allocate an AVFrame structure

pFrameRGB=avcodec_alloc_frame();

if(pFrameRGB==NULL)

    handle_error();

// Determine required buffer size and allocate buffer

numBytes=avpicture_get_size(PIX_FMT_RGB24, pCodecCtx->width,

    pCodecCtx->height);

buffer=new uint8_t[numBytes];

// Assign appropriate parts of buffer to image planes in pFrameRGB

avpicture_fill((AVPicture *)pFrameRGB, buffer, PIX_FMT_RGB24,

    pCodecCtx->width, pCodecCtx->height);

Cleaning up

OK, we've read and processed our video, now all that's left for us to do is clean up after ourselves:

// Free the RGB image

delete [] buffer;

av_free(pFrameRGB);

// Free the YUV frame

av_free(pFrame);

// Close the codec

avcodec_close(pCodecCtx);

// Close the video file

av_close_input_file(pFormatCtx);

Done!

Sample Code

A sample app that wraps all of this code up in compilable form is here. If you have any additional comments, please contact me at boehme@inb.uni-luebeckREMOVETHIS.de. Standard disclaimer: I assume no liability for the correct functioning of the code and techniques presented in this article.

 

 

 

 

 

二,解碼流程

FFMpeg的解碼流程

1. 從基礎談起
先給出幾個概念,以在后面的分析中方便理解
Container:在音視頻中的容器,一般指的是一種特定的文件格式,里面指明了所包含的
    音視頻,字幕等相關信息
Stream:這個詞有些微妙,很多地方都用到,比如TCP,SVR4系統等,其實在音視頻,你
    可以理解為單純的音頻數據或者視頻數據等
Frames:這個概念不是很好明確的表示,指的是Stream中的一個數據單元,要真正對這
    個概念有所理解,可能需要看一些音視頻編碼解碼的理論知識
Packet:是Stream的raw數據
Codec:Coded + Decoded
其實這些概念在在FFmpeg中都有很好的體現,我們在后續分析中會慢慢看到

2.解碼的基本流程
我很懶,於是還是選擇了從<An ffmpeg and SDL Tutorial>中的流程概述:

10 OPEN video_stream FROM video.avi
20 READ packet FROM video_stream INTO frame
30 IF frame NOT COMPLETE GOTO 20
40 DO SOMETHING WITH frame
50 GOTO 20

這就是解碼的全過程,一眼看去,是不是感覺不過如此:),不過,事情有深有淺,從淺
到深,然后從深回到淺可能才是一個有意思的過程,我們的故事,就從這里開始,展開
來講。

3.例子代碼
在<An ffmpeg and SDL Tutorial 1>中,給出了一個陽春版的解碼器,我們來仔細看看
陽春后面的故事,為了方便講述,我先貼出代碼:

#include <ffmpeg/avcodec.h>
#include <ffmpeg/avformat.h>

#include <stdio.h>

void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame) {
FILE *pFile;
char szFilename[32];
int y;

// Open file
sprintf(szFilename, "frame%d.ppm", iFrame);
pFile=fopen(szFilename, "wb");
if(pFile==NULL)
    return;

// Write header
fprintf(pFile, "P6\n%d %d\n255\n", width, height);

// Write pixel data
for(y=0; y<height; y++)
    fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);

// Close file
fclose(pFile);
}

int main(int argc, char *argv[]) {
AVFormatContext *pFormatCtx;
int             i, videoStream;
AVCodecContext *pCodecCtx;
AVCodec         *pCodec;
AVFrame         *pFrame; 
AVFrame         *pFrameRGB;
AVPacket        packet;
int             frameFinished;
int             numBytes;
uint8_t         *buffer;

if(argc < 2) {
    printf("Please provide a movie file\n");
    return -1;
}
// Register all formats and codecs
########################################
[1]
########################################
av_register_all();

// Open video file
########################################
[2]
########################################
if(av_open_input_file(&pFormatCtx, argv[1], NULL, 0, NULL)!=0)
    return -1; // Couldn't open file

// Retrieve stream information
########################################
[3]
########################################
if(av_find_stream_info(pFormatCtx)<0)
    return -1; // Couldn't find stream information

// Dump information about file onto standard error
dump_format(pFormatCtx, 0, argv[1], 0);

// Find the first video stream
videoStream=-1;
for(i=0; i<pFormatCtx->nb_streams; i++)
    if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO) {
      videoStream=i;
      break;
    }
if(videoStream==-1)
    return -1; // Didn't find a video stream

// Get a pointer to the codec context for the video stream
pCodecCtx=pFormatCtx->streams[videoStream]->codec;

// Find the decoder for the video stream
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL) {
    fprintf(stderr, "Unsupported codec!\n");
    return -1; // Codec not found
}
// Open codec
if(avcodec_open(pCodecCtx, pCodec)<0)
    return -1; // Could not open codec

// Allocate video frame
pFrame=avcodec_alloc_frame();

// Allocate an AVFrame structure
pFrameRGB=avcodec_alloc_frame();
if(pFrameRGB==NULL)
    return -1;
    
// Determine required buffer size and allocate buffer
numBytes=avpicture_get_size(PIX_FMT_RGB24, pCodecCtx->width,
                  pCodecCtx->height);
buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));

// Assign appropriate parts of buffer to image planes in pFrameRGB
// Note that pFrameRGB is an AVFrame, but AVFrame is a superset
// of AVPicture
avpicture_fill((AVPicture *)pFrameRGB, buffer, PIX_FMT_RGB24,
         pCodecCtx->width, pCodecCtx->height);

// Read frames and save first five frames to disk
########################################
[4]
########################################
i=0;
while(av_read_frame(pFormatCtx, &packet)>=0) {
    // Is this a packet from the video stream?
    if(packet.stream_index==videoStream) {
      // Decode video frame
      avcodec_decode_video(pCodecCtx, pFrame, &frameFinished, 
               packet.data, packet.size);
      
      // Did we get a video frame?
      if(frameFinished) {
    // Convert the image from its native format to RGB
    img_convert((AVPicture *)pFrameRGB, PIX_FMT_RGB24, 
                    (AVPicture*)pFrame, pCodecCtx->pix_fmt, 
                    pCodecCtx->width, 
                    pCodecCtx->height);
    
    // Save the frame to disk
    if(++i<=5)
      SaveFrame(pFrameRGB, pCodecCtx->width, pCodecCtx->height, 
            i);
      }
    }
    
    // Free the packet that was allocated by av_read_frame
    av_free_packet(&packet);
}

// Free the RGB image
av_free(buffer);
av_free(pFrameRGB);

// Free the YUV frame
av_free(pFrame);

// Close the codec
avcodec_close(pCodecCtx);

// Close the video file
av_close_input_file(pFormatCtx);

return 0;
}

代碼注釋得很清楚,沒什么過多需要講解的,關於其中的什么YUV420,RGB,PPM等格式
,如果不理解,麻煩還是google一下,也可以參考:http://barrypopy.cublog.cn/里面
的相關文章

其實這部分代碼,很好了Demo了怎么樣去抓屏功能的實現,但我們得去看看魔術師在后
台的一些手法,而不只是簡單的享受其表演。

4.背后的故事
真正的難度,其實就是上面的[1],[2],[3],[4],其他部分,都是數據結構之間的轉換,
如果你認真看代碼的話,不難理解其他部分。

[1]:沒什么太多好說的,如果不明白,看我轉載的關於FFmepg框架的文章

[2]:先說說里面的AVFormatContext *pFormatCtx結構,字面意思理解AVFormatContext
就是關於AVFormat(其實就是我們上面說的Container格式)的所處的Context(場景),自
然是保存Container信息的總控結構了,后面你也可以看到,基本上所有的信息,都可
以從它出發而獲取到
    
我們來看看av_open_input_file()都做了些什么:
[libavformat/utils.c]
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
                       AVInputFormat *fmt,
                       int buf_size,
                       AVFormatParameters *ap)
{
    ......
    if (!fmt) {
       
        fmt = av_probe_input_format(pd, 0);
    }

   ......
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
   ......
}

這樣看來,只是做了兩件事情:
1). 偵測容器文件格式
2). 從容器文件獲取Stream的信息

這兩件事情,實際上就是調用特定文件的demuxer以分離Stream的過程:

具體流程如下:

av_open_input_file
    |
    +---->av_probe_input_format從first_iformat中遍歷注冊的所有demuxer以 
    |     調用相應的probe函數
    |
    +---->av_open_input_stream調用指定demuxer的read_header函數以獲取相關
          流的信息ic->iformat->read_header

如果反過來再參考我轉貼的關於ffmpeg框架的文章,是否清楚一些了呢:)

[3]:簡單從AVFormatContext獲取Stream的信息,沒什么好多說的

[4]:先簡單說一些ffmpeg方面的東西,從理論角度說過來,Packet可以包含frame的部
分數據,但ffmpeg為了實現上的方便,使得對於視頻來說,每個Packet至少包含一
frame,對於音頻也是相應處理,這是實現方面的考慮,而非協議要求.
因此,在上面的代碼實際上是這樣的:
    從文件中讀取packet,從Packet中解碼相應的frame;
    從幀中解碼;
    if(解碼幀完成)
        do something();

我們來看看如何獲取Packet,又如何從Packet中解碼frame的。

av_read_frame
    |
    +---->av_read_frame_internal
        |
        +---->av_parser_parse調用的是指定解碼器的s->parser->parser_parse函數以從raw packet中重構frame

avcodec_decode_video
    |
    +---->avctx->codec->decode調用指定Codec的解碼函數
    
因此,從上面的過程可以看到,實際上分為了兩部分:

一部分是解復用(demuxer),然后是解碼(decode)

使用的分別是:
av_open_input_file()            ---->解復用

av_read_frame()            |
                           |    ---->解碼    
avcodec_decode_video()     |

5.后面該做些什么
結合這部分和轉貼的ffmepg框架的文章,應該可以基本打通解碼的流程了,后面的問題則是針對具體容器格式和具體編碼解碼器的分析

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM