From 12db39ca963d2a333bd1891b0dbba65218800fd8 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 01/12] 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); + } + } + } +} + From 68abf77e2ddaea226a742efcb363630fa07faa3c Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 02/12] Extract score writer changes from SoundCraft 7509b64c --- crates/score/src/lib.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 30375b652..3aee96472 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -45,7 +45,13 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) + s.chars() + .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) + .collect::() + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) } fn note_type(units: u32) -> (&'static str, bool) { From 9dfaaf27af936868710d44042ede6705cb9e616f Mon Sep 17 00:00:00 2001 From: Samuel Bacaro Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 03/12] Extract score writer changes from SoundCraft ccd3fe7c --- crates/score/src/lib.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 3aee96472..d51ab8333 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -3,6 +3,14 @@ use std::fmt::Write as _; +const MAX_OUTPUT_BYTES: usize = 256 * 1024 * 1024; // 256 MiB +fn over_budget(buf: &str) -> Result<(), String> { + if buf.len() > MAX_OUTPUT_BYTES { + return Err(format!("score too large: over {} MiB", MAX_OUTPUT_BYTES / (1024 * 1024))); + } + Ok(()) +} + #[derive(Debug, Clone, PartialEq)] pub struct ScoreSetup { pub title: String, @@ -45,13 +53,7 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.chars() - .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) - .collect::() - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) } fn note_type(units: u32) -> (&'static str, bool) { @@ -68,7 +70,7 @@ fn note_type(units: u32) -> (&'static str, bool) { } /// MusicXML 4.0 (partwise) for `parts`. -pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> String { +pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { let mut x = String::new(); x.push_str("\n"); x.push_str("\n"); @@ -149,11 +151,12 @@ pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> String { } } x.push_str(" \n"); + over_budget(&x)?; } x.push_str(" \n"); } x.push_str("\n"); - x + Ok(x) } /// Staff position of `pitch` in half-spaces above the bottom line (treble E4 / bass G2). @@ -165,7 +168,7 @@ fn staff_step(pitch: u8, bass: bool) -> i32 { } /// An engraved score as a printable SVG page (A4 portrait width, as tall as needed). -pub fn svg(parts: &[Part], setup: &ScoreSetup) -> String { +pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { const W: f64 = 794.0; const MARGIN: f64 = 48.0; const SP: f64 = 7.0; // staff space @@ -299,6 +302,7 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> String { let _ = writeln!(o, "", x + 3.0); } } + over_budget(&o)?; } } // System bracket. @@ -311,7 +315,7 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> String { ); } o.push_str("\n"); - o + Ok(o) } fn rest(o: &mut String, x: f64, y0: f64, sp: f64, units: u32) { From 8c6e050f324f8e50bddf556d12fcd48e3476d505 Mon Sep 17 00:00:00 2001 From: Samuel Bacaro Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 04/12] Extract score writer changes from SoundCraft fa77e03e --- crates/score/src/lib.rs | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index d51ab8333..59a28de68 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -4,9 +4,9 @@ use std::fmt::Write as _; const MAX_OUTPUT_BYTES: usize = 256 * 1024 * 1024; // 256 MiB -fn over_budget(buf: &str) -> Result<(), String> { - if buf.len() > MAX_OUTPUT_BYTES { - return Err(format!("score too large: over {} MiB", MAX_OUTPUT_BYTES / (1024 * 1024))); +fn over_budget(buf: &str, budget: usize) -> Result<(), String> { + if buf.len() > budget { + return Err(format!("score too large: over {} bytes", budget)); } Ok(()) } @@ -71,10 +71,19 @@ fn note_type(units: u32) -> (&'static str, bool) { /// MusicXML 4.0 (partwise) for `parts`. pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { + musicxml_budgeted(parts, setup, MAX_OUTPUT_BYTES) +} + +/// [`musicxml`] with an explicit byte budget (kept separate so tests can pass a tiny budget +/// instead of building a 256 MiB score). +fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { let mut x = String::new(); x.push_str("\n"); x.push_str("\n"); x.push_str("\n"); + // The header (and an oversized title/composer, escaped) can itself exceed the budget even with + // no measures, so check before the per-measure loop too. + over_budget(&x, budget)?; let _ = writeln!(x, " {}", xml_escape(&setup.title)); x.push_str(" \n"); if !setup.composer.is_empty() { @@ -85,6 +94,7 @@ pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { let _ = writeln!(x, " {}", i + 1, xml_escape(&p.name)); } x.push_str(" \n"); + over_budget(&x, budget)?; for (i, p) in parts.iter().enumerate() { let _ = writeln!(x, " ", i + 1); let mut meter = (0, 0); @@ -151,11 +161,12 @@ pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { } } x.push_str(" \n"); - over_budget(&x)?; + over_budget(&x, budget)?; } x.push_str(" \n"); } x.push_str("\n"); + over_budget(&x, budget)?; Ok(x) } @@ -169,6 +180,12 @@ fn staff_step(pitch: u8, bass: bool) -> i32 { /// An engraved score as a printable SVG page (A4 portrait width, as tall as needed). pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { + svg_budgeted(parts, setup, MAX_OUTPUT_BYTES) +} + +/// [`svg`] with an explicit byte budget (kept separate so tests can pass a tiny budget instead of +/// building a 256 MiB score). +fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { const W: f64 = 794.0; const MARGIN: f64 = 48.0; const SP: f64 = 7.0; // staff space @@ -190,7 +207,9 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { let _ = writeln!(o, "{}", W / 2.0, xml_escape(&setup.title)); if !setup.composer.is_empty() { let _ = writeln!(o, "{}", W - MARGIN, xml_escape(&setup.composer)); + over_budget(&o, budget)?; } + over_budget(&o, budget)?; let bar_w = (staff_x1 - staff_x0) / per as f64; for sys in 0..systems { let y_sys = top + sys as f64 * sys_h; @@ -302,8 +321,13 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { let _ = writeln!(o, "", x + 3.0); } } - over_budget(&o)?; + // Check each measure, so a run of rest-only or missing measures that only draws + // bar lines cannot grow the output past the budget untouched. + over_budget(&o, budget)?; } + // The staff markup (lines, clef, track names) itself grows with the part count even + // without any items, so check once per staff too. + over_budget(&o, budget)?; } // System bracket. let y_last = y_sys + (parts.len().max(1) - 1) as f64 * STAFF_GAP + 4.0 * SP; @@ -313,8 +337,10 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { staff_x0 - 30.0, staff_x0 - 30.0 ); + over_budget(&o, budget)?; } o.push_str("\n"); + over_budget(&o, budget)?; Ok(o) } From 1002aca27092b6fe41e3af5b3212080a354555cb Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 05/12] Extract score writer changes from SoundCraft 5075da2f --- crates/score/src/lib.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 59a28de68..023f35554 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -53,7 +53,13 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) + s.chars() + .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) + .collect::() + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) } fn note_type(units: u32) -> (&'static str, bool) { From bfef2e5ce28dbc1e57e897058851024d161bd09b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 06/12] Extract score writer changes from SoundCraft fa34e0c1 --- crates/score/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 023f35554..c64ac0054 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -198,7 +198,9 @@ fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 07/12] Extract score writer changes from SoundCraft 4bdda5ff --- crates/score/src/lib.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index c64ac0054..d8e757b21 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -53,13 +53,10 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.chars() - .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) - .collect::() - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) + // Keep the score export's existing literal whitespace and quote spelling. The + // shared attribute writer owns XML legality/escaping; only its generated + // whitespace references are restored (input ampersands were escaped first). + craft_xml::esc_attr(s).replace(" ", "\t").replace(" ", "\n").replace(" ", "\r") } fn note_type(units: u32) -> (&'static str, bool) { From 3d160af4d90797f39196c22e81288d9c403030d2 Mon Sep 17 00:00:00 2001 From: Vikram Bhaskaran Date: Mon, 16 Nov 2026 19:20:52 -0500 Subject: [PATCH 08/12] Extract score writer changes from SoundCraft 21cb618d --- crates/score/src/lib.rs | 40 ++++++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index d8e757b21..cab0ad9bd 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -33,8 +33,10 @@ 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, + /// Pitches continuing into the next item. + pub tie_start: Vec, + /// Pitches continuing from the previous item. + pub tie_stop: Vec, } #[derive(Debug, Clone, PartialEq)] @@ -53,10 +55,13 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - // Keep the score export's existing literal whitespace and quote spelling. The - // shared attribute writer owns XML legality/escaping; only its generated - // whitespace references are restored (input ampersands were escaped first). - craft_xml::esc_attr(s).replace(" ", "\t").replace(" ", "\n").replace(" ", "\r") + s.chars() + .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) + .collect::() + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) } fn note_type(units: u32) -> (&'static str, bool) { @@ -137,10 +142,10 @@ fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Resul let _ = write!(x, "{alter}"); } let _ = write!(x, "{octave}{}", it.units); - if it.tie_stop { + if it.tie_stop.contains(pitch) { x.push_str(""); } - if it.tie_start { + if it.tie_start.contains(pitch) { x.push_str(""); } let _ = write!(x, "1{ty}"); @@ -150,12 +155,12 @@ fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Resul if alter != 0 { x.push_str("sharp"); } - if it.tie_stop || it.tie_start { + if it.tie_stop.contains(pitch) || it.tie_start.contains(pitch) { x.push_str(""); - if it.tie_stop { + if it.tie_stop.contains(pitch) { x.push_str(""); } - if it.tie_start { + if it.tie_start.contains(pitch) { x.push_str(""); } x.push_str(""); @@ -321,9 +326,16 @@ fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result", x + 3.0); + for pitch in &it.tie_start { + let above = it.pitches.first().is_some_and(|low| pitch > low); + let direction = if above { -1.0 } else { 1.0 }; + let y = bottom - f64::from(staff_step(*pitch, p.bass)) * SP / 2.0 + direction * 6.0; + let _ = writeln!( + o, + "", + x + 3.0, + direction * 5.0 + ); } } // Check each measure, so a run of rest-only or missing measures that only draws From 9b570237ef8682c3848bacf374ff1db06dc95241 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 19:23:04 -0500 Subject: [PATCH 09/12] feat(score): register reusable writers with bounded public notation input --- ATTRIBUTION.md | 4 +++ Cargo.lock | 7 +++++ Cargo.toml | 1 + crates/score/Cargo.toml | 14 +++++++++ crates/score/src/lib.rs | 65 ++++++++++++++++++++++++++++++++--------- 5 files changed, 77 insertions(+), 14 deletions(-) create mode 100644 crates/score/Cargo.toml diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ab167207c..70a929de8 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -103,3 +103,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso `crates/tga/src/metadata_tests.rs` and metadata-boundary helpers in `crates/tga/src/lib.rs` are adapted from nuclearspike's FilmCraft #1932 at `e7842f76f887005c460c64a8ab51d59d086e6f27` (MIT OR Apache-2.0). Synthetic fixtures are original contributor test data; primary Git author retained. The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper are ported from Craft Anything `8f3b775157d331dd31cfa4da911e26d8856b8c77` (same MIT OR Apache-2.0 source licenses). Brandon Thomas is the primary import author; retained hardening credits include Afloat, BFlat, Rahul, RRFZ and NetterSilver. The finite-real fix preserves gmrmad1 as author from Craft Anything #1905 (`d85e104f`); quoted-attribute/line-ending regressions preserve RRFZ. Bounds/adaptation and bounded entity scanning are subsequent Dylan M. Taylor changes. App-specific JSON projections and keyed-archive interpretation remain outside this crate. + +## Score serializers + +`crates/score` extracts SoundCraft MusicXML and SVG score writing from `crates/engine/src/score.rs` at main `648ed9db9a0e98cc55643babffac381521a556c8`, with per-pitch ties adapted from [SoundCraft #182](https://github.com/storytold/soundcraft/pull/182) at `21cb618d93ec0e8d4771ac534994de8d5996ff10`. Source is MIT OR Apache-2.0. Import commits preserve Brandon Thomas, NetterSilver, Samuel Bacaro and Vikram Bhaskaran as primary authors of their respective changes. The consumer retains session mapping and layout. Shared API wiring, validation and focused tests are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index ef82f1afa..41290ac89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2791,6 +2791,13 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-score" +version = "0.1.0" +dependencies = [ + "craft-xml", +] + [[package]] name = "craft-scraft-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c8ae36287..8c3c97517 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-score = { path = "crates/score" } craft-shx = { path = "crates/shx" } craft-http-url = { path = "crates/http-url" } craft-usd = { path = "crates/usd" } diff --git a/crates/score/Cargo.toml b/crates/score/Cargo.toml new file mode 100644 index 000000000..f283282c4 --- /dev/null +++ b/crates/score/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-score" +description = "Application-independent MusicXML and printable SVG score writers" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[dependencies] +craft-xml.workspace = true + +[lints] +workspace = true diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index cab0ad9bd..130f9e857 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -13,6 +13,8 @@ fn over_budget(buf: &str, budget: usize) -> Result<(), String> { #[derive(Debug, Clone, PartialEq)] pub struct ScoreSetup { + /// Software name recorded in the MusicXML encoding metadata. + pub software: String, pub title: String, pub composer: String, pub bars_per_system: u32, @@ -55,13 +57,10 @@ fn spell(pitch: u8) -> (char, i32, i32) { } fn xml_escape(s: &str) -> String { - s.chars() - .filter(|c| matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')) - .collect::() - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) + // Keep the score export's existing literal whitespace and quote spelling. The + // shared attribute writer owns XML legality/escaping; only its generated + // whitespace references are restored (input ampersands were escaped first). + craft_xml::esc_attr(s).replace(" ", "\t").replace(" ", "\n").replace(" ", "\r") } fn note_type(units: u32) -> (&'static str, bool) { @@ -82,9 +81,10 @@ pub fn musicxml(parts: &[Part], setup: &ScoreSetup) -> Result { musicxml_budgeted(parts, setup, MAX_OUTPUT_BYTES) } -/// [`musicxml`] with an explicit byte budget (kept separate so tests can pass a tiny budget -/// instead of building a 256 MiB score). -fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { +/// MusicXML with an explicit byte budget, capped at 256 MiB. +pub fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { + validate(parts, setup)?; + let budget = budget.min(MAX_OUTPUT_BYTES); let mut x = String::new(); x.push_str("\n"); x.push_str("\n"); @@ -97,7 +97,8 @@ fn musicxml_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Resul if !setup.composer.is_empty() { let _ = writeln!(x, " {}", xml_escape(&setup.composer)); } - x.push_str(" SoundCraft\n \n \n"); + let _ = writeln!(x, " {}", xml_escape(&setup.software)); + x.push_str(" \n \n"); for (i, p) in parts.iter().enumerate() { let _ = writeln!(x, " {}", i + 1, xml_escape(&p.name)); } @@ -191,9 +192,10 @@ pub fn svg(parts: &[Part], setup: &ScoreSetup) -> Result { svg_budgeted(parts, setup, MAX_OUTPUT_BYTES) } -/// [`svg`] with an explicit byte budget (kept separate so tests can pass a tiny budget instead of -/// building a 256 MiB score). -fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { +/// SVG with an explicit byte budget, capped at 256 MiB. +pub fn svg_budgeted(parts: &[Part], setup: &ScoreSetup, budget: usize) -> Result { + validate(parts, setup)?; + let budget = budget.min(MAX_OUTPUT_BYTES); const W: f64 = 794.0; const MARGIN: f64 = 48.0; const SP: f64 = 7.0; // staff space @@ -395,3 +397,38 @@ fn rest(o: &mut String, x: f64, y0: f64, sp: f64, units: u32) { } } +// Public notation data can come from callers other than SoundCraft's bounded layout. +// Validate before writing/escaping so malicious dimensions cannot overflow sums or create +// an unbounded temporary string before the output-budget checks run. +fn validate(parts: &[Part], setup: &ScoreSetup) -> Result<(), String> { + let invalid = || "score exceeds supported notation limits".to_string(); + if parts.len() > 4096 { + return Err(invalid()); + } + let mut text = setup.title.len().checked_add(setup.composer.len()).and_then(|n| n.checked_add(setup.software.len())).ok_or_else(invalid)?; + for part in parts { + text = text.checked_add(part.name.len()).ok_or_else(invalid)?; + if text > 16 * 1024 * 1024 || part.measures.len() > 2000 { + return Err(invalid()); + } + for measure in &part.measures { + if measure.items.len() > 128 { + return Err(invalid()); + } + for item in &measure.items { + if ![1, 2, 3, 4, 6, 8, 12, 16].contains(&item.units) + || item.pitches.len() > 16 + || item.tie_start.len() > 16 + || item.tie_stop.len() > 16 + || item.pitches.iter().chain(&item.tie_start).chain(&item.tie_stop).any(|p| *p > 127) + { + return Err(invalid()); + } + } + } + } + if text > 16 * 1024 * 1024 { + return Err(invalid()); + } + Ok(()) +} From 0006665d60e6a4ee6aeb231de33cd41d38931ece Mon Sep 17 00:00:00 2001 From: Vikram Bhaskaran Date: Mon, 16 Nov 2026 19:23:23 -0500 Subject: [PATCH 10/12] test(score): retain per-pitch MusicXML and SVG tie regression from SoundCraft 182 --- crates/score/src/lib.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 130f9e857..fccb5c32f 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -432,3 +432,37 @@ fn validate(parts: &[Part], setup: &ScoreSetup) -> Result<(), String> { } Ok(()) } +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + fn setup() -> ScoreSetup { + ScoreSetup { software: "SoundCraft".into(), title: "A<&\u{1}".into(), composer: "B".into(), bars_per_system: 4, show_track_names: true } + } + fn parts() -> Vec { + vec![Part { + name: "Keys".into(), + bass: false, + measures: vec![Measure { + numerator: 4, + denominator: 4, + items: vec![ + Item { pitches: vec![60, 64], units: 4, tie_start: vec![64], tie_stop: vec![] }, + Item { pitches: vec![64], units: 12, tie_start: vec![], tie_stop: vec![64] }, + ], + }], + }] + } + #[test] + fn per_pitch_ties_and_escaping_survive_serialization() { + let parts = parts(); + let xml = musicxml(&parts, &setup()).unwrap(); + assert!(xml.contains("A<&")); + let notes: Vec<_> = xml.split("").skip(1).map(|n| n.split("").next().unwrap()).collect(); + assert!(notes[0].contains("4")); + assert!(!notes[0].contains("") && notes[1].contains("")); + assert!(notes[2].contains("12") && notes[2].contains("")); + assert_eq!(svg(&parts, &setup()).unwrap().matches("stroke-width=\"0.9\"").count(), 1); + } +} From d5d65b128dfc74f77ffd23ea08fd3ea428a7d0cd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 19:23:23 -0500 Subject: [PATCH 11/12] test(score): exercise byte budgets and hostile notation input --- crates/score/src/lib.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index fccb5c32f..7ec2141c5 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -465,4 +465,13 @@ mod tests { assert!(notes[2].contains("12") && notes[2].contains("")); assert_eq!(svg(&parts, &setup()).unwrap().matches("stroke-width=\"0.9\"").count(), 1); } + #[test] + fn byte_budgets_and_hostile_durations_fail() { + assert!(musicxml_budgeted(&parts(), &setup(), 32).is_err()); + assert!(svg_budgeted(&parts(), &setup(), 32).is_err()); + let mut parts = parts(); + parts[0].measures[0].items[0].units = u32::MAX; + assert!(musicxml(&parts, &setup()).is_err()); + assert!(svg(&parts, &setup()).is_err()); + } } From 9595e0ca9bff15b04c0096458c63d96d8b090b63 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 16 Nov 2026 19:25:08 -0500 Subject: [PATCH 12/12] test(score): retain original pitch spelling and staff placement regression --- crates/score/src/lib.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/score/src/lib.rs b/crates/score/src/lib.rs index 7ec2141c5..7ca06261e 100644 --- a/crates/score/src/lib.rs +++ b/crates/score/src/lib.rs @@ -474,4 +474,12 @@ mod tests { assert!(musicxml(&parts, &setup()).is_err()); assert!(svg(&parts, &setup()).is_err()); } + #[test] + fn spelling_and_staff_steps() { + assert_eq!(spell(60), ('C', 0, 4)); + assert_eq!(spell(61), ('C', 1, 4)); + assert_eq!(staff_step(64, false), 0); // E4: bottom treble line + assert_eq!(staff_step(77, false), 8); // F5: top treble line + assert_eq!(staff_step(43, true), 0); // G2: bottom bass line + } }