]> git.sesse.net Git - nageru/blob - nageru/audio_encoder.cpp
126e0e2dce19ef40f0406bea7a3d4abed120c731
[nageru] / 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 <libswresample/swresample.h>
7 #include <libavutil/channel_layout.h>
8 #include <libavutil/error.h>
9 #include <libavutil/frame.h>
10 #include <libavutil/mem.h>
11 #include <libavutil/opt.h>
12 #include <libavutil/rational.h>
13 #include <libavutil/samplefmt.h>
14 }
15
16 #include <assert.h>
17 #include <errno.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <memory>
21 #include <string>
22 #include <vector>
23
24 #include "defs.h"
25 #include "shared/mux.h"
26 #include "shared/timebase.h"
27
28 using namespace std;
29
30 AudioEncoder::AudioEncoder(const string &codec_name, int bit_rate, const AVOutputFormat *oformat)
31 {
32         const AVCodec *codec = avcodec_find_encoder_by_name(codec_name.c_str());
33         if (codec == nullptr) {
34                 fprintf(stderr, "ERROR: Could not find codec '%s'\n", codec_name.c_str());
35                 abort();
36         }
37
38         ctx = avcodec_alloc_context3(codec);
39         ctx->bit_rate = bit_rate;
40         ctx->sample_rate = OUTPUT_FREQUENCY;
41         ctx->sample_fmt = codec->sample_fmts[0];
42         ctx->ch_layout.order = AV_CHANNEL_ORDER_NATIVE;
43         ctx->ch_layout.nb_channels = 2;
44         ctx->ch_layout.u.mask = AV_CH_LAYOUT_STEREO;
45         ctx->time_base = AVRational{1, TIMEBASE};
46         if (oformat->flags & AVFMT_GLOBALHEADER) {
47                 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
48         }
49         if (avcodec_open2(ctx, codec, NULL) < 0) {
50                 fprintf(stderr, "Could not open codec '%s'\n", codec_name.c_str());
51                 abort();
52         }
53
54         resampler = nullptr;
55         int ok = swr_alloc_set_opts2(&resampler,
56                                      /*out_ch_layout=*/&ctx->ch_layout,
57                                      /*out_sample_fmt=*/ctx->sample_fmt,
58                                      /*out_sample_rate=*/OUTPUT_FREQUENCY,
59                                      /*in_ch_layout=*/&ctx->ch_layout,
60                                      /*in_sample_fmt=*/AV_SAMPLE_FMT_FLT,
61                                      /*in_sample_rate=*/OUTPUT_FREQUENCY,
62                                      /*log_offset=*/0,
63                                      /*log_ctx=*/nullptr);
64         if (ok != 0) {
65                 fprintf(stderr, "Allocating resampler failed.\n");
66                 abort();
67         }
68
69         if (swr_init(resampler) < 0) {
70                 fprintf(stderr, "Could not open resample context.\n");
71                 abort();
72         }
73
74         audio_frame = av_frame_alloc();
75 }
76
77 AudioEncoder::~AudioEncoder()
78 {
79         av_frame_free(&audio_frame);
80         swr_free(&resampler);
81         avcodec_free_context(&ctx);
82 }
83
84 void AudioEncoder::encode_audio(const vector<float> &audio, int64_t audio_pts)
85 {
86         if (ctx->frame_size == 0) {
87                 // No queueing needed.
88                 assert(audio_queue.empty());
89                 assert(audio.size() % 2 == 0);
90                 encode_audio_one_frame(&audio[0], audio.size() / 2, audio_pts);
91                 return;
92         }
93
94         int64_t sample_offset = audio_queue.size();
95
96         audio_queue.insert(audio_queue.end(), audio.begin(), audio.end());
97         size_t sample_num;
98         for (sample_num = 0;
99              sample_num + ctx->frame_size * 2 <= audio_queue.size();
100              sample_num += ctx->frame_size * 2) {
101                 int64_t adjusted_audio_pts = audio_pts + (int64_t(sample_num) - sample_offset) * TIMEBASE / (OUTPUT_FREQUENCY * 2);
102                 encode_audio_one_frame(&audio_queue[sample_num],
103                                        ctx->frame_size,
104                                        adjusted_audio_pts);
105         }
106         audio_queue.erase(audio_queue.begin(), audio_queue.begin() + sample_num);
107
108         last_pts = audio_pts + audio.size() * TIMEBASE / (OUTPUT_FREQUENCY * 2);
109 }
110
111 void AudioEncoder::encode_audio_one_frame(const float *audio, size_t num_samples, int64_t audio_pts)
112 {
113         audio_frame->pts = audio_pts;
114         audio_frame->nb_samples = num_samples;
115         audio_frame->ch_layout.order = AV_CHANNEL_ORDER_NATIVE;
116         audio_frame->ch_layout.nb_channels = 2;
117         audio_frame->ch_layout.u.mask = AV_CH_LAYOUT_STEREO;
118         audio_frame->format = ctx->sample_fmt;
119         audio_frame->sample_rate = OUTPUT_FREQUENCY;
120
121         if (av_samples_alloc(audio_frame->data, nullptr, 2, num_samples, ctx->sample_fmt, 0) < 0) {
122                 fprintf(stderr, "Could not allocate %zu samples.\n", num_samples);
123                 abort();
124         }
125
126         if (swr_convert(resampler, audio_frame->data, num_samples, reinterpret_cast<const uint8_t **>(&audio), num_samples) < 0) {
127                 fprintf(stderr, "Audio conversion failed.\n");
128                 abort();
129         }
130
131         int err = avcodec_send_frame(ctx, audio_frame);
132         if (err < 0) {
133                 fprintf(stderr, "avcodec_send_frame() failed with error %d\n", err);
134                 abort();
135         }
136
137         for ( ;; ) {  // Termination condition within loop.
138                 AVPacket pkt;
139                 av_init_packet(&pkt);
140                 pkt.data = nullptr;
141                 pkt.size = 0;
142                 int err = avcodec_receive_packet(ctx, &pkt);
143                 if (err == 0) {
144                         pkt.stream_index = 1;
145                         pkt.flags = 0;
146                         for (Mux *mux : muxes) {
147                                 mux->add_packet(pkt, pkt.pts, pkt.dts);
148                         }
149                         av_packet_unref(&pkt);
150                 } else if (err == AVERROR(EAGAIN)) {
151                         break;
152                 } else {
153                         fprintf(stderr, "avcodec_receive_frame() failed with error %d\n", err);
154                         abort();
155                 }
156         }
157
158         av_freep(&audio_frame->data[0]);
159         av_frame_unref(audio_frame);
160 }
161
162 void AudioEncoder::encode_last_audio()
163 {
164         if (!audio_queue.empty()) {
165                 // Last frame can be whatever size we want.
166                 assert(audio_queue.size() % 2 == 0);
167                 encode_audio_one_frame(&audio_queue[0], audio_queue.size() / 2, last_pts);
168                 audio_queue.clear();
169         }
170
171         if (ctx->codec->capabilities & AV_CODEC_CAP_DELAY) {
172                 // Collect any delayed frames.
173                 for ( ;; ) {
174                         AVPacket pkt;
175                         av_init_packet(&pkt);
176                         pkt.data = nullptr;
177                         pkt.size = 0;
178                         int err = avcodec_receive_packet(ctx, &pkt);
179                         if (err == 0) {
180                                 pkt.stream_index = 1;
181                                 pkt.flags = 0;
182                                 for (Mux *mux : muxes) {
183                                         mux->add_packet(pkt, pkt.pts, pkt.dts);
184                                 }
185                                 av_packet_unref(&pkt);
186                         } else if (err == AVERROR_EOF) {
187                                 break;
188                         } else {
189                                 fprintf(stderr, "avcodec_receive_frame() failed with error %d\n", err);
190                                 abort();
191                         }
192                 }
193         }
194 }
195
196 AVCodecParametersWithDeleter AudioEncoder::get_codec_parameters()
197 {
198         AVCodecParameters *codecpar = avcodec_parameters_alloc();
199         avcodec_parameters_from_context(codecpar, ctx);
200         return AVCodecParametersWithDeleter(codecpar);
201 }