Skip to main content

qualia_audio/midi/sequencer/
time_signature.rs

1//! Time-signature representation and bars/beats/ticks conversion.
2//!
3//! A [`TimeSignature`] is `numerator/denominator` (e.g. `4/4`, `6/8`). The
4//! sequencer measures absolute time in PPQ ticks (ticks per quarter note); this
5//! module maps an absolute tick position to a musical [`BarBeatTick`] address
6//! and back.
7//!
8//! One "beat" is one note of the denominator's value: a quarter note in `4/4`,
9//! an eighth note in `6/8`. Since PPQ counts ticks per *quarter* note, a beat
10//! spans `ppq * 4 / denominator` ticks. All fields are 0-indexed (bar 0, beat 0,
11//! tick 0 is the downbeat of the first bar); add 1 for musician-facing display.
12
13use crate::types::AudioError;
14
15/// A musical time signature `numerator/denominator`.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct TimeSignature {
18    /// Beats per bar (top number). Must be ≥ 1.
19    pub numerator: u16,
20    /// Beat unit as a note value (bottom number): 1, 2, 4, 8, 16, 32… Must be ≥ 1.
21    pub denominator: u16,
22}
23
24/// A musical position as (bar, beat, tick), all 0-indexed.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct BarBeatTick {
27    /// Bar index from the start of the timeline (0 = first bar).
28    pub bar: u64,
29    /// Beat within the bar (0 = downbeat), `0 ..= numerator-1`.
30    pub beat: u32,
31    /// Tick within the beat, `0 ..= ticks_per_beat-1`.
32    pub tick: u32,
33}
34
35impl TimeSignature {
36    /// Common time, `4/4`.
37    pub const COMMON: TimeSignature = TimeSignature {
38        numerator: 4,
39        denominator: 4,
40    };
41
42    /// Construct, validating that both numbers are ≥ 1.
43    pub fn new(numerator: u16, denominator: u16) -> Result<Self, AudioError> {
44        if numerator == 0 || denominator == 0 {
45            return Err(AudioError::InvalidParameter);
46        }
47        Ok(Self {
48            numerator,
49            denominator,
50        })
51    }
52
53    /// Ticks in one beat (one denominator-note) at the given PPQ.
54    ///
55    /// Errors if `ppq == 0`, the signature is malformed, or the denominator
56    /// does not divide `ppq * 4` evenly (which would lose tick precision).
57    pub fn ticks_per_beat(self, ppq: u32) -> Result<u32, AudioError> {
58        if ppq == 0 || self.numerator == 0 || self.denominator == 0 {
59            return Err(AudioError::InvalidParameter);
60        }
61        let quarter_times_four = (ppq as u64) * 4;
62        if quarter_times_four % self.denominator as u64 != 0 {
63            return Err(AudioError::InvalidParameter);
64        }
65        Ok((quarter_times_four / self.denominator as u64) as u32)
66    }
67
68    /// Ticks in one full bar at the given PPQ.
69    pub fn ticks_per_bar(self, ppq: u32) -> Result<u64, AudioError> {
70        let tpb = self.ticks_per_beat(ppq)? as u64;
71        Ok(tpb * self.numerator as u64)
72    }
73
74    /// Map an absolute tick position to a (bar, beat, tick) address.
75    pub fn ticks_to_bbt(self, ticks: u64, ppq: u32) -> Result<BarBeatTick, AudioError> {
76        let tpb = self.ticks_per_beat(ppq)? as u64;
77        let tpbar = tpb * self.numerator as u64;
78        let bar = ticks / tpbar;
79        let rem = ticks % tpbar;
80        let beat = (rem / tpb) as u32;
81        let tick = (rem % tpb) as u32;
82        Ok(BarBeatTick { bar, beat, tick })
83    }
84
85    /// Map a (bar, beat, tick) address back to an absolute tick position.
86    ///
87    /// Errors if `beat` is not within the bar or `tick` overflows a beat.
88    pub fn bbt_to_ticks(self, pos: BarBeatTick, ppq: u32) -> Result<u64, AudioError> {
89        let tpb = self.ticks_per_beat(ppq)? as u64;
90        if pos.beat as u64 >= self.numerator as u64 || pos.tick as u64 >= tpb {
91            return Err(AudioError::InvalidParameter);
92        }
93        Ok(pos.bar * tpb * self.numerator as u64 + pos.beat as u64 * tpb + pos.tick as u64)
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn four_four_at_480() {
103        let ts = TimeSignature::COMMON;
104        assert_eq!(ts.ticks_per_beat(480).unwrap(), 480);
105        assert_eq!(ts.ticks_per_bar(480).unwrap(), 1920);
106    }
107
108    #[test]
109    fn six_eight_beat_is_eighth_note() {
110        let ts = TimeSignature::new(6, 8).unwrap();
111        assert_eq!(ts.ticks_per_beat(480).unwrap(), 240);
112        assert_eq!(ts.ticks_per_bar(480).unwrap(), 1440);
113    }
114
115    #[test]
116    fn bbt_round_trip() {
117        let ts = TimeSignature::COMMON;
118        // Bar 2, beat 3, tick 100 in 4/4 @480: 2*1920 + 3*480 + 100 = 5380
119        let pos = BarBeatTick {
120            bar: 2,
121            beat: 3,
122            tick: 100,
123        };
124        let ticks = ts.bbt_to_ticks(pos, 480).unwrap();
125        assert_eq!(ticks, 5380);
126        assert_eq!(ts.ticks_to_bbt(ticks, 480).unwrap(), pos);
127    }
128
129    #[test]
130    fn rejects_out_of_range() {
131        let ts = TimeSignature::COMMON;
132        assert!(TimeSignature::new(0, 4).is_err());
133        assert!(ts
134            .bbt_to_ticks(
135                BarBeatTick {
136                    bar: 0,
137                    beat: 4,
138                    tick: 0
139                },
140                480
141            )
142            .is_err());
143        assert!(ts
144            .bbt_to_ticks(
145                BarBeatTick {
146                    bar: 0,
147                    beat: 0,
148                    tick: 480
149                },
150                480
151            )
152            .is_err());
153    }
154}