如何修改avformat_alloc_output_context2默认加载的音视频编码器为AAC和H264
FFmpeg FLV推流自定义音视频编码器解决方案
核心原理
avformat_alloc_output_context2 初始化时返回的 AVOutputFormat 中默认的音视频编码器仅为容器格式的推荐 fallback 值,不会强制绑定实际输出使用的编码,你可以在创建输出流时手动指定需要的编码器ID,不需要修改AVOutputFormat的内置字段。
实现步骤
- 初始化输出上下文,直接使用你原来的调用逻辑即可
AVFormatContext* _ctx = NULL; int ret = avformat_alloc_output_context2(&_ctx, NULL, "flv", "rtmp://192.168.1.7/live/surface"); if (ret < 0) { // 自行添加错误处理逻辑 }
- 添加H264视频流(直接拷贝输入流)
// 创建输出视频流 AVStream* out_vstream = avformat_new_stream(_ctx, NULL); // 假设in_vstream为输入文件的对应视频流 ret = avcodec_parameters_copy(out_vstream->codecpar, in_vstream->codecpar); if (ret < 0) { // 错误处理 } // 手动指定视频编码器为H264 out_vstream->codecpar->codec_id = AV_CODEC_ID_H264; // 设置codec_tag为0,让FFmpeg自动适配FLV容器的编码标签要求 out_vstream->codecpar->codec_tag = 0;
- 添加AAC音频流
// 创建输出音频流 AVStream* out_astream = avformat_new_stream(_ctx, NULL); // 查找AAC编码器 const AVCodec* aac_codec = avcodec_find_encoder(AV_CODEC_ID_AAC); AVCodecContext* aac_ctx = avcodec_alloc_context3(aac_codec); // 配置AAC编码参数,对应你命令行的配置 aac_ctx->sample_rate = 44100; aac_ctx->bit_rate = 160 * 1024; aac_ctx->channels = 2; aac_ctx->channel_layout = AV_CH_LAYOUT_STEREO; aac_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP; // FLV容器要求AAC使用浮点平面格式 aac_ctx->time_base = (AVRational){1, 44100}; // 打开编码器 ret = avcodec_open2(aac_ctx, aac_codec, NULL); if (ret < 0) { // 错误处理 } // 将编码器参数同步到输出流 ret = avcodec_parameters_from_context(out_astream->codecpar, aac_ctx); if (ret < 0) { // 错误处理 } out_astream->codecpar->codec_tag = 0;
- 配置FLV容器参数,对应命令行
-flvflags no_duration_filesize
av_opt_set(_ctx->priv_data, "flvflags", "no_duration_filesize", 0);
完成上述配置后,按照正常FFmpeg推流流程调用avio_open打开输出地址、avformat_write_header写文件头、循环写帧、最后写文件尾即可,输出的FLV流就会使用H264+AAC的编码组合。
内容的提问来源于stack exchange,提问作者mythili3093
相关产品推荐
相关产品推荐

