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

psx_io/
cd.rs

1//! CD-ROM drive: commands, responses, sector polling, CD-DA playback in
2//! [`audio`], XA-ADPCM music in [`xa`] and polled data-sector reads in
3//! [`reader`].
4//!
5//! One driver owns the controller: the [`Cd`] token. Every command and
6//! register step is a method taking `&mut Cd`, so the borrow checker sees a
7//! second driver that tries to program the controller while one is mid-command.
8//! [`xa::Player`] and [`reader::SectorReader`] hold the token while they exist
9//! and give it back with `release`.
10//!
11//! The controller exposes four byte registers selected by the low two
12//! bits of the index register at [`psx_hw::cd::reg::INDEX`]. Register addresses, command bytes
13//! and status bits live in [`psx_hw::cd`].
14
15pub mod audio;
16pub mod pause;
17pub mod reader;
18pub mod xa;
19pub mod xa_clock;
20
21use crate::periph::Cd;
22use crate::{irq, read_u8, write_u8};
23
24use psx_hw::cd::{
25    index_status as status, irq as code, reg, request, volume_apply, CMD_DEMUTE, CMD_GETLOCP,
26    CMD_GETSTAT, CMD_MUTE, CMD_PAUSE, CMD_PLAY, CMD_READN, CMD_SETLOC, CMD_SETMODE, CMD_STOP,
27    STAT_PLAYING, STAT_SEEKING,
28};
29
30/// Response bytes a sector probe discards at most. The FIFO holds 16, but a
31/// controller wedged "not empty" must not be able to spin the drain forever.
32const SECTOR_POLL_DRAIN_LIMIT: u32 = 256;
33
34/// Fixed-size command response.
35#[derive(Copy, Clone, Debug, PartialEq, Eq)]
36pub struct Response {
37    bytes: [u8; 16],
38    len: usize,
39}
40
41impl Response {
42    /// A response with no bytes, what a deprecated forwarder hands back where
43    /// the command it wraps now reports a [`CdError`].
44    pub const fn empty() -> Self {
45        Response {
46            bytes: [0; 16],
47            len: 0,
48        }
49    }
50
51    /// Number of response bytes captured.
52    pub const fn len(&self) -> usize {
53        self.len
54    }
55
56    /// Whether no response bytes were captured.
57    pub const fn is_empty(&self) -> bool {
58        self.len == 0
59    }
60
61    /// Response bytes in FIFO order.
62    pub fn bytes(&self) -> &[u8] {
63        &self.bytes[..self.len]
64    }
65}
66
67/// Why a CD command produced no response.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub enum CdError {
70    /// The controller did not free a parameter slot or answer within the poll
71    /// budget (no drive, no disc, or a wedged controller).
72    Timeout,
73    /// The drive answered with an error (INT5).
74    DriveError,
75}
76
77/// Poll budget the blocking commands give the controller for each wait (a
78/// parameter slot, then the acknowledge). Generous: the controller frees a
79/// slot and acknowledges within microseconds to milliseconds, so this is a
80/// hang guard, not a latency.
81pub const DEFAULT_COMMAND_SPINS: u32 = 131_072;
82
83impl Cd {
84    /// Send a command and return its first response packet, waiting at most
85    /// [`DEFAULT_COMMAND_SPINS`] polls for each step.
86    ///
87    /// Returns [`CdError::Timeout`] when the controller never answers and
88    /// [`CdError::DriveError`] when the drive reports an error. A timed-out
89    /// command leaves CD-ROM IRQ output masked, as [`Self::try_command`] does.
90    pub fn command(&mut self, command: u8, params: &[u8]) -> Result<Response, CdError> {
91        self.command_within(command, params, DEFAULT_COMMAND_SPINS)
92    }
93
94    /// [`Self::command`] with an explicit poll budget per step.
95    pub fn command_within(
96        &mut self,
97        command: u8,
98        params: &[u8],
99        spin_limit: u32,
100    ) -> Result<Response, CdError> {
101        run_command(&mut Mmio, command, params, spin_limit)
102    }
103
104    /// Try to send a command and capture its first response packet.
105    ///
106    /// Returns `None` if the controller does not expose parameter room or
107    /// a response within `spin_limit` polls, or if the drive reports an error
108    /// ([`Self::command_within`] tells the two apart). Use this for gameplay paths
109    /// where a not-ready drive should not stall rendering forever. If a
110    /// dispatched command times out, CD-ROM IRQ output remains masked so a
111    /// late ACK cannot interrupt a polling caller.
112    pub fn try_command(&mut self, command: u8, params: &[u8], spin_limit: u32) -> Option<Response> {
113        self.command_within(command, params, spin_limit).ok()
114    }
115
116    /// Current CD-ROM IRQ flag value (0 = none, 1 = data ready, 2 = complete,
117    /// 3 = ack, 5 = error).
118    ///
119    /// Exposed so callers can build their own wait loops bounded by a hardware
120    /// timer rather than by a poll count. A poll budget is only a proxy for time
121    /// and drifts with CPU and bus speed, which matters when the thing being
122    /// measured is mechanical.
123    pub fn irq_flag_value(&mut self) -> u8 {
124        irq_flag()
125    }
126
127    /// Acknowledge the given CD-ROM IRQ bits.
128    pub fn acknowledge_irq(&mut self, bits: u8) {
129        ack_irq(bits);
130    }
131
132    /// Drain any pending response bytes, discarding them.
133    pub fn discard_response(&mut self) {
134        drain_response_fifo();
135    }
136
137    /// Send a command without waiting for any response. Pairs with
138    /// [`Self::irq_flag_value`] for caller-timed waits.
139    ///
140    /// Returns the CD-ROM IRQ enable to give back to
141    /// [`restore_irq_output`](Self::restore_irq_output), or `None` if the
142    /// parameter FIFO never made room. Leaves CD-ROM IRQ
143    /// output masked exactly as the polled helpers do, so a late ACK cannot
144    /// interrupt the caller mid-measurement; call [`Self::restore_irq_output`] when done.
145    pub fn dispatch_command(&mut self, command: u8, params: &[u8], spin_limit: u32) -> Option<u8> {
146        let irq_enable = begin_polled_command();
147        select_index(0);
148        for &param in params {
149            if !wait_param_room_bounded(spin_limit) {
150                finish_failed_polled_command(irq_enable);
151                return None;
152            }
153            write_byte(reg::PARAMETER, param);
154        }
155        crate::diag::cd_command(command);
156        write_byte(reg::COMMAND_RESPONSE, command);
157        Some(irq_enable)
158    }
159
160    /// Restore the CD-ROM IRQ enable saved by [`Self::dispatch_command`].
161    pub fn restore_irq_output(&mut self, saved: u8) {
162        drain_response_fifo();
163        ack_irq(code::ACK_ALL);
164        restore_irq_enable(saved);
165        select_index(0);
166    }
167
168    /// Nonblocking readiness probe for a sector reader that owns the INT1 ACK.
169    /// Data-ready is never acknowledged here. Other completion responses are
170    /// drained (at most 256 bytes) and acknowledged; drive errors also reset the
171    /// parameter FIFO. A ready data FIFO is accepted if no classified IRQ remains.
172    pub fn poll_data_sector(&mut self) -> Result<bool, SectorPollError> {
173        poll_sector(&mut SectorPollMmio)
174    }
175
176    /// Wait for the next streamed data sector (INT1) and acknowledge it.
177    ///
178    /// Use between [`Self::try_start_reading`] and [`Self::try_pause_until_complete`] to step through
179    /// a sector stream. Unrelated pending IRQs are drained and acknowledged so a
180    /// stale response cannot be mistaken for a sector arrival. Returns `false` on
181    /// a drive error or if no sector arrives within `spin_limit` polls.
182    pub fn try_wait_data_sector(&mut self, spin_limit: u32) -> bool {
183        let mut spins = spin_limit;
184        loop {
185            let flag = irq_flag();
186            if flag == code::DATA_READY {
187                ack_irq(flag);
188                return true;
189            }
190            if flag == code::ERROR {
191                let _ = read_response_fifo();
192                ack_irq(flag);
193                return false;
194            }
195            if flag != 0 {
196                let _ = read_response_fifo();
197                ack_irq(flag);
198            }
199            if spins == 0 {
200                return false;
201            }
202            spins -= 1;
203            core::hint::spin_loop();
204        }
205    }
206
207    /// Get the CD-ROM drive status byte.
208    #[doc(alias = "Getstat")]
209    #[doc(alias = "CdlNop")]
210    pub fn status(&mut self) -> Result<Response, CdError> {
211        self.command(CMD_GETSTAT, &[])
212    }
213
214    /// Try to get the CD-ROM drive status byte.
215    #[doc(alias = "Getstat")]
216    pub fn try_status(&mut self, spin_limit: u32) -> Option<Response> {
217        self.try_command(CMD_GETSTAT, &[], spin_limit)
218    }
219
220    /// Set the CD-ROM controller mode byte.
221    pub fn set_mode(&mut self, mode: u8) -> Result<Response, CdError> {
222        self.command(CMD_SETMODE, &[mode])
223    }
224
225    /// Try to set the CD-ROM controller mode byte.
226    pub fn try_set_mode(&mut self, mode: u8, spin_limit: u32) -> Option<Response> {
227        self.try_command(CMD_SETMODE, &[mode], spin_limit)
228    }
229
230    /// Seek to a logical data-sector LBA (the command receives absolute BCD MSF).
231    #[doc(alias = "Setloc")]
232    #[doc(alias = "CdlSetloc")]
233    pub fn try_set_target_lba(&mut self, lba: u32, spin_limit: u32) -> Option<Response> {
234        let [minute, second, frame] = lba_to_bcd_msf(lba);
235        self.try_command(CMD_SETLOC, &[minute, second, frame], spin_limit)
236    }
237
238    /// Begin a normal data-sector stream at the most recently selected location.
239    #[doc(alias = "ReadN")]
240    #[doc(alias = "CdlReadN")]
241    pub fn try_start_reading(&mut self, spin_limit: u32) -> Option<Response> {
242        self.try_command(CMD_READN, &[], spin_limit)
243    }
244
245    /// Route CD-DA/XA output out of the CD-ROM controller.
246    #[doc(alias = "Demute")]
247    #[doc(alias = "CdlDemute")]
248    pub fn unmute(&mut self) -> Result<Response, CdError> {
249        self.command(CMD_DEMUTE, &[])
250    }
251
252    /// Try to route CD-DA/XA output out of the CD-ROM controller.
253    #[doc(alias = "Demute")]
254    pub fn try_unmute(&mut self, spin_limit: u32) -> Option<Response> {
255        self.try_command(CMD_DEMUTE, &[], spin_limit)
256    }
257
258    /// Mute CD-DA/XA output at the CD-ROM controller.
259    pub fn mute(&mut self) -> Result<Response, CdError> {
260        self.command(CMD_MUTE, &[])
261    }
262
263    /// Try to mute CD-DA/XA output at the CD-ROM controller.
264    pub fn try_mute(&mut self, spin_limit: u32) -> Option<Response> {
265        self.try_command(CMD_MUTE, &[], spin_limit)
266    }
267
268    /// Start CD-DA playback at a 1-based track number.
269    ///
270    /// The number is relative to this program's own tracks; on a multi-program
271    /// disc [`crate::disc_base`] shifts it past whatever came before.
272    pub fn play_track(&mut self, track: u8) -> Result<Response, CdError> {
273        self.command(
274            CMD_PLAY,
275            &[bin_to_bcd(crate::disc_base::shift_track(track))],
276        )
277    }
278
279    /// Try to start CD-DA playback at a 1-based track number. Shifted like
280    /// [`Self::play_track`].
281    pub fn try_play_track(&mut self, track: u8, spin_limit: u32) -> Option<Response> {
282        self.try_command(
283            CMD_PLAY,
284            &[bin_to_bcd(crate::disc_base::shift_track(track))],
285            spin_limit,
286        )
287    }
288
289    /// Pause CD-DA/read playback.
290    pub fn pause(&mut self) -> Result<Response, CdError> {
291        self.command(CMD_PAUSE, &[])
292    }
293
294    /// Try to pause CD-DA/read playback.
295    pub fn try_pause(&mut self, spin_limit: u32) -> Option<Response> {
296        self.try_command(CMD_PAUSE, &[], spin_limit)
297    }
298
299    /// Try to pause CD-DA/read playback and wait for the completion IRQ.
300    ///
301    /// Unlike [`Self::try_stop`], this leaves the drive spun up, which makes it the
302    /// right handoff before gameplay code starts issuing data-read commands.
303    ///
304    /// `spin_limit` bounds each of the two waits. Out of a data read the second
305    /// response comes 1.2 to 3.9 million system clocks after the first on the
306    /// console (and about 4.2 million after CD-DA), so a limit under
307    /// [`pause::COMPLETE_SPINS`] can report failure for a Pause that is merely
308    /// slow. Returns `false` for a refusal (INT5, during a seek) as well; the
309    /// protocol that waits the seek out and sends again is
310    /// [`pause::pause_until_stopped`].
311    pub fn try_pause_until_complete(&mut self, spin_limit: u32) -> bool {
312        try_command_until_complete_inner(CMD_PAUSE, &[], spin_limit)
313    }
314
315    /// Stop the CD-ROM motor/playback.
316    pub fn stop(&mut self) -> Result<Response, CdError> {
317        self.command(CMD_STOP, &[])
318    }
319
320    /// Try to stop the CD-ROM motor/playback.
321    ///
322    /// **This returns when the command is ACCEPTED, not when the drive is
323    /// done.** On real hardware the motor then winds down for one to two
324    /// seconds, during which GetStat reports no activity bits and data-read
325    /// commands fail; an emulator answers instantly and hides the window
326    /// (proven by a demo-disc burn whose every chain-load died this way). If
327    /// data reads follow, either call [`Self::stop_and_settle`], or better, keep the
328    /// drive spun up with [`Self::try_pause_until_complete`].
329    pub fn try_stop(&mut self, spin_limit: u32) -> Option<Response> {
330        self.try_command(CMD_STOP, &[], spin_limit)
331    }
332
333    /// Stop playback and wait until the drive has genuinely gone quiet:
334    /// GetStat reporting neither playing nor seeking on two consecutive polls,
335    /// with a short pause between polls. Bounded by `max_polls` so a wedged
336    /// drive cannot hang the caller; returns whether the drive settled.
337    ///
338    /// This is the safe prelude to issuing data-read commands after CD-DA.
339    /// [`Self::try_pause_until_complete`] is the faster choice when the next reads
340    /// are imminent, since it keeps the motor spinning.
341    pub fn stop_and_settle(&mut self, spin_limit: u32, max_polls: u32) -> bool {
342        let _ = self.try_stop(spin_limit);
343        let mut settled = 0u8;
344        for _ in 0..max_polls {
345            // Pace the polls: on silicon each takes real time anyway, but an
346            // emulator answers instantly and would burn the poll budget in
347            // microseconds. Volatile MMIO reads cannot be optimized out.
348            for _ in 0..20_000u32 {
349                // SAFETY: `reg::INDEX` is the CD-ROM controller's index/status register, byte-wide
350                // MMIO on every PS1. Reading it has no side effects, so this is a pure delay.
351                unsafe { core::ptr::read_volatile(reg::INDEX as *const u8) };
352            }
353            let quiet = match self.try_status(spin_limit) {
354                Some(r) => r
355                    .bytes()
356                    .first()
357                    .is_some_and(|s| s & (STAT_PLAYING | STAT_SEEKING) == 0),
358                None => false,
359            };
360            settled = if quiet { settled + 1 } else { 0 };
361            if settled >= 2 {
362                return true;
363            }
364        }
365        false
366    }
367
368    /// Get the current physical play position (CdlGetlocP). The 8-byte reply is
369    /// `[Track(bcd), Index(raw), RMM, RSS, RSECT, AMM, ASS, ASECT]`; parse it with
370    /// [`PlayPosition::parse`].
371    #[doc(alias = "GetlocP")]
372    #[doc(alias = "CdlGetlocP")]
373    pub fn play_position(&mut self) -> Result<Response, CdError> {
374        self.command(CMD_GETLOCP, &[])
375    }
376
377    /// Try to get the current physical play position, giving up after `spin_limit`.
378    #[doc(alias = "GetlocP")]
379    pub fn try_play_position(&mut self, spin_limit: u32) -> Option<Response> {
380        self.try_command(CMD_GETLOCP, &[], spin_limit)
381    }
382
383    /// Send a command and wait for its SECOND response (the completion IRQ),
384    /// not just the initial acknowledgement.
385    ///
386    /// Seek, read and init all acknowledge immediately and finish much later, so
387    /// timing them against the ack measures command dispatch rather than the
388    /// mechanical operation. Returns `false` if either response fails to arrive
389    /// within `spin_limit` polls.
390    pub fn try_command_until_complete(
391        &mut self,
392        command: u8,
393        params: &[u8],
394        spin_limit: u32,
395    ) -> bool {
396        try_command_until_complete_inner(command, params, spin_limit)
397    }
398
399    /// Program the drive's audio mixer (CD-DA and XA-ADPCM on their way to
400    /// the SPU's CD input) and apply it. Volumes are 0..=0xFF with 0x80 as
401    /// unity; `(0x80, 0, 0x80, 0)` is plain stereo. The SPU side still needs
402    /// its CD input enabled and a CD volume (`psx-spu`).
403    pub fn set_audio_mixer(
404        &mut self,
405        left_to_left: u8,
406        left_to_right: u8,
407        right_to_right: u8,
408        right_to_left: u8,
409    ) {
410        select_index(2);
411        write_byte(reg::PARAMETER, left_to_left);
412        write_byte(reg::REQUEST_IRQ, left_to_right);
413        select_index(3);
414        write_byte(reg::COMMAND_RESPONSE, right_to_right);
415        write_byte(reg::PARAMETER, right_to_left);
416        // Apply the new volumes (index 3, register 3, bit 5), un-muting ADPCM.
417        write_byte(reg::REQUEST_IRQ, volume_apply::APPLY);
418        select_index(0);
419    }
420}
421
422/// Register-level steps, for a driver that sequences commands itself, such as
423/// the polled [`reader::SectorReader`].
424///
425/// Each is one controller access or a short fixed run of them, and each
426/// leaves register index 0 selected, so the byte steps that follow need not
427/// select it again.
428impl Cd {
429    /// Acknowledge every controller IRQ (writing `0x5F`, which also resets
430    /// the parameter FIFO) and the CD-ROM bit of `I_STAT`.
431    pub fn acknowledge_all_and_reset_parameters(&mut self) {
432        ack_all_and_reset_parameters();
433    }
434
435    /// The controller's IRQ enable bits.
436    pub fn irq_enable_mask(&mut self) -> u8 {
437        irq_enable()
438    }
439
440    /// Set the controller's IRQ enable bits (five are defined).
441    pub fn set_irq_enable_mask(&mut self, mask: u8) {
442        set_irq_enable(mask);
443    }
444
445    /// Pop and discard up to `limit` response bytes. The FIFO is 16 bytes
446    /// deep; the bound is for a controller wedged "not empty".
447    pub fn drain_response_limited(&mut self, limit: u32) {
448        drain_response_limited(limit);
449    }
450
451    /// Whether the data FIFO holds sector bytes to pop.
452    pub fn is_data_fifo_ready(&mut self) -> bool {
453        data_fifo_ready()
454    }
455
456    /// Wait for the parameter FIFO to have room, for at most `spins` more
457    /// status reads. `false` on timeout.
458    pub fn wait_parameter_room(&mut self, spins: u32) -> bool {
459        wait_param_room_bounded(spins)
460    }
461
462    /// Empty the parameter FIFO.
463    pub fn reset_parameter_fifo(&mut self) {
464        clear_parameter_fifo();
465    }
466
467    /// Push one parameter byte. Wait for room first.
468    pub fn send_parameter_byte(&mut self, byte: u8) {
469        write_byte(reg::PARAMETER, byte);
470    }
471
472    /// Write the command byte, which starts the command.
473    pub fn send_command_byte(&mut self, byte: u8) {
474        crate::diag::cd_command(byte);
475        write_byte(reg::COMMAND_RESPONSE, byte);
476    }
477
478    /// Pop one response byte.
479    pub fn read_response_byte(&mut self) -> u8 {
480        read_byte(reg::COMMAND_RESPONSE)
481    }
482
483    /// The status register: FIFO flags and the busy bit.
484    pub fn status_register(&mut self) -> u8 {
485        read_status()
486    }
487
488    /// Arm the data FIFO so the drive's buffered sector can be popped with
489    /// [`read_data_byte`](Self::read_data_byte) once
490    /// [`is_data_fifo_ready`](Self::is_data_fifo_ready) says it filled.
491    #[doc(alias = "BFRD")]
492    pub fn request_data(&mut self) {
493        write_byte(reg::REQUEST_IRQ, request::WANT_DATA);
494    }
495
496    /// Drop the data request, which resets the data FIFO.
497    pub fn clear_data_request(&mut self) {
498        write_byte(reg::REQUEST_IRQ, 0);
499    }
500
501    /// Pop one byte of sector data.
502    pub fn read_data_byte(&mut self) -> u8 {
503        read_byte(reg::PARAMETER)
504    }
505}
506
507/// The controller steps one polled command takes, so the order and the
508/// timeouts can be tested against a fake.
509trait CommandIo {
510    fn begin(&mut self) -> u8;
511    fn wait_param_room(&mut self, spins: u32) -> bool;
512    fn write_param(&mut self, value: u8);
513    fn write_command(&mut self, command: u8);
514    fn wait_irq(&mut self, expected: u8, spins: u32) -> Result<u8, CdError>;
515    fn finish(&mut self, irq_enable: u8, irq: u8) -> Response;
516    /// Leave the controller clean after a drive error: drain, acknowledge
517    /// everything and restore the IRQ enable.
518    fn recover(&mut self, irq_enable: u8);
519    /// Give the IRQ enable back without touching the response side.
520    fn restore_enable(&mut self, irq_enable: u8);
521}
522
523struct Mmio;
524
525impl CommandIo for Mmio {
526    fn begin(&mut self) -> u8 {
527        begin_polled_command()
528    }
529    fn wait_param_room(&mut self, spins: u32) -> bool {
530        wait_param_room_bounded(spins)
531    }
532    fn write_param(&mut self, value: u8) {
533        write_byte(reg::PARAMETER, value);
534    }
535    fn write_command(&mut self, command: u8) {
536        crate::diag::cd_command(command);
537        write_byte(reg::COMMAND_RESPONSE, command);
538    }
539    fn wait_irq(&mut self, expected: u8, spins: u32) -> Result<u8, CdError> {
540        wait_irq_flag(expected, spins, irq_flag, |flag| {
541            let _ = read_response_fifo();
542            ack_irq(flag);
543        })
544    }
545    fn finish(&mut self, irq_enable: u8, irq: u8) -> Response {
546        finish_polled_command(irq_enable, irq)
547    }
548    fn recover(&mut self, irq_enable: u8) {
549        finish_failed_polled_command(irq_enable);
550    }
551    fn restore_enable(&mut self, irq_enable: u8) {
552        restore_irq_enable(irq_enable);
553        select_index(0);
554    }
555}
556
557fn run_command(
558    io: &mut impl CommandIo,
559    command: u8,
560    params: &[u8],
561    spin_limit: u32,
562) -> Result<Response, CdError> {
563    let irq_enable = io.begin();
564    for &param in params {
565        if !io.wait_param_room(spin_limit) {
566            // Nothing was dispatched, so the IRQ output can be given back.
567            io.restore_enable(irq_enable);
568            return Err(CdError::Timeout);
569        }
570        io.write_param(param);
571    }
572    io.write_command(command);
573    match io.wait_irq(code::ACKNOWLEDGE, spin_limit) {
574        Ok(irq) => Ok(io.finish(irq_enable, irq)),
575        Err(CdError::DriveError) => {
576            io.recover(irq_enable);
577            Err(CdError::DriveError)
578        }
579        // A command is in flight: leave IRQ output masked so its late ACK
580        // cannot interrupt a polling caller.
581        Err(CdError::Timeout) => Err(CdError::Timeout),
582    }
583}
584
585/// A drive error reported while polling for the next streamed sector.
586#[derive(Clone, Copy, Debug, PartialEq, Eq)]
587pub struct SectorPollError;
588
589trait SectorPollIo {
590    fn flag(&mut self) -> u8;
591    fn drain(&mut self);
592    fn acknowledge(&mut self, flag: u8, reset: bool);
593    fn data_ready(&mut self) -> bool;
594}
595struct SectorPollMmio;
596impl SectorPollIo for SectorPollMmio {
597    #[inline]
598    fn flag(&mut self) -> u8 {
599        irq_flag()
600    }
601    #[inline]
602    fn drain(&mut self) {
603        drain_response_limited(SECTOR_POLL_DRAIN_LIMIT);
604    }
605    #[inline]
606    fn acknowledge(&mut self, flag: u8, reset: bool) {
607        if reset {
608            ack_all_and_reset_parameters();
609        } else {
610            ack_irq(flag);
611        }
612    }
613    #[inline]
614    fn data_ready(&mut self) -> bool {
615        data_fifo_ready()
616    }
617}
618#[inline]
619fn poll_sector(io: &mut impl SectorPollIo) -> Result<bool, SectorPollError> {
620    match io.flag() {
621        code::DATA_READY => Ok(true),
622        code::ERROR => {
623            io.drain();
624            io.acknowledge(code::ACK_ALL, true);
625            Err(SectorPollError)
626        }
627        flag @ (code::COMPLETE | code::ACKNOWLEDGE | code::DATA_END) => {
628            io.drain();
629            io.acknowledge(flag, false);
630            Ok(false)
631        }
632        _ => Ok(io.data_ready()),
633    }
634}
635
636/// Data-track LBA to the absolute BCD `[minute, second, frame]` Setloc takes.
637/// LBA 0 is 00:02:00: the 150-sector lead-in puts it two seconds in. Minutes
638/// clamp at 99.
639pub const fn lba_to_bcd_msf(lba: u32) -> [u8; 3] {
640    let absolute = lba.saturating_add(150);
641    let raw_minute = absolute / (60 * 75);
642    let minute = if raw_minute > 99 {
643        99
644    } else {
645        raw_minute as u8
646    };
647    let second = ((absolute / 75) % 60) as u8;
648    let frame = (absolute % 75) as u8;
649    [bin_to_bcd(minute), bin_to_bcd(second), bin_to_bcd(frame)]
650}
651
652/// Convert binary `0..=99` to BCD for CD-ROM command parameters.
653pub const fn bin_to_bcd(v: u8) -> u8 {
654    let v = if v > 99 { 99 } else { v };
655    ((v / 10) << 4) | (v % 10)
656}
657
658/// Convert a BCD byte back to binary. Inverse of [`bin_to_bcd`] for well-formed
659/// input; nibbles above 9 are not normalised (the drive never emits them).
660pub const fn bcd_to_bin(v: u8) -> u8 {
661    (v >> 4) * 10 + (v & 0x0f)
662}
663
664/// Decoded CdlGetlocP reply. The relative MSF (`relative_*`) is elapsed time
665/// into the current track, independent of the pregap, which makes it the source
666/// of truth for a music/song clock. The absolute MSF (`absolute_*`) is the raw
667/// disc position.
668#[derive(Clone, Copy, PartialEq, Eq, Debug)]
669pub struct PlayPosition {
670    /// 1-based track number the drive is currently in.
671    pub track: u8,
672    /// Track index (raw): 0 = pregap, 1 = program area.
673    pub index: u8,
674    /// Minutes elapsed into the current track.
675    pub relative_min: u8,
676    /// Seconds elapsed into the current track (0..=59).
677    pub relative_sec: u8,
678    /// MSF frames elapsed into the current track (0..=74, 75 per second).
679    pub relative_frame: u8,
680    /// Absolute disc position, minutes.
681    pub absolute_min: u8,
682    /// Absolute disc position, seconds (0..=59).
683    pub absolute_sec: u8,
684    /// Absolute disc position, MSF frames (0..=74).
685    pub absolute_frame: u8,
686}
687
688impl PlayPosition {
689    /// Parse a GetlocP [`Response`]. Returns `None` if fewer than 8 bytes came
690    /// back (drive not ready / no disc). Track and MSF fields are BCD; index is
691    /// raw.
692    pub fn parse(resp: &Response) -> Option<Self> {
693        let b = resp.bytes();
694        if b.len() < 8 {
695            return None;
696        }
697        Some(PlayPosition {
698            track: bcd_to_bin(b[0]),
699            index: b[1],
700            relative_min: bcd_to_bin(b[2]),
701            relative_sec: bcd_to_bin(b[3]),
702            relative_frame: bcd_to_bin(b[4]),
703            absolute_min: bcd_to_bin(b[5]),
704            absolute_sec: bcd_to_bin(b[6]),
705            absolute_frame: bcd_to_bin(b[7]),
706        })
707    }
708
709    /// Elapsed sectors into the current track (75 sectors per second).
710    pub fn relative_sectors(&self) -> u32 {
711        (self.relative_min as u32 * 60 + self.relative_sec as u32) * 75 + self.relative_frame as u32
712    }
713
714    /// Elapsed milliseconds into the current track. This is the song clock feed.
715    pub fn relative_millis(&self) -> u32 {
716        self.relative_sectors() * 1000 / 75
717    }
718}
719
720fn begin_polled_command() -> u8 {
721    let irq_enable = irq_enable();
722    set_irq_enable(0);
723    ack_irq(code::ACK_ALL);
724    select_index(0);
725    drain_response_fifo();
726    clear_parameter_fifo();
727    irq_enable
728}
729
730fn finish_polled_command(irq_enable: u8, irq: u8) -> Response {
731    let response = read_response_fifo();
732    ack_irq(irq);
733    restore_irq_enable(irq_enable);
734    select_index(0);
735    response
736}
737
738/// Poll `flag` until it reads `expected`, at most `spins` more times after the
739/// first read. A drive error (INT5) ends the wait at once; any other nonzero
740/// flag is a stale response, handed to `discard` and polled past.
741fn wait_irq_flag(
742    expected: u8,
743    mut spins: u32,
744    mut flag: impl FnMut() -> u8,
745    mut discard: impl FnMut(u8),
746) -> Result<u8, CdError> {
747    loop {
748        let irq = flag();
749        if irq == expected {
750            return Ok(irq);
751        }
752        if irq == code::ERROR {
753            return Err(CdError::DriveError);
754        }
755        if irq != 0 {
756            discard(irq);
757        }
758        if spins == 0 {
759            return Err(CdError::Timeout);
760        }
761        spins -= 1;
762        core::hint::spin_loop();
763    }
764}
765
766fn wait_irq_bounded(expected: u8, spins: u32) -> Option<u8> {
767    Mmio.wait_irq(expected, spins).ok()
768}
769
770fn try_command_until_complete_inner(command: u8, params: &[u8], spin_limit: u32) -> bool {
771    let irq_enable = begin_polled_command();
772    select_index(0);
773    for &param in params {
774        if !wait_param_room_bounded(spin_limit) {
775            finish_failed_polled_command(irq_enable);
776            return false;
777        }
778        write_byte(reg::PARAMETER, param);
779    }
780    crate::diag::cd_command(command);
781    write_byte(reg::COMMAND_RESPONSE, command);
782
783    let ok = wait_ack_then_complete(spin_limit);
784    drain_response_fifo();
785    ack_irq(code::ACK_ALL);
786    restore_irq_enable(irq_enable);
787    select_index(0);
788    ok
789}
790
791fn wait_ack_then_complete(spin_limit: u32) -> bool {
792    if wait_irq_bounded(code::ACKNOWLEDGE, spin_limit).is_none() {
793        return false;
794    }
795    drain_response_fifo();
796    ack_irq(code::ACKNOWLEDGE);
797
798    if wait_irq_bounded(code::COMPLETE, spin_limit).is_none() {
799        return false;
800    }
801    drain_response_fifo();
802    ack_irq(code::COMPLETE);
803    true
804}
805
806fn finish_failed_polled_command(irq_enable: u8) {
807    drain_response_fifo();
808    ack_irq(code::ACK_ALL);
809    restore_irq_enable(irq_enable);
810    select_index(0);
811}
812
813fn read_response_fifo() -> Response {
814    select_index(0);
815
816    let mut bytes = [0u8; 16];
817    let mut len = 0;
818    while read_status() & status::RESPONSE_NOT_EMPTY != 0 && len < bytes.len() {
819        bytes[len] = read_byte(reg::COMMAND_RESPONSE);
820        len += 1;
821    }
822    Response { bytes, len }
823}
824
825fn drain_response_fifo() {
826    let _ = read_response_fifo();
827}
828
829fn wait_param_room_bounded(mut spins: u32) -> bool {
830    while read_status() & status::PARAM_NOT_FULL == 0 {
831        if spins == 0 {
832            return false;
833        }
834        spins -= 1;
835        core::hint::spin_loop();
836    }
837    true
838}
839
840/// Pop and discard up to `limit` response bytes.
841fn drain_response_limited(limit: u32) {
842    select_index(0);
843    let mut drained = 0;
844    while read_status() & status::RESPONSE_NOT_EMPTY != 0 && drained < limit {
845        let _ = read_byte(reg::COMMAND_RESPONSE);
846        drained += 1;
847    }
848}
849
850/// Acknowledge every controller IRQ and reset the parameter FIFO, then the
851/// CD-ROM bit of I_STAT.
852fn ack_all_and_reset_parameters() {
853    select_index(1);
854    write_byte(reg::REQUEST_IRQ, code::ACK_ALL | code::CLEAR_PARAMETER_FIFO);
855    irq::acknowledge(1 << psx_hw::irq::source::CDROM);
856    select_index(0);
857}
858
859fn data_fifo_ready() -> bool {
860    select_index(0);
861    read_status() & status::DATA_FIFO_NOT_EMPTY != 0
862}
863
864fn clear_parameter_fifo() {
865    select_index(1);
866    write_byte(reg::REQUEST_IRQ, code::CLEAR_PARAMETER_FIFO);
867    select_index(0);
868}
869
870fn ack_irq(bits: u8) {
871    crate::diag::cd_irq_acked(bits);
872    select_index(1);
873    write_byte(reg::REQUEST_IRQ, bits & code::ACK_ALL);
874    irq::acknowledge(1 << psx_hw::irq::source::CDROM);
875    select_index(0);
876}
877
878fn irq_flag() -> u8 {
879    select_index(1);
880    let flag = read_byte(reg::REQUEST_IRQ) & code::ACK_ALL;
881    select_index(0);
882    crate::diag::cd_irq_seen(flag);
883    flag
884}
885
886fn irq_enable() -> u8 {
887    select_index(0);
888    let enable = read_byte(reg::REQUEST_IRQ) & code::ACK_ALL;
889    select_index(0);
890    enable
891}
892
893fn restore_irq_enable(enable: u8) {
894    set_irq_enable(enable);
895}
896
897fn set_irq_enable(enable: u8) {
898    select_index(1);
899    write_byte(reg::PARAMETER, enable & code::ACK_ALL);
900    select_index(0);
901}
902
903fn read_status() -> u8 {
904    read_byte(reg::INDEX)
905}
906
907fn select_index(index: u8) {
908    write_byte(reg::INDEX, index & 0x03);
909}
910
911fn read_byte(addr: u32) -> u8 {
912    // SAFETY: fixed CD-ROM MMIO register read.
913    unsafe { read_u8(addr) }
914}
915
916fn write_byte(addr: u32, value: u8) {
917    // SAFETY: fixed CD-ROM MMIO register write.
918    unsafe { write_u8(addr, value) }
919}
920
921/// A token for a deprecated forwarder that never took one.
922fn steal() -> Cd {
923    // SAFETY: a token is a logic guard, not a memory-safety one (see
924    // `crate::periph`), and the old free functions never took one.
925    unsafe { Cd::steal() }
926}
927
928/// Moved to [`Cd::try_command`].
929#[deprecated(note = "use `Cd::try_command` with the `Cd` token")]
930#[inline(always)]
931pub fn try_command(command: u8, params: &[u8], spin_limit: u32) -> Option<Response> {
932    steal().try_command(command, params, spin_limit)
933}
934
935/// Moved to [`Cd::irq_flag_value`].
936#[deprecated(note = "use `Cd::irq_flag_value` with the `Cd` token")]
937#[inline(always)]
938pub fn irq_flag_value() -> u8 {
939    steal().irq_flag_value()
940}
941
942/// Moved to [`Cd::acknowledge_irq`].
943#[deprecated(note = "use `Cd::acknowledge_irq` with the `Cd` token")]
944#[inline(always)]
945pub fn acknowledge_irq(bits: u8) {
946    steal().acknowledge_irq(bits)
947}
948
949/// Moved to [`Cd::discard_response`].
950#[deprecated(note = "use `Cd::discard_response` with the `Cd` token")]
951#[inline(always)]
952pub fn discard_response() {
953    steal().discard_response()
954}
955
956/// Moved to [`Cd::dispatch_command`].
957#[deprecated(note = "use `Cd::dispatch_command` with the `Cd` token")]
958#[inline(always)]
959pub fn dispatch_command(command: u8, params: &[u8], spin_limit: u32) -> Option<u8> {
960    steal().dispatch_command(command, params, spin_limit)
961}
962
963/// Moved to [`Cd::restore_irq_output`].
964#[deprecated(note = "use `Cd::restore_irq_output` with the `Cd` token")]
965#[inline(always)]
966pub fn restore_irq_output(saved: u8) {
967    steal().restore_irq_output(saved)
968}
969
970/// Moved to [`Cd::poll_data_sector`].
971#[deprecated(note = "use `Cd::poll_data_sector` with the `Cd` token")]
972#[inline(always)]
973pub fn poll_data_sector() -> Result<bool, SectorPollError> {
974    steal().poll_data_sector()
975}
976
977/// Moved to [`Cd::try_status`].
978#[deprecated(note = "use `Cd::try_status` with the `Cd` token")]
979#[inline(always)]
980pub fn try_status(spin_limit: u32) -> Option<Response> {
981    steal().try_status(spin_limit)
982}
983
984/// Moved to [`Cd::try_set_mode`].
985#[deprecated(note = "use `Cd::try_set_mode` with the `Cd` token")]
986#[inline(always)]
987pub fn try_set_mode(mode: u8, spin_limit: u32) -> Option<Response> {
988    steal().try_set_mode(mode, spin_limit)
989}
990
991/// Moved to [`Cd::try_set_target_lba`].
992#[deprecated(note = "use `Cd::try_set_target_lba` with the `Cd` token")]
993#[inline(always)]
994pub fn try_set_target_lba(lba: u32, spin_limit: u32) -> Option<Response> {
995    steal().try_set_target_lba(lba, spin_limit)
996}
997
998/// Moved to [`Cd::try_start_reading`].
999#[deprecated(note = "use `Cd::try_start_reading` with the `Cd` token")]
1000#[inline(always)]
1001pub fn try_start_reading(spin_limit: u32) -> Option<Response> {
1002    steal().try_start_reading(spin_limit)
1003}
1004
1005/// Moved to [`Cd::try_unmute`].
1006#[deprecated(note = "use `Cd::try_unmute` with the `Cd` token")]
1007#[inline(always)]
1008pub fn try_unmute(spin_limit: u32) -> Option<Response> {
1009    steal().try_unmute(spin_limit)
1010}
1011
1012/// Moved to [`Cd::try_mute`].
1013#[deprecated(note = "use `Cd::try_mute` with the `Cd` token")]
1014#[inline(always)]
1015pub fn try_mute(spin_limit: u32) -> Option<Response> {
1016    steal().try_mute(spin_limit)
1017}
1018
1019/// Moved to [`Cd::try_play_track`].
1020#[deprecated(note = "use `Cd::try_play_track` with the `Cd` token")]
1021#[inline(always)]
1022pub fn try_play_track(track: u8, spin_limit: u32) -> Option<Response> {
1023    steal().try_play_track(track, spin_limit)
1024}
1025
1026/// Moved to [`Cd::try_pause`].
1027#[deprecated(note = "use `Cd::try_pause` with the `Cd` token")]
1028#[inline(always)]
1029pub fn try_pause(spin_limit: u32) -> Option<Response> {
1030    steal().try_pause(spin_limit)
1031}
1032
1033/// Moved to [`Cd::try_pause_until_complete`].
1034#[deprecated(note = "use `Cd::try_pause_until_complete` with the `Cd` token")]
1035#[inline(always)]
1036pub fn try_pause_until_complete(spin_limit: u32) -> bool {
1037    steal().try_pause_until_complete(spin_limit)
1038}
1039
1040/// Moved to [`Cd::try_play_position`].
1041#[deprecated(note = "use `Cd::try_play_position` with the `Cd` token")]
1042#[inline(always)]
1043pub fn try_play_position(spin_limit: u32) -> Option<Response> {
1044    steal().try_play_position(spin_limit)
1045}
1046
1047#[cfg(test)]
1048mod tests {
1049    use super::*;
1050
1051    #[test]
1052    fn sector_probe_leaves_int1_and_orders_other_acknowledgements() {
1053        struct Fake {
1054            flag: u8,
1055            ready: bool,
1056            events: [u8; 4],
1057            len: usize,
1058        }
1059        impl Fake {
1060            fn event(&mut self, e: u8) {
1061                self.events[self.len] = e;
1062                self.len += 1;
1063            }
1064        }
1065        impl SectorPollIo for Fake {
1066            fn flag(&mut self) -> u8 {
1067                self.event(1);
1068                self.flag
1069            }
1070            fn drain(&mut self) {
1071                self.event(2);
1072            }
1073            fn acknowledge(&mut self, flag: u8, reset: bool) {
1074                assert_eq!(flag, if reset { 31 } else { self.flag });
1075                self.event(if reset { 4 } else { 3 });
1076            }
1077            fn data_ready(&mut self) -> bool {
1078                self.event(5);
1079                self.ready
1080            }
1081        }
1082        for flag in 0..=5 {
1083            for ready in [false, true] {
1084                let mut io = Fake {
1085                    flag,
1086                    ready,
1087                    events: [0; 4],
1088                    len: 0,
1089                };
1090                let result = poll_sector(&mut io);
1091                let expected = match flag {
1092                    1 => Ok(true),
1093                    5 => Err(SectorPollError),
1094                    2..=4 => Ok(false),
1095                    _ => Ok(ready),
1096                };
1097                assert_eq!(result, expected);
1098                let events: &[u8] = match flag {
1099                    1 => &[1],
1100                    5 => &[1, 2, 4],
1101                    2..=4 => &[1, 2, 3],
1102                    _ => &[1, 5],
1103                };
1104                assert_eq!(&io.events[..io.len], events);
1105            }
1106        }
1107    }
1108
1109    /// Records the controller steps a command takes and answers each wait from
1110    /// a script.
1111    struct FakeIo {
1112        room: bool,
1113        irq: Result<u8, CdError>,
1114        events: [u8; 12],
1115        len: usize,
1116        spins_seen: [u32; 4],
1117        spins_len: usize,
1118    }
1119
1120    impl FakeIo {
1121        fn new(room: bool, irq: Result<u8, CdError>) -> Self {
1122            FakeIo {
1123                room,
1124                irq,
1125                events: [0; 12],
1126                len: 0,
1127                spins_seen: [0; 4],
1128                spins_len: 0,
1129            }
1130        }
1131        fn event(&mut self, e: u8) {
1132            self.events[self.len] = e;
1133            self.len += 1;
1134        }
1135        fn events(&self) -> &[u8] {
1136            &self.events[..self.len]
1137        }
1138        fn spins(&mut self, spins: u32) {
1139            self.spins_seen[self.spins_len] = spins;
1140            self.spins_len += 1;
1141        }
1142    }
1143
1144    // Event codes: begin, param room, param byte, command byte, wait irq,
1145    // finish, recover, restore enable.
1146    const BEGIN: u8 = 1;
1147    const ROOM: u8 = 2;
1148    const PARAM: u8 = 3;
1149    const COMMAND: u8 = 4;
1150    const WAIT: u8 = 5;
1151    const FINISH: u8 = 6;
1152    const RECOVER: u8 = 7;
1153    const RESTORE: u8 = 8;
1154
1155    impl CommandIo for FakeIo {
1156        fn begin(&mut self) -> u8 {
1157            self.event(BEGIN);
1158            0x1f
1159        }
1160        fn wait_param_room(&mut self, spins: u32) -> bool {
1161            self.event(ROOM);
1162            self.spins(spins);
1163            self.room
1164        }
1165        fn write_param(&mut self, _value: u8) {
1166            self.event(PARAM);
1167        }
1168        fn write_command(&mut self, _command: u8) {
1169            self.event(COMMAND);
1170        }
1171        fn wait_irq(&mut self, _expected: u8, spins: u32) -> Result<u8, CdError> {
1172            self.event(WAIT);
1173            self.spins(spins);
1174            self.irq
1175        }
1176        fn finish(&mut self, _irq_enable: u8, _irq: u8) -> Response {
1177            self.event(FINISH);
1178            response_from(&[0x02])
1179        }
1180        fn recover(&mut self, _irq_enable: u8) {
1181            self.event(RECOVER);
1182        }
1183        fn restore_enable(&mut self, _irq_enable: u8) {
1184            self.event(RESTORE);
1185        }
1186    }
1187
1188    #[test]
1189    fn a_full_parameter_fifo_times_out_without_writing_the_parameter() {
1190        // The wait used to ignore its own timeout and write the byte anyway.
1191        let mut io = FakeIo::new(false, Ok(code::ACKNOWLEDGE));
1192        let result = run_command(&mut io, CMD_SETLOC, &[0x00, 0x02, 0x00], 77);
1193        assert_eq!(result, Err(CdError::Timeout));
1194        assert_eq!(io.events(), &[BEGIN, ROOM, RESTORE]);
1195    }
1196
1197    #[test]
1198    fn a_command_nobody_acknowledges_times_out_and_leaves_irq_output_masked() {
1199        let mut io = FakeIo::new(true, Err(CdError::Timeout));
1200        let result = run_command(&mut io, CMD_GETSTAT, &[], DEFAULT_COMMAND_SPINS);
1201        assert_eq!(result, Err(CdError::Timeout));
1202        // No finish, recover or restore: the late ACK stays masked.
1203        assert_eq!(io.events(), &[BEGIN, COMMAND, WAIT]);
1204        assert_eq!(&io.spins_seen[..io.spins_len], &[DEFAULT_COMMAND_SPINS]);
1205    }
1206
1207    #[test]
1208    fn a_drive_error_is_reported_and_the_controller_cleaned_up() {
1209        let mut io = FakeIo::new(true, Err(CdError::DriveError));
1210        let result = run_command(&mut io, CMD_PLAY, &[0x01], 10);
1211        assert_eq!(result, Err(CdError::DriveError));
1212        assert_eq!(io.events(), &[BEGIN, ROOM, PARAM, COMMAND, WAIT, RECOVER]);
1213    }
1214
1215    #[test]
1216    fn an_acknowledged_command_returns_its_response() {
1217        let mut io = FakeIo::new(true, Ok(code::ACKNOWLEDGE));
1218        let result = run_command(&mut io, CMD_SETLOC, &[1, 2, 3], 10).unwrap();
1219        assert_eq!(result.bytes(), &[0x02]);
1220        assert_eq!(
1221            io.events(),
1222            &[BEGIN, ROOM, PARAM, ROOM, PARAM, ROOM, PARAM, COMMAND, WAIT, FINISH]
1223        );
1224    }
1225
1226    #[test]
1227    fn the_flag_wait_discards_stale_responses_and_stops_at_its_budget() {
1228        // Stale INT2 then INT3: the stale one is discarded, INT3 ends the wait.
1229        let script = [0u8, 2, 3];
1230        let mut next = 0;
1231        let mut discarded = [0u8; 4];
1232        let mut dropped = 0;
1233        let got = wait_irq_flag(
1234            code::ACKNOWLEDGE,
1235            10,
1236            || {
1237                let flag = script[next];
1238                next += 1;
1239                flag
1240            },
1241            |flag| {
1242                discarded[dropped] = flag;
1243                dropped += 1;
1244            },
1245        );
1246        assert_eq!(got, Ok(code::ACKNOWLEDGE));
1247        assert_eq!(&discarded[..dropped], &[2]);
1248
1249        // Silence: one read plus `spins` more, then Timeout.
1250        let mut reads = 0u32;
1251        let got = wait_irq_flag(
1252            code::ACKNOWLEDGE,
1253            5,
1254            || {
1255                reads += 1;
1256                0
1257            },
1258            |_| {},
1259        );
1260        assert_eq!(got, Err(CdError::Timeout));
1261        assert_eq!(reads, 6);
1262
1263        // INT5 ends it at once, whatever budget is left.
1264        let got = wait_irq_flag(code::ACKNOWLEDGE, 1000, || code::ERROR, |_| {});
1265        assert_eq!(got, Err(CdError::DriveError));
1266    }
1267
1268    #[test]
1269    fn bcd_clamps_to_two_digits() {
1270        assert_eq!(bin_to_bcd(2), 0x02);
1271        assert_eq!(bin_to_bcd(42), 0x42);
1272        assert_eq!(bin_to_bcd(100), 0x99);
1273    }
1274
1275    #[test]
1276    fn bcd_to_bin_roundtrips() {
1277        for v in 0u8..=99 {
1278            assert_eq!(bcd_to_bin(bin_to_bcd(v)), v);
1279        }
1280    }
1281
1282    #[test]
1283    fn lba_to_msf_includes_the_lead_in() {
1284        assert_eq!(lba_to_bcd_msf(0), [0x00, 0x02, 0x00]);
1285        assert_eq!(lba_to_bcd_msf(424), [0x00, 0x07, 0x49]);
1286        assert_eq!(lba_to_bcd_msf(992), [0x00, 0x15, 0x17]);
1287    }
1288
1289    fn response_from(bytes: &[u8]) -> Response {
1290        let mut buf = [0u8; 16];
1291        buf[..bytes.len()].copy_from_slice(bytes);
1292        Response {
1293            bytes: buf,
1294            len: bytes.len(),
1295        }
1296    }
1297
1298    #[test]
1299    fn play_position_parses_and_converts() {
1300        // Track 2, index 1, relative 01:23:45 (min:sec:frame), absolute 04:56:00.
1301        let resp = response_from(&[
1302            bin_to_bcd(2),
1303            0x01,
1304            bin_to_bcd(1),
1305            bin_to_bcd(23),
1306            bin_to_bcd(45),
1307            bin_to_bcd(4),
1308            bin_to_bcd(56),
1309            bin_to_bcd(0),
1310        ]);
1311        let p = PlayPosition::parse(&resp).unwrap();
1312        assert_eq!(p.track, 2);
1313        assert_eq!(p.index, 1);
1314        assert_eq!(
1315            (p.relative_min, p.relative_sec, p.relative_frame),
1316            (1, 23, 45)
1317        );
1318        // (1*60 + 23) * 75 + 45 = 6270 sectors.
1319        assert_eq!(p.relative_sectors(), 6270);
1320        // 6270 * 1000 / 75 = 83600 ms.
1321        assert_eq!(p.relative_millis(), 83_600);
1322    }
1323
1324    #[test]
1325    fn play_position_rejects_short_response() {
1326        assert!(PlayPosition::parse(&response_from(&[0x02, 0x01, 0x00])).is_none());
1327    }
1328}