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