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