Skip to main content

qualia_audio/midi/sync/
song_position.rs

1//! Song Position Pointer (SPP) — 14-bit MIDI-beat position codec.
2//!
3//! SPP is the System Common message `0xF2 LSB MSB`: two 7-bit data bytes form a
4//! 14-bit value counting **MIDI beats** from the start of the song, where one
5//! MIDI beat = 6 MIDI clocks = a sixteenth note. The value range is
6//! `0 ..= 16383`. This module encodes a beat count into the two data bytes
7//! (least-significant 7 bits first) and decodes them back, validating that the
8//! data bytes have their high bit clear. Allocation-free.
9
10use crate::types::AudioError;
11
12/// Song Position Pointer status byte (System Common).
13pub const SONG_POSITION: u8 = 0xF2;
14
15/// Maximum representable MIDI-beat position (14 bits).
16pub const MAX_BEATS: u16 = 0x3FFF;
17
18/// Encode a MIDI-beat position into the two SPP data bytes `[LSB, MSB]`.
19///
20/// Errors with [`AudioError::InvalidParameter`] if `beats > 16383`.
21#[inline]
22pub fn encode_song_position(beats: u16) -> Result<[u8; 2], AudioError> {
23    if beats > MAX_BEATS {
24        return Err(AudioError::InvalidParameter);
25    }
26    let lsb = (beats & 0x7F) as u8;
27    let msb = ((beats >> 7) & 0x7F) as u8;
28    Ok([lsb, msb])
29}
30
31/// Decode the two SPP data bytes back into a MIDI-beat position.
32///
33/// Errors with [`AudioError::InvalidParameter`] if either byte has its high bit
34/// set (data bytes must be 7-bit).
35#[inline]
36pub fn decode_song_position(lsb: u8, msb: u8) -> Result<u16, AudioError> {
37    if lsb & 0x80 != 0 || msb & 0x80 != 0 {
38        return Err(AudioError::InvalidParameter);
39    }
40    Ok(((msb as u16) << 7) | lsb as u16)
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn golden_eight_beats_round_trip() {
49        let [lsb, msb] = encode_song_position(8).unwrap();
50        assert_eq!([lsb, msb], [8, 0]);
51        assert_eq!(decode_song_position(lsb, msb).unwrap(), 8);
52    }
53
54    #[test]
55    fn round_trip_across_range() {
56        for &b in &[0u16, 1, 127, 128, 1000, 8192, 16383] {
57            let [lsb, msb] = encode_song_position(b).unwrap();
58            assert_eq!(decode_song_position(lsb, msb).unwrap(), b);
59        }
60    }
61
62    #[test]
63    fn rejects_overflow_and_bad_bytes() {
64        assert_eq!(
65            encode_song_position(16384),
66            Err(AudioError::InvalidParameter)
67        );
68        assert_eq!(
69            decode_song_position(0x80, 0),
70            Err(AudioError::InvalidParameter)
71        );
72        assert_eq!(
73            decode_song_position(0, 0x80),
74            Err(AudioError::InvalidParameter)
75        );
76    }
77}