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

psx_io/cd/
xa.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! XA-ADPCM music: stream one channel of an interleaved XA file through the
3//! drive's own decoder to the SPU's CD input.
4//!
5//! The encoder side is `psx-audio-cook xa-encode`; `docs/XA-MUSIC.md` has the
6//! workflow. A song file holds several songs as interleaved channels (every
7//! fourth sector for four 37.8 kHz stereo songs at single speed). With
8//! XA-ADPCM and the file/channel filter switched on, the drive hands the
9//! sectors of the chosen channel to its decoder and drops the rest; the CPU
10//! never sees the audio.
11//!
12//! # The drive is busy while music plays
13//!
14//! Music is a read: the drive streams the file continuously, so the CPU
15//! cannot read data from the disc meanwhile, not even at the same time at the
16//! same speed (the laser follows the file, not the data). Load first, then
17//! start the song, or lend the drive for the load with
18//! [`Player::with_cd_suspended`] and [`Player::resume`] afterwards (a seek
19//! back to where the song was), or stop it and start it again (it restarts
20//! from the top). Streaming data and music together needs the data
21//! interleaved into the filler slots of the song file, which this player does
22//! not do.
23//!
24//! # Polling
25//!
26//! The player is poll-driven like [`super::audio`]: call [`Player::poll`]
27//! about once per frame. It asks the drive where the head is, and when the
28//! head reaches the end of the song file it either restarts the file
29//! (looping) or pauses the drive. A restart is a seek, so a loop has an
30//! audible gap whose length is the drive's seek time; authoring the loop
31//! point into a quiet passage hides it.
32
33use super::PlayPosition;
34use crate::disc_base::shift_lba;
35use crate::periph::Cd;
36use psx_hw::cd::xa::{END_GUARD_SECTORS, SECTORS_PER_SECOND};
37use psx_hw::cd::{CMD_READS, CMD_SETFILTER, MODE_DOUBLE_SPEED, MODE_XA_ADPCM, MODE_XA_FILTER};
38
39/// Per-command response spin budget: generous, the drive answers far sooner.
40pub const COMMAND_SPINS: u32 = 131_072;
41/// Spin budget for a pause to finish (the drive spends up to about a tenth
42/// of a second stopping a read).
43const PAUSE_SPINS: u32 = 2_000_000;
44
45/// Speed the song file was interleaved for (`psx-audio-cook xa-encode --speed`).
46#[derive(Copy, Clone, Debug, PartialEq, Eq)]
47pub enum DriveSpeed {
48    /// 75 sectors per second.
49    Single,
50    /// 150 sectors per second.
51    Double,
52}
53
54impl DriveSpeed {
55    const fn sectors_per_second(self) -> u32 {
56        match self {
57            DriveSpeed::Single => SECTORS_PER_SECOND,
58            DriveSpeed::Double => 2 * SECTORS_PER_SECOND,
59        }
60    }
61
62    const fn mode(self) -> u8 {
63        let speed = match self {
64            DriveSpeed::Single => 0,
65            DriveSpeed::Double => MODE_DOUBLE_SPEED,
66        };
67        MODE_XA_ADPCM | MODE_XA_FILTER | speed
68    }
69}
70
71/// An interleaved XA file on the disc.
72#[derive(Copy, Clone, Debug, PartialEq, Eq)]
73pub struct File {
74    lba: u32,
75    sector_count: u32,
76    number: u8,
77    speed: DriveSpeed,
78}
79
80impl File {
81    /// A file at `lba` (relative to this program's disc image, see
82    /// [`crate::disc_base`]) of `sector_count` sectors, including the end
83    /// guard `mkisopsx` keeps. `number` and `speed` come from the encoder's
84    /// manifest.
85    pub const fn new(lba: u32, sector_count: u32, number: u8, speed: DriveSpeed) -> Self {
86        Self {
87            lba,
88            sector_count,
89            number,
90            speed,
91        }
92    }
93
94    /// A file from its ISO 9660 directory record: first LBA and size in
95    /// bytes (a whole number of 2048-byte sectors for an XA file).
96    pub const fn from_directory_entry(
97        lba: u32,
98        size_bytes: u32,
99        number: u8,
100        speed: DriveSpeed,
101    ) -> Self {
102        Self::new(lba, size_bytes / 2048, number, speed)
103    }
104
105    /// Channel `channel` of this file as a song.
106    pub const fn song(self, channel: u8) -> Song {
107        Song {
108            file: self,
109            channel,
110        }
111    }
112
113    /// Sectors the songs span, without the end guard.
114    pub const fn span_sector_count(self) -> u32 {
115        self.sector_count.saturating_sub(END_GUARD_SECTORS)
116    }
117}
118
119/// One channel of an [`File`].
120#[derive(Copy, Clone, Debug, PartialEq, Eq)]
121pub struct Song {
122    file: File,
123    channel: u8,
124}
125
126/// The step of starting a song that the drive refused.
127#[derive(Copy, Clone, Debug, PartialEq, Eq)]
128pub enum Error {
129    /// Demute did not answer.
130    Unmute,
131    /// Setmode did not answer.
132    SetMode,
133    /// Setfilter did not answer.
134    SetFilter,
135    /// Setloc did not answer.
136    Seek,
137    /// ReadS did not answer.
138    Read,
139}
140
141/// The drive refused Pause, as it does during the seek at the start of a
142/// read. Keep polling and try again.
143#[derive(Copy, Clone, Debug, PartialEq, Eq)]
144pub struct PauseRefused;
145
146/// What [`Player::poll`] saw.
147#[derive(Copy, Clone, Debug, PartialEq, Eq)]
148pub enum Event {
149    /// No song is playing.
150    Idle,
151    /// A song is playing (or its start is still seeking).
152    Playing,
153    /// The song reached its end and restarted from the top.
154    Looped,
155    /// The song reached its end and the drive was paused.
156    Finished,
157}
158
159/// One reading of the drive head inside the playing song, taken by
160/// [`Player::poll`].
161#[derive(Copy, Clone, Debug, PartialEq, Eq)]
162pub struct HeadSample {
163    /// Changes whenever a read starts (a start, a loop or a resume): readings
164    /// of different epochs do not belong to one run of the song.
165    pub epoch: u32,
166    /// Changes with every new reading in the same epoch.
167    pub serial: u32,
168    /// The sector the head was in, counted from the top of the song file.
169    pub sector: u32,
170    /// Sectors the drive reads per second at the file's speed (75 or 150).
171    pub sectors_per_second: u32,
172}
173
174impl HeadSample {
175    /// Start of the head's sector, in milliseconds since the top of the file.
176    ///
177    /// `floor(sector * 1000 / sectors_per_second)`, wrapped to `u32` exactly
178    /// as the former `u64` expression was, in 32-bit operations: the sector
179    /// splits into whole seconds of sectors and a remainder below
180    /// `sectors_per_second`, so the remainder term is at most 150 * 1000.
181    pub const fn millis(self) -> u32 {
182        let whole = self.sector / self.sectors_per_second;
183        let part = self.sector % self.sectors_per_second;
184        whole
185            .wrapping_mul(1000)
186            .wrapping_add(part * 1000 / self.sectors_per_second)
187    }
188
189    /// Middle of the head's sector, in milliseconds: the head was somewhere
190    /// in the sector, so this is the reading with the least expected error
191    /// (half a sector, 6.7 ms at single speed).
192    ///
193    /// `floor((2 * sector + 1) * 500 / sectors_per_second)`, which is
194    /// `floor((sector * 1000 + 500) / sectors_per_second)`, split like
195    /// [`Self::millis`] so no product exceeds 32 bits.
196    pub const fn centre_millis(self) -> u32 {
197        let whole = self.sector / self.sectors_per_second;
198        let part = self.sector % self.sectors_per_second;
199        whole
200            .wrapping_mul(1000)
201            .wrapping_add((part * 1000 + 500) / self.sectors_per_second)
202    }
203}
204
205/// The drive commands the player needs, so the state machine can run against
206/// a model on the host.
207trait Drive {
208    fn unmute(&mut self) -> bool;
209    fn set_mode(&mut self, mode: u8) -> bool;
210    fn set_filter(&mut self, file: u8, channel: u8) -> bool;
211    fn set_target(&mut self, lba: u32) -> bool;
212    fn start_streaming(&mut self) -> bool;
213    /// Pause the drive and wait for it; `false` if the drive refused (it
214    /// does during the seek at the start of a read).
215    fn pause(&mut self) -> bool;
216    /// Absolute LBA the head is reading, if the drive answers.
217    fn head_lba(&mut self) -> Option<u32>;
218}
219
220impl Drive for Cd {
221    fn unmute(&mut self) -> bool {
222        self.try_unmute(COMMAND_SPINS).is_some()
223    }
224    fn set_mode(&mut self, mode: u8) -> bool {
225        self.try_set_mode(mode, COMMAND_SPINS).is_some()
226    }
227    fn set_filter(&mut self, file: u8, channel: u8) -> bool {
228        self.try_command(CMD_SETFILTER, &[file, channel], COMMAND_SPINS)
229            .is_some()
230    }
231    fn set_target(&mut self, lba: u32) -> bool {
232        self.try_set_target_lba(lba, COMMAND_SPINS).is_some()
233    }
234    fn start_streaming(&mut self) -> bool {
235        self.try_command(CMD_READS, &[], COMMAND_SPINS).is_some()
236    }
237    fn pause(&mut self) -> bool {
238        self.try_pause_until_complete(PAUSE_SPINS)
239    }
240    fn head_lba(&mut self) -> Option<u32> {
241        let position = PlayPosition::parse(&self.try_play_position(COMMAND_SPINS)?)?;
242        let frames = (position.absolute_min as u32 * 60 + position.absolute_sec as u32) * 75
243            + position.absolute_frame as u32;
244        // The drive counts from the start of the lead-in, two seconds before LBA 0.
245        frames.checked_sub(150)
246    }
247}
248
249#[derive(Copy, Clone, Debug, PartialEq, Eq)]
250enum State {
251    Idle,
252    /// Started; the head has not been seen inside the file yet. The drive
253    /// reports its old position until the seek lands, so an end test now
254    /// would fire on the previous run's position.
255    Seeking,
256    Streaming,
257}
258
259struct Engine {
260    state: State,
261    song: Option<Song>,
262    looping: bool,
263    /// A pause was refused; try again at the next poll.
264    pause_pending: bool,
265    suspended: bool,
266    suspend_pending: bool,
267    /// Absolute LBA of the top of the song file.
268    start_lba: u32,
269    /// Where the last read was aimed: the top of the file for a start or a
270    /// loop, the saved position for a resume.
271    target_lba: u32,
272    head_lba: u32,
273    /// Where a suspended song continues, fixed when the pause is accepted.
274    resume_lba: u32,
275    /// Counts reads started (start, loop, resume): a new epoch means the
276    /// head readings before it say nothing about the ones after.
277    epoch: u32,
278    /// Counts head readings taken while streaming, so a clock can tell a
279    /// fresh reading from the one it already used.
280    head_serial: u32,
281}
282
283impl Engine {
284    const fn new() -> Self {
285        Self {
286            state: State::Idle,
287            song: None,
288            looping: false,
289            pause_pending: false,
290            suspended: false,
291            suspend_pending: false,
292            start_lba: 0,
293            target_lba: 0,
294            head_lba: 0,
295            resume_lba: 0,
296            epoch: 0,
297            head_serial: 0,
298        }
299    }
300
301    fn start(&mut self, drive: &mut impl Drive, song: Song, looping: bool) -> Result<(), Error> {
302        self.suspended = false;
303        self.suspend_pending = false;
304        let file = song.file;
305        let result = (|| {
306            if !drive.unmute() {
307                return Err(Error::Unmute);
308            }
309            if !drive.set_mode(file.speed.mode()) {
310                return Err(Error::SetMode);
311            }
312            if !drive.set_filter(file.number, song.channel) {
313                return Err(Error::SetFilter);
314            }
315            self.begin_read(drive, song)
316        })();
317        if result.is_ok() {
318            self.song = Some(song);
319            self.looping = looping;
320        } else {
321            self.state = State::Idle;
322            self.song = None;
323        }
324        result
325    }
326
327    /// Seek to the top of the file and start streaming.
328    fn begin_read(&mut self, drive: &mut impl Drive, song: Song) -> Result<(), Error> {
329        let top = shift_lba(song.file.lba);
330        self.begin_read_at(drive, top, top)
331    }
332
333    /// Seek to `at` (an absolute LBA inside the song file whose top is `top`)
334    /// and start streaming.
335    fn begin_read_at(&mut self, drive: &mut impl Drive, top: u32, at: u32) -> Result<(), Error> {
336        if !drive.set_target(at) {
337            return Err(Error::Seek);
338        }
339        if !drive.start_streaming() {
340            return Err(Error::Read);
341        }
342        self.start_lba = top;
343        self.target_lba = at;
344        self.head_lba = at;
345        self.pause_pending = false;
346        self.state = State::Seeking;
347        self.epoch = self.epoch.wrapping_add(1);
348        Ok(())
349    }
350
351    /// Pause a running drive. The drive refuses a pause during the seek that
352    /// starts a read, so a refused pause is retried by [`Self::poll`].
353    fn stop(&mut self, drive: &mut impl Drive) {
354        self.suspended = false;
355        self.suspend_pending = false;
356        if self.state != State::Idle {
357            self.pause_pending = !drive.pause();
358        }
359        self.state = State::Idle;
360        self.song = None;
361    }
362
363    fn suspend(&mut self, drive: &mut impl Drive) -> bool {
364        if self.state == State::Idle || self.suspended {
365            return true;
366        }
367        self.suspended = drive.pause();
368        self.suspend_pending = !self.suspended;
369        if self.suspended {
370            self.note_resume_position(drive);
371        }
372        self.suspended
373    }
374
375    /// Fix where a resume continues, now that the pause is accepted and the
376    /// head holds still. A poll may be a long time old (a game that polls
377    /// only near the end of a song never refreshed it), so ask the drive
378    /// once more; if it does not answer, fall back to the last position the
379    /// poll saw, or to the seek target when no poll ever saw the head.
380    fn note_resume_position(&mut self, drive: &mut impl Drive) {
381        let Some(song) = self.song else {
382            return;
383        };
384        let end = self.start_lba + song.file.span_sector_count();
385        if let Some(head) = drive.head_lba() {
386            if (self.target_lba..end).contains(&head) {
387                self.state = State::Streaming;
388                self.head_lba = head;
389                self.resume_lba = head;
390                return;
391            }
392        }
393        self.resume_lba = if self.state == State::Streaming {
394            self.head_lba
395        } else {
396            self.target_lba
397        };
398    }
399
400    /// Continue a suspended song. Anything may have happened to the drive
401    /// since the pause (a data read rewrites the mode, the head sits at the
402    /// data), so every setting is sent again, in the order a start sends
403    /// them, and the read is aimed at the saved position, not left to wherever
404    /// the controller stopped. A refused step leaves the song suspended.
405    fn resume(&mut self, drive: &mut impl Drive) -> Result<(), Error> {
406        if self.suspended {
407            if let Some(song) = self.song {
408                let file = song.file;
409                if !drive.unmute() {
410                    return Err(Error::Unmute);
411                }
412                if !drive.set_mode(file.speed.mode()) {
413                    return Err(Error::SetMode);
414                }
415                if !drive.set_filter(file.number, song.channel) {
416                    return Err(Error::SetFilter);
417                }
418                self.begin_read_at(drive, self.start_lba, self.resume_lba)?;
419            }
420            self.suspended = false;
421        }
422        // A refused Pause left the original read active. Cancel its retry
423        // without starting another read or changing the pending seek.
424        self.suspend_pending = false;
425        Ok(())
426    }
427
428    fn poll(&mut self, drive: &mut impl Drive) -> Event {
429        let Some(song) = self.song else {
430            if self.pause_pending {
431                self.pause_pending = !drive.pause();
432            }
433            return Event::Idle;
434        };
435        if self.suspend_pending {
436            self.suspend(drive);
437        }
438        if self.suspended || self.suspend_pending {
439            return Event::Playing;
440        }
441        let end = self.start_lba + song.file.span_sector_count();
442        if let Some(head) = drive.head_lba() {
443            if self.state == State::Seeking && (self.target_lba..end).contains(&head) {
444                self.state = State::Streaming;
445            }
446            if self.state == State::Streaming {
447                self.head_lba = head;
448                self.head_serial = self.head_serial.wrapping_add(1);
449            }
450            if self.state == State::Streaming && head >= end {
451                return self.reach_end(drive, song);
452            }
453        }
454        Event::Playing
455    }
456
457    fn is_streaming(&self) -> bool {
458        self.state == State::Streaming && !self.suspended && !self.suspend_pending
459    }
460
461    fn elapsed_millis(&self) -> u32 {
462        let Some(song) = self.song else {
463            return 0;
464        };
465        let sectors = self.head_lba.saturating_sub(self.start_lba);
466        sectors * 1000 / song.file.speed.sectors_per_second()
467    }
468
469    fn head_sample(&self) -> Option<HeadSample> {
470        if !self.is_streaming() {
471            return None;
472        }
473        Some(HeadSample {
474            epoch: self.epoch,
475            serial: self.head_serial,
476            sector: self.head_lba.saturating_sub(self.start_lba),
477            sectors_per_second: self.song?.file.speed.sectors_per_second(),
478        })
479    }
480
481    fn reach_end(&mut self, drive: &mut impl Drive, song: Song) -> Event {
482        if self.looping && self.begin_read(drive, song).is_ok() {
483            return Event::Looped;
484        }
485        self.stop(drive);
486        Event::Finished
487    }
488}
489
490/// Plays XA-ADPCM songs. Owns the CD token: nothing else drives the
491/// controller while a player exists.
492pub struct Player {
493    cd: Cd,
494    engine: Engine,
495}
496
497impl Player {
498    /// A player with nothing playing. The SPU's CD input must be on and have
499    /// a volume (`psx_spu::enable_cd_audio`, `psx_spu::set_cd_volume`), and
500    /// the drive's own mixer must pass audio ([`set_volume`](Self::set_volume)).
501    pub const fn new(cd: Cd) -> Self {
502        Self {
503            cd,
504            engine: Engine::new(),
505        }
506    }
507
508    /// Stop and give the token back.
509    pub fn release(mut self) -> Cd {
510        self.stop();
511        self.cd
512    }
513
514    /// Start `song` from the top (or restart it). With `looping` it
515    /// restarts by itself when [`poll`](Self::poll) sees it end. Blocks for
516    /// the five drive commands, a few milliseconds on a warm drive.
517    pub fn play(&mut self, song: Song, looping: bool) -> Result<(), Error> {
518        self.engine.start(&mut self.cd, song, looping)
519    }
520
521    /// Pause the drive and forget the song. Waits for the drive to settle.
522    pub fn stop(&mut self) {
523        self.engine.stop(&mut self.cd);
524    }
525
526    /// Suspend the current song without releasing the CD token or forgetting
527    /// its filter, looping policy or elapsed position. Returns false when the
528    /// drive refuses Pause during a seek; keep polling to retry it.
529    /// An idle player or an already suspended song returns true.
530    pub fn suspend(&mut self) -> bool {
531        self.engine.suspend(&mut self.cd)
532    }
533
534    /// Continue a suspended song where it stopped. Safe after the drive was
535    /// used for something else in between (see
536    /// [`with_cd_suspended`](Self::with_cd_suspended)): it sends Demute,
537    /// Setmode (XA, filter and the file's speed), Setfilter (the file and
538    /// channel) and Setloc to the position the pause left, then ReadS, the
539    /// same steps [`play`](Self::play) takes except that it aims at the saved
540    /// position and not at the top. Costs a short seek.
541    ///
542    /// The position is the head at the pause, read back from the drive, so
543    /// the music continues within about one sector of where it stopped. A
544    /// channel gets one of its sectors every few sectors of the file (every
545    /// fourth for four 37.8 kHz stereo songs, 53 ms of sound each), so the
546    /// first sector after a resume can repeat or skip up to that much sound.
547    /// This is not a sample-exact cursor.
548    ///
549    /// A refused step returns its [`Error`] and leaves the song suspended for
550    /// an explicit retry. Cancels a still-pending suspension; idle and
551    /// running players are no-ops.
552    pub fn resume(&mut self) -> Result<(), Error> {
553        self.engine.resume(&mut self.cd)
554    }
555
556    /// Lend the drive to `f` while the song is suspended, for a data read
557    /// (a level load) that must not run on top of the music. Suspends the
558    /// song first; if the drive refuses the pause (it does during the seek
559    /// at the start of a read), `f` is not called and the error says to keep
560    /// calling [`poll`](Self::poll) and try again. `f` gets the token and
561    /// hands it back with its result. Afterwards call
562    /// [`resume`](Self::resume) to continue the song, or [`play`](Self::play)
563    /// to start another.
564    ///
565    /// ```ignore
566    /// let loaded = player.with_cd_suspended(|cd| {
567    ///     let mut reader = SectorReader::with_cd(cd);
568    ///     let ok = load_level(&mut reader);
569    ///     (reader.release(), ok)
570    /// })?;
571    /// player.resume()?;
572    /// ```
573    pub fn with_cd_suspended<R>(
574        &mut self,
575        f: impl FnOnce(Cd) -> (Cd, R),
576    ) -> Result<R, PauseRefused> {
577        if !self.engine.suspend(&mut self.cd) {
578            return Err(PauseRefused);
579        }
580        // SAFETY: a token is a logic guard, not a memory-safety one (see
581        // `crate::periph`). The stand-in sits in the player for the length of
582        // `f` and nothing can reach it: the player is mutably borrowed.
583        let cd = core::mem::replace(&mut self.cd, unsafe { Cd::steal() });
584        let (cd, result) = f(cd);
585        self.cd = cd;
586        Ok(result)
587    }
588
589    /// Whether the drive has acknowledged suspension. False while Pause is
590    /// still being retried. The retained song still counts as `is_playing`.
591    pub fn is_suspended(&self) -> bool {
592        self.engine.suspended
593    }
594
595    /// Call about once per frame: notices the end of the song and loops or
596    /// stops, or retries a pending suspension. A suspended song returns
597    /// `Event::Playing` without querying or advancing the head.
598    pub fn poll(&mut self) -> Event {
599        self.engine.poll(&mut self.cd)
600    }
601
602    /// Whether a song is started and has not finished.
603    pub fn is_playing(&self) -> bool {
604        self.engine.state != State::Idle
605    }
606
607    /// Whether the head has been seen inside the song file since the last
608    /// start, so the audio is flowing and not still seeking.
609    pub fn is_streaming(&self) -> bool {
610        self.engine.is_streaming()
611    }
612
613    /// The song being played.
614    pub fn song(&self) -> Option<Song> {
615        self.engine.song
616    }
617
618    /// Time since the start of the song file at the last poll, in
619    /// milliseconds (the head runs a sector or two ahead of the sound). The
620    /// value only moves when [`poll`](Self::poll) reads the head; for a time
621    /// that advances every frame see [`SongClock`](super::xa_clock::SongClock).
622    pub fn elapsed_millis(&self) -> u32 {
623        self.engine.elapsed_millis()
624    }
625
626    /// The newest head reading, while the song is streaming (`None` while
627    /// it seeks, is suspended or is not playing). The input of
628    /// [`SongClock`](super::xa_clock::SongClock).
629    pub fn head_sample(&self) -> Option<HeadSample> {
630        self.engine.head_sample()
631    }
632
633    /// Set the level of the drive's audio output (CD-DA too). `0x80` is
634    /// unity, `0xFF` about twice that; `(left, right)` feed the left and
635    /// right outputs of a stereo song.
636    pub fn set_volume(&mut self, left: u8, right: u8) {
637        self.cd.set_audio_mixer(left, 0, right, 0);
638    }
639}
640
641#[cfg(test)]
642mod tests {
643    extern crate std;
644    use super::*;
645    use std::string::{String, ToString};
646    use std::vec::Vec;
647    use std::{format, vec};
648
649    #[test]
650    fn head_sample_milliseconds_match_the_wide_form_for_every_sector() {
651        let wide_start =
652            |sector: u32, rate: u32| (u64::from(sector) * 1000 / u64::from(rate)) as u32;
653        let wide_centre =
654            |sector: u32, rate: u32| ((2 * u64::from(sector) + 1) * 500 / u64::from(rate)) as u32;
655        let check = |sector: u32, rate: u32| {
656            let head = HeadSample {
657                epoch: 0,
658                serial: 0,
659                sector,
660                sectors_per_second: rate,
661            };
662            assert_eq!(
663                head.millis(),
664                wide_start(sector, rate),
665                "{sector} at {rate}"
666            );
667            assert_eq!(
668                head.centre_millis(),
669                wide_centre(sector, rate),
670                "{sector} at {rate}"
671            );
672        };
673        for rate in [75, 150] {
674            // Every sector of an 80-minute disc, then the u32 edges.
675            for sector in 0..400_000 {
676                check(sector, rate);
677            }
678            for sector in [u32::MAX, u32::MAX - 1, u32::MAX / 2, 1 << 31, (1 << 31) - 1] {
679                check(sector, rate);
680            }
681            let mut state = 0x9e37_79b9u32;
682            for _ in 0..200_000 {
683                state ^= state << 13;
684                state ^= state >> 17;
685                state ^= state << 5;
686                check(state, rate);
687            }
688        }
689    }
690
691    #[test]
692    fn an_idle_player_owns_the_token_and_hands_it_back() {
693        // SAFETY: a test-local token on the host; an idle player sends the
694        // drive nothing.
695        let player = Player::new(unsafe { Cd::steal() });
696        assert!(!player.is_playing());
697        let _token: Cd = player.release();
698    }
699
700    /// Records commands; `heads` is what GetlocP answers, one per poll.
701    #[derive(Default)]
702    struct Fake {
703        log: Vec<String>,
704        fail_at: Option<&'static str>,
705        heads: Vec<Option<u32>>,
706        pause_refusals: u32,
707    }
708
709    impl Fake {
710        fn step(&mut self, name: &str) -> bool {
711            self.log.push(name.to_string());
712            self.fail_at
713                != Some(match name {
714                    n if n.starts_with("unmute") => "unmute",
715                    n if n.starts_with("mode") => "mode",
716                    n if n.starts_with("filter") => "filter",
717                    n if n.starts_with("target") => "target",
718                    _ => "read",
719                })
720        }
721    }
722
723    impl Drive for Fake {
724        fn unmute(&mut self) -> bool {
725            self.step("unmute")
726        }
727        fn set_mode(&mut self, mode: u8) -> bool {
728            self.step(&format!("mode {mode:#04x}"))
729        }
730        fn set_filter(&mut self, file: u8, channel: u8) -> bool {
731            self.step(&format!("filter {file} {channel}"))
732        }
733        fn set_target(&mut self, lba: u32) -> bool {
734            self.step(&format!("target {lba}"))
735        }
736        fn start_streaming(&mut self) -> bool {
737            self.step("read")
738        }
739        fn pause(&mut self) -> bool {
740            self.log.push("pause".into());
741            if self.pause_refusals > 0 {
742                self.pause_refusals -= 1;
743                return false;
744            }
745            true
746        }
747        fn head_lba(&mut self) -> Option<u32> {
748            if self.heads.is_empty() {
749                None
750            } else {
751                self.heads.remove(0)
752            }
753        }
754    }
755
756    /// 100 sectors of songs plus the guard, at LBA 1000.
757    fn song(speed: DriveSpeed) -> Song {
758        File::new(1000, 100 + END_GUARD_SECTORS, 3, speed).song(2)
759    }
760
761    #[test]
762    fn suspension_retains_song_and_resumes_without_seek() {
763        let mut drive = Fake::default();
764        let mut engine = Engine::new();
765        let original = song(DriveSpeed::Single);
766        engine.start(&mut drive, original, true).unwrap();
767        drive.heads = vec![Some(1040)];
768        engine.poll(&mut drive);
769        let elapsed = engine.elapsed_millis();
770        drive.log.clear();
771        assert!(engine.suspend(&mut drive));
772        assert!(!engine.is_streaming());
773        drive.heads = vec![Some(1105)];
774        assert_eq!(engine.poll(&mut drive), Event::Playing);
775        assert_eq!(engine.elapsed_millis(), elapsed);
776        assert_eq!(
777            drive.heads.len(),
778            1,
779            "suspended polls must not read the head"
780        );
781        assert!(engine.looping);
782        assert_eq!(engine.song, Some(original));
783        assert!(engine.suspend(&mut drive));
784        engine.resume(&mut drive).unwrap();
785        // Every setting again, aimed at the head the pause left (1040), not
786        // the top of the file and not wherever the controller happens to be.
787        assert_eq!(
788            drive.log,
789            [
790                "pause",
791                "unmute",
792                "mode 0x48",
793                "filter 3 2",
794                "target 1040",
795                "read"
796            ]
797        );
798        assert_eq!(engine.elapsed_millis(), elapsed);
799        assert_eq!(engine.state, State::Seeking);
800        drive.heads = vec![Some(1050), Some(1100)];
801        assert_eq!(engine.poll(&mut drive), Event::Playing);
802        assert!(engine.is_streaming());
803        assert_eq!(engine.poll(&mut drive), Event::Looped);
804    }
805
806    #[test]
807    fn refused_suspend_retries_without_advancing_or_looping() {
808        let mut drive = Fake {
809            pause_refusals: 2,
810            ..Fake::default()
811        };
812        let mut engine = Engine::new();
813        engine
814            .start(&mut drive, song(DriveSpeed::Double), true)
815            .unwrap();
816        drive.log.clear();
817        assert!(!engine.suspend(&mut drive));
818        assert_eq!(engine.poll(&mut drive), Event::Playing);
819        assert!(!engine.suspended);
820        assert_eq!(engine.poll(&mut drive), Event::Playing);
821        assert!(engine.suspended);
822        assert_eq!(drive.log, ["pause", "pause", "pause"]);
823        engine.resume(&mut drive).unwrap();
824        assert_eq!(engine.state, State::Seeking);
825        drive.heads = vec![Some(2000), Some(1010)];
826        assert_eq!(engine.poll(&mut drive), Event::Playing);
827        assert!(!engine.is_streaming());
828        assert_eq!(engine.poll(&mut drive), Event::Playing);
829        assert!(engine.is_streaming());
830    }
831
832    #[test]
833    fn resume_cancels_refused_pause_without_duplicate_read() {
834        let mut drive = Fake {
835            pause_refusals: 1,
836            ..Fake::default()
837        };
838        let mut engine = Engine::new();
839        engine
840            .start(&mut drive, song(DriveSpeed::Single), false)
841            .unwrap();
842        drive.log.clear();
843        assert!(!engine.suspend(&mut drive));
844        engine.resume(&mut drive).unwrap();
845        engine.poll(&mut drive);
846        assert_eq!(drive.log, ["pause"]);
847        assert!(!engine.suspend_pending);
848    }
849
850    #[test]
851    fn refused_resume_keeps_suspension_for_explicit_retry() {
852        let mut drive = Fake::default();
853        let mut engine = Engine::new();
854        engine
855            .start(&mut drive, song(DriveSpeed::Single), false)
856            .unwrap();
857        assert!(engine.suspend(&mut drive));
858        drive.fail_at = Some("read");
859        assert_eq!(engine.resume(&mut drive), Err(Error::Read));
860        assert!(engine.suspended);
861        drive.log.clear();
862        assert_eq!(engine.poll(&mut drive), Event::Playing);
863        assert!(drive.log.is_empty());
864        drive.fail_at = None;
865        engine.resume(&mut drive).unwrap();
866        assert!(!engine.suspended);
867    }
868
869    #[test]
870    fn replacement_song_and_stop_cancel_old_suspension() {
871        for pending in [false, true] {
872            let mut drive = Fake::default();
873            let mut engine = Engine::new();
874            engine
875                .start(&mut drive, song(DriveSpeed::Single), true)
876                .unwrap();
877            drive.pause_refusals = u32::from(pending);
878            engine.suspend(&mut drive);
879            let replacement = song(DriveSpeed::Double);
880            engine.start(&mut drive, replacement, false).unwrap();
881            drive.log.clear();
882            engine.resume(&mut drive).unwrap();
883            assert_eq!(engine.song, Some(replacement));
884            assert!(!engine.looping);
885            assert!(drive.log.is_empty());
886            engine.suspend(&mut drive);
887            engine.stop(&mut drive);
888            drive.log.clear();
889            engine.resume(&mut drive).unwrap();
890            assert_eq!(engine.poll(&mut drive), Event::Idle);
891            assert!(engine.song.is_none());
892            assert!(drive.log.is_empty());
893        }
894    }
895
896    #[test]
897    fn start_sets_up_the_filter_before_the_read() {
898        let mut drive = Fake::default();
899        let mut engine = Engine::new();
900        engine
901            .start(&mut drive, song(DriveSpeed::Single), true)
902            .unwrap();
903        assert_eq!(
904            drive.log,
905            ["unmute", "mode 0x48", "filter 3 2", "target 1000", "read"]
906        );
907        let mut drive = Fake::default();
908        engine
909            .start(&mut drive, song(DriveSpeed::Double), true)
910            .unwrap();
911        assert_eq!(drive.log[1], "mode 0xc8");
912    }
913
914    #[test]
915    fn each_refused_step_is_reported_and_leaves_the_player_idle() {
916        for (at, error) in [
917            ("unmute", Error::Unmute),
918            ("mode", Error::SetMode),
919            ("filter", Error::SetFilter),
920            ("target", Error::Seek),
921            ("read", Error::Read),
922        ] {
923            let mut drive = Fake {
924                fail_at: Some(at),
925                ..Fake::default()
926            };
927            let mut engine = Engine::new();
928            let result = engine.start(&mut drive, song(DriveSpeed::Single), false);
929            assert_eq!(result, Err(error));
930            assert_eq!(engine.poll(&mut drive), Event::Idle);
931        }
932    }
933
934    #[test]
935    fn an_old_head_position_does_not_end_a_fresh_start() {
936        let mut drive = Fake::default();
937        let mut engine = Engine::new();
938        engine
939            .start(&mut drive, song(DriveSpeed::Double), true)
940            .unwrap();
941        drive.log.clear();
942        // Past the end (where the previous run stopped), then inside the file.
943        drive.heads = vec![Some(1105), None, Some(1003), Some(1050)];
944        assert_eq!(engine.poll(&mut drive), Event::Playing);
945        assert_eq!(engine.poll(&mut drive), Event::Playing);
946        assert!(!engine.is_streaming());
947        assert_eq!(engine.poll(&mut drive), Event::Playing);
948        assert!(engine.is_streaming());
949        assert_eq!(engine.elapsed_millis(), 3 * 1000 / 150);
950        assert_eq!(engine.poll(&mut drive), Event::Playing);
951        assert_eq!(engine.elapsed_millis(), 50 * 1000 / 150);
952        assert!(
953            drive.log.is_empty(),
954            "no command beyond GetlocP: {:?}",
955            drive.log
956        );
957    }
958
959    #[test]
960    fn a_loop_restarts_at_the_top_and_waits_for_the_head_again() {
961        let mut drive = Fake::default();
962        let mut engine = Engine::new();
963        engine
964            .start(&mut drive, song(DriveSpeed::Single), true)
965            .unwrap();
966        drive.log.clear();
967        drive.heads = vec![Some(1010), Some(1100), Some(1103), Some(1020)];
968        assert_eq!(engine.poll(&mut drive), Event::Playing);
969        assert_eq!(engine.poll(&mut drive), Event::Looped);
970        assert_eq!(drive.log, ["target 1000", "read"]);
971        // The drive still reports the guard region until the seek lands.
972        assert_eq!(engine.poll(&mut drive), Event::Playing);
973        assert_eq!(drive.log.len(), 2);
974        assert_eq!(engine.poll(&mut drive), Event::Playing);
975        assert!(engine.is_streaming());
976    }
977
978    #[test]
979    fn a_one_shot_pauses_at_the_end_and_goes_idle() {
980        let mut drive = Fake::default();
981        let mut engine = Engine::new();
982        engine
983            .start(&mut drive, song(DriveSpeed::Single), false)
984            .unwrap();
985        drive.log.clear();
986        drive.heads = vec![Some(1099), Some(1101)];
987        assert_eq!(engine.poll(&mut drive), Event::Playing);
988        assert_eq!(engine.poll(&mut drive), Event::Finished);
989        assert_eq!(drive.log, ["pause"]);
990        assert_eq!(engine.poll(&mut drive), Event::Idle);
991    }
992
993    #[test]
994    fn stop_pauses_only_a_running_player() {
995        let mut drive = Fake::default();
996        let mut engine = Engine::new();
997        engine.stop(&mut drive);
998        assert!(drive.log.is_empty());
999        engine
1000            .start(&mut drive, song(DriveSpeed::Single), false)
1001            .unwrap();
1002        engine.stop(&mut drive);
1003        assert_eq!(drive.log.last().unwrap(), "pause");
1004        assert_eq!(engine.poll(&mut drive), Event::Idle);
1005    }
1006
1007    #[test]
1008    fn a_refused_pause_is_retried_at_the_next_polls() {
1009        let mut drive = Fake {
1010            pause_refusals: 2,
1011            ..Fake::default()
1012        };
1013        let mut engine = Engine::new();
1014        engine
1015            .start(&mut drive, song(DriveSpeed::Single), false)
1016            .unwrap();
1017        drive.log.clear();
1018        engine.stop(&mut drive);
1019        assert_eq!(engine.poll(&mut drive), Event::Idle);
1020        assert_eq!(engine.poll(&mut drive), Event::Idle);
1021        assert_eq!(drive.log, ["pause", "pause", "pause"]);
1022        // Accepted: no further commands.
1023        assert_eq!(engine.poll(&mut drive), Event::Idle);
1024        assert_eq!(drive.log.len(), 3);
1025    }
1026
1027    #[test]
1028    fn starting_a_song_cancels_a_pending_pause() {
1029        let mut drive = Fake {
1030            pause_refusals: 5,
1031            ..Fake::default()
1032        };
1033        let mut engine = Engine::new();
1034        engine
1035            .start(&mut drive, song(DriveSpeed::Single), false)
1036            .unwrap();
1037        engine.stop(&mut drive);
1038        engine
1039            .start(&mut drive, song(DriveSpeed::Single), false)
1040            .unwrap();
1041        drive.log.clear();
1042        assert_eq!(engine.poll(&mut drive), Event::Playing);
1043        assert!(drive.log.is_empty());
1044    }
1045
1046    #[test]
1047    fn a_failed_loop_restart_finishes_the_song() {
1048        let mut drive = Fake::default();
1049        let mut engine = Engine::new();
1050        engine
1051            .start(&mut drive, song(DriveSpeed::Single), true)
1052            .unwrap();
1053        drive.heads = vec![Some(1010), Some(1100)];
1054        drive.fail_at = Some("target");
1055        assert_eq!(engine.poll(&mut drive), Event::Playing);
1056        assert_eq!(engine.poll(&mut drive), Event::Finished);
1057        assert_eq!(drive.log.last().unwrap(), "pause");
1058    }
1059
1060    /// The head the drive reports after the pause wins over a poll that is
1061    /// long out of date; without an answer the last poll does; a song that
1062    /// never got past the seek resumes at its seek target.
1063    #[test]
1064    fn resume_aims_at_the_best_position_known() {
1065        // The pause-time reading beats a stale poll.
1066        let mut drive = Fake::default();
1067        let mut engine = Engine::new();
1068        engine
1069            .start(&mut drive, song(DriveSpeed::Single), false)
1070            .unwrap();
1071        drive.heads = vec![Some(1010)];
1072        engine.poll(&mut drive);
1073        drive.heads = vec![Some(1070)];
1074        assert!(engine.suspend(&mut drive));
1075        drive.log.clear();
1076        engine.resume(&mut drive).unwrap();
1077        assert_eq!(drive.log.last().unwrap(), "read");
1078        assert_eq!(drive.log[drive.log.len() - 2], "target 1070");
1079        assert_eq!(engine.elapsed_millis(), 70 * 1000 / 75);
1080
1081        // No answer after the pause: the last poll.
1082        let mut drive = Fake::default();
1083        let mut engine = Engine::new();
1084        engine
1085            .start(&mut drive, song(DriveSpeed::Single), false)
1086            .unwrap();
1087        drive.heads = vec![Some(1010)];
1088        engine.poll(&mut drive);
1089        assert!(engine.suspend(&mut drive));
1090        drive.log.clear();
1091        engine.resume(&mut drive).unwrap();
1092        assert!(drive.log.contains(&"target 1010".to_string()));
1093
1094        // Never seen streaming and no answer: the seek target (the top). A
1095        // reading outside the file (the old position) is not believed.
1096        let mut drive = Fake::default();
1097        let mut engine = Engine::new();
1098        engine
1099            .start(&mut drive, song(DriveSpeed::Single), false)
1100            .unwrap();
1101        drive.heads = vec![Some(9000)];
1102        assert!(engine.suspend(&mut drive));
1103        drive.log.clear();
1104        engine.resume(&mut drive).unwrap();
1105        assert!(drive.log.contains(&"target 1000".to_string()));
1106        assert_eq!(engine.state, State::Seeking);
1107    }
1108
1109    /// The data read that motivated the rework: a reader leaves the mode with
1110    /// no XA bits, the filter maybe elsewhere and the head at the data. The
1111    /// resume must send all of it again, in the order a start does, aimed at
1112    /// the song, and the first stale head readings must not look like music.
1113    #[test]
1114    fn resume_after_a_data_read_restores_mode_filter_and_position() {
1115        let mut drive = Fake::default();
1116        let mut engine = Engine::new();
1117        engine
1118            .start(&mut drive, song(DriveSpeed::Double), true)
1119            .unwrap();
1120        drive.heads = vec![Some(1030)];
1121        engine.poll(&mut drive);
1122        assert!(engine.suspend(&mut drive));
1123        // ... a data read happens here; the fake does not model it ...
1124        drive.log.clear();
1125        engine.resume(&mut drive).unwrap();
1126        assert_eq!(
1127            drive.log,
1128            ["unmute", "mode 0xc8", "filter 3 2", "target 1030", "read"]
1129        );
1130        // The head is still at the data (LBA 300), then lands on the song.
1131        drive.heads = vec![Some(300), Some(1031)];
1132        assert_eq!(engine.poll(&mut drive), Event::Playing);
1133        assert!(!engine.is_streaming());
1134        assert_eq!(engine.poll(&mut drive), Event::Playing);
1135        assert!(engine.is_streaming());
1136        assert_eq!(engine.elapsed_millis(), 31 * 1000 / 150);
1137    }
1138
1139    #[test]
1140    fn each_refused_resume_step_is_reported_and_keeps_the_suspension() {
1141        for (at, error) in [
1142            ("unmute", Error::Unmute),
1143            ("mode", Error::SetMode),
1144            ("filter", Error::SetFilter),
1145            ("target", Error::Seek),
1146            ("read", Error::Read),
1147        ] {
1148            let mut drive = Fake::default();
1149            let mut engine = Engine::new();
1150            engine
1151                .start(&mut drive, song(DriveSpeed::Single), false)
1152                .unwrap();
1153            assert!(engine.suspend(&mut drive));
1154            drive.fail_at = Some(at);
1155            assert_eq!(engine.resume(&mut drive), Err(error), "{at}");
1156            assert!(engine.suspended, "{at}");
1157            drive.fail_at = None;
1158            engine.resume(&mut drive).unwrap();
1159            assert!(!engine.suspended);
1160        }
1161    }
1162
1163    #[test]
1164    fn the_epoch_changes_with_every_read_and_the_serial_with_every_reading() {
1165        let mut drive = Fake::default();
1166        let mut engine = Engine::new();
1167        let looped = song(DriveSpeed::Single);
1168        engine.start(&mut drive, looped, true).unwrap();
1169        assert!(engine.head_sample().is_none(), "not streaming yet");
1170        let first = engine.epoch;
1171        drive.heads = vec![Some(1010), Some(1020)];
1172        engine.poll(&mut drive);
1173        let a = engine.head_sample().unwrap();
1174        engine.poll(&mut drive);
1175        let b = engine.head_sample().unwrap();
1176        assert_eq!((a.epoch, b.epoch), (first, first));
1177        assert_ne!(a.serial, b.serial);
1178        assert_eq!((a.sector, b.sector), (10, 20));
1179        assert_eq!(b.sectors_per_second, 75);
1180        // A loop, a resume and a restart each start a new epoch, and a
1181        // suspended song has no sample.
1182        drive.heads = vec![Some(1100)];
1183        assert_eq!(engine.poll(&mut drive), Event::Looped);
1184        assert_ne!(engine.epoch, first);
1185        let looped_epoch = engine.epoch;
1186        assert!(engine.suspend(&mut drive));
1187        assert!(engine.head_sample().is_none());
1188        engine.resume(&mut drive).unwrap();
1189        assert_ne!(engine.epoch, looped_epoch);
1190    }
1191
1192    #[test]
1193    fn the_drive_lent_for_a_read_comes_back_and_the_song_resumes() {
1194        // SAFETY: a test-local token on the host; the closure sends nothing.
1195        let mut player = Player::new(unsafe { Cd::steal() });
1196        // Idle: lending still works, nothing to suspend.
1197        let seen = player.with_cd_suspended(|cd| (cd, 7)).unwrap();
1198        assert_eq!(seen, 7);
1199        assert!(!player.is_suspended());
1200    }
1201
1202    #[test]
1203    fn the_file_span_excludes_the_guard() {
1204        let file = File::from_directory_entry(7, 2048 * 116, 1, DriveSpeed::Single);
1205        assert_eq!(file.span_sector_count(), 100);
1206        assert_eq!(
1207            File::new(0, 4, 0, DriveSpeed::Double).span_sector_count(),
1208            0
1209        );
1210    }
1211}