[转]FFMpeg的解码流程
来源:互联网 发布:失落沙洲知乎 编辑:程序博客网 时间:2024/05/21 03:16
FFMpeg的解码流程
1. 从基础谈起
先给出几个概念,以在后面的分析中方便理解
Container:在音视频中的容器,一般指的是一种特定的文件格式,里面指明了所包含的
Stream:这个词有些微妙,很多地方都用到,比如TCP,SVR4系统等,其实在音视频,你
Frames:这个概念不是很好明确的表示,指的是Stream中的一个数据单元,要真正对这
Packet:是Stream的raw数据
Codec:Coded + Decoded
其实这些概念在在FFmpeg中都有很好的体现,我们在后续分析中会慢慢看到
2.解码的基本流程
我很懒,于是还是选择了从<An ffmpeg and SDLTutorial>中的流程概述:
10 OPEN video_stream FROMvideo.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 Tutorial1>中,给出了一个阳春版的解码器,我们来仔细看看
阳春后面的故事,为了方便讲述,我先贴出代码:
#include<ffmpeg/avcodec.h>
#include <ffmpeg/avformat.h>
#include<stdio.h>
void SaveFrame(AVFrame *pFrame, intwidth, 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)
// Write header
fprintf(pFile, "P6\n%d %d\n255\n", width, height);
// Write pixel data
for(y=0; y<height; y++)
// Close file
fclose(pFile);
}
int main(int argc, char *argv[]){
AVFormatContext *pFormatCtx;
int
AVCodecContext *pCodecCtx;
AVCodec
AVFrame
AVFrame
AVPacket
int
int
uint8_t
if(argc < 2) {
}
// 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)
// Retrieve stream information
########################################
[3]
########################################
if(av_find_stream_info(pFormatCtx)<0)
// 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(videoStream==-1)
// Get a pointer to the codec context for the videostream
pCodecCtx=pFormatCtx->streams[videoStream]->codec;
// Find the decoder for the video stream
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL) {
}
// Open codec
if(avcodec_open(pCodecCtx, pCodec)<0)
// Allocate video frame
pFrame=avcodec_alloc_frame();
// Allocate an AVFrame structure
pFrameRGB=avcodec_alloc_frame();
if(pFrameRGB==NULL)
// Determine required buffer size and allocate buffer
numBytes=avpicture_get_size(PIX_FMT_RGB24,pCodecCtx->width,
buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
// Assign appropriate parts of buffer to image planes inpFrameRGB
// Note that pFrameRGB is an AVFrame, but AVFrame is asuperset
// of AVPicture
avpicture_fill((AVPicture *)pFrameRGB, buffer,PIX_FMT_RGB24,
// Read frames and save first five frames to disk
########################################
[4]
########################################
i=0;
while(av_read_frame(pFormatCtx,&packet)>=0) {