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