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