SPB Git

Repository Public

graph.rs 10.5 KB 197 lines rust

1//! ORIX Sonata2//! File: crates/sonata-compiler/tests/graph.rs3//! Description: Mixing-graph tests on the fixture registry: structure, sends and buses,4//! latency compensation, bus loops, pruning, determinism; session cache and module reuse.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_compiler::*;10use sonata_ir::*;11use sonata_semantics::testing::fixture_registry;1213const DEFS: &str = "instrument Piano { model piano }\n";1415fn program(body: &str) -> Program {16    let src = format!("{DEFS}composition \"g\" {{\n{body}\n}}");17    let out = compile_with_registry("g.sonata", &src, &NoLoader, &CompileOptions::default(), &fixture_registry());18    assert!(!out.has_errors(), "{}", out.render_diagnostics());19    (*out.program.unwrap()).clone()20}2122fn graph(p: &Program, prune: bool) -> DspGraph {23    build_graph_with(p, 48_000, &fixture_registry(), GraphOptions { prune_silent: prune }).unwrap()24}2526fn kinds(g: &DspGraph) -> Vec<String> {27    g.order28        .iter()29        .map(|id| match &g.nodes[*id as usize].kind {30            NodeKind::Instrument { track } => format!("inst{track}"),31            NodeKind::AudioClips { track } => format!("clips{track}"),32            NodeKind::Effect { spec, .. } => format!("fx:{}", spec.kind),33            NodeKind::Fader { strip } => format!("fader:{strip:?}"),34            NodeKind::Send { to_bus, pre_fader, .. } => format!("send>{to_bus}{}", if *pre_fader { ":pre" } else { "" }),35            NodeKind::Sum { strip } => format!("sum:{strip:?}"),36            NodeKind::LatencyDelay { samples } => format!("delay{samples}"),37            NodeKind::Limiter { .. } => "limiter".into(),38            NodeKind::Output => "out".into(),39        })40        .collect()41}4243#[test]44fn a_single_track_is_source_inserts_fader_master_limiter_output() {45    let p = program("instrument a: Piano { effects { eq; reverb hall }\n play C4 }");46    let g = graph(&p, false);47    g.validate().unwrap();48    assert_eq!(kinds(&g), vec!["inst0", "fx:eq", "fx:reverb", "fader:Track(0)", "sum:Master", "fader:Master", "limiter", "out"]);49    // The fixture limiter looks ahead 5 ms = 240 samples at 48 kHz.50    assert_eq!(g.total_latency, 240);51    assert_eq!(build_graph_with(&p, 96_000, &fixture_registry(), GraphOptions::default()).unwrap().total_latency, 480);52    let no_limit = program("instrument a: Piano { play C4 }\nmaster { peak_limit off }");53    assert!(!kinds(&graph(&no_limit, false)).contains(&"limiter".to_string()));54    assert_eq!(graph(&no_limit, false).total_latency, 0);55}5657#[test]58fn sends_buses_and_latency_compensation() {59    let p = program(60        "bus hall { effects { reverb hall(mix: 100%) } }\n bus crush { effects { distortion; limiter }; output hall }\n bus unused { effects { reverb } }\n\61         instrument dry: Piano { send hall -6dB\n send hall -12dB pre\n play C4 }\n\62         instrument wet: Piano { output crush\n play E4 }",63    );64    let g = graph(&p, false);65    g.validate().unwrap();66    let k = kinds(&g);67    // The bus nobody feeds is not built.68    assert!(!k.contains(&"sum:Bus(2)".to_string()));69    assert_eq!(k.iter().filter(|x| x.starts_with("send>0")).count(), 2);70    assert!(k.contains(&"send>0:pre".to_string()));71    // `crush` adds 16 samples (distortion) + 240 (limiter) before reaching `hall`; the two72    // sends from `dry` arrive with no latency and are delayed by 256 to stay aligned.73    assert_eq!(k.iter().filter(|x| *x == "delay256").count(), 2 + 1, "two sends into hall, and the dry track into the master");74    let hall_sum = g.nodes.iter().find(|n| matches!(n.kind, NodeKind::Sum { strip: Strip::Bus(0) })).unwrap();75    assert_eq!(hall_sum.total_latency, 256);76    let master_sum = g.nodes.iter().find(|n| matches!(n.kind, NodeKind::Sum { strip: Strip::Master })).unwrap();77    assert_eq!(master_sum.total_latency, 256);78    assert_eq!(g.total_latency, 256 + 240);79    // Every input of every sum is aligned (also checked by validate()).80    for n in g.nodes.iter().filter(|n| matches!(n.kind, NodeKind::Sum { .. })) {81        let lat: Vec<u32> = g.inputs_of(n.id).map(|i| g.nodes[i as usize].total_latency).collect();82        assert!(lat.windows(2).all(|w| w[0] == w[1]), "{lat:?}");83    }84    // Same program, same graph.85    assert_eq!(graph(&p, false), g);86}8788#[test]89fn bus_loops_are_rejected() {90    let src = format!(91        "{DEFS}composition \"g\" {{\n bus a {{ output b }}\n bus b {{ send c }}\n bus c {{ send a -3dB }}\n instrument t: Piano {{ output a\n play C4 }}\n}}"92    );93    let out = compile_with_registry("g.sonata", &src, &NoLoader, &CompileOptions::default(), &fixture_registry());94    let errors: Vec<&Diagnostic> = out.errors().collect();95    assert_eq!(errors.len(), 1);96    assert_eq!(errors[0].code, "G5001");97    assert!(errors[0].message.contains("a → b → c → a"), "{}", errors[0].message);98    assert_eq!(errors[0].related.len(), 2);99    assert!(out.program.is_none() && out.graph.is_none());100}101102#[test]103fn pruning_removes_only_what_cannot_be_heard() {104    let p = program(105        "bus hall { effects { reverb } }\n instrument a: Piano { mute\n send hall\n play C4 }\n instrument b: Piano { play E4 }\n audio c { clip \"x.wav\" }",106    );107    let full = kinds(&graph(&p, false));108    assert!(full.contains(&"inst0".to_string()) && full.contains(&"sum:Bus(0)".to_string()) && full.contains(&"clips2".to_string()));109    let pruned = kinds(&graph(&p, true));110    assert!(!pruned.contains(&"inst0".to_string()), "a muted track is removed");111    assert!(!pruned.contains(&"sum:Bus(0)".to_string()), "a bus fed only by a muted track is removed");112    assert!(pruned.contains(&"inst1".to_string()) && pruned.contains(&"clips2".to_string()));113    let solo = program("instrument a: Piano { solo\n play C4 }\n instrument b: Piano { play E4 }");114    let k = kinds(&graph(&solo, true));115    assert!(k.contains(&"inst0".to_string()) && !k.contains(&"inst1".to_string()));116    assert!(kinds(&graph(&solo, false)).contains(&"inst1".to_string()));117}118119#[test]120fn the_session_reuses_modules_and_whole_results() {121    let lib = "pattern motif(root: Pitch) { play root\n play root + 7st }";122    let main = |n: u32| format!("import lib.m\ncomposition \"s\" {{ instrument a: GrandPiano {{ repeat {n} {{ motif(C4) }} }} }}");123    let loader = MapLoader::default().with("lib.m", lib);124    let mut c = Compiler::new();125    let options = CompileOptions::default();126    let first = c.compile("s.sonata", &main(2), &loader, &options);127    assert!(!first.has_errors(), "{}", first.render_diagnostics());128    assert!(!first.stats.cache_hit && first.stats.modules_reused == 0 && first.stats.modules == 5);129    assert!(first.stats.parse_us > 0.0 && first.stats.sema_us > 0.0 && first.stats.total_us >= first.stats.sema_us);130    assert_eq!((first.stats.events, first.stats.tracks), (4, 1));131    assert!(first.stats.estimated_memory_bytes > 0 && first.stats.nodes > 0);132    // Nothing changed: the whole result comes back, bit for bit.133    let again = c.compile("s.sonata", &main(2), &loader, &options);134    assert!(again.stats.cache_hit);135    assert_eq!(again.program, first.program);136    assert!(std::sync::Arc::ptr_eq(again.program.as_ref().unwrap(), first.program.as_ref().unwrap()));137    // The root changed: the four other modules are reused without parsing.138    let edited = c.compile("s.sonata", &main(3), &loader, &options);139    assert!(!edited.stats.cache_hit);140    assert_eq!((edited.stats.modules_reused, edited.stats.events), (4, 6));141    // An imported module changed: the result follows, the cache does not hide it.142    let loader2 = MapLoader::default().with("lib.m", "pattern motif(root: Pitch) { play root }");143    let relinked = c.compile("s.sonata", &main(3), &loader2, &options);144    assert!(!relinked.stats.cache_hit);145    assert_eq!(relinked.stats.events, 3);146    // Options are part of the key.147    let other = c.compile("s.sonata", &main(3), &loader2, &CompileOptions { sample_rate: Some(96_000), ..CompileOptions::default() });148    assert!(!other.stats.cache_hit);149    assert_eq!(other.graph.as_ref().unwrap().sample_rate, 96_000);150    // A cached and a fresh compilation agree.151    let fresh = compile("s.sonata", &main(3), &loader2, &options);152    assert_eq!(fresh.program, relinked.program);153    assert_eq!(fresh.graph, relinked.graph);154}155156#[test]157fn diagnostics_render_with_locations_and_json() {158    let src = "composition \"d\" {\n    instrument a: GrandPiano {\n        play D4 duration 1s\n        gain -8\n    }\n}\n";159    let out = compile("piece.sonata", src, &NoLoader, &CompileOptions::default());160    let text = out.render_diagnostics();161    assert!(text.contains("piece.sonata:3:26: error[T3003]"), "{text}");162    assert!(text.contains("        play D4 duration 1s\n  |                          ^^"), "{text}");163    assert!(text.contains("piece.sonata:4:14: error[T3006]") && text.contains("help: add the unit: -8dB"), "{text}");164    let json: serde_json::Value = serde_json::from_str(&out.diagnostics_json()).unwrap();165    assert_eq!(json[0]["code"], "T3003");166    assert_eq!(json[0]["location"]["line"], 3);167    assert_eq!(json[0]["location"]["file"], "piece.sonata");168    assert_eq!(json[1]["fix"]["replacement"], "dB");169    let loc = out.sources.locate(out.diagnostics[0].span);170    assert_eq!((loc.line, loc.column, loc.end_column), (3, 26, 28));171    assert_eq!(out.sources.snippet(out.diagnostics[0].span), Some("1s"));172    assert_eq!(out.program_json(), "null");173    assert!(out.ast_json().contains("\"item\": \"composition\""));174}175176#[test]177fn the_directory_loader_cannot_leave_its_root() {178    let dir = std::env::temp_dir().join(format!("sonata-loader-{}", std::process::id()));179    let _ = std::fs::remove_dir_all(&dir);180    std::fs::create_dir_all(dir.join("root/lib")).unwrap();181    std::fs::write(dir.join("root/lib/a.sonata"), "const a = 1").unwrap();182    std::fs::write(dir.join("secret.sonata"), "const secret = 1").unwrap();183    #[cfg(unix)]184    std::os::unix::fs::symlink(dir.join("secret.sonata"), dir.join("root/link.sonata")).unwrap();185    let loader = DirLoader::new(dir.join("root"));186    assert_eq!(loader.load("lib.a").as_deref(), Some("const a = 1"));187    assert_eq!(loader.load("lib.missing"), None);188    assert_eq!(loader.load("..secret"), None);189    assert_eq!(loader.load("lib/../../secret"), None);190    assert_eq!(loader.load("link"), None, "a symbolic link leaving the root is refused");191    assert_eq!(loader.load(""), None);192    let overlay = DirLoader::new(dir.join("root")).with_overlay("lib.a", "const a = 2");193    assert_eq!(overlay.load("lib.a").as_deref(), Some("const a = 2"));194    assert_eq!(DirLoader::overlays_only().load("lib.a"), None);195    let _ = std::fs::remove_dir_all(&dir);196}197
Files main
Menu

Theme