avformat_write_header失败,错误"无效参数

时间:2014-09-04 11:05:56

标签: c ffmpeg libavformat

我正在尝试将一大块mp4文件写入.ts文件,该文件尚不存在。 所以首先我用这种方式创建AVFormatContext:

AVOutputFormat *oformat = av_guess_format( NULL,
                                           "mpegts",
                                           "video/x-mpegts" );
AVFormatContext * outFormatContext = NULL;
avformat_alloc_output_context2( &outFormatContext, oformat, NULL, dst_file)
创建

outFormatContext,并将outFormatContext-> oformat设置为oformat。然后我在outFormatContext上打开I / O上下文:

avio_open(&outFormatContext->pb, dst_file, AVIO_FLAG_WRITE)
avformat_write_header( outFormatContext, NULL );

根据this这足以让avformat_write_header工作但它失败并出现错误“invalid argument”。

成功编写标题还需要做些什么?

1 个答案:

答案 0 :(得分:2)

虽然有点迟,但我希望它会有所帮助。 这是我调用avformat_write_header的方法,您应该提供一个流来编写标题。

AVFormatContext* pOutFormatContext;
AVOutputFormat* avOutputFormat;
if ((avOutputFormat = av_guess_format(NULL, "mp4", "video/mp4")) == NULL) {
    cerr << "Could not guess output format" << endl;
    return -1;
}

avformat_alloc_output_context2(&pOutFormatContext,
                               av_guess_format("mp4", NULL, "video/mp4"), NULL, NULL);
if (pOutFormatContext == NULL) {
    cerr << "Could not allocate output context" << endl;
    return -1;
}

for (int i = 0; i < avFormatContext->nb_streams; i++) {
    AVStream* inAVStream = avFormatContext->streams[i];
    AVStream* outAVStream = avformat_new_stream(pOutFormatContext, inAVStream->codec->codec);
    if (avcodec_copy_context(outAVStream->codec, inAVStream->codec) < 0) {
        cerr << "Failed to copy codec context" << endl;
        return -1;
    }

    outAVStream->codec->codec_tag = 0;
    if (pOutFormatContext->oformat->flags & AVFMT_GLOBALHEADER) {
        outAVStream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    }
}

avio_open(&pOutFormatContext->pb, "test.mp4", AVIO_FLAG_READ_WRITE);
if (pOutFormatContext->pb == NULL) {
    cerr << "Could not open for writing" << endl;
    return -1;
}
if (avformat_write_header(pOutFormatContext, NULL) != 0) {
    cerr << "Could not write header" << endl;
    return -1;
}