使用FFmpeg将H.264码流封装为MP4

一、调用流程

初始化FFmpeg库 创建输入/输出上下文 配置视频流参数 写入文件头 循环读取H.264数据包 时间戳处理与封装 资源释放


二、关键步骤详解

1. 初始化FFmpeg库
c 复制代码
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>

avformat_network_init();  // 若需网络功能(可选)
av_register_all();       // 旧版本需注册,新版本可省略
2. 创建输入/输出上下文
c 复制代码
// 打开H264裸流输入
AVFormatContext *in_fmt_ctx = NULL;
if (avformat_open_input(&in_fmt_ctx, "input.h264", NULL, NULL) != 0) {
    fprintf(stderr, "无法打开输入文件\n");
    return -1;
}
avformat_find_stream_info(in_fmt_ctx, NULL);  // 获取流信息

// 创建MP4输出上下文
AVFormatContext *out_fmt_ctx = NULL;
avformat_alloc_output_context2(&out_fmt_ctx, NULL, NULL, "output.mp4");
if (!out_fmt_ctx) {
    fprintf(stderr, "无法创建输出文件\n");
    return -1;
}

// 打开输出文件IO
if (!(out_fmt_ctx->oformat->flags & AVFMT_NOFILE)) {
    if (avio_open(&out_fmt_ctx->pb, "output.mp4", AVIO_FLAG_WRITE) < 0) {
        fprintf(stderr, "无法打开输出IO\n");
        return -1;
    }
}
3. 配置视频流参数
c 复制代码
// 从输入流复制编解码参数到输出流
AVStream *in_stream = in_fmt_ctx->streams[0];
AVStream *out_stream = avformat_new_stream(out_fmt_ctx, NULL);
avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);

// 设置时间基(关键!)
out_stream->time_base = (AVRational){1, 30};  // 假设帧率30fps
4. 写入文件头
c 复制代码
if (avformat_write_header(out_fmt_ctx, NULL) < 0) {
    fprintf(stderr, "写入文件头失败\n");
    return -1;
}
5. 数据包处理与封装
c 复制代码
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;

while (av_read_frame(in_fmt_ctx, &pkt) >= 0) {
    // 时间戳重计算(防止音画不同步)
    if (pkt.pts != AV_NOPTS_VALUE)
        pkt.pts = av_rescale_q(pkt.pts, in_stream->time_base, out_stream->time_base);
    if (pkt.dts != AV_NOPTS_VALUE)
        pkt.dts = av_rescale_q(pkt.dts, in_stream->time_base, out_stream->time_base);

    pkt.stream_index = out_stream->index;  // 更新流索引
    av_interleaved_write_frame(out_fmt_ctx, &pkt);  // 写入封装文件
    av_packet_unref(&pkt);
}
6. 收尾处理
c 复制代码
av_write_trailer(out_fmt_ctx);  // 写入文件尾

// 释放资源
avformat_close_input(&in_fmt_ctx);
if (out_fmt_ctx && !(out_fmt_ctx->oformat->flags & AVFMT_NOFILE))
    avio_closep(&out_fmt_ctx->pb);
avformat_free_context(out_fmt_ctx);

三、注意事项

  1. 时间戳同步

    • 必须通过av_rescale_q重计算时间戳,否则会导致播放速度异常或音画不同步。
    • 若输入流无时间戳,需手动生成递增的PTS/DTS。
  2. 编解码参数兼容性

    • MP4封装要求H.264流包含SPS/PPS信息(通常位于extradata中),若裸流缺失需手动插入。
  3. 封装失败 :检查输入是否为标准H.264 Annex B格式(起始码0x00000001),否则需通过h264_mp4toannexb过滤器转换。

  4. 性能优化

    • 使用av_interleaved_write_frame而非av_write_frame,确保数据包交错写入(避免音视频交错问题)。

    • 启用faststart标志可将MOOV原子移至文件头,便于网络播放:

      c 复制代码
      AVDictionary *options = NULL;
      av_dict_set(&options, "movflags", "faststart", 0);
      avformat_write_header(out_fmt_ctx, &options);
相关推荐
上海合宙LuatOS2 小时前
LuatOS核心库API——【audio 】
java·网络·单片机·嵌入式硬件·物联网·音视频·硬件工程
Android系统攻城狮3 小时前
Android16进阶之音频播放定位MediaPlayer.seekTo调用流程与实战(二百二十七)
音视频·mediaplayer·android16·音频进阶·音频性能实战
晚霞的不甘4 小时前
Flutter for OpenHarmony 可视化教学:A* 寻路算法的交互式演示
人工智能·算法·flutter·架构·开源·音视频
听麟5 小时前
HarmonyOS 6.0+ 跨端智慧政务服务平台开发实战:多端协同办理与电子证照管理落地
笔记·华为·wpf·音视频·harmonyos·政务
晚霞的不甘6 小时前
Flutter for OpenHarmony 实现计算几何:Graham Scan 凸包算法的可视化演示
人工智能·算法·flutter·架构·开源·音视频
零一iTEM6 小时前
MAX98357A_音频输出测试
单片机·嵌入式硬件·开源·音视频·硬件工程
Android系统攻城狮8 小时前
Android16进阶之获取播放位置MediaPlayer.getCurrentPosition调用流程与实战(二百二十八)
音视频·android16·音频进阶·音频性能实战
炼金术8 小时前
SkyPlayer v1.2.0 : AI 字幕-端侧 Whisper 实时语音识别实践
ffmpeg·openai
愚公搬代码9 小时前
【愚公系列】《AI短视频创作一本通》020-AI短视频创作实例精解(文旅宣传AI短视频实例精解)
人工智能·音视频
有位神秘人9 小时前
Android获取设备中本地音频
android·音视频