Extract MIDI synchronization wire helpers from LoopCraft (#1478)

Preserve transport/SPP and non-drop MTC wire behavior; keep scheduling app-owned. Add allocation-free shared APIs and protocol regression tests.

Co-authored-by: bflatastic <bombayapirat@gmail.com>
This commit is contained in:
Dylan M. Taylorandbflatastic authored and GitHub committed 2026-11-15 04:02:15 -05:00
1 parent cd8207b436
commit 979413980e
5 files changed
+206 -1

No files matched your search

+15 -1
View File
@@ -1,6 +1,6 @@
# craft-midi
MIDI file formats. Bytes in, a neutral model out, and back. No file access: callers pass bytes,
MIDI file formats and synchronization wire messages. Bytes in, a neutral model out, and back. No file access: callers pass bytes,
so the crate builds for wasm32.
| Format | Read | Write |
@@ -79,3 +79,17 @@ of two, more than 65535 tracks or a gap beyond the 28-bit delta limit is an erro
Written from the public Standard MIDI Files 1.0 specification (the MIDI Association). No other
product's code, assets or strings were used. The code comes from SoundCraft's `soundcraft-midi`
crate; the tests build every file they read in code, so the crate ships no binary test data.
## Synchronization wire messages
`sync` provides MIDI Clock/Start/Continue/Stop and Song Position Pointer parsing,
clamped song-position encoding, and full-frame/quarter-frame MIDI Time Code serialization.
It is allocation-free and contains no port access, clocks, tempo estimation or transport scheduling.
`SyncMessage::parse` accepts a status-first prefix and ignores trailing bytes, matching LoopCraft;
it is not a byte-stream parser. Time code supports only 24/25/30 non-drop fps, not 29.97 drop-frame.
These wire helpers are extracted from LoopCraft's `crates/midi/src/sync.rs` at
[`18c68c6e`](https://github.com/storytold/loopcraft/blob/18c68c6e18b13d90db3001dd9f95462cdc4b05a8/crates/midi/src/sync.rs).
The source history credits bflatastic. Transport state and scheduling remain app-owned.
Tests cover known wire vectors, truncated/invalid input, all song-position input values and
legacy conversion behavior. No application consumer cutover is claimed by this library addition.
+1
View File
@@ -12,6 +12,7 @@
mod sequence;
mod smf;
pub mod sync;
pub use sequence::{CtrlEvent, CtrlKind, Note, Sequence};
pub use smf::{LenientRead, MAX_EVENTS, MAX_TRACKS, MAX_WARNINGS, Smf, SmfTrack, read_smf, read_smf_lenient, write_smf};
+135
View File
@@ -0,0 +1,135 @@
//! MIDI synchronization wire messages, separate from transport scheduling.
//!
//! Extracted from LoopCraft `crates/midi/src/sync.rs` at
//! `18c68c6e18b13d90db3001dd9f95462cdc4b05a8` (source history credits bflatastic).
//! This module preserves its prefix-parser, clamped song-position and non-drop time-code
//! behavior. It does not parse a byte stream or schedule clocks; hosts retain those policies.
//!
//! Only 24, 25 and 30 non-drop frames per second are represented, not 29.97 drop-frame.
/// MIDI clock: 24 to the quarter note.
pub const CLOCKS_PER_QUARTER: u32 = 24;
pub const CLOCK: u8 = 0xF8;
pub const START: u8 = 0xFA;
pub const CONTINUE: u8 = 0xFB;
pub const STOP: u8 = 0xFC;
pub const SONG_POSITION: u8 = 0xF2;
pub const QUARTER_FRAME: u8 = 0xF1;
/// The furthest Song Position Pointer reaches, in sixteenth notes (fourteen bits).
pub const MAX_POSITION: u16 = 0x3FFF;
/// What a device that leads the time sends.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SyncMessage {
Clock,
Start,
Continue,
Stop,
/// Song Position Pointer: sixteenth notes from the start of the song.
Position(u16),
}
impl SyncMessage {
/// Parse a status-first message prefix; trailing bytes are ignored for compatibility.
/// Returns `None` for an unknown status, truncated song position, or non-seven-bit data.
/// This is not a stream parser and does not remove interleaved real-time messages.
pub fn parse(message: &[u8]) -> Option<SyncMessage> {
Some(match *message {
[CLOCK, ..] => SyncMessage::Clock,
[START, ..] => SyncMessage::Start,
[CONTINUE, ..] => SyncMessage::Continue,
[STOP, ..] => SyncMessage::Stop,
[SONG_POSITION, low, high, ..] if low < 0x80 && high < 0x80 => SyncMessage::Position(u16::from(high) << 7 | u16::from(low)),
_ => return None,
})
}
}
/// Song Position Pointer at `sixteenths` from the start, the low seven bits first.
pub fn song_position(sixteenths: u16) -> [u8; 3] {
let at = sixteenths.min(MAX_POSITION);
[SONG_POSITION, (at & 0x7F) as u8, (at >> 7) as u8]
}
/// The frame rates time code is sent at (non-drop).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Rate {
Fps24,
#[default]
Fps25,
Fps30,
}
impl Rate {
/// 24 and 30 frames a second are themselves; anything else is 25.
pub fn of(fps: u8) -> Rate {
match fps {
24 => Rate::Fps24,
30 => Rate::Fps30,
_ => Rate::Fps25,
}
}
pub fn fps(self) -> u8 {
match self {
Rate::Fps24 => 24,
Rate::Fps25 => 25,
Rate::Fps30 => 30,
}
}
/// As the hours byte carries it: 0 for 24, 1 for 25, 3 for 30 non-drop.
fn code(self) -> u8 {
match self {
Rate::Fps24 => 0,
Rate::Fps25 => 1,
Rate::Fps30 => 3,
}
}
}
/// Hours, minutes, seconds and frames at `secs`; the hours wrap at a day.
fn timecode(secs: f64, rate: Rate) -> [u8; 4] {
let fps = u64::from(rate.fps());
// `as` saturates: before the start, and NaN, is the start. The nudge keeps a frame's own
// start in it when the sum lands a hair short.
let frames = (secs * fps as f64 + 1e-6) as u64;
let s = frames / fps;
[(s / 3600 % 24) as u8, (s / 60 % 60) as u8, (s % 60) as u8, (frames % fps) as u8]
}
/// The full-frame message (universal real-time SysEx, all devices) locating to `secs`.
///
/// Compatibility conversion: negative values and NaN locate to zero; positive overflow
/// saturates the frame count at `u64::MAX`. Hours wrap at 24. No drop-frame conversion.
pub fn full_frame(secs: f64, rate: Rate) -> [u8; 10] {
let [h, m, s, f] = timecode(secs, rate);
[0xF0, 0x7F, 0x7F, 0x01, 0x01, rate.code() << 5 | h, m, s, f, 0xF7]
}
/// Quarter frame `piece` (0..8) of `time` (hours, minutes, seconds, frames): eight of them, a
/// quarter of a frame apart, carry the whole time, the frames' low nibble first.
fn quarter_frame(time: [u8; 4], rate: Rate, piece: u8) -> [u8; 2] {
let [h, m, s, f] = time;
let piece = piece & 7;
let nibble = match piece {
0 => f,
1 => f >> 4,
2 => s,
3 => s >> 4,
4 => m,
5 => m >> 4,
6 => h,
_ => h >> 4 | rate.code() << 1,
};
[QUARTER_FRAME, piece << 4 | nibble & 0x0F]
}
/// All eight quarter-frame wire messages for a single time-code snapshot, in wire order.
///
/// This is serialization only: the host must send each piece at the appropriate time and
/// account for transport direction/latency. Seconds use the same conversion as [`full_frame`].
pub fn quarter_frames(secs: f64, rate: Rate) -> [[u8; 2]; 8] {
let time = timecode(secs, rate);
[0, 1, 2, 3, 4, 5, 6, 7].map(|piece| quarter_frame(time, rate, piece))
}
+1
View File
@@ -3,3 +3,4 @@
mod lenient;
mod sequence;
mod smf;
mod sync;
+54
View File
@@ -0,0 +1,54 @@
use craft_midi::sync::{CLOCK, CONTINUE, MAX_POSITION, Rate, SONG_POSITION, START, STOP, SyncMessage, full_frame, quarter_frames, song_position};
#[test]
fn transport_prefix_compatibility() {
for (status, expected) in [(CLOCK, SyncMessage::Clock), (START, SyncMessage::Start), (CONTINUE, SyncMessage::Continue), (STOP, SyncMessage::Stop)]
{
assert_eq!(SyncMessage::parse(&[status]), Some(expected));
assert_eq!(SyncMessage::parse(&[status, 0, 0xff]), Some(expected));
}
for invalid in [&[][..], &[0x90, 60, 127], &[SONG_POSITION], &[SONG_POSITION, 0], &[SONG_POSITION, 0x80, 0], &[SONG_POSITION, 0, 0x80]] {
assert_eq!(SyncMessage::parse(invalid), None);
}
}
#[test]
fn song_position_preserves_clamping_and_seven_bit_order() {
for value in 0..=u16::MAX {
let bytes = song_position(value);
assert!(bytes[1] < 128 && bytes[2] < 128);
assert_eq!(SyncMessage::parse(&bytes), Some(SyncMessage::Position(value.min(MAX_POSITION))));
}
assert_eq!(song_position(128), [0xf2, 0, 1]);
assert_eq!(SyncMessage::parse(&[0xf2, 1, 2, 0xff]), Some(SyncMessage::Position(257)));
}
#[test]
fn full_frame_known_vectors_and_legacy_conversion() {
for (rate, bits) in [(Rate::Fps24, 0), (Rate::Fps25, 0x20), (Rate::Fps30, 0x60)] {
assert_eq!(full_frame(3723.0, rate), [0xf0, 0x7f, 0x7f, 1, 1, bits | 1, 2, 3, 0, 0xf7]);
assert_eq!(full_frame(86400.0, rate), full_frame(0.0, rate));
assert_eq!(full_frame(-1.0, rate), full_frame(0.0, rate));
assert_eq!(full_frame(f64::NAN, rate), full_frame(0.0, rate));
assert_eq!(full_frame(1.0 / f64::from(rate.fps()), rate)[8], 1);
}
assert_eq!(Rate::of(24), Rate::Fps24);
assert_eq!(Rate::of(30), Rate::Fps30);
assert_eq!(Rate::of(29), Rate::Fps25);
}
#[test]
fn quarter_frames_known_vector() {
assert_eq!(
quarter_frames(3723.04, Rate::Fps25),
[[0xf1, 1], [0xf1, 0x10], [0xf1, 0x23], [0xf1, 0x30], [0xf1, 0x42], [0xf1, 0x50], [0xf1, 0x61], [0xf1, 0x72]]
);
for rate in [Rate::Fps24, Rate::Fps25, Rate::Fps30] {
for secs in [0.0, 59.99, 3599.99, 86399.99, f64::INFINITY, f64::NEG_INFINITY, f64::NAN] {
for bytes in quarter_frames(secs, rate) {
assert_eq!(bytes[0], 0xf1);
assert!(bytes[1] < 128);
}
}
}
}