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