]> git.sesse.net Git - nageru/blob - audio_mixer.cpp
Refactor fill_audio_bus() into its own function.
[nageru] / audio_mixer.cpp
1 #include "audio_mixer.h"
2
3 #include <assert.h>
4 #include <endian.h>
5 #include <bmusb/bmusb.h>
6 #include <stdio.h>
7 #include <endian.h>
8 #include <cmath>
9
10 #include "db.h"
11 #include "flags.h"
12 #include "timebase.h"
13
14 using namespace bmusb;
15 using namespace std;
16
17 namespace {
18
19 // TODO: If these prove to be a bottleneck, they can be SSSE3-optimized
20 // (usually including multiple channels at a time).
21
22 void convert_fixed24_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
23                              const uint8_t *src, size_t in_channel, size_t in_num_channels,
24                              size_t num_samples)
25 {
26         assert(in_channel < in_num_channels);
27         assert(out_channel < out_num_channels);
28         src += in_channel * 3;
29         dst += out_channel;
30
31         for (size_t i = 0; i < num_samples; ++i) {
32                 uint32_t s1 = src[0];
33                 uint32_t s2 = src[1];
34                 uint32_t s3 = src[2];
35                 uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
36                 *dst = int(s) * (1.0f / 2147483648.0f);
37
38                 src += 3 * in_num_channels;
39                 dst += out_num_channels;
40         }
41 }
42
43 void convert_fixed32_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
44                              const uint8_t *src, size_t in_channel, size_t in_num_channels,
45                              size_t num_samples)
46 {
47         assert(in_channel < in_num_channels);
48         assert(out_channel < out_num_channels);
49         src += in_channel * 4;
50         dst += out_channel;
51
52         for (size_t i = 0; i < num_samples; ++i) {
53                 int32_t s = le32toh(*(int32_t *)src);
54                 *dst = s * (1.0f / 2147483648.0f);
55
56                 src += 4 * in_num_channels;
57                 dst += out_num_channels;
58         }
59 }
60
61 }  // namespace
62
63 AudioMixer::AudioMixer(unsigned num_cards)
64         : num_cards(num_cards),
65           level_compressor(OUTPUT_FREQUENCY),
66           limiter(OUTPUT_FREQUENCY),
67           compressor(OUTPUT_FREQUENCY)
68 {
69         locut.init(FILTER_HPF, 2);
70
71         set_locut_enabled(global_flags.locut_enabled);
72         set_gain_staging_db(global_flags.initial_gain_staging_db);
73         set_gain_staging_auto(global_flags.gain_staging_auto);
74         set_compressor_enabled(global_flags.compressor_enabled);
75         set_limiter_enabled(global_flags.limiter_enabled);
76         set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
77
78         // Generate a very simple, default input mapping.
79         InputMapping::Bus input;
80         input.name = "Main";
81         input.input_source_type = InputSourceType::CAPTURE_CARD;
82         input.input_source_index = 0;
83         input.source_channel[0] = 0;
84         input.source_channel[1] = 1;
85
86         InputMapping new_input_mapping;
87         new_input_mapping.buses.push_back(input);
88         set_input_mapping(new_input_mapping);
89 }
90
91 void AudioMixer::reset_card(unsigned card_index)
92 {
93         lock_guard<mutex> lock(audio_mutex);
94         reset_card_mutex_held(card_index);
95 }
96
97 void AudioMixer::reset_card_mutex_held(unsigned card_index)
98 {
99         CaptureCard *card = &cards[card_index];
100         if (card->interesting_channels.empty()) {
101                 card->resampling_queue.reset();
102         } else {
103                 card->resampling_queue.reset(new ResamplingQueue(card_index, OUTPUT_FREQUENCY, OUTPUT_FREQUENCY, card->interesting_channels.size()));
104         }
105         card->next_local_pts = 0;
106 }
107
108 void AudioMixer::add_audio(unsigned card_index, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length)
109 {
110         lock_guard<mutex> lock(audio_mutex);
111         CaptureCard *card = &cards[card_index];
112
113         if (card->resampling_queue == nullptr) {
114                 // No buses use this card; throw it away.
115                 return;
116         }
117
118         unsigned num_channels = card->interesting_channels.size();
119         assert(num_channels > 0);
120
121         // Convert the audio to stereo fp32.
122         vector<float> audio;
123         audio.resize(num_samples * num_channels);
124         unsigned channel_index = 0;
125         for (auto channel_it = card->interesting_channels.cbegin(); channel_it != card->interesting_channels.end(); ++channel_it, ++channel_index) {
126                 switch (audio_format.bits_per_sample) {
127                 case 0:
128                         assert(num_samples == 0);
129                         break;
130                 case 24:
131                         convert_fixed24_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
132                         break;
133                 case 32:
134                         convert_fixed32_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
135                         break;
136                 default:
137                         fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
138                         assert(false);
139                 }
140         }
141
142         // Now add it.
143         int64_t local_pts = card->next_local_pts;
144         card->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.data(), num_samples);
145         card->next_local_pts = local_pts + frame_length;
146 }
147
148 void AudioMixer::add_silence(unsigned card_index, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
149 {
150         CaptureCard *card = &cards[card_index];
151         lock_guard<mutex> lock(audio_mutex);
152
153         if (card->resampling_queue == nullptr) {
154                 // No buses use this card; throw it away.
155                 return;
156         }
157
158         unsigned num_channels = card->interesting_channels.size();
159         assert(num_channels > 0);
160
161         vector<float> silence(samples_per_frame * num_channels, 0.0f);
162         for (unsigned i = 0; i < num_frames; ++i) {
163                 card->resampling_queue->add_input_samples(card->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame);
164                 // Note that if the format changed in the meantime, we have
165                 // no way of detecting that; we just have to assume the frame length
166                 // is always the same.
167                 card->next_local_pts += frame_length;
168         }
169 }
170
171 void AudioMixer::find_sample_src_from_capture_card(const vector<float> *samples_card, unsigned card_index, int source_channel, const float **srcptr, unsigned *stride)
172 {
173         static float zero = 0.0f;
174         if (source_channel == -1) {
175                 *srcptr = &zero;
176                 *stride = 0;
177                 return;
178         }
179         CaptureCard *card = &cards[card_index];
180         unsigned channel_index = 0;
181         for (int channel : card->interesting_channels) {
182                 if (channel == source_channel) break;
183                 ++channel_index;
184         }
185         assert(channel_index < card->interesting_channels.size());
186         *srcptr = &samples_card[card_index][channel_index];
187         *stride = card->interesting_channels.size();
188 }
189
190 // TODO: Can be SSSE3-optimized if need be.
191 void AudioMixer::fill_audio_bus(const vector<float> *samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output)
192 {
193         if (bus.input_source_type == InputSourceType::SILENCE) {
194                 memset(output, 0, num_samples * sizeof(*output));
195         } else {
196                 assert(bus.input_source_type == InputSourceType::CAPTURE_CARD);
197                 const float *lsrc, *rsrc;
198                 unsigned lstride, rstride;
199                 float *dptr = output;
200                 find_sample_src_from_capture_card(samples_card, bus.input_source_index, bus.source_channel[0], &lsrc, &lstride);
201                 find_sample_src_from_capture_card(samples_card, bus.input_source_index, bus.source_channel[1], &rsrc, &rstride);
202                 for (unsigned i = 0; i < num_samples; ++i) {
203                         *dptr++ = *lsrc;
204                         *dptr++ = *rsrc;
205                         lsrc += lstride;
206                         rsrc += rstride;
207                 }
208         }
209 }
210
211 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
212 {
213         vector<float> samples_card[MAX_CARDS];
214         vector<float> samples_bus;
215
216         lock_guard<mutex> lock(audio_mutex);
217
218         // Pick out all the interesting channels from all the cards.
219         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
220                 CaptureCard *card = &cards[card_index];
221                 if (!card->interesting_channels.empty()) {
222                         samples_card[card_index].resize(num_samples * card->interesting_channels.size());
223                         card->resampling_queue->get_output_samples(
224                                 pts,
225                                 &samples_card[card_index][0],
226                                 num_samples,
227                                 rate_adjustment_policy);
228                 }
229         }
230
231         // TODO: Move lo-cut etc. into each bus.
232         vector<float> samples_out;
233         samples_out.resize(num_samples * 2);
234         samples_bus.resize(num_samples * 2);
235         for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
236                 fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]);
237
238                 float volume = from_db(fader_volume_db[bus_index]);
239                 if (bus_index == 0) {
240                         for (unsigned i = 0; i < num_samples * 2; ++i) {
241                                 samples_out[i] = samples_bus[i] * volume;
242                         }
243                 } else {
244                         for (unsigned i = 0; i < num_samples * 2; ++i) {
245                                 samples_out[i] += samples_bus[i] * volume;
246                         }
247                 }
248         }
249
250         // Cut away everything under 120 Hz (or whatever the cutoff is);
251         // we don't need it for voice, and it will reduce headroom
252         // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
253         // should be dampened.)
254         if (locut_enabled) {
255                 locut.render(samples_out.data(), samples_out.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
256         }
257
258         {
259                 lock_guard<mutex> lock(compressor_mutex);
260
261                 // Apply a level compressor to get the general level right.
262                 // Basically, if it's over about -40 dBFS, we squeeze it down to that level
263                 // (or more precisely, near it, since we don't use infinite ratio),
264                 // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
265                 // entirely arbitrary, but from practical tests with speech, it seems to
266                 // put ut around -23 LUFS, so it's a reasonable starting point for later use.
267                 {
268                         if (level_compressor_enabled) {
269                                 float threshold = 0.01f;   // -40 dBFS.
270                                 float ratio = 20.0f;
271                                 float attack_time = 0.5f;
272                                 float release_time = 20.0f;
273                                 float makeup_gain = from_db(ref_level_dbfs - (-40.0f));  // +26 dB.
274                                 level_compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
275                                 gain_staging_db = to_db(level_compressor.get_attenuation() * makeup_gain);
276                         } else {
277                                 // Just apply the gain we already had.
278                                 float g = from_db(gain_staging_db);
279                                 for (size_t i = 0; i < samples_out.size(); ++i) {
280                                         samples_out[i] *= g;
281                                 }
282                         }
283                 }
284
285         #if 0
286                 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
287                         level_compressor.get_level(), to_db(level_compressor.get_level()),
288                         level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
289                         to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
290         #endif
291
292         //      float limiter_att, compressor_att;
293
294                 // The real compressor.
295                 if (compressor_enabled) {
296                         float threshold = from_db(compressor_threshold_dbfs);
297                         float ratio = 20.0f;
298                         float attack_time = 0.005f;
299                         float release_time = 0.040f;
300                         float makeup_gain = 2.0f;  // +6 dB.
301                         compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
302         //              compressor_att = compressor.get_attenuation();
303                 }
304
305                 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
306                 // Note that since ratio is not infinite, we could go slightly higher than this.
307                 if (limiter_enabled) {
308                         float threshold = from_db(limiter_threshold_dbfs);
309                         float ratio = 30.0f;
310                         float attack_time = 0.0f;  // Instant.
311                         float release_time = 0.020f;
312                         float makeup_gain = 1.0f;  // 0 dB.
313                         limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
314         //              limiter_att = limiter.get_attenuation();
315                 }
316
317         //      printf("limiter=%+5.1f  compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
318         }
319
320         // At this point, we are most likely close to +0 LU, but all of our
321         // measurements have been on raw sample values, not R128 values.
322         // So we have a final makeup gain to get us to +0 LU; the gain
323         // adjustments required should be relatively small, and also, the
324         // offset shouldn't change much (only if the type of audio changes
325         // significantly). Thus, we shoot for updating this value basically
326         // “whenever we process buffers”, since the R128 calculation isn't exactly
327         // something we get out per-sample.
328         //
329         // Note that there's a feedback loop here, so we choose a very slow filter
330         // (half-time of 30 seconds).
331         double target_loudness_factor, alpha;
332         double loudness_lu = loudness_lufs - ref_level_lufs;
333         double current_makeup_lu = to_db(final_makeup_gain);
334         target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
335
336         // If we're outside +/- 5 LU uncorrected, we don't count it as
337         // a normal signal (probably silence) and don't change the
338         // correction factor; just apply what we already have.
339         if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
340                 alpha = 0.0;
341         } else {
342                 // Formula adapted from
343                 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
344                 const double half_time_s = 30.0;
345                 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
346                 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
347         }
348
349         {
350                 lock_guard<mutex> lock(compressor_mutex);
351                 double m = final_makeup_gain;
352                 for (size_t i = 0; i < samples_out.size(); i += 2) {
353                         samples_out[i + 0] *= m;
354                         samples_out[i + 1] *= m;
355                         m += (target_loudness_factor - m) * alpha;
356                 }
357                 final_makeup_gain = m;
358         }
359
360         return samples_out;
361 }
362
363 vector<string> AudioMixer::get_names() const
364 {
365         lock_guard<mutex> lock(audio_mutex);
366         vector<string> names;
367         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
368                 const CaptureCard *card = &cards[card_index];
369                 names.push_back(card->name);
370         }
371         return names;
372 }
373
374 void AudioMixer::set_name(unsigned card_index, const string &name)
375 {
376         lock_guard<mutex> lock(audio_mutex);
377         CaptureCard *card = &cards[card_index];
378         card->name = name;
379 }
380
381 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
382 {
383         lock_guard<mutex> lock(audio_mutex);
384
385         map<unsigned, set<unsigned>> interesting_channels;
386         for (const InputMapping::Bus &bus : new_input_mapping.buses) {
387                 if (bus.input_source_type == InputSourceType::CAPTURE_CARD) {
388                         for (unsigned channel = 0; channel < 2; ++channel) {
389                                 if (bus.source_channel[channel] != -1) {
390                                         interesting_channels[bus.input_source_index].insert(bus.source_channel[channel]);
391                                 }
392                         }
393                 }
394         }
395
396         // Reset resamplers for all cards that don't have the exact same state as before.
397         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
398                 CaptureCard *card = &cards[card_index];
399                 if (card->interesting_channels != interesting_channels[card_index]) {
400                         card->interesting_channels = interesting_channels[card_index];
401                         reset_card_mutex_held(card_index);
402                 }
403         }
404
405         input_mapping = new_input_mapping;
406 }
407
408 InputMapping AudioMixer::get_input_mapping() const
409 {
410         lock_guard<mutex> lock(audio_mutex);
411         return input_mapping;
412 }