Windows下FFmpeg C API创建AV_CODEC_ID_H264编码器崩溃问题
解决FFmpeg H264编码器初始化崩溃及h264_mf错误问题
你的问题核心是FFmpeg默认选中了Windows Media Foundation(h264_mf)的H264编码器,该编码器对部分参数(比如你设置的180000分母的time_base、2560x1440分辨率)兼容性不佳,导致初始化失败甚至崩溃。结合你的环境,给出以下解决步骤:
强制使用libx264编码器
avcodec_find_encoder(AV_CODEC_ID_H264)会优先返回系统中可用的H264编码器,Windows环境下可能默认选h264_mf。直接指定libx264可绕开这个问题,修改编码器查找逻辑:auto codec = avcodec_find_encoder_by_name("libx264");确认vcpkg安装的FFmpeg包含libx264
默认vcpkg安装的FFmpeg可能不带libx264,需要重新安装带该组件的版本:vcpkg install ffmpeg[libx264]:x64-windows补充必要的编码器参数
部分编码器需要基础参数才能正常初始化,在打开编码器前补充以下配置(可选但推荐):codec_ctx->bit_rate = 10000000; // 根据需求调整码率 codec_ctx->gop_size = 25; // 每25帧生成一个关键帧 codec_ctx->max_b_frames = 3; codec_ctx->profile = FF_PROFILE_H264_MAIN;添加错误检查
给avcodec_open2添加返回值检查,方便定位后续问题:int ret = avcodec_open2(codec_ctx, codec, NULL); if (ret < 0) { char err_buf[AV_ERROR_MAX_STRING_SIZE]; av_strerror(ret, err_buf, AV_ERROR_MAX_STRING_SIZE); fprintf(stderr, "Failed to open encoder: %s\n", err_buf); return ret; }
修改后的完整代码:
extern "C" { #include <libavcodec/avcodec.h> #include <libavutil/error.h> #include <stdio.h> } int main() { // 强制使用libx264编码器 auto codec = avcodec_find_encoder_by_name("libx264"); if (!codec) { fprintf(stderr, "libx264 encoder not found\n"); return -1; } auto codec_ctx = avcodec_alloc_context3(codec); if (!codec_ctx) { fprintf(stderr, "Failed to allocate codec context\n"); return -1; } codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; codec_ctx->width = 2560; codec_ctx->height = 1440; codec_ctx->time_base.num = 1; codec_ctx->time_base.den = 180000; // 补充必要参数 codec_ctx->bit_rate = 10000000; codec_ctx->gop_size = 25; codec_ctx->max_b_frames = 3; codec_ctx->profile = FF_PROFILE_H264_MAIN; int ret = avcodec_open2(codec_ctx, codec, NULL); if (ret < 0) { char err_buf[AV_ERROR_MAX_STRING_SIZE]; av_strerror(ret, err_buf, AV_ERROR_MAX_STRING_SIZE); fprintf(stderr, "Failed to open encoder: %s\n", err_buf); avcodec_free_context(&codec_ctx); return ret; } fprintf(stdout, "Encoder opened successfully\n"); // 资源清理 avcodec_free_context(&codec_ctx); return 0; }
如果仍有问题,可以尝试降低time_base的分母(比如改为30或60),h264_mf对极高帧率的time_base支持确实有限,但使用libx264基本不会出现这类问题。
内容的提问来源于stack exchange,提问作者Guanyuming He
相关产品推荐
相关产品推荐

