1 #include "audio_encoder.h"
4 #include <libavcodec/avcodec.h>
5 #include <libavformat/avformat.h>
6 #include <libavresample/avresample.h>
7 #include <libavutil/channel_layout.h>
8 #include <libavutil/frame.h>
9 #include <libavutil/rational.h>
10 #include <libavutil/samplefmt.h>
11 #include <libavutil/opt.h>
24 AudioEncoder::AudioEncoder(const string &codec_name, int bit_rate, const AVOutputFormat *oformat)
26 AVCodec *codec = avcodec_find_encoder_by_name(codec_name.c_str());
27 if (codec == nullptr) {
28 fprintf(stderr, "ERROR: Could not find codec '%s'\n", codec_name.c_str());
32 ctx = avcodec_alloc_context3(codec);
33 ctx->bit_rate = bit_rate;
34 ctx->sample_rate = OUTPUT_FREQUENCY;
35 ctx->sample_fmt = codec->sample_fmts[0];
37 ctx->channel_layout = AV_CH_LAYOUT_STEREO;
38 ctx->time_base = AVRational{1, TIMEBASE};
39 if (oformat->flags & AVFMT_GLOBALHEADER) {
40 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
42 if (avcodec_open2(ctx, codec, NULL) < 0) {
43 fprintf(stderr, "Could not open codec '%s'\n", codec_name.c_str());
47 resampler = avresample_alloc_context();
48 if (resampler == nullptr) {
49 fprintf(stderr, "Allocating resampler failed.\n");
53 av_opt_set_int(resampler, "in_channel_layout", AV_CH_LAYOUT_STEREO, 0);
54 av_opt_set_int(resampler, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
55 av_opt_set_int(resampler, "in_sample_rate", OUTPUT_FREQUENCY, 0);
56 av_opt_set_int(resampler, "out_sample_rate", OUTPUT_FREQUENCY, 0);
57 av_opt_set_int(resampler, "in_sample_fmt", AV_SAMPLE_FMT_FLT, 0);
58 av_opt_set_int(resampler, "out_sample_fmt", ctx->sample_fmt, 0);
60 if (avresample_open(resampler) < 0) {
61 fprintf(stderr, "Could not open resample context.\n");
65 audio_frame = av_frame_alloc();
68 AudioEncoder::~AudioEncoder()
70 av_frame_free(&audio_frame);
71 avresample_free(&resampler);
72 avcodec_free_context(&ctx);
75 void AudioEncoder::encode_audio(const vector<float> &audio, int64_t audio_pts)
77 if (ctx->frame_size == 0) {
78 // No queueing needed.
79 assert(audio_queue.empty());
80 assert(audio.size() % 2 == 0);
81 encode_audio_one_frame(&audio[0], audio.size() / 2, audio_pts);
85 int64_t sample_offset = audio_queue.size();
87 audio_queue.insert(audio_queue.end(), audio.begin(), audio.end());
90 sample_num + ctx->frame_size * 2 <= audio_queue.size();
91 sample_num += ctx->frame_size * 2) {
92 int64_t adjusted_audio_pts = audio_pts + (int64_t(sample_num) - sample_offset) * TIMEBASE / (OUTPUT_FREQUENCY * 2);
93 encode_audio_one_frame(&audio_queue[sample_num],
97 audio_queue.erase(audio_queue.begin(), audio_queue.begin() + sample_num);
99 last_pts = audio_pts + audio.size() * TIMEBASE / (OUTPUT_FREQUENCY * 2);
102 void AudioEncoder::encode_audio_one_frame(const float *audio, size_t num_samples, int64_t audio_pts)
104 audio_frame->pts = audio_pts;
105 audio_frame->nb_samples = num_samples;
106 audio_frame->channel_layout = AV_CH_LAYOUT_STEREO;
107 audio_frame->format = ctx->sample_fmt;
108 audio_frame->sample_rate = OUTPUT_FREQUENCY;
110 if (av_samples_alloc(audio_frame->data, nullptr, 2, num_samples, ctx->sample_fmt, 0) < 0) {
111 fprintf(stderr, "Could not allocate %ld samples.\n", num_samples);
115 if (avresample_convert(resampler, audio_frame->data, 0, num_samples,
116 (uint8_t **)&audio, 0, num_samples) < 0) {
117 fprintf(stderr, "Audio conversion failed.\n");
121 int err = avcodec_send_frame(ctx, audio_frame);
123 fprintf(stderr, "avcodec_send_frame() failed with error %d\n", err);
127 for ( ;; ) { // Termination condition within loop.
129 av_init_packet(&pkt);
132 int err = avcodec_receive_packet(ctx, &pkt);
134 pkt.stream_index = 1;
136 for (Mux *mux : muxes) {
137 mux->add_packet(pkt, pkt.pts, pkt.dts);
139 av_packet_unref(&pkt);
140 } else if (err == AVERROR(EAGAIN)) {
143 fprintf(stderr, "avcodec_receive_frame() failed with error %d\n", err);
148 av_freep(&audio_frame->data[0]);
149 av_frame_unref(audio_frame);
152 void AudioEncoder::encode_last_audio()
154 if (!audio_queue.empty()) {
155 // Last frame can be whatever size we want.
156 assert(audio_queue.size() % 2 == 0);
157 encode_audio_one_frame(&audio_queue[0], audio_queue.size() / 2, last_pts);
161 if (ctx->codec->capabilities & AV_CODEC_CAP_DELAY) {
162 // Collect any delayed frames.
165 av_init_packet(&pkt);
168 int err = avcodec_receive_packet(ctx, &pkt);
170 pkt.stream_index = 1;
172 for (Mux *mux : muxes) {
173 mux->add_packet(pkt, pkt.pts, pkt.dts);
175 av_packet_unref(&pkt);
176 } else if (err == AVERROR_EOF) {
179 fprintf(stderr, "avcodec_receive_frame() failed with error %d\n", err);
186 AVCodecParametersWithDeleter AudioEncoder::get_codec_parameters()
188 AVCodecParameters *codecpar = avcodec_parameters_alloc();
189 avcodec_parameters_from_context(codecpar, ctx);
190 return AVCodecParametersWithDeleter(codecpar, avcodec_parameters_free_unique);