SPB Git

Repository Public

musicxml.rs 16.3 KB 380 lines rust

1//! ORIX Sonata2//! File: crates/sonata-interop/src/musicxml.rs3//! Description: MusicXML 4.0 (score-partwise) writer over the notation model.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use crate::score::{build_score, Clef, Element, Score};9use sonata_ir::{Articulation, Program, Rational};10use std::fmt::Write;1112fn esc(s: &str) -> String {13    let mut o = String::with_capacity(s.len());14    for c in s.chars() {15        match c {16            '&' => o.push_str("&amp;"),17            '<' => o.push_str("&lt;"),18            '>' => o.push_str("&gt;"),19            '"' => o.push_str("&quot;"),20            '\'' => o.push_str("&apos;"),21            c if (c as u32) < 0x20 && c != '\n' && c != '\t' => {}22            c => o.push(c),23        }24    }25    o26}2728fn gcd(a: i64, b: i64) -> i64 {29    if b == 0 {30        a.abs()31    } else {32        gcd(b, a % b)33    }34}3536/// Divisions per quarter note such that every element length is an integer.37fn divisions(score: &Score) -> i64 {38    let mut div = 1i64;39    let mut feed = |x: Rational| {40        // length in quarters = x * 441        let q = x.checked_mul(Rational::from_int(4)).unwrap_or(x);42        let d = q.den();43        let l = div / gcd(div, d) * d;44        if l <= 1_000_000 {45            div = l;46        }47    };48    for m in &score.measures {49        feed(m.length);50    }51    for p in &score.parts {52        for m in &p.measures {53            for v in &m.voices {54                for e in v {55                    feed(e.duration);56                    feed(e.offset);57                }58            }59        }60    }61    div62}6364fn ticks(x: Rational, div: i64) -> i64 {65    (x.to_f64() * 4.0 * div as f64).round() as i6466}6768fn fmt_num(x: f64) -> String {69    if (x - x.round()).abs() < 1e-9 {70        format!("{}", x.round() as i64)71    } else {72        let s = format!("{x:.4}");73        s.trim_end_matches('0').trim_end_matches('.').to_string()74    }75}7677fn write_element(o: &mut String, e: &Element, voice: usize, div: i64, tuplet_start: bool, tuplet_stop: bool) {78    let dur = ticks(e.duration, div);79    let whole_rest = e.is_rest() && e.offset.is_zero() && e.tuplet.is_none() && e.dots == 0 && e.note_type == crate::score::NoteType::Whole;80    let count = e.pitches.len().max(1);81    for i in 0..count {82        o.push_str("      <note>\n");83        if let Some(p) = e.pitches.get(i) {84            if i > 0 {85                o.push_str("        <chord/>\n");86            }87            let step = ['C', 'D', 'E', 'F', 'G', 'A', 'B'][p.step as usize % 7];88            let _ = writeln!(o, "        <pitch>\n          <step>{step}</step>");89            if p.alter.abs() > 1e-9 {90                let _ = writeln!(o, "          <alter>{}</alter>", fmt_num(p.alter));91            }92            let _ = writeln!(o, "          <octave>{}</octave>\n        </pitch>", p.octave);93        } else if whole_rest {94            o.push_str("        <rest measure=\"yes\"/>\n");95        } else {96            o.push_str("        <rest/>\n");97        }98        let _ = writeln!(o, "        <duration>{dur}</duration>");99        if let Some(p) = e.pitches.get(i) {100            if p.tie_stop {101                o.push_str("        <tie type=\"stop\"/>\n");102            }103            if p.tie_start {104                o.push_str("        <tie type=\"start\"/>\n");105            }106        }107        let _ = writeln!(o, "        <voice>{}</voice>", voice + 1);108        if !whole_rest {109            let _ = writeln!(o, "        <type>{}</type>", e.note_type.xml_name());110            for _ in 0..e.dots {111                o.push_str("        <dot/>\n");112            }113            if let Some(p) = e.pitches.get(i) {114                let whole = p.alter.round();115                let micro = p.alter - whole;116                let name = if micro.abs() > 1e-9 {117                    Some(if p.alter > 0.0 { "quarter-sharp" } else { "quarter-flat" })118                } else {119                    match whole as i32 {120                        1 => Some("sharp"),121                        -1 => Some("flat"),122                        2 => Some("double-sharp"),123                        -2 => Some("flat-flat"),124                        0 => Some("natural"),125                        _ => None,126                    }127                };128                // Printed accidentals follow the engraving pass (key signature and measure129                // memory); microtones are always written, most readers would otherwise drop them.130                if let (Some(n), true) = (name, p.show_accidental || micro.abs() > 1e-9) {131                    let _ = writeln!(o, "        <accidental>{n}</accidental>");132                }133            }134            if let Some(t) = e.tuplet {135                let _ = writeln!(o, "        <time-modification>\n          <actual-notes>{}</actual-notes>\n          <normal-notes>{}</normal-notes>\n        </time-modification>", t.actual, t.normal);136            }137            if !e.is_rest() && e.note_type != crate::score::NoteType::Whole {138                let _ = writeln!(o, "        <stem>{}</stem>", if e.stem_up { "up" } else { "down" });139            }140            if i == 0 {141                let role = match e.beam {142                    crate::score::Beam::Begin => Some("begin"),143                    crate::score::Beam::Continue => Some("continue"),144                    crate::score::Beam::End => Some("end"),145                    crate::score::Beam::None => None,146                };147                if let Some(role) = role {148                    let _ = writeln!(o, "        <beam number=\"1\">{role}</beam>");149                }150            }151        }152        let p = e.pitches.get(i);153        let art = if i == 0 {154            match e.articulation {155                Articulation::Staccato | Articulation::Pizzicato => Some("staccato"),156                Articulation::Staccatissimo => Some("staccatissimo"),157                Articulation::Tenuto => Some("tenuto"),158                Articulation::Accent => Some("accent"),159                Articulation::Marcato => Some("strong-accent"),160                _ => None,161            }162        } else {163            None164        };165        let ties = p.map(|p| (p.tie_stop, p.tie_start)).unwrap_or((false, false));166        let tup = i == 0 && (tuplet_start || tuplet_stop);167        let trem = i == 0 && e.articulation == Articulation::Tremolo && !e.is_rest();168        if ties.0 || ties.1 || art.is_some() || tup || trem {169            o.push_str("        <notations>\n");170            if ties.0 {171                o.push_str("          <tied type=\"stop\"/>\n");172            }173            if ties.1 {174                o.push_str("          <tied type=\"start\"/>\n");175            }176            if i == 0 && tuplet_stop {177                o.push_str("          <tuplet type=\"stop\"/>\n");178            }179            if i == 0 && tuplet_start {180                o.push_str("          <tuplet type=\"start\"/>\n");181            }182            if trem {183                o.push_str("          <ornaments>\n            <tremolo type=\"single\">3</tremolo>\n          </ornaments>\n");184            }185            if let Some(a) = art {186                let attr = if a == "strong-accent" { " type=\"up\"" } else { "" };187                let _ = writeln!(o, "          <articulations>\n            <{a}{attr}/>\n          </articulations>");188            }189            o.push_str("        </notations>\n");190        }191        o.push_str("      </note>\n");192    }193}194195/// Serialises a notation model as MusicXML 4.0.196pub fn score_to_musicxml(score: &Score) -> String {197    let div = divisions(score);198    let mut o = String::new();199    o.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");200    o.push_str("<!DOCTYPE score-partwise PUBLIC \"-//Recordare//DTD MusicXML 4.0 Partwise//EN\" \"http://www.musicxml.org/dtds/partwise.dtd\">\n");201    o.push_str("<score-partwise version=\"4.0\">\n");202    let _ = writeln!(o, "  <work>\n    <work-title>{}</work-title>\n  </work>", esc(&score.title));203    let _ = writeln!(204        o,205        "  <identification>\n    <encoding>\n      <software>ORIX Sonata {}</software>\n    </encoding>\n  </identification>",206        env!("CARGO_PKG_VERSION")207    );208    o.push_str("  <part-list>\n");209    for p in &score.parts {210        let _ = writeln!(o, "    <score-part id=\"{}\">\n      <part-name>{}</part-name>\n    </score-part>", p.id, esc(&p.name));211    }212    o.push_str("  </part-list>\n");213    for p in &score.parts {214        let _ = writeln!(o, "  <part id=\"{}\">", p.id);215        for (mi, m) in score.measures.iter().enumerate() {216            let _ = writeln!(o, "    <measure number=\"{}\">", m.number);217            if mi == 0 || m.signature_change {218                o.push_str("      <attributes>\n");219                if mi == 0 {220                    let _ = writeln!(o, "        <divisions>{div}</divisions>");221                    let _ = writeln!(222                        o,223                        "        <key>\n          <fifths>{}</fifths>\n          <mode>{}</mode>\n        </key>",224                        score.fifths,225                        if score.minor { "minor" } else { "major" }226                    );227                }228                let _ = writeln!(229                    o,230                    "        <time>\n          <beats>{}</beats>\n          <beat-type>{}</beat-type>\n        </time>",231                    m.numerator, m.denominator232                );233                if mi == 0 {234                    let (sign, line) = match p.clef {235                        Clef::Treble => ("G", 2),236                        Clef::Bass => ("F", 4),237                        Clef::Alto => ("C", 3),238                        Clef::Percussion => ("percussion", 2),239                    };240                    let _ = writeln!(o, "        <clef>\n          <sign>{sign}</sign>\n          <line>{line}</line>\n        </clef>");241                    if p.transposition != 0 {242                        let _ = writeln!(o, "        <transpose>\n          <chromatic>{}</chromatic>\n        </transpose>", -p.transposition);243                    }244                }245                o.push_str("      </attributes>\n");246            }247            for (bpm, unit) in &m.tempos {248                let (name, dot) = match (unit.num(), unit.den()) {249                    (1, 2) => ("half", false),250                    (1, 8) => ("eighth", false),251                    (3, 8) => ("quarter", true),252                    (3, 16) => ("eighth", true),253                    (3, 4) => ("half", true),254                    _ => ("quarter", false),255                };256                let qpm = bpm * unit.to_f64() * 4.0;257                let _ = writeln!(258                    o,259                    "      <direction placement=\"above\">\n        <direction-type>\n          <metronome>\n            <beat-unit>{name}</beat-unit>{}\n            <per-minute>{}</per-minute>\n          </metronome>\n        </direction-type>\n        <sound tempo=\"{}\"/>\n      </direction>",260                    if dot { "\n            <beat-unit-dot/>" } else { "" },261                    fmt_num(*bpm),262                    fmt_num(qpm)263                );264            }265            let pm = &p.measures[mi];266            for (vi, voice) in pm.voices.iter().enumerate() {267                if vi > 0 {268                    let _ = writeln!(o, "      <backup>\n        <duration>{}</duration>\n      </backup>", ticks(m.length, div));269                }270                let mut written = Rational::ZERO;271                for (ei, e) in voice.iter().enumerate() {272                    if e.offset > written {273                        // A quantisation residue: keep later notes aligned.274                        let gap = e.offset.checked_sub(written).unwrap_or(Rational::ZERO);275                        let _ = writeln!(o, "      <forward>\n        <duration>{}</duration>\n      </forward>", ticks(gap, div));276                    }277                    let prev_t = ei.checked_sub(1).and_then(|i| voice[i].tuplet);278                    let next_t = voice.get(ei + 1).and_then(|n| n.tuplet);279                    let start = e.tuplet.is_some() && prev_t != e.tuplet;280                    let stop = e.tuplet.is_some() && next_t != e.tuplet;281                    write_element(&mut o, e, vi, div, start, stop);282                    written = e.offset.checked_add(e.duration).unwrap_or(written);283                }284                if written < m.length {285                    let gap = m.length.checked_sub(written).unwrap_or(Rational::ZERO);286                    let _ = writeln!(o, "      <forward>\n        <duration>{}</duration>\n      </forward>", ticks(gap, div));287                }288            }289            if mi + 1 == score.measures.len() {290                o.push_str("      <barline location=\"right\">\n        <bar-style>light-heavy</bar-style>\n      </barline>\n");291            }292            o.push_str("    </measure>\n");293        }294        o.push_str("  </part>\n");295    }296    o.push_str("</score-partwise>\n");297    o298}299300/// MusicXML of a program, with the list of approximations made.301pub fn program_to_musicxml(program: &Program) -> (String, Vec<String>) {302    let score = build_score(program);303    (score_to_musicxml(&score), score.warnings)304}305306#[cfg(test)]307mod tests {308    use super::*;309    use crate::score::tests::{note, program};310311    fn r(n: i64, d: i64) -> Rational {312        Rational::new(n, d).unwrap()313    }314315    /// Sums `<duration>` per voice inside each measure, honouring backup/forward and chords.316    fn check_measures(xml: &str, expect_ticks: i64) {317        for measure in xml.split("<measure ").skip(1) {318            let mut pos = 0i64;319            let mut max = 0i64;320            let mut rest = measure;321            while let Some(i) = rest.find('<') {322                rest = &rest[i..];323                let tag = |name: &str| rest.starts_with(&format!("<{name}>")) || rest.starts_with(&format!("<{name} "));324                if tag("note") || tag("backup") || tag("forward") {325                    let kind = if tag("note") {326                        "note"327                    } else if tag("backup") {328                        "backup"329                    } else {330                        "forward"331                    };332                    let end = rest.find(&format!("</{kind}>")).unwrap();333                    let body = &rest[..end];334                    let d: i64 = body.split("<duration>").nth(1).unwrap().split('<').next().unwrap().parse().unwrap();335                    match kind {336                        "note" if body.contains("<chord/>") => {}337                        "note" | "forward" => pos += d,338                        _ => pos -= d,339                    }340                    max = max.max(pos);341                    rest = &rest[end..];342                } else {343                    rest = &rest[1..];344                }345            }346            assert_eq!(max, expect_ticks, "a measure does not add up");347            assert_eq!(pos, expect_ticks, "last voice does not end on the bar line");348        }349    }350351    #[test]352    fn writes_consistent_measures() {353        let notes = vec![354            note(0, r(0, 1), r(1, 4), 62.0, 0),355            note(1, r(0, 1), r(1, 4), 65.0, 0),356            note(2, r(3, 8), r(3, 8), 69.0, 0),357            note(3, r(7, 8), r(1, 2), 72.0, 0),358            note(4, r(3, 2), r(1, 12), 60.0, 0),359            note(5, r(19, 12), r(1, 12), 62.0, 0),360            note(6, r(20, 12), r(1, 12), 64.0, 0),361            note(7, r(0, 1), r(1, 1), 48.0, 1),362        ];363        let mut p = program(notes);364        p.title = "A & B <test>".into();365        let (xml, warnings) = program_to_musicxml(&p);366        assert!(warnings.is_empty());367        assert!(xml.contains("<work-title>A &amp; B &lt;test&gt;</work-title>"));368        let div: i64 = xml.split("<divisions>").nth(1).unwrap().split('<').next().unwrap().parse().unwrap();369        assert_eq!(div, 6, "eighths and triplet eighths need 6 divisions per quarter");370        check_measures(&xml, 4 * div);371        assert_eq!(xml.matches("<tuplet type=\"start\"/>").count(), 1);372        assert_eq!(xml.matches("<tuplet type=\"stop\"/>").count(), 1);373        assert_eq!(xml.matches("<tie type=\"start\"/>").count(), xml.matches("<tie type=\"stop\"/>").count());374        // Balanced tags (cheap well-formedness check; the CLI tests also run xmllint when present).375        for tag in ["note", "measure", "part", "pitch", "notations", "attributes"] {376            assert_eq!(xml.matches(&format!("<{tag}>")).count() + xml.matches(&format!("<{tag} ")).count(), xml.matches(&format!("</{tag}>")).count(), "{tag}");377        }378    }379}380
Files main
Menu

Theme