Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 46 additions & 8 deletions backend/src/blocks/builtin/mixer/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,25 @@ use tracing::{debug, info, warn};
use super::elements::*;
use super::metering::connect_mixer_meter_handler;
use super::properties::*;
use super::{METER_INTERVAL_NS, MIN_KNEE_LINEAR};
use super::{METER_INTERVAL_NS, MIN_KNEE_LINEAR, MIXER_SAMPLE_RATE};
use strom_types::mixer::{DEFAULT_LATENCY_MS, DEFAULT_MIN_UPSTREAM_LATENCY_MS};

/// Follow a bus mixer with its rate pin. Returns the pin's id: the bus's
/// output now leaves from there.
fn push_rate_pin(
mixer_id: &str,
elements: &mut Vec<(String, gst::Element)>,
internal_links: &mut Vec<(ElementPadRef, ElementPadRef)>,
) -> Result<String, BlockBuildError> {
let pin_id = format!("{}_rate", mixer_id);
elements.push((pin_id.clone(), make_rate_pin(&pin_id)?));
internal_links.push((
ElementPadRef::pad(mixer_id, "src"),
ElementPadRef::pad(&pin_id, "sink"),
));
Ok(pin_id)
}

/// Mixer block builder.
pub struct MixerBuilder;

Expand Down Expand Up @@ -128,6 +144,7 @@ impl BlockBuilder for MixerBuilder {
let audiomixer =
make_audiomixer(&mixer_id, force_live, latency_ms, min_upstream_latency_ms)?;
elements.push((mixer_id.clone(), audiomixer.clone()));
let mixer_out_id = push_rate_pin(&mixer_id, &mut elements, &mut internal_links)?;

// ========================================================================
// Main bus processing: comp → EQ → limiter
Expand Down Expand Up @@ -242,7 +259,7 @@ impl BlockBuilder for MixerBuilder {

// Link: mixer → main_comp → main_eq → main_limiter → main_volume → main_level → main_out_tee
internal_links.push((
ElementPadRef::pad(&mixer_id, "src"),
ElementPadRef::pad(&mixer_out_id, "src"),
ElementPadRef::pad(&main_comp_id, "sink"),
));
internal_links.push((
Expand Down Expand Up @@ -285,6 +302,7 @@ impl BlockBuilder for MixerBuilder {
min_upstream_latency_ms,
)?;
elements.push((solo_mixer_id.clone(), solo_mixer));
let solo_out_id = push_rate_pin(&solo_mixer_id, &mut elements, &mut internal_links)?;

// Gates feeding monitor_mixer
let solo_to_mon_id = format!("{}:solo_to_mon", instance_id);
Expand Down Expand Up @@ -328,6 +346,7 @@ impl BlockBuilder for MixerBuilder {
min_upstream_latency_ms,
)?;
elements.push((monitor_mixer_id.clone(), monitor_mixer));
let monitor_out_id = push_rate_pin(&monitor_mixer_id, &mut elements, &mut internal_links)?;

// Monitor master volume (driven by `monitor_fader` exposed property)
let monitor_master_vol_id = format!("{}:monitor_master_vol", instance_id);
Expand Down Expand Up @@ -364,7 +383,7 @@ impl BlockBuilder for MixerBuilder {
// ├→ monitor_mixer → monitor_master_vol → monitor_level → monitor_out_tee
// main_out_tee→ main_to_mon → main_to_mon_queue ─┘
internal_links.push((
ElementPadRef::pad(&solo_mixer_id, "src"),
ElementPadRef::pad(&solo_out_id, "src"),
ElementPadRef::pad(&solo_to_mon_id, "sink"),
));
internal_links.push((
Expand All @@ -388,7 +407,7 @@ impl BlockBuilder for MixerBuilder {
ElementPadRef::element(&monitor_mixer_id),
));
internal_links.push((
ElementPadRef::pad(&monitor_mixer_id, "src"),
ElementPadRef::pad(&monitor_out_id, "src"),
ElementPadRef::pad(&monitor_master_vol_id, "sink"),
));
internal_links.push((
Expand All @@ -412,6 +431,7 @@ impl BlockBuilder for MixerBuilder {
min_upstream_latency_ms,
)?;
elements.push((aux_mixer_id.clone(), aux_mixer));
let aux_out_id = push_rate_pin(&aux_mixer_id, &mut elements, &mut internal_links)?;

let aux_fader = get_float_prop(properties, &format!("aux{}_fader", aux + 1), 1.0);
let aux_mute = get_bool_prop(properties, &format!("aux{}_mute", aux + 1), false);
Expand Down Expand Up @@ -451,7 +471,7 @@ impl BlockBuilder for MixerBuilder {

// Link: aux_mixer → aux_volume → aux_level → aux_out_tee
internal_links.push((
ElementPadRef::pad(&aux_mixer_id, "src"),
ElementPadRef::pad(&aux_out_id, "src"),
ElementPadRef::pad(&aux_volume_id, "sink"),
));
internal_links.push((
Expand Down Expand Up @@ -515,6 +535,7 @@ impl BlockBuilder for MixerBuilder {
min_upstream_latency_ms,
)?;
elements.push((sg_mixer_id.clone(), sg_mixer));
let sg_out_id = push_rate_pin(&sg_mixer_id, &mut elements, &mut internal_links)?;

let sg_fader = get_float_prop(properties, &format!("group{}_fader", sg + 1), 1.0);
let sg_mute = get_bool_prop(properties, &format!("group{}_mute", sg + 1), false);
Expand Down Expand Up @@ -566,7 +587,7 @@ impl BlockBuilder for MixerBuilder {
// Link: group_mixer → group_volume → group_level → group_out_tee
// group_out_tee → queue → main audiomixer
internal_links.push((
ElementPadRef::pad(&sg_mixer_id, "src"),
ElementPadRef::pad(&sg_out_id, "src"),
ElementPadRef::pad(&sg_volume_id, "sink"),
));
internal_links.push((
Expand Down Expand Up @@ -669,10 +690,23 @@ impl BlockBuilder for MixerBuilder {
})?;
elements.push((convert_id.clone(), convert));

// capsfilter to ensure F32LE stereo format for LV2 plugins
// audioresample: the buses run at MIXER_SAMPLE_RATE, so a source at
// another rate is converted here rather than refused.
let resample_id = format!("{}:resample_{}", instance_id, ch);
let resample = gst::ElementFactory::make("audioresample")
.name(&resample_id)
.build()
.map_err(|e| {
BlockBuildError::ElementCreation(format!("audioresample ch{}: {}", ch_num, e))
})?;
elements.push((resample_id.clone(), resample));

// capsfilter to ensure F32LE stereo format for LV2 plugins, at the
// buses' rate
let caps_id = format!("{}:caps_{}", instance_id, ch);
let caps = gst::Caps::builder("audio/x-raw")
.field("format", "F32LE")
.field("rate", MIXER_SAMPLE_RATE)
.field("channels", 2i32)
.field("layout", "interleaved")
.build();
Expand Down Expand Up @@ -987,11 +1021,15 @@ impl BlockBuilder for MixerBuilder {
// ----------------------------------------------------------------
// Main chain links
// ----------------------------------------------------------------
// Chain: convert → caps → gain → hpf → gate → comp → eq → level → pre_fader_tee
// Chain: convert → resample → caps → gain → hpf → gate → comp → eq → level → pre_fader_tee
// The channel `level` element sits pre-fader (after EQ/dynamics, before
// pan/fader/mute) so the meter reflects the signal hitting the fader.
internal_links.push((
ElementPadRef::pad(&convert_id, "src"),
ElementPadRef::pad(&resample_id, "sink"),
));
internal_links.push((
ElementPadRef::pad(&resample_id, "src"),
ElementPadRef::pad(&caps_id, "sink"),
));
internal_links.push((
Expand Down
18 changes: 17 additions & 1 deletion backend/src/blocks/builtin/mixer/elements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::sync::OnceLock;
use tracing::{error, warn};

use super::properties::db_to_linear;
use super::EQ_BAND_TYPE_BELL;
use super::{EQ_BAND_TYPE_BELL, MIXER_SAMPLE_RATE};

/// Cached result of checking whether audiomixer supports the force-live property.
static AUDIOMIXER_HAS_FORCE_LIVE: OnceLock<bool> = OnceLock::new();
Expand Down Expand Up @@ -65,6 +65,22 @@ pub(crate) fn make_audiomixer(
Ok(mixer)
}

/// Create the capsfilter that follows a bus mixer and pins it to
/// `MIXER_SAMPLE_RATE`. Only the rate is fixed: format and channels stay
/// with whatever the bus negotiates.
pub(super) fn make_rate_pin(name: &str) -> Result<gst::Element, BlockBuildError> {
gst::ElementFactory::make("capsfilter")
.name(name)
.property(
"caps",
gst::Caps::builder("audio/x-raw")
.field("rate", MIXER_SAMPLE_RATE)
.build(),
)
.build()
.map_err(|e| BlockBuildError::ElementCreation(format!("capsfilter {}: {}", name, e)))
}

/// Create a gate element, falling back to identity passthrough if unavailable.
pub(super) fn make_gate_element(
name: &str,
Expand Down
12 changes: 11 additions & 1 deletion backend/src/blocks/builtin/mixer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//!
//! Pipeline structure per channel:
//! ```text
//! input_N → audioconvert → capsfilter(F32LE) → gain → hpf → gate → compressor → EQ →
//! input_N → audioconvert → audioresample → capsfilter(F32LE, 48 kHz) → gain → hpf → gate → compressor → EQ →
//! level_N → pre_fader_tee → audiopanorama_N → volume_N → post_fader_tee →
//! routing_tee_N → [group or main audiomixer]
//!
Expand All @@ -38,6 +38,9 @@
//! `monitor_level`, `auxN_level`, `groupN_level`) sit on the bus output,
//! post-master.
//!
//! Every bus mixer (main, monitor, solo, aux, group) is followed by a
//! `<mixer>_rate` capsfilter that pins it to `MIXER_SAMPLE_RATE`.
//!
//! Main bus: audiomixer → main_comp → main_eq → main_limiter → main_volume → main_level → main_out_tee
//!
//! Monitor bus: the solo_mixer and a tap from main_out_tee both feed a
Expand Down Expand Up @@ -68,6 +71,13 @@ mod tests;
use strom_types::mixer::{
DEFAULT_CHANNELS, MAX_AUX_BUSES, MAX_CHANNELS, MAX_GROUPS, MIN_KNEE_LINEAR,
};
/// Sample rate every bus inside the mixer runs at. The buses feed one another
/// (aux and group AFL into solo, solo and main into monitor), and an
/// audiomixer cannot resample, so they must agree on one rate. Left free, a
/// bus with no input yet fixates to audiomixer's default of 44100 while one
/// with a pinned consumer settles at that consumer's rate, and from then on
/// no channel can link.
const MIXER_SAMPLE_RATE: i32 = 48_000;
/// Level meter interval in nanoseconds (100ms)
const METER_INTERVAL_NS: u64 = 100_000_000;
/// EQ band type for Peaking/Bell filter (lsp-rs-equalizer enum value)
Expand Down
145 changes: 145 additions & 0 deletions backend/src/blocks/builtin/mixer/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -826,3 +826,148 @@ fn test_built_mixer_passes_audio_to_main_out() {
}
}
}

/// Hang `caps → level → fakesink` off `tee`. The level element is named
/// `level_name` so its messages can be told apart on the bus.
fn tap(m: &Assembled, tee: &str, caps: &str, level_name: &str) {
let filter = gst::ElementFactory::make("capsfilter")
.property("caps", caps.parse::<gst::Caps>().unwrap())
.build()
.unwrap();
let level = gst::ElementFactory::make("level")
.name(level_name)
.property("interval", 50_000_000u64)
.property("post-messages", true)
.build()
.unwrap();
let sink = gst::ElementFactory::make("fakesink")
.property("sync", false)
.property("async", false)
.build()
.unwrap();
m.pipeline.add_many([&filter, &level, &sink]).unwrap();
m.element(tee)
.link_pads(Some("src_%u"), &filter, None)
.unwrap();
gst::Element::link_many([&filter, &level, &sink]).unwrap();
}

/// A mixer with return feeds: aux buses and the solo bus start with no input
/// and nothing downstream that fixes a rate, while main feeds a consumer that
/// needs 48 kHz (an encoder, the vision mixer). An input at `rate` that
/// arrives after startup, as every WHIP input does, must link and be heard
/// on main and on an aux bus.
fn assert_late_input_is_heard(rate: i32) {
let m = assemble(&props(&[
("num_channels", PropertyValue::UInt(2)),
("num_aux_buses", PropertyValue::UInt(2)),
("num_groups", PropertyValue::UInt(1)),
("dsp_backend", PropertyValue::String("rust".to_string())),
// Aux sends default to 0: open channel 1's send to aux 2.
("ch1_aux2_level", PropertyValue::Float(1.0)),
]));
tap(&m, "main_out_tee", "audio/x-raw,rate=48000", "tap_main");
tap(&m, "aux1_out_tee", "audio/x-raw", "tap_aux1");
tap(&m, "aux0_out_tee", "audio/x-raw", "tap_aux0");
tap(&m, "monitor_out_tee", "audio/x-raw", "tap_monitor");
tap(&m, "group0_out_tee", "audio/x-raw", "tap_group0");

m.pipeline.set_state(gst::State::Playing).unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
// An idle bus left to fixate on its own picks 44100; check the rate
// before the late link, which would otherwise fail and hide the cause.
for bus in [
"audiomixer",
"aux0_mixer",
"aux1_mixer",
"group0_mixer",
"solo_mixer",
"monitor_mixer",
] {
let pad = m.element(bus).static_pad("src").unwrap();
let caps = loop {
if let Some(caps) = pad.current_caps() {
break caps;
}
assert!(Instant::now() < deadline, "{bus} never negotiated");
std::thread::sleep(Duration::from_millis(20));
};
assert_eq!(
caps.structure(0).unwrap().get::<i32>("rate").unwrap(),
MIXER_SAMPLE_RATE,
"{bus} negotiated {caps}"
);
}

let src = gst::ElementFactory::make("audiotestsrc")
.property("is-live", true)
.build()
.unwrap();
let decoded = gst::ElementFactory::make("capsfilter")
.property(
"caps",
gst::Caps::builder("audio/x-raw")
.field("format", "S16LE")
.field("rate", rate)
.field("channels", 2i32)
.field("layout", "interleaved")
.build(),
)
.build()
.unwrap();
m.pipeline.add_many([&src, &decoded]).unwrap();
src.link(&decoded).unwrap();
decoded
.static_pad("src")
.unwrap()
.link(&m.element("convert_0").static_pad("sink").unwrap())
.expect("a late input must link into a running mixer");
src.sync_state_with_parent().unwrap();
decoded.sync_state_with_parent().unwrap();

// The buses are live and emit silence with no input, so buffers alone
// prove nothing: wait for the tone's level on main and on aux1.
let bus = m.pipeline.bus().unwrap();
let mut heard = HashSet::new();
while heard.len() < 2 {
assert!(
Instant::now() < deadline,
"the input was not heard on {:?}",
["tap_main", "tap_aux1"]
.iter()
.filter(|n| !heard.contains(**n))
.collect::<Vec<_>>()
);
let Some(msg) = bus.timed_pop_filtered(
gst::ClockTime::from_mseconds(50),
&[gst::MessageType::Error, gst::MessageType::Element],
) else {
continue;
};
if let gst::MessageView::Error(err) = msg.view() {
panic!("pipeline error: {err:?}");
}
let (Some(from), Some(structure)) = (msg.src(), msg.structure()) else {
continue;
};
let name = from.name();
if structure.name() == "level"
&& (name == "tap_main" || name == "tap_aux1")
&& extract_level_values(structure, "peak")
.iter()
.any(|db| *db > -40.0)
{
heard.insert(name.to_string());
}
}
}

#[test]
fn test_input_links_late_when_main_consumer_pins_rate() {
assert_late_input_is_heard(48_000);
}

#[test]
fn test_late_input_at_another_rate_is_resampled() {
assert_late_input_is_heard(44_100);
}
Loading