使用 libavcodec 编码视频时比特率极高

nic*_*are 7 ffmpeg libavcodec libav libavformat

我正在尝试捕获相机输出并使用 libavcodec 制作视频。作为如何完成此操作的示例,我使用了ffmpeg muxing 示例

问题是 4 秒视频的大小为 ~15mb,比特率为 ~30000 kb/s,尽管我已将 AVCodecContext 上的比特率设置为 400000(我认为该值以比特/秒为单位,而不是 kb/s) .

我还尝试从命令行使用 ffmpeg 录制视频,它的比特率约为 700 kb/s。

有人知道为什么不保留比特率从而导致生成的文件非常大吗?我用来初始化编解码器上下文的代码如下:

初始化部分:

avformat_alloc_output_context2(&m_formatContext, NULL, NULL, filename);
outputFormat = m_formatContext->oformat;

codec = avcodec_find_encoder(outputFormat->video_codec);

m_videoStream = avformat_new_stream(m_formatContext, codec);

m_videoStream->id = m_formatContext->nb_streams - 1;

codecContext = m_videoStream->codec;

codecContext->codec_id = outputFormat->video_codec;

codecContext->width = m_videoResolution.width();
codecContext->height = m_videoResolution.height();

int m_bitRate = 400000;
codecContext->bit_rate = m_bitRate;
codecContext->rc_min_rate = m_bitRate;
codecContext->rc_max_rate = m_bitRate;
codecContext->bit_rate_tolerance = 0;

codecContext->time_base.den = 20;
codecContext->time_base.num = 1;

codecContext->pix_fmt = AV_PIX_FMT_YUV422P;

if (m_formatContext->oformat->flags & AVFMT_GLOBALHEADER)
    codecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
/* open it */
ret = avcodec_open2(codecContext, codec, NULL);

avFrame = avcodec_alloc_frame();

ret = avpicture_alloc(&avPicture, codecContext->pix_fmt, codecContext->width, codecContext->height);

*((AVPicture *)avFrame) = avPicture;

av_dump_format(m_formatContext, 0, filename, 1);

if (!(outputFormat->flags & AVFMT_NOFILE)) {
    ret = avio_open(&m_formatContext->pb, filename, AVIO_FLAG_WRITE);
}

ret = avformat_write_header(m_formatContext, NULL);

if (avFrame)
    avFrame->pts = 0;
Run Code Online (Sandbox Code Playgroud)

UmN*_*obe 2

因为每个编码器都有自己的配置文件,您提供的比特率只是一个提示。如果您的比特率是有效值(不太小也不太大),编解码器将在其配置文件列表中选择支持的比特率。

编解码器“功能”也可能影响比特率,但据我所知。

编解码器配置文件定义至少以下之间的相关性:

  • 框架尺寸(宽度、高度)
  • 比特率
  • 像素格式
  • 帧率

我仍然在努力寻找一种使用 api 从编解码器获取比特率的方法,但您可以通过在打开编解码器之前提供非常低的比特率来找出其配置文件。

与代码

codecContext->bit_rate = 1;
avcodec_open2(codecContext, codec, NULL);
Run Code Online (Sandbox Code Playgroud)

FFmpeg 编解码器将记录投诉和上面列出的可接受元组的列表

注意:仅尝试使用不需要外部库的编解码器