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