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