Skip to content

Instantly share code, notes, and snippets.

@GerrieWell
Last active June 2, 2016 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GerrieWell/4bc60bd578b0323856804fe42827538b to your computer and use it in GitHub Desktop.
Save GerrieWell/4bc60bd578b0323856804fe42827538b to your computer and use it in GitHub Desktop.
ffmpeg 写mp4 header

ffmpeg 写mp4 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment