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