1 #include "audio_mixer.h"
5 #include <bmusb/bmusb.h>
11 #include <immintrin.h>
20 using namespace bmusb;
22 using namespace std::placeholders;
26 // TODO: If these prove to be a bottleneck, they can be SSSE3-optimized
27 // (usually including multiple channels at a time).
29 void convert_fixed16_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
30 const uint8_t *src, size_t in_channel, size_t in_num_channels,
33 assert(in_channel < in_num_channels);
34 assert(out_channel < out_num_channels);
35 src += in_channel * 2;
38 for (size_t i = 0; i < num_samples; ++i) {
39 int16_t s = le16toh(*(int16_t *)src);
40 *dst = s * (1.0f / 32768.0f);
42 src += 2 * in_num_channels;
43 dst += out_num_channels;
47 void convert_fixed24_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
48 const uint8_t *src, size_t in_channel, size_t in_num_channels,
51 assert(in_channel < in_num_channels);
52 assert(out_channel < out_num_channels);
53 src += in_channel * 3;
56 for (size_t i = 0; i < num_samples; ++i) {
60 uint32_t s = s1 | (s1 << 8) | (s2 << 16) | (s3 << 24);
61 *dst = int(s) * (1.0f / 2147483648.0f);
63 src += 3 * in_num_channels;
64 dst += out_num_channels;
68 void convert_fixed32_to_fp32(float *dst, size_t out_channel, size_t out_num_channels,
69 const uint8_t *src, size_t in_channel, size_t in_num_channels,
72 assert(in_channel < in_num_channels);
73 assert(out_channel < out_num_channels);
74 src += in_channel * 4;
77 for (size_t i = 0; i < num_samples; ++i) {
78 int32_t s = le32toh(*(int32_t *)src);
79 *dst = s * (1.0f / 2147483648.0f);
81 src += 4 * in_num_channels;
82 dst += out_num_channels;
86 float find_peak_plain(const float *samples, size_t num_samples) __attribute__((unused));
88 float find_peak_plain(const float *samples, size_t num_samples)
90 float m = fabs(samples[0]);
91 for (size_t i = 1; i < num_samples; ++i) {
92 m = max(m, fabs(samples[i]));
98 static inline float horizontal_max(__m128 m)
100 __m128 tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 0, 3, 2));
101 m = _mm_max_ps(m, tmp);
102 tmp = _mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 3, 0, 1));
103 m = _mm_max_ps(m, tmp);
104 return _mm_cvtss_f32(m);
107 float find_peak(const float *samples, size_t num_samples)
109 const __m128 abs_mask = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffffu));
110 __m128 m = _mm_setzero_ps();
111 for (size_t i = 0; i < (num_samples & ~3); i += 4) {
112 __m128 x = _mm_loadu_ps(samples + i);
113 x = _mm_and_ps(x, abs_mask);
114 m = _mm_max_ps(m, x);
116 float result = horizontal_max(m);
118 for (size_t i = (num_samples & ~3); i < num_samples; ++i) {
119 result = max(result, fabs(samples[i]));
123 // Self-test. We should be bit-exact the same.
124 float reference_result = find_peak_plain(samples, num_samples);
125 if (result != reference_result) {
126 fprintf(stderr, "Error: Peak is %f [%f %f %f %f]; should be %f.\n",
128 _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(0, 0, 0, 0))),
129 _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(1, 1, 1, 1))),
130 _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(2, 2, 2, 2))),
131 _mm_cvtss_f32(_mm_shuffle_ps(m, m, _MM_SHUFFLE(3, 3, 3, 3))),
139 float find_peak(const float *samples, size_t num_samples)
141 return find_peak_plain(samples, num_samples);
145 void deinterleave_samples(const vector<float> &in, vector<float> *out_l, vector<float> *out_r)
147 size_t num_samples = in.size() / 2;
148 out_l->resize(num_samples);
149 out_r->resize(num_samples);
151 const float *inptr = in.data();
152 float *lptr = &(*out_l)[0];
153 float *rptr = &(*out_r)[0];
154 for (size_t i = 0; i < num_samples; ++i) {
162 AudioMixer::AudioMixer(unsigned num_cards)
163 : num_cards(num_cards),
164 limiter(OUTPUT_FREQUENCY),
165 correlation(OUTPUT_FREQUENCY)
167 global_audio_mixer = this;
169 for (unsigned bus_index = 0; bus_index < MAX_BUSES; ++bus_index) {
170 locut[bus_index].init(FILTER_HPF, 2);
171 eq[bus_index][EQ_BAND_BASS].init(FILTER_LOW_SHELF, 1);
172 // Note: EQ_BAND_MID isn't used (see comments in apply_eq()).
173 eq[bus_index][EQ_BAND_TREBLE].init(FILTER_HIGH_SHELF, 1);
174 compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
175 level_compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY));
177 set_bus_settings(bus_index, get_default_bus_settings());
179 set_limiter_enabled(global_flags.limiter_enabled);
180 set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto);
183 if (!global_flags.input_mapping_filename.empty()) {
184 current_mapping_mode = MappingMode::MULTICHANNEL;
185 InputMapping new_input_mapping;
186 if (!load_input_mapping_from_file(get_devices(),
187 global_flags.input_mapping_filename,
188 &new_input_mapping)) {
189 fprintf(stderr, "Failed to load input mapping from '%s', exiting.\n",
190 global_flags.input_mapping_filename.c_str());
193 set_input_mapping(new_input_mapping);
195 set_simple_input(/*card_index=*/0);
196 if (global_flags.multichannel_mapping_mode) {
197 current_mapping_mode = MappingMode::MULTICHANNEL;
201 r128.init(2, OUTPUT_FREQUENCY);
204 // hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise,
205 // and there's a limit to how important the peak meter is.
206 peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0);
209 void AudioMixer::reset_resampler(DeviceSpec device_spec)
211 lock_guard<timed_mutex> lock(audio_mutex);
212 reset_resampler_mutex_held(device_spec);
215 void AudioMixer::reset_resampler_mutex_held(DeviceSpec device_spec)
217 AudioDevice *device = find_audio_device(device_spec);
219 if (device->interesting_channels.empty()) {
220 device->resampling_queue.reset();
222 // TODO: ResamplingQueue should probably take the full device spec.
223 // (It's only used for console output, though.)
224 device->resampling_queue.reset(new ResamplingQueue(device_spec.index, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size()));
226 device->next_local_pts = 0;
229 bool AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length)
231 AudioDevice *device = find_audio_device(device_spec);
233 unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
234 if (!lock.try_lock_for(chrono::milliseconds(10))) {
237 if (device->resampling_queue == nullptr) {
238 // No buses use this device; throw it away.
242 unsigned num_channels = device->interesting_channels.size();
243 assert(num_channels > 0);
245 // Convert the audio to fp32.
246 unique_ptr<float[]> audio(new float[num_samples * num_channels]);
247 unsigned channel_index = 0;
248 for (auto channel_it = device->interesting_channels.cbegin(); channel_it != device->interesting_channels.end(); ++channel_it, ++channel_index) {
249 switch (audio_format.bits_per_sample) {
251 assert(num_samples == 0);
254 convert_fixed16_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
257 convert_fixed24_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
260 convert_fixed32_to_fp32(audio.get(), channel_index, num_channels, data, *channel_it, audio_format.num_channels, num_samples);
263 fprintf(stderr, "Cannot handle audio with %u bits per sample\n", audio_format.bits_per_sample);
269 int64_t local_pts = device->next_local_pts;
270 device->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.get(), num_samples);
271 device->next_local_pts = local_pts + frame_length;
275 bool AudioMixer::add_silence(DeviceSpec device_spec, unsigned samples_per_frame, unsigned num_frames, int64_t frame_length)
277 AudioDevice *device = find_audio_device(device_spec);
279 unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
280 if (!lock.try_lock_for(chrono::milliseconds(10))) {
283 if (device->resampling_queue == nullptr) {
284 // No buses use this device; throw it away.
288 unsigned num_channels = device->interesting_channels.size();
289 assert(num_channels > 0);
291 vector<float> silence(samples_per_frame * num_channels, 0.0f);
292 for (unsigned i = 0; i < num_frames; ++i) {
293 device->resampling_queue->add_input_samples(device->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame);
294 // Note that if the format changed in the meantime, we have
295 // no way of detecting that; we just have to assume the frame length
296 // is always the same.
297 device->next_local_pts += frame_length;
302 bool AudioMixer::silence_card(DeviceSpec device_spec, bool silence)
304 AudioDevice *device = find_audio_device(device_spec);
306 unique_lock<timed_mutex> lock(audio_mutex, defer_lock);
307 if (!lock.try_lock_for(chrono::milliseconds(10))) {
311 if (device->silenced && !silence) {
312 reset_resampler_mutex_held(device_spec);
314 device->silenced = silence;
318 AudioMixer::BusSettings AudioMixer::get_default_bus_settings()
320 BusSettings settings;
321 settings.fader_volume_db = 0.0f;
322 settings.locut_enabled = global_flags.locut_enabled;
323 for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
324 settings.eq_level_db[band_index] = 0.0f;
326 settings.gain_staging_db = global_flags.initial_gain_staging_db;
327 settings.level_compressor_enabled = global_flags.gain_staging_auto;
328 settings.compressor_threshold_dbfs = ref_level_dbfs - 12.0f; // -12 dB.
329 settings.compressor_enabled = global_flags.compressor_enabled;
333 AudioMixer::BusSettings AudioMixer::get_bus_settings(unsigned bus_index) const
335 lock_guard<timed_mutex> lock(audio_mutex);
336 BusSettings settings;
337 settings.fader_volume_db = fader_volume_db[bus_index];
338 settings.locut_enabled = locut_enabled[bus_index];
339 for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
340 settings.eq_level_db[band_index] = eq_level_db[bus_index][band_index];
342 settings.gain_staging_db = gain_staging_db[bus_index];
343 settings.level_compressor_enabled = level_compressor_enabled[bus_index];
344 settings.compressor_threshold_dbfs = compressor_threshold_dbfs[bus_index];
345 settings.compressor_enabled = compressor_enabled[bus_index];
349 void AudioMixer::set_bus_settings(unsigned bus_index, const AudioMixer::BusSettings &settings)
351 lock_guard<timed_mutex> lock(audio_mutex);
352 fader_volume_db[bus_index] = settings.fader_volume_db;
353 locut_enabled[bus_index] = settings.locut_enabled;
354 for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) {
355 eq_level_db[bus_index][band_index] = settings.eq_level_db[band_index];
357 gain_staging_db[bus_index] = settings.gain_staging_db;
358 last_gain_staging_db[bus_index] = gain_staging_db[bus_index];
359 level_compressor_enabled[bus_index] = settings.level_compressor_enabled;
360 compressor_threshold_dbfs[bus_index] = settings.compressor_threshold_dbfs;
361 compressor_enabled[bus_index] = settings.compressor_enabled;
364 AudioMixer::AudioDevice *AudioMixer::find_audio_device(DeviceSpec device)
366 switch (device.type) {
367 case InputSourceType::CAPTURE_CARD:
368 return &video_cards[device.index];
369 case InputSourceType::ALSA_INPUT:
370 return &alsa_inputs[device.index];
371 case InputSourceType::SILENCE:
378 // Get a pointer to the given channel from the given device.
379 // The channel must be picked out earlier and resampled.
380 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)
382 static float zero = 0.0f;
383 if (source_channel == -1 || device_spec.type == InputSourceType::SILENCE) {
388 AudioDevice *device = find_audio_device(device_spec);
389 assert(device->interesting_channels.count(source_channel) != 0);
390 unsigned channel_index = 0;
391 for (int channel : device->interesting_channels) {
392 if (channel == source_channel) break;
395 assert(channel_index < device->interesting_channels.size());
396 const auto it = samples_card.find(device_spec);
397 assert(it != samples_card.end());
398 *srcptr = &(it->second)[channel_index];
399 *stride = device->interesting_channels.size();
402 // TODO: Can be SSSE3-optimized if need be.
403 void AudioMixer::fill_audio_bus(const map<DeviceSpec, vector<float>> &samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output)
405 if (bus.device.type == InputSourceType::SILENCE) {
406 memset(output, 0, num_samples * sizeof(*output));
408 assert(bus.device.type == InputSourceType::CAPTURE_CARD ||
409 bus.device.type == InputSourceType::ALSA_INPUT);
410 const float *lsrc, *rsrc;
411 unsigned lstride, rstride;
412 float *dptr = output;
413 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[0], &lsrc, &lstride);
414 find_sample_src_from_device(samples_card, bus.device, bus.source_channel[1], &rsrc, &rstride);
415 for (unsigned i = 0; i < num_samples; ++i) {
424 vector<DeviceSpec> AudioMixer::get_active_devices() const
426 vector<DeviceSpec> ret;
427 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
428 const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
429 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
430 ret.push_back(device_spec);
433 for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
434 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
435 if (!find_audio_device(device_spec)->interesting_channels.empty()) {
436 ret.push_back(device_spec);
444 void apply_gain(float db, float last_db, vector<float> *samples)
446 if (fabs(db - last_db) < 1e-3) {
447 // Constant over this frame.
448 const float gain = from_db(db);
449 for (size_t i = 0; i < samples->size(); ++i) {
450 (*samples)[i] *= gain;
453 // We need to do a fade.
454 unsigned num_samples = samples->size() / 2;
455 float gain = from_db(last_db);
456 const float gain_inc = pow(from_db(db - last_db), 1.0 / num_samples);
457 for (size_t i = 0; i < num_samples; ++i) {
458 (*samples)[i * 2 + 0] *= gain;
459 (*samples)[i * 2 + 1] *= gain;
467 vector<float> AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy)
469 map<DeviceSpec, vector<float>> samples_card;
470 vector<float> samples_bus;
472 lock_guard<timed_mutex> lock(audio_mutex);
474 // Pick out all the interesting channels from all the cards.
475 for (const DeviceSpec &device_spec : get_active_devices()) {
476 AudioDevice *device = find_audio_device(device_spec);
477 samples_card[device_spec].resize(num_samples * device->interesting_channels.size());
478 if (device->silenced) {
479 memset(&samples_card[device_spec][0], 0, samples_card[device_spec].size() * sizeof(float));
481 device->resampling_queue->get_output_samples(
483 &samples_card[device_spec][0],
485 rate_adjustment_policy);
489 vector<float> samples_out, left, right;
490 samples_out.resize(num_samples * 2);
491 samples_bus.resize(num_samples * 2);
492 for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) {
493 fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]);
494 apply_eq(bus_index, &samples_bus);
497 lock_guard<mutex> lock(compressor_mutex);
499 // Apply a level compressor to get the general level right.
500 // Basically, if it's over about -40 dBFS, we squeeze it down to that level
501 // (or more precisely, near it, since we don't use infinite ratio),
502 // then apply a makeup gain to get it to -14 dBFS. -14 dBFS is, of course,
503 // entirely arbitrary, but from practical tests with speech, it seems to
504 // put ut around -23 LUFS, so it's a reasonable starting point for later use.
505 if (level_compressor_enabled[bus_index]) {
506 float threshold = 0.01f; // -40 dBFS.
508 float attack_time = 0.5f;
509 float release_time = 20.0f;
510 float makeup_gain = from_db(ref_level_dbfs - (-40.0f)); // +26 dB.
511 level_compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
512 gain_staging_db[bus_index] = to_db(level_compressor[bus_index]->get_attenuation() * makeup_gain);
514 // Just apply the gain we already had.
515 float db = gain_staging_db[bus_index];
516 float last_db = last_gain_staging_db[bus_index];
517 apply_gain(db, last_db, &samples_bus);
519 last_gain_staging_db[bus_index] = gain_staging_db[bus_index];
522 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n",
523 level_compressor.get_level(), to_db(level_compressor.get_level()),
524 level_compressor.get_attenuation(), to_db(level_compressor.get_attenuation()),
525 to_db(level_compressor.get_level() * level_compressor.get_attenuation() * makeup_gain));
528 // The real compressor.
529 if (compressor_enabled[bus_index]) {
530 float threshold = from_db(compressor_threshold_dbfs[bus_index]);
532 float attack_time = 0.005f;
533 float release_time = 0.040f;
534 float makeup_gain = 2.0f; // +6 dB.
535 compressor[bus_index]->process(samples_bus.data(), samples_bus.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
536 // compressor_att = compressor.get_attenuation();
540 add_bus_to_master(bus_index, samples_bus, &samples_out);
541 deinterleave_samples(samples_bus, &left, &right);
542 measure_bus_levels(bus_index, left, right);
546 lock_guard<mutex> lock(compressor_mutex);
548 // Finally a limiter at -4 dB (so, -10 dBFS) to take out the worst peaks only.
549 // Note that since ratio is not infinite, we could go slightly higher than this.
550 if (limiter_enabled) {
551 float threshold = from_db(limiter_threshold_dbfs);
553 float attack_time = 0.0f; // Instant.
554 float release_time = 0.020f;
555 float makeup_gain = 1.0f; // 0 dB.
556 limiter.process(samples_out.data(), samples_out.size() / 2, threshold, ratio, attack_time, release_time, makeup_gain);
557 // limiter_att = limiter.get_attenuation();
560 // printf("limiter=%+5.1f compressor=%+5.1f\n", to_db(limiter_att), to_db(compressor_att));
563 // At this point, we are most likely close to +0 LU (at least if the
564 // faders sum to 0 dB and the compressors are on), but all of our
565 // measurements have been on raw sample values, not R128 values.
566 // So we have a final makeup gain to get us to +0 LU; the gain
567 // adjustments required should be relatively small, and also, the
568 // offset shouldn't change much (only if the type of audio changes
569 // significantly). Thus, we shoot for updating this value basically
570 // “whenever we process buffers”, since the R128 calculation isn't exactly
571 // something we get out per-sample.
573 // Note that there's a feedback loop here, so we choose a very slow filter
574 // (half-time of 30 seconds).
575 double target_loudness_factor, alpha;
576 double loudness_lu = r128.loudness_M() - ref_level_lufs;
577 double current_makeup_lu = to_db(final_makeup_gain);
578 target_loudness_factor = final_makeup_gain * from_db(-loudness_lu);
580 // If we're outside +/- 5 LU uncorrected, we don't count it as
581 // a normal signal (probably silence) and don't change the
582 // correction factor; just apply what we already have.
583 if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) {
586 // Formula adapted from
587 // https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter.
588 const double half_time_s = 30.0;
589 const double fc_mul_2pi_delta_t = 1.0 / (half_time_s * OUTPUT_FREQUENCY);
590 alpha = fc_mul_2pi_delta_t / (fc_mul_2pi_delta_t + 1.0);
594 lock_guard<mutex> lock(compressor_mutex);
595 double m = final_makeup_gain;
596 for (size_t i = 0; i < samples_out.size(); i += 2) {
597 samples_out[i + 0] *= m;
598 samples_out[i + 1] *= m;
599 m += (target_loudness_factor - m) * alpha;
601 final_makeup_gain = m;
604 update_meters(samples_out);
611 void apply_filter_fade(StereoFilter *filter, float *data, unsigned num_samples, float cutoff_hz, float db, float last_db)
613 // A granularity of 32 samples is an okay tradeoff between speed and
614 // smoothness; recalculating the filters is pretty expensive, so it's
615 // good that we don't do this all the time.
616 static constexpr unsigned filter_granularity_samples = 32;
618 const float cutoff_linear = cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY;
619 if (fabs(db - last_db) < 1e-3) {
620 // Constant over this frame.
621 if (fabs(db) > 0.01f) {
622 filter->render(data, num_samples, cutoff_linear, 0.5f, db / 40.0f);
625 // We need to do a fade. (Rounding up avoids division by zero.)
626 unsigned num_blocks = (num_samples + filter_granularity_samples - 1) / filter_granularity_samples;
627 const float inc_db_norm = (db - last_db) / 40.0f / num_blocks;
628 float db_norm = db / 40.0f;
629 for (size_t i = 0; i < num_samples; i += filter_granularity_samples) {
630 size_t samples_this_block = std::min<size_t>(num_samples - i, filter_granularity_samples);
631 filter->render(data + i * 2, samples_this_block, cutoff_linear, 0.5f, db_norm);
632 db_norm += inc_db_norm;
639 void AudioMixer::apply_eq(unsigned bus_index, vector<float> *samples_bus)
641 constexpr float bass_freq_hz = 200.0f;
642 constexpr float treble_freq_hz = 4700.0f;
644 // Cut away everything under 120 Hz (or whatever the cutoff is);
645 // we don't need it for voice, and it will reduce headroom
646 // and confuse the compressor. (In particular, any hums at 50 or 60 Hz
647 // should be dampened.)
648 if (locut_enabled[bus_index]) {
649 locut[bus_index].render(samples_bus->data(), samples_bus->size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f);
652 // Apply the rest of the EQ. Since we only have a simple three-band EQ,
653 // we can implement it with two shelf filters. We use a simple gain to
654 // set the mid-level filter, and then offset the low and high bands
655 // from that if we need to. (We could perhaps have folded the gain into
656 // the next part, but it's so cheap that the trouble isn't worth it.)
658 // If any part of the EQ has changed appreciably since last frame,
659 // we fade smoothly during the course of this frame.
660 const float bass_db = eq_level_db[bus_index][EQ_BAND_BASS];
661 const float mid_db = eq_level_db[bus_index][EQ_BAND_MID];
662 const float treble_db = eq_level_db[bus_index][EQ_BAND_TREBLE];
664 const float last_bass_db = last_eq_level_db[bus_index][EQ_BAND_BASS];
665 const float last_mid_db = last_eq_level_db[bus_index][EQ_BAND_MID];
666 const float last_treble_db = last_eq_level_db[bus_index][EQ_BAND_TREBLE];
668 assert(samples_bus->size() % 2 == 0);
669 const unsigned num_samples = samples_bus->size() / 2;
671 apply_gain(mid_db, last_mid_db, samples_bus);
673 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);
674 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);
676 last_eq_level_db[bus_index][EQ_BAND_BASS] = bass_db;
677 last_eq_level_db[bus_index][EQ_BAND_MID] = mid_db;
678 last_eq_level_db[bus_index][EQ_BAND_TREBLE] = treble_db;
681 void AudioMixer::add_bus_to_master(unsigned bus_index, const vector<float> &samples_bus, vector<float> *samples_out)
683 assert(samples_bus.size() == samples_out->size());
684 assert(samples_bus.size() % 2 == 0);
685 unsigned num_samples = samples_bus.size() / 2;
686 if (fabs(fader_volume_db[bus_index] - last_fader_volume_db[bus_index]) > 1e-3) {
687 // The volume has changed; do a fade over the course of this frame.
688 // (We might have some numerical issues here, but it seems to sound OK.)
689 // For the purpose of fading here, the silence floor is set to -90 dB
690 // (the fader only goes to -84).
691 float old_volume = from_db(max<float>(last_fader_volume_db[bus_index], -90.0f));
692 float volume = from_db(max<float>(fader_volume_db[bus_index], -90.0f));
694 float volume_inc = pow(volume / old_volume, 1.0 / num_samples);
696 if (bus_index == 0) {
697 for (unsigned i = 0; i < num_samples; ++i) {
698 (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
699 (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
700 volume *= volume_inc;
703 for (unsigned i = 0; i < num_samples; ++i) {
704 (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
705 (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
706 volume *= volume_inc;
710 float volume = from_db(fader_volume_db[bus_index]);
711 if (bus_index == 0) {
712 for (unsigned i = 0; i < num_samples; ++i) {
713 (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume;
714 (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume;
717 for (unsigned i = 0; i < num_samples; ++i) {
718 (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume;
719 (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume;
724 last_fader_volume_db[bus_index] = fader_volume_db[bus_index];
727 void AudioMixer::measure_bus_levels(unsigned bus_index, const vector<float> &left, const vector<float> &right)
729 assert(left.size() == right.size());
730 const float volume = from_db(fader_volume_db[bus_index]);
731 const float peak_levels[2] = {
732 find_peak(left.data(), left.size()) * volume,
733 find_peak(right.data(), right.size()) * volume
735 for (unsigned channel = 0; channel < 2; ++channel) {
736 // Compute the current value, including hold and falloff.
737 // The constants are borrowed from zita-mu1 by Fons Adriaensen.
738 static constexpr float hold_sec = 0.5f;
739 static constexpr float falloff_db_sec = 15.0f; // dB/sec falloff after hold.
741 PeakHistory &history = peak_history[bus_index][channel];
742 history.historic_peak = max(history.historic_peak, peak_levels[channel]);
743 if (history.age_seconds < hold_sec) {
744 current_peak = history.last_peak;
746 current_peak = history.last_peak * from_db(-falloff_db_sec * (history.age_seconds - hold_sec));
749 // See if we have a new peak to replace the old (possibly falling) one.
750 if (peak_levels[channel] > current_peak) {
751 history.last_peak = peak_levels[channel];
752 history.age_seconds = 0.0f; // Not 100% correct, but more than good enough given our frame sizes.
753 current_peak = peak_levels[channel];
755 history.age_seconds += float(left.size()) / OUTPUT_FREQUENCY;
757 history.current_level = peak_levels[channel];
758 history.current_peak = current_peak;
762 void AudioMixer::update_meters(const vector<float> &samples)
764 // Upsample 4x to find interpolated peak.
765 peak_resampler.inp_data = const_cast<float *>(samples.data());
766 peak_resampler.inp_count = samples.size() / 2;
768 vector<float> interpolated_samples;
769 interpolated_samples.resize(samples.size());
771 lock_guard<mutex> lock(audio_measure_mutex);
773 while (peak_resampler.inp_count > 0) { // About four iterations.
774 peak_resampler.out_data = &interpolated_samples[0];
775 peak_resampler.out_count = interpolated_samples.size() / 2;
776 peak_resampler.process();
777 size_t out_stereo_samples = interpolated_samples.size() / 2 - peak_resampler.out_count;
778 peak = max<float>(peak, find_peak(interpolated_samples.data(), out_stereo_samples * 2));
779 peak_resampler.out_data = nullptr;
783 // Find R128 levels and L/R correlation.
784 vector<float> left, right;
785 deinterleave_samples(samples, &left, &right);
786 float *ptrs[] = { left.data(), right.data() };
788 lock_guard<mutex> lock(audio_measure_mutex);
789 r128.process(left.size(), ptrs);
790 correlation.process_samples(samples);
793 send_audio_level_callback();
796 void AudioMixer::reset_meters()
798 lock_guard<mutex> lock(audio_measure_mutex);
799 peak_resampler.reset();
806 void AudioMixer::send_audio_level_callback()
808 if (audio_level_callback == nullptr) {
812 lock_guard<mutex> lock(audio_measure_mutex);
813 double loudness_s = r128.loudness_S();
814 double loudness_i = r128.integrated();
815 double loudness_range_low = r128.range_min();
816 double loudness_range_high = r128.range_max();
818 vector<BusLevel> bus_levels;
819 bus_levels.resize(input_mapping.buses.size());
821 lock_guard<mutex> lock(compressor_mutex);
822 for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) {
823 bus_levels[bus_index].current_level_dbfs[0] = to_db(peak_history[bus_index][0].current_level);
824 bus_levels[bus_index].current_level_dbfs[1] = to_db(peak_history[bus_index][1].current_level);
825 bus_levels[bus_index].peak_level_dbfs[0] = to_db(peak_history[bus_index][0].current_peak);
826 bus_levels[bus_index].peak_level_dbfs[1] = to_db(peak_history[bus_index][1].current_peak);
827 bus_levels[bus_index].historic_peak_dbfs = to_db(
828 max(peak_history[bus_index][0].historic_peak,
829 peak_history[bus_index][1].historic_peak));
830 bus_levels[bus_index].gain_staging_db = gain_staging_db[bus_index];
831 if (compressor_enabled[bus_index]) {
832 bus_levels[bus_index].compressor_attenuation_db = -to_db(compressor[bus_index]->get_attenuation());
834 bus_levels[bus_index].compressor_attenuation_db = 0.0;
839 audio_level_callback(loudness_s, to_db(peak), bus_levels,
840 loudness_i, loudness_range_low, loudness_range_high,
841 to_db(final_makeup_gain),
842 correlation.get_correlation());
845 map<DeviceSpec, DeviceInfo> AudioMixer::get_devices()
847 lock_guard<timed_mutex> lock(audio_mutex);
849 map<DeviceSpec, DeviceInfo> devices;
850 for (unsigned card_index = 0; card_index < num_cards; ++card_index) {
851 const DeviceSpec spec{ InputSourceType::CAPTURE_CARD, card_index };
852 const AudioDevice *device = &video_cards[card_index];
854 info.display_name = device->display_name;
855 info.num_channels = 8;
856 devices.insert(make_pair(spec, info));
858 vector<ALSAPool::Device> available_alsa_devices = alsa_pool.get_devices();
859 for (unsigned card_index = 0; card_index < available_alsa_devices.size(); ++card_index) {
860 const DeviceSpec spec{ InputSourceType::ALSA_INPUT, card_index };
861 const ALSAPool::Device &device = available_alsa_devices[card_index];
863 info.display_name = device.display_name();
864 info.num_channels = device.num_channels;
865 info.alsa_name = device.name;
866 info.alsa_info = device.info;
867 info.alsa_address = device.address;
868 devices.insert(make_pair(spec, info));
873 void AudioMixer::set_display_name(DeviceSpec device_spec, const string &name)
875 AudioDevice *device = find_audio_device(device_spec);
877 lock_guard<timed_mutex> lock(audio_mutex);
878 device->display_name = name;
881 void AudioMixer::serialize_device(DeviceSpec device_spec, DeviceSpecProto *device_spec_proto)
883 lock_guard<timed_mutex> lock(audio_mutex);
884 switch (device_spec.type) {
885 case InputSourceType::SILENCE:
886 device_spec_proto->set_type(DeviceSpecProto::SILENCE);
888 case InputSourceType::CAPTURE_CARD:
889 device_spec_proto->set_type(DeviceSpecProto::CAPTURE_CARD);
890 device_spec_proto->set_index(device_spec.index);
891 device_spec_proto->set_display_name(video_cards[device_spec.index].display_name);
893 case InputSourceType::ALSA_INPUT:
894 alsa_pool.serialize_device(device_spec.index, device_spec_proto);
899 void AudioMixer::set_simple_input(unsigned card_index)
901 InputMapping new_input_mapping;
902 InputMapping::Bus input;
904 input.device.type = InputSourceType::CAPTURE_CARD;
905 input.device.index = card_index;
906 input.source_channel[0] = 0;
907 input.source_channel[1] = 1;
909 new_input_mapping.buses.push_back(input);
911 lock_guard<timed_mutex> lock(audio_mutex);
912 current_mapping_mode = MappingMode::SIMPLE;
913 set_input_mapping_lock_held(new_input_mapping);
914 fader_volume_db[0] = 0.0f;
917 unsigned AudioMixer::get_simple_input() const
919 lock_guard<timed_mutex> lock(audio_mutex);
920 if (input_mapping.buses.size() == 1 &&
921 input_mapping.buses[0].device.type == InputSourceType::CAPTURE_CARD &&
922 input_mapping.buses[0].source_channel[0] == 0 &&
923 input_mapping.buses[0].source_channel[1] == 1) {
924 return input_mapping.buses[0].device.index;
926 return numeric_limits<unsigned>::max();
930 void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
932 lock_guard<timed_mutex> lock(audio_mutex);
933 set_input_mapping_lock_held(new_input_mapping);
934 current_mapping_mode = MappingMode::MULTICHANNEL;
937 AudioMixer::MappingMode AudioMixer::get_mapping_mode() const
939 lock_guard<timed_mutex> lock(audio_mutex);
940 return current_mapping_mode;
943 void AudioMixer::set_input_mapping_lock_held(const InputMapping &new_input_mapping)
945 map<DeviceSpec, set<unsigned>> interesting_channels;
946 for (const InputMapping::Bus &bus : new_input_mapping.buses) {
947 if (bus.device.type == InputSourceType::CAPTURE_CARD ||
948 bus.device.type == InputSourceType::ALSA_INPUT) {
949 for (unsigned channel = 0; channel < 2; ++channel) {
950 if (bus.source_channel[channel] != -1) {
951 interesting_channels[bus.device].insert(bus.source_channel[channel]);
957 // Reset resamplers for all cards that don't have the exact same state as before.
958 for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) {
959 const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index};
960 AudioDevice *device = find_audio_device(device_spec);
961 if (device->interesting_channels != interesting_channels[device_spec]) {
962 device->interesting_channels = interesting_channels[device_spec];
963 reset_resampler_mutex_held(device_spec);
966 for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) {
967 const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index};
968 AudioDevice *device = find_audio_device(device_spec);
969 if (interesting_channels[device_spec].empty()) {
970 alsa_pool.release_device(card_index);
972 alsa_pool.hold_device(card_index);
974 if (device->interesting_channels != interesting_channels[device_spec]) {
975 device->interesting_channels = interesting_channels[device_spec];
976 alsa_pool.reset_device(device_spec.index);
977 reset_resampler_mutex_held(device_spec);
981 input_mapping = new_input_mapping;
984 InputMapping AudioMixer::get_input_mapping() const
986 lock_guard<timed_mutex> lock(audio_mutex);
987 return input_mapping;
990 void AudioMixer::reset_peak(unsigned bus_index)
992 lock_guard<timed_mutex> lock(audio_mutex);
993 for (unsigned channel = 0; channel < 2; ++channel) {
994 PeakHistory &history = peak_history[bus_index][channel];
995 history.current_level = 0.0f;
996 history.historic_peak = 0.0f;
997 history.current_peak = 0.0f;
998 history.last_peak = 0.0f;
999 history.age_seconds = 0.0f;
1003 AudioMixer *global_audio_mixer = nullptr;