上一篇文章给出了将flv文件解复用的解决方案:
从flv文件中提取h264码流(使用av_bsf_send_packet和av_bsf_receive_packet)
这篇文章给出复用mp4文件的解决方案,源代码还是参考了雷神的demo:
最简单的基于FFmpeg的封装格式处理:视音频复用器(muxer)
自己对代码逻辑进行了梳理和注释,对于一些看不懂的逻辑和觉得没必要的逻辑进行了优化,大家可以参考一下。注意这里使用的aac音频是adts封装形式的,h264视频流是annexb封装形式的,也就是说可以直接用ffplay播放的,怎么得到这两种形式文件的可以参照上一篇文章。
下面直接给出源代码:
#include <stdio.h>
#include <libavformat/avformat.h>
int main() {
AVFormatContext *ifmt_ctx_v = NULL, *ifmt_ctx_a = NULL, *ofmt_ctx = NULL;
AVOutputFormat *ofmt = NULL;
AVPacket pkt;
int ret, i;
int videoindex_v = -1, videoindex_out = -1; // 表示输入/输出video流的index
int audioindex_a = -1, audioindex_out = -1; // 表示输入/输出audio流的index
int64_t cur_pts_v = 0, cur_pts_a = 0;
int frame_index = 0;
const char *in_filename_v = "muxer.h264";
const char *in_filename_a = "muxer.aac";
const char *out_filename = "muxer.mp4";
// 打开输入文件,读取信息
if ((ret = avformat_open_input(&ifmt_ctx_v, in_filename_v, 0, 0)) < 0) {
printf("Could not open input file!\n");
goto END;
}
if ((ret = avformat_find_stream_info(ifmt_ctx_v, 0)) < 0) {
printf( "Failed to retrieve input stream information");
goto END;
}
if ((ret = avformat_open_input(&ifmt_ctx_a, in_filename_a, 0, 0)) < 0) {
printf( "Could not open input file.");
goto END;
}
if