Skip to main content

qualia_audio/midi/sequencer/
ppq_clock.rs

1//! PPQ (pulses-per-quarter-note) tick ↔ musical time ↔ wall-clock time.
2//!
3//! A MIDI sequence measures time in *ticks*: there are `ppq` ticks in one
4//! quarter note (a "beat" in 4/4). At a tempo of `bpm` quarter notes per
5//! minute, one quarter note lasts `60 / bpm` seconds, so
6//!
7//! ```text
8//! seconds = (ticks / ppq) * (60 / bpm)
9//! ticks   = seconds * (bpm / 60) * ppq
10//! ```
11//!
12//! Both directions are pure functions with no allocation — safe on the hot
13//! path. Values are validated: `ppq` and `bpm` must be strictly positive.
14
15use crate::types::AudioError;
16
17/// Convert a PPQ tick count to seconds of wall-clock time at a given tempo.
18///
19/// `ppq` = ticks per quarter note (e.g. 480). `bpm` = quarter notes/minute.
20/// Returns [`AudioError::InvalidParameter`] if `ppq == 0` or `bpm <= 0`.
21#[inline]
22pub fn ticks_to_seconds(ticks: u64, ppq: u32, bpm: f64) -> Result<f64, AudioError> {
23    if ppq == 0 || !(bpm > 0.0) || !bpm.is_finite() {
24        return Err(AudioError::InvalidParameter);
25    }
26    Ok((ticks as f64 / ppq as f64) * (60.0 / bpm))
27}
28
29/// Convert seconds of wall-clock time to a fractional PPQ tick count.
30///
31/// Inverse of [`ticks_to_seconds`]. Returns a fractional tick position; callers
32/// that need an integer tick can round/floor. Returns
33/// [`AudioError::InvalidParameter`] if `ppq == 0`, `bpm <= 0`, or `seconds`
34/// is not finite/negative.
35#[inline]
36pub fn seconds_to_ticks(seconds: f64, ppq: u32, bpm: f64) -> Result<f64, AudioError> {
37    if ppq == 0 || !(bpm > 0.0) || !bpm.is_finite() || !seconds.is_finite() || seconds < 0.0 {
38        return Err(AudioError::InvalidParameter);
39    }
40    Ok(seconds * (bpm / 60.0) * ppq as f64)
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn golden_480_ticks_is_half_second_at_120bpm() {
49        let s = ticks_to_seconds(480, 480, 120.0).expect("valid");
50        assert!((s - 0.5).abs() < 1e-6, "got {s}");
51        let s2 = ticks_to_seconds(960, 480, 120.0).expect("valid");
52        assert!((s2 - 1.0).abs() < 1e-6, "got {s2}");
53    }
54
55    #[test]
56    fn round_trip_ticks_seconds() {
57        let t = seconds_to_ticks(0.5, 480, 120.0).expect("valid");
58        assert!((t - 480.0).abs() < 1e-6, "got {t}");
59        let t2 = seconds_to_ticks(1.0, 480, 120.0).expect("valid");
60        assert!((t2 - 960.0).abs() < 1e-6, "got {t2}");
61    }
62
63    #[test]
64    fn rejects_bad_params() {
65        assert_eq!(
66            ticks_to_seconds(1, 0, 120.0),
67            Err(AudioError::InvalidParameter)
68        );
69        assert_eq!(
70            ticks_to_seconds(1, 480, 0.0),
71            Err(AudioError::InvalidParameter)
72        );
73        assert_eq!(
74            seconds_to_ticks(-1.0, 480, 120.0),
75            Err(AudioError::InvalidParameter)
76        );
77    }
78}