SPB Git

Repository Public

midi.rs 21.6 KB 565 lines rust

1//! ORIX Sonata2//! File: crates/sonata-interop/src/midi.rs3//! Description: Standard MIDI File (format 1) export of a Program, and strict SMF import that4//! produces Sonata source text (the code stays the canonical form of a composition).5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_ir::{Program, Rational, TrackKind};10use std::fmt::Write;1112/// Ticks per quarter note of exported files. 960 divides evenly by 2, 3, 4, 5, 6, 8, 10, 12, 15, 16...13pub const EXPORT_PPQ: u16 = 960;1415fn vlq(mut v: u32, out: &mut Vec<u8>) {16    let mut buf = [0u8; 5];17    let mut i = 4;18    buf[i] = (v & 0x7f) as u8;19    v >>= 7;20    while v > 0 {21        i -= 1;22        buf[i] = 0x80 | (v & 0x7f) as u8;23        v >>= 7;24    }25    out.extend_from_slice(&buf[i..]);26}2728fn to_ticks(pos: Rational) -> u32 {29    // whole note = 4 quarters.30    let t = pos.to_f64() * 4.0 * EXPORT_PPQ as f64;31    if t <= 0.0 {32        033    } else {34        (t + 0.5).floor().min(u32::MAX as f64 / 2.0) as u3235    }36}3738struct Ev {39    tick: u32,40    /// Sort key at equal ticks: note-offs first, then meta, then note-ons.41    order: u8,42    data: Vec<u8>,43}4445fn chunk(events: &mut [Ev], out: &mut Vec<u8>) {46    events.sort_by(|a, b| a.tick.cmp(&b.tick).then(a.order.cmp(&b.order)));47    let mut body = Vec::new();48    let mut last = 0u32;49    for e in events.iter() {50        vlq(e.tick - last, &mut body);51        body.extend_from_slice(&e.data);52        last = e.tick;53    }54    body.extend_from_slice(&[0x00, 0xff, 0x2f, 0x00]);55    out.extend_from_slice(b"MTrk");56    out.extend_from_slice(&(body.len() as u32).to_be_bytes());57    out.extend_from_slice(&body);58}5960fn meta(kind: u8, payload: &[u8]) -> Vec<u8> {61    let mut d = vec![0xff, kind];62    vlq(payload.len() as u32, &mut d);63    d.extend_from_slice(payload);64    d65}6667/// General MIDI percussion key of an unpitched engine.68fn drum_key(model: &str) -> Option<u8> {69    match model {70        "kick" => Some(36),71        "snare" => Some(38),72        "hihat" => Some(42),73        _ => None,74    }75}7677/// Exports a program as a format-1 Standard MIDI File.78///79/// Rules: track 0 carries tempo, time signatures and markers; one MIDI track per instrument80/// track; positions are rounded half up to 1/960 of a quarter note; tempo ramps become one tempo81/// event per sixteenth note; unpitched engines go to channel 10 with General MIDI keys; other82/// tracks use channels 1-9 and 11-16 in order (wrapping after 15 tracks); microtonal pitches are83/// rounded to the nearest semitone and reported in the returned warnings.84pub fn program_to_midi(program: &Program) -> (Vec<u8>, Vec<String>) {85    let mut warnings = Vec::new();86    let mut out = Vec::new();87    let tracks: Vec<_> = program.tracks.iter().filter(|t| t.kind == TrackKind::Instrument).collect();88    out.extend_from_slice(b"MThd");89    out.extend_from_slice(&6u32.to_be_bytes());90    out.extend_from_slice(&1u16.to_be_bytes());91    out.extend_from_slice(&((tracks.len() + 1) as u16).to_be_bytes());92    out.extend_from_slice(&EXPORT_PPQ.to_be_bytes());9394    let mut conductor = vec![Ev { tick: 0, order: 1, data: meta(0x03, program.title.as_bytes()) }];95    let tempo_event = |bpm: f64, unit: Rational| {96        let qpm = (bpm * unit.to_f64() * 4.0).max(1.0);97        let us = (60_000_000.0 / qpm).round().clamp(1.0, 16_777_215.0) as u32;98        meta(0x51, &us.to_be_bytes()[1..])99    };100    let pts = &program.tempo_map.points;101    for (i, p) in pts.iter().enumerate() {102        conductor.push(Ev { tick: to_ticks(p.at), order: 1, data: tempo_event(p.bpm, p.beat_unit) });103        if let (true, Some(n)) = (p.ramp, pts.get(i + 1)) {104            let step = Rational::new(1, 16).unwrap();105            let span = n.at.to_f64() - p.at.to_f64();106            let mut pos = p.at.checked_add(step).unwrap_or(n.at);107            while pos < n.at {108                let f = (pos.to_f64() - p.at.to_f64()) / span;109                // Linear in seconds-per-whole, like the tempo map itself.110                let spw = p.seconds_per_whole() + (n.seconds_per_whole() - p.seconds_per_whole()) * f;111                let qpm = 240.0 / spw;112                conductor.push(Ev { tick: to_ticks(pos), order: 1, data: tempo_event(qpm, Rational::new(1, 4).unwrap()) });113                pos = pos.checked_add(step).unwrap_or(n.at);114            }115        }116    }117    for s in &program.signatures {118        let dd = (s.denominator.max(1) as f64).log2().round() as u8;119        let clocks = (24 * 4 / s.denominator.max(1)).clamp(1, 255) as u8;120        conductor.push(Ev { tick: to_ticks(s.at), order: 1, data: meta(0x58, &[s.numerator.min(255) as u8, dd, clocks, 8]) });121    }122    if let Some(k) = &program.key {123        let (fifths, minor) = crate::score::key_fifths(k);124        conductor.push(Ev { tick: 0, order: 1, data: meta(0x59, &[fifths as u8, minor as u8]) });125    }126    for m in &program.markers {127        conductor.push(Ev { tick: to_ticks(m.at), order: 1, data: meta(0x06, m.name.as_bytes()) });128    }129    chunk(&mut conductor, &mut out);130131    let mut next_channel = 0u8;132    for t in &tracks {133        let model = t.instrument.as_ref().map(|i| i.model.as_str()).unwrap_or("");134        let drum = drum_key(model);135        let channel = if drum.is_some() {136            9137        } else {138            let c = next_channel;139            next_channel = (next_channel + 1) % 15;140            if c >= 9 {141                c + 1142            } else {143                c144            }145        };146        let mut evs = vec![Ev { tick: 0, order: 1, data: meta(0x03, t.name.as_bytes()) }];147        let mut micro = 0usize;148        let mut out_of_range = 0usize;149        for n in &t.notes {150            let rounded = n.pitch.round();151            if (n.pitch - rounded).abs() > 1e-6 {152                micro += 1;153            }154            let key = match drum {155                Some(k) => k,156                None => {157                    if !(0.0..=127.0).contains(&rounded) {158                        out_of_range += 1;159                        continue;160                    }161                    rounded as u8162                }163            };164            let on = to_ticks(n.start);165            let mut off = to_ticks(n.start.checked_add(n.duration).unwrap_or(n.start));166            if off <= on {167                off = on + 1;168            }169            let vel = ((n.velocity as f64 * 127.0).round() as i64).clamp(1, 127) as u8;170            evs.push(Ev { tick: on, order: 2, data: vec![0x90 | channel, key, vel] });171            evs.push(Ev { tick: off, order: 0, data: vec![0x80 | channel, key, 64] });172        }173        if micro > 0 {174            warnings.push(format!("{}: {micro} microtonal note(s) rounded to the nearest semitone", t.name));175        }176        if out_of_range > 0 {177            warnings.push(format!("{}: {out_of_range} note(s) outside the MIDI range were omitted", t.name));178        }179        chunk(&mut evs, &mut out);180    }181    if program.tracks.iter().any(|t| t.kind == TrackKind::Audio) {182        warnings.push("audio tracks are not part of a MIDI file".into());183    }184    (out, warnings)185}186187// ───────────────────────────── import ─────────────────────────────188189#[derive(Clone, Debug, PartialEq)]190pub struct MidiNote {191    pub start: u64,192    pub duration: u64,193    pub key: u8,194    pub velocity: u8,195    pub channel: u8,196}197198#[derive(Clone, Debug, Default, PartialEq)]199pub struct MidiTrack {200    pub name: String,201    pub notes: Vec<MidiNote>,202}203204#[derive(Clone, Debug, PartialEq)]205pub struct MidiFile {206    pub format: u16,207    pub ppq: u16,208    /// (tick, microseconds per quarter note)209    pub tempos: Vec<(u64, u32)>,210    /// (tick, numerator, denominator)211    pub signatures: Vec<(u64, u8, u32)>,212    pub tracks: Vec<MidiTrack>,213    pub title: Option<String>,214}215216/// Limits applied while reading untrusted files.217pub const MAX_MIDI_BYTES: usize = 64 * 1024 * 1024;218pub const MAX_MIDI_NOTES: usize = 2_000_000;219220struct Reader<'a> {221    d: &'a [u8],222    p: usize,223}224225impl<'a> Reader<'a> {226    fn u8(&mut self) -> Result<u8, String> {227        let v = *self.d.get(self.p).ok_or("unexpected end of file")?;228        self.p += 1;229        Ok(v)230    }231    fn take(&mut self, n: usize) -> Result<&'a [u8], String> {232        let end = self.p.checked_add(n).filter(|e| *e <= self.d.len()).ok_or("chunk length runs past the end of the file")?;233        let s = &self.d[self.p..end];234        self.p = end;235        Ok(s)236    }237    fn u16(&mut self) -> Result<u16, String> {238        let s = self.take(2)?;239        Ok(u16::from_be_bytes([s[0], s[1]]))240    }241    fn u32(&mut self) -> Result<u32, String> {242        let s = self.take(4)?;243        Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))244    }245    fn vlq(&mut self) -> Result<u32, String> {246        let mut v = 0u32;247        for _ in 0..4 {248            let b = self.u8()?;249            v = (v << 7) | (b & 0x7f) as u32;250            if b & 0x80 == 0 {251                return Ok(v);252            }253        }254        Err("variable-length quantity longer than 4 bytes".into())255    }256}257258/// Parses a Standard MIDI File (formats 0 and 1, metrical time division). Never panics.259pub fn parse_midi(data: &[u8]) -> Result<MidiFile, String> {260    if data.len() > MAX_MIDI_BYTES {261        return Err(format!("file is larger than {} MiB", MAX_MIDI_BYTES >> 20));262    }263    let mut r = Reader { d: data, p: 0 };264    if r.take(4)? != b"MThd" {265        return Err("not a Standard MIDI File (missing MThd)".into());266    }267    let hlen = r.u32()? as usize;268    if hlen < 6 {269        return Err("header chunk is too short".into());270    }271    let format = r.u16()?;272    let ntracks = r.u16()?;273    let division = r.u16()?;274    r.take(hlen - 6)?;275    if format > 1 {276        return Err(format!("SMF format {format} is not supported (only 0 and 1)"));277    }278    if division & 0x8000 != 0 {279        return Err("SMPTE time division is not supported".into());280    }281    if division == 0 {282        return Err("time division is zero".into());283    }284    let mut file = MidiFile { format, ppq: division, tempos: Vec::new(), signatures: Vec::new(), tracks: Vec::new(), title: None };285    let mut total_notes = 0usize;286    let mut seen = 0u16;287    while seen < ntracks && r.p < data.len() {288        let id = r.take(4)?;289        let len = r.u32()? as usize;290        let body = r.take(len)?;291        if id != b"MTrk" {292            continue; // unknown chunks are skipped, as the standard requires293        }294        seen += 1;295        let mut t = Reader { d: body, p: 0 };296        let mut track = MidiTrack::default();297        let mut tick = 0u64;298        let mut status = 0u8;299        // Open notes: (channel, key) -> stack of (start tick, velocity).300        let mut open: Vec<(u8, u8, u64, u8)> = Vec::new();301        while t.p < body.len() {302            tick += t.vlq()? as u64;303            let mut b = t.u8()?;304            if b < 0x80 {305                if status < 0x80 {306                    return Err("running status without a previous status byte".into());307                }308                t.p -= 1;309                b = status;310            } else if b < 0xf0 {311                status = b;312            }313            match b {314                0xff => {315                    let kind = t.u8()?;316                    let len = t.vlq()? as usize;317                    let payload = t.take(len)?;318                    match kind {319                        0x2f => break,320                        0x03 => {321                            let name = String::from_utf8_lossy(payload).trim().to_string();322                            if file.tracks.is_empty() && file.title.is_none() && format == 1 {323                                file.title = Some(name.clone());324                            }325                            track.name = name;326                        }327                        0x51 if payload.len() == 3 => {328                            let us = u32::from_be_bytes([0, payload[0], payload[1], payload[2]]);329                            if us > 0 {330                                file.tempos.push((tick, us));331                            }332                        }333                        0x58 if payload.len() >= 2 && payload[0] > 0 && payload[1] <= 6 => file.signatures.push((tick, payload[0], 1u32 << payload[1])),334                        _ => {}335                    }336                }337                0xf0 | 0xf7 => {338                    let len = t.vlq()? as usize;339                    t.take(len)?;340                }341                0xf1..=0xfe => return Err("unexpected system message inside a track".into()),342                _ => {343                    let ch = b & 0x0f;344                    let kind = b & 0xf0;345                    let d1 = t.u8()? & 0x7f;346                    let d2 = if kind == 0xc0 || kind == 0xd0 { 0 } else { t.u8()? & 0x7f };347                    let is_on = kind == 0x90 && d2 > 0;348                    let is_off = kind == 0x80 || (kind == 0x90 && d2 == 0);349                    if is_on {350                        open.push((ch, d1, tick, d2));351                    } else if is_off {352                        if let Some(i) = open.iter().position(|o| o.0 == ch && o.1 == d1) {353                            let (_, _, start, vel) = open.remove(i);354                            if tick > start {355                                track.notes.push(MidiNote { start, duration: tick - start, key: d1, velocity: vel, channel: ch });356                                total_notes += 1;357                                if total_notes > MAX_MIDI_NOTES {358                                    return Err(format!("more than {MAX_MIDI_NOTES} notes"));359                                }360                            }361                        }362                    }363                }364            }365        }366        // Notes never released end at the last event of the track.367        for (ch, key, start, vel) in open {368            if tick > start {369                track.notes.push(MidiNote { start, duration: tick - start, key, velocity: vel, channel: ch });370            }371        }372        track.notes.sort_by(|a, b| a.start.cmp(&b.start).then(a.key.cmp(&b.key)));373        file.tracks.push(track);374    }375    file.tempos.sort_by_key(|t| t.0);376    file.tempos.dedup_by_key(|t| t.0);377    file.signatures.sort_by_key(|t| t.0);378    file.signatures.dedup_by_key(|t| t.0);379    Ok(file)380}381382fn note_name(key: u8) -> String {383    const N: [&str; 12] = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];384    format!("{}{}", N[key as usize % 12], key as i32 / 12 - 1)385}386387fn ident(name: &str, index: usize, used: &mut Vec<String>) -> String {388    let mut s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }).collect();389    s = s.trim_matches('_').to_string();390    while s.contains("__") {391        s = s.replace("__", "_");392    }393    // Lower-case identifiers can never collide with note literals (which start with A-G upper case).394    if s.is_empty() || !s.chars().next().unwrap().is_ascii_alphabetic() {395        s = format!("track{}", index + 1);396    }397    let base = format!("t_{s}");398    let mut cand = base.clone();399    let mut k = 2;400    while used.contains(&cand) {401        cand = format!("{base}_{k}");402        k += 1;403    }404    used.push(cand.clone());405    cand406}407408fn dur_text(ticks: u64, ppq: u16) -> String {409    // whole note = 4 * ppq ticks410    Rational::new(ticks as i64, 4 * ppq as i64).map(|r| if r.is_integer() { format!("{}/1", r.num()) } else { r.to_string() }).unwrap_or_else(|| "1/4".into())411}412413/// Converts a parsed MIDI file into Sonata source. Each MIDI track becomes an instrument track414/// (`instrument` is the Sonata instrument name to use, e.g. `GrandPiano`); overlapping notes are415/// distributed over `voice` blocks; simultaneous notes of equal length become chords.416pub fn midi_to_sonata(file: &MidiFile, instrument: &str) -> String {417    let mut o = String::new();418    let title = file.title.clone().filter(|t| !t.is_empty()).unwrap_or_else(|| "Imported MIDI".into());419    let _ = writeln!(o, "import std.music\nimport std.instruments\n");420    let _ = writeln!(o, "composition \"{}\" {{", title.replace('\\', "\\\\").replace('"', "\\\""));421    let bpm = |us: u32| 60_000_000.0 / us as f64;422    let first_tempo = file.tempos.first().filter(|t| t.0 == 0).map(|t| bpm(t.1)).unwrap_or(120.0);423    let _ = writeln!(o, "    tempo {}bpm", trim_float(first_tempo));424    let (num, den) = file.signatures.first().filter(|s| s.0 == 0).map(|s| (s.1, s.2)).unwrap_or((4, 4));425    let _ = writeln!(o, "    signature {num}/{den}");426    let mut used = Vec::new();427    let mut first_track = true;428    for (ti, t) in file.tracks.iter().enumerate() {429        if t.notes.is_empty() {430            continue;431        }432        let name = ident(&t.name, ti, &mut used);433        let _ = writeln!(o, "\n    instrument {name}: {instrument} {{");434        if first_track {435            // Later tempo changes are written once, on the first track, at their position.436            for (tick, us) in file.tempos.iter().filter(|t| t.0 > 0) {437                let _ = writeln!(o, "        at {} {{ tempo {}bpm }}", dur_text(*tick, file.ppq), trim_float(bpm(*us)));438            }439            first_track = false;440        }441        // Chords, then greedy voices.442        /// (start tick, length, velocity, keys)443        type ChordRow = (u64, u64, u8, Vec<u8>);444        let mut chords: Vec<ChordRow> = Vec::new();445        for n in &t.notes {446            match chords.last_mut() {447                Some(c) if c.0 == n.start && c.1 == n.duration && c.2 == n.velocity => c.3.push(n.key),448                _ => chords.push((n.start, n.duration, n.velocity, vec![n.key])),449            }450        }451        let mut voices: Vec<Vec<&ChordRow>> = Vec::new();452        for c in &chords {453            match voices.iter_mut().find(|v| v.last().map(|l| l.0 + l.1 <= c.0).unwrap_or(true)) {454                Some(v) => v.push(c),455                None => voices.push(vec![c]),456            }457        }458        let many = voices.len() > 1;459        for v in &voices {460            let pad = if many { "            " } else { "        " };461            if many {462                o.push_str("        voice {\n");463            }464            let mut cursor = 0u64;465            for c in v {466                if c.0 > cursor {467                    let _ = writeln!(o, "{pad}rest {}", dur_text(c.0 - cursor, file.ppq));468                }469                let vel = trim_float((c.2 as f64 / 127.0 * 1000.0).round() / 1000.0);470                if c.3.len() == 1 {471                    let _ = writeln!(o, "{pad}play {} duration {} velocity {vel}", note_name(c.3[0]), dur_text(c.1, file.ppq));472                } else {473                    let names: Vec<String> = c.3.iter().map(|k| note_name(*k)).collect();474                    let _ = writeln!(o, "{pad}chord [{}] duration {} velocity {vel}", names.join(", "), dur_text(c.1, file.ppq));475                }476                cursor = c.0 + c.1;477            }478            if many {479                o.push_str("        }\n");480            }481        }482        o.push_str("    }\n");483    }484    o.push_str("}\n");485    o486}487488fn trim_float(x: f64) -> String {489    let s = format!("{x:.3}");490    let s = s.trim_end_matches('0').trim_end_matches('.');491    if s.is_empty() {492        "0".into()493    } else {494        s.to_string()495    }496}497498#[cfg(test)]499mod tests {500    use super::*;501    use crate::score::tests::{note, program};502503    fn r(n: i64, d: i64) -> Rational {504        Rational::new(n, d).unwrap()505    }506507    #[test]508    fn export_then_import_round_trips_notes() {509        let p = program(vec![510            note(0, r(0, 1), r(1, 4), 62.0, 0),511            note(1, r(0, 1), r(1, 4), 65.0, 0),512            note(2, r(1, 4), r(1, 12), 69.0, 0),513            note(3, r(1, 3), r(2, 3), 60.25, 0),514        ]);515        let (bytes, warnings) = program_to_midi(&p);516        assert_eq!(warnings.len(), 1, "one microtone warning: {warnings:?}");517        let f = parse_midi(&bytes).unwrap();518        assert_eq!((f.format, f.ppq), (1, 960));519        assert_eq!(f.tempos, vec![(0, 500_000)]);520        assert_eq!(f.signatures, vec![(0, 4, 4)]);521        assert_eq!(f.title.as_deref(), Some("Test"));522        let notes = &f.tracks[1].notes;523        assert_eq!(notes.len(), 4);524        assert_eq!((notes[0].start, notes[0].duration, notes[0].key), (0, 960, 62));525        assert_eq!((notes[2].start, notes[2].duration, notes[2].key), (960, 320, 69));526        assert_eq!((notes[3].start, notes[3].duration, notes[3].key), (1280, 2560, 60));527        assert_eq!(notes[0].velocity, 102);528        let src = midi_to_sonata(&f, "GrandPiano");529        assert!(src.contains("chord [D4, F4] duration 1/4 velocity 0.803"), "{src}");530        assert!(src.contains("play A4 duration 1/12"));531        assert!(src.contains("play C4 duration 2/3"));532    }533534    #[test]535    fn rejects_garbage_without_panicking() {536        assert!(parse_midi(b"").is_err());537        assert!(parse_midi(b"RIFF....").is_err());538        assert!(parse_midi(b"MThd\0\0\0\x06\0\x01\0\x01\xe7\x28").is_err(), "SMPTE division");539        assert!(parse_midi(b"MThd\0\0\0\x06\0\x01\0\x01\x01\xe0MTrk\xff\xff\xff\xff").is_err(), "length past the end");540        // Deterministic pseudo-random mutations of a valid file.541        let (bytes, _) = program_to_midi(&program(vec![note(0, r(0, 1), r(1, 4), 62.0, 0)]));542        let mut s = 0x9e3779b97f4a7c15u64;543        for _ in 0..4000 {544            let mut m = bytes.clone();545            for _ in 0..3 {546                s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);547                let i = (s >> 33) as usize % m.len();548                m[i] = (s >> 24) as u8;549            }550            let _ = parse_midi(&m);551        }552    }553554    #[test]555    fn vlq_encoding() {556        let mut v = Vec::new();557        for x in [0u32, 0x40, 0x7f, 0x80, 0x2000, 0x3fff, 0x4000, 0x0fff_ffff] {558            v.clear();559            vlq(x, &mut v);560            let mut r = Reader { d: &v, p: 0 };561            assert_eq!(r.vlq().unwrap(), x);562        }563    }564}565
Files main
Menu

Theme