如何解决FFmpeg库开发中的废弃警告问题?
解决FFmpeg废弃API警告的方案
你遇到的废弃警告核心原因是使用了FFmpeg新版本中被标记为废弃的AVStream->codec字段——这个字段在FFmpeg 3.1及以后的版本里已经被官方弃用,取而代之的是通过AVStream->codecpar获取流编码参数,再手动创建并初始化AVCodecContext的方式。
下面是针对你代码的具体修改步骤和完整示例:
1. 替换废弃的流编码参数获取方式
原来的代码中直接访问pFormatCtx->streams[i]->codec来判断媒体类型和获取编码信息,现在需要改为从codecpar读取类型,再单独创建解码器上下文。
2. 修改后的完整代码片段
// 原有的avformat_find_stream_info调用可以保留,这部分目前还没被废弃 if (avformat_find_stream_info(pFormatCtx, NULL) < 0) { std::cout << "Get Stream Information Error 13" << std::endl; avformat_close_input(&pFormatCtx); pFormatCtx = NULL; return -13; } av_dump_format(pFormatCtx, 0, filenameSrc, 0); int video_stream_index = -1; AVCodecContext* pCodecCtx = nullptr; for (unsigned int i = 0; i < pFormatCtx->nb_streams; i++) { // 改用codecpar判断媒体类型 if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { video_stream_index = i; // 获取对应的解码器 const AVCodec* pCodec = avcodec_find_decoder(pFormatCtx->streams[i]->codecpar->codec_id); if (!pCodec) { std::cout << "Unsupported video codec!" << std::endl; avformat_close_input(&pFormatCtx); pFormatCtx = NULL; return -14; } // 创建解码器上下文 pCodecCtx = avcodec_alloc_context3(pCodec); if (!pCodecCtx) { std::cout << "Failed to allocate codec context!" << std::endl; avformat_close_input(&pFormatCtx); pFormatCtx = NULL; return -15; } // 将流的编码参数复制到解码器上下文 if (avcodec_parameters_to_context(pCodecCtx, pFormatCtx->streams[i]->codecpar) < 0) { std::cout << "Failed to copy codec parameters to context!" << std::endl; avcodec_free_context(&pCodecCtx); avformat_close_input(&pFormatCtx); pFormatCtx = NULL; return -16; } // 初始化解码器上下文 if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) { std::cout << "Failed to open codec!" << std::endl; avcodec_free_context(&pCodecCtx); avformat_close_input(&pFormatCtx); pFormatCtx = NULL; return -17; } break; } } // 后续使用pCodecCtx来处理解码,记得在最后释放资源 // ... // 资源释放示例(在程序结束或不再使用时) if (pCodecCtx) { avcodec_free_context(&pCodecCtx); } avformat_close_input(&pFormatCtx);
关键改动说明
- 用
AVStream->codecpar->codec_type替代AVStream->codec->coder_type判断媒体类型 - 不再直接使用旧的
codec上下文,而是手动创建AVCodecContext - 通过
avcodec_parameters_to_context将流的编码参数复制到新的解码器上下文 - 新增
avcodec_open2来初始化解码器,确保上下文可用
额外注意事项
- 一定要记得在使用完
AVCodecContext后调用avcodec_free_context释放内存,避免内存泄漏 - 如果你的项目中还有其他使用
AVCodecContext旧创建方式的代码,都需要按这个逻辑进行替换 - 建议同步查看你使用的FFmpeg版本的官方文档,确认API的兼容性
内容的提问来源于stack exchange,提问作者Trần Quốc Việt




