c - avformat_write_header 失败并出现错误“无效参数

标签 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 工作,但它失败并出现错误“无效参数”。

还需要做什么才能成功写入 header ?

最佳答案

虽然有点晚了,但希望对你有帮助。 这是我调用 avformat_write_header 的方法,您应该提供一个流来写入 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;
}

关于c - avformat_write_header 失败并出现错误“无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25663884/

相关文章:

c - 使用 FFMPEG 从 NV12 原始数据转换为 H264 时出现颜色不匹配

c - 一个数字在一个数字中出现了多少次

Android - 将录制的 H.264 Main Profile 视频转换为 H.264 Baseline Profile 的最佳解决方案

android - 使用 ffmpeg 确定歌曲的节奏

ffmpeg - 使用 libavcodec 读取 .mkv 视频文件

c++ - 使用 avformat_open_input 打开原始音频

java - 填充错误 - 在 Java 中使用 AES 加密并在 C 中使用解密时

c - Xeon Phi 的 reduce 操作的内联组装

c - C 中的 Getaddrinfo 问题

ffmpeg - 使用 sox 组合音频