]> git.sesse.net Git - nageru/blob - audio_encoder.cpp
Make the master peak display clickable, like all the other peak labels.
[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, const AVOutputFormat *oformat)
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         if (oformat->flags & AVFMT_GLOBALHEADER) {
40                 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
41         }
42         if (avcodec_open2(ctx, codec, NULL) < 0) {
43                 fprintf(stderr, "Could not open codec '%s'\n", codec_name.c_str());
44                 exit(1);
45         }
46
47         resampler = avresample_alloc_context();
48         if (resampler == nullptr) {
49                 fprintf(stderr, "Allocating resampler failed.\n");
50                 exit(1);
51         }
52
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);
59
60         if (avresample_open(resampler) < 0) {
61                 fprintf(stderr, "Could not open resample context.\n");
62                 exit(1);
63         }
64
65         audio_frame = av_frame_alloc();
66 }
67
68 AudioEncoder::~AudioEncoder()
69 {
70         av_frame_free(&audio_frame);
71         avresample_free(&resampler);
72         avcodec_free_context(&ctx);
73 }
74
75 void AudioEncoder::encode_audio(const vector<float> &audio, int64_t audio_pts)
76 {
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);
82                 return;
83         }
84
85         int64_t sample_offset = audio_queue.size();
86
87         audio_queue.insert(audio_queue.end(), audio.begin(), audio.end());
88         size_t sample_num;
89         for (sample_num = 0;
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],
94                                        ctx->frame_size,
95                                        adjusted_audio_pts);
96         }
97         audio_queue.erase(audio_queue.begin(), audio_queue.begin() + sample_num);
98
99         last_pts = audio_pts + audio.size() * TIMEBASE / (OUTPUT_FREQUENCY * 2);
100 }
101
102 void AudioEncoder::encode_audio_one_frame(const float *audio, size_t num_samples, int64_t audio_pts)
103 {
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;
109
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);
112                 exit(1);
113         }
114
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");
118                 exit(1);
119         }
120
121         int err = avcodec_send_frame(ctx, audio_frame);
122         if (err < 0) {
123                 fprintf(stderr, "avcodec_send_frame() failed with error %d\n", err);
124                 exit(1);
125         }
126
127         for ( ;; ) {  // Termination condition within loop.
128                 AVPacket pkt;
129                 av_init_packet(&pkt);
130                 pkt.data = nullptr;
131                 pkt.size = 0;
132                 int err = avcodec_receive_packet(ctx, &pkt);
133                 if (err == 0) {
134                         pkt.stream_index = 1;
135                         pkt.flags = 0;
136                         for (Mux *mux : muxes) {
137                                 mux->add_packet(pkt, pkt.pts, pkt.dts);
138                         }
139                         av_packet_unref(&pkt);
140                 } else if (err == AVERROR(EAGAIN)) {
141                         break;
142                 } else {
143                         fprintf(stderr, "avcodec_receive_frame() failed with error %d\n", err);
144                         exit(1);
145                 }
146         }
147
148         av_freep(&audio_frame->data[0]);
149         av_frame_unref(audio_frame);
150 }
151
152 void AudioEncoder::encode_last_audio()
153 {
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);
158                 audio_queue.clear();
159         }
160
161         if (ctx->codec->capabilities & AV_CODEC_CAP_DELAY) {
162                 // Collect any delayed frames.
163                 for ( ;; ) {
164                         AVPacket pkt;
165                         av_init_packet(&pkt);
166                         pkt.data = nullptr;
167                         pkt.size = 0;
168                         int err = avcodec_receive_packet(ctx, &pkt);
169                         if (err == 0) {
170                                 pkt.stream_index = 1;
171                                 pkt.flags = 0;
172                                 for (Mux *mux : muxes) {
173                                         mux->add_packet(pkt, pkt.pts, pkt.dts);
174                                 }
175                                 av_packet_unref(&pkt);
176                         } else if (err == AVERROR_EOF) {
177                                 break;
178                         } else {
179                                 fprintf(stderr, "avcodec_receive_frame() failed with error %d\n", err);
180                                 exit(1);
181                         }
182                 }
183         }
184 }
185
186 AVCodecParametersWithDeleter AudioEncoder::get_codec_parameters()
187 {
188         AVCodecParameters *codecpar = avcodec_parameters_alloc();
189         avcodec_parameters_from_context(codecpar, ctx);
190         return AVCodecParametersWithDeleter(codecpar, avcodec_parameters_free_unique);
191 }