Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_io/cd/
xa_clock.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! A song clock for XA-ADPCM music: where the playing song is, in
3//! milliseconds, every frame, for beat sync, spectrum bars and rhythm games.
4//!
5//! The XA player has no sample counter to read. What the drive can say is
6//! which sector its head is in ([`Player::poll`] asks with GetlocP), and a
7//! song's sectors stream at a fixed rate (75 a second at single speed, 150
8//! at double), so the head's place in the file *is* the song's time. The
9//! clock turns that coarse, occasional reading into a smooth one the way
10//! [`PlaybackClock`] does for CD-DA: it anchors on the reading and advances
11//! with the caller's own tick counter in between, so the drive is asked
12//! rarely (once per 15 to 30 ticks is plenty) and the display and CD
13//! oscillators cannot drift apart for long.
14//!
15//! ```ignore
16//! let mut clock = SongClock::new(60);
17//! // once per tick:
18//! player.poll();                               // or every 15..30 ticks
19//! if let Some(ms) = clock.update(&player, tick) {
20//!     // ms into the song file, smooth and never backwards
21//! }
22//! ```
23//!
24//! # Precision
25//!
26//! These are the errors this module can account for. All of them are reasoned
27//! from how the clock works and checked against a simulated drive in the unit
28//! tests; none is measured on a console.
29//!
30//! * **Sector quantum, 13.3 ms at single speed (6.7 ms at double).** The
31//!   head reading is a whole sector. The clock takes the middle of it, so
32//!   the error is at most half a sector either way (6.7 ms), and zero on
33//!   average.
34//! * **Tick granularity.** The anchor is stamped with the tick of the call,
35//!   but the drive answers some milliseconds into the frame. Allow up to one
36//!   tick (16.7 ms at 60 Hz) on top, one-sided: the clock reads slightly
37//!   early. Call [`SongClock::update`] right after `poll`, at the same place
38//!   in the frame every time, so the offset is constant.
39//! * **Drift.** Between readings the clock runs on the tick counter. The
40//!   display and CD crystals differ by well under 0.1 percent, so 30 ticks
41//!   (half a second) drift a fraction of a millisecond, and every reading
42//!   re-anchors it. Nothing accumulates over a song.
43//! * **Never backwards.** Small corrections only move the clock forward and
44//!   large ones are held until a second reading agrees (the
45//!   [`PlaybackClock`] policy), so the output does not step back inside one
46//!   run of the song. A loop or a resume starts a new run.
47//! * **Head versus sound: not known.** The drive reads ahead of what the
48//!   speakers play. The sector the head is in is decoded and queued at the
49//!   SPU, which then needs time to play it out. The player's own doc says
50//!   "a sector or two", and the XA decoder works in 4-sector groups, so a
51//!   constant offset up to roughly 55 ms is plausible. Nothing in this crate
52//!   can observe it and the emulator does not model it. It has to be
53//!   measured on the console (the hardware-test suite's XA clock step is
54//!   there for that) and put in with [`SongClock::with_head_lead_ms`]. Until
55//!   then the clock reports where the *head* is, and the sound is behind it
56//!   by that unmeasured amount.
57//!
58//! So: the clock is ahead of the sound by the unmeasured head lead, and
59//! otherwise within about 7 ms either way plus up to 17 ms early. Rhythm
60//! timing windows in the tens of milliseconds (gh-psx uses plus or minus
61//! 90 ms) fit with a margin; sample-accurate sync does not.
62//!
63//! # What would sharpen it
64//!
65//! The SPU writes the CD input it is playing into its capture buffer in SPU
66//! RAM, and that write position moves every 22.7 microseconds. Reading it
67//! would pin the phase inside a sector. It is not used: reaching it needs an
68//! SPU IRQ address or a RAM read-back that nothing in this SDK has proved on
69//! silicon, and a 90 ms window does not need it. A per-sector interrupt (the
70//! Report mode bit) would timestamp each sector boundary but needs a CD
71//! interrupt handler, which the polled players avoid. Both are options if a
72//! game ever needs under 10 ms.
73
74use super::audio::PlaybackClock;
75use super::xa::{HeadSample, Player};
76
77/// Smooth, monotonic song time for the XA song a [`Player`] is playing.
78pub struct SongClock {
79    clock: PlaybackClock,
80    epoch: Option<u32>,
81    serial: u32,
82    head_lead_ms: i32,
83}
84
85impl SongClock {
86    /// A clock for a tick counter running at `ticks_hz` (60 NTSC, 50 PAL).
87    pub const fn new(ticks_hz: u32) -> Self {
88        Self {
89            clock: PlaybackClock::new(ticks_hz),
90            epoch: None,
91            serial: 0,
92            head_lead_ms: 0,
93        }
94    }
95
96    /// Subtract `ms` from every reading: how far the drive head is ahead of
97    /// the sound you hear. Measured on a console, not derived (see the module
98    /// docs); negative moves the other way. Also the place for a
99    /// player-facing audio latency setting.
100    pub const fn with_head_lead_ms(mut self, ms: i32) -> Self {
101        self.head_lead_ms = ms;
102        self
103    }
104
105    /// Song time in milliseconds at `now_tick`, from the newest reading
106    /// `player` holds. Call it every tick, after [`Player::poll`]. `None`
107    /// while the song is not streaming (starting, seeking after a loop or a
108    /// resume, suspended, stopped); the clock restarts from the first
109    /// reading of each new run.
110    pub fn update(&mut self, player: &Player, now_tick: u32) -> Option<u32> {
111        self.update_with(player.head_sample(), now_tick)
112    }
113
114    fn update_with(&mut self, sample: Option<HeadSample>, now_tick: u32) -> Option<u32> {
115        let sample = sample?;
116        let reading = sample.centre_millis();
117        let ms = if self.epoch != Some(sample.epoch) {
118            self.epoch = Some(sample.epoch);
119            self.serial = sample.serial;
120            self.clock.start_at(now_tick, reading);
121            reading
122        } else if sample.serial != self.serial {
123            self.serial = sample.serial;
124            self.clock.observe(now_tick, Some(reading))
125        } else {
126            self.clock.observe(now_tick, None)
127        };
128        Some(if self.head_lead_ms >= 0 {
129            ms.saturating_sub(self.head_lead_ms as u32)
130        } else {
131            ms.saturating_add(self.head_lead_ms.unsigned_abs())
132        })
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    const SPS: u32 = 75;
141
142    /// The sample the drive gives at true song time `true_ms`: the sector the
143    /// time falls in.
144    fn sample(epoch: u32, serial: u32, true_ms: u32) -> HeadSample {
145        HeadSample {
146            epoch,
147            serial,
148            sector: true_ms * SPS / 1000,
149            sectors_per_second: SPS,
150        }
151    }
152
153    #[test]
154    fn a_head_sample_is_centred_in_its_sector() {
155        let s = HeadSample {
156            epoch: 1,
157            serial: 1,
158            sector: 3,
159            sectors_per_second: 75,
160        };
161        assert_eq!(s.millis(), 40);
162        assert_eq!(s.centre_millis(), 46);
163        let d = HeadSample {
164            sectors_per_second: 150,
165            ..s
166        };
167        assert_eq!(d.millis(), 20);
168        assert_eq!(d.centre_millis(), 23);
169    }
170
171    #[test]
172    fn nothing_is_reported_before_the_song_streams() {
173        let mut clock = SongClock::new(60);
174        assert_eq!(clock.update_with(None, 5), None);
175    }
176
177    /// The song starts mid-run on the tick counter; the drive is read every
178    /// 30 ticks and answers in whole sectors. The output follows the true
179    /// time to within half a sector plus a tick, never steps back, and does
180    /// not drift over three minutes even though the tick counter runs 0.05
181    /// percent slow against the song.
182    #[test]
183    fn follows_true_time_within_a_sector_and_a_tick_without_drift() {
184        let mut clock = SongClock::new(60);
185        let start_tick = 100;
186        let mut serial = 0;
187        let mut previous = 0;
188        let mut worst = 0i32;
189        for tick in start_tick..start_tick + 60 * 180 {
190            // True song time at this tick; the song runs 0.05 percent ahead
191            // of the tick counter.
192            let true_ms = ((tick - start_tick) as u64 * 1000 / 60 * 10_005 / 10_000) as u32;
193            if (tick - start_tick) % 30 == 3 {
194                serial += 1;
195            }
196            let ms = clock
197                .update_with(Some(sample(1, serial, true_ms)), tick)
198                .expect("streaming");
199            assert!(ms >= previous, "tick {tick}: {ms} after {previous}");
200            previous = ms;
201            worst = worst.max((ms as i32 - true_ms as i32).abs());
202        }
203        // Half a sector (7), one tick (17), the 30-tick drift of 0.05
204        // percent (under 10) and rounding.
205        assert!(worst <= 7 + 17 + 10 + 2, "worst error {worst} ms");
206    }
207
208    #[test]
209    fn a_new_epoch_restarts_the_clock_and_forgets_the_old_floor() {
210        let mut clock = SongClock::new(60);
211        clock.update_with(Some(sample(1, 1, 50_000)), 10);
212        let late = clock.update_with(Some(sample(1, 1, 50_000)), 70).unwrap();
213        assert!(late >= 50_900, "{late}");
214        // A loop: the new epoch's first reading is near the top.
215        let top = clock.update_with(Some(sample(2, 5, 40)), 71).unwrap();
216        assert!(top < 100, "restarted at {top}");
217        let a_second_on = clock.update_with(Some(sample(2, 5, 40)), 131).unwrap();
218        assert!((a_second_on - top).abs_diff(1000) <= 17, "{a_second_on}");
219    }
220
221    #[test]
222    fn head_lead_is_subtracted_and_floors_at_zero() {
223        let mut clock = SongClock::new(60).with_head_lead_ms(30);
224        assert_eq!(clock.update_with(Some(sample(1, 1, 0)), 0), Some(0));
225        let mut clock = SongClock::new(60).with_head_lead_ms(-20);
226        assert_eq!(clock.update_with(Some(sample(1, 1, 0)), 0), Some(26));
227    }
228}