You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用libavcodec编码H264时avcodec_open2返回-22无效参数问题

Libavcodec H264编码avcodec_open2返回错误码-22的问题排查

你遇到的错误码-22(Invalid argument)是编码器参数冲突导致的,以下是具体问题和修正方案:

核心错误:Baseline Profile与B帧不兼容

你在代码中设置H264编码为baseline profile,同时配置了max_b_frames = 1。根据H264标准,Baseline Profile不支持B帧(双向预测帧),这直接触发编码器参数验证失败,返回无效参数错误。

冗余设置建议移除

codecContext->codec_type = AVMEDIA_TYPE_VIDEO属于冗余操作:调用avcodec_alloc_context3(codec)时,函数会根据传入的编码器自动初始化codec_type字段,手动设置无必要,建议移除。

修正后的代码片段

针对Baseline Profile的修正

/* put sample parameters */
codecContext->bit_rate = 400000;
codecContext->width = 1920;
codecContext->height = 1080;
codecContext->time_base = { 1, 25 };
codecContext->framerate = { 25, 1 };

codecContext->gop_size = 10;
// Baseline Profile不支持B帧,设置为0
codecContext->max_b_frames = 0;
codecContext->pix_fmt = AV_PIX_FMT_YUV420P;

if (codec->id == AV_CODEC_ID_H264)
    av_opt_set(codecContext->priv_data, "profile", "baseline", 0);

如果需要使用B帧

可改用支持B帧的Profile(如Main或High):

if (codec->id == AV_CODEC_ID_H264)
    // 改用Main Profile支持B帧
    av_opt_set(codecContext->priv_data, "profile", "main", 0);
// max_b_frames = 1 可以保留

额外排查点

  • 确认你的FFmpeg/libav库已编译H264编码器(如x264):部分系统预装库默认不包含H264编码支持,可通过打印编码器名称验证:
    fprintf(stdout, "Using encoder: %s\n", codec->name);
    
  • 确保分辨率为偶数:你的代码中1920x1080已满足要求,但后续修改分辨率时需注意,H264要求宽高必须为偶数。

内容的提问来源于stack exchange,提问作者Fries of Doom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 21:12:44