qualia_audio/midi/sync/
song_position.rs1use crate::types::AudioError;
11
12pub const SONG_POSITION: u8 = 0xF2;
14
15pub const MAX_BEATS: u16 = 0x3FFF;
17
18#[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#[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}