[FFmpeg-user] How to set X264 options using FFmpeg libraries

Zach Jacobs zachjacobs at gmail.com
Thu Jul 25 21:43:12 CEST 2013


Hello,

I am trying to control the bit rate of a file using x264 with the crf and
maximum bit rate parameters.  I am following the x264 encoding guide
here<https://trac.ffmpeg.org/wiki/x264EncodingGuide#CRFwithmaximumbitrate>.
 I tried the following from the command line:

ffmpeg -i input.m4v -c:v libx264 -crf 20 -maxrate 400k -bufsize 1835k
output.ts

This works very well and the resulting bit rate is usually very close to
400k.  However when I try to do the same thing by using the FFmpeg
libraries, the encoder seems to ignore the maxrate parameter.  Here is how
I am setting up my CodecContext:

                AVDictionary* opt = null;
                FFmpegInvoke.av_dict_set(&opt, "preset", "slow", 0);
                FFmpegInvoke.av_dict_set(&opt, "crf", "20.0", 0);
                FFmpegInvoke.av_dict_set(&opt, "maxrate", "400k", 0);
                FFmpegInvoke.av_dict_set(&opt, "bufsize", "1835k", 0);

                videoCodec =
FFmpegInvoke.avcodec_find_encoder(AVCodecID.AV_CODEC_ID_H264);

                if (videoCodec == null)
                    throw new Exception("FFMPEG Encoder Error: Codec Not
Found");

                videoCodecContext =
FFmpegInvoke.avcodec_alloc_context3(videoCodec);
                videoCodecContext->width = encoderInfo.Settings.VideoWidth;
                videoCodecContext->height =
encoderInfo.Settings.VideoHeight;

                videoCodecContext->pix_fmt =
AVPixelFormat.AV_PIX_FMT_YUV420P;
                videoCodecContext->time_base.num = 1;
                videoCodecContext->time_base.den = 1000;

                videoCodecContext->codec_type =
AVMediaType.AVMEDIA_TYPE_VIDEO;
                videoCodecContext->codec_id = AVCodecID.AV_CODEC_ID_H264;

                if (codecFlags != -1)
                    videoCodecContext->flags |= codecFlags;

                if (FFmpegInvoke.avcodec_open2(videoCodecContext,
videoCodec, &opt) < 0)
                    throw new Exception("FFmpeg Encoder Error: could not
open video codec");

opt is empty after avcodec_open2 is called indicating all of my dictionary
options that I tried to set were found and processed.  However, the output
video bit rate is no where near 400k maxrate that I specified.  If I
increase maxrate, the bit rate increases but it still isn't anywhere close
to what it should be.  The output file is roughly 319 MB.

>From the command line, the video bit rate is 395k and the resulting video
size is only 42MB.  Am I missing a setting?

Thanks for your time!

Zach


More information about the ffmpeg-user mailing list