[轉(zhuǎn)載更新] FFMpeg的解碼流程

1. 從基礎(chǔ)談起

先給出幾個(gè)概念拿霉,以在后面的分析中方便理解
Container: 在音視頻中的容器曹体,一般指的是一種特定的文件格式扳缕,里面指明了所包含的音視頻,字幕等相關(guān)信息
Stream: 這個(gè)詞有些微妙举畸,很多地方都用到查排,比如TCP,SVR4系統(tǒng)等抄沮,其實(shí)在音視頻跋核,你 可以理解為單純的音頻數(shù)據(jù)或者視頻數(shù)據(jù)等
Frame: 這個(gè)概念不是很好明確的表示,指的是Stream中的一個(gè)數(shù)據(jù)單元叛买,要真正對(duì)這個(gè)概念有所理解砂代,可能需要看一些音視頻編碼解碼的理論知識(shí)
Packet: 是Stream的raw數(shù)據(jù)
Codec: encoder + decoder
其實(shí)這些概念在在FFmpeg中都有很好的體現(xiàn),我們?cè)诤罄m(xù)分析中會(huì)慢慢看到

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

這就是解碼的全過(guò)程刻伊,一眼看去,是不是感覺(jué)不過(guò)如此:),不過(guò)椒功,事情有深有淺捶箱,從淺到深,然后從深回到淺可能才是一個(gè)有意思的過(guò)程蛾茉,我們的故事,就從這里開(kāi)始撩鹿,展開(kāi)來(lái)講谦炬。

3.例子代碼

在<An ffmpeg and SDL Tutorial 1>中,給出了一個(gè)陽(yáng)春版的解碼器,我們來(lái)仔細(xì)看看陽(yáng)春后面的故事键思,為了方便講述础爬,我先貼出代碼:

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>

#include <stdio.h>

// compatibility with newer API
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif

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[]) {
  // Initalizing these to NULL prevents segfaults!
  AVFormatContext   *pFormatCtx = NULL;
  int               i, videoStream;
  AVCodecContext    *pCodecCtxOrig = NULL;
  AVCodecContext    *pCodecCtx = NULL;
  AVCodec           *pCodec = NULL;
  AVFrame           *pFrame = NULL;
  AVFrame           *pFrameRGB = NULL;
  AVPacket          packet;
  int               frameFinished;
  int               numBytes;
  uint8_t           *buffer = NULL;
  struct SwsContext *sws_ctx = NULL;

  if(argc < 2) {
    printf("Please provide a movie file\n");
    return -1;
  }
  // [1] Register all formats and codecs
  av_register_all();
  
  // [2] Open video file
  if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0)
    return -1; // Couldn't open file
  
  // [3] Retrieve stream information
  if(avformat_find_stream_info(pFormatCtx, NULL)<0)
    return -1; // Couldn't find stream information
  
  // Dump information about file onto standard error
  av_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==AVMEDIA_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
  pCodecCtxOrig=pFormatCtx->streams[videoStream]->codec;
  // Find the decoder for the video stream
  pCodec=avcodec_find_decoder(pCodecCtxOrig->codec_id);
  if(pCodec==NULL) {
    fprintf(stderr, "Unsupported codec!\n");
    return -1; // Codec not found
  }
  // Copy context
  pCodecCtx = avcodec_alloc_context3(pCodec);
  if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) {
    fprintf(stderr, "Couldn't copy codec context");
    return -1; // Error copying codec context
  }

  // Open codec
  if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
    return -1; // Could not open codec
  
  // Allocate video frame
  pFrame=av_frame_alloc();
  
  // Allocate an AVFrame structure
  pFrameRGB=av_frame_alloc();
  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);
  
  // initialize SWS context for software scaling
  sws_ctx = sws_getContext(pCodecCtx->width,
               pCodecCtx->height,
               pCodecCtx->pix_fmt,
               pCodecCtx->width,
               pCodecCtx->height,
               PIX_FMT_RGB24,
               SWS_BILINEAR,
               NULL,
               NULL,
               NULL
               );

  // [4] Read frames and save first five frames to disk
  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_video2(pCodecCtx, pFrame, &frameFinished, &packet);
      
      // Did we get a video frame?
      if(frameFinished) {
    // Convert the image from its native format to RGB
    sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
          pFrame->linesize, 0, pCodecCtx->height,
          pFrameRGB->data, pFrameRGB->linesize);
    
    // 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_frame_free(&pFrameRGB);
  
  // Free the YUV frame
  av_frame_free(&pFrame);
  
  // Close the codecs
  avcodec_close(pCodecCtx);
  avcodec_close(pCodecCtxOrig);

  // Close the video file
  avformat_close_input(&pFormatCtx);
  
  return 0;
}

代碼注釋得很清楚,沒(méi)什么過(guò)多需要講解的吼鳞,關(guān)于其中的什么YUV420看蚜,RGB,PPM等格式赔桌,如果不理解供炎,麻煩還是google一下,也可以參考:http://barrypopy.cublog.cn/里面的相關(guān)文章其實(shí)這部分代碼疾党,很好了Demo了怎么樣去抓屏功能的實(shí)現(xiàn)音诫,但我們得去看看魔術(shù)師在后臺(tái)的一些手法,而不只是簡(jiǎn)單的享受其表演雪位。

4.背后的故事

真正的難度竭钝,其實(shí)就是上面的[1],[2],[3],[4],其他部分,都是數(shù)據(jù)結(jié)構(gòu)之間的轉(zhuǎn)換雹洗,如果你認(rèn)真看代碼的話香罐,不難理解其他部分。

[1]:av_register_all

注冊(cè)所有容器與codec

[2]:avformat_open_input

先說(shuō)說(shuō)里面的AVFormatContext *pFormatCtx結(jié)構(gòu)时肿,字面意思理解AVFormatContext就是關(guān)于AVFormat(其實(shí)就是我們上面說(shuō)的Container格式)的所處的Context(場(chǎng)景)庇茫,自然是保存Container信息的總控結(jié)構(gòu)了,后面你也可以看到嗜侮,基本上所有的信息港令,都可以從它出發(fā)而獲取到
我們來(lái)看看avformat_open_input()都做了些什么:

Paste_Image.png

這樣看來(lái),只是做了兩件事情:

1). 偵測(cè)容器文件格式

實(shí)際上就是探測(cè)確定demuxer
av_probe_input_format3從first_iformat開(kāi)始遍歷注冊(cè)的所有demuxer锈颗,以mkv為例:

AVInputFormat ff_matroska_demuxer = { 
  .name = "matroska,webm", 
  .long_name = NULL_IF_CONFIG_SMALL("Matroska / WebM"), 
  .extensions = "mkv,mk3d,mka,mks", 
  .priv_data_size = sizeof(MatroskaDemuxContext), 
  .read_probe = matroska_probe, 
  .read_header = matroska_read_header, 
  .read_packet = matroska_read_packet, 
  .read_close = matroska_read_close, 
  .read_seek = matroska_read_seek, 
  .mime_type = "audio/webm,audio/x-matroska,video/webm,video/x-matroska"
};

遍歷調(diào)用相應(yīng)的read_probe函數(shù)顷霹,最終確定容器格式( AVFormatContext的iformat ):

typedef struct AVFormatContext { 
......
/** 
* The input container format. 
* 
* Demuxing only, set by avformat_open_input(). 
*/ 
struct AVInputFormat *iformat;
......
}

2). 從容器文件獲取Stream的信息

其實(shí)就是使用確定了的demuxer的方法分離出所有Stream的過(guò)程:
av_open_input_stream調(diào)用已確定demuxer的read_header函數(shù)以獲取所有stream信息(AVFormatContext的streams):

/** 
* Number of elements in AVFormatContext.streams. 
* 
* Set by avformat_new_stream(), must not be modified by any other code. 
*/
unsigned int nb_streams;
/** 
* A list of all streams in the file. New streams are created with 
* avformat_new_stream(). 
* 
* - demuxing: streams are created by libavformat in avformat_open_input(). 
*             If AVFMTCTX_NOHEADER is set in ctx_flags, then new streams may also 
*             appear in av_read_frame(). 
* - muxing: streams are created by the user before avformat_write_header(). 
* 
* Freed by libavformat in avformat_free_context(). 
*/
AVStream **streams;

[3]: avformat_find_stream_info

進(jìn)一步解析Stream的信息,比如根據(jù)上一步確定的enum AVCodecID codec_id击吱,確定對(duì)應(yīng)的const struct AVCodec *codec

[4]: av_read_frame, avcodec_decode_video2

先簡(jiǎn)單說(shuō)一些ffmpeg方面的東西淋淀,從理論角度說(shuō)過(guò)來(lái),Packet可以包含frame的部分?jǐn)?shù)據(jù)覆醇,但ffmpeg為了實(shí)現(xiàn)上的方便朵纷,使得對(duì)于視頻來(lái)說(shuō),每個(gè)Packet至少包含一frame,對(duì)于音頻也是相應(yīng)處理永脓,這是實(shí)現(xiàn)方面的考慮袍辞,而非協(xié)議要求.因此,在上面的代碼實(shí)際上是這樣的: 從文件中讀取packet常摧,從Packet中解碼相應(yīng)的frame; 從幀中解碼; if(解碼幀完成) do something();
我們來(lái)看看如何獲取Packet,又如何從Packet中解碼frame的搅吁。

av_read_frame 
---> av_read_frame_internal  
---> ff_read_packet  
---> (AVInputFormat *) iformat->read_packet
  avcodec_decode_video2 
---> avctx->codec->decode  (調(diào)用指定Codec的解碼函數(shù))

因此威创,從上面的過(guò)程可以看到,實(shí)際上分為了兩部分:
一部分是解復(fù)用(demuxer):av_read_frame();
然后是解碼(decode): avcodec_decode_video2()

5.后面該做些什么

結(jié)合這部分和轉(zhuǎn)貼的ffmepg框架的文章谎懦,應(yīng)該可以基本打通解碼的流程了肚豺,后面的問(wèn)題則是針對(duì)具體容器格式和具體編碼解碼器的分析,后面我們繼續(xù)參考:
[1]. <An ffmpeg and SDL Tutorial>
http://dranger.com/ffmpeg/tutorial01.html
[2]. <FFMpeg框架代碼閱讀>
http://blog.csdn.net/wstarx/archive/2007/04/20/1572393.aspx

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末界拦,一起剝皮案震驚了整個(gè)濱河市吸申,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌享甸,老刑警劉巖截碴,帶你破解...
    沈念sama閱讀 222,252評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異枪萄,居然都是意外死亡隐岛,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)瓷翻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)聚凹,“玉大人,你說(shuō)我怎么就攤上這事齐帚《恃溃” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,814評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵对妄,是天一觀的道長(zhǎng)湘今。 經(jīng)常有香客問(wèn)我,道長(zhǎng)剪菱,這世上最難降的妖魔是什么摩瞎? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,869評(píng)論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮孝常,結(jié)果婚禮上旗们,老公的妹妹穿的比我還像新娘。我一直安慰自己构灸,他們只是感情好上渴,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著喜颁,像睡著了一般稠氮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上半开,一...
    開(kāi)封第一講書(shū)人閱讀 52,475評(píng)論 1 312
  • 那天隔披,我揣著相機(jī)與錄音,去河邊找鬼寂拆。 笑死奢米,一個(gè)胖子當(dāng)著我的面吹牛芥炭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播恃慧,決...
    沈念sama閱讀 41,010評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼渺蒿!你這毒婦竟也來(lái)了痢士?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,924評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤茂装,失蹤者是張志新(化名)和其女友劉穎怠蹂,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體少态,經(jīng)...
    沈念sama閱讀 46,469評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡城侧,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了彼妻。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嫌佑。...
    茶點(diǎn)故事閱讀 40,680評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖侨歉,靈堂內(nèi)的尸體忽然破棺而出屋摇,到底是詐尸還是另有隱情,我是刑警寧澤幽邓,帶...
    沈念sama閱讀 36,362評(píng)論 5 351
  • 正文 年R本政府宣布炮温,位于F島的核電站,受9級(jí)特大地震影響牵舵,放射性物質(zhì)發(fā)生泄漏柒啤。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評(píng)論 3 335
  • 文/蒙蒙 一畸颅、第九天 我趴在偏房一處隱蔽的房頂上張望担巩。 院中可真熱鬧,春花似錦重斑、人聲如沸兵睛。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,519評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)祖很。三九已至,卻和暖如春漾脂,著一層夾襖步出監(jiān)牢的瞬間假颇,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,621評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工骨稿, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留笨鸡,地道東北人姜钳。 一個(gè)月前我還...
    沈念sama閱讀 49,099評(píng)論 3 378
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像形耗,于是被迫代替她去往敵國(guó)和親哥桥。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容