Skip to main content

qualia_audio/midi/sync/
midi_clock.rs

1//! 24-PPQN MIDI clock — generation and consumption.
2//!
3//! MIDI transmits 24 timing-clock bytes (`0xF8`) per quarter note. One clock
4//! therefore lasts `(60 / bpm) / 24` seconds. This module both *generates* the
5//! stream (how many clock pulses fall inside a wall-clock time slice) and
6//! *consumes* it (estimate BPM from the interval between received pulses,
7//! smoothed over a small fixed window so jitter on a single interval does not
8//! throw the tempo). No allocation; all state lives on the stack.
9
10use crate::types::AudioError;
11
12/// MIDI System Real-Time: Timing Clock (24 per quarter note).
13pub const TIMING_CLOCK: u8 = 0xF8;
14/// MIDI System Real-Time: Start.
15pub const START: u8 = 0xFA;
16/// MIDI System Real-Time: Continue.
17pub const CONTINUE: u8 = 0xFB;
18/// MIDI System Real-Time: Stop.
19pub const STOP: u8 = 0xFC;
20
21/// Clock pulses per quarter note, per the MIDI spec.
22pub const CLOCKS_PER_QUARTER: u32 = 24;
23
24/// Seconds between consecutive clock pulses at a given tempo.
25///
26/// Errors if `bpm` is not a positive finite number.
27#[inline]
28pub fn clock_period_seconds(bpm: f64) -> Result<f64, AudioError> {
29    if !(bpm > 0.0) || !bpm.is_finite() {
30        return Err(AudioError::InvalidParameter);
31    }
32    Ok((60.0 / bpm) / CLOCKS_PER_QUARTER as f64)
33}
34
35/// Recover BPM from the interval (seconds) between two clock pulses.
36///
37/// Errors if `period_seconds` is not a positive finite number.
38#[inline]
39pub fn bpm_from_clock_period(period_seconds: f64) -> Result<f64, AudioError> {
40    if !(period_seconds > 0.0) || !period_seconds.is_finite() {
41        return Err(AudioError::InvalidParameter);
42    }
43    Ok(60.0 / (period_seconds * CLOCKS_PER_QUARTER as f64))
44}
45
46/// A 24-PPQN clock that both emits pulses over time and estimates incoming BPM.
47///
48/// Generation: [`ClockSync::advance`] accumulates elapsed seconds and returns
49/// how many whole clock pulses should be transmitted. Consumption:
50/// [`ClockSync::on_pulse`] feeds pulse timestamps and returns the current
51/// smoothed BPM estimate once enough intervals are known.
52#[derive(Debug, Clone, Copy)]
53pub struct ClockSync {
54    period: f64,
55    accum: f64,
56    // Ring of recent inter-pulse intervals for smoothing.
57    intervals: [f64; 8],
58    filled: usize,
59    write: usize,
60    last_pulse: f64,
61    have_last: bool,
62}
63
64impl ClockSync {
65    /// Build a generator/estimator anchored at `bpm`. Errors on bad tempo.
66    pub fn new(bpm: f64) -> Result<Self, AudioError> {
67        Ok(Self {
68            period: clock_period_seconds(bpm)?,
69            accum: 0.0,
70            intervals: [0.0; 8],
71            filled: 0,
72            write: 0,
73            last_pulse: 0.0,
74            have_last: false,
75        })
76    }
77
78    /// Retune the generator's tempo. Errors on bad tempo.
79    pub fn set_bpm(&mut self, bpm: f64) -> Result<(), AudioError> {
80        self.period = clock_period_seconds(bpm)?;
81        Ok(())
82    }
83
84    /// Generation: advance by `delta_seconds`, returning the number of whole
85    /// clock pulses to transmit in that slice. Errors if `delta_seconds` is
86    /// negative or not finite.
87    pub fn advance(&mut self, delta_seconds: f64) -> Result<u32, AudioError> {
88        if !delta_seconds.is_finite() || delta_seconds < 0.0 {
89            return Err(AudioError::InvalidParameter);
90        }
91        self.accum += delta_seconds;
92        let mut pulses = 0u32;
93        while self.accum >= self.period {
94            self.accum -= self.period;
95            pulses += 1;
96        }
97        Ok(pulses)
98    }
99
100    /// Consumption: feed the absolute timestamp (seconds) of a received clock
101    /// pulse. Returns `Some(bpm)` once at least one interval is known, using
102    /// the average of the recent-interval window; `None` on the first pulse.
103    pub fn on_pulse(&mut self, timestamp_seconds: f64) -> Option<f64> {
104        if !timestamp_seconds.is_finite() {
105            return None;
106        }
107        if self.have_last {
108            let dt = timestamp_seconds - self.last_pulse;
109            if dt > 0.0 && dt.is_finite() {
110                self.intervals[self.write] = dt;
111                self.write = (self.write + 1) % self.intervals.len();
112                if self.filled < self.intervals.len() {
113                    self.filled += 1;
114                }
115            }
116        }
117        self.last_pulse = timestamp_seconds;
118        self.have_last = true;
119
120        if self.filled == 0 {
121            return None;
122        }
123        let mut sum = 0.0;
124        for &v in &self.intervals[..self.filled] {
125            sum += v;
126        }
127        let avg = sum / self.filled as f64;
128        bpm_from_clock_period(avg).ok()
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn period_matches_120bpm() {
138        // 120 BPM: quarter = 0.5s, /24 = 0.0208333...s per clock.
139        let p = clock_period_seconds(120.0).unwrap();
140        assert!((p - 0.5 / 24.0).abs() < 1e-9, "got {p}");
141        assert!((bpm_from_clock_period(p).unwrap() - 120.0).abs() < 1e-6);
142    }
143
144    #[test]
145    fn generates_24_pulses_per_quarter() {
146        let mut c = ClockSync::new(120.0).unwrap();
147        // Half a second at 120 BPM is exactly one quarter note = 24 pulses.
148        let pulses = c.advance(0.5).unwrap();
149        assert_eq!(pulses, 24);
150    }
151
152    #[test]
153    fn estimates_bpm_from_pulses() {
154        let mut c = ClockSync::new(100.0).unwrap();
155        let period = clock_period_seconds(140.0).unwrap();
156        let mut t = 0.0;
157        c.on_pulse(t);
158        let mut last = None;
159        for _ in 0..8 {
160            t += period;
161            last = c.on_pulse(t);
162        }
163        let bpm = last.expect("estimate available");
164        assert!((bpm - 140.0).abs() < 1e-3, "got {bpm}");
165    }
166}