diff --git a/crates/aurora-speaker-tuning/src/mic.rs b/crates/aurora-speaker-tuning/src/mic.rs index 3ecefaa2..e83a20aa 100644 --- a/crates/aurora-speaker-tuning/src/mic.rs +++ b/crates/aurora-speaker-tuning/src/mic.rs @@ -1003,6 +1003,100 @@ pub struct Nest<'a> { pub dev_drop_tone_types: u64, } +/// The region between a `split` box and the `join` that gathers its +/// outputs back, as a stand-alone graph (input wired to the split, the +/// join wired to the output) for [`nested`]. Every path out of the split +/// must reach that one join without leaving the region. +fn split_region(g: &Graph, split: &str) -> Result<(Graph, String, Vec)> { + let mut members: Vec = Vec::new(); + let mut join: Option = None; + let mut todo: Vec = vec![split.to_string()]; + while let Some(n) = todo.pop() { + for w in g.wires.iter().filter(|w| w.src.node == n) { + let d = &w.dst.node; + let bx = g.find_box(d).ok_or_else(|| bad(format!("split region of {split}: {d} is not a box")))?; + if subtype(bx) == "join" { + match &join { + Some(j) if j != d => { + return Err(bad(format!("split region of {split}: two joins ({j}, {d})"))); + } + _ => join = Some(d.clone()), + } + continue; + } + if subtype(bx) == "split" || members.len() > 64 { + return Err(bad(format!("split region of {split}: nested split or too large at {d}"))); + } + if !members.contains(d) { + members.push(d.clone()); + todo.push(d.clone()); + } + } + } + let join = join.ok_or_else(|| bad(format!("split region of {split}: no join")))?; + // every input of every member and of the join comes from inside the region + let inside = |n: &str| n == split || members.iter().any(|m| m == n); + for w in g.wires.iter().filter(|w| w.dst.node == join || members.contains(&w.dst.node)) { + if !inside(&w.src.node) { + return Err(bad(format!("split region of {split}: {} feeds {} from outside", w.src.node, w.dst.node))); + } + } + let (i, o) = ("__region_in".to_string(), "__region_out".to_string()); + let keep = |n: &str| n == split || n == join || members.iter().any(|m| m == n); + let mut sub = g.clone(); + sub.inputs = vec![i.clone()]; + sub.outputs = vec![o.clone()]; + sub.boxes.retain(|b| keep(&b.name)); + let into_split = g + .wires + .iter() + .find(|w| w.dst.node == split) + .cloned() + .ok_or_else(|| bad(format!("split region of {split}: nothing feeds the split")))?; + let out_of_join = g + .wires + .iter() + .find(|w| w.src.node == join && w.src.port == 0) + .cloned() + .ok_or_else(|| bad(format!("split region of {split}: the join feeds nothing")))?; + let mut wires: Vec = + g.wires.iter().filter(|w| keep(&w.src.node) && keep(&w.dst.node)).cloned().collect(); + let mut a = into_split; + a.src = dspg::Endpoint { node: i, port: 0 }; + let mut z = out_of_join; + z.dst = dspg::Endpoint { node: o, port: 0 }; + wires.insert(0, a); + wires.push(z); + sub.wires = wires; + // Graph parameters reach the region's boxes unchanged: keep the + // declarations and every link into a region box (the caller passes the + // resolved values). A link that crosses the region boundary (a + // parameter box outside driving a box inside, or the reverse) or a + // property link into the region cannot be preserved: refuse. + for l in &g.box_param_links { + if keep(&l.from.node) != keep(&l.to.node) { + return Err(bad(format!( + "split region of {split}: parameter link {} -> {} crosses the region", + l.from.node, l.to.node + ))); + } + } + if let Some(l) = g.box_property_links.iter().find(|l| keep(&l.from.node) || keep(&l.to.node)) { + return Err(bad(format!( + "split region of {split}: property link {} -> {} not carried", + l.from.node, l.to.node + ))); + } + if let Some(l) = g.property_links.iter().find(|l| keep(&l.target.node)) { + return Err(bad(format!("split region of {split}: property {} -> {} not carried", l.name, l.target.node))); + } + sub.param_links.retain(|l| keep(&l.target.node)); + sub.box_param_links.retain(|l| keep(&l.from.node) && keep(&l.to.node)); + sub.box_property_links.clear(); + sub.property_links.clear(); + Ok((sub, join, members)) +} + /// A nested graph (`aufx/dspg` box) flattened into one voicing chain: its /// filter boxes, `split`/`join` routing, `asum` sums and dB gains, at the /// static values of its parameter logic. `width` is the parent's wire. @@ -1453,6 +1547,61 @@ pub fn compile(b: &Bundle, opts: &Options, diags: &mut Diagnostics) -> Result { + let mut dropped = Vec::new(); + let nest = Nest { + graph: &sub_g, + strip: &strip, + props: props.as_ref(), + parent_params: &graph_params, + width: in_w, + fs: fs as f64, + dev_drop_tone_types: opts.dev_drop_tone_types, + }; + let stages = if domain == Domain::PostTime { &mut post } else { &mut pre }; + match nested(&nest, &mut r.notes, &mut dropped) { + Ok(spec) => { + let n = spec.nodes.len(); + stages.push(Stage::Graph(spec)); + let dom = "time"; + r.stage( + &nx, + "split", + dom, + Status::Exact, + format!("split/join region ({}) flattened to {n} nodes", members.join(", ")), + ); + if !dropped.is_empty() { + r.refusals.push(format!( + "{nx}: development option switched off {} (analysis only, never a blob)", + dropped.join(", ") + )); + } + } + Err(err) => { + r.stage(&nx, "split", "time", Status::Refused, err.to_string()); + r.refusals.push(err.to_string()); + break; + } + } + visited.extend(members); + visited.push(join.clone()); + node = join; + continue; + } + Err(err) => { + r.stage(&nx, "split", "time", Status::Refused, err.to_string()); + r.refusals.push(err.to_string()); + break; + } + } + } let e = strip.effect(&nx); let ov = overrides.get(&nx).cloned().unwrap_or_default(); let kind = kind_name(bx); diff --git a/crates/aurora-speaker-tuning/tests/mic.rs b/crates/aurora-speaker-tuning/tests/mic.rs index a3348d57..4e4a4691 100644 --- a/crates/aurora-speaker-tuning/tests/mic.rs +++ b/crates/aurora-speaker-tuning/tests/mic.rs @@ -767,3 +767,94 @@ fn the_phase_companion_is_a_butterworth_allpass() { assert!((s.a1 - (-2.0 * w0.cos() / a0)).abs() < 1e-9 && (s.a2 - (1.0 - alpha) / a0).abs() < 1e-9, "{s:?}"); assert!((s.b0 - s.a2).abs() < 1e-12 && (s.b1 - s.a1).abs() < 1e-12 && (s.b2 - 1.0).abs() < 1e-12); } + +#[test] +fn per_microphone_trims_between_a_split_and_a_join_are_carried() { + let tone = |e: &mut Engine| { + let n = 48_000; + let x: Vec = + (0..n).map(|k| 0.1 * (2.0 * std::f64::consts::PI * 1000.0 * k as f64 / 48_000.0).sin() as f32).collect(); + let mut y = vec![0.0f32; n]; + for at in (0..n).step_by(128) { + e.process(&[&x[at..at + 128], &x[at..at + 128]], &mut y[at..at + 128], 128); + } + let tail = &y[24_000..24_000 + 48 * 400]; + (tail.iter().map(|v| f64::from(*v).powi(2)).sum::() / tail.len() as f64).sqrt() + }; + let base = Fixture::new().tree("mic-trim-base"); + let p0 = mic::compile(&base, &mic::Options::default(), &mut Diagnostics::default()).unwrap().params.unwrap(); + let r0 = tone(&mut Engine::new(p0).unwrap()); + + let mut f = Fixture::new(); + f.graph = graph(None) + .replace( + "wire Rb Sens ([fs] [numChansIn] [blockSize])\n", + "wire Rb Sp ([fs] [numChansIn] [blockSize])\n\ + wire (Sp 0) T0 ([fs] 1 [blockSize])\n\ + wire (Sp 1) T1 ([fs] 1 [blockSize])\n\ + wire T0 (Jn 0) ([fs] 1 [blockSize])\n\ + wire T1 (Jn 1) ([fs] 1 [blockSize])\n\ + wire Jn Sens ([fs] [numChansIn] [blockSize])\n", + ) + .replace( + "box Eq (aufx tmst appl) 1 1\n", + "box Eq (aufx tmst appl) 1 1\nbox Sp split 1 2\nbox Jn join 2 1\nbox T0 dbgn 1 1\nbox T1 dbgn 1 1\n", + ); + let six = 20.0 * 2f64.log10(); + f.effects.push(unit_effect("T0", "dbgn", &state(&[(0, six as f32), (1, 0.0)]), false, Some("dbgain"))); + f.effects.push(unit_effect("T1", "dbgn", &state(&[(0, six as f32), (1, 0.0)]), false, Some("dbgain"))); + let b = f.tree("mic-trim"); + let c = mic::compile(&b, &mic::Options::default(), &mut Diagnostics::default()).unwrap(); + assert!(!c.refused(), "{:?}", c.report.refusals); + assert!(c.report.stages.iter().any(|s| s.name == "Sp" && s.status == Status::Exact), "{:?}", c.report.stages); + let r1 = tone(&mut Engine::new(c.params.unwrap()).unwrap()); + assert!((r1 / r0 - 2.0).abs() < 2e-3, "trimmed {r1} vs base {r0}"); +} + +#[test] +fn an_outer_graph_default_driving_a_trim_inside_a_split_region_is_carried() { + let tone = |e: &mut Engine| { + let n = 48_000; + let x: Vec = + (0..n).map(|k| 0.1 * (2.0 * std::f64::consts::PI * 1000.0 * k as f64 / 48_000.0).sin() as f32).collect(); + let mut y = vec![0.0f32; n]; + for at in (0..n).step_by(128) { + e.process(&[&x[at..at + 128], &x[at..at + 128]], &mut y[at..at + 128], 128); + } + let tail = &y[24_000..24_000 + 48 * 400]; + (tail.iter().map(|v| f64::from(*v).powi(2)).sum::() / tail.len() as f64).sqrt() + }; + let base = Fixture::new().tree("mic-param-base"); + let p0 = mic::compile(&base, &mic::Options::default(), &mut Diagnostics::default()).unwrap().params.unwrap(); + let r0 = tone(&mut Engine::new(p0).unwrap()); + + // the trims' saved state is 0 dB; the graph parameter's default (+6.02 dB) + // drives both through the outer graph's links + let six = 20.0 * 2f64.log10(); + let mut f = Fixture::new(); + f.graph = graph(None) + .replace( + "wire Rb Sens ([fs] [numChansIn] [blockSize])\n", + "wire Rb Sp ([fs] [numChansIn] [blockSize])\n\ + wire (Sp 0) T0 ([fs] 1 [blockSize])\n\ + wire (Sp 1) T1 ([fs] 1 [blockSize])\n\ + wire T0 (Jn 0) ([fs] 1 [blockSize])\n\ + wire T1 (Jn 1) ([fs] 1 [blockSize])\n\ + wire Jn Sens ([fs] [numChansIn] [blockSize])\n", + ) + .replace( + "box Eq (aufx tmst appl) 1 1\n", + "box Eq (aufx tmst appl) 1 1\nbox Sp split 1 2\nbox Jn join 2 1\nbox T0 dbgn 1 1\nbox T1 dbgn 1 1\n", + ) + .replace( + "param mvol 0\n", + &format!("param mvol 0\nparam tdb {six}\nwireGraphParam tdb (T0 0)\nwireGraphParam tdb (T1 0)\n"), + ); + f.effects.push(unit_effect("T0", "dbgn", &state(&[(0, 0.0), (1, 0.0)]), false, Some("dbgain"))); + f.effects.push(unit_effect("T1", "dbgn", &state(&[(0, 0.0), (1, 0.0)]), false, Some("dbgain"))); + let b = f.tree("mic-param-trim"); + let c = mic::compile(&b, &mic::Options::default(), &mut Diagnostics::default()).unwrap(); + assert!(!c.refused(), "{:?}", c.report.refusals); + let r1 = tone(&mut Engine::new(c.params.unwrap()).unwrap()); + assert!((r1 / r0 - 2.0).abs() < 2e-3, "parameter-driven trim {r1} vs base {r0}"); +}