]> git.sesse.net Git - nageru/blob - audio_encoder.cpp
2b735e4d44f5ff27b95588032fd3e73459ff7e64
[nageru] / audio_encoder.cpp
1 #include "audio_encoder.h"
2
3 extern "C" {
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>
12 }
13
14 #include <assert.h>
15
16 #include <string>
17 #include <vector>
18
19 #include "defs.h"
20 #include "timebase.h"
21
22 using namespace std;
23
24 AudioEncoder::AudioEncoder(const string &codec_name, int bit_rate)
25 {
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());
29                 exit(1);
30         }
31
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];
36         ctx->channels = 2;
37         ctx->channel_layout = AV_CH_LAYOUT_STEREO;
38         ctx->time_base = AVRational{1, TIMEBASE};
39         ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
40         if (avcodec_open2(ctx, codec, NULL) < 0) {
41                 fprintf(stderr, "Could not open codec '%s'\n", codec_name.c_str());
42                 exit(1);
43         }
44
45         resampler = avresample_alloc_context();
46         if (resampler == nullptr) {
47                 fprintf(stderr, "Allocating resampler failed.\n");
48                 exit(1);
49         }
50
51         av_opt_set_int(resampler, "in_channel_layout",  AV_CH_LAYOUT_STEREO,       0);
52         av_opt_set_int(resampler, "out_channel_layout", AV_CH_LAYOUT_STEREO,       0);
53         av_opt_set_int(resampler, "in_sample_rate",     OUTPUT_FREQUENCY,          0);
54         av_opt_set_int(resampler, "out_sample_rate",    OUTPUT_FREQUENCY,          0);
55         av_opt_set_int(resampler, "in_sample_fmt",      AV_SAMPLE_FMT_FLT,         0);
56         av_opt_set_int(resampler, "out_sample_fmt",     ctx->sample_fmt, 0);
57
58         if (avresample_open(resampler) < 0) {
59                 fprintf(stderr, "Could not open resample context.\n");
60                 exit(1);
61         }
62
63         audio_frame = av_frame_alloc();
64 }
65
66 AudioEncoder::~AudioEncoder()
67 {
68         av_frame_free(&audio_frame);
69         avresample_free(&resampler);
70         avcodec_free_context(&ctx);
71 }
72
73 void AudioEncoder::encode_audio(const vector<float> &audio, int64_t audio_pts)
74 {
75         if (ctx->frame_size == 0) {
76                 // No queueing needed.
77                 assert(audio_queue.empty());
78                 assert(audio.size() % 2 == 0);
79                 encode_audio_one_frame(&audio[0], audio.size() / 2, audio_pts);
80                 return;
81         }
82
83         int64_t sample_offset = audio_queue.size();
84
85         audio_queue.insert(audio_queue.end(), audio.begin(), audio.end());
86         size_t sample_num;
87         for (sample_num = 0;
88              sample_num + ctx->frame_size * 2 <= audio_queue.size();
89              sample_num += ctx->frame_size * 2) {
90                 int64_t adjusted_audio_pts = audio_pts + (int64_t(sample_num) - sample_offset) * TIMEBASE / (OUTPUT_FREQUENCY * 2);
91                 encode_audio_one_frame(&audio_queue[sample_num],
92                                        ctx->frame_size,
93                                        adjusted_audio_pts);
94         }
95         audio_queue.erase(audio_queue.begin(), audio_queue.begin() + sample_num);
96
97         last_pts = audio_pts + audio.size() * TIMEBASE / (OUTPUT_FREQUENCY * 2);
98 }
99
100 void AudioEncoder::encode_audio_one_frame(const float *audio, size_t num_samples, int64_t audio_pts)
101 {
102         audio_frame->pts = audio_pts;
103         audio_frame->nb_samples = num_samples;
104         audio_frame->channel_layout = AV_CH_LAYOUT_STEREO;
105         audio_frame->format = ctx->sample_fmt;
106         audio_frame->sample_rate = OUTPUT_FREQUENCY;
107
108         if (av_samples_alloc(audio_frame->data, nullptr, 2, num_samples, ctx->sample_fmt, 0) < 0) {
109                 fprintf(stderr, "Could not allocate %ld samples.\n", num_samples);
110                 exit(1);
111         }
112
113         if (avresample_convert(resampler, audio_frame->data, 0, num_samples,
114                                (uint8_t **)&audio, 0, num_samples) < 0) {
115                 fprintf(stderr, "Audio conversion failed.\n");
116                 exit(1);
117         }
118
119         AVPacket pkt;
120         av_init_packet(&pkt);
121         pkt.data = nullptr;
122         pkt.size = 0;
123         int got_output = 0;
124         avcodec_encode_audio2(ctx, &pkt, audio_frame, &got_output);
125         if (got_output) {
126                 pkt.stream_index = 1;
127                 pkt.flags = 0;
128                 for (Mux *mux : muxes) {
129                         mux->add_packet(pkt, pkt.pts, pkt.dts);
130                 }
131         }
132
133         av_freep(&audio_frame->data[0]);
134
135         av_frame_unref(audio_frame);
136         av_free_packet(&pkt);
137 }
138
139 void AudioEncoder::encode_last_audio()
140 {
141         if (!audio_queue.empty()) {
142                 // Last frame can be whatever size we want.
143                 assert(audio_queue.size() % 2 == 0);
144                 encode_audio_one_frame(&audio_queue[0], audio_queue.size() / 2, last_pts);
145                 audio_queue.clear();
146         }
147
148         if (ctx->codec->capabilities & AV_CODEC_CAP_DELAY) {
149                 // Collect any delayed frames.
150                 for ( ;; ) {
151                         int got_output = 0;
152                         AVPacket pkt;
153                         av_init_packet(&pkt);
154                         pkt.data = nullptr;
155                         pkt.size = 0;
156                         avcodec_encode_audio2(ctx, &pkt, nullptr, &got_output);
157                         if (!got_output) break;
158
159                         pkt.stream_index = 1;
160                         pkt.flags = 0;
161                         for (Mux *mux : muxes) {
162                                 mux->add_packet(pkt, pkt.pts, pkt.dts);
163                         }
164                         av_free_packet(&pkt);
165                 }
166         }
167 }