Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/examples/audition.rs3//! Description: Renders every engine and preset to WAV files under build/audition/ and prints4//! measured peak level, RMS and tuning error, so the instruments can be listened to and checked.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_dsp::core::{cents, estimate_f0, lin_to_db, midi_to_hz};10use sonata_instruments::{create_instrument, engine_registry, NoteOn};11use sonata_ir::{Articulation, InstrumentSpec, ParamValue, Params};12use std::io::Write;1314const SR: u32 = 48_000;1516fn write_wav(path: &std::path::Path, left: &[f32], right: &[f32]) -> std::io::Result<()> {17 let mut f = std::io::BufWriter::new(std::fs::File::create(path)?);18 let data_len = (left.len() * 4) as u32;19 f.write_all(b"RIFF")?;20 f.write_all(&(36 + data_len).to_le_bytes())?;21 f.write_all(b"WAVEfmt ")?;22 f.write_all(&16u32.to_le_bytes())?;23 f.write_all(&1u16.to_le_bytes())?;24 f.write_all(&2u16.to_le_bytes())?;25 f.write_all(&SR.to_le_bytes())?;26 f.write_all(&(SR * 4).to_le_bytes())?;27 f.write_all(&4u16.to_le_bytes())?;28 f.write_all(&16u16.to_le_bytes())?;29 f.write_all(b"data")?;30 f.write_all(&data_len.to_le_bytes())?;31 for (l, r) in left.iter().zip(right) {32 f.write_all(&((l.clamp(-1.0, 1.0) * 32767.0) as i16).to_le_bytes())?;33 f.write_all(&((r.clamp(-1.0, 1.0) * 32767.0) as i16).to_le_bytes())?;34 }35 Ok(())36}3738fn main() {39 let out_dir = std::path::PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| "build/audition".into()));40 std::fs::create_dir_all(&out_dir).expect("create output directory");41 println!("{:<18} {:<14} {:>8} {:>8} {:>10} phrase", "model", "preset", "peak dB", "rms dB", "f0 cents");42 for desc in engine_registry() {43 if desc.model == "patch" {44 continue;45 }46 let mut presets: Vec<Option<String>> = vec![None];47 presets.extend(desc.presets.iter().map(|p| Some(p.name.clone())));48 for preset in presets {49 let mut params = Params::new();50 if let Some(p) = &preset {51 params.insert("preset".into(), ParamValue::Text(p.clone()));52 }53 let spec = InstrumentSpec { name: "Audition".into(), model: desc.model.clone(), params, patch: None };54 let mut inst = create_instrument(&spec, 440.0, 1).expect("create");55 inst.prepare(SR as f32, 512, 16);56 // A short phrase inside the range: arpeggio then a chord, each note 0.45 s, velocity 0.8.57 let centre = ((desc.range.0 as u32 + desc.range.1 as u32) / 2).clamp(40, 72) as f32;58 let centre = if desc.family == "bass" { 40.0 } else { centre };59 let steps: [&[f32]; 6] = [&[0.0], &[4.0], &[7.0], &[12.0], &[7.0], &[0.0, 4.0, 7.0, 12.0]];60 let (mut l, mut r) = (Vec::new(), Vec::new());61 let mut id = 0u64;62 let block = 256;63 for (si, step) in steps.iter().enumerate() {64 let ids: Vec<u64> = step65 .iter()66 .map(|off| {67 id += 1;68 let pitch = centre + off;69 inst.note_on(&NoteOn { id, pitch, freq: midi_to_hz(pitch, 440.0), velocity: 0.8, articulation: Articulation::Normal });70 id71 })72 .collect();73 let hold = if si == 5 { 1.2 } else { 0.45 };74 let n_hold = (hold * 0.8 * SR as f32) as usize / block;75 let n_gap = (hold * 0.2 * SR as f32) as usize / block;76 for b in 0..n_hold + n_gap {77 if b == n_hold {78 ids.iter().for_each(|i| inst.note_off(*i));79 }80 let (mut bl, mut br) = (vec![0.0f32; block], vec![0.0f32; block]);81 inst.process(&mut bl, &mut br);82 l.extend(bl);83 r.extend(br);84 }85 }86 for _ in 0..(1.5 * SR as f32) as usize / block {87 let (mut bl, mut br) = (vec![0.0f32; block], vec![0.0f32; block]);88 inst.process(&mut bl, &mut br);89 l.extend(bl);90 r.extend(br);91 }92 let name = preset.clone().unwrap_or_else(|| "default".into());93 write_wav(&out_dir.join(format!("{}-{}.wav", desc.model, name)), &l, &r).expect("write wav");94 // Single note at velocity 1 for the level and tuning figures.95 let mut inst = create_instrument(&spec, 440.0, 1).expect("create");96 inst.prepare(SR as f32, 512, 8);97 let pitch = centre;98 let f = midi_to_hz(pitch, 440.0);99 inst.note_on(&NoteOn { id: 1, pitch, freq: f, velocity: 1.0, articulation: Articulation::Normal });100 let (mut sl, mut sr) = (vec![0.0f32; SR as usize], vec![0.0f32; SR as usize]);101 for (cl, cr) in sl.chunks_mut(512).zip(sr.chunks_mut(512)) {102 inst.process(cl, cr);103 }104 let peak = sl.iter().chain(sr.iter()).fold(0.0f32, |m, x| m.max(x.abs()));105 let rms = (sl.iter().map(|x| x * x).sum::<f32>() / sl.len() as f32).sqrt();106 let tune = if desc.pitched {107 estimate_f0(&sl[12_000..36_000], SR as f32, f * 0.94, f * 1.06).map(|e| format!("{:+.1}", cents(e, f))).unwrap_or_else(|| "n/a".into())108 } else {109 "-".into()110 };111 println!("{:<18} {:<14} {:>8.1} {:>8.1} {:>10} {:.1} s", desc.model, name, lin_to_db(peak), lin_to_db(rms), tune, l.len() as f32 / SR as f32);112 }113 }114 println!("wrote WAV files to {}", out_dir.display());115}116