在 FFMPEG 中填充一个 BGR 帧数据

Fill a BGR Frame Data in FFMPEG

我正在关注 FFmpeg 视频编码示例 here,但它会生成一些虚拟的 YUV420P 帧,并且我已经从相机中捕获了 BGR 图像。

我不确定如何使用 frame->data[]frame->linesize[] 用我的 BGR 图像填充它们,所以我可以编码 H264 视频。


编辑:

在 Ronald 的回答后,我有以下代码(相机发送的每张新照片都会调用它):

    .............
    AVFrame *bgrFrame = av_frame_alloc();

    bgrFrame->width = originalBGRImage.cols;
    bgrFrame->height = originalBGRImage.rows;

    ret = av_image_alloc(bgrFrame->data, bgrFrame->linesize, bgrFrame->width, bgrFrame->height, AV_PIX_FMT_BGR24, 32);

    /////////////////////////////////////
    // This works and prevents memory leak....if I remove it, it consumes all the RAM....but I can't free this memory here, since I will use it later...
    av_freep(&bgrFrame->data[0]);
    av_frame_free(&bgrFrame);
    return;
    /////////////////////////////////////

    ret = av_image_fill_pointers(bgrFrame->data, AV_PIX_FMT_BGR24, bgrFrame->height, originalBGRImage.data, bgrFrame->linesize);

    /////////////////////////////////////
    // Here is where I am done using the memory so I will want to free it...but this same code crashes the program.
    av_freep(&bgrFrame->data[0]);
    av_frame_free(&bgrFrame);
    return;
    /////////////////////////////////////

因此,如果我删除代码末尾的 av_freep(&bgrFrame->data[0]);,我将出现内存泄漏...但将其留在那里会崩溃...那么释放已用内存的正确方法是什么?

使用av_image_fill_linesizes() to fill the linesizes (unless they're padded, in which case you should specify them manually), and after that use av_image_fill_pointers() to fill the data pointers. As pix_fmt, use AV_PIX_FMT_BGR24.

现在,这给了你一张 BGR24 图片。您可以使用 libx264rgb 编码器将其编码为 RGB H264 图像。如果你想编码 YUV H264,你首先需要将 RGB 图像转换为 YUV,你可以使用 libswscale 来完成。 Google "libswscale example" 以查找有关如何执行此操作的示例代码。