Search code examples
c++ffmpegwebmvp8

How to pass VP8 encoder option programmatically in ffmpeg based program


I am building a program using ffmpeg libraries based on the standard ffmpeg transcoder example. My aim is to build video transcoder which encodes any suitable video (i.e. which ffmpeg can read) into WEBM format. The question is how do I pass options to VP8 encoder to control output video quality and other parameters? I mean passing these option via C++ code.


Solution

  • Use the following code:

    AVDictionary *options = NULL;
    AVCodec *codec = avcodec_find_encoder(AVCODEC_ID_VP8);
    AVCodecContext *ctx = avcodec_alloc_context3(codec);
    
    av_dict_set(&options, "option", "value", 0);
    
    int res = avcodec_open2(ctx, codec, &options);
    if (res < 0)
        error();
    
    while (..) {
        res = avcodec_encode_video2(ctx, ..);
        if (res < 0)
            error();
    }
    
    avcodec_close(ctx);
    avcodec_free_context(ctx);
    

    The relevant "option"/"value" pairs are whatever you would get from the vp8 encoding guides from e.g. the FFmpeg wiki. For example, to set a bitrate of 1 mbps (first example in wiki), use:

    av_dict_set_int(&options, "b", 1024 * 1024, 0);
    

    or

    av_dict_set(&options, "b", "1M", 0);
    

    I recommend to use VP9 instead of VP8, you won't get great quality with VP8, but that's obviously your choice.