Skip to main content

qualia_audio/midi/smf/
tempo_map.rs

1//! Tempo map: tick ↔ seconds conversion for a parsed SMF.
2//!
3//! A [`TempoMap`] is the ordered list of tempo changes (absolute tick →
4//! microseconds-per-quarter) plus the file's [`Division`]. For metrical (PPQ)
5//! division, elapsed seconds are integrated piecewise across tempo segments; for
6//! SMPTE division the tick rate is fixed by the time-code and tempo is ignored.
7//! Cold path — this runs at load/analysis time, not in the audio callback.
8//!
9//! Lane AU-MIDI-FILE.
10
11use super::meta_event::MetaEvent;
12use super::read::{Division, SmfFile, TrackEvent};
13
14/// Default tempo before any tempo meta-event: 120 BPM = 500000 µs/quarter.
15pub const DEFAULT_US_PER_QUARTER: u32 = 500_000;
16
17/// One tempo change at an absolute tick position.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct TempoEntry {
20    /// Absolute tick (from the start of the sequence).
21    pub tick: u64,
22    /// Microseconds per quarter note in effect from this tick onward.
23    pub us_per_quarter: u32,
24}
25
26/// An ordered tempo map for one SMF, with its time division.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct TempoMap {
29    division: Division,
30    /// Tempo changes sorted by ascending tick. Always non-empty; a synthetic
31    /// entry at tick 0 with [`DEFAULT_US_PER_QUARTER`] is inserted if the file
32    /// declares no tempo at tick 0.
33    entries: Vec<TempoEntry>,
34}
35
36impl TempoMap {
37    /// Build a single-tempo map (useful for tests and tempo-less files).
38    pub fn constant(division: Division, us_per_quarter: u32) -> Self {
39        TempoMap {
40            division,
41            entries: vec![TempoEntry {
42                tick: 0,
43                us_per_quarter,
44            }],
45        }
46    }
47
48    /// The tempo entries, sorted by tick.
49    pub fn entries(&self) -> &[TempoEntry] {
50        &self.entries
51    }
52
53    /// Convert an absolute tick position to elapsed seconds from the start.
54    pub fn ticks_to_seconds(&self, tick: u64) -> f64 {
55        match self.division {
56            Division::Smpte {
57                fps,
58                ticks_per_frame,
59            } => {
60                let per_second = f64::from(fps) * f64::from(ticks_per_frame);
61                if per_second == 0.0 {
62                    0.0
63                } else {
64                    tick as f64 / per_second
65                }
66            }
67            Division::Ppq(ppq) => {
68                let ppq = f64::from(ppq.max(1));
69                let mut seconds = 0.0;
70                for i in 0..self.entries.len() {
71                    let seg_start = self.entries[i].tick;
72                    if seg_start >= tick {
73                        break;
74                    }
75                    let seg_end = self
76                        .entries
77                        .get(i + 1)
78                        .map(|e| e.tick.min(tick))
79                        .unwrap_or(tick);
80                    let seg_ticks = seg_end.saturating_sub(seg_start) as f64;
81                    let sec_per_tick =
82                        (f64::from(self.entries[i].us_per_quarter) / 1_000_000.0) / ppq;
83                    seconds += seg_ticks * sec_per_tick;
84                }
85                seconds
86            }
87        }
88    }
89
90    /// Convert elapsed seconds from the start to an absolute tick position
91    /// (rounded to the nearest tick).
92    pub fn seconds_to_ticks(&self, seconds: f64) -> u64 {
93        if seconds <= 0.0 {
94            return 0;
95        }
96        match self.division {
97            Division::Smpte {
98                fps,
99                ticks_per_frame,
100            } => {
101                let per_second = f64::from(fps) * f64::from(ticks_per_frame);
102                (seconds * per_second).round() as u64
103            }
104            Division::Ppq(ppq) => {
105                let ppq = f64::from(ppq.max(1));
106                let mut remaining = seconds;
107                for i in 0..self.entries.len() {
108                    let seg_start = self.entries[i].tick;
109                    let sec_per_tick =
110                        (f64::from(self.entries[i].us_per_quarter) / 1_000_000.0) / ppq;
111                    // Duration of this segment (until the next tempo change, or ∞).
112                    let seg_ticks = self
113                        .entries
114                        .get(i + 1)
115                        .map(|e| (e.tick - seg_start) as f64)
116                        .unwrap_or(f64::INFINITY);
117                    let seg_seconds = seg_ticks * sec_per_tick;
118                    if remaining <= seg_seconds || !seg_seconds.is_finite() {
119                        let ticks_in = if sec_per_tick > 0.0 {
120                            remaining / sec_per_tick
121                        } else {
122                            0.0
123                        };
124                        return seg_start + ticks_in.round() as u64;
125                    }
126                    remaining -= seg_seconds;
127                }
128                self.entries.last().map(|e| e.tick).unwrap_or(0)
129            }
130        }
131    }
132}
133
134/// Build a [`TempoMap`] from a parsed SMF.
135///
136/// Collects every tempo meta-event across all tracks (converting each track's
137/// per-track delta times to absolute ticks), sorts them by tick, and guarantees
138/// an entry at tick 0. For format-1 files tempo events conventionally live in
139/// track 0, but events found in any track are honoured.
140pub fn build_tempo_map(file: &SmfFile) -> TempoMap {
141    let mut entries: Vec<TempoEntry> = Vec::new();
142    for track in &file.tracks {
143        let mut abs_tick: u64 = 0;
144        for ev in &track.events {
145            abs_tick += u64::from(ev.delta_ticks);
146            if let TrackEvent::Meta(MetaEvent::Tempo(us)) = &ev.event {
147                entries.push(TempoEntry {
148                    tick: abs_tick,
149                    us_per_quarter: *us,
150                });
151            }
152        }
153    }
154    // Stable sort by tick; later-file-order wins ties (rare).
155    entries.sort_by_key(|e| e.tick);
156
157    // Guarantee a starting tempo at tick 0.
158    if entries.first().map(|e| e.tick) != Some(0) {
159        entries.insert(
160            0,
161            TempoEntry {
162                tick: 0,
163                us_per_quarter: DEFAULT_US_PER_QUARTER,
164            },
165        );
166    }
167
168    TempoMap {
169        division: file.division,
170        entries,
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::super::read::{Event, SmfFile, Track};
177    use super::*;
178
179    #[test]
180    fn golden_120bpm_480ppq_half_second() {
181        // 500000 µs/quarter (120 BPM), division 480 → 480 ticks == 0.5 s.
182        let map = TempoMap::constant(Division::Ppq(480), 500_000);
183        let s = map.ticks_to_seconds(480);
184        assert!((s - 0.5).abs() < 1e-9, "expected 0.5 s, got {s}");
185        // And back.
186        assert_eq!(map.seconds_to_ticks(0.5), 480);
187        // One whole quarter (480 ticks) at 120 BPM is 0.5 s; a full bar of 4 is 2 s.
188        assert!((map.ticks_to_seconds(480 * 4) - 2.0).abs() < 1e-9);
189    }
190
191    #[test]
192    fn tempo_change_midway() {
193        // 480 PPQ. 120 BPM for first 480 ticks (0.5 s), then 60 BPM (1e6 µs/q).
194        let map = TempoMap {
195            division: Division::Ppq(480),
196            entries: vec![
197                TempoEntry {
198                    tick: 0,
199                    us_per_quarter: 500_000,
200                },
201                TempoEntry {
202                    tick: 480,
203                    us_per_quarter: 1_000_000,
204                },
205            ],
206        };
207        // At tick 480: 0.5 s. At tick 960: 0.5 + (480 ticks @ 60 BPM = 1.0 s) = 1.5 s.
208        assert!((map.ticks_to_seconds(480) - 0.5).abs() < 1e-9);
209        assert!((map.ticks_to_seconds(960) - 1.5).abs() < 1e-9);
210        assert_eq!(map.seconds_to_ticks(1.5), 960);
211    }
212
213    #[test]
214    fn build_from_file_uses_default_when_no_tempo() {
215        let file = SmfFile {
216            format: 0,
217            division: Division::Ppq(96),
218            tracks: vec![Track { events: vec![] }],
219        };
220        let map = build_tempo_map(&file);
221        assert_eq!(
222            map.entries(),
223            &[TempoEntry {
224                tick: 0,
225                us_per_quarter: 500_000
226            }]
227        );
228    }
229
230    #[test]
231    fn build_from_file_collects_tempo_events() {
232        use super::super::read::TrackEvent;
233        let events = vec![
234            Event {
235                delta_ticks: 0,
236                event: TrackEvent::Meta(MetaEvent::Tempo(600_000)),
237            },
238            Event {
239                delta_ticks: 240,
240                event: TrackEvent::Meta(MetaEvent::Tempo(400_000)),
241            },
242        ];
243        let file = SmfFile {
244            format: 0,
245            division: Division::Ppq(480),
246            tracks: vec![Track { events }],
247        };
248        let map = build_tempo_map(&file);
249        assert_eq!(
250            map.entries(),
251            &[
252                TempoEntry {
253                    tick: 0,
254                    us_per_quarter: 600_000
255                },
256                TempoEntry {
257                    tick: 240,
258                    us_per_quarter: 400_000
259                },
260            ]
261        );
262    }
263
264    #[test]
265    fn smpte_division_is_tempo_independent() {
266        // 25 fps, 40 ticks/frame → 1000 ticks/second.
267        let map = TempoMap::constant(
268            Division::Smpte {
269                fps: 25,
270                ticks_per_frame: 40,
271            },
272            500_000,
273        );
274        assert!((map.ticks_to_seconds(1000) - 1.0).abs() < 1e-9);
275        assert_eq!(map.seconds_to_ticks(1.0), 1000);
276    }
277}