]> git.sesse.net Git - nageru/blob - audio_mixer.cpp
Reset audio resampler when FFmpeg inputs restart due to errors.
[nageru] / audio_mixer.cpp
1 #include "audio_mixer.h"
2
3 #include <assert.h>
4 #include <bmusb/bmusb.h>
5 #include <endian.h>
6 #include <math.h>
7 #ifdef __SSE2__
8 #include <immintrin.h>
9 #endif
10 #include <stdbool.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <algorithm>
15 #include <chrono>
16 #include <cmath>
17 #include <cstddef>
18 #include <limits>
19 #include <utility>
20
21 #include "db.h"
22 #include "flags.h"
23 #include "metrics.h"
24 #include "state.pb.h"
25 #include "timebase.h"
26
27 using namespace bmusb;
28 using namespace std;
29 using namespace std::chrono;
30 using namespace std::placeholders;
31
32 namespace {
33
34 // TODO: If these prove to be a bottleneck, they can be SSSE3-optimized
35 // (usually including multiple channels at a time).
36
37 void convert_fixed16_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
38                              const uint8_t *src, size_t in_channel, size_t in_num_channels,
39                              size_t num_samples)
40 {
41         assert(in_channel < in_num_channels);
42         assert(out_channel < out_num_channels);
43         src += in_channel * 2;
44         dst += out_channel;
45
46         for (size_t i = 0; i < num_samples; ++i) {
47                 int16_t s = le16toh(*(int16_t *)src);
48                 *dst = s * (1.0f / 32768.0f);
49
50                 src += 2 * in_num_channels;
51                 dst += out_num_channels;
52         }
53 }
54
55 void convert_fixed24_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
56                              const uint8_t *src, size_t in_channel, size_t in_num_channels,
57                              size_t num_samples)
58 {
59         assert(in_channel < in_num_channels);
60         assert(out_channel < out_num_channels);
61         src += in_channel * 3;
62         dst += out_channel;
63
64         for (size_t i = 0; i < num_samples; ++i) {
65                 uint32_t s1 = src[0];
66                 uint32_t s2 = src[1];
67                 uint32_t s3 = src[2];
68                 uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
69                 *dst = int(s) * (1.0f / 2147483648.0f);
70
71                 src += 3 * in_num_channels;
72                 dst += out_num_channels;
73         }
74 }
75
76 void convert_fixed32_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
77                              const uint8_t *src, size_t in_channel, size_t in_num_channels,
78                              size_t num_samples)
79 {
80         assert(in_channel < in_num_channels);
81         assert(out_channel < out_num_channels);
82         src += in_channel * 4;
83         dst += out_channel;
84
85         for (size_t i = 0; i < num_samples; ++i) {
86                 int32_t s = le32toh(*(int32_t *)src);
87                 *dst = s * (1.0f / 2147483648.0f);
88
89                 src += 4 * in_num_channels;
90                 dst += out_num_channels;
91         }
92 }
93
94 float find_peak_plain(const float *samples, size_t num_samples) __attribute__((unused));
95
96 float find_peak_plain(const float *samples, size_t num_samples)
97 {
98         float m = fabs(samples[0]);
99         for (size_t i = 1; i < num_samples; ++i) {
100                 m = max(m, fabs(samples[i]));
101         }
102         return m;
103 }
104
105 #ifdef __SSE__
106 static inline float horizontal_max(__m128 m)
107 {
108         __m128 tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 0, 3, 2));
109         m = _mm_max_ps(m, tmp);
110         tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 3, 0, 1));
111         m = _mm_max_ps(m, tmp);
112         return _mm_cvtss_f32(m);
113 }
114
115 float find_peak(const float *samples, size_t num_samples)
116 {
117         const __m128 abs_mask = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffu));
118         __m128 m = _mm_setzero_ps();
119         for (size_t i = 0; i < (num_samples & ~3); i += 4) {
120                 __m128 x = _mm_loadu_ps(samples + i);
121                 x = _mm_and_ps(x, abs_mask);
122                 m = _mm_max_ps(m, x);
123         }
124         float result = horizontal_max(m);
125
126         for (size_t i = (num_samples & ~3); i < num_samples; ++i) {
127                 result = max(result, fabs(samples[i]));
128         }
129
130 #if 0
131         // Self-test. We should be bit-exact the same.
132         float reference_result = find_peak_plain(samples, num_samples);
133         if (result != reference_result) {
134                 fprintf(stderr, "Error: Peak is %f [%f %f %f %f]; should be %f.\n",
135                         result,
136                         _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(0, 0, 0, 0))),
137                         _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1))),
138                         _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 2, 2, 2))),
139                         _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(3, 3, 3, 3))),
140                         reference_result);
141                 abort();
142         }
143 #endif
144         return result;
145 }
146 #else
147 float find_peak(const float *samples, size_t num_samples)
148 {
149         return find_peak_plain(samples, num_samples);
150 }
151 #endif
152
153 void deinterleave_samples(const vector<float> &in, vector<float> *out_l, vector<float> *out_r)
154 {
155         size_t num_samples = in.size() / 2;
156         out_l->resize(num_samples);
157         out_r->resize(num_samples);
158
159         const float *inptr = in.data();
160         float *lptr = &(*out_l)[0];
161         float *rptr = &(*out_r)[0];
162         for (size_t i = 0; i < num_samples; ++i) {
163                 *lptr++ = *inptr++;
164                 *rptr++ = *inptr++;
165         }
166 }
167
168 }  // namespace
169
170 AudioMixer::AudioMixer(unsigned num_cards)
171         : num_cards(num_cards),
172           limiter(OUTPUT_FREQUENCY),
173           correlation(OUTPUT_FREQUENCY)
174 {
175         for (unsigned bus_index = 0; bus_index < MAX_BUSES; ++bus_index) {
176                 locut[bus_index].init(FILTER_HPF, 2);
177                 eq[bus_index][EQ_BAND_BASS].init(FILTER_LOW_SHELF, 1);
178                 // Note: EQ_BAND_MID isn't used (see comments in apply_eq()).
179                 eq[bus_index][EQ_BAND_TREBLE].init(FILTER_HIGH_SHELF, 1);
180                 compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
181                 level_compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
182
183                 set_bus_settings(bus_index, get_default_bus_settings());
184         }
185         set_limiter_enabled(global_flags.limiter_enabled);
186         set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
187
188         r128.init(2, OUTPUT_FREQUENCY);
189         r128.integr_start();
190
191         // hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise,
192         // and there's a limit to how important the peak meter is.
193         peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0);
194
195         global_audio_mixer = this;
196         alsa_pool.init();
197
198         if (!global_flags.input_mapping_filename.empty()) {
199                 // Must happen after ALSAPool is initialized, as it needs to know the card list.
200                 current_mapping_mode = MappingMode::MULTICHANNEL;
201                 InputMapping new_input_mapping;
202                 if (!load_input_mapping_from_file(get_devices(),
203                                                   global_flags.input_mapping_filename,
204                                                   &new_input_mapping)) {
205                         fprintf(stderr, "Failed to load input mapping from '%s', exiting.\n",
206                                 global_flags.input_mapping_filename.c_str());
207                         exit(1);
208                 }
209                 set_input_mapping(new_input_mapping);
210         } else {
211                 set_simple_input(/*card_index=*/0);
212                 if (global_flags.multichannel_mapping_mode) {
213                         current_mapping_mode = MappingMode::MULTICHANNEL;
214                 }
215         }
216
217         global_metrics.add("audio_loudness_short_lufs", &metric_audio_loudness_short_lufs, Metrics::TYPE_GAUGE);
218         global_metrics.add("audio_loudness_integrated_lufs", &metric_audio_loudness_integrated_lufs, Metrics::TYPE_GAUGE);
219         global_metrics.add("audio_loudness_range_low_lufs", &metric_audio_loudness_range_low_lufs, Metrics::TYPE_GAUGE);
220         global_metrics.add("audio_loudness_range_high_lufs", &metric_audio_loudness_range_high_lufs, Metrics::TYPE_GAUGE);
221         global_metrics.add("audio_peak_dbfs", &metric_audio_peak_dbfs, Metrics::TYPE_GAUGE);
222         global_metrics.add("audio_final_makeup_gain_db", &metric_audio_final_makeup_gain_db, Metrics::TYPE_GAUGE);
223         global_metrics.add("audio_correlation", &metric_audio_correlation, Metrics::TYPE_GAUGE);
224 }
225
226 void AudioMixer::reset_resampler(DeviceSpec device_spec)
227 {
228         lock_guard<timed_mutex> lock(audio_mutex);
229         reset_resampler_mutex_held(device_spec);
230 }
231
232 void AudioMixer::reset_resampler_mutex_held(DeviceSpec device_spec)
233 {
234         AudioDevice *device = find_audio_device(device_spec);
235
236         if (device->interesting_channels.empty()) {
237                 device->resampling_queue.reset();
238         } else {
239                 device->resampling_queue.reset(new ResamplingQueue(
240                         device_spec, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size(),
241                         global_flags.audio_queue_length_ms * 0.001));
242         }
243 }
244
245 bool AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length, steady_clock::time_point frame_time)
246 {
247         AudioDevice *device = find_audio_device(device_spec);
248
249         unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
250         if (!lock.try_lock_for(chrono::milliseconds(10))) {
251                 return false;
252         }
253         if (device->resampling_queue == nullptr) {
254                 // No buses use this device; throw it away.
255                 return true;
256         }
257
258         unsigned num_channels = device->interesting_channels.size();
259         assert(num_channels > 0);
260
261         // Convert the audio to fp32.
262         unique_ptr<float[]> audio(new float[num_samples * num_channels]);
263         unsigned channel_index = 0;
264         for (auto channel_it = device->interesting_channels.cbegin(); channel_it != device->interesting_channels.end(); ++channel_it, ++channel_index) {
265                 switch (audio_format.bits_per_sample) {
266                 case 0:
267                         assert(num_samples == 0);
268                         break;
269                 case 16:
270                         convert_fixed16_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
271                         break;
272                 case 24:
273                         convert_fixed24_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
274                         break;
275                 case 32:
276                         convert_fixed32_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
277                         break;
278                 default:
279                         fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
280                         assert(false);
281                 }
282         }
283
284         // If we changed frequency since last frame, we'll need to reset the resampler.
285         if (audio_format.sample_rate != device->capture_frequency) {
286                 device->capture_frequency = audio_format.sample_rate;
287                 reset_resampler_mutex_held(device_spec);
288         }
289
290         // Now add it.
291         device->resampling_queue->add_input_samples(frame_time, audio.get(), num_samples, ResamplingQueue::ADJUST_RATE);
292         return true;
293 }
294
295 bool AudioMixer::add_silence(DeviceSpec device_spec, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
296 {
297         AudioDevice *device = find_audio_device(device_spec);
298
299         unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
300         if (!lock.try_lock_for(chrono::milliseconds(10))) {
301                 return false;
302         }
303         if (device->resampling_queue == nullptr) {
304                 // No buses use this device; throw it away.
305                 return true;
306         }
307
308         unsigned num_channels = device->interesting_channels.size();
309         assert(num_channels > 0);
310
311         vector<float> silence(samples_per_frame * num_channels, 0.0f);
312         for (unsigned i = 0; i < num_frames; ++i) {
313                 device->resampling_queue->add_input_samples(steady_clock::now(), silence.data(), samples_per_frame, ResamplingQueue::DO_NOT_ADJUST_RATE);
314         }
315         return true;
316 }
317
318 bool AudioMixer::silence_card(DeviceSpec device_spec, bool silence)
319 {
320         AudioDevice *device = find_audio_device(device_spec);
321
322         unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
323         if (!lock.try_lock_for(chrono::milliseconds(10))) {
324                 return false;
325         }
326
327         if (device->silenced && !silence) {
328                 reset_resampler_mutex_held(device_spec);
329         }
330         device->silenced = silence;
331         return true;
332 }
333
334 AudioMixer::BusSettings AudioMixer::get_default_bus_settings()
335 {
336         BusSettings settings;
337         settings.fader_volume_db = 0.0f;
338         settings.muted = false;
339         settings.locut_enabled = global_flags.locut_enabled;
340         for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
341                 settings.eq_level_db[band_index] = 0.0f;
342         }
343         settings.gain_staging_db = global_flags.initial_gain_staging_db;
344         settings.level_compressor_enabled = global_flags.gain_staging_auto;
345         settings.compressor_threshold_dbfs = ref_level_dbfs - 12.0f;  // -12 dB.
346         settings.compressor_enabled = global_flags.compressor_enabled;
347         return settings;
348 }
349
350 AudioMixer::BusSettings AudioMixer::get_bus_settings(unsigned bus_index) const
351 {
352         lock_guard<timed_mutex> lock(audio_mutex);
353         BusSettings settings;
354         settings.fader_volume_db = fader_volume_db[bus_index];
355         settings.muted = mute[bus_index];
356         settings.locut_enabled = locut_enabled[bus_index];
357         for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
358                 settings.eq_level_db[band_index] = eq_level_db[bus_index][band_index];
359         }
360         settings.gain_staging_db = gain_staging_db[bus_index];
361         settings.level_compressor_enabled = level_compressor_enabled[bus_index];
362         settings.compressor_threshold_dbfs = compressor_threshold_dbfs[bus_index];
363         settings.compressor_enabled = compressor_enabled[bus_index];
364         return settings;
365 }
366
367 void AudioMixer::set_bus_settings(unsigned bus_index, const AudioMixer::BusSettings &settings)
368 {
369         lock_guard<timed_mutex> lock(audio_mutex);
370         fader_volume_db[bus_index] = settings.fader_volume_db;
371         mute[bus_index] = settings.muted;
372         locut_enabled[bus_index] = settings.locut_enabled;
373         for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
374                 eq_level_db[bus_index][band_index] = settings.eq_level_db[band_index];
375         }
376         gain_staging_db[bus_index] = settings.gain_staging_db;
377         last_gain_staging_db[bus_index] = gain_staging_db[bus_index];
378         level_compressor_enabled[bus_index] = settings.level_compressor_enabled;
379         compressor_threshold_dbfs[bus_index] = settings.compressor_threshold_dbfs;
380         compressor_enabled[bus_index] = settings.compressor_enabled;
381 }
382
383 AudioMixer::AudioDevice *AudioMixer::find_audio_device(DeviceSpec device)
384 {
385         switch (device.type) {
386         case InputSourceType::CAPTURE_CARD:
387                 return &video_cards[device.index];
388         case InputSourceType::ALSA_INPUT:
389                 return &alsa_inputs[device.index];
390         case InputSourceType::SILENCE:
391         default:
392                 assert(false);
393         }
394         return nullptr;
395 }
396
397 // Get a pointer to the given channel from the given device.
398 // The channel must be picked out earlier and resampled.
399 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)
400 {
401         static float zero = 0.0f;
402         if (source_channel == -1 || device_spec.type == InputSourceType::SILENCE) {
403                 *srcptr = &zero;
404                 *stride = 0;
405                 return;
406         }
407         AudioDevice *device = find_audio_device(device_spec);
408         assert(device->interesting_channels.count(source_channel) != 0);
409         unsigned channel_index = 0;
410         for (int channel : device->interesting_channels) {
411                 if (channel == source_channel) break;
412                 ++channel_index;
413         }
414         assert(channel_index < device->interesting_channels.size());
415         const auto it = samples_card.find(device_spec);
416         assert(it != samples_card.end());
417         *srcptr = &(it->second)[channel_index];
418         *stride = device->interesting_channels.size();
419 }
420
421 // TODO: Can be SSSE3-optimized if need be.
422 void AudioMixer::fill_audio_bus(const map<DeviceSpec, vector<float>> &samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output)
423 {
424         if (bus.device.type == InputSourceType::SILENCE) {
425                 memset(output, 0, num_samples * 2 * sizeof(*output));
426         } else {
427                 assert(bus.device.type == InputSourceType::CAPTURE_CARD ||
428                        bus.device.type == InputSourceType::ALSA_INPUT);
429                 const float *lsrc, *rsrc;
430                 unsigned lstride, rstride;
431                 float *dptr = output;
432                 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[0], &lsrc, &lstride);
433                 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[1], &rsrc, &rstride);
434                 for (unsigned i = 0; i < num_samples; ++i) {
435                         *dptr++ = *lsrc;
436                         *dptr++ = *rsrc;
437                         lsrc += lstride;
438                         rsrc += rstride;
439                 }
440         }
441 }
442
443 vector<DeviceSpec> AudioMixer::get_active_devices() const
444 {
445         vector<DeviceSpec> ret;
446         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
447                 const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
448                 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
449                         ret.push_back(device_spec);
450                 }
451         }
452         for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
453                 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
454                 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
455                         ret.push_back(device_spec);
456                 }
457         }
458         return ret;
459 }
460
461 namespace {
462
463 void apply_gain(float db, float last_db, vector<float> *samples)
464 {
465         if (fabs(db - last_db) < 1e-3) {
466                 // Constant over this frame.
467                 const float gain = from_db(db);
468                 for (size_t i = 0; i < samples->size(); ++i) {
469                         (*samples)[i] *= gain;
470                 }
471         } else {
472                 // We need to do a fade.
473                 unsigned num_samples = samples->size() / 2;
474                 float gain = from_db(last_db);
475                 const float gain_inc = pow(from_db(db - last_db), 1.0 / num_samples);
476                 for (size_t i = 0; i < num_samples; ++i) {
477                         (*samples)[i * 2 + 0] *= gain;
478                         (*samples)[i * 2 + 1] *= gain;
479                         gain *= gain_inc;
480                 }
481         }
482 }
483
484 }  // namespace
485
486 vector<float> AudioMixer::get_output(steady_clock::time_point ts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
487 {
488         map<DeviceSpec, vector<float>> samples_card;
489         vector<float> samples_bus;
490
491         lock_guard<timed_mutex> lock(audio_mutex);
492
493         // Pick out all the interesting channels from all the cards.
494         for (const DeviceSpec &device_spec : get_active_devices()) {
495                 AudioDevice *device = find_audio_device(device_spec);
496                 samples_card[device_spec].resize(num_samples * device->interesting_channels.size());
497                 if (device->silenced) {
498                         memset(&samples_card[device_spec][0], 0, samples_card[device_spec].size() * sizeof(float));
499                 } else {
500                         device->resampling_queue->get_output_samples(
501                                 ts,
502                                 &samples_card[device_spec][0],
503                                 num_samples,
504                                 rate_adjustment_policy);
505                 }
506         }
507
508         vector<float> samples_out, left, right;
509         samples_out.resize(num_samples * 2);
510         samples_bus.resize(num_samples * 2);
511         for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
512                 fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]);
513                 apply_eq(bus_index, &samples_bus);
514
515                 {
516                         lock_guard<mutex> lock(compressor_mutex);
517
518                         // Apply a level compressor to get the general level right.
519                         // Basically, if it's over about -40 dBFS, we squeeze it down to that level
520                         // (or more precisely, near it, since we don't use infinite ratio),
521                         // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
522                         // entirely arbitrary, but from practical tests with speech, it seems to
523                         // put ut around -23 LUFS, so it's a reasonable starting point for later use.
524                         if (level_compressor_enabled[bus_index]) {
525                                 float threshold = 0.01f;   // -40 dBFS.
526                                 float ratio = 20.0f;
527                                 float attack_time = 0.5f;
528                                 float release_time = 20.0f;
529                                 float makeup_gain = from_db(ref_level_dbfs - (-40.0f));  // +26 dB.
530                                 level_compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
531                                 gain_staging_db[bus_index] = to_db(level_compressor[bus_index]->get_attenuation() * makeup_gain);
532                         } else {
533                                 // Just apply the gain we already had.
534                                 float db = gain_staging_db[bus_index];
535                                 float last_db = last_gain_staging_db[bus_index];
536                                 apply_gain(db, last_db, &samples_bus);
537                         }
538                         last_gain_staging_db[bus_index] = gain_staging_db[bus_index];
539
540 #if 0
541                         printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
542                                 level_compressor.get_level(), to_db(level_compressor.get_level()),
543                                 level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
544                                 to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
545 #endif
546
547                         // The real compressor.
548                         if (compressor_enabled[bus_index]) {
549                                 float threshold = from_db(compressor_threshold_dbfs[bus_index]);
550                                 float ratio = 20.0f;
551                                 float attack_time = 0.005f;
552                                 float release_time = 0.040f;
553                                 float makeup_gain = 2.0f;  // +6 dB.
554                                 compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
555                 //              compressor_att = compressor.get_attenuation();
556                         }
557                 }
558
559                 add_bus_to_master(bus_index, samples_bus, &samples_out);
560                 deinterleave_samples(samples_bus, &left, &right);
561                 measure_bus_levels(bus_index, left, right);
562         }
563
564         {
565                 lock_guard<mutex> lock(compressor_mutex);
566
567                 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
568                 // Note that since ratio is not infinite, we could go slightly higher than this.
569                 if (limiter_enabled) {
570                         float threshold = from_db(limiter_threshold_dbfs);
571                         float ratio = 30.0f;
572                         float attack_time = 0.0f;  // Instant.
573                         float release_time = 0.020f;
574                         float makeup_gain = 1.0f;  // 0 dB.
575                         limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
576         //              limiter_att = limiter.get_attenuation();
577                 }
578
579         //      printf("limiter=%+5.1f  compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
580         }
581
582         // At this point, we are most likely close to +0 LU (at least if the
583         // faders sum to 0 dB and the compressors are on), but all of our
584         // measurements have been on raw sample values, not R128 values.
585         // So we have a final makeup gain to get us to +0 LU; the gain
586         // adjustments required should be relatively small, and also, the
587         // offset shouldn't change much (only if the type of audio changes
588         // significantly). Thus, we shoot for updating this value basically
589         // “whenever we process buffers”, since the R128 calculation isn't exactly
590         // something we get out per-sample.
591         //
592         // Note that there's a feedback loop here, so we choose a very slow filter
593         // (half-time of 30 seconds).
594         double target_loudness_factor, alpha;
595         double loudness_lu = r128.loudness_M() - ref_level_lufs;
596         target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
597
598         // If we're outside +/- 5 LU (after correction), we don't count it as
599         // a normal signal (probably silence) and don't change the
600         // correction factor; just apply what we already have.
601         if (fabs(loudness_lu) >= 5.0 || !final_makeup_gain_auto) {
602                 alpha = 0.0;
603         } else {
604                 // Formula adapted from
605                 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
606                 const double half_time_s = 30.0;
607                 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
608                 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
609         }
610
611         {
612                 lock_guard<mutex> lock(compressor_mutex);
613                 double m = final_makeup_gain;
614                 for (size_t i = 0; i < samples_out.size(); i += 2) {
615                         samples_out[i + 0] *= m;
616                         samples_out[i + 1] *= m;
617                         m += (target_loudness_factor - m) * alpha;
618                 }
619                 final_makeup_gain = m;
620         }
621
622         update_meters(samples_out);
623
624         return samples_out;
625 }
626
627 namespace {
628
629 void apply_filter_fade(StereoFilter *filter, float *data, unsigned num_samples, float cutoff_hz, float db, float last_db)
630 {
631         // A granularity of 32 samples is an okay tradeoff between speed and
632         // smoothness; recalculating the filters is pretty expensive, so it's
633         // good that we don't do this all the time.
634         static constexpr unsigned filter_granularity_samples = 32;
635
636         const float cutoff_linear = cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY;
637         if (fabs(db - last_db) < 1e-3) {
638                 // Constant over this frame.
639                 if (fabs(db) > 0.01f) {
640                         filter->render(data, num_samples, cutoff_linear, 0.5f, db / 40.0f);
641                 }
642         } else {
643                 // We need to do a fade. (Rounding up avoids division by zero.)
644                 unsigned num_blocks = (num_samples + filter_granularity_samples - 1) / filter_granularity_samples;
645                 const float inc_db_norm = (db - last_db) / 40.0f / num_blocks;
646                 float db_norm = db / 40.0f;
647                 for (size_t i = 0; i < num_samples; i += filter_granularity_samples) {
648                         size_t samples_this_block = std::min<size_t>(num_samples - i, filter_granularity_samples);
649                         filter->render(data + i * 2, samples_this_block, cutoff_linear, 0.5f, db_norm);
650                         db_norm += inc_db_norm;
651                 }
652         }
653 }
654
655 }  // namespace
656
657 void AudioMixer::apply_eq(unsigned bus_index, vector<float> *samples_bus)
658 {
659         constexpr float bass_freq_hz = 200.0f;
660         constexpr float treble_freq_hz = 4700.0f;
661
662         // Cut away everything under 120 Hz (or whatever the cutoff is);
663         // we don't need it for voice, and it will reduce headroom
664         // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
665         // should be dampened.)
666         if (locut_enabled[bus_index]) {
667                 locut[bus_index].render(samples_bus->data(), samples_bus->size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
668         }
669
670         // Apply the rest of the EQ. Since we only have a simple three-band EQ,
671         // we can implement it with two shelf filters. We use a simple gain to
672         // set the mid-level filter, and then offset the low and high bands
673         // from that if we need to. (We could perhaps have folded the gain into
674         // the next part, but it's so cheap that the trouble isn't worth it.)
675         //
676         // If any part of the EQ has changed appreciably since last frame,
677         // we fade smoothly during the course of this frame.
678         const float bass_db = eq_level_db[bus_index][EQ_BAND_BASS];
679         const float mid_db = eq_level_db[bus_index][EQ_BAND_MID];
680         const float treble_db = eq_level_db[bus_index][EQ_BAND_TREBLE];
681
682         const float last_bass_db = last_eq_level_db[bus_index][EQ_BAND_BASS];
683         const float last_mid_db = last_eq_level_db[bus_index][EQ_BAND_MID];
684         const float last_treble_db = last_eq_level_db[bus_index][EQ_BAND_TREBLE];
685
686         assert(samples_bus->size() % 2 == 0);
687         const unsigned num_samples = samples_bus->size() / 2;
688
689         apply_gain(mid_db, last_mid_db, samples_bus);
690
691         apply_filter_fade(&eq[bus_index][EQ_BAND_BASS], samples_bus->data(), num_samples, bass_freq_hz, bass_db - mid_db, last_bass_db - last_mid_db);
692         apply_filter_fade(&eq[bus_index][EQ_BAND_TREBLE], samples_bus->data(), num_samples, treble_freq_hz, treble_db - mid_db, last_treble_db - last_mid_db);
693
694         last_eq_level_db[bus_index][EQ_BAND_BASS] = bass_db;
695         last_eq_level_db[bus_index][EQ_BAND_MID] = mid_db;
696         last_eq_level_db[bus_index][EQ_BAND_TREBLE] = treble_db;
697 }
698
699 void AudioMixer::add_bus_to_master(unsigned bus_index, const vector<float> &samples_bus, vector<float> *samples_out)
700 {
701         assert(samples_bus.size() == samples_out->size());
702         assert(samples_bus.size() % 2 == 0);
703         unsigned num_samples = samples_bus.size() / 2;
704         const float new_volume_db = mute[bus_index] ? -90.0f : fader_volume_db[bus_index].load();
705         if (fabs(new_volume_db - last_fader_volume_db[bus_index]) > 1e-3) {
706                 // The volume has changed; do a fade over the course of this frame.
707                 // (We might have some numerical issues here, but it seems to sound OK.)
708                 // For the purpose of fading here, the silence floor is set to -90 dB
709                 // (the fader only goes to -84).
710                 float old_volume = from_db(max<float>(last_fader_volume_db[bus_index], -90.0f));
711                 float volume = from_db(max<float>(new_volume_db, -90.0f));
712
713                 float volume_inc = pow(volume / old_volume, 1.0 / num_samples);
714                 volume = old_volume;
715                 if (bus_index == 0) {
716                         for (unsigned i = 0; i < num_samples; ++i) {
717                                 (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
718                                 (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
719                                 volume *= volume_inc;
720                         }
721                 } else {
722                         for (unsigned i = 0; i < num_samples; ++i) {
723                                 (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
724                                 (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
725                                 volume *= volume_inc;
726                         }
727                 }
728         } else if (new_volume_db > -90.0f) {
729                 float volume = from_db(new_volume_db);
730                 if (bus_index == 0) {
731                         for (unsigned i = 0; i < num_samples; ++i) {
732                                 (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
733                                 (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
734                         }
735                 } else {
736                         for (unsigned i = 0; i < num_samples; ++i) {
737                                 (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
738                                 (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
739                         }
740                 }
741         }
742
743         last_fader_volume_db[bus_index] = new_volume_db;
744 }
745
746 void AudioMixer::measure_bus_levels(unsigned bus_index, const vector<float> &left, const vector<float> &right)
747 {
748         assert(left.size() == right.size());
749         const float volume = mute[bus_index] ? 0.0f : from_db(fader_volume_db[bus_index]);
750         const float peak_levels[2] = {
751                 find_peak(left.data(), left.size()) * volume,
752                 find_peak(right.data(), right.size()) * volume
753         };
754         for (unsigned channel = 0; channel < 2; ++channel) {
755                 // Compute the current value, including hold and falloff.
756                 // The constants are borrowed from zita-mu1 by Fons Adriaensen.
757                 static constexpr float hold_sec = 0.5f;
758                 static constexpr float falloff_db_sec = 15.0f;  // dB/sec falloff after hold.
759                 float current_peak;
760                 PeakHistory &history = peak_history[bus_index][channel];
761                 history.historic_peak = max(history.historic_peak, peak_levels[channel]);
762                 if (history.age_seconds < hold_sec) {
763                         current_peak = history.last_peak;
764                 } else {
765                         current_peak = history.last_peak * from_db(-falloff_db_sec * (history.age_seconds - hold_sec));
766                 }
767
768                 // See if we have a new peak to replace the old (possibly falling) one.
769                 if (peak_levels[channel] > current_peak) {
770                         history.last_peak = peak_levels[channel];
771                         history.age_seconds = 0.0f;  // Not 100% correct, but more than good enough given our frame sizes.
772                         current_peak = peak_levels[channel];
773                 } else {
774                         history.age_seconds += float(left.size()) / OUTPUT_FREQUENCY;
775                 }
776                 history.current_level = peak_levels[channel];
777                 history.current_peak = current_peak;
778         }
779 }
780
781 void AudioMixer::update_meters(const vector<float> &samples)
782 {
783         // Upsample 4x to find interpolated peak.
784         peak_resampler.inp_data = const_cast<float *>(samples.data());
785         peak_resampler.inp_count = samples.size() / 2;
786
787         vector<float> interpolated_samples;
788         interpolated_samples.resize(samples.size());
789         {
790                 lock_guard<mutex> lock(audio_measure_mutex);
791
792                 while (peak_resampler.inp_count > 0) {  // About four iterations.
793                         peak_resampler.out_data = &interpolated_samples[0];
794                         peak_resampler.out_count = interpolated_samples.size() / 2;
795                         peak_resampler.process();
796                         size_t out_stereo_samples = interpolated_samples.size() / 2 - peak_resampler.out_count;
797                         peak = max<float>(peak, find_peak(interpolated_samples.data(), out_stereo_samples * 2));
798                         peak_resampler.out_data = nullptr;
799                 }
800         }
801
802         // Find R128 levels and L/R correlation.
803         vector<float> left, right;
804         deinterleave_samples(samples, &left, &right);
805         float *ptrs[] = { left.data(), right.data() };
806         {
807                 lock_guard<mutex> lock(audio_measure_mutex);
808                 r128.process(left.size(), ptrs);
809                 correlation.process_samples(samples);
810         }
811
812         send_audio_level_callback();
813 }
814
815 void AudioMixer::reset_meters()
816 {
817         lock_guard<mutex> lock(audio_measure_mutex);
818         peak_resampler.reset();
819         peak = 0.0f;
820         r128.reset();
821         r128.integr_start();
822         correlation.reset();
823 }
824
825 void AudioMixer::send_audio_level_callback()
826 {
827         if (audio_level_callback == nullptr) {
828                 return;
829         }
830
831         lock_guard<mutex> lock(audio_measure_mutex);
832         double loudness_s = r128.loudness_S();
833         double loudness_i = r128.integrated();
834         double loudness_range_low = r128.range_min();
835         double loudness_range_high = r128.range_max();
836
837         metric_audio_loudness_short_lufs = loudness_s;
838         metric_audio_loudness_integrated_lufs = loudness_i;
839         metric_audio_loudness_range_low_lufs = loudness_range_low;
840         metric_audio_loudness_range_high_lufs = loudness_range_high;
841         metric_audio_peak_dbfs = to_db(peak);
842         metric_audio_final_makeup_gain_db = to_db(final_makeup_gain);
843         metric_audio_correlation = correlation.get_correlation();
844
845         vector<BusLevel> bus_levels;
846         bus_levels.resize(input_mapping.buses.size());
847         {
848                 lock_guard<mutex> lock(compressor_mutex);
849                 for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) {
850                         BusLevel &levels = bus_levels[bus_index];
851                         BusMetrics &metrics = bus_metrics[bus_index];
852
853                         levels.current_level_dbfs[0] = metrics.current_level_dbfs[0] = to_db(peak_history[bus_index][0].current_level);
854                         levels.current_level_dbfs[1] = metrics.current_level_dbfs[1] = to_db(peak_history[bus_index][1].current_level);
855                         levels.peak_level_dbfs[0] = metrics.peak_level_dbfs[0] = to_db(peak_history[bus_index][0].current_peak);
856                         levels.peak_level_dbfs[1] = metrics.peak_level_dbfs[1] = to_db(peak_history[bus_index][1].current_peak);
857                         levels.historic_peak_dbfs = metrics.historic_peak_dbfs = to_db(
858                                 max(peak_history[bus_index][0].historic_peak,
859                                     peak_history[bus_index][1].historic_peak));
860                         levels.gain_staging_db = metrics.gain_staging_db = gain_staging_db[bus_index];
861                         if (compressor_enabled[bus_index]) {
862                                 levels.compressor_attenuation_db = metrics.compressor_attenuation_db = -to_db(compressor[bus_index]->get_attenuation());
863                         } else {
864                                 levels.compressor_attenuation_db = 0.0;
865                                 metrics.compressor_attenuation_db = 0.0 / 0.0;
866                         }
867                 }
868         }
869
870         audio_level_callback(loudness_s, to_db(peak), bus_levels,
871                 loudness_i, loudness_range_low, loudness_range_high,
872                 to_db(final_makeup_gain),
873                 correlation.get_correlation());
874 }
875
876 map<DeviceSpec, DeviceInfo> AudioMixer::get_devices()
877 {
878         lock_guard<timed_mutex> lock(audio_mutex);
879
880         map<DeviceSpec, DeviceInfo> devices;
881         for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
882                 const DeviceSpec spec{ InputSourceType::CAPTURE_CARD, card_index };
883                 const AudioDevice *device = &video_cards[card_index];
884                 DeviceInfo info;
885                 info.display_name = device->display_name;
886                 info.num_channels = 8;
887                 devices.insert(make_pair(spec, info));
888         }
889         vector<ALSAPool::Device> available_alsa_devices = alsa_pool.get_devices();
890         for (unsigned card_index = 0; card_index < available_alsa_devices.size(); ++card_index) {
891                 const DeviceSpec spec{ InputSourceType::ALSA_INPUT, card_index };
892                 const ALSAPool::Device &device = available_alsa_devices[card_index];
893                 DeviceInfo info;
894                 info.display_name = device.display_name();
895                 info.num_channels = device.num_channels;
896                 info.alsa_name = device.name;
897                 info.alsa_info = device.info;
898                 info.alsa_address = device.address;
899                 devices.insert(make_pair(spec, info));
900         }
901         return devices;
902 }
903
904 void AudioMixer::set_display_name(DeviceSpec device_spec, const string &name)
905 {
906         AudioDevice *device = find_audio_device(device_spec);
907
908         lock_guard<timed_mutex> lock(audio_mutex);
909         device->display_name = name;
910 }
911
912 void AudioMixer::serialize_device(DeviceSpec device_spec, DeviceSpecProto *device_spec_proto)
913 {
914         lock_guard<timed_mutex> lock(audio_mutex);
915         switch (device_spec.type) {
916                 case InputSourceType::SILENCE:
917                         device_spec_proto->set_type(DeviceSpecProto::SILENCE);
918                         break;
919                 case InputSourceType::CAPTURE_CARD:
920                         device_spec_proto->set_type(DeviceSpecProto::CAPTURE_CARD);
921                         device_spec_proto->set_index(device_spec.index);
922                         device_spec_proto->set_display_name(video_cards[device_spec.index].display_name);
923                         break;
924                 case InputSourceType::ALSA_INPUT:
925                         alsa_pool.serialize_device(device_spec.index, device_spec_proto);
926                         break;
927         }
928 }
929
930 void AudioMixer::set_simple_input(unsigned card_index)
931 {
932         InputMapping new_input_mapping;
933         InputMapping::Bus input;
934         input.name = "Main";
935         input.device.type = InputSourceType::CAPTURE_CARD;
936         input.device.index = card_index;
937         input.source_channel[0] = 0;
938         input.source_channel[1] = 1;
939
940         new_input_mapping.buses.push_back(input);
941
942         lock_guard<timed_mutex> lock(audio_mutex);
943         current_mapping_mode = MappingMode::SIMPLE;
944         set_input_mapping_lock_held(new_input_mapping);
945         fader_volume_db[0] = 0.0f;
946 }
947
948 unsigned AudioMixer::get_simple_input() const
949 {
950         lock_guard<timed_mutex> lock(audio_mutex);
951         if (input_mapping.buses.size() == 1 &&
952             input_mapping.buses[0].device.type == InputSourceType::CAPTURE_CARD &&
953             input_mapping.buses[0].source_channel[0] == 0 &&
954             input_mapping.buses[0].source_channel[1] == 1) {
955                 return input_mapping.buses[0].device.index;
956         } else {
957                 return numeric_limits<unsigned>::max();
958         }
959 }
960
961 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
962 {
963         lock_guard<timed_mutex> lock(audio_mutex);
964         set_input_mapping_lock_held(new_input_mapping);
965         current_mapping_mode = MappingMode::MULTICHANNEL;
966 }
967
968 AudioMixer::MappingMode AudioMixer::get_mapping_mode() const
969 {
970         lock_guard<timed_mutex> lock(audio_mutex);
971         return current_mapping_mode;
972 }
973
974 void AudioMixer::set_input_mapping_lock_held(const InputMapping &new_input_mapping)
975 {
976         map<DeviceSpec, set<unsigned>> interesting_channels;
977         for (const InputMapping::Bus &bus : new_input_mapping.buses) {
978                 if (bus.device.type == InputSourceType::CAPTURE_CARD ||
979                     bus.device.type == InputSourceType::ALSA_INPUT) {
980                         for (unsigned channel = 0; channel < 2; ++channel) {
981                                 if (bus.source_channel[channel] != -1) {
982                                         interesting_channels[bus.device].insert(bus.source_channel[channel]);
983                                 }
984                         }
985                 }
986         }
987
988         // Kill all the old metrics, and set up new ones.
989         for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
990                 BusMetrics &metrics = bus_metrics[bus_index];
991
992                 vector<pair<string, string>> labels_left = metrics.labels;
993                 labels_left.emplace_back("channel", "left");
994                 vector<pair<string, string>> labels_right = metrics.labels;
995                 labels_right.emplace_back("channel", "right");
996
997                 global_metrics.remove("bus_current_level_dbfs", labels_left);
998                 global_metrics.remove("bus_current_level_dbfs", labels_right);
999                 global_metrics.remove("bus_peak_level_dbfs", labels_left);
1000                 global_metrics.remove("bus_peak_level_dbfs", labels_right);
1001                 global_metrics.remove("bus_historic_peak_dbfs", metrics.labels);
1002                 global_metrics.remove("bus_gain_staging_db", metrics.labels);
1003                 global_metrics.remove("bus_compressor_attenuation_db", metrics.labels);
1004         }
1005         bus_metrics.reset(new BusMetrics[new_input_mapping.buses.size()]);
1006         for (unsigned bus_index = 0; bus_index < new_input_mapping.buses.size(); ++bus_index) {
1007                 const InputMapping::Bus &bus = new_input_mapping.buses[bus_index];
1008                 BusMetrics &metrics = bus_metrics[bus_index];
1009
1010                 char bus_index_str[16], source_index_str[16], source_channels_str[64];
1011                 snprintf(bus_index_str, sizeof(bus_index_str), "%u", bus_index);
1012                 snprintf(source_index_str, sizeof(source_index_str), "%u", bus.device.index);
1013                 snprintf(source_channels_str, sizeof(source_channels_str), "%d:%d", bus.source_channel[0], bus.source_channel[1]);
1014
1015                 vector<pair<string, string>> labels;
1016                 metrics.labels.emplace_back("index", bus_index_str);
1017                 metrics.labels.emplace_back("name", bus.name);
1018                 if (bus.device.type == InputSourceType::SILENCE) {
1019                         metrics.labels.emplace_back("source_type", "silence");
1020                 } else if (bus.device.type == InputSourceType::CAPTURE_CARD) {
1021                         metrics.labels.emplace_back("source_type", "capture_card");
1022                 } else if (bus.device.type == InputSourceType::ALSA_INPUT) {
1023                         metrics.labels.emplace_back("source_type", "alsa_input");
1024                 } else {
1025                         assert(false);
1026                 }
1027                 metrics.labels.emplace_back("source_index", source_index_str);
1028                 metrics.labels.emplace_back("source_channels", source_channels_str);
1029
1030                 vector<pair<string, string>> labels_left = metrics.labels;
1031                 labels_left.emplace_back("channel", "left");
1032                 vector<pair<string, string>> labels_right = metrics.labels;
1033                 labels_right.emplace_back("channel", "right");
1034
1035                 global_metrics.add("bus_current_level_dbfs", labels_left, &metrics.current_level_dbfs[0], Metrics::TYPE_GAUGE);
1036                 global_metrics.add("bus_current_level_dbfs", labels_right, &metrics.current_level_dbfs[1], Metrics::TYPE_GAUGE);
1037                 global_metrics.add("bus_peak_level_dbfs", labels_left, &metrics.peak_level_dbfs[0], Metrics::TYPE_GAUGE);
1038                 global_metrics.add("bus_peak_level_dbfs", labels_right, &metrics.peak_level_dbfs[1], Metrics::TYPE_GAUGE);
1039                 global_metrics.add("bus_historic_peak_dbfs", metrics.labels, &metrics.historic_peak_dbfs, Metrics::TYPE_GAUGE);
1040                 global_metrics.add("bus_gain_staging_db", metrics.labels, &metrics.gain_staging_db, Metrics::TYPE_GAUGE);
1041                 global_metrics.add("bus_compressor_attenuation_db", metrics.labels, &metrics.compressor_attenuation_db, Metrics::TYPE_GAUGE);
1042         }
1043
1044         // Reset resamplers for all cards that don't have the exact same state as before.
1045         for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1046                 const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
1047                 AudioDevice *device = find_audio_device(device_spec);
1048                 if (device->interesting_channels != interesting_channels[device_spec]) {
1049                         device->interesting_channels = interesting_channels[device_spec];
1050                         reset_resampler_mutex_held(device_spec);
1051                 }
1052         }
1053         for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
1054                 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
1055                 AudioDevice *device = find_audio_device(device_spec);
1056                 if (interesting_channels[device_spec].empty()) {
1057                         alsa_pool.release_device(card_index);
1058                 } else {
1059                         alsa_pool.hold_device(card_index);
1060                 }
1061                 if (device->interesting_channels != interesting_channels[device_spec]) {
1062                         device->interesting_channels = interesting_channels[device_spec];
1063                         alsa_pool.reset_device(device_spec.index);
1064                         reset_resampler_mutex_held(device_spec);
1065                 }
1066         }
1067
1068         input_mapping = new_input_mapping;
1069 }
1070
1071 InputMapping AudioMixer::get_input_mapping() const
1072 {
1073         lock_guard<timed_mutex> lock(audio_mutex);
1074         return input_mapping;
1075 }
1076
1077 unsigned AudioMixer::num_buses() const
1078 {
1079         lock_guard<timed_mutex> lock(audio_mutex);
1080         return input_mapping.buses.size();
1081 }
1082
1083 void AudioMixer::reset_peak(unsigned bus_index)
1084 {
1085         lock_guard<timed_mutex> lock(audio_mutex);
1086         for (unsigned channel = 0; channel < 2; ++channel) {
1087                 PeakHistory &history = peak_history[bus_index][channel];
1088                 history.current_level = 0.0f;
1089                 history.historic_peak = 0.0f;
1090                 history.current_peak = 0.0f;
1091                 history.last_peak = 0.0f;
1092                 history.age_seconds = 0.0f;
1093         }
1094 }
1095
1096 AudioMixer *global_audio_mixer = nullptr;