OpenCV Mat to ffmpeg AVPicture 转换内存泄漏

OpenCV Mat to ffmpeg AVPicture conversion memory leak

我有下一个代码:

void matToAvPicture(cv::Mat frame, AVPicture *picture)
{
    cv::resize(frame, frame, cv::Size(m_streamWidth, m_streamHeight));
    uint8_t* buf = (uint8_t*)malloc(avpicture_get_size(AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight)); // 3 bytes per pixel
    for(int i = 0; i < m_streamHeight; i++)
    {
        memcpy(&(buf[i * m_streamWidth * 3]), &(frame.data[i * frame.step]), m_streamWidth * 3);
    }
    AVPicture bgrPicture;
    avpicture_alloc(&bgrPicture, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);
    avpicture_fill(&bgrPicture, buf, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);
    sws_scale(rgbToYuvContext, (const uint8_t * const *)bgrPicture.data, bgrPicture.linesize, 0, m_streamHeight, picture->data, picture->linesize);
    avpicture_free(&bgrPicture);
//    free(buf);
}

但是 avpicture_free(&bgrPicture) 的调用并没有完全释放内存。如果我注释行 avpicture_fill(&bgrPicture, buf, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight); 而未注释行
free(buf)
不会出现内存泄漏。 有什么问题?

uint8_t* buf = (uint8_t*)malloc(avpicture_get_size(AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight)); // 3 bytes per pixel
avpicture_alloc(&bgrPicture, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);
avpicture_fill(&bgrPicture, buf, AV_PIX_FMT_BGR24, m_streamWidth, m_streamHeight);

那是做同样的事情两次。 avpicture_alloc allocates and fills the data array in a picture with a self-allocated buffer (free'ed with avpicture_free), and avpicture_fill fills the data structure with some buffer that you control yourself (in your case: malloc/free manually). Use either malloc+avpicture_fill+free, or use avpicture_alloc+avpicture_free。不要同时使用两者。