欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AVFrame 的两种手动分配内部buf和data的方式

程序员文章站 2022-03-04 23:41:53
...

用ffmpeg的时候我们有时候需要手动为AVFrame分配内存数据,目前有两种方式,
第一种:

AVFrame *m_yuvFrame{nullptr};
uint8_t *m_outbuf{nullptr};
int m_outbuffSize{0};
m_yuvFrame = av_frame_alloc();

 // allocate buffer to store decoded frame
    AVPixelFormat av_fmt = AV_PIX_FMT_YUV420P;
    m_outbuffSize = av_image_get_buffer_size(av_fmt, width, height, 1);
    m_outbuf = static_cast<unsigned char *>(av_malloc(size_t(m_outbuffSize)));
    if (m_outbuf == nullptr) {
      LOG_ERROR("allocate buffer failed! image w:{}, h:{}", width, height);
      break;
    }

    av_image_fill_arrays(m_yuvFrame->data, m_yuvFrame->linesize, m_outbuf,
                         av_fmt, width, height, 1);

.....

  if (m_yuvFrame) {
    av_frame_unref(m_yuvFrame);
    av_frame_free(&m_yuvFrame);
    m_yuvFrame = nullptr;
  }
  
  if (m_outbuf) {
    av_free(m_outbuf);
    m_outbuf = nullptr;
  }

按照上述方式就可以将内存分配了,可以看到三个关键点:像素格式,宽和高。

第二种方式简单一点:

AVFrame *m_inFrame{nullptr};
 m_inFrame = av_frame_alloc();

  m_inFrame->width = w;
    m_inFrame->height = h;
    m_inFrame->format = AV_PIX_FMT_YUV420P;
    if (av_frame_get_buffer(m_inFrame, 0) < 0 ||
        av_frame_make_writable(m_inFrame) < 0)
      return false;

....
  if (m_inFrame) {
    av_frame_free(&m_inFrame);
    m_frame = nullptr;
  }