1 #include "audio_mixer.h"
4 #include <bmusb/bmusb.h>
22 #include "delay_analyzer.h"
24 #include "shared/metrics.h"
26 #include "shared/timebase.h"
28 using namespace bmusb;
30 using namespace std::chrono;
31 using namespace std::placeholders;
35 // TODO: If these prove to be a bottleneck, they can be SSSE3-optimized
36 // (usually including multiple channels at a time).
38 void convert_fixed16_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
39 const uint8_t *src, size_t in_channel, size_t in_num_channels,
42 assert(in_channel < in_num_channels);
43 assert(out_channel < out_num_channels);
44 src += in_channel * 2;
47 for (size_t i = 0; i < num_samples; ++i) {
48 int16_t s = le16toh(*(int16_t *)src);
49 *dst = s * (1.0f / 32768.0f);
51 src += 2 * in_num_channels;
52 dst += out_num_channels;
56 void convert_fixed16_to_fixed32(int32_t *dst, size_t out_channel, size_t out_num_channels,
57 const uint8_t *src, size_t in_channel, size_t in_num_channels,
60 assert(in_channel < in_num_channels);
61 assert(out_channel < out_num_channels);
62 src += in_channel * 2;
65 for (size_t i = 0; i < num_samples; ++i) {
66 uint32_t s = uint32_t(uint16_t(le16toh(*(int16_t *)src))) << 16;
68 // Keep the sign bit in place, repeat the other 15 bits as far as they go.
69 *dst = s | ((s & 0x7fffffff) >> 15) | ((s & 0x7fffffff) >> 30);
71 src += 2 * in_num_channels;
72 dst += out_num_channels;
76 void convert_fixed24_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
77 const uint8_t *src, size_t in_channel, size_t in_num_channels,
80 assert(in_channel < in_num_channels);
81 assert(out_channel < out_num_channels);
82 src += in_channel * 3;
85 for (size_t i = 0; i < num_samples; ++i) {
89 uint32_t s = (s1 << 8) | (s2 << 16) | (s3 << 24); // Note: The bottom eight bits are zero; s3 includes the sign bit.
90 *dst = int(s) * (1.0f / (256.0f * 8388608.0f)); // 256 for signed down-shift by 8, then 2^23 for the actual conversion.
92 src += 3 * in_num_channels;
93 dst += out_num_channels;
97 void convert_fixed24_to_fixed32(int32_t *dst, size_t out_channel, size_t out_num_channels,
98 const uint8_t *src, size_t in_channel, size_t in_num_channels,
101 assert(in_channel < in_num_channels);
102 assert(out_channel < out_num_channels);
103 src += in_channel * 3;
106 for (size_t i = 0; i < num_samples; ++i) {
107 uint32_t s1 = src[0];
108 uint32_t s2 = src[1];
109 uint32_t s3 = src[2];
110 uint32_t s = (s1 << 8) | (s2 << 16) | (s3 << 24);
112 // Keep the sign bit in place, repeat the other 23 bits as far as they go.
113 *dst = s | ((s & 0x7fffffff) >> 23);
115 src += 3 * in_num_channels;
116 dst += out_num_channels;
120 void convert_fixed32_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
121 const uint8_t *src, size_t in_channel, size_t in_num_channels,
124 assert(in_channel < in_num_channels);
125 assert(out_channel < out_num_channels);
126 src += in_channel * 4;
129 for (size_t i = 0; i < num_samples; ++i) {
130 int32_t s = le32toh(*(int32_t *)src);
131 *dst = s * (1.0f / 2147483648.0f);
133 src += 4 * in_num_channels;
134 dst += out_num_channels;
138 // Basically just a reinterleave.
139 void convert_fixed32_to_fixed32(int32_t *dst, size_t out_channel, size_t out_num_channels,
140 const uint8_t *src, size_t in_channel, size_t in_num_channels,
143 assert(in_channel < in_num_channels);
144 assert(out_channel < out_num_channels);
145 src += in_channel * 4;
148 for (size_t i = 0; i < num_samples; ++i) {
149 int32_t s = le32toh(*(int32_t *)src);
152 src += 4 * in_num_channels;
153 dst += out_num_channels;
157 float find_peak_plain(const float *samples, size_t num_samples) __attribute__((unused));
159 float find_peak_plain(const float *samples, size_t num_samples)
161 float m = fabs(samples[0]);
162 for (size_t i = 1; i < num_samples; ++i) {
163 m = max(m, fabs(samples[i]));
169 static inline float horizontal_max(__m128 m)
171 __m128 tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 0, 3, 2));
172 m = _mm_max_ps(m, tmp);
173 tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 3, 0, 1));
174 m = _mm_max_ps(m, tmp);
175 return _mm_cvtss_f32(m);
178 float find_peak(const float *samples, size_t num_samples)
180 const __m128 abs_mask = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffu));
181 __m128 m = _mm_setzero_ps();
182 for (size_t i = 0; i < (num_samples & ~3); i += 4) {
183 __m128 x = _mm_loadu_ps(samples + i);
184 x = _mm_and_ps(x, abs_mask);
185 m = _mm_max_ps(m, x);
187 float result = horizontal_max(m);
189 for (size_t i = (num_samples & ~3); i < num_samples; ++i) {
190 result = max(result, fabs(samples[i]));
194 // Self-test. We should be bit-exact the same.
195 float reference_result = find_peak_plain(samples, num_samples);
196 if (result != reference_result) {
197 fprintf(stderr, "Error: Peak is %f [%f %f %f %f]; should be %f.\n",
199 _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(0, 0, 0, 0))),
200 _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1))),
201 _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 2, 2, 2))),
202 _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(3, 3, 3, 3))),
210 float find_peak(const float *samples, size_t num_samples)
212 return find_peak_plain(samples, num_samples);
216 void deinterleave_samples(const vector<float> &in, vector<float> *out_l, vector<float> *out_r)
218 size_t num_samples = in.size() / 2;
219 out_l->resize(num_samples);
220 out_r->resize(num_samples);
222 const float *inptr = in.data();
223 float *lptr = &(*out_l)[0];
224 float *rptr = &(*out_r)[0];
225 for (size_t i = 0; i < num_samples; ++i) {
231 double get_delay_seconds(double extra_delay_ms)
233 // Make sure we never get negative delay. Even 1 ms is probably way less than we
234 // could ever hope to actually have; this is just a failsafe.
235 double delay_ms = max(global_flags.audio_queue_length_ms + extra_delay_ms, 1.0);
236 return delay_ms * 0.001;
241 AudioMixer::AudioMixer(unsigned num_capture_cards, unsigned num_ffmpeg_inputs)
242 : num_capture_cards(num_capture_cards),
243 num_ffmpeg_inputs(num_ffmpeg_inputs),
244 ffmpeg_inputs(new AudioDevice[num_ffmpeg_inputs]),
245 limiter(OUTPUT_FREQUENCY),
246 correlation(OUTPUT_FREQUENCY)
248 for (unsigned bus_index = 0; bus_index < MAX_BUSES; ++bus_index) {
249 locut[bus_index].init(FILTER_HPF, 2);
250 eq[bus_index][EQ_BAND_BASS].init(FILTER_LOW_SHELF, 1);
251 // Note: EQ_BAND_MID isn't used (see comments in apply_eq()).
252 eq[bus_index][EQ_BAND_TREBLE].init(FILTER_HIGH_SHELF, 1);
253 compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
254 level_compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
256 set_bus_settings(bus_index, get_default_bus_settings());
258 set_limiter_enabled(global_flags.limiter_enabled);
259 set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
261 r128.init(2, OUTPUT_FREQUENCY);
264 // hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise,
265 // and there's a limit to how important the peak meter is.
266 peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0);
268 global_audio_mixer = this;
271 if (!global_flags.input_mapping_filename.empty()) {
272 // Must happen after ALSAPool is initialized, as it needs to know the card list.
273 current_mapping_mode = MappingMode::MULTICHANNEL;
274 InputMapping new_input_mapping;
275 if (!load_input_mapping_from_file(get_devices(HOLD_ALSA_DEVICES),
276 global_flags.input_mapping_filename,
277 &new_input_mapping)) {
278 fprintf(stderr, "Failed to load input mapping from '%s', exiting.\n",
279 global_flags.input_mapping_filename.c_str());
282 set_input_mapping(new_input_mapping);
284 set_simple_input(/*card_index=*/0);
285 if (global_flags.multichannel_mapping_mode) {
286 current_mapping_mode = MappingMode::MULTICHANNEL;
290 global_metrics.add("audio_loudness_short_lufs", &metric_audio_loudness_short_lufs, Metrics::TYPE_GAUGE);
291 global_metrics.add("audio_loudness_integrated_lufs", &metric_audio_loudness_integrated_lufs, Metrics::TYPE_GAUGE);
292 global_metrics.add("audio_loudness_range_low_lufs", &metric_audio_loudness_range_low_lufs, Metrics::TYPE_GAUGE);
293 global_metrics.add("audio_loudness_range_high_lufs", &metric_audio_loudness_range_high_lufs, Metrics::TYPE_GAUGE);
294 global_metrics.add("audio_peak_dbfs", &metric_audio_peak_dbfs, Metrics::TYPE_GAUGE);
295 global_metrics.add("audio_final_makeup_gain_db", &metric_audio_final_makeup_gain_db, Metrics::TYPE_GAUGE);
296 global_metrics.add("audio_correlation", &metric_audio_correlation, Metrics::TYPE_GAUGE);
299 void AudioMixer::reset_resampler(DeviceSpec device_spec)
301 lock_guard<timed_mutex> lock(audio_mutex);
302 reset_resampler_mutex_held(device_spec);
305 void AudioMixer::reset_resampler_mutex_held(DeviceSpec device_spec)
307 AudioDevice *device = find_audio_device(device_spec);
309 if (device->interesting_channels.empty()) {
310 device->resampling_queue.reset();
312 device->resampling_queue.reset(new ResamplingQueue(
313 device_spec, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size(),
314 get_delay_seconds(device->extra_delay_ms)));
318 bool AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, steady_clock::time_point frame_time)
320 if (delay_analyzer != nullptr && delay_analyzer->is_grabbing()) {
321 delay_analyzer->add_audio(device_spec, data, num_samples, audio_format, frame_time);
324 AudioDevice *device = find_audio_device(device_spec);
326 unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
327 if (!lock.try_lock_for(chrono::milliseconds(10))) {
330 if (device->resampling_queue == nullptr) {
331 // No buses use this device; throw it away.
335 unsigned num_channels = device->interesting_channels.size();
336 assert(num_channels > 0);
338 // Convert the audio to fp32.
339 unique_ptr<float[]> audio(new float[num_samples * num_channels]);
340 unsigned channel_index = 0;
341 for (auto channel_it = device->interesting_channels.cbegin(); channel_it != device->interesting_channels.end(); ++channel_it, ++channel_index) {
342 convert_audio_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format, num_samples);
345 // If we changed frequency since last frame, we'll need to reset the resampler.
346 if (audio_format.sample_rate != device->capture_frequency) {
347 device->capture_frequency = audio_format.sample_rate;
348 reset_resampler_mutex_held(device_spec);
352 device->resampling_queue->add_input_samples(frame_time, audio.get(), num_samples, ResamplingQueue::ADJUST_RATE);
356 // Converts all channels.
357 vector<int32_t> convert_audio_to_fixed32(const uint8_t *data, unsigned num_samples, bmusb::AudioFormat audio_format, unsigned num_channels)
359 vector<int32_t> audio;
361 if (num_channels > audio_format.num_channels) {
362 audio.resize(num_samples * num_channels, 0);
364 audio.resize(num_samples * num_channels);
366 for (unsigned channel_index = 0; channel_index < num_channels && channel_index < audio_format.num_channels; ++channel_index) {
367 switch (audio_format.bits_per_sample) {
369 assert(num_samples == 0);
372 convert_fixed16_to_fixed32(&audio[0], channel_index, num_channels, data, channel_index, audio_format.num_channels, num_samples);
375 convert_fixed24_to_fixed32(&audio[0], channel_index, num_channels, data, channel_index, audio_format.num_channels, num_samples);
378 convert_fixed32_to_fixed32(&audio[0], channel_index, num_channels, data, channel_index, audio_format.num_channels, num_samples);
381 fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
389 // Converts only one channel.
390 void convert_audio_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
391 const uint8_t *src, size_t in_channel, bmusb::AudioFormat in_audio_format,
394 switch (in_audio_format.bits_per_sample) {
396 assert(num_samples == 0);
399 convert_fixed16_to_fp32(dst, out_channel, out_num_channels, src, in_channel, in_audio_format.num_channels, num_samples);
402 convert_fixed24_to_fp32(dst, out_channel, out_num_channels, src, in_channel, in_audio_format.num_channels, num_samples);
405 convert_fixed32_to_fp32(dst, out_channel, out_num_channels, src, in_channel, in_audio_format.num_channels, num_samples);
408 fprintf(stderr, "Cannot handle audio with %u bits per sample\n", in_audio_format.bits_per_sample);
413 bool AudioMixer::add_silence(DeviceSpec device_spec, unsigned samples_per_frame, unsigned num_frames)
415 AudioDevice *device = find_audio_device(device_spec);
417 unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
418 if (!lock.try_lock_for(chrono::milliseconds(10))) {
421 if (device->resampling_queue == nullptr) {
422 // No buses use this device; throw it away.
426 unsigned num_channels = device->interesting_channels.size();
427 assert(num_channels > 0);
429 vector<float> silence(samples_per_frame * num_channels, 0.0f);
430 for (unsigned i = 0; i < num_frames; ++i) {
431 device->resampling_queue->add_input_samples(steady_clock::now(), silence.data(), samples_per_frame, ResamplingQueue::DO_NOT_ADJUST_RATE);
436 bool AudioMixer::silence_card(DeviceSpec device_spec, bool silence)
438 AudioDevice *device = find_audio_device(device_spec);
440 unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
441 if (!lock.try_lock_for(chrono::milliseconds(10))) {
445 if (device->silenced && !silence) {
446 reset_resampler_mutex_held(device_spec);
448 device->silenced = silence;
452 AudioMixer::BusSettings AudioMixer::get_default_bus_settings()
454 BusSettings settings;
455 settings.fader_volume_db = 0.0f;
456 settings.muted = false;
457 settings.locut_enabled = global_flags.locut_enabled;
458 settings.stereo_width = 1.0f;
459 for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
460 settings.eq_level_db[band_index] = 0.0f;
462 settings.gain_staging_db = global_flags.initial_gain_staging_db;
463 settings.level_compressor_enabled = global_flags.gain_staging_auto;
464 settings.compressor_threshold_dbfs = ref_level_dbfs - 12.0f; // -12 dB.
465 settings.compressor_enabled = global_flags.compressor_enabled;
469 AudioMixer::BusSettings AudioMixer::get_bus_settings(unsigned bus_index) const
471 lock_guard<timed_mutex> lock(audio_mutex);
472 BusSettings settings;
473 settings.fader_volume_db = fader_volume_db[bus_index];
474 settings.muted = mute[bus_index];
475 settings.locut_enabled = locut_enabled[bus_index];
476 settings.stereo_width = stereo_width[bus_index];
477 for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
478 settings.eq_level_db[band_index] = eq_level_db[bus_index][band_index];
480 settings.gain_staging_db = gain_staging_db[bus_index];
481 settings.level_compressor_enabled = level_compressor_enabled[bus_index];
482 settings.compressor_threshold_dbfs = compressor_threshold_dbfs[bus_index];
483 settings.compressor_enabled = compressor_enabled[bus_index];
487 void AudioMixer::set_bus_settings(unsigned bus_index, const AudioMixer::BusSettings &settings)
489 lock_guard<timed_mutex> lock(audio_mutex);
490 fader_volume_db[bus_index] = settings.fader_volume_db;
491 mute[bus_index] = settings.muted;
492 locut_enabled[bus_index] = settings.locut_enabled;
493 stereo_width[bus_index] = settings.stereo_width;
494 for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
495 eq_level_db[bus_index][band_index] = settings.eq_level_db[band_index];
497 gain_staging_db[bus_index] = settings.gain_staging_db;
498 last_gain_staging_db[bus_index] = gain_staging_db[bus_index];
499 level_compressor_enabled[bus_index] = settings.level_compressor_enabled;
500 compressor_threshold_dbfs[bus_index] = settings.compressor_threshold_dbfs;
501 compressor_enabled[bus_index] = settings.compressor_enabled;
504 AudioMixer::AudioDevice *AudioMixer::find_audio_device(DeviceSpec device)
506 switch (device.type) {
507 case InputSourceType::CAPTURE_CARD:
508 return &video_cards[device.index];
509 case InputSourceType::ALSA_INPUT:
510 return &alsa_inputs[device.index];
511 case InputSourceType::FFMPEG_VIDEO_INPUT:
512 return &ffmpeg_inputs[device.index];
513 case InputSourceType::SILENCE:
520 // Get a pointer to the given channel from the given device.
521 // The channel must be picked out earlier and resampled.
522 void AudioMixer::find_sample_src_from_device(const map<DeviceSpec, vector<float>> &samples_card, DeviceSpec device_spec, int source_channel, const float **srcptr, unsigned *stride)
524 static float zero = 0.0f;
525 if (source_channel == -1 || device_spec.type == InputSourceType::SILENCE) {
530 AudioDevice *device = find_audio_device(device_spec);
531 assert(device->interesting_channels.count(source_channel) != 0);
532 unsigned channel_index = 0;
533 for (int channel : device->interesting_channels) {
534 if (channel == source_channel) break;
537 assert(channel_index < device->interesting_channels.size());
538 const auto it = samples_card.find(device_spec);
539 assert(it != samples_card.end());
540 *srcptr = &(it->second)[channel_index];
541 *stride = device->interesting_channels.size();
544 // TODO: Can be SSSE3-optimized if need be.
545 void AudioMixer::fill_audio_bus(const map<DeviceSpec, vector<float>> &samples_card, const InputMapping::Bus &bus, unsigned num_samples, float stereo_width, float *output)
547 if (bus.device.type == InputSourceType::SILENCE) {
548 memset(output, 0, num_samples * 2 * sizeof(*output));
550 assert(bus.device.type == InputSourceType::CAPTURE_CARD ||
551 bus.device.type == InputSourceType::ALSA_INPUT ||
552 bus.device.type == InputSourceType::FFMPEG_VIDEO_INPUT);
553 const float *lsrc, *rsrc;
554 unsigned lstride, rstride;
555 float *dptr = output;
556 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[0], &lsrc, &lstride);
557 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[1], &rsrc, &rstride);
559 // Apply stereo width settings. Set stereo width w to a 0..1 range instead of
560 // -1..1, since it makes for much easier calculations (so 0.5 = completely mono).
561 // Then, what we want is
563 // L' = wL + (1-w)R = R + w(L-R)
564 // R' = wR + (1-w)L = L + w(R-L)
566 // This can be further simplified calculation-wise by defining the weighted
567 // difference signal D = w(R-L), so that:
571 float w = 0.5f * stereo_width + 0.5f;
572 if (bus.source_channel[0] == bus.source_channel[1]) {
573 // Mono anyway, so no need to bother.
575 } else if (fabs(w) < 1e-3) {
578 swap(lstride, rstride);
581 if (fabs(w - 1.0f) < 1e-3) {
582 // No calculations needed for stereo_width = 1.
583 for (unsigned i = 0; i < num_samples; ++i) {
591 for (unsigned i = 0; i < num_samples; ++i) {
592 float left = *lsrc, right = *rsrc;
593 float diff = w * (right - left);
594 *dptr++ = right - diff;
595 *dptr++ = left + diff;
603 vector<DeviceSpec> AudioMixer::get_active_devices() const
605 vector<DeviceSpec> ret;
606 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
607 const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
608 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
609 ret.push_back(device_spec);
612 for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
613 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
614 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
615 ret.push_back(device_spec);
618 for (unsigned card_index = 0; card_index < num_ffmpeg_inputs; ++card_index) {
619 const DeviceSpec device_spec{InputSourceType::FFMPEG_VIDEO_INPUT, card_index};
620 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
621 ret.push_back(device_spec);
629 void apply_gain(float db, float last_db, vector<float> *samples)
631 if (fabs(db - last_db) < 1e-3) {
632 // Constant over this frame.
633 const float gain = from_db(db);
634 for (size_t i = 0; i < samples->size(); ++i) {
635 (*samples)[i] *= gain;
638 // We need to do a fade.
639 unsigned num_samples = samples->size() / 2;
640 float gain = from_db(last_db);
641 const float gain_inc = pow(from_db(db - last_db), 1.0 / num_samples);
642 for (size_t i = 0; i < num_samples; ++i) {
643 (*samples)[i * 2 + 0] *= gain;
644 (*samples)[i * 2 + 1] *= gain;
652 vector<float> AudioMixer::get_output(steady_clock::time_point ts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
654 map<DeviceSpec, vector<float>> samples_card;
655 vector<float> samples_bus;
657 lock_guard<timed_mutex> lock(audio_mutex);
659 // Pick out all the interesting channels from all the cards.
660 for (const DeviceSpec &device_spec : get_active_devices()) {
661 AudioDevice *device = find_audio_device(device_spec);
662 samples_card[device_spec].resize(num_samples * device->interesting_channels.size());
663 if (device->silenced) {
664 memset(&samples_card[device_spec][0], 0, samples_card[device_spec].size() * sizeof(float));
666 device->resampling_queue->get_output_samples(
668 &samples_card[device_spec][0],
670 rate_adjustment_policy);
674 vector<float> samples_out, left, right;
675 samples_out.resize(num_samples * 2);
676 samples_bus.resize(num_samples * 2);
677 for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
678 fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, stereo_width[bus_index], &samples_bus[0]);
679 apply_eq(bus_index, &samples_bus);
682 lock_guard<mutex> lock(compressor_mutex);
684 // Apply a level compressor to get the general level right.
685 // Basically, if it's over about -40 dBFS, we squeeze it down to that level
686 // (or more precisely, near it, since we don't use infinite ratio),
687 // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
688 // entirely arbitrary, but from practical tests with speech, it seems to
689 // put ut around -23 LUFS, so it's a reasonable starting point for later use.
690 if (level_compressor_enabled[bus_index]) {
691 float threshold = 0.01f; // -40 dBFS.
693 float attack_time = 0.5f;
694 float release_time = 20.0f;
695 float makeup_gain = from_db(ref_level_dbfs - (-40.0f)); // +26 dB.
696 level_compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
697 gain_staging_db[bus_index] = to_db(level_compressor[bus_index]->get_attenuation() * makeup_gain);
699 // Just apply the gain we already had.
700 float db = gain_staging_db[bus_index];
701 float last_db = last_gain_staging_db[bus_index];
702 apply_gain(db, last_db, &samples_bus);
704 last_gain_staging_db[bus_index] = gain_staging_db[bus_index];
707 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
708 level_compressor.get_level(), to_db(level_compressor.get_level()),
709 level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
710 to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
713 // The real compressor.
714 if (compressor_enabled[bus_index]) {
715 float threshold = from_db(compressor_threshold_dbfs[bus_index]);
717 float attack_time = 0.005f;
718 float release_time = 0.040f;
719 float makeup_gain = 2.0f; // +6 dB.
720 compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
721 // compressor_att = compressor.get_attenuation();
725 add_bus_to_master(bus_index, samples_bus, &samples_out);
726 deinterleave_samples(samples_bus, &left, &right);
727 measure_bus_levels(bus_index, left, right);
731 lock_guard<mutex> lock(compressor_mutex);
733 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
734 // Note that since ratio is not infinite, we could go slightly higher than this.
735 if (limiter_enabled) {
736 float threshold = from_db(limiter_threshold_dbfs);
738 float attack_time = 0.0f; // Instant.
739 float release_time = 0.020f;
740 float makeup_gain = 1.0f; // 0 dB.
741 limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
742 // limiter_att = limiter.get_attenuation();
745 // printf("limiter=%+5.1f compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
748 // At this point, we are most likely close to +0 LU (at least if the
749 // faders sum to 0 dB and the compressors are on), but all of our
750 // measurements have been on raw sample values, not R128 values.
751 // So we have a final makeup gain to get us to +0 LU; the gain
752 // adjustments required should be relatively small, and also, the
753 // offset shouldn't change much (only if the type of audio changes
754 // significantly). Thus, we shoot for updating this value basically
755 // “whenever we process buffers”, since the R128 calculation isn't exactly
756 // something we get out per-sample.
758 // Note that there's a feedback loop here, so we choose a very slow filter
759 // (half-time of 30 seconds).
760 double target_loudness_factor, alpha;
761 double loudness_lu = r128.loudness_M() - ref_level_lufs;
762 target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
764 // If we're outside +/- 5 LU (after correction), we don't count it as
765 // a normal signal (probably silence) and don't change the
766 // correction factor; just apply what we already have.
767 if (fabs(loudness_lu) >= 5.0 || !final_makeup_gain_auto) {
770 // Formula adapted from
771 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
772 const double half_time_s = 30.0;
773 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
774 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
778 lock_guard<mutex> lock(compressor_mutex);
779 double m = final_makeup_gain;
780 for (size_t i = 0; i < samples_out.size(); i += 2) {
781 samples_out[i + 0] *= m;
782 samples_out[i + 1] *= m;
783 m += (target_loudness_factor - m) * alpha;
785 final_makeup_gain = m;
788 update_meters(samples_out);
795 void apply_filter_fade(StereoFilter *filter, float *data, unsigned num_samples, float cutoff_hz, float db, float last_db)
797 // A granularity of 32 samples is an okay tradeoff between speed and
798 // smoothness; recalculating the filters is pretty expensive, so it's
799 // good that we don't do this all the time.
800 static constexpr unsigned filter_granularity_samples = 32;
802 const float cutoff_linear = cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY;
803 if (fabs(db - last_db) < 1e-3) {
804 // Constant over this frame.
805 if (fabs(db) > 0.01f) {
806 filter->render(data, num_samples, cutoff_linear, 0.5f, db / 40.0f);
809 // We need to do a fade. (Rounding up avoids division by zero.)
810 unsigned num_blocks = (num_samples + filter_granularity_samples - 1) / filter_granularity_samples;
811 const float inc_db_norm = (db - last_db) / 40.0f / num_blocks;
812 float db_norm = db / 40.0f;
813 for (size_t i = 0; i < num_samples; i += filter_granularity_samples) {
814 size_t samples_this_block = std::min<size_t>(num_samples - i, filter_granularity_samples);
815 filter->render(data + i * 2, samples_this_block, cutoff_linear, 0.5f, db_norm);
816 db_norm += inc_db_norm;
823 void AudioMixer::apply_eq(unsigned bus_index, vector<float> *samples_bus)
825 constexpr float bass_freq_hz = 200.0f;
826 constexpr float treble_freq_hz = 4700.0f;
828 // Cut away everything under 120 Hz (or whatever the cutoff is);
829 // we don't need it for voice, and it will reduce headroom
830 // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
831 // should be dampened.)
832 if (locut_enabled[bus_index]) {
833 locut[bus_index].render(samples_bus->data(), samples_bus->size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
836 // Apply the rest of the EQ. Since we only have a simple three-band EQ,
837 // we can implement it with two shelf filters. We use a simple gain to
838 // set the mid-level filter, and then offset the low and high bands
839 // from that if we need to. (We could perhaps have folded the gain into
840 // the next part, but it's so cheap that the trouble isn't worth it.)
842 // If any part of the EQ has changed appreciably since last frame,
843 // we fade smoothly during the course of this frame.
844 const float bass_db = eq_level_db[bus_index][EQ_BAND_BASS];
845 const float mid_db = eq_level_db[bus_index][EQ_BAND_MID];
846 const float treble_db = eq_level_db[bus_index][EQ_BAND_TREBLE];
848 const float last_bass_db = last_eq_level_db[bus_index][EQ_BAND_BASS];
849 const float last_mid_db = last_eq_level_db[bus_index][EQ_BAND_MID];
850 const float last_treble_db = last_eq_level_db[bus_index][EQ_BAND_TREBLE];
852 assert(samples_bus->size() % 2 == 0);
853 const unsigned num_samples = samples_bus->size() / 2;
855 apply_gain(mid_db, last_mid_db, samples_bus);
857 apply_filter_fade(&eq[bus_index][EQ_BAND_BASS], samples_bus->data(), num_samples, bass_freq_hz, bass_db - mid_db, last_bass_db - last_mid_db);
858 apply_filter_fade(&eq[bus_index][EQ_BAND_TREBLE], samples_bus->data(), num_samples, treble_freq_hz, treble_db - mid_db, last_treble_db - last_mid_db);
860 last_eq_level_db[bus_index][EQ_BAND_BASS] = bass_db;
861 last_eq_level_db[bus_index][EQ_BAND_MID] = mid_db;
862 last_eq_level_db[bus_index][EQ_BAND_TREBLE] = treble_db;
865 void AudioMixer::add_bus_to_master(unsigned bus_index, const vector<float> &samples_bus, vector<float> *samples_out)
867 assert(samples_bus.size() == samples_out->size());
868 assert(samples_bus.size() % 2 == 0);
869 unsigned num_samples = samples_bus.size() / 2;
870 const float new_volume_db = mute[bus_index] ? -90.0f : fader_volume_db[bus_index].load();
871 if (fabs(new_volume_db - last_fader_volume_db[bus_index]) > 1e-3) {
872 // The volume has changed; do a fade over the course of this frame.
873 // (We might have some numerical issues here, but it seems to sound OK.)
874 // For the purpose of fading here, the silence floor is set to -90 dB
875 // (the fader only goes to -84).
876 float old_volume = from_db(max<float>(last_fader_volume_db[bus_index], -90.0f));
877 float volume = from_db(max<float>(new_volume_db, -90.0f));
879 float volume_inc = pow(volume / old_volume, 1.0 / num_samples);
881 if (bus_index == 0) {
882 for (unsigned i = 0; i < num_samples; ++i) {
883 (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
884 (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
885 volume *= volume_inc;
888 for (unsigned i = 0; i < num_samples; ++i) {
889 (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
890 (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
891 volume *= volume_inc;
894 } else if (new_volume_db > -90.0f) {
895 float volume = from_db(new_volume_db);
896 if (bus_index == 0) {
897 for (unsigned i = 0; i < num_samples; ++i) {
898 (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
899 (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
902 for (unsigned i = 0; i < num_samples; ++i) {
903 (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
904 (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
909 last_fader_volume_db[bus_index] = new_volume_db;
912 void AudioMixer::measure_bus_levels(unsigned bus_index, const vector<float> &left, const vector<float> &right)
914 assert(left.size() == right.size());
915 const float volume = mute[bus_index] ? 0.0f : from_db(fader_volume_db[bus_index]);
916 const float peak_levels[2] = {
917 find_peak(left.data(), left.size()) * volume,
918 find_peak(right.data(), right.size()) * volume
920 for (unsigned channel = 0; channel < 2; ++channel) {
921 // Compute the current value, including hold and falloff.
922 // The constants are borrowed from zita-mu1 by Fons Adriaensen.
923 static constexpr float hold_sec = 0.5f;
924 static constexpr float falloff_db_sec = 15.0f; // dB/sec falloff after hold.
926 PeakHistory &history = peak_history[bus_index][channel];
927 history.historic_peak = max(history.historic_peak, peak_levels[channel]);
928 if (history.age_seconds < hold_sec) {
929 current_peak = history.last_peak;
931 current_peak = history.last_peak * from_db(-falloff_db_sec * (history.age_seconds - hold_sec));
934 // See if we have a new peak to replace the old (possibly falling) one.
935 if (peak_levels[channel] > current_peak) {
936 history.last_peak = peak_levels[channel];
937 history.age_seconds = 0.0f; // Not 100% correct, but more than good enough given our frame sizes.
938 current_peak = peak_levels[channel];
940 history.age_seconds += float(left.size()) / OUTPUT_FREQUENCY;
942 history.current_level = peak_levels[channel];
943 history.current_peak = current_peak;
947 void AudioMixer::update_meters(const vector<float> &samples)
949 // Upsample 4x to find interpolated peak.
950 peak_resampler.inp_data = const_cast<float *>(samples.data());
951 peak_resampler.inp_count = samples.size() / 2;
953 vector<float> interpolated_samples;
954 interpolated_samples.resize(samples.size());
956 lock_guard<mutex> lock(audio_measure_mutex);
958 while (peak_resampler.inp_count > 0) { // About four iterations.
959 peak_resampler.out_data = &interpolated_samples[0];
960 peak_resampler.out_count = interpolated_samples.size() / 2;
961 peak_resampler.process();
962 size_t out_stereo_samples = interpolated_samples.size() / 2 - peak_resampler.out_count;
963 peak = max<float>(peak, find_peak(interpolated_samples.data(), out_stereo_samples * 2));
964 peak_resampler.out_data = nullptr;
968 // Find R128 levels and L/R correlation.
969 vector<float> left, right;
970 deinterleave_samples(samples, &left, &right);
971 float *ptrs[] = { left.data(), right.data() };
973 lock_guard<mutex> lock(audio_measure_mutex);
974 r128.process(left.size(), ptrs);
975 correlation.process_samples(samples);
978 send_audio_level_callback();
981 void AudioMixer::reset_meters()
983 lock_guard<mutex> lock(audio_measure_mutex);
984 peak_resampler.reset();
991 void AudioMixer::send_audio_level_callback()
993 if (audio_level_callback == nullptr) {
997 lock_guard<mutex> lock(audio_measure_mutex);
998 double loudness_s = r128.loudness_S();
999 double loudness_i = r128.integrated();
1000 double loudness_range_low = r128.range_min();
1001 double loudness_range_high = r128.range_max();
1003 metric_audio_loudness_short_lufs = loudness_s;
1004 metric_audio_loudness_integrated_lufs = loudness_i;
1005 metric_audio_loudness_range_low_lufs = loudness_range_low;
1006 metric_audio_loudness_range_high_lufs = loudness_range_high;
1007 metric_audio_peak_dbfs = to_db(peak);
1008 metric_audio_final_makeup_gain_db = to_db(final_makeup_gain);
1009 metric_audio_correlation = correlation.get_correlation();
1011 vector<BusLevel> bus_levels;
1012 bus_levels.resize(input_mapping.buses.size());
1014 lock_guard<mutex> lock(compressor_mutex);
1015 for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) {
1016 BusLevel &levels = bus_levels[bus_index];
1017 BusMetrics &metrics = bus_metrics[bus_index];
1019 levels.current_level_dbfs[0] = metrics.current_level_dbfs[0] = to_db(peak_history[bus_index][0].current_level);
1020 levels.current_level_dbfs[1] = metrics.current_level_dbfs[1] = to_db(peak_history[bus_index][1].current_level);
1021 levels.peak_level_dbfs[0] = metrics.peak_level_dbfs[0] = to_db(peak_history[bus_index][0].current_peak);
1022 levels.peak_level_dbfs[1] = metrics.peak_level_dbfs[1] = to_db(peak_history[bus_index][1].current_peak);
1023 levels.historic_peak_dbfs = metrics.historic_peak_dbfs = to_db(
1024 max(peak_history[bus_index][0].historic_peak,
1025 peak_history[bus_index][1].historic_peak));
1026 levels.gain_staging_db = metrics.gain_staging_db = gain_staging_db[bus_index];
1027 if (compressor_enabled[bus_index]) {
1028 levels.compressor_attenuation_db = metrics.compressor_attenuation_db = -to_db(compressor[bus_index]->get_attenuation());
1030 levels.compressor_attenuation_db = 0.0;
1031 metrics.compressor_attenuation_db = 0.0 / 0.0;
1036 audio_level_callback(loudness_s, to_db(peak), bus_levels,
1037 loudness_i, loudness_range_low, loudness_range_high,
1038 to_db(final_makeup_gain),
1039 correlation.get_correlation());
1042 map<DeviceSpec, DeviceInfo> AudioMixer::get_devices(HoldDevices hold_devices)
1044 lock_guard<timed_mutex> lock(audio_mutex);
1046 map<DeviceSpec, DeviceInfo> devices;
1047 for (unsigned card_index = 0; card_index < num_capture_cards; ++card_index) {
1048 const DeviceSpec spec{ InputSourceType::CAPTURE_CARD, card_index };
1049 const AudioDevice *device = &video_cards[card_index];
1051 info.display_name = device->display_name;
1052 info.num_channels = 8;
1053 devices.insert(make_pair(spec, info));
1055 vector<ALSAPool::Device> available_alsa_devices = alsa_pool.get_devices(hold_devices);
1056 for (unsigned card_index = 0; card_index < available_alsa_devices.size(); ++card_index) {
1057 const DeviceSpec spec{ InputSourceType::ALSA_INPUT, card_index };
1058 const ALSAPool::Device &device = available_alsa_devices[card_index];
1060 info.display_name = device.display_name();
1061 info.num_channels = device.num_channels;
1062 info.alsa_name = device.name;
1063 info.alsa_info = device.info;
1064 info.alsa_address = device.address;
1065 devices.insert(make_pair(spec, info));
1067 for (unsigned card_index = 0; card_index < num_ffmpeg_inputs; ++card_index) {
1068 const DeviceSpec spec{ InputSourceType::FFMPEG_VIDEO_INPUT, card_index };
1069 const AudioDevice *device = &ffmpeg_inputs[card_index];
1071 info.display_name = device->display_name;
1072 info.num_channels = 2;
1073 devices.insert(make_pair(spec, info));
1078 void AudioMixer::set_display_name(DeviceSpec device_spec, const string &name)
1080 AudioDevice *device = find_audio_device(device_spec);
1082 lock_guard<timed_mutex> lock(audio_mutex);
1083 device->display_name = name;
1086 void AudioMixer::serialize_device(DeviceSpec device_spec, DeviceSpecProto *device_spec_proto)
1088 lock_guard<timed_mutex> lock(audio_mutex);
1089 switch (device_spec.type) {
1090 case InputSourceType::SILENCE:
1091 device_spec_proto->set_type(DeviceSpecProto::SILENCE);
1093 case InputSourceType::CAPTURE_CARD:
1094 device_spec_proto->set_type(DeviceSpecProto::CAPTURE_CARD);
1095 device_spec_proto->set_index(device_spec.index);
1096 device_spec_proto->set_display_name(video_cards[device_spec.index].display_name);
1098 case InputSourceType::ALSA_INPUT:
1099 alsa_pool.serialize_device(device_spec.index, device_spec_proto);
1101 case InputSourceType::FFMPEG_VIDEO_INPUT:
1102 device_spec_proto->set_type(DeviceSpecProto::FFMPEG_VIDEO_INPUT);
1103 device_spec_proto->set_index(device_spec.index);
1104 device_spec_proto->set_display_name(ffmpeg_inputs[device_spec.index].display_name);
1109 void AudioMixer::set_simple_input(unsigned card_index)
1111 assert(card_index < num_capture_cards + num_ffmpeg_inputs);
1112 InputMapping new_input_mapping;
1113 InputMapping::Bus input;
1114 input.name = "Main";
1115 if (card_index >= num_capture_cards) {
1116 input.device = DeviceSpec{InputSourceType::FFMPEG_VIDEO_INPUT, card_index - num_capture_cards};
1118 input.device = DeviceSpec{InputSourceType::CAPTURE_CARD, card_index};
1120 input.source_channel[0] = 0;
1121 input.source_channel[1] = 1;
1123 new_input_mapping.buses.push_back(input);
1125 // NOTE: Delay is implicitly at 0.0 ms, since none has been set in the mapping.
1127 lock_guard<timed_mutex> lock(audio_mutex);
1128 current_mapping_mode = MappingMode::SIMPLE;
1129 set_input_mapping_lock_held(new_input_mapping);
1130 fader_volume_db[0] = 0.0f;
1133 unsigned AudioMixer::get_simple_input() const
1135 lock_guard<timed_mutex> lock(audio_mutex);
1136 if (input_mapping.buses.size() == 1 &&
1137 input_mapping.buses[0].device.type == InputSourceType::CAPTURE_CARD &&
1138 input_mapping.buses[0].source_channel[0] == 0 &&
1139 input_mapping.buses[0].source_channel[1] == 1) {
1140 return input_mapping.buses[0].device.index;
1141 } else if (input_mapping.buses.size() == 1 &&
1142 input_mapping.buses[0].device.type == InputSourceType::FFMPEG_VIDEO_INPUT &&
1143 input_mapping.buses[0].source_channel[0] == 0 &&
1144 input_mapping.buses[0].source_channel[1] == 1) {
1145 return input_mapping.buses[0].device.index + num_capture_cards;
1147 return numeric_limits<unsigned>::max();
1151 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
1153 lock_guard<timed_mutex> lock(audio_mutex);
1154 set_input_mapping_lock_held(new_input_mapping);
1155 current_mapping_mode = MappingMode::MULTICHANNEL;
1158 AudioMixer::MappingMode AudioMixer::get_mapping_mode() const
1160 lock_guard<timed_mutex> lock(audio_mutex);
1161 return current_mapping_mode;
1164 void AudioMixer::set_input_mapping_lock_held(const InputMapping &new_input_mapping)
1166 map<DeviceSpec, set<unsigned>> interesting_channels;
1167 for (const InputMapping::Bus &bus : new_input_mapping.buses) {
1168 if (bus.device.type == InputSourceType::CAPTURE_CARD ||
1169 bus.device.type == InputSourceType::ALSA_INPUT ||
1170 bus.device.type == InputSourceType::FFMPEG_VIDEO_INPUT) {
1171 for (unsigned channel = 0; channel < 2; ++channel) {
1172 if (bus.source_channel[channel] != -1) {
1173 interesting_channels[bus.device].insert(bus.source_channel[channel]);
1177 assert(bus.device.type == InputSourceType::SILENCE);
1181 // Kill all the old metrics, and set up new ones.
1182 for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
1183 BusMetrics &metrics = bus_metrics[bus_index];
1185 vector<pair<string, string>> labels_left = metrics.labels;
1186 labels_left.emplace_back("channel", "left");
1187 vector<pair<string, string>> labels_right = metrics.labels;
1188 labels_right.emplace_back("channel", "right");
1190 global_metrics.remove("bus_current_level_dbfs", labels_left);
1191 global_metrics.remove("bus_current_level_dbfs", labels_right);
1192 global_metrics.remove("bus_peak_level_dbfs", labels_left);
1193 global_metrics.remove("bus_peak_level_dbfs", labels_right);
1194 global_metrics.remove("bus_historic_peak_dbfs", metrics.labels);
1195 global_metrics.remove("bus_gain_staging_db", metrics.labels);
1196 global_metrics.remove("bus_compressor_attenuation_db", metrics.labels);
1198 bus_metrics.reset(new BusMetrics[new_input_mapping.buses.size()]);
1199 for (unsigned bus_index = 0; bus_index < new_input_mapping.buses.size(); ++bus_index) {
1200 const InputMapping::Bus &bus = new_input_mapping.buses[bus_index];
1201 BusMetrics &metrics = bus_metrics[bus_index];
1203 char bus_index_str[16], source_index_str[16], source_channels_str[64];
1204 snprintf(bus_index_str, sizeof(bus_index_str), "%u", bus_index);
1205 snprintf(source_index_str, sizeof(source_index_str), "%u", bus.device.index);
1206 snprintf(source_channels_str, sizeof(source_channels_str), "%d:%d", bus.source_channel[0], bus.source_channel[1]);
1208 vector<pair<string, string>> labels;
1209 metrics.labels.emplace_back("index", bus_index_str);
1210 metrics.labels.emplace_back("name", bus.name);
1211 if (bus.device.type == InputSourceType::SILENCE) {
1212 metrics.labels.emplace_back("source_type", "silence");
1213 } else if (bus.device.type == InputSourceType::CAPTURE_CARD) {
1214 metrics.labels.emplace_back("source_type", "capture_card");
1215 } else if (bus.device.type == InputSourceType::ALSA_INPUT) {
1216 metrics.labels.emplace_back("source_type", "alsa_input");
1217 } else if (bus.device.type == InputSourceType::FFMPEG_VIDEO_INPUT) {
1218 metrics.labels.emplace_back("source_type", "ffmpeg_video_input");
1222 metrics.labels.emplace_back("source_index", source_index_str);
1223 metrics.labels.emplace_back("source_channels", source_channels_str);
1225 vector<pair<string, string>> labels_left = metrics.labels;
1226 labels_left.emplace_back("channel", "left");
1227 vector<pair<string, string>> labels_right = metrics.labels;
1228 labels_right.emplace_back("channel", "right");
1230 global_metrics.add("bus_current_level_dbfs", labels_left, &metrics.current_level_dbfs[0], Metrics::TYPE_GAUGE);
1231 global_metrics.add("bus_current_level_dbfs", labels_right, &metrics.current_level_dbfs[1], Metrics::TYPE_GAUGE);
1232 global_metrics.add("bus_peak_level_dbfs", labels_left, &metrics.peak_level_dbfs[0], Metrics::TYPE_GAUGE);
1233 global_metrics.add("bus_peak_level_dbfs", labels_right, &metrics.peak_level_dbfs[1], Metrics::TYPE_GAUGE);
1234 global_metrics.add("bus_historic_peak_dbfs", metrics.labels, &metrics.historic_peak_dbfs, Metrics::TYPE_GAUGE);
1235 global_metrics.add("bus_gain_staging_db", metrics.labels, &metrics.gain_staging_db, Metrics::TYPE_GAUGE);
1236 global_metrics.add("bus_compressor_attenuation_db", metrics.labels, &metrics.compressor_attenuation_db, Metrics::TYPE_GAUGE);
1239 // Reset resamplers for all cards that don't have the exact same state as before.
1240 map<DeviceSpec, double> new_extra_delay_ms = new_input_mapping.extra_delay_ms; // Convenience so we can use [].
1241 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
1242 const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
1243 AudioDevice *device = find_audio_device(device_spec);
1244 double extra_delay_ms = new_extra_delay_ms[device_spec];
1245 if (device->interesting_channels != interesting_channels[device_spec]) {
1246 device->interesting_channels = interesting_channels[device_spec];
1247 device->extra_delay_ms = extra_delay_ms;
1248 reset_resampler_mutex_held(device_spec);
1249 } else if (device->extra_delay_ms != extra_delay_ms &&
1250 device->resampling_queue != nullptr) {
1251 device->extra_delay_ms = extra_delay_ms;
1252 device->resampling_queue->change_expected_delay(get_delay_seconds(extra_delay_ms));
1255 for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
1256 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
1257 AudioDevice *device = find_audio_device(device_spec);
1258 double extra_delay_ms = new_extra_delay_ms[device_spec];
1259 if (device->interesting_channels != interesting_channels[device_spec]) {
1260 device->interesting_channels = interesting_channels[device_spec];
1261 device->extra_delay_ms = extra_delay_ms;
1262 reset_resampler_mutex_held(device_spec);
1263 } else if (device->extra_delay_ms != extra_delay_ms &&
1264 device->resampling_queue != nullptr) {
1265 device->extra_delay_ms = extra_delay_ms;
1266 device->resampling_queue->change_expected_delay(get_delay_seconds(extra_delay_ms));
1268 start_or_stop_alsa_capture(device_spec);
1270 for (unsigned card_index = 0; card_index < num_ffmpeg_inputs; ++card_index) {
1271 const DeviceSpec device_spec{InputSourceType::FFMPEG_VIDEO_INPUT, card_index};
1272 AudioDevice *device = find_audio_device(device_spec);
1273 double extra_delay_ms = new_extra_delay_ms[device_spec];
1274 if (device->interesting_channels != interesting_channels[device_spec]) {
1275 device->interesting_channels = interesting_channels[device_spec];
1276 device->extra_delay_ms = extra_delay_ms;
1277 reset_resampler_mutex_held(device_spec);
1278 } else if (device->extra_delay_ms != extra_delay_ms &&
1279 device->resampling_queue != nullptr) {
1280 device->extra_delay_ms = extra_delay_ms;
1281 device->resampling_queue->change_expected_delay(get_delay_seconds(extra_delay_ms));
1285 input_mapping = new_input_mapping;
1288 InputMapping AudioMixer::get_input_mapping() const
1290 lock_guard<timed_mutex> lock(audio_mutex);
1291 return input_mapping;
1294 void AudioMixer::set_extra_devices(const set<DeviceSpec> &devices)
1296 lock_guard<timed_mutex> lock(audio_mutex);
1297 extra_devices = devices;
1298 for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
1299 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
1300 start_or_stop_alsa_capture(device_spec);
1304 unsigned AudioMixer::num_buses() const
1306 lock_guard<timed_mutex> lock(audio_mutex);
1307 return input_mapping.buses.size();
1310 void AudioMixer::reset_peak(unsigned bus_index)
1312 lock_guard<timed_mutex> lock(audio_mutex);
1313 for (unsigned channel = 0; channel < 2; ++channel) {
1314 PeakHistory &history = peak_history[bus_index][channel];
1315 history.current_level = 0.0f;
1316 history.historic_peak = 0.0f;
1317 history.current_peak = 0.0f;
1318 history.last_peak = 0.0f;
1319 history.age_seconds = 0.0f;
1323 bool AudioMixer::is_mono(unsigned bus_index)
1325 lock_guard<timed_mutex> lock(audio_mutex);
1326 const InputMapping::Bus &bus = input_mapping.buses[bus_index];
1327 if (bus.device.type == InputSourceType::SILENCE) {
1330 assert(bus.device.type == InputSourceType::CAPTURE_CARD ||
1331 bus.device.type == InputSourceType::ALSA_INPUT ||
1332 bus.device.type == InputSourceType::FFMPEG_VIDEO_INPUT);
1333 return bus.source_channel[0] == bus.source_channel[1];
1337 void AudioMixer::start_or_stop_alsa_capture(DeviceSpec device_spec)
1339 assert(device_spec.type == InputSourceType::ALSA_INPUT);
1340 AudioDevice *device = find_audio_device(device_spec);
1341 bool previously_held = alsa_pool.device_is_held(device_spec.index);
1342 bool should_be_held = !device->interesting_channels.empty() || extra_devices.count(device_spec);
1343 if (should_be_held) {
1344 alsa_pool.hold_device(device_spec.index);
1346 alsa_pool.release_device(device_spec.index);
1348 if (previously_held != should_be_held) {
1349 alsa_pool.reset_device(device_spec.index);
1353 AudioMixer *global_audio_mixer = nullptr;