Repository Public
1//! ORIX Sonata2//! File: crates/sonata-interop/tests/examples.rs3//! Description: Every example of the repository is transcribed to notation, MusicXML and MIDI;4//! measures must add up, the XML must be well formed (xmllint when present) and the MIDI must5//! parse back with the same number of notes.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use sonata_compiler::{compile, CompileOptions, DirLoader};11use sonata_interop::{build_score, parse_midi, program_to_midi, score_to_musicxml};12use sonata_ir::Rational;13use std::path::PathBuf;1415fn examples() -> Vec<PathBuf> {16 let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../Examples");17 let mut v: Vec<PathBuf> = std::fs::read_dir(&dir)18 .expect("Examples directory")19 .filter_map(|e| e.ok().map(|e| e.path()))20 .filter(|p| p.extension().is_some_and(|e| e == "sonata"))21 .collect();22 v.sort();23 assert!(v.len() >= 10, "expected the example set, found {}", v.len());24 v25}2627#[test]28fn every_example_transcribes_consistently() {29 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../Examples");30 let xmllint = std::path::Path::new("/usr/bin/xmllint").exists();31 let tmp = std::env::temp_dir().join(format!("sonata-interop-examples-{}", std::process::id()));32 std::fs::create_dir_all(&tmp).unwrap();33 let mut checked = 0;34 for path in examples() {35 let name = path.file_name().unwrap().to_string_lossy().to_string();36 let source = std::fs::read_to_string(&path).unwrap();37 let out = compile(&name, &source, &DirLoader::new(&root), &CompileOptions::default());38 assert!(!out.has_errors(), "{name} does not compile: {}", out.render_diagnostics());39 let Some(program) = out.program.as_deref() else { continue };40 let score = build_score(program);4142 // Every voice of every measure adds up to the measure (minus what was reported as quantised).43 let quantised = score.warnings.iter().any(|w| w.contains("quantised"));44 for part in &score.parts {45 assert_eq!(part.measures.len(), score.measures.len(), "{name}");46 for (mi, pm) in part.measures.iter().enumerate() {47 for voice in &pm.voices {48 let total = voice.iter().fold(Rational::ZERO, |a, e| a.checked_add(e.duration).unwrap());49 if quantised {50 assert!(total <= score.measures[mi].length, "{name} measure {}", mi + 1);51 } else {52 assert_eq!(total, score.measures[mi].length, "{name} part {} measure {}", part.name, mi + 1);53 }54 // Beams are well bracketed.55 let mut open = false;56 for e in voice {57 match e.beam {58 sonata_interop::score::Beam::Begin => {59 assert!(!open, "{name}: nested beam");60 open = true;61 }62 sonata_interop::score::Beam::Continue => assert!(open, "{name}: beam continues without beginning"),63 sonata_interop::score::Beam::End => {64 assert!(open, "{name}: beam ends without beginning");65 open = false;66 }67 sonata_interop::score::Beam::None => assert!(!open, "{name}: unbeamed note inside a beam"),68 }69 }70 assert!(!open, "{name}: beam left open at the bar line");71 }72 }73 }7475 let xml = score_to_musicxml(&score);76 assert_eq!(xml.matches("<tie type=\"start\"/>").count(), xml.matches("<tie type=\"stop\"/>").count(), "{name}: unbalanced ties");77 if xmllint {78 let file = tmp.join(format!("{name}.musicxml"));79 std::fs::write(&file, &xml).unwrap();80 // --noout: well-formedness only (the DTD is not fetched; no network access).81 let status = std::process::Command::new("/usr/bin/xmllint").arg("--noout").arg("--nonet").arg(&file).output().unwrap();82 assert!(status.status.success(), "{name}: xmllint: {}", String::from_utf8_lossy(&status.stderr));83 }8485 let (midi, _) = program_to_midi(program);86 let parsed = parse_midi(&midi).unwrap_or_else(|e| panic!("{name}: exported MIDI does not parse: {e}"));87 let exported: usize = parsed.tracks.iter().map(|t| t.notes.len()).sum();88 let in_range: usize = program89 .tracks90 .iter()91 .flat_map(|t| t.notes.iter().map(move |n| (t, n)))92 .filter(|(t, n)| {93 let drum = t.instrument.as_ref().is_some_and(|i| matches!(i.model.as_str(), "kick" | "snare" | "hihat"));94 drum || (0.0..=127.0).contains(&n.pitch.round())95 })96 .count();97 // Identical simultaneous notes on one key collapse in MIDI; never more notes than the program has.98 assert!(exported <= in_range && exported * 10 >= in_range * 9, "{name}: {exported} MIDI notes for {in_range} notes");99 checked += 1;100 }101 let _ = std::fs::remove_dir_all(&tmp);102 assert!(checked >= 10, "only {checked} examples produced a program");103}104