Last active
May 12, 2017 14:46
-
-
Save mondain/acbec32fb1d120b7da1b393bfca8180b to your computer and use it in GitHub Desktop.
ffmpeg and the libopus encoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
av_register_all(); // Initialize libavformat and register all the muxers, demuxers and protocols (but not the codecs) | |
avcodec_register_all(); // Register the codec and initialize libavcodec | |
SwrContext *swr; | |
AVCodec *codec; | |
AVCodecContext *context; | |
// get the libopus codec encoder | |
codec = avcodec_find_encoder_by_name("libopus"); | |
if (codec) { | |
swr = swr_alloc_set_opts(NULL, // we're allocating a new context | |
AV_CH_LAYOUT_STEREO, // out_ch_layout | |
AV_SAMPLE_FMT_FLTP, // out_sample_fmt | |
48000, // out_sample_rate | |
AV_CH_LAYOUT_MONO, // in_ch_layout | |
AV_SAMPLE_FMT_S16, // in_sample_fmt | |
48000, // in_sample_rate | |
0, // log_offset | |
NULL); // log_ctx | |
int results = swr_init(swr); | |
AVDictionary *opts = NULL; | |
av_dict_set(&opts, "strict", "experimental", 0); | |
// Use variable bitrate encoding (default) | |
//av_dict_set(&opts, "vbr", NULL, 0); | |
// Target bitrate in kbit/sec (6-256/channel) | |
//av_dict_set(&opts, "bitrate", (br / 1000), 0); | |
// Encoding complexity (0-10, default: 10 (slowest)) | |
av_dict_set(&opts, "comp", "10", 0); | |
// Maximum frame size in milliseconds (2.5, 5, 10, 20, 40, 60, default: 20) | |
av_dict_set(&opts, "framesize", "20", 0); | |
// Percentage packet loss to expect (default: 0) | |
av_dict_set(&opts, "expect-loss", "0", 0); | |
// Downmix to stereo (if >2 channels) | |
//av_dict_set(&opts, "downmix-stereo", NULL, 0); | |
// Maximum container delay in milliseconds (0-1000, default: 1000) | |
av_dict_set(&opts, "max-delay", "1000", 0); | |
context = avcodec_alloc_context3(codec); | |
if (context) { | |
//memset(context, 0, sizeof(context)); | |
context->sample_rate = 48000; | |
context->time_base.den = 48000; | |
context->time_base.num = 1; | |
context->channels = 2; | |
context->channel_layout = AV_CH_LAYOUT_STEREO; | |
context->sample_fmt = AV_SAMPLE_FMT_FLTP; | |
context->bit_rate = 32000; | |
} | |
// this fails just a quickly as without opts | |
//results = avcodec_open2(context, codec, &opts); | |
results = avcodec_open2(context, codec, 0); | |
if (results < 0) { | |
printf("codec not opened: %d\n", results); | |
} else { | |
if (context->codec != 0) { | |
printf("codec opened\n"); | |
} else { | |
printf("setting codec\n"); | |
context->codec=codec; | |
} | |
} | |
} else { | |
fprintf(stderr, "Could not find an Opus encoder\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment