psx_cdstream/lib.rs
1//! Interrupt-driven CD-ROM sector streaming.
2//!
3//! The SDK's `SectorReader` reads a disc by waiting: fine at boot, wrong in
4//! the middle of a game, where the drive delivers a sector every 6.5 ms and a
5//! frame loop that looks once per frame loses most of them. This crate reads
6//! the way a streamer has to: you queue [`Request`]s, the CD interrupt
7//! handler pops one sector per interrupt straight into the request's
8//! destination, and the foreground only submits, cancels and asks how far a
9//! request has got. Nothing busy-waits for the drive.
10//!
11//! # What it does
12//!
13//! - **PIO, one sector per interrupt.** The sector is popped from the data
14//! FIFO by the CPU. Chopped CD DMA (channel 3) is unreliable on a console;
15//! the PIO path is the one that has loaded byte-perfect streams there. The
16//! price is CPU time while a read runs (about 1.3 ms per sector more than a
17//! working DMA is the figure on record), so read in bursts when there is
18//! work, not continuously.
19//! - **Seek first.** Every transfer is Setloc, SeekL, Setmode (double speed),
20//! ReadN: the bracket the BIOS uses. A bare Setloc plus ReadN starts
21//! delivering while the mechanism is still settling and corrupts a long
22//! stream on a console.
23//! - **Abort at the next sector.** [`Engine::cancel`] only sets a flag; the
24//! handler drops the next sector and pauses the drive itself. (A Pause sent
25//! from the foreground while sectors were arriving lost its acknowledge on
26//! silicon.) The request ends [`Outcome::Cancelled`] with the sectors that
27//! had landed; [`Request::remaining_after`] builds the request that
28//! continues it.
29//! - **A small priority queue.** [`QUEUE_DEPTH`] requests wait behind the
30//! active one, most urgent [`Priority`] first.
31//! - **Contiguous chaining.** A queued request that starts at the sector
32//! after the active one's last continues without a Pause or a seek: the
33//! handler swaps the destination and keeps popping. A layout-ordered group
34//! of regions costs one seek.
35//! - **Resume.** A request can carry a resume budget
36//! ([`Request::with_resumes`]): after a drive error the transport pauses,
37//! seeks back to `lba + received` and carries on.
38//! - **A drive arbiter.** CD-DA and XA playback and data reads cannot share
39//! the laser. [`Engine::request_audio_lease`] stops the read in flight,
40//! waits for the drive to stop, closes the CD interrupt source and (on the
41//! console) hands the controller token to the audio code;
42//! releasing the lease takes it back and queued reads carry on. End audio
43//! with Pause, never Stop: after Stop the motor spins down, reports status
44//! 0 for a second or two, and reads started then failed on a console.
45//! A lease that is asked for and left pending is granted the moment the
46//! drive stops, ahead of any read queued meanwhile. Audio that must not
47//! hold up reads uses [`Engine::try_audio_lease`], which takes the drive
48//! only if it is free and leaves nothing pending, or ends the pending
49//! request with [`Engine::withdraw_audio_lease`].
50//!
51//! # Use
52//!
53//! ```ignore
54//! // After the polled boot reads are done (SectorReader::release gives the
55//! // token back):
56//! psx_cdstream::install(cd, psx_cdstream::Config::DEFAULT).ok();
57//!
58//! // SAFETY: ROOM is not touched until the request has finished.
59//! let request = unsafe { Request::new_raw(lba, sectors, ROOM.as_mut_ptr().cast()) };
60//! let ticket = psx_cdstream::submit(request.with_priority(Priority::URGENT))?;
61//!
62//! // Each frame:
63//! if let RequestState::Finished(done) = psx_cdstream::state(ticket) {
64//! // done.outcome, done.received
65//! }
66//! ```
67//!
68//! # Next to the polled reader
69//!
70//! A program that loads with `SectorReader` (maps, tables, boot assets) and only
71//! wants some reads kept out of the frame loop (a weapon model that streams in
72//! while the world renders) has two ways to use this crate without giving up the
73//! polled reader.
74//!
75//! The cheap one is [`drain`]: start the read with the polled reader as always,
76//! hand its sectors to the CD interrupt with `drain::start`, look at
77//! `drain::poll` once a frame and end the read with the reader's `stop`. There is
78//! no transport, so it costs about 1.4 KB of RAM where the transport is about 9 KB
79//! in a game built with profile-guided optimisation, and every command still goes
80//! out through the polled path that has been proved on a console. A polled read
81//! at 150 sectors a second needs a call every 6.7 ms and loses sectors when the
82//! frame loop looks once per frame (the controller keeps a few, and delivers the
83//! newest); the handler has no such limit.
84//!
85//! The full one is the transport below, for a program that can route its reads
86//! through it: call [`ensure_installed`] with [`IrqMaskPolicy::OnlyWhileBusy`]
87//! before a read (it also puts the wrapper back after `install_vblank_counter`
88//! reset the exception vector), submit the request, and look at it once a frame.
89//! Between requests the CD interrupt source is closed and the polled reader works
90//! as before; before a polled command, [`stop_and_wait`] ends a request still in
91//! flight. Use one or the other in a program, not both at once: each puts a
92//! wrapper in the exception vector and both would answer a CD interrupt.
93//!
94//! # How it is built
95//!
96//! [`Engine`] is the whole state machine, generic over [`CdHw`], the
97//! controller as it sees it. On the console [`install`] puts an exception
98//! wrapper in front of psx-rt's handler that calls the one global engine
99//! once per CD interrupt, and the free functions (`submit`, `state`, ...)
100//! reach it with the CD source closed. On the host the tests drive the same
101//! engine against a scripted drive, so every phase, cancel point, error path,
102//! chaining rule and lease transition is exercised without hardware. The
103//! counters are published as `PSX_CD_STATS` ([`StreamStats`]) for tools that
104//! read guest memory.
105//!
106//! Boot-time and blocking loads still use `psx_io::cd::reader::SectorReader`
107//! (or `psx_pack::cd`): it needs the controller token, and so does
108//! `install`, so the compiler keeps the two from sharing the drive.
109//! `uninstall` hands the token back.
110#![no_std]
111#![cfg_attr(target_arch = "mips", feature(asm_experimental_arch))]
112#![deny(unsafe_op_in_unsafe_fn)]
113#![warn(missing_docs)]
114
115mod engine;
116mod hw;
117mod request;
118
119#[cfg(any(target_arch = "mips", doc))]
120mod console;
121#[cfg(any(target_arch = "mips", doc))]
122pub use console::*;
123#[cfg(any(target_arch = "mips", doc))]
124pub mod drain;
125
126pub use engine::*;
127pub use hw::CdHw;
128pub use request::*;
129
130#[cfg(test)]
131extern crate std;
132#[cfg(test)]
133mod fake;
134#[cfg(test)]
135mod tests;