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