欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FFMPEG文件转封装

程序员文章站 2022-07-13 13:22:59
...

前段时间开发了一个基于FFMPEG的文件录制功能,具体来讲,就是把在线码流转封装成本地文件。当然,实际应用过程中,需要考虑指定的封装格式与输入文件或码流的编码格式是否兼容,录制固定大小或时长的文件时对于文件size或时间戳的处理,等等。这里先将这些细节省略,只讲一下大体流程。

媒体转封装的过程可参考如下框图:左侧为输入文件(或码流),右侧为输出文件。推流的流程大抵也是如此,但要加上网络初始化函数,并考虑时间戳与当前时间的一致性等。

FFMPEG文件转封装

输入侧:

avformat_open_input(): 打开指定文件或码流,赋值输入AVFormatContext结构体中的相关参数;

avformat_find_stream_info():获取输入文件的流信息;

av_read_frame():从输入AVFormatContext中读取数据包;

avformat_close_input():输入文件读取结束后,调用该函数关闭输入文件,释放AVFormatContext等相关结构体。

输出侧:

avformat_alloc_output_context2():通过输出文件名称创建输出的AVFormatContext;

avformat_new_stream():根据输入stream number创建相应的输出stream;

avio_open():打开输出文件IO;

avformat_write_header():写输出文件头信息;

av_interleaved_write_frame():向输出文件中写入数据包,如果包含视频、音频、字母等多个码流的数据包,则按照时间戳大小交织写入。

av_write_trailer():写输出文件尾信息,并释放私有数据。

avio_closep():关闭输出文件IO;

avformat_free_context():释放输出文件的AVFormatContext;

不多废话,上示例代码。

int main(int argc, char **argv)
{
    AVOutputFormat *ofmt = NULL;
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
    AVPacket pkt;
    const char *in_filename, *out_filename;
    int ret, i;
    int stream_index = 0;
    int *stream_mapping = NULL;
    int stream_mapping_size = 0;

    if (argc < 3) {
        printf("usage: %s input output\n"
               "API example program to remux a media file with libavformat and libavcodec.\n"
               "The output format is guessed according to the file extension.\n"
               "\n", argv[0]);
        return 1;
    }

    in_filename  = argv[1];   // 输入输出文件名通过命令行参数传入
    out_filename = argv[2];

    av_register_all();    //初始化libavformat并注册所有的muxers、demuxers和protocols。
    //打开输入文件并读取头信息
    if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
        fprintf(stderr, "Could not open input file '%s'", in_filename);
        goto end;
    }
    //读取输入文件的包数据来获取流信息
    if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
        fprintf(stderr, "Failed to retrieve input stream information");
        goto end;
    }
    //打印输入信息,可忽略
    av_dump_format(ifmt_ctx, 0, in_filename, 0);
    //为输出分配AVFormatContext
    avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);
    if (!ofmt_ctx) {
        fprintf(stderr, "Could not create output context\n");
        ret = AVERROR_UNKNOWN;
        goto end;
    }

    stream_mapping_size = ifmt_ctx->nb_streams;
    stream_mapping = av_mallocz_array(stream_mapping_size, sizeof(*stream_mapping));
    if (!stream_mapping) {
        ret = AVERROR(ENOMEM);
        goto end;
    }

    ofmt = ofmt_ctx->oformat;

    for (i = 0; i < ifmt_ctx->nb_streams; i++) {
        AVStream *out_stream;
        AVStream *in_stream = ifmt_ctx->streams[i];
        AVCodecParameters *in_codecpar = in_stream->codecpar;

        if (in_codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
            in_codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
            in_codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
            stream_mapping[i] = -1;
            continue;
        }

        stream_mapping[i] = stream_index++;
       // 分配一个新的输出流
        out_stream = avformat_new_stream(ofmt_ctx, NULL);
        if (!out_stream) {
            fprintf(stderr, "Failed allocating output stream\n");
            ret = AVERROR_UNKNOWN;
            goto end;
        }
        // 将当前输入流的参数拷贝到对应的输出流参数中
        ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);
        if (ret < 0) {
            fprintf(stderr, "Failed to copy codec parameters\n");
            goto end;
        }
        out_stream->codecpar->codec_tag = 0;
    }
    av_dump_format(ofmt_ctx, 0, out_filename, 1);  //打印输出文件信息,可忽略

    if (!(ofmt->flags & AVFMT_NOFILE)) {
        ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);   //打开输出文件并创建对应的AVIOContext
        if (ret < 0) {
            fprintf(stderr, "Could not open output file '%s'", out_filename);
            goto end;
        }
    }
   //打开输出文件后,分配输出文件的私有数据空间,并写入输出文件的头信息
    ret = avformat_write_header(ofmt_ctx, NULL);
    if (ret < 0) {
        fprintf(stderr, "Error occurred when opening output file\n");
        goto end;
    }
    //下面while循环就是不断地从输入文件中读取数据包,做相应的时间戳转换后,交织写入输出文件中
    while (1) {
        AVStream *in_stream, *out_stream;
        //从输入文件中读取一包数据,这里的一包,一般是一帧的压缩数据
        ret = av_read_frame(ifmt_ctx, &pkt);
        if (ret < 0)
            break;

        in_stream  = ifmt_ctx->streams[pkt.stream_index];
        if (pkt.stream_index >= stream_mapping_size ||
            stream_mapping[pkt.stream_index] < 0) {
            av_packet_unref(&pkt);
            continue;
        }

        pkt.stream_index = stream_mapping[pkt.stream_index];
        out_stream = ofmt_ctx->streams[pkt.stream_index];
        
        //对时间戳进行必要的处理
        /* copy packet */
        pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
        pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
        pkt.pos = -1;    // pos表示该packet在输出流中的位置,-1,表示unknown
        
        //将该packet按照DTS的先后顺序交织写入输出文件中
        ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
        if (ret < 0) {
            fprintf(stderr, "Error muxing packet\n");
            break;
        }
        av_packet_unref(&pkt);
    }
    // 写完packets之后,写入文件尾信息,并释放输出文件的私有数据
    av_write_trailer(ofmt_ctx);
end:
    //操作完成后,一定要调用该函数来关闭输入文件并释放AVFormatContext 
  avformat_close_input(&ifmt_ctx);
    /* close output */
    if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
        avio_closep(&ofmt_ctx->pb);   //关闭输出文件并释放由AVIOContext访问的资源
    avformat_free_context(ofmt_ctx);   //释放输出AVFormatContext,并释放所有的streams

    av_freep(&stream_mapping);

    if (ret < 0 && ret != AVERROR_EOF) {
        fprintf(stderr, "Error occurred: %s\n", av_err2str(ret));
        return 1;
    }

    return 0;
}