X-Git-Url: https://git.sesse.net/?a=blobdiff_plain;f=audio_mixer.cpp;h=468edd531859b75793750564bc6a29f433a1675b;hb=b9feb66845bf24465b7671ac9ff7a52b88f6032b;hp=6b7ffeb0d6d28fb1ffdbfa8308ab341970893b20;hpb=54067dbc70999d936adf9d263b5ff2b1efb4dfd0;p=nageru diff --git a/audio_mixer.cpp b/audio_mixer.cpp index 6b7ffeb..468edd5 100644 --- a/audio_mixer.cpp +++ b/audio_mixer.cpp @@ -1,21 +1,32 @@ #include "audio_mixer.h" #include -#include #include -#include #include -#include -#ifdef __SSE__ +#include +#ifdef __SSE2__ #include #endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "db.h" #include "flags.h" +#include "metrics.h" +#include "state.pb.h" #include "timebase.h" using namespace bmusb; using namespace std; +using namespace std::chrono; using namespace std::placeholders; namespace { @@ -163,50 +174,54 @@ AudioMixer::AudioMixer(unsigned num_cards) { for (unsigned bus_index = 0; bus_index < MAX_BUSES; ++bus_index) { locut[bus_index].init(FILTER_HPF, 2); - locut_enabled[bus_index] = global_flags.locut_enabled; - gain_staging_db[bus_index] = global_flags.initial_gain_staging_db; + eq[bus_index][EQ_BAND_BASS].init(FILTER_LOW_SHELF, 1); + // Note: EQ_BAND_MID isn't used (see comments in apply_eq()). + eq[bus_index][EQ_BAND_TREBLE].init(FILTER_HIGH_SHELF, 1); compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY)); - compressor_threshold_dbfs[bus_index] = ref_level_dbfs - 12.0f; // -12 dB. - compressor_enabled[bus_index] = global_flags.compressor_enabled; level_compressor[bus_index].reset(new StereoCompressor(OUTPUT_FREQUENCY)); - level_compressor_enabled[bus_index] = global_flags.gain_staging_auto; + + set_bus_settings(bus_index, get_default_bus_settings()); } set_limiter_enabled(global_flags.limiter_enabled); set_final_makeup_gain_auto(global_flags.final_makeup_gain_auto); - // Generate a very simple, default input mapping. - InputMapping::Bus input; - input.name = "Main"; - input.device.type = InputSourceType::CAPTURE_CARD; - input.device.index = 0; - input.source_channel[0] = 0; - input.source_channel[1] = 1; - - InputMapping new_input_mapping; - new_input_mapping.buses.push_back(input); - set_input_mapping(new_input_mapping); - - // Look for ALSA cards. - available_alsa_cards = ALSAInput::enumerate_devices(); - r128.init(2, OUTPUT_FREQUENCY); r128.integr_start(); // hlen=16 is pretty low quality, but we use quite a bit of CPU otherwise, // and there's a limit to how important the peak meter is. peak_resampler.setup(OUTPUT_FREQUENCY, OUTPUT_FREQUENCY * 4, /*num_channels=*/2, /*hlen=*/16, /*frel=*/1.0); -} -AudioMixer::~AudioMixer() -{ - for (unsigned card_index = 0; card_index < available_alsa_cards.size(); ++card_index) { - const AudioDevice &device = alsa_inputs[card_index]; - if (device.alsa_device != nullptr) { - device.alsa_device->stop_capture_thread(); + global_audio_mixer = this; + alsa_pool.init(); + + if (!global_flags.input_mapping_filename.empty()) { + // Must happen after ALSAPool is initialized, as it needs to know the card list. + current_mapping_mode = MappingMode::MULTICHANNEL; + InputMapping new_input_mapping; + if (!load_input_mapping_from_file(get_devices(), + global_flags.input_mapping_filename, + &new_input_mapping)) { + fprintf(stderr, "Failed to load input mapping from '%s', exiting.\n", + global_flags.input_mapping_filename.c_str()); + exit(1); + } + set_input_mapping(new_input_mapping); + } else { + set_simple_input(/*card_index=*/0); + if (global_flags.multichannel_mapping_mode) { + current_mapping_mode = MappingMode::MULTICHANNEL; } } -} + global_metrics.add("audio_loudness_short_lufs", &metric_audio_loudness_short_lufs, Metrics::TYPE_GAUGE); + global_metrics.add("audio_loudness_integrated_lufs", &metric_audio_loudness_integrated_lufs, Metrics::TYPE_GAUGE); + global_metrics.add("audio_loudness_range_low_lufs", &metric_audio_loudness_range_low_lufs, Metrics::TYPE_GAUGE); + global_metrics.add("audio_loudness_range_high_lufs", &metric_audio_loudness_range_high_lufs, Metrics::TYPE_GAUGE); + global_metrics.add("audio_peak_dbfs", &metric_audio_peak_dbfs, Metrics::TYPE_GAUGE); + global_metrics.add("audio_final_makeup_gain_db", &metric_audio_final_makeup_gain_db, Metrics::TYPE_GAUGE); + global_metrics.add("audio_correlation", &metric_audio_correlation, Metrics::TYPE_GAUGE); +} void AudioMixer::reset_resampler(DeviceSpec device_spec) { @@ -223,31 +238,13 @@ void AudioMixer::reset_resampler_mutex_held(DeviceSpec device_spec) } else { // TODO: ResamplingQueue should probably take the full device spec. // (It's only used for console output, though.) - device->resampling_queue.reset(new ResamplingQueue(device_spec.index, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size())); - } - device->next_local_pts = 0; -} - -void AudioMixer::reset_alsa_mutex_held(DeviceSpec device_spec) -{ - assert(device_spec.type == InputSourceType::ALSA_INPUT); - unsigned card_index = device_spec.index; - AudioDevice *device = find_audio_device(device_spec); - - if (device->alsa_device != nullptr) { - device->alsa_device->stop_capture_thread(); - } - if (device->interesting_channels.empty()) { - device->alsa_device.reset(); - } else { - const ALSAInput::Device &alsa_dev = available_alsa_cards[card_index]; - device->alsa_device.reset(new ALSAInput(alsa_dev.address.c_str(), OUTPUT_FREQUENCY, alsa_dev.num_channels, bind(&AudioMixer::add_audio, this, device_spec, _1, _2, _3, _4))); - device->capture_frequency = device->alsa_device->get_sample_rate(); - device->alsa_device->start_capture_thread(); + device->resampling_queue.reset(new ResamplingQueue( + device_spec.index, device->capture_frequency, OUTPUT_FREQUENCY, device->interesting_channels.size(), + global_flags.audio_queue_length_ms * 0.001)); } } -bool AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned num_samples, AudioFormat audio_format, int64_t frame_length) +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) { AudioDevice *device = find_audio_device(device_spec); @@ -286,10 +283,14 @@ bool AudioMixer::add_audio(DeviceSpec device_spec, const uint8_t *data, unsigned } } + // If we changed frequency since last frame, we'll need to reset the resampler. + if (audio_format.sample_rate != device->capture_frequency) { + device->capture_frequency = audio_format.sample_rate; + reset_resampler_mutex_held(device_spec); + } + // Now add it. - int64_t local_pts = device->next_local_pts; - device->resampling_queue->add_input_samples(local_pts / double(TIMEBASE), audio.get(), num_samples); - device->next_local_pts = local_pts + frame_length; + device->resampling_queue->add_input_samples(frame_time, audio.get(), num_samples, ResamplingQueue::ADJUST_RATE); return true; } @@ -311,15 +312,76 @@ bool AudioMixer::add_silence(DeviceSpec device_spec, unsigned samples_per_frame, vector silence(samples_per_frame * num_channels, 0.0f); for (unsigned i = 0; i < num_frames; ++i) { - device->resampling_queue->add_input_samples(device->next_local_pts / double(TIMEBASE), silence.data(), samples_per_frame); - // Note that if the format changed in the meantime, we have - // no way of detecting that; we just have to assume the frame length - // is always the same. - device->next_local_pts += frame_length; + device->resampling_queue->add_input_samples(steady_clock::now(), silence.data(), samples_per_frame, ResamplingQueue::DO_NOT_ADJUST_RATE); + } + return true; +} + +bool AudioMixer::silence_card(DeviceSpec device_spec, bool silence) +{ + AudioDevice *device = find_audio_device(device_spec); + + unique_lock lock(audio_mutex, defer_lock); + if (!lock.try_lock_for(chrono::milliseconds(10))) { + return false; + } + + if (device->silenced && !silence) { + reset_resampler_mutex_held(device_spec); } + device->silenced = silence; return true; } +AudioMixer::BusSettings AudioMixer::get_default_bus_settings() +{ + BusSettings settings; + settings.fader_volume_db = 0.0f; + settings.muted = false; + settings.locut_enabled = global_flags.locut_enabled; + for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) { + settings.eq_level_db[band_index] = 0.0f; + } + settings.gain_staging_db = global_flags.initial_gain_staging_db; + settings.level_compressor_enabled = global_flags.gain_staging_auto; + settings.compressor_threshold_dbfs = ref_level_dbfs - 12.0f; // -12 dB. + settings.compressor_enabled = global_flags.compressor_enabled; + return settings; +} + +AudioMixer::BusSettings AudioMixer::get_bus_settings(unsigned bus_index) const +{ + lock_guard lock(audio_mutex); + BusSettings settings; + settings.fader_volume_db = fader_volume_db[bus_index]; + settings.muted = mute[bus_index]; + settings.locut_enabled = locut_enabled[bus_index]; + for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) { + settings.eq_level_db[band_index] = eq_level_db[bus_index][band_index]; + } + settings.gain_staging_db = gain_staging_db[bus_index]; + settings.level_compressor_enabled = level_compressor_enabled[bus_index]; + settings.compressor_threshold_dbfs = compressor_threshold_dbfs[bus_index]; + settings.compressor_enabled = compressor_enabled[bus_index]; + return settings; +} + +void AudioMixer::set_bus_settings(unsigned bus_index, const AudioMixer::BusSettings &settings) +{ + lock_guard lock(audio_mutex); + fader_volume_db[bus_index] = settings.fader_volume_db; + mute[bus_index] = settings.muted; + locut_enabled[bus_index] = settings.locut_enabled; + for (unsigned band_index = 0; band_index < NUM_EQ_BANDS; ++band_index) { + eq_level_db[bus_index][band_index] = settings.eq_level_db[band_index]; + } + gain_staging_db[bus_index] = settings.gain_staging_db; + last_gain_staging_db[bus_index] = gain_staging_db[bus_index]; + level_compressor_enabled[bus_index] = settings.level_compressor_enabled; + compressor_threshold_dbfs[bus_index] = settings.compressor_threshold_dbfs; + compressor_enabled[bus_index] = settings.compressor_enabled; +} + AudioMixer::AudioDevice *AudioMixer::find_audio_device(DeviceSpec device) { switch (device.type) { @@ -362,7 +424,7 @@ void AudioMixer::find_sample_src_from_device(const map void AudioMixer::fill_audio_bus(const map> &samples_card, const InputMapping::Bus &bus, unsigned num_samples, float *output) { if (bus.device.type == InputSourceType::SILENCE) { - memset(output, 0, num_samples * sizeof(*output)); + memset(output, 0, num_samples * 2 * sizeof(*output)); } else { assert(bus.device.type == InputSourceType::CAPTURE_CARD || bus.device.type == InputSourceType::ALSA_INPUT); @@ -380,7 +442,50 @@ void AudioMixer::fill_audio_bus(const map> &samples_ca } } -vector AudioMixer::get_output(double pts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy) +vector AudioMixer::get_active_devices() const +{ + vector ret; + for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) { + const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index}; + if (!find_audio_device(device_spec)->interesting_channels.empty()) { + ret.push_back(device_spec); + } + } + for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) { + const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index}; + if (!find_audio_device(device_spec)->interesting_channels.empty()) { + ret.push_back(device_spec); + } + } + return ret; +} + +namespace { + +void apply_gain(float db, float last_db, vector *samples) +{ + if (fabs(db - last_db) < 1e-3) { + // Constant over this frame. + const float gain = from_db(db); + for (size_t i = 0; i < samples->size(); ++i) { + (*samples)[i] *= gain; + } + } else { + // We need to do a fade. + unsigned num_samples = samples->size() / 2; + float gain = from_db(last_db); + const float gain_inc = pow(from_db(db - last_db), 1.0 / num_samples); + for (size_t i = 0; i < num_samples; ++i) { + (*samples)[i * 2 + 0] *= gain; + (*samples)[i * 2 + 1] *= gain; + gain *= gain_inc; + } + } +} + +} // namespace + +vector AudioMixer::get_output(steady_clock::time_point ts, unsigned num_samples, ResamplingQueue::RateAdjustmentPolicy rate_adjustment_policy) { map> samples_card; vector samples_bus; @@ -388,16 +493,14 @@ vector AudioMixer::get_output(double pts, unsigned num_samples, Resamplin lock_guard lock(audio_mutex); // Pick out all the interesting channels from all the cards. - // TODO: If the card has been hotswapped, the number of channels - // might have changed; if so, we need to do some sort of remapping - // to silence. - for (const auto &spec_and_info : get_devices_mutex_held()) { - const DeviceSpec &device_spec = spec_and_info.first; + for (const DeviceSpec &device_spec : get_active_devices()) { AudioDevice *device = find_audio_device(device_spec); - if (!device->interesting_channels.empty()) { - samples_card[device_spec].resize(num_samples * device->interesting_channels.size()); + samples_card[device_spec].resize(num_samples * device->interesting_channels.size()); + if (device->silenced) { + memset(&samples_card[device_spec][0], 0, samples_card[device_spec].size() * sizeof(float)); + } else { device->resampling_queue->get_output_samples( - pts, + ts, &samples_card[device_spec][0], num_samples, rate_adjustment_policy); @@ -409,14 +512,7 @@ vector AudioMixer::get_output(double pts, unsigned num_samples, Resamplin samples_bus.resize(num_samples * 2); for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) { fill_audio_bus(samples_card, input_mapping.buses[bus_index], num_samples, &samples_bus[0]); - - // Cut away everything under 120 Hz (or whatever the cutoff is); - // we don't need it for voice, and it will reduce headroom - // and confuse the compressor. (In particular, any hums at 50 or 60 Hz - // should be dampened.) - if (locut_enabled[bus_index]) { - locut[bus_index].render(samples_bus.data(), samples_bus.size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f); - } + apply_eq(bus_index, &samples_bus); { lock_guard lock(compressor_mutex); @@ -437,11 +533,11 @@ vector AudioMixer::get_output(double pts, unsigned num_samples, Resamplin gain_staging_db[bus_index] = to_db(level_compressor[bus_index]->get_attenuation() * makeup_gain); } else { // Just apply the gain we already had. - float g = from_db(gain_staging_db[bus_index]); - for (size_t i = 0; i < samples_bus.size(); ++i) { - samples_bus[i] *= g; - } + float db = gain_staging_db[bus_index]; + float last_db = last_gain_staging_db[bus_index]; + apply_gain(db, last_db, &samples_bus); } + last_gain_staging_db[bus_index] = gain_staging_db[bus_index]; #if 0 printf("level=%f (%+5.2f dBFS) attenuation=%f (%+5.2f dB) end_result=%+5.2f dB\n", @@ -462,19 +558,9 @@ vector AudioMixer::get_output(double pts, unsigned num_samples, Resamplin } } - float volume = from_db(fader_volume_db[bus_index]); - if (bus_index == 0) { - for (unsigned i = 0; i < num_samples * 2; ++i) { - samples_out[i] = samples_bus[i] * volume; - } - } else { - for (unsigned i = 0; i < num_samples * 2; ++i) { - samples_out[i] += samples_bus[i] * volume; - } - } - + add_bus_to_master(bus_index, samples_bus, &samples_out); deinterleave_samples(samples_bus, &left, &right); - measure_bus_levels(bus_index, left, right, volume); + measure_bus_levels(bus_index, left, right); } { @@ -509,13 +595,12 @@ vector AudioMixer::get_output(double pts, unsigned num_samples, Resamplin // (half-time of 30 seconds). double target_loudness_factor, alpha; double loudness_lu = r128.loudness_M() - ref_level_lufs; - double current_makeup_lu = to_db(final_makeup_gain); target_loudness_factor = final_makeup_gain * from_db(-loudness_lu); - // If we're outside +/- 5 LU uncorrected, we don't count it as + // If we're outside +/- 5 LU (after correction), we don't count it as // a normal signal (probably silence) and don't change the // correction factor; just apply what we already have. - if (fabs(loudness_lu - current_makeup_lu) >= 5.0 || !final_makeup_gain_auto) { + if (fabs(loudness_lu) >= 5.0 || !final_makeup_gain_auto) { alpha = 0.0; } else { // Formula adapted from @@ -541,9 +626,129 @@ vector AudioMixer::get_output(double pts, unsigned num_samples, Resamplin return samples_out; } -void AudioMixer::measure_bus_levels(unsigned bus_index, const vector &left, const vector &right, float volume) +namespace { + +void apply_filter_fade(StereoFilter *filter, float *data, unsigned num_samples, float cutoff_hz, float db, float last_db) +{ + // A granularity of 32 samples is an okay tradeoff between speed and + // smoothness; recalculating the filters is pretty expensive, so it's + // good that we don't do this all the time. + static constexpr unsigned filter_granularity_samples = 32; + + const float cutoff_linear = cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY; + if (fabs(db - last_db) < 1e-3) { + // Constant over this frame. + if (fabs(db) > 0.01f) { + filter->render(data, num_samples, cutoff_linear, 0.5f, db / 40.0f); + } + } else { + // We need to do a fade. (Rounding up avoids division by zero.) + unsigned num_blocks = (num_samples + filter_granularity_samples - 1) / filter_granularity_samples; + const float inc_db_norm = (db - last_db) / 40.0f / num_blocks; + float db_norm = db / 40.0f; + for (size_t i = 0; i < num_samples; i += filter_granularity_samples) { + size_t samples_this_block = std::min(num_samples - i, filter_granularity_samples); + filter->render(data + i * 2, samples_this_block, cutoff_linear, 0.5f, db_norm); + db_norm += inc_db_norm; + } + } +} + +} // namespace + +void AudioMixer::apply_eq(unsigned bus_index, vector *samples_bus) +{ + constexpr float bass_freq_hz = 200.0f; + constexpr float treble_freq_hz = 4700.0f; + + // Cut away everything under 120 Hz (or whatever the cutoff is); + // we don't need it for voice, and it will reduce headroom + // and confuse the compressor. (In particular, any hums at 50 or 60 Hz + // should be dampened.) + if (locut_enabled[bus_index]) { + locut[bus_index].render(samples_bus->data(), samples_bus->size() / 2, locut_cutoff_hz * 2.0 * M_PI / OUTPUT_FREQUENCY, 0.5f); + } + + // Apply the rest of the EQ. Since we only have a simple three-band EQ, + // we can implement it with two shelf filters. We use a simple gain to + // set the mid-level filter, and then offset the low and high bands + // from that if we need to. (We could perhaps have folded the gain into + // the next part, but it's so cheap that the trouble isn't worth it.) + // + // If any part of the EQ has changed appreciably since last frame, + // we fade smoothly during the course of this frame. + const float bass_db = eq_level_db[bus_index][EQ_BAND_BASS]; + const float mid_db = eq_level_db[bus_index][EQ_BAND_MID]; + const float treble_db = eq_level_db[bus_index][EQ_BAND_TREBLE]; + + const float last_bass_db = last_eq_level_db[bus_index][EQ_BAND_BASS]; + const float last_mid_db = last_eq_level_db[bus_index][EQ_BAND_MID]; + const float last_treble_db = last_eq_level_db[bus_index][EQ_BAND_TREBLE]; + + assert(samples_bus->size() % 2 == 0); + const unsigned num_samples = samples_bus->size() / 2; + + apply_gain(mid_db, last_mid_db, samples_bus); + + 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); + 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); + + last_eq_level_db[bus_index][EQ_BAND_BASS] = bass_db; + last_eq_level_db[bus_index][EQ_BAND_MID] = mid_db; + last_eq_level_db[bus_index][EQ_BAND_TREBLE] = treble_db; +} + +void AudioMixer::add_bus_to_master(unsigned bus_index, const vector &samples_bus, vector *samples_out) +{ + assert(samples_bus.size() == samples_out->size()); + assert(samples_bus.size() % 2 == 0); + unsigned num_samples = samples_bus.size() / 2; + const float new_volume_db = mute[bus_index] ? -90.0f : fader_volume_db[bus_index].load(); + if (fabs(new_volume_db - last_fader_volume_db[bus_index]) > 1e-3) { + // The volume has changed; do a fade over the course of this frame. + // (We might have some numerical issues here, but it seems to sound OK.) + // For the purpose of fading here, the silence floor is set to -90 dB + // (the fader only goes to -84). + float old_volume = from_db(max(last_fader_volume_db[bus_index], -90.0f)); + float volume = from_db(max(new_volume_db, -90.0f)); + + float volume_inc = pow(volume / old_volume, 1.0 / num_samples); + volume = old_volume; + if (bus_index == 0) { + for (unsigned i = 0; i < num_samples; ++i) { + (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume; + (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume; + volume *= volume_inc; + } + } else { + for (unsigned i = 0; i < num_samples; ++i) { + (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume; + (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume; + volume *= volume_inc; + } + } + } else if (new_volume_db > -90.0f) { + float volume = from_db(new_volume_db); + if (bus_index == 0) { + for (unsigned i = 0; i < num_samples; ++i) { + (*samples_out)[i * 2 + 0] = samples_bus[i * 2 + 0] * volume; + (*samples_out)[i * 2 + 1] = samples_bus[i * 2 + 1] * volume; + } + } else { + for (unsigned i = 0; i < num_samples; ++i) { + (*samples_out)[i * 2 + 0] += samples_bus[i * 2 + 0] * volume; + (*samples_out)[i * 2 + 1] += samples_bus[i * 2 + 1] * volume; + } + } + } + + last_fader_volume_db[bus_index] = new_volume_db; +} + +void AudioMixer::measure_bus_levels(unsigned bus_index, const vector &left, const vector &right) { assert(left.size() == right.size()); + const float volume = mute[bus_index] ? 0.0f : from_db(fader_volume_db[bus_index]); const float peak_levels[2] = { find_peak(left.data(), left.size()) * volume, find_peak(right.data(), right.size()) * volume @@ -555,6 +760,7 @@ void AudioMixer::measure_bus_levels(unsigned bus_index, const vector &lef static constexpr float falloff_db_sec = 15.0f; // dB/sec falloff after hold. float current_peak; PeakHistory &history = peak_history[bus_index][channel]; + history.historic_peak = max(history.historic_peak, peak_levels[channel]); if (history.age_seconds < hold_sec) { current_peak = history.last_peak; } else { @@ -630,20 +836,35 @@ void AudioMixer::send_audio_level_callback() double loudness_range_low = r128.range_min(); double loudness_range_high = r128.range_max(); + metric_audio_loudness_short_lufs = loudness_s; + metric_audio_loudness_integrated_lufs = loudness_i; + metric_audio_loudness_range_low_lufs = loudness_range_low; + metric_audio_loudness_range_high_lufs = loudness_range_high; + metric_audio_peak_dbfs = to_db(peak); + metric_audio_final_makeup_gain_db = to_db(final_makeup_gain); + metric_audio_correlation = correlation.get_correlation(); + vector bus_levels; bus_levels.resize(input_mapping.buses.size()); { lock_guard lock(compressor_mutex); for (unsigned bus_index = 0; bus_index < bus_levels.size(); ++bus_index) { - bus_levels[bus_index].current_level_dbfs[0] = to_db(peak_history[bus_index][0].current_level); - bus_levels[bus_index].current_level_dbfs[1] = to_db(peak_history[bus_index][1].current_level); - bus_levels[bus_index].peak_level_dbfs[0] = to_db(peak_history[bus_index][0].current_peak); - bus_levels[bus_index].peak_level_dbfs[1] = to_db(peak_history[bus_index][1].current_peak); - bus_levels[bus_index].gain_staging_db = gain_staging_db[bus_index]; + BusLevel &levels = bus_levels[bus_index]; + BusMetrics &metrics = bus_metrics[bus_index]; + + levels.current_level_dbfs[0] = metrics.current_level_dbfs[0] = to_db(peak_history[bus_index][0].current_level); + levels.current_level_dbfs[1] = metrics.current_level_dbfs[1] = to_db(peak_history[bus_index][1].current_level); + levels.peak_level_dbfs[0] = metrics.peak_level_dbfs[0] = to_db(peak_history[bus_index][0].current_peak); + levels.peak_level_dbfs[1] = metrics.peak_level_dbfs[1] = to_db(peak_history[bus_index][1].current_peak); + levels.historic_peak_dbfs = metrics.historic_peak_dbfs = to_db( + max(peak_history[bus_index][0].historic_peak, + peak_history[bus_index][1].historic_peak)); + levels.gain_staging_db = metrics.gain_staging_db = gain_staging_db[bus_index]; if (compressor_enabled[bus_index]) { - bus_levels[bus_index].compressor_attenuation_db = -to_db(compressor[bus_index]->get_attenuation()); + levels.compressor_attenuation_db = metrics.compressor_attenuation_db = -to_db(compressor[bus_index]->get_attenuation()); } else { - bus_levels[bus_index].compressor_attenuation_db = 0.0; + levels.compressor_attenuation_db = 0.0; + metrics.compressor_attenuation_db = 0.0 / 0.0; } } } @@ -654,46 +875,106 @@ void AudioMixer::send_audio_level_callback() correlation.get_correlation()); } -map AudioMixer::get_devices() const +map AudioMixer::get_devices() { lock_guard lock(audio_mutex); - return get_devices_mutex_held(); -} -map AudioMixer::get_devices_mutex_held() const -{ map devices; for (unsigned card_index = 0; card_index < num_cards; ++card_index) { const DeviceSpec spec{ InputSourceType::CAPTURE_CARD, card_index }; const AudioDevice *device = &video_cards[card_index]; DeviceInfo info; - info.name = device->name; - info.num_channels = 8; // FIXME: This is wrong for fake cards. + info.display_name = device->display_name; + info.num_channels = 8; devices.insert(make_pair(spec, info)); } - for (unsigned card_index = 0; card_index < available_alsa_cards.size(); ++card_index) { + vector available_alsa_devices = alsa_pool.get_devices(); + for (unsigned card_index = 0; card_index < available_alsa_devices.size(); ++card_index) { const DeviceSpec spec{ InputSourceType::ALSA_INPUT, card_index }; - const ALSAInput::Device &device = available_alsa_cards[card_index]; + const ALSAPool::Device &device = available_alsa_devices[card_index]; DeviceInfo info; - info.name = device.name + " (" + device.info + ")"; + info.display_name = device.display_name(); info.num_channels = device.num_channels; + info.alsa_name = device.name; + info.alsa_info = device.info; + info.alsa_address = device.address; devices.insert(make_pair(spec, info)); } return devices; } -void AudioMixer::set_name(DeviceSpec device_spec, const string &name) +void AudioMixer::set_display_name(DeviceSpec device_spec, const string &name) { AudioDevice *device = find_audio_device(device_spec); lock_guard lock(audio_mutex); - device->name = name; + device->display_name = name; +} + +void AudioMixer::serialize_device(DeviceSpec device_spec, DeviceSpecProto *device_spec_proto) +{ + lock_guard lock(audio_mutex); + switch (device_spec.type) { + case InputSourceType::SILENCE: + device_spec_proto->set_type(DeviceSpecProto::SILENCE); + break; + case InputSourceType::CAPTURE_CARD: + device_spec_proto->set_type(DeviceSpecProto::CAPTURE_CARD); + device_spec_proto->set_index(device_spec.index); + device_spec_proto->set_display_name(video_cards[device_spec.index].display_name); + break; + case InputSourceType::ALSA_INPUT: + alsa_pool.serialize_device(device_spec.index, device_spec_proto); + break; + } +} + +void AudioMixer::set_simple_input(unsigned card_index) +{ + InputMapping new_input_mapping; + InputMapping::Bus input; + input.name = "Main"; + input.device.type = InputSourceType::CAPTURE_CARD; + input.device.index = card_index; + input.source_channel[0] = 0; + input.source_channel[1] = 1; + + new_input_mapping.buses.push_back(input); + + lock_guard lock(audio_mutex); + current_mapping_mode = MappingMode::SIMPLE; + set_input_mapping_lock_held(new_input_mapping); + fader_volume_db[0] = 0.0f; +} + +unsigned AudioMixer::get_simple_input() const +{ + lock_guard lock(audio_mutex); + if (input_mapping.buses.size() == 1 && + input_mapping.buses[0].device.type == InputSourceType::CAPTURE_CARD && + input_mapping.buses[0].source_channel[0] == 0 && + input_mapping.buses[0].source_channel[1] == 1) { + return input_mapping.buses[0].device.index; + } else { + return numeric_limits::max(); + } } void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping) { lock_guard lock(audio_mutex); + set_input_mapping_lock_held(new_input_mapping); + current_mapping_mode = MappingMode::MULTICHANNEL; +} + +AudioMixer::MappingMode AudioMixer::get_mapping_mode() const +{ + lock_guard lock(audio_mutex); + return current_mapping_mode; +} +void AudioMixer::set_input_mapping_lock_held(const InputMapping &new_input_mapping) +{ map> interesting_channels; for (const InputMapping::Bus &bus : new_input_mapping.buses) { if (bus.device.type == InputSourceType::CAPTURE_CARD || @@ -706,15 +987,82 @@ void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping) } } + // Kill all the old metrics, and set up new ones. + for (unsigned bus_index = 0; bus_index < input_mapping.buses.size(); ++bus_index) { + BusMetrics &metrics = bus_metrics[bus_index]; + + vector> labels_left = metrics.labels; + labels_left.emplace_back("channel", "left"); + vector> labels_right = metrics.labels; + labels_right.emplace_back("channel", "right"); + + global_metrics.remove("bus_current_level_dbfs", labels_left); + global_metrics.remove("bus_current_level_dbfs", labels_right); + global_metrics.remove("bus_peak_level_dbfs", labels_left); + global_metrics.remove("bus_peak_level_dbfs", labels_right); + global_metrics.remove("bus_historic_peak_dbfs", metrics.labels); + global_metrics.remove("bus_gain_staging_db", metrics.labels); + global_metrics.remove("bus_compressor_attenuation_db", metrics.labels); + } + bus_metrics.reset(new BusMetrics[new_input_mapping.buses.size()]); + for (unsigned bus_index = 0; bus_index < new_input_mapping.buses.size(); ++bus_index) { + const InputMapping::Bus &bus = new_input_mapping.buses[bus_index]; + BusMetrics &metrics = bus_metrics[bus_index]; + + char bus_index_str[16], source_index_str[16], source_channels_str[64]; + snprintf(bus_index_str, sizeof(bus_index_str), "%u", bus_index); + snprintf(source_index_str, sizeof(source_index_str), "%u", bus.device.index); + snprintf(source_channels_str, sizeof(source_channels_str), "%d:%d", bus.source_channel[0], bus.source_channel[1]); + + vector> labels; + metrics.labels.emplace_back("index", bus_index_str); + metrics.labels.emplace_back("name", bus.name); + if (bus.device.type == InputSourceType::SILENCE) { + metrics.labels.emplace_back("source_type", "silence"); + } else if (bus.device.type == InputSourceType::CAPTURE_CARD) { + metrics.labels.emplace_back("source_type", "capture_card"); + } else if (bus.device.type == InputSourceType::ALSA_INPUT) { + metrics.labels.emplace_back("source_type", "alsa_input"); + } else { + assert(false); + } + metrics.labels.emplace_back("source_index", source_index_str); + metrics.labels.emplace_back("source_channels", source_channels_str); + + vector> labels_left = metrics.labels; + labels_left.emplace_back("channel", "left"); + vector> labels_right = metrics.labels; + labels_right.emplace_back("channel", "right"); + + global_metrics.add("bus_current_level_dbfs", labels_left, &metrics.current_level_dbfs[0], Metrics::TYPE_GAUGE); + global_metrics.add("bus_current_level_dbfs", labels_right, &metrics.current_level_dbfs[1], Metrics::TYPE_GAUGE); + global_metrics.add("bus_peak_level_dbfs", labels_left, &metrics.peak_level_dbfs[0], Metrics::TYPE_GAUGE); + global_metrics.add("bus_peak_level_dbfs", labels_right, &metrics.peak_level_dbfs[1], Metrics::TYPE_GAUGE); + global_metrics.add("bus_historic_peak_dbfs", metrics.labels, &metrics.historic_peak_dbfs, Metrics::TYPE_GAUGE); + global_metrics.add("bus_gain_staging_db", metrics.labels, &metrics.gain_staging_db, Metrics::TYPE_GAUGE); + global_metrics.add("bus_compressor_attenuation_db", metrics.labels, &metrics.compressor_attenuation_db, Metrics::TYPE_GAUGE); + } + // Reset resamplers for all cards that don't have the exact same state as before. - for (const auto &spec_and_info : get_devices_mutex_held()) { - const DeviceSpec &device_spec = spec_and_info.first; + for (unsigned card_index = 0; card_index < MAX_VIDEO_CARDS; ++card_index) { + const DeviceSpec device_spec{InputSourceType::CAPTURE_CARD, card_index}; AudioDevice *device = find_audio_device(device_spec); if (device->interesting_channels != interesting_channels[device_spec]) { device->interesting_channels = interesting_channels[device_spec]; - if (device_spec.type == InputSourceType::ALSA_INPUT) { - reset_alsa_mutex_held(device_spec); - } + reset_resampler_mutex_held(device_spec); + } + } + for (unsigned card_index = 0; card_index < MAX_ALSA_CARDS; ++card_index) { + const DeviceSpec device_spec{InputSourceType::ALSA_INPUT, card_index}; + AudioDevice *device = find_audio_device(device_spec); + if (interesting_channels[device_spec].empty()) { + alsa_pool.release_device(card_index); + } else { + alsa_pool.hold_device(card_index); + } + if (device->interesting_channels != interesting_channels[device_spec]) { + device->interesting_channels = interesting_channels[device_spec]; + alsa_pool.reset_device(device_spec.index); reset_resampler_mutex_held(device_spec); } } @@ -727,3 +1075,24 @@ InputMapping AudioMixer::get_input_mapping() const lock_guard lock(audio_mutex); return input_mapping; } + +unsigned AudioMixer::num_buses() const +{ + lock_guard lock(audio_mutex); + return input_mapping.buses.size(); +} + +void AudioMixer::reset_peak(unsigned bus_index) +{ + lock_guard lock(audio_mutex); + for (unsigned channel = 0; channel < 2; ++channel) { + PeakHistory &history = peak_history[bus_index][channel]; + history.current_level = 0.0f; + history.historic_peak = 0.0f; + history.current_peak = 0.0f; + history.last_peak = 0.0f; + history.age_seconds = 0.0f; + } +} + +AudioMixer *global_audio_mixer = nullptr;