使用libav/FFmpeg将RGB8转为NV12时sws_scale报读取访问错误
问题排查与修复
核心错误点
sws_scale第二参数传入格式错误:该参数要求传入存储各个输入平面指针的数组,你直接将单指针rgb_in强转为二级指针,接口会把rgb_in指向的像素数据内容当做内存地址读取,直接触发读访问违规。- 输入像素格式不匹配:你配置的输入行宽为
3 * width,对应每个像素占3字节的RGB24格式,代码中传入的AV_PIX_FMT_RGB8是单字节调色板格式,格式不匹配会导致内存访问越界。 - 函数参数遗漏类型定义:
width和height未声明类型,编译阶段会产生警告。
修正后完整代码
void convertRGB2NV12(unsigned char *rgb_in, int width, int height) { struct SwsContext* sws_context = nullptr; const int in_linesize[1] = {3 * width}; // RGB24 行步长 int out_linesize[2] = {width, width}; // NV12 行步长 uint8_t* out_planes[2]; out_planes[0] = new uint8_t[width * height]; out_planes[1] = new uint8_t[width * height / 2]; // 构造输入平面指针数组 const uint8_t* in_planes[1] = {rgb_in}; // 修正输入像素格式为RGB24,指定缩放算法为双线性插值 sws_context = sws_getCachedContext(sws_context, width, height, AV_PIX_FMT_RGB24, width, height, AV_PIX_FMT_NV12, SWS_BILINEAR, nullptr, nullptr, nullptr); // 传入合法的输入平面数组 sws_scale(sws_context, in_planes, in_linesize, 0, height, out_planes, out_linesize); // 此处填写后续业务逻辑 // 释放资源避免泄漏 sws_freeContext(sws_context); delete[] out_planes[0]; delete[] out_planes[1]; }
内容的提问来源于stack exchange,提问作者Xavi
相关产品推荐
相关产品推荐

