1)ffmpeg 写avi时候,avio_open成功,但是写avi头时调用avformat_write_header失败
在解码器初始化时,先avio_open创建文件后,然后马上调用avformat_write_header函数,会出现avformat_write_header失败,返回值-22;但是如果将解码器封装成一个类,提供一个封装好的avformat_write_header函数就没有这个问题了。
原因:avformat_write_header的参数信息不正确,增加帧率控制就ok了
DecodecContext->time_base.num=1;
DecodecContext->time_base.den=25;
//释放avDecodeFmtContext 失败
2)avformat_free_context(avDecodeFmtContext);
if (VideoDecodeSt->codec!=NULL)
{
avcodec_close(VideoDecodeSt->codec);
av_free(VideoDecodeSt->codec);
VideoDecodeSt->codec=NULL;
}
if (avDecodeFmtContext!=NULL)
{
avformat_free_context(avDecodeFmtContext);
avDecodeFmtContext=NULL;
}
这样是失败的,但是改为这样就ok
if (VideoDecodeSt->codec!=NULL)
{
avcodec_close(VideoDecodeSt->codec);
//av_free(VideoDecodeSt->codec);
//VideoDecodeSt->codec=NULL;
}
if (avDecodeFmtContext!=NULL)
{
avformat_free_context(avDecodeFmtContext);
avDecodeFmtContext=NULL;
}
但是这样后,造成释放avformat_free_context(avDecodeFmtContext); 后,在重新初始化avformat_alloc_output_context2 出错,该函数返回值-22
原因是:
int ret=avformat_alloc_output_context2(&avDecodeFmtContext, NULL, NULL, fileName.c_str());
最后的fileName.c_str());没有传递正确;
ffmpeg 转码使用的api调用顺序:
1) av_register_all();
2) avformat_alloc_output_context2(&oc, NULL, NULL, filename);
3)avcodec_find_encoder(codec_id);
4)avformat_new_stream(oc, *codec);
5)可选
//防止编码延迟修改参数
av_opt_set(c->priv_data, "preset", "superfast", 0);
av_opt_set(c->priv_data, "tune", "zerolatency", 0);
6) av_dump_format(oc, 0, filename, 1);
7) if (!(fmt->flags & AVFMT_NOFILE)) {
ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
if (ret < 0) {
//fprintf(stderr, "Could not open '%s': %s\n", filename,av_err2str(ret));
return 1;
}
}
8) ret = avformat_write_header(oc, NULL);
9) ret = av_interleaved_write_frame(oc, &pkt);
10) av_write_trailer(oc);
11)avcodec_close(st->codec);
12)if (!(fmt->flags & AVFMT_NOFILE))
{
/* Close the output file. */
avio_close(oc->pb);
}
13) avformat_free_context(oc);