]> git.sesse.net Git - nageru/blob - audio_mixer.cpp
8d09ad3bfa9a279f5d74af38613503ce835311e8
[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 float find_peak(const float *samples, size_t num_samples)
81 {
82         float m = fabs(samples[0]);
83         for (size_t i = 1; i < num_samples; ++i) {
84                 m = max(m, fabs(samples[i]));
85         }
86         return m;
87 }
88
89 void deinterleave_samples(const vector<float> &in, vector<float> *out_l, vector<float> *out_r)
90 {
91         size_t num_samples = in.size() / 2;
92         out_l->resize(num_samples);
93         out_r->resize(num_samples);
94
95         const float *inptr = in.data();
96         float *lptr = &(*out_l)[0];
97         float *rptr = &(*out_r)[0];
98         for (size_t i = 0; i < num_samples; ++i) {
99                 *lptr++ = *inptr++;
100                 *rptr++ = *inptr++;
101         }
102 }
103
104 }  // namespace
105
106 AudioMixer::AudioMixer(unsigned num_cards)
107         : num_cards(num_cards),
108           limiter(OUTPUT_FREQUENCY),
109           correlation(OUTPUT_FREQUENCY)
110 {
111         for (unsigned bus_index = 0; bus_index < MAX_BUSES; ++bus_index) {
112                 locut[bus_index].init(FILTER_HPF, 2);
113                 locut_enabled[bus_index] = global_flags.locut_enabled;
114                 gain_staging_db[bus_index] = global_flags.initial_gain_staging_db;
115                 compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
116                 compressor_threshold_dbfs[bus_index] = ref_level_dbfs - 12.0f;  // -12 dB.
117                 compressor_enabled[bus_index] = global_flags.compressor_enabled;
118                 level_compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
119                 level_compressor_enabled[bus_index] = global_flags.gain_staging_auto;
120         }
121         set_limiter_enabled(global_flags.limiter_enabled);
122         set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
123
124         // Generate a very simple, default input mapping.
125         InputMapping::Bus input;
126         input.name = "Main";
127         input.device.type = InputSourceType::CAPTURE_CARD;
128         input.device.index = 0;
129         input.source_channel[0] = 0;
130         input.source_channel[1] = 1;
131
132         InputMapping new_input_mapping;
133         new_input_mapping.buses.push_back(input);
134         set_input_mapping(new_input_mapping);
135
136         // Look for ALSA cards.
137         available_alsa_cards = ALSAInput::enumerate_devices();
138
139         r128.init(2, OUTPUT_FREQUENCY);
140         r128.integr_start();
141
142         // hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise,
143         // and there's a limit to how important the peak meter is.
144         peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0);
145 }
146
147 AudioMixer::~AudioMixer()
148 {
149         for (unsigned card_index = 0; card_index < available_alsa_cards.size(); ++card_index) {
150                 const AudioDevice &device = alsa_inputs[card_index];
151                 if (device.alsa_device != nullptr) {
152                         device.alsa_device->stop_capture_thread();
153                 }
154         }
155 }
156
157
158 void AudioMixer::reset_resampler(DeviceSpec device_spec)
159 {
160         lock_guard<timed_mutex> lock(audio_mutex);
161         reset_resampler_mutex_held(device_spec);
162 }
163
164 void AudioMixer::reset_resampler_mutex_held(DeviceSpec device_spec)
165 {
166         AudioDevice *device = find_audio_device(device_spec);
167
168         if (device->interesting_channels.empty()) {
169                 device->resampling_queue.reset();
170         } else {
171                 // TODO: ResamplingQueue should probably take the full device spec.
172                 // (It's only used for console output, though.)
173                 device->resampling_queue.reset(new ResamplingQueue(device_spec.index, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size()));
174         }
175         device->next_local_pts = 0;
176 }
177
178 void AudioMixer::reset_alsa_mutex_held(DeviceSpec device_spec)
179 {
180         assert(device_spec.type == InputSourceType::ALSA_INPUT);
181         unsigned card_index = device_spec.index;
182         AudioDevice *device = find_audio_device(device_spec);
183
184         if (device->alsa_device != nullptr) {
185                 device->alsa_device->stop_capture_thread();
186         }
187         if (device->interesting_channels.empty()) {
188                 device->alsa_device.reset();
189         } else {
190                 const ALSAInput::Device &alsa_dev = available_alsa_cards[card_index];
191                 device->alsa_device.reset(new ALSAInput(alsa_dev.address.c_str(), OUTPUT_FREQUENCY, alsa_dev.num_channels, bind(&AudioMixer::add_audio, this, device_spec, _1, _2, _3, _4)));
192                 device->capture_frequency = device->alsa_device->get_sample_rate();
193                 device->alsa_device->start_capture_thread();
194         }
195 }
196
197 bool AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length)
198 {
199         AudioDevice *device = find_audio_device(device_spec);
200
201         unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
202         if (!lock.try_lock_for(chrono::milliseconds(10))) {
203                 return false;
204         }
205         if (device->resampling_queue == nullptr) {
206                 // No buses use this device; throw it away.
207                 return true;
208         }
209
210         unsigned num_channels = device->interesting_channels.size();
211         assert(num_channels > 0);
212
213         // Convert the audio to fp32.
214         vector<float> audio;
215         audio.resize(num_samples * num_channels);
216         unsigned channel_index = 0;
217         for (auto channel_it = device->interesting_channels.cbegin(); channel_it != device->interesting_channels.end(); ++channel_it, ++channel_index) {
218                 switch (audio_format.bits_per_sample) {
219                 case 0:
220                         assert(num_samples == 0);
221                         break;
222                 case 16:
223                         convert_fixed16_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
224                         break;
225                 case 24:
226                         convert_fixed24_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
227                         break;
228                 case 32:
229                         convert_fixed32_to_fp32(&audio[0], channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
230                         break;
231                 default:
232                         fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
233                         assert(false);
234                 }
235         }
236
237         // Now add it.
238         int64_t local_pts = device->next_local_pts;
239         device->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.data(), num_samples);
240         device->next_local_pts = local_pts + frame_length;
241         return true;
242 }
243
244 bool AudioMixer::add_silence(DeviceSpec device_spec, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
245 {
246         AudioDevice *device = find_audio_device(device_spec);
247
248         unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
249         if (!lock.try_lock_for(chrono::milliseconds(10))) {
250                 return false;
251         }
252         if (device->resampling_queue == nullptr) {
253                 // No buses use this device; throw it away.
254                 return true;
255         }
256
257         unsigned num_channels = device->interesting_channels.size();
258         assert(num_channels > 0);
259
260         vector<float> silence(samples_per_frame * num_channels, 0.0f);
261         for (unsigned i = 0; i < num_frames; ++i) {
262                 device->resampling_queue->add_input_samples(device->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame);
263                 // Note that if the format changed in the meantime, we have
264                 // no way of detecting that; we just have to assume the frame length
265                 // is always the same.
266                 device->next_local_pts += frame_length;
267         }
268         return true;
269 }
270
271 AudioMixer::AudioDevice *AudioMixer::find_audio_device(DeviceSpec device)
272 {
273         switch (device.type) {
274         case InputSourceType::CAPTURE_CARD:
275                 return &video_cards[device.index];
276         case InputSourceType::ALSA_INPUT:
277                 return &alsa_inputs[device.index];
278         case InputSourceType::SILENCE:
279         default:
280                 assert(false);
281         }
282         return nullptr;
283 }
284
285 // Get a pointer to the given channel from the given device.
286 // The channel must be picked out earlier and resampled.
287 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)
288 {
289         static float zero = 0.0f;
290         if (source_channel == -1 || device_spec.type == InputSourceType::SILENCE) {
291                 *srcptr = &zero;
292                 *stride = 0;
293                 return;
294         }
295         AudioDevice *device = find_audio_device(device_spec);
296         assert(device->interesting_channels.count(source_channel) != 0);
297         unsigned channel_index = 0;
298         for (int channel : device->interesting_channels) {
299                 if (channel == source_channel) break;
300                 ++channel_index;
301         }
302         assert(channel_index < device->interesting_channels.size());
303         const auto it = samples_card.find(device_spec);
304         assert(it != samples_card.end());
305         *srcptr = &(it->second)[channel_index];
306         *stride = device->interesting_channels.size();
307 }
308
309 // TODO: Can be SSSE3-optimized if need be.
310 void AudioMixer::fill_audio_bus(const map<DeviceSpec, vector<float>> &samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output)
311 {
312         if (bus.device.type == InputSourceType::SILENCE) {
313                 memset(output, 0, num_samples * sizeof(*output));
314         } else {
315                 assert(bus.device.type == InputSourceType::CAPTURE_CARD ||
316                        bus.device.type == InputSourceType::ALSA_INPUT);
317                 const float *lsrc, *rsrc;
318                 unsigned lstride, rstride;
319                 float *dptr = output;
320                 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[0], &lsrc, &lstride);
321                 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[1], &rsrc, &rstride);
322                 for (unsigned i = 0; i < num_samples; ++i) {
323                         *dptr++ = *lsrc;
324                         *dptr++ = *rsrc;
325                         lsrc += lstride;
326                         rsrc += rstride;
327                 }
328         }
329 }
330
331 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
332 {
333         map<DeviceSpec, vector<float>> samples_card;
334         vector<float> samples_bus;
335
336         lock_guard<timed_mutex> lock(audio_mutex);
337
338         // Pick out all the interesting channels from all the cards.
339         // TODO: If the card has been hotswapped, the number of channels
340         // might have changed; if so, we need to do some sort of remapping
341         // to silence.
342         for (const auto &spec_and_info : get_devices_mutex_held()) {
343                 const DeviceSpec &device_spec = spec_and_info.first;
344                 AudioDevice *device = find_audio_device(device_spec);
345                 if (!device->interesting_channels.empty()) {
346                         samples_card[device_spec].resize(num_samples * device->interesting_channels.size());
347                         device->resampling_queue->get_output_samples(
348                                 pts,
349                                 &samples_card[device_spec][0],
350                                 num_samples,
351                                 rate_adjustment_policy);
352                 }
353         }
354
355         vector<float> samples_out, left, right;
356         samples_out.resize(num_samples * 2);
357         samples_bus.resize(num_samples * 2);
358         for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
359                 fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]);
360
361                 // Cut away everything under 120 Hz (or whatever the cutoff is);
362                 // we don't need it for voice, and it will reduce headroom
363                 // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
364                 // should be dampened.)
365                 if (locut_enabled[bus_index]) {
366                         locut[bus_index].render(samples_bus.data(), samples_bus.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
367                 }
368
369                 {
370                         lock_guard<mutex> lock(compressor_mutex);
371
372                         // Apply a level compressor to get the general level right.
373                         // Basically, if it's over about -40 dBFS, we squeeze it down to that level
374                         // (or more precisely, near it, since we don't use infinite ratio),
375                         // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
376                         // entirely arbitrary, but from practical tests with speech, it seems to
377                         // put ut around -23 LUFS, so it's a reasonable starting point for later use.
378                         if (level_compressor_enabled[bus_index]) {
379                                 float threshold = 0.01f;   // -40 dBFS.
380                                 float ratio = 20.0f;
381                                 float attack_time = 0.5f;
382                                 float release_time = 20.0f;
383                                 float makeup_gain = from_db(ref_level_dbfs - (-40.0f));  // +26 dB.
384                                 level_compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
385                                 gain_staging_db[bus_index] = to_db(level_compressor[bus_index]->get_attenuation() * makeup_gain);
386                         } else {
387                                 // Just apply the gain we already had.
388                                 float g = from_db(gain_staging_db[bus_index]);
389                                 for (size_t i = 0; i < samples_bus.size(); ++i) {
390                                         samples_bus[i] *= g;
391                                 }
392                         }
393
394 #if 0
395                         printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
396                                 level_compressor.get_level(), to_db(level_compressor.get_level()),
397                                 level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
398                                 to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
399 #endif
400
401                         // The real compressor.
402                         if (compressor_enabled[bus_index]) {
403                                 float threshold = from_db(compressor_threshold_dbfs[bus_index]);
404                                 float ratio = 20.0f;
405                                 float attack_time = 0.005f;
406                                 float release_time = 0.040f;
407                                 float makeup_gain = 2.0f;  // +6 dB.
408                                 compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
409                 //              compressor_att = compressor.get_attenuation();
410                         }
411                 }
412
413                 // TODO: We should measure post-fader.
414                 deinterleave_samples(samples_bus, &left, &right);
415                 measure_bus_levels(bus_index, left, right);
416
417                 float volume = from_db(fader_volume_db[bus_index]);
418                 if (bus_index == 0) {
419                         for (unsigned i = 0; i < num_samples * 2; ++i) {
420                                 samples_out[i] = samples_bus[i] * volume;
421                         }
422                 } else {
423                         for (unsigned i = 0; i < num_samples * 2; ++i) {
424                                 samples_out[i] += samples_bus[i] * volume;
425                         }
426                 }
427         }
428
429         {
430                 lock_guard<mutex> lock(compressor_mutex);
431
432                 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
433                 // Note that since ratio is not infinite, we could go slightly higher than this.
434                 if (limiter_enabled) {
435                         float threshold = from_db(limiter_threshold_dbfs);
436                         float ratio = 30.0f;
437                         float attack_time = 0.0f;  // Instant.
438                         float release_time = 0.020f;
439                         float makeup_gain = 1.0f;  // 0 dB.
440                         limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
441         //              limiter_att = limiter.get_attenuation();
442                 }
443
444         //      printf("limiter=%+5.1f  compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
445         }
446
447         // At this point, we are most likely close to +0 LU (at least if the
448         // faders sum to 0 dB and the compressors are on), but all of our
449         // measurements have been on raw sample values, not R128 values.
450         // So we have a final makeup gain to get us to +0 LU; the gain
451         // adjustments required should be relatively small, and also, the
452         // offset shouldn't change much (only if the type of audio changes
453         // significantly). Thus, we shoot for updating this value basically
454         // “whenever we process buffers”, since the R128 calculation isn't exactly
455         // something we get out per-sample.
456         //
457         // Note that there's a feedback loop here, so we choose a very slow filter
458         // (half-time of 30 seconds).
459         double target_loudness_factor, alpha;
460         double loudness_lu = r128.loudness_M() - ref_level_lufs;
461         double current_makeup_lu = to_db(final_makeup_gain);
462         target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
463
464         // If we're outside +/- 5 LU uncorrected, we don't count it as
465         // a normal signal (probably silence) and don't change the
466         // correction factor; just apply what we already have.
467         if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
468                 alpha = 0.0;
469         } else {
470                 // Formula adapted from
471                 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
472                 const double half_time_s = 30.0;
473                 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
474                 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
475         }
476
477         {
478                 lock_guard<mutex> lock(compressor_mutex);
479                 double m = final_makeup_gain;
480                 for (size_t i = 0; i < samples_out.size(); i += 2) {
481                         samples_out[i + 0] *= m;
482                         samples_out[i + 1] *= m;
483                         m += (target_loudness_factor - m) * alpha;
484                 }
485                 final_makeup_gain = m;
486         }
487
488         update_meters(samples_out);
489
490         return samples_out;
491 }
492
493 void AudioMixer::measure_bus_levels(unsigned bus_index, const vector<float> &left, const vector<float> &right)
494 {
495         const float *ptrs[] = { left.data(), right.data() };
496         {
497                 lock_guard<mutex> lock(audio_measure_mutex);
498                 bus_r128[bus_index]->process(left.size(), const_cast<float **>(ptrs));
499         }
500 }
501
502 void AudioMixer::update_meters(const vector<float> &samples)
503 {
504         // Upsample 4x to find interpolated peak.
505         peak_resampler.inp_data = const_cast<float *>(samples.data());
506         peak_resampler.inp_count = samples.size() / 2;
507
508         vector<float> interpolated_samples;
509         interpolated_samples.resize(samples.size());
510         {
511                 lock_guard<mutex> lock(audio_measure_mutex);
512
513                 while (peak_resampler.inp_count > 0) {  // About four iterations.
514                         peak_resampler.out_data = &interpolated_samples[0];
515                         peak_resampler.out_count = interpolated_samples.size() / 2;
516                         peak_resampler.process();
517                         size_t out_stereo_samples = interpolated_samples.size() / 2 - peak_resampler.out_count;
518                         peak = max<float>(peak, find_peak(interpolated_samples.data(), out_stereo_samples * 2));
519                         peak_resampler.out_data = nullptr;
520                 }
521         }
522
523         // Find R128 levels and L/R correlation.
524         vector<float> left, right;
525         deinterleave_samples(samples, &left, &right);
526         float *ptrs[] = { left.data(), right.data() };
527         {
528                 lock_guard<mutex> lock(audio_measure_mutex);
529                 r128.process(left.size(), ptrs);
530                 correlation.process_samples(samples);
531         }
532
533         send_audio_level_callback();
534 }
535
536 void AudioMixer::reset_meters()
537 {
538         lock_guard<mutex> lock(audio_measure_mutex);
539         peak_resampler.reset();
540         peak = 0.0f;
541         r128.reset();
542         r128.integr_start();
543         correlation.reset();
544 }
545
546 void AudioMixer::send_audio_level_callback()
547 {
548         if (audio_level_callback == nullptr) {
549                 return;
550         }
551
552         lock_guard<mutex> lock(audio_measure_mutex);
553         double loudness_s = r128.loudness_S();
554         double loudness_i = r128.integrated();
555         double loudness_range_low = r128.range_min();
556         double loudness_range_high = r128.range_max();
557
558         vector<BusLevel> bus_levels;
559         bus_levels.resize(input_mapping.buses.size());
560         {
561                 lock_guard<mutex> lock(compressor_mutex);
562                 for (unsigned bus_index = 0; bus_index < bus_r128.size(); ++bus_index) {
563                         bus_levels[bus_index].loudness_lufs = bus_r128[bus_index]->loudness_S();
564                         bus_levels[bus_index].gain_staging_db = gain_staging_db[bus_index];
565                         if (compressor_enabled[bus_index]) {
566                                 bus_levels[bus_index].compressor_attenuation_db = -to_db(compressor[bus_index]->get_attenuation());
567                         } else {
568                                 bus_levels[bus_index].compressor_attenuation_db = 0.0;
569                         }
570                 }
571         }
572
573         audio_level_callback(loudness_s, to_db(peak), bus_levels,
574                 loudness_i, loudness_range_low, loudness_range_high,
575                 to_db(final_makeup_gain),
576                 correlation.get_correlation());
577 }
578
579 map<DeviceSpec, DeviceInfo> AudioMixer::get_devices() const
580 {
581         lock_guard<timed_mutex> lock(audio_mutex);
582         return get_devices_mutex_held();
583 }
584
585 map<DeviceSpec, DeviceInfo> AudioMixer::get_devices_mutex_held() const
586 {
587         map<DeviceSpec, DeviceInfo> devices;
588         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
589                 const DeviceSpec spec{ InputSourceType::CAPTURE_CARD, card_index };
590                 const AudioDevice *device = &video_cards[card_index];
591                 DeviceInfo info;
592                 info.name = device->name;
593                 info.num_channels = 8;  // FIXME: This is wrong for fake cards.
594                 devices.insert(make_pair(spec, info));
595         }
596         for (unsigned card_index = 0; card_index < available_alsa_cards.size(); ++card_index) {
597                 const DeviceSpec spec{ InputSourceType::ALSA_INPUT, card_index };
598                 const ALSAInput::Device &device = available_alsa_cards[card_index];
599                 DeviceInfo info;
600                 info.name = device.name + " (" + device.info + ")";
601                 info.num_channels = device.num_channels;
602                 devices.insert(make_pair(spec, info));
603         }
604         return devices;
605 }
606
607 void AudioMixer::set_name(DeviceSpec device_spec, const string &name)
608 {
609         AudioDevice *device = find_audio_device(device_spec);
610
611         lock_guard<timed_mutex> lock(audio_mutex);
612         device->name = name;
613 }
614
615 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
616 {
617         lock_guard<timed_mutex> lock(audio_mutex);
618
619         map<DeviceSpec, set<unsigned>> interesting_channels;
620         for (const InputMapping::Bus &bus : new_input_mapping.buses) {
621                 if (bus.device.type == InputSourceType::CAPTURE_CARD ||
622                     bus.device.type == InputSourceType::ALSA_INPUT) {
623                         for (unsigned channel = 0; channel < 2; ++channel) {
624                                 if (bus.source_channel[channel] != -1) {
625                                         interesting_channels[bus.device].insert(bus.source_channel[channel]);
626                                 }
627                         }
628                 }
629         }
630
631         // Reset resamplers for all cards that don't have the exact same state as before.
632         for (const auto &spec_and_info : get_devices_mutex_held()) {
633                 const DeviceSpec &device_spec = spec_and_info.first;
634                 AudioDevice *device = find_audio_device(device_spec);
635                 if (device->interesting_channels != interesting_channels[device_spec]) {
636                         device->interesting_channels = interesting_channels[device_spec];
637                         if (device_spec.type == InputSourceType::ALSA_INPUT) {
638                                 reset_alsa_mutex_held(device_spec);
639                         }
640                         reset_resampler_mutex_held(device_spec);
641                 }
642         }
643
644         {
645                 lock_guard<mutex> lock(audio_measure_mutex);
646                 bus_r128.resize(new_input_mapping.buses.size());
647                 for (unsigned bus_index = 0; bus_index < bus_r128.size(); ++bus_index) {
648                         if (bus_r128[bus_index] == nullptr) {
649                                 bus_r128[bus_index].reset(new Ebu_r128_proc);
650                         }
651                         bus_r128[bus_index]->init(2, OUTPUT_FREQUENCY);
652                 }
653         }
654
655         input_mapping = new_input_mapping;
656 }
657
658 InputMapping AudioMixer::get_input_mapping() const
659 {
660         lock_guard<timed_mutex> lock(audio_mutex);
661         return input_mapping;
662 }