]> git.sesse.net Git - nageru/blob - audio_mixer.cpp
Pick out the right channels when resampling.
[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 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
191 {
192         vector<float> samples_card[MAX_CARDS];
193         vector<float> samples_bus;
194
195         lock_guard<mutex> lock(audio_mutex);
196
197         // Pick out all the interesting channels from all the cards.
198         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
199                 CaptureCard *card = &cards[card_index];
200                 if (!card->interesting_channels.empty()) {
201                         samples_card[card_index].resize(num_samples * card->interesting_channels.size());
202                         card->resampling_queue->get_output_samples(
203                                 pts,
204                                 &samples_card[card_index][0],
205                                 num_samples,
206                                 rate_adjustment_policy);
207                 }
208         }
209
210         // TODO: Move lo-cut etc. into each bus.
211         vector<float> samples_out;
212         samples_out.resize(num_samples * 2);
213         samples_bus.resize(num_samples * 2);
214         for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
215                 const InputMapping::Bus &input = input_mapping.buses[bus_index];
216                 if (input.input_source_type == InputSourceType::SILENCE) {
217                         memset(&samples_bus[0], 0, samples_bus.size() * sizeof(samples_bus[0]));
218                 } else {
219                         // TODO: Move this into its own function. Can be SSSE3-optimized if need be.
220                         assert(input.input_source_type == InputSourceType::CAPTURE_CARD);
221                         const float *lsrc, *rsrc;
222                         unsigned lstride, rstride;
223                         float *dptr = &samples_bus[0];
224                         find_sample_src_from_capture_card(samples_card, input.input_source_index, input.source_channel[0], &lsrc, &lstride);
225                         find_sample_src_from_capture_card(samples_card, input.input_source_index, input.source_channel[1], &rsrc, &rstride);
226                         for (unsigned i = 0; i < num_samples; ++i) {
227                                 *dptr++ = *lsrc;
228                                 *dptr++ = *rsrc;
229                                 lsrc += lstride;
230                                 rsrc += rstride;
231                         }
232                 }
233
234                 float volume = from_db(fader_volume_db[bus_index]);
235                 if (bus_index == 0) {
236                         for (unsigned i = 0; i < num_samples * 2; ++i) {
237                                 samples_out[i] = samples_bus[i] * volume;
238                         }
239                 } else {
240                         for (unsigned i = 0; i < num_samples * 2; ++i) {
241                                 samples_out[i] += samples_bus[i] * volume;
242                         }
243                 }
244         }
245
246         // Cut away everything under 120 Hz (or whatever the cutoff is);
247         // we don't need it for voice, and it will reduce headroom
248         // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
249         // should be dampened.)
250         if (locut_enabled) {
251                 locut.render(samples_out.data(), samples_out.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
252         }
253
254         {
255                 lock_guard<mutex> lock(compressor_mutex);
256
257                 // Apply a level compressor to get the general level right.
258                 // Basically, if it's over about -40 dBFS, we squeeze it down to that level
259                 // (or more precisely, near it, since we don't use infinite ratio),
260                 // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
261                 // entirely arbitrary, but from practical tests with speech, it seems to
262                 // put ut around -23 LUFS, so it's a reasonable starting point for later use.
263                 {
264                         if (level_compressor_enabled) {
265                                 float threshold = 0.01f;   // -40 dBFS.
266                                 float ratio = 20.0f;
267                                 float attack_time = 0.5f;
268                                 float release_time = 20.0f;
269                                 float makeup_gain = from_db(ref_level_dbfs - (-40.0f));  // +26 dB.
270                                 level_compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
271                                 gain_staging_db = to_db(level_compressor.get_attenuation() * makeup_gain);
272                         } else {
273                                 // Just apply the gain we already had.
274                                 float g = from_db(gain_staging_db);
275                                 for (size_t i = 0; i < samples_out.size(); ++i) {
276                                         samples_out[i] *= g;
277                                 }
278                         }
279                 }
280
281         #if 0
282                 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
283                         level_compressor.get_level(), to_db(level_compressor.get_level()),
284                         level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
285                         to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
286         #endif
287
288         //      float limiter_att, compressor_att;
289
290                 // The real compressor.
291                 if (compressor_enabled) {
292                         float threshold = from_db(compressor_threshold_dbfs);
293                         float ratio = 20.0f;
294                         float attack_time = 0.005f;
295                         float release_time = 0.040f;
296                         float makeup_gain = 2.0f;  // +6 dB.
297                         compressor.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
298         //              compressor_att = compressor.get_attenuation();
299                 }
300
301                 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
302                 // Note that since ratio is not infinite, we could go slightly higher than this.
303                 if (limiter_enabled) {
304                         float threshold = from_db(limiter_threshold_dbfs);
305                         float ratio = 30.0f;
306                         float attack_time = 0.0f;  // Instant.
307                         float release_time = 0.020f;
308                         float makeup_gain = 1.0f;  // 0 dB.
309                         limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
310         //              limiter_att = limiter.get_attenuation();
311                 }
312
313         //      printf("limiter=%+5.1f  compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
314         }
315
316         // At this point, we are most likely close to +0 LU, but all of our
317         // measurements have been on raw sample values, not R128 values.
318         // So we have a final makeup gain to get us to +0 LU; the gain
319         // adjustments required should be relatively small, and also, the
320         // offset shouldn't change much (only if the type of audio changes
321         // significantly). Thus, we shoot for updating this value basically
322         // “whenever we process buffers”, since the R128 calculation isn't exactly
323         // something we get out per-sample.
324         //
325         // Note that there's a feedback loop here, so we choose a very slow filter
326         // (half-time of 30 seconds).
327         double target_loudness_factor, alpha;
328         double loudness_lu = loudness_lufs - ref_level_lufs;
329         double current_makeup_lu = to_db(final_makeup_gain);
330         target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
331
332         // If we're outside +/- 5 LU uncorrected, we don't count it as
333         // a normal signal (probably silence) and don't change the
334         // correction factor; just apply what we already have.
335         if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
336                 alpha = 0.0;
337         } else {
338                 // Formula adapted from
339                 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
340                 const double half_time_s = 30.0;
341                 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
342                 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
343         }
344
345         {
346                 lock_guard<mutex> lock(compressor_mutex);
347                 double m = final_makeup_gain;
348                 for (size_t i = 0; i < samples_out.size(); i += 2) {
349                         samples_out[i + 0] *= m;
350                         samples_out[i + 1] *= m;
351                         m += (target_loudness_factor - m) * alpha;
352                 }
353                 final_makeup_gain = m;
354         }
355
356         return samples_out;
357 }
358
359 vector<string> AudioMixer::get_names() const
360 {
361         lock_guard<mutex> lock(audio_mutex);
362         vector<string> names;
363         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
364                 const CaptureCard *card = &cards[card_index];
365                 names.push_back(card->name);
366         }
367         return names;
368 }
369
370 void AudioMixer::set_name(unsigned card_index, const string &name)
371 {
372         lock_guard<mutex> lock(audio_mutex);
373         CaptureCard *card = &cards[card_index];
374         card->name = name;
375 }
376
377 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
378 {
379         lock_guard<mutex> lock(audio_mutex);
380
381         map<unsigned, set<unsigned>> interesting_channels;
382         for (const InputMapping::Bus &bus : new_input_mapping.buses) {
383                 if (bus.input_source_type == InputSourceType::CAPTURE_CARD) {
384                         for (unsigned channel = 0; channel < 2; ++channel) {
385                                 if (bus.source_channel[channel] != -1) {
386                                         interesting_channels[bus.input_source_index].insert(bus.source_channel[channel]);
387                                 }
388                         }
389                 }
390         }
391
392         // Reset resamplers for all cards that don't have the exact same state as before.
393         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
394                 CaptureCard *card = &cards[card_index];
395                 if (card->interesting_channels != interesting_channels[card_index]) {
396                         card->interesting_channels = interesting_channels[card_index];
397                         reset_card_mutex_held(card_index);
398                 }
399         }
400
401         input_mapping = new_input_mapping;
402 }
403
404 InputMapping AudioMixer::get_input_mapping() const
405 {
406         lock_guard<mutex> lock(audio_mutex);
407         return input_mapping;
408 }