LibAV/FFmpeg如何正确调用get_device_list获取设备列表(调用崩溃无官方示例)
AVInputFormat::get_device_list 正确使用方法 常见崩溃核心原因
你之前写的代码触发崩溃,本质是遗漏了接口强制要求的初始化步骤、内存管理规则,并非接口本身存在缺陷。
标准实现流程
以下为Windows平台通过dshow枚举设备的可运行逻辑,其他平台仅需替换对应的输入格式名即可:
#include <libavformat/avformat.h> #include <libavdevice/avdevice.h> #include <QDebug> int main() { // 1. 全量注册采集设备(必做步骤) avdevice_register_all(); // 2. 定位目标输入格式,和你原有逻辑一致 AVInputFormat *dshow_input = av_find_input_format("dshow"); if (!dshow_input) { qDebug() << "未找到dshow输入格式"; return -1; } // 3. 初始化并绑定输入格式到AVFormatContext(你之前缺失的核心步骤) // 不能仅通过avformat_alloc_context分配裸上下文,必须通过avformat_open_input完成格式和上下文的绑定 AVFormatContext *fmt_ctx = avformat_alloc_context(); // 传空文件名,仅完成格式绑定,不实际打开设备流 int ret = avformat_open_input(&fmt_ctx, nullptr, dshow_input, nullptr); if (ret < 0) { qDebug() << "输入格式绑定失败,错误码:" << ret; avformat_free_context(fmt_ctx); return -1; } // 4. 初始化设备列表结构体,全内存清零 // 未清零的结构体内部指针为随机值,接口写入内存时会直接触发段错误 AVDeviceInfoList *device_list = av_mallocz(sizeof(AVDeviceInfoList)); // 5. 调用设备列表枚举接口 if (dshow_input->get_device_list) { ret = dshow_input->get_device_list(fmt_ctx, &device_list); if (ret < 0) { qDebug() << "设备枚举失败,错误码:" << ret; av_free(device_list); } else { // 此时读取nb_devices不会触发崩溃 qDebug() << "枚举到设备总数:" << device_list->nb_devices; // 遍历打印设备名称示例 for (int i = 0; i < device_list->nb_devices; i++) { qDebug() << "设备" << i << ":" << device_list->devices[i]->device_name; } } // 必须调用官方接口释放列表内存,手动free会造成二次释放 avdevice_free_list_devices(&device_list); } // 收尾释放上下文资源 avformat_close_input(&fmt_ctx); return 0; }
你原有代码的具体踩坑点
- 必须绑定输入格式:分配的AVFormatContext是完全裸的空结构,没有绑定dshow输入格式,接口内部读取上下文私有数据段时直接访问非法内存
- 必须做结构体内存清零:定义AVDeviceInfoList时没有对成员做清零初始化,结构体内部指针、计数值为随机内存值,接口写入时触发内存访问违规
- 必须走官方释放流程:遗漏了设备列表的官方释放流程,即使首次运行不崩溃,多次调用后也会因内存泄漏、内存损坏触发崩溃
跨平台注意事项
- 不同系统的枚举输入格式名存在差异:macOS用
avfoundation、Linux用video4linux2枚举摄像头、alsa枚举音频设备,不能硬编码dshow适配所有平台 - 接口返回的错误码可以通过
av_strerror转成可读字符串,快速定位权限不足、无匹配设备等问题 - 设备列表中的所有条目内存由FFmpeg托管,在调用
avdevice_free_list_devices完成释放前,不要手动操作列表内部的指针内存
内容的提问来源于stack exchange,提问作者FennecFix
相关产品推荐
相关产品推荐

