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