From 12db39ca963d2a333bd1891b0dbba65218800fd8 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH] Extract score writer changes from SoundCraft 0751dd31 --- crates/score/src/lib.rs | 344 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 344 insertions(+) create mode 100644 crates/score/src/lib.rs diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs new file mode 100644 index 000000000..30375b652 --- /dev/null +++ b/crates/score/src/lib.rs @@ -0,0 +1,344 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! MusicXML and SVG score writing over application-independent notation data. + +use std::fmt::Write as _; + +#[derive(Debug, Clone, PartialEq)] +pub struct ScoreSetup { + pub title: String, + pub composer: String, + pub bars_per_system: u32, + pub show_track_names: bool, +} + +/// One measure: its meter and its items (notes, chords or rests), in sixteenths. +#[derive(Debug, Clone, PartialEq)] +pub struct Measure { + pub numerator: u32, + pub denominator: u32, + pub items: Vec, +} + +/// A notehead group (chord) or a rest (no pitches). +#[derive(Debug, Clone, PartialEq)] +pub struct Item { + pub pitches: Vec, + /// Duration in sixteenths; always one of the supported duration values. + pub units: u32, + pub tie_start: bool, + pub tie_stop: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Part { + pub name: String, + /// True when the part reads best in bass clef. + pub bass: bool, + pub measures: Vec, +} + +fn spell(pitch: u8) -> (char, i32, i32) { + const STEPS: [(char, i32); 12] = + [('C', 0), ('C', 1), ('D', 0), ('D', 1), ('E', 0), ('F', 0), ('F', 1), ('G', 0), ('G', 1), ('A', 0), ('A', 1), ('B', 0)]; + let (step, alter) = STEPS[usize::from(pitch % 12)]; + (step, alter, i32::from(pitch / 12) - 1) +} + +fn xml_escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +fn note_type(units: u32) -> (&'static str, bool) { + match units { + 16 => ("whole", false), + 12 => ("half", true), + 8 => ("half", false), + 6 => ("quarter", true), + 4 => ("quarter", false), + 3 => ("eighth", true), + 2 => ("eighth", false), + _ => ("16th", false), + } +} + +/// MusicXML 4.0 (partwise) for `parts`. +pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> String { + let mut x = String::new(); + x.push_str("\n"); + x.push_str("\n"); + x.push_str("\n"); + let _ = writeln!(x, " {}", xml_escape(&setup.title)); + x.push_str(" \n"); + if !setup.composer.is_empty() { + let _ = writeln!(x, " {}", xml_escape(&setup.composer)); + } + x.push_str(" SoundCraft\n \n \n"); + for (i, p) in parts.iter().enumerate() { + let _ = writeln!(x, " {}", i + 1, xml_escape(&p.name)); + } + x.push_str(" \n"); + for (i, p) in parts.iter().enumerate() { + let _ = writeln!(x, " ", i + 1); + let mut meter = (0, 0); + for (mi, m) in p.measures.iter().enumerate() { + let _ = writeln!(x, " ", mi + 1); + if mi == 0 || meter != (m.numerator, m.denominator) { + x.push_str(" "); + if mi == 0 { + x.push_str("40"); + } + let _ = write!(x, "", m.numerator, m.denominator); + if mi == 0 { + x.push_str(if p.bass { "F4" } else { "G2" }); + } + x.push_str("\n"); + meter = (m.numerator, m.denominator); + } + for it in &m.items { + let (ty, dot) = note_type(it.units); + if it.pitches.is_empty() { + let _ = writeln!( + x, + " {}1{ty}{}", + it.units, + if dot { "" } else { "" } + ); + continue; + } + for (k, pitch) in it.pitches.iter().enumerate() { + let (step, alter, octave) = spell(*pitch); + x.push_str(" "); + if k > 0 { + x.push_str(""); + } + let _ = write!(x, "{step}"); + if alter != 0 { + let _ = write!(x, "{alter}"); + } + let _ = write!(x, "{octave}{}", it.units); + if it.tie_stop { + x.push_str(""); + } + if it.tie_start { + x.push_str(""); + } + let _ = write!(x, "1{ty}"); + if dot { + x.push_str(""); + } + if alter != 0 { + x.push_str("sharp"); + } + if it.tie_stop || it.tie_start { + x.push_str(""); + if it.tie_stop { + x.push_str(""); + } + if it.tie_start { + x.push_str(""); + } + x.push_str(""); + } + x.push_str("\n"); + } + } + x.push_str(" \n"); + } + x.push_str(" \n"); + } + x.push_str("\n"); + x +} + +/// Staff position of `pitch` in half-spaces above the bottom line (treble E4 / bass G2). +fn staff_step(pitch: u8, bass: bool) -> i32 { + let (step, _, octave) = spell(pitch); + let idx = "CDEFGAB".find(step).map_or(0, |i| i as i32); + let diatonic = octave * 7 + idx; + diatonic - if bass { 2 * 7 + 4 } else { 4 * 7 + 2 } +} + +/// An engraved score as a printable SVG page (A4 portrait width, as tall as needed). +pub fn svg(parts: &[Part], setup: &ScoreSetup) -> String { + const W: f64 = 794.0; + const MARGIN: f64 = 48.0; + const SP: f64 = 7.0; // staff space + const STAFF_GAP: f64 = 70.0; + const SYSTEM_GAP: f64 = 40.0; + let n_measures = parts.iter().map(|p| p.measures.len()).max().unwrap_or(0); + let per = setup.bars_per_system.max(1) as usize; + let systems = n_measures.div_ceil(per).max(1); + let label_w = if setup.show_track_names { 70.0 } else { 0.0 }; + let staff_x0 = MARGIN + label_w + 34.0; + let staff_x1 = W - MARGIN; + let sys_h = parts.len().max(1) as f64 * STAFF_GAP + SYSTEM_GAP; + let top = 110.0; + let h = top + systems as f64 * sys_h + MARGIN; + let mut o = String::new(); + let _ = + writeln!(o, ""); + let _ = writeln!(o, ""); + let _ = writeln!(o, "{}", W / 2.0, xml_escape(&setup.title)); + if !setup.composer.is_empty() { + let _ = writeln!(o, "{}", W - MARGIN, xml_escape(&setup.composer)); + } + let bar_w = (staff_x1 - staff_x0) / per as f64; + for sys in 0..systems { + let y_sys = top + sys as f64 * sys_h; + for (pi, p) in parts.iter().enumerate() { + let y0 = y_sys + pi as f64 * STAFF_GAP; // top line + let bottom = y0 + 4.0 * SP; + if setup.show_track_names && sys == 0 { + let _ = writeln!(o, "{}", y0 + 2.0 * SP + 4.0, xml_escape(&p.name)); + } + for l in 0..5 { + let y = y0 + f64::from(l) * SP; + let _ = writeln!( + o, + "", + staff_x0 - 30.0 + ); + } + let clef = if p.bass { "𝄢" } else { "𝄞" }; + let _ = writeln!( + o, + "{clef}", + staff_x0 - 29.0, + bottom + if p.bass { -SP } else { SP * 0.6 }, + if p.bass { 26 } else { 36 } + ); + for k in 0..per { + let mi = sys * per + k; + let x0 = staff_x0 + k as f64 * bar_w; + let _ = writeln!( + o, + "", + x0 + bar_w, + x0 + bar_w + ); + let Some(m) = p.measures.get(mi) else { continue }; + if pi == 0 { + let _ = writeln!(o, "{}", x0 + 2.0, y0 - 8.0, mi + 1); + } + let total: u32 = m.items.iter().map(|i| i.units).sum::().max(1); + let mut acc = 0u32; + for it in &m.items { + let x = x0 + 10.0 + (bar_w - 16.0) * f64::from(acc) / f64::from(total); + acc += it.units; + let (_, dot) = note_type(it.units); + if it.pitches.is_empty() { + rest(&mut o, x, y0, SP, it.units); + if dot { + let _ = writeln!(o, "", x + 7.0, y0 + 1.5 * SP); + } + continue; + } + let steps: Vec = it.pitches.iter().map(|p2| staff_step(*p2, p.bass)).collect(); + let filled = it.units < 8; + for (pitch, st) in it.pitches.iter().zip(&steps) { + let y = bottom - f64::from(*st) * SP / 2.0; + // Ledger lines. + let mut l = if *st < 0 { -2 } else { 10 }; + while (*st < 0 && l >= *st) || (*st > 8 && l <= *st) { + let ly = bottom - f64::from(l) * SP / 2.0; + let _ = writeln!( + o, + "", + x - 7.0, + x + 7.0 + ); + l += if *st < 0 { -2 } else { 2 }; + } + let fill = if filled { "black" } else { "white" }; + let _ = writeln!( + o, + "" + ); + if spell(*pitch).1 != 0 { + let _ = writeln!(o, "♯", x - 14.0, y + 4.0); + } + if dot { + let _ = writeln!(o, "", x + 8.0, y - 1.5); + } + } + if it.units < 16 { + let (lo, hi) = (steps.iter().copied().min().unwrap_or(4), steps.iter().copied().max().unwrap_or(4)); + let up = (lo + hi) < 8; + let (sx, y_from, y_to) = if up { + (x + 4.3, bottom - f64::from(lo) * SP / 2.0, bottom - f64::from(hi) * SP / 2.0 - 3.5 * SP) + } else { + (x - 4.3, bottom - f64::from(hi) * SP / 2.0, bottom - f64::from(lo) * SP / 2.0 + 3.5 * SP) + }; + let _ = writeln!( + o, + "" + ); + let flags = match it.units { + 1 => 2, + 2 | 3 => 1, + _ => 0, + }; + for f in 0..flags { + let fy = y_to + f64::from(f) * if up { 5.0 } else { -5.0 }; + let dy = if up { 9.0 } else { -9.0 }; + let _ = writeln!( + o, + "", + dy * 0.5 + ); + } + } + if it.tie_start { + let y = bottom - f64::from(steps[0]) * SP / 2.0 + 6.0; + let _ = writeln!(o, "", x + 3.0); + } + } + } + } + // System bracket. + let y_last = y_sys + (parts.len().max(1) - 1) as f64 * STAFF_GAP + 4.0 * SP; + let _ = writeln!( + o, + "", + staff_x0 - 30.0, + staff_x0 - 30.0 + ); + } + o.push_str("\n"); + o +} + +fn rest(o: &mut String, x: f64, y0: f64, sp: f64, units: u32) { + let mid = y0 + 2.0 * sp; + match units { + 16 => { + let _ = writeln!(o, "", x - 4.5, y0 + sp, sp / 2.0); + } + 8 | 12 => { + let _ = writeln!(o, "", x - 4.5, mid - sp / 2.0, sp / 2.0); + } + 4 | 6 => { + let _ = writeln!( + o, + "", + x - 2.0, + mid - 9.0 + ); + } + _ => { + let _ = writeln!(o, "", x - 2.0, mid - 3.0); + let _ = writeln!( + o, + "", + x + 2.5, + mid - 4.0, + x - 1.0, + mid + 7.0 + ); + if units == 1 { + let _ = writeln!(o, "", x - 3.5, mid + 2.0); + } + } + } +} +