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