主要函数说明:
av_register_all();
avformat_alloc_output_context2():初始化输出文件。
avio_open():打开输出文件。
avformat_write_header():写入文件头。
avformat_new_stream() 向媒体文件添加新流。
av_interleaved_write_frame():写入一个AVPacket到输出文件。
av_write_trailer():写入文件尾。
实现代码参考:
参考雷神的 最简单的基于FFmpeg的封装格式处理
和
ffmpeg h264文件和裸流 封装mp4
实现代码如下:
头文件和全局定义:
#include "libavformat/avformat.h"
static AVFormatContext* g_OutFmt_Ctx;
static int vi = -1;
static int STREAM_FRAME_RATE = 30;
static HI_BOOL b_First_IDR_Find = HI_FALSE;
static int ptsInc = 0;
添加新流函数
/* Add an output stream */
static int HI_PDT_Add_Stream(AVFormatContext *poutFmtCtx)
{
AVOutputFormat *pOutFmt = NULL;
AVCodecContext *PAVCodecCtx = NULL;
AVStream *pAVStream = NULL;
AVCodec *pcodec = NULL;
pOutFmt = poutFmtCtx->oformat;
/* find the encoder */
pcodec = avcodec_find_encoder(pOutFmt->video_codec);
if (NULL == pcodec)
{
printf("could not find encoder for '%s' \n", avcodec_get_name(pOutFmt->video_codec));
return -1;
}
pAVStream = avformat_new_stream(poutFmtCtx, pcodec);
if (NULL == pAVStream)
{
printf("could not allocate stream \n");
return -1;
}
pAVStream->id = poutFmtCtx->nb_streams-1;
PAVCodecCtx = pAVStream->codec;
vi = pAVStream->index;
switch ((pcodec)->type)
{
case AVMEDIA_TYPE_AUDIO:
printf("AVMEDIA_TYPE_AUDIO\n");
PAVCodecCtx->sample_fmt = (pcodec)->sample_fmts ? (pcodec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
PAVCodecCtx->bit_rate = 64000;
PAVCodecCtx->sample_rate = 44100;
PAVCodecCtx->channels = 2;
break;
case AVMEDIA_TYPE_VIDEO:
printf(