+
+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<size_t>(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<float> *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<float> &samples_bus, vector<float> *samples_out)
+{
+ assert(samples_bus.size() == samples_out->size());
+ assert(samples_bus.size() % 2 == 0);
+ unsigned num_samples = samples_bus.size() / 2;
+ if (fabs(fader_volume_db[bus_index] - 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<float>(last_fader_volume_db[bus_index], -90.0f));
+ float volume = from_db(max<float>(fader_volume_db[bus_index], -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 {
+ float volume = from_db(fader_volume_db[bus_index]);
+ 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] = fader_volume_db[bus_index];
+}
+
+void AudioMixer::measure_bus_levels(unsigned bus_index, const vector<float> &left, const vector<float> &right)
+{
+ assert(left.size() == right.size());
+ const float volume = 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
+ };
+ for (unsigned channel = 0; channel < 2; ++channel) {
+ // Compute the current value, including hold and falloff.
+ // The constants are borrowed from zita-mu1 by Fons Adriaensen.
+ static constexpr float hold_sec = 0.5f;
+ 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 {
+ current_peak = history.last_peak * from_db(-falloff_db_sec * (history.age_seconds - hold_sec));
+ }
+
+ // See if we have a new peak to replace the old (possibly falling) one.
+ if (peak_levels[channel] > current_peak) {
+ history.last_peak = peak_levels[channel];
+ history.age_seconds = 0.0f; // Not 100% correct, but more than good enough given our frame sizes.
+ current_peak = peak_levels[channel];
+ } else {
+ history.age_seconds += float(left.size()) / OUTPUT_FREQUENCY;
+ }
+ history.current_level = peak_levels[channel];
+ history.current_peak = current_peak;
+ }
+}
+
+void AudioMixer::update_meters(const vector<float> &samples)
+{
+ // Upsample 4x to find interpolated peak.
+ peak_resampler.inp_data = const_cast<float *>(samples.data());
+ peak_resampler.inp_count = samples.size() / 2;
+
+ vector<float> interpolated_samples;
+ interpolated_samples.resize(samples.size());
+ {
+ lock_guard<mutex> lock(audio_measure_mutex);
+
+ while (peak_resampler.inp_count > 0) { // About four iterations.
+ peak_resampler.out_data = &interpolated_samples[0];
+ peak_resampler.out_count = interpolated_samples.size() / 2;
+ peak_resampler.process();
+ size_t out_stereo_samples = interpolated_samples.size() / 2 - peak_resampler.out_count;
+ peak = max<float>(peak, find_peak(interpolated_samples.data(), out_stereo_samples * 2));
+ peak_resampler.out_data = nullptr;
+ }
+ }
+
+ // Find R128 levels and L/R correlation.
+ vector<float> left, right;
+ deinterleave_samples(samples, &left, &right);
+ float *ptrs[] = { left.data(), right.data() };
+ {
+ lock_guard<mutex> lock(audio_measure_mutex);
+ r128.process(left.size(), ptrs);
+ correlation.process_samples(samples);
+ }
+
+ send_audio_level_callback();
+}
+
+void AudioMixer::reset_meters()
+{
+ lock_guard<mutex> lock(audio_measure_mutex);
+ peak_resampler.reset();
+ peak = 0.0f;
+ r128.reset();
+ r128.integr_start();
+ correlation.reset();
+}
+
+void AudioMixer::send_audio_level_callback()
+{
+ if (audio_level_callback == nullptr) {
+ return;
+ }
+
+ lock_guard<mutex> lock(audio_measure_mutex);
+ double loudness_s = r128.loudness_S();
+ double loudness_i = r128.integrated();
+ double loudness_range_low = r128.range_min();
+ double loudness_range_high = r128.range_max();
+
+ vector<BusLevel> bus_levels;
+ bus_levels.resize(input_mapping.buses.size());
+ {
+ lock_guard<mutex> 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].historic_peak_dbfs = to_db(
+ max(peak_history[bus_index][0].historic_peak,
+ peak_history[bus_index][1].historic_peak));
+ bus_levels[bus_index].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());
+ } else {
+ bus_levels[bus_index].compressor_attenuation_db = 0.0;
+ }
+ }
+ }
+
+ audio_level_callback(loudness_s, to_db(peak), bus_levels,
+ loudness_i, loudness_range_low, loudness_range_high,
+ to_db(final_makeup_gain),
+ correlation.get_correlation());
+}
+
+map<DeviceSpec, DeviceInfo> AudioMixer::get_devices()
+{
+ lock_guard<timed_mutex> lock(audio_mutex);
+
+ map<DeviceSpec, DeviceInfo> 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.display_name = device->display_name;
+ info.num_channels = 8;
+ devices.insert(make_pair(spec, info));
+ }
+ vector<ALSAPool::Device> 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 ALSAPool::Device &device = available_alsa_devices[card_index];
+ DeviceInfo 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_display_name(DeviceSpec device_spec, const string &name)
+{
+ AudioDevice *device = find_audio_device(device_spec);
+
+ lock_guard<timed_mutex> lock(audio_mutex);
+ device->display_name = name;
+}
+
+void AudioMixer::serialize_device(DeviceSpec device_spec, DeviceSpecProto *device_spec_proto)
+{
+ lock_guard<timed_mutex> 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<timed_mutex> 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<timed_mutex> 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<unsigned>::max();
+ }
+}
+
+void AudioMixer::set_input_mapping(const InputMapping &new_input_mapping)
+{
+ lock_guard<timed_mutex> 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<timed_mutex> lock(audio_mutex);
+ return current_mapping_mode;
+}
+
+void AudioMixer::set_input_mapping_lock_held(const InputMapping &new_input_mapping)
+{
+ map<DeviceSpec, set<unsigned>> interesting_channels;
+ for (const InputMapping::Bus &bus : new_input_mapping.buses) {
+ if (bus.device.type == InputSourceType::CAPTURE_CARD ||
+ bus.device.type == InputSourceType::ALSA_INPUT) {
+ for (unsigned channel = 0; channel < 2; ++channel) {
+ if (bus.source_channel[channel] != -1) {
+ interesting_channels[bus.device].insert(bus.source_channel[channel]);
+ }
+ }
+ }
+ }
+
+ // Reset resamplers for all cards that don't have the exact same state as before.
+ 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];
+ 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);
+ }
+ }
+
+ input_mapping = new_input_mapping;
+}
+
+InputMapping AudioMixer::get_input_mapping() const
+{
+ lock_guard<timed_mutex> lock(audio_mutex);
+ return input_mapping;
+}
+
+void AudioMixer::reset_peak(unsigned bus_index)
+{
+ lock_guard<timed_mutex> 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;