FFmpeg无法获取AVFormatContext及avformat_open_input返回-12错误求助
FFmpeg调试问题排查修复方案
错误码-12/12含义说明
你遇到的AVERROR(EONEM)是笔误,实际为AVERROR(ENOMEM),对应错误码-12,含义为内存分配失败,如果打印时类型处理不当会显示为正数12。
逐问题修复
1. AVFormatContext初始化错误修复
你的代码存在两处核心逻辑错误:
- 仅声明了
avformat_alloc_context()函数,没有实际调用执行分配操作,av_format_ctx全程为NULL - 状态判断逻辑写反:
!av_format_ctx代表指针为空、分配失败,你的日志输出逻辑完全颠倒
可选两种初始化方案:
- 手动分配:调用
av_format_ctx = avformat_alloc_context();,分配后先判断指针非空再执行后续操作 - 自动分配:直接给
avformat_open_input传入NULL的av_format_ctx指针,函数会自动完成上下文分配操作
2. av_strerror未定义报错修复
该函数定义在libavutil/error.h头文件中,你没有引入该头文件,添加如下引入即可:
#include "libavutil/error.h"
使用示例:
char err_buf[AV_ERROR_MAX_STRING_SIZE] = {0}; int ret = avformat_open_input(&av_format_ctx, myFile.c_str(), NULL, NULL); if (ret != 0) { av_strerror(ret, err_buf, sizeof(err_buf)); std::cout << "打开文件失败,错误信息:" << err_buf << std::endl; }
3. 其他代码问题修复
- 补充C++标准库头文件:
<iostream>、<string>,cout和string属于std命名空间,需要加std::前缀或者添加using namespace std;声明 - 文件路径直接传递
std::string的c_str()返回值即可,不需要手动转char数组,写法更安全 - 不要在错误分支中重复调用
avformat_open_input,会导致资源重复分配、内存泄漏问题
修复后代码示例
#include <iostream> #include <string> #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "libavutil/error.h" int main() { std::string myFile = "C:/Users/Username/Downloads/Video/QGRAPHICS.mp4"; AVFormatContext *av_format_ctx = NULL; // 打开输入文件,自动分配AVFormatContext char err_buf[AV_ERROR_MAX_STRING_SIZE] = {0}; int ret = avformat_open_input(&av_format_ctx, myFile.c_str(), NULL, NULL); if (ret != 0) { av_strerror(ret, err_buf, sizeof(err_buf)); std::cout << "打开文件失败,错误码:" << ret << ",错误信息:" << err_buf << std::endl; return -1; } std::cout << "文件打开成功" << std::endl; // 后续处理逻辑... // 释放资源 avformat_close_input(&av_format_ctx); avformat_free_context(av_format_ctx); return 0; }
内容的提问来源于stack exchange,提问作者Bakh
相关产品推荐
相关产品推荐

