#[cfg(test)]
mod tests {
use crate::engine::PROGRAM_TRIM_DB;
const SR: f32 = 44100.0;
const EARLY_WINDOW_S: f32 = 0.150;
const FAMILIES: [&str; 16] = [
"Piano",
"ChromPerc",
"Organ",
"Guitar",
"Bass",
"Strings",
"Ensemble",
"Brass",
"Reed",
"Pipe",
"Lead",
"Pad",
"SynthFX",
"Ethnic",
"Percussive",
"SoundFX",
];
const CELLS: [(u8, u8); 5] = [(48, 80), (60, 80), (72, 80), (60, 55), (60, 105)];
fn voice_level_db(program: u8, key: u8, vel: u8) -> f32 {
let n = (EARLY_WINDOW_S * SR) as usize;
let mut buf = vec![0.0f32; n];
let mut v = crate::voices::make(program, key, vel, SR, 0x5EED_1234, true);
let mut i = 0;
while i < n {
let k = 64.min(n - i);
v.render(&mut buf[i..i + k]);
i += k;
}
let energy: f32 = buf.iter().map(|x| x * x).sum();
20.0 * (energy / n as f32).sqrt().max(1e-12).log10()
}
fn voice_level_mean(program: u8) -> f32 {
CELLS
.iter()
.map(|&(k, v)| voice_level_db(program, k, v))
.sum::<f32>()
/ CELLS.len() as f32
}
#[test]
fn every_program_trim_reaches_the_strip_at_its_tabled_value() {
let mut worst = (0u8, 0.0f32);
for p in 0..128u8 {
let tabled = PROGRAM_TRIM_DB[p as usize];
let lin = crate::engine::program_trim_lin(p);
if tabled == 0.0 {
assert_eq!(
lin, 1.0,
"GM{p} has no trim but program_trim_lin returned {lin}, not exactly 1.0. \
An untouched program must be bit-identical, so this must be exact \
equality and not a tolerance."
);
continue;
}
assert!(
lin > 0.0 && lin.is_finite(),
"GM{p}: trim {tabled} dB produced a non-positive or non-finite gain {lin}"
);
let round_trip = 20.0 * lin.log10();
let err = (round_trip - tabled).abs();
if err > worst.1 {
worst = (p, err);
}
assert!(
err < 1e-4,
"GM{p}: tabled {tabled:+.2} dB but program_trim_lin gives {lin} \
= {round_trip:+.4} dB (error {err:.6} dB). The table and the gain \
conversion have diverged."
);
assert_eq!(
lin > 1.0,
tabled > 0.0,
"GM{p}: trim {tabled:+.2} dB produced gain {lin}, which moves the level \
the WRONG WAY. A boost must be >1.0 and a cut <1.0."
);
}
println!(
"all 128 program trims round-trip; worst error GM{} at {:.2e} dB",
worst.0, worst.1
);
}
#[test]
fn the_strip_actually_applies_the_program_trim() {
let src = include_str!("engine.rs");
let call = "program_trim_lin(strip.program)";
assert!(
src.contains(call),
"the channel strip no longer calls `{call}` — the per-program trim has been disconnected from the signal path, and every level oracle that checks only the TABLE would stay green through that regression"
);
let g_line = src
.lines()
.find(|l| l.contains("let g = strip.volume"))
.expect("the strip gain line `let g = strip.volume ...` has moved or been renamed");
assert!(
g_line.contains("trim"),
"the strip gain no longer includes the program trim:
{g_line}"
);
assert!(
src.contains("if ci != 9 {"),
"the ch9 drum exclusion around the program trim has gone; a program-indexed trim on the key-indexed drum channel would mis-level the kit"
);
}
#[test]
fn trim_derivation_reads_one_exact_engine_state() {
let tool = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.ancestors()
.nth(2)
.expect("crates/ferrosintesis sits two levels below the repo root")
.join("tools/instrument-balance/derive_trims.py");
let src = std::fs::read_to_string(&tool)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", tool.display()));
let parsers = src
.split_once("def parse_shipped(")
.and_then(|(_, rest)| rest.split_once("\ndef load_shipped("))
.map(|(body, _)| body)
.expect("derive_trims.py must define its engine parsers before load_shipped");
let ear_parser = parsers
.split_once("def parse_ear_decided(")
.map(|(_, body)| body)
.expect("derive_trims.py must define parse_ear_decided");
for required in ["_SHIPPED_RE.findall(text)", "if len(matches) != 1:"] {
assert!(
parsers.contains(required),
"derive_trims.py no longer enforces `{required}` while parsing the shipped \
trim table; a sibling, missing, or cfg-gated duplicate declaration could \
silently produce proposals against the wrong table"
);
}
assert!(
src.contains(r"\bconst\s+PROGRAM_TRIM_DB\b"),
"derive_trims.py no longer anchors the shipped-table parser to the exact \
`const PROGRAM_TRIM_DB` declaration; a prefixed sibling can match"
);
for required in [
"_EAR_DECIDED_RE.findall(text)",
"if not matches:",
"if invalid:",
"if len(programs) != len(set(programs)):",
] {
assert!(
ear_parser.contains(required),
"derive_trims.py no longer enforces `{required}` while deriving recorded \
zero-valued ear decisions; a missing, duplicate, or invalid pin could \
silently change which programs the tool is allowed to propose"
);
}
assert!(
src.contains(r"assert_eq!\(\s*PROGRAM_TRIM_DB\["),
"derive_trims.py no longer derives ear decisions from canonical \
`assert_eq!(PROGRAM_TRIM_DB[P], 0.0);` pins"
);
let assignments: Vec<&str> = src
.lines()
.map(|line| line.split('#').next().unwrap_or("").trim())
.filter(|line| {
line.split_once('=')
.map(|(lhs, _)| {
lhs.split(',')
.map(str::trim)
.any(|name| name == "SHIPPED" || name == "EAR_DECIDED")
})
.unwrap_or(false)
})
.collect();
assert_eq!(
assignments,
["SHIPPED, EAR_DECIDED = load_shipped()"],
"derive_trims.py must assign SHIPPED and EAR_DECIDED exactly once from the \
same engine.rs read; a literal or alternate assignment recreates source drift"
);
}
#[test]
fn residual_baseline_covers_every_program_and_both_references() {
let tools = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.ancestors()
.nth(2)
.expect("crates/ferrosintesis sits two levels below the repo root")
.join("tools/instrument-balance");
let baseline_path = tools.join("residual-baseline.csv");
let baseline = std::fs::read_to_string(&baseline_path)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", baseline_path.display()));
let mut data = baseline
.lines()
.filter(|line| !line.trim().is_empty() && !line.starts_with('#'));
assert_eq!(
data.next(),
Some("program,reference,residual_db,shipped_db,guard_excluded")
);
let mut keys = std::collections::BTreeSet::new();
let mut gm6 = Vec::new();
for line in data {
let columns: Vec<&str> = line.split(',').collect();
assert_eq!(columns.len(), 5, "malformed residual baseline row: {line}");
let program: u8 = columns[0]
.parse()
.unwrap_or_else(|e| panic!("bad program in `{line}`: {e}"));
assert!(
matches!(columns[1], "sc55" | "yxg"),
"unidentified reference in `{line}`"
);
if !columns[2].is_empty() {
let residual: f32 = columns[2]
.parse()
.unwrap_or_else(|e| panic!("bad residual in `{line}`: {e}"));
assert!(residual.is_finite(), "non-finite residual in `{line}`");
}
let shipped: f32 = columns[3]
.parse()
.unwrap_or_else(|e| panic!("bad shipped trim in `{line}`: {e}"));
assert!(shipped.is_finite(), "non-finite shipped trim in `{line}`");
assert!(
matches!(columns[4], "true" | "false"),
"bad guard state in `{line}`"
);
assert!(
keys.insert((program, columns[1])),
"duplicate residual baseline row: {line}"
);
if program == 6 {
gm6.push((columns[1], columns[2], columns[4]));
}
}
let expected: std::collections::BTreeSet<(u8, &str)> = (0..128)
.flat_map(|program| [(program, "sc55"), (program, "yxg")])
.collect();
assert_eq!(keys, expected, "baseline must cover all 256 reference rows");
assert_eq!(
gm6,
[("sc55", "-5.58", "true"), ("yxg", "-3.12", "true")],
"GM6 is the live excluded-on-both residual example"
);
let tool_path = tools.join("derive_trims.py");
let tool = std::fs::read_to_string(&tool_path)
.unwrap_or_else(|e| panic!("cannot read {}: {e}", tool_path.display()));
for required in [
"DRIFT_FLAG_DB = 1.0",
"def residual_baseline_findings(",
"old[\"guard_excluded\"] != new[\"guard_excluded\"]",
"new_residual + new[\"shipped_db\"]",
"baseline excluded={old['guard_excluded']}",
"return 0 if compare_residual_baseline(refs) else 1",
] {
assert!(
tool.contains(required),
"derive_trims.py no longer enforces cross-run invariant `{required}`"
);
}
}
#[test]
fn the_trim_gate_rejects_a_divergent_conversion() {
let wrong = |db: f32| 10f32.powf(db / 10.0);
let mut caught = 0;
for p in 0..128u8 {
let tabled = PROGRAM_TRIM_DB[p as usize];
if tabled == 0.0 {
continue;
}
let round_trip = 20.0 * wrong(tabled).log10();
if (round_trip - tabled).abs() >= 1e-4 {
caught += 1;
}
}
assert!(
caught > 0,
"the round-trip check cannot detect a power-vs-amplitude dB error, so it \
would pass on a synth whose trims were all half as strong as tabled"
);
let right = |db: f32| 10f32.powf(db / 20.0);
for p in 0..128u8 {
let tabled = PROGRAM_TRIM_DB[p as usize];
if tabled == 0.0 {
continue;
}
assert!(
(20.0 * right(tabled).log10() - tabled).abs() < 1e-4,
"the check rejects the CORRECT conversion at GM{p} — it is too tight"
);
}
}
#[test]
fn gm85_formant_bank_keeps_its_make_up_gain() {
let gm84 = voice_level_mean(84);
let gm85 = voice_level_mean(85);
let delta = gm85 - gm84;
println!("GM85 {gm85:.2} dB vs GM84 {gm84:.2} dB -> {delta:+.2} dB");
assert!(
delta.abs() <= 6.0,
"GM85 sits {delta:+.2} dB from GM84 (bar +/-6). A formant bandpass bank passes far less broadband energy than a lowpass, so it needs a make-up gain - see LEAD85_FORMANT_MAKEUP_DB in voices.rs. MM-BUG-KILN-00108 was exactly this, at -12.6 dB."
);
}
#[test]
#[ignore = "diagnostic; run with --ignored when reviewing instrument balance"]
fn report_trim_effect_on_family_spread() {
let spread = |family: usize, trimmed: bool| -> f32 {
let levels: Vec<f32> = ((family * 8)..(family * 8 + 8))
.map(|p| voice_level_mean(p as u8) + if trimmed { PROGRAM_TRIM_DB[p] } else { 0.0 })
.collect();
levels.iter().cloned().fold(f32::NEG_INFINITY, f32::max)
- levels.iter().cloned().fold(f32::INFINITY, f32::min)
};
println!(
"\n{:>3} {:<11} {:>10} {:>10} {:>10} effect",
"#", "family", "untrimmed", "trimmed", "change"
);
for (f, name) in FAMILIES.iter().enumerate() {
let (un, tr) = (spread(f, false), spread(f, true));
let d = tr - un;
let touched = ((f * 8)..(f * 8 + 8)).any(|p| PROGRAM_TRIM_DB[p] != 0.0);
let effect = if !touched {
"untouched"
} else if d < -0.05 {
"narrows"
} else if d > 0.05 {
"widens"
} else {
"neutral"
};
println!("{f:>3} {name:<11} {un:>9.2} {tr:>9.2} {d:>+9.2} {effect}");
}
println!("\n(widening is not a defect - the target is SC-55 fidelity, not flatness)\n");
}
}