# pcenginecd-rust A Rust PC Engine **CD-ROM² / Super CD-ROM² / Arcade Card**, transcribed from [pcenginecd-python](https://github.com/alewman/pcenginecd-python) at `v0.1.0` and proven equivalent to it: every CPU bus cycle (physical address, value, kind, master clock), every frame's picture, every mixed audio sample (PSG, CD audio and ADPCM), the CPU's state and the drive's command log, frame by frame, on a card of our own that drives the unit through every register, on the real System Card and on real discs. pcenginecd-python is the specification (readable, cited, compared with Geargrafx and Beetle PCE); this crate adds nothing and tunes nothing. It is an **add-on crate**: it plugs into [pcengine-rust](../pcengine-rust)'s socket traits exactly as the Python add-on plugs into pcengine-python's sockets, and copies nothing from it. The System Card (with the Super System Card's RAM and id registers) goes in the HuCard slot; the CD unit (64 KiB CD RAM, 2 KiB backup RAM, the `$1800-$180F` interface, the SCSI-class controller, the seek model, CD audio with the fader, the ADPCM unit, the Arcade Card) goes on the expansion port, raises IRQ2 with its own bit and hands the mixer its two audio sources. Module for module the reference's, with the same names, every named switch as a field with the reference's default, and the comments that cite a source carried over. Where Rust forced a difference the module header says so, and they are listed below. **The disc is the one part designed for the browser and not only transcribed**: the sector store is a trait (`SectorSource`), with an in-memory implementation, a file-backed one for bin/cue, and room for a web page to answer from slices of a file the user chose; the cue sheet is parsed from its text, with no filesystem. CHD is not read here (the reference shells out to `chdman`): extract to bin/cue first, as the gate does. ```text cargo build --release cargo test --release # 107 tests, nothing but synthetic discs scripts/fetch_reference.sh # the reference and what it runs on, at their pins, into external/ scripts/rung2.sh # the probe card in lockstep with the reference ``` `Cargo.toml` depends on pcengine-rust by path (`../pcengine-rust`, which depends on `../huc6280-rust`) while the three are local only: clone them side by side. The System Card and every disc are bring-your-own, read in place and never committed (`.gitignore` refuses their extensions). Nothing GPL or LGPL was read or transcribed for this crate: the only source transcribed is pcenginecd-python, which is ours and MIT; no emulator's source and no `reference/` directory was opened. The seek model derives from Dave Shadoff's MIT-licensed measurements, through the reference ([NOTICE.md](NOTICE.md)). ## Certification | What | Version | | --- | --- | | pcenginecd-python (the reference) | tag `v0.1.0`, `5fec99e` | | pcengine-python (what the reference runs on) | tag `v0.1.0`, `bc9b976` | | huc6280-python, 6502-python (its core and frame) | `v0.3.0` (`bf20330`), `2146eba` | | pcengine-rust (the base board), by path | `49e3d48` | | huc6280-rust (the CPU), through the base board | `7f49bf8` | | The System Card | Super CD-ROM² System v3.0 (Japan), 262,144 bytes, SHA-1 `79f5ff55…bd1f56a2c` (the user's) | | The discs | six CHDs of the user's library (below), extracted with `chdman` 0.285 | Ladder status at this commit, each rung reproduced with the script named, on Linux x86_64, rustc 1.93.1, the reference on PyPy 7.3.20 (Python 3.11, `PYPY_GC_NURSERY=1M`): | Rung | What | Result | Script | | --- | --- | --- | --- | | 1 | The reference's unit tests, transcribed, on the same synthetic discs | 97 tests pass: the reference's 90 (`test_disc` 5, `test_scsi` 15, `test_cdda` 11, `test_adpcm` 15, `test_arcade` 21, `test_unit` 13, `test_board` 10) and 7 of this crate's (the disc's new shape, backup RAM in and out, the fade's rounding); with `tests/state.rs` (9) and `tests/reference_notes.rs`, 107 | `rung1.sh` | | 2 | The gate itself, on the probe card with every default | identical, all 520 frames | `rung2.sh` | | 3 | Synthetic programs: the probe card on every machine and medium and with every named switch away from its default | 45 of 45 identical (23,400 frames); 43 of 43 cases change the reference's trace and the one that should not does not | `rung3.sh` | | 4 | The real System Card on a synthetic disc, 700 frames with a RUN press | identical, all 700 frames | `rung4.sh` | | 5 | Real discs, 3,000 frames each with RUN at 450 | 6 of 6 identical, audio included (18,000 frames): the three Arcade Card discs (Ryuuko no Ken, Mad Stalker, Ginga Fukei Densetsu Sapphire) and the three of the m7 and m8 records (The Addams Family, Pyramid Plunder, Insanity) | `rung5.sh` | | 6 | Save states: the round trip and the run-ahead pass on rung 4's boot, the probe card and two real discs in mid-boot; the refusals as unit tests | 5 of 5 runs equal, twice each, and the run-ahead pass equal on all 5 (the System Card's boot, the probe card twice, Ryuuko no Ken inside frame 2000, Mad Stalker inside frame 1500); 9 unit tests | `rung6.sh` | | 7 | Seeded faults | 45 caught, 0 missed (below) | `rung7.sh` | **The gate** (`scripts/lockstep_cd.py`) runs each case of `scripts/cases_cd.tsv` on both sides: `scripts/pcecd_trace.py` builds the reference's `PcEngineCd` on PyPy (the pinned checkouts of `external/` on `PYTHONPATH`) and `target/release/pcecd-trace` builds this crate's from the same command line. Each writes one line a frame: the base gate's line (pcengine-rust's `scripts/pce_trace.py`, imported by path, and its `trace::frame_line`: the frame counter, the master clock, the count and SHA-1 of the CPU bus log, the SHA-1 of the picture, the count and SHA-1 of the mixed audio and every field of the CPU's state) and `cmd=N:SHA-1`, the drive's command log of the frame (each command's bytes with the master clock the bus had when it ran). A case passes when the two files are identical. Otherwise the first differing frame is named and both sides run again with `--detail` on it, which narrows the difference to the first differing bus cycle (the base gate's comparison and narrowing, imported by path). The reference runs at an eighth to a quarter of real time, and its trace of a case never changes while the pins do not: each is kept in `external/refcache`, named by the case and a hash of its frames, card, disc and arguments, so a rerun costs the Rust side only (the 45 probe cases then take half a minute on six cores, against about seven minutes of six PyPy processes; the six discs, with their extraction, two minutes against an hour and a half). A real disc is extracted with `chdman extractcd` into `scratch/disc/`, **one at a time**, and removed when its case ends. **In all, 42,100 frames in 52 cases, and no case has ever differed**: the transcription was identical to the reference on the first run of each. (The per-cycle narrowing has therefore only been exercised by the seeded faults.) **Rungs 2 and 3: the probe card.** `scripts/make_cdprobe.py` assembles an 8 KiB card, this repository's own code and not a ROM of anything, that takes the System Card's place in the slot and drives the unit as a BIOS would, through `$1800-$180F`, `$18C0-$18C7`, `$1A00-$1AFF` and the banks the unit claims: the registers at power-on; backup RAM (locked reads, the unlock, the header, the lock by a read of `$1803`); CD RAM and the Super System Card's RAM; TEST UNIT READY, READ TOC of every kind, an unknown command, a READ past the disc and REQUEST SENSE in both lengths; READ through `$1801` with the handshake and through `$1808` with the auto-ACK, of data and of an audio sector, with a count of zero, by a late reader (the re-read penalty), aborted by SEL in data in (the 8-byte message, the command phase that comes back by itself), and reset through `$1804` in mid-transfer; the ADPCM RAM port both ways with the busy bits read every 15 master clocks, a write at length zero, the length latch, playback with and without the stop bit, the reset bit held, a signal driven into the rail, the CD-to-ADPCM DMA of a sector and its playback under the fader aimed at ADPCM; CD audio started by track, by MSF and by LBA, playing and paused, the `$1805/$1806` latch and its guard, READ SUBQ while playing, paused and stopped, the fader slow and fast, PAUSE, AUDIO END in modes 1 (loop), 2 (busy to the end, then status), 3 and 0, a start past the disc and a data read that takes the head from the music; the Arcade Card's ID, its four ports through `$1A00` and through banks `$40` and `$42`, the offset triggers, the signed offset, the mirror, and the shift and rotate unit. **Every IRQ2 source the unit has** (status/message `$20`, data in `$40`, ADPCM half `$04` and end `$08`) is enabled in turn and taken by a handler that reads `$1803`, `$1800` and `$180C` (eight interrupts in the default run; the subchannel source `$10` is not built in the reference). It ends in a loop, music and ADPCM repeating, that reads the registers for ever, so a reset from the host shows. 43 drive commands, 9,636 ADPCM samples. Every wait has a timeout, so the card goes on, differently, whatever a switch does. The cases, 520 frames each on the synthetic discs of `scripts/make_discs.py` (`mixed`: audio, data, audio; `data`: one data track; `pregap`: two FILEs with stored `INDEX 00` pregaps, the shape `chdman` writes): | Cases | What is crossed | | --- | --- | | `probe-base` | the Arcade Card fitted, the card built as a Super System Card | | `probe-plain`, `probe-no-super`, `probe-us-tg16` | no Arcade Card and a plain System Card (by size); a Super System Card refused by `super_system_card = false`; the US ids on the TurboGrafx-16 row | | `probe-no-disc`, `probe-data-disc`, `probe-pregap-disc` | an empty drive (every command but REQUEST SENSE fails), a disc without audio, a disc in two files with pregaps | | `probe-bram` | a backup RAM image put back by the host | | `probe-reset-button`, `probe-reset-power`, `probe-reset-power-early` | `Board::reset` from the host: `Button` at frame 460; `PowerOn` at frame 470 with music and ADPCM running; `PowerOn` at frame 250 in the middle of the ADPCM section, then `Button` | | 34 `sw-` cases | each of the 31 named switches away from its default: the drive's twelve timings and lengths (`ScsiSwitches`), the unit's two (`UnitSwitches`), the fader's four times and `PCETECH_FADE` and `SUBQ_STATUS` (the reference's `CddaPlayer` attributes), the ADPCM unit's six (`AdpcmSwitches`; the two busy times at Mednafen's values and at 0), the Arcade Card's five (`ArcadeSwitches`); the DMA's delay both shorter (30 master clocks, where the DMA finds the RAM still busy and asks again) and longer | **A switch that changes nothing proves nothing**: if the reference's trace with the switch is its trace without, both sides agree whether or not this crate reads the switch. `scripts/switch_effect_cd.py` compares each case's reference trace with its baseline's (the probe with every default; for the two `PCETECH_*_SECONDS` the `PCETECH_FADE` case; for `RESET_CLEARS_REGISTERS` the `Button` reset) and fails if a case changes nothing. The first run found six that did: the probe never read backup RAM past the header before writing it, read the ADPCM busy bits only after both busy times had passed, and wrote ADPCM RAM "at length zero" with the end flag already up (its own first read of `$180A` had raised it). It does all of that now: 43 of 43 change the trace, and the `Button` reset alone, which does nothing to this machine unless a switch says so, changes nothing, as it should. **Rung 4.** `syscard3.pce` on the `mixed` disc, RUN held for 20 frames from frame 450 (the reference's `tests/test_boot_slow.py`): the BIOS draws its screen, takes RUN, issues TEST UNIT READY, READ TOC and READ, and finds no IPL. 700 frames, 6 drive commands, identical. **Rung 5.** Each CHD of the user's library is extracted with `chdman extractcd` into `scratch/disc/`, run on both sides with `syscard3.pce` on the PC Engine row with RUN held for 20 frames from frame 450 (the runs of the reference's records), and removed; one disc at a time. | Disc | Extracted | Arcade Card | Drive commands | What plays | The reference's trace took | Result | | --- | --- | --- | --- | --- | --- | --- | | Ryuuko no Ken (Japan) (En,Ja,Es) (FACT) | 464 MiB, 32 tracks | fitted | 12 | CD audio from frame 1154; ADPCM in four stretches (47,410 samples) | 311 s | identical, 3,000 frames | | Mad Stalker - Full Metal Force (Japan) | 586 MiB, 34 tracks | fitted | 455 (streaming reads) | CD audio in frames 964-1253 and from 2275 | 694 s | identical, 3,000 frames | | Ginga Fukei Densetsu Sapphire (Japan) | 389 MiB, 17 tracks | fitted | 19 | CD audio from frame 1792 | 968 s | identical, 3,000 frames | | The Addams Family (USA) | 13 MiB, 1 track | no | 18 | ADPCM from frame 1005 (533,755 samples, DMA'd from the disc) | 1,113 s | identical, 3,000 frames | | Pyramid Plunder (USA) (Unl) | 2 MiB, 1 track | no | 12 | ADPCM (114,688 samples, two ends) | 1,243 s | identical, 3,000 frames | | Insanity (USA) (Unl) | 212 MiB, 13 tracks | no | 10 | CD audio from frame 603 (a looping track) | 1,178 s | identical, 3,000 frames | 18,000 frames; every bus cycle, every picture and each of the 13.3 million mixed samples equal. The command counts and the ADPCM sample counts are also those the reference's own records give for these runs (m7, m8 and m9: 12, 455 and 19 commands; 533,755 samples and one end flag; 114,688 and two). No disc was left out. What these runs are is what the reference's were: openings and first screens, with no input beyond RUN. **Rung 6.** The base board's `save_state` / `load_state` and its snapshot pair cover this machine through `DeviceState`: nothing of the base crate was changed. As the reference's `scripts/cd_state.py` (`trace::roundtrip` over this machine): a run is saved some instructions into a frame, the state loaded into a fresh machine (which opens the disc itself) and into one that had run half as long, and the 60 frames after compared by the gate's own lines; the loaded machine saved at once gives the same bytes. Then the snapshot pair: 30 frames, after each a snapshot, two frames run ahead with other buttons held, the snapshot put back; every frame's line and the end state equal the plain run's. | Run | Saved | A state | A snapshot | | --- | --- | --- | --- | | The System Card on the `mixed` disc (rung 4) | 777 instructions into frame 480, while the BIOS reads the disc | 10 KiB | 569 KiB | | The probe card | 1,234 instructions into frame 200 (ADPCM playing), and 4,321 into frame 265 (CD audio playing) | 4 KiB | 2.6 MiB (the Arcade Card's RAM) | | Ryuuko no Ken | 777 instructions into frame 2000 (Arcade Card, CD audio and ADPCM in use) | 340 KiB | 2.6 MiB | | Mad Stalker | 2,001 instructions into frame 1500 (streaming reads) | 82 KiB | 2.6 MiB | `tests/state.rs` has the reference's `tests/test_state.py` (the unit, the ADPCM RAM, the Arcade Card and the Super System Card's RAM come back; a state holds no sector and no System Card byte) and the refusals, each leaving the machine untouched: **another disc** ("a state made with another expansion device or other media (another disc?)"; two discs with one table of contents are not told apart, the reference's rule), an empty drive, **another System Card** (another image, or the same image without its Super RAM), **a machine without the Arcade Card** (and one with it, for a state made without); and the unit's own round trip in the middle of a read with ADPCM playing and the fader set, register for register and sample for sample; that loading keeps the machine's switches and wiring; the snapshot pair. ### Seeded faults `scripts/seeded_faults_cd.py` plants one single-line fault at a time in a copy of `src/`, builds it, and runs the checks cheapest first until one fails: rung 2 (the probe with every default), rung 4 (the System Card), rung 3 (the probe on every machine, medium and switch), rung 1 (`cargo test`, the transcribed unit tests), rung 6 (`tests/state.rs`, then the round trips on the synthetic cases), and the real discs last. | Fault | Module | What it changes | Caught by | | --- | --- | --- | --- | | `msf-without-the-lead-in` | `disc.rs` | an LBA's absolute time leaves out the two-second lead-in (READ TOC, READ SUBQ) | rung 2 (`probe-base`) | | `data-from-the-sync` | `disc.rs` | a data sector's payload is taken 4 bytes early (the header counted as data) | rung 2 (`probe-base`) | | `pregap-belongs-to-no-track` | `disc.rs` | a track's INDEX 00 pregap is not part of it: its sectors read as zeros | rung 3 (`probe-pregap-disc`) | | `second-file-at-lba-0` | `disc.rs` | every FILE of a cue sheet starts at LBA 0 (they do not lie end to end) | rung 3 (`probe-pregap-disc`) | | `audio-track-read-as-data` | `disc.rs` | READ of an audio sector returns its bytes, not zeros | rung 2 (`probe-base`) | | `short-seek-three-vsyncs` | `seek.rs` | a gap under 5 sectors costs 3 VSYNC (seektime.c's dead branch, C20) | rung 2 (`probe-base`) | | `seek-ignores-the-rotation` | `seek.rs` | the half rotation is the starting zone's, not the target's | rung 1 (`seek_times_are_the_references_doubles`) | | `fade-aimed-at-the-other-source` | `cdda.rs` | `$180F` bit 1 aims the fade at CD audio, not ADPCM | rung 2 (`probe-base`) | | `loop-plays-on` | `cdda.rs` | AUDIO END mode 2 loops and mode 1 stops at the end of its range | rung 2 (`probe-base`) | | `audio-end-exclusive` | `cdda.rs` | playback stops a sector early (the end sector is not played) | rung 2 (`probe-base`) | | `faded-sample-rounded` | `cdda.rs` | a faded CD sample is rounded, not cut toward zero (Python's int()) | rung 2 (`probe-base`) | | `audio-end-leaves-a-stopped-player` | `cdda.rs` | AUDIO END does not start a stopped player | rung 3 (`probe-data-disc`) | | `read-lba-16-bits` | `scsi.rs` | READ(6) drops the top five bits of its 21-bit LBA | rung 2 (`probe-base`) | | `no-reread-penalty` | `scsi.rs` | a missed sector comes round again after one sector time, not the re-read penalty | rung 2 (`probe-base`) | | `sel-in-data-in-not-an-abort` | `scsi.rs` | SEL during data in starts a command as from any other phase: no 8-byte abort | rung 2 (`probe-base`) | | `irq-sources-swapped` | `scsi.rs` | REQ in data in raises the status/message source and the other way round | rung 2 (`probe-base`) | | `seek-from-the-last-read` | `scsi.rs` | a seek is timed from the last data sector even while music plays | rung 2 (`probe-base`) | | `queued-timer-rearmed` | `scsi.rs` | a drive timer of the same kind is queued again only while one is pending | rung 2 (`probe-base`) | | `toc-track-type-audio` | `scsi.rs` | READ TOC marks audio tracks as data and data tracks as audio | rung 2 (`probe-base`) | | `subq-relative-from-zero` | `scsi.rs` | READ SUBQ's track-relative time is the disc's | rung 2 (`probe-base`) | | `ack-pulse-a-cycle-long` | `scsi.rs` | the `$1808` auto-ACK pulse lasts one CPU cycle longer | rung 2 (`probe-base`) | | `sense-not-cleared` | `scsi.rs` | REQUEST SENSE leaves the sense key for the next one | rung 2 (`probe-base`) | | `low-nibble-first` | `adpcm.rs` | a byte's two samples both come from its low nibble | rung 2 (`probe-base`) | | `length-16-bits` | `adpcm.rs` | the length counter wraps at 16 bits (playing past zero without the stop bit) | rung 2 (`probe-base`) | | `adpcm-rounds-half-away` | `adpcm.rs` | a faded ADPCM sample rounds a half away from zero (Rust's round), not to even (Python's) | rung 1 (`a_faded_sample_on_a_half_rounds_to_even_as_pythons_round_does`) | | `read-pointer-not-stepped-back` | `adpcm.rs` | `$180D` bit 3 copies the latch to the read pointer as it is, whatever bit 2 says | rung 2 (`probe-base`) | | `decoder-keeps-its-state` | `adpcm.rs` | a play request restarts the signal but not the step index (C-ad1) | rung 2 (`probe-base`) | | `end-flag-survives-the-length-latch` | `adpcm.rs` | latching a new length leaves the end flag (and its IRQ2 source) up | rung 2 (`probe-base`) | | `sample-clock-from-the-write` | `adpcm.rs` | the first sample of a playback comes at the play write, not a period after it | rung 2 (`probe-base`) | | `signed-offset-unsigned` | `arcade.rs` | the signed-offset bit does not reach below the base for an access | rung 2 (`probe-base`) | | `rotate-shifts` | `arcade.rs` | `$1AE5` shifts left where it should rotate | rung 2 (`probe-base`) | | `base-increment-16-bits` | `arcade.rs` | an auto-incremented base wraps at 16 bits | rung 2 (`probe-base`) | | `trigger-on-either-byte` | `arcade.rs` | a write of the offset's high byte adds it into the base in every trigger mode | rung 2 (`probe-base`) | | `irq-raised-in-reset` | `unit.rs` | a bus source can raise its active bit while `$1804` holds the drive in reset | rung 2 (`probe-base`) | | `bram-stays-unlocked` | `unit.rs` | a read of `$1803` does not lock the backup RAM | rung 2 (`probe-base`) | | `dma-retry-late` | `unit.rs` | the CD-to-ADPCM DMA asks the busy RAM again every 6 master clocks, not 3 | rung 3 (`sw-unit.DMA_BYTE_CLOCKS`) | | `latch-guard-not-set` | `unit.rs` | a second `$1805` write right after the first toggles the channel again | rung 2 (`probe-base`) | | `drive-enables-kept-in-reset` | `unit.rs` | `$1804` bit 1 does not clear the drive's IRQ enables | rung 1 (`reset_register_clears_drive_irq_enables_and_blocks_new_irqs`) | | `unit-forgets-the-fader` | `unit.rs` | a loaded state keeps the fader of the machine it is loaded into | rung 6 (`loading_keeps_the_switches_and_the_wiring`) | | `identity-without-the-disc` | `unit.rs` | a state does not name its disc: another disc's machine takes it | rung 6 (`a_state_names_the_disc_by_its_contents_table_and_holds_no_sector`) | | `super-ram-a-bank-short` | `syscard.rs` | the Super System Card's RAM starts at bank $69 | rung 2 (`probe-base`) | | `id-registers-region-blind` | `syscard.rs` | `$18C5` answers the other region's value | rung 2 (`probe-base`) | | `card-forgets-its-ram` | `syscard.rs` | a loaded state keeps the Super System Card RAM of the machine it is loaded into | rung 6 (`the_unit_the_adpcm_ram_and_the_arcade_card_come_back`) | | `switches-not-handed-to-the-bus` | `board.rs` | the builder leaves the drive's timings at their defaults whatever it is given | rung 3 (`sw-scsi.SEL_TO_COMMAND_PHASE`) | | `arcade-card-always-fitted` | `board.rs` | every machine has an Arcade Card | rung 3 (`probe-plain`) | **45 caught, 0 missed**: 33 by rung 2 (the probe card with every default), 6 by rung 3 (the pregap disc twice, the data-only disc, the machine without an Arcade Card, and two switch cases), 3 by rung 1's unit tests, 3 by `tests/state.rs`. The System Card's boot, the round trips on the synthetic cases and the real discs come later in the order and were never needed. The first run of this list missed seven. One changed no behaviour, which makes it not a fault, and was dropped ("an Arcade Card access runs the drive up to the access": the board has already run the unit up to that master clock; see the notes on the reference). Five were holes in the probe card, not in the crate: it never sent a READ whose LBA needs its top five bits (`read-lba-16-bits`), never let the ADPCM length pass 16 bits (`length-16-bits`), never stepped an Arcade Card base past 16 bits (`base-increment-16-bits`; the reference's own test of the 24-bit wrap passes with a 16-bit one too), never raised a drive source while `$1804` held the reset bit (`irq-raised-in-reset`), and no case made the CD-to-ADPCM DMA find the RAM busy, so its retry never ran (`dma-retry-late`). The probe does the first four now, and the `DMA_BYTE_CLOCKS` switch case runs the fifth (at 30 master clocks the DMA arrives while the last byte is still being written; at the default 60, and on every disc run, it never does). The seventh, `adpcm-rounds-half-away`, cannot be reached from a program in any reasonable time (a faded sample falls on an exact half only when the fader's gain is an exact binary fraction at a sample instant) and is caught by a unit test written for it. `signed-offset-unsigned` was caught by a unit test only, because the probe wrote through a signed offset and never read back; it reads back now. ### Speed Speed is the fast fork's job; this is the figure to measure it against. Frames per second from power-on, nothing logged, the mixed audio taken every frame (`pcecd-bench`, `scripts/bench_cd.py`), one core: | Run | pcenginecd-rust | pcenginecd-python on PyPy 7.3.20 (whole run; second half) | | --- | --- | --- | | Ryuuko no Ken, 3,000 frames, Arcade Card | 210-247 | 10.9; 16.3 | | Mad Stalker, 3,000 frames, Arcade Card | 228-232 | 12.4; 15.2 | | The System Card on the `mixed` disc, 700 frames | 164-174 | 7.4; 7.7 | About 3.8 times real time (59.8 frames a second) on a disc against the reference's 0.2, some 20 times the reference, on a machine at load 16 (the Rust runs one after another, three times each; the reference's once). The time is the base board's: the unit costs one early-out a CPU cycle (`catch_up`), as in the reference. ## Where Rust forced a difference Each module's header says so; together: - **The board owns the card and the unit** (`board.rs`). The reference's `PcEngineCd` keeps `card`, `unit`, `arcade` and `board` side by side; here `PcEngineCd` is the description (the reference's constructor arguments with its defaults, and every named switch) and `build()` hands back the base board's `System`. `board::unit`, `card` and `arcade` reach the devices inside a board. The reference's `**board_kwargs` is the `board` field, a `BoardOptions` whose card and port are replaced. - **`BoardPins` arrives with each call** (the base board's rule), so there is no `bind`. A unit driven with no board behind it takes the base crate's `DetachedPins`. - **Callbacks became lists.** The reference's SCSI bus and ADPCM unit call the unit (`_bus_irq`, `_adpcm_irq`) and its audio player calls the bus (`on_good_status`). Here the bus and the ADPCM unit list their `(mask, level)` changes in order (`irq_changes`) and the unit applies them after each call (`sync_irq`, which also sets its bit on IRQ2); the player counts the good statuses it owes (`good_status_due`) and the bus answers them right after the player ran. Nothing the callbacks read can change in between, so the order of effects is the reference's. - **Who holds what.** The bus owns the audio player (`unit.bus.cdda`, `unit.cdda()`); the ADPCM unit is its own audio source (the reference's `AdpcmSource` object is three fields and the `AudioSource` impl of `Adpcm`); the two are what `PortDevice::audio_sources` hands the mixer, after the PSG, where the reference appends them to the board's list. The fader both sources ask (`$180F`) is one `Fader` value behind an `Rc>`, and the disc the bus and the player share is an `Rc`. The reference's ADPCM source first catches the unit up to the mixer's clock; the board has always done that already, and here the source cannot reach the unit. - **The id registers** `$18C0-$18C7` are asked of `pins.card` when it is a `SystemCard` (the reference's unit keeps the card it was built with). - **Switches.** The reference's class attributes are `ScsiSwitches`, `UnitSwitches`, `AdpcmSwitches`, `ArcadeSwitches` and the fade times of `Fader`, public fields of their devices and together `CdSwitches` in the builder; `CddaPlayer.SUBQ_STATUS` is `subq_status`. A subclass with other attributes there is `ArcadeCard::with(switches)` here. - **The disc** (`disc.rs`): the sector store is a trait and the cue sheet is parsed from text (below); no CHD; no `close`. LBAs are `i64` with Python's floor division (an audio command may name a position before LBA 0); `to_bcd` answers the low eight bits where the reference's integer is unbounded; a `TRACK` before any `FILE`, which the reference attaches to the last file through a negative index, is refused; a track without `INDEX 01` is an error where the reference raises `KeyError`. - **Python's arithmetic** is spelled out: the seek model's `int`/`float` mix in `i64` and `f64` in the reference's order (`tests/disc.rs` holds twelve of its doubles, bit for bit), `-(-a // b)` as `ceil_div`, `int()` as truncation, `round()` to even. The ADPCM step table is the 49 integers `floor(16 * 1.1 ** index)` written out, so it does not depend on a platform's `pow`. - **Save states**: the base board's format, through `DeviceState`. The unit saves everything that changes as the console runs (the bus and the player, the ADPCM unit with its RAM, CD RAM, backup RAM, the Arcade Card with its 2 MiB, the fader) as one bincode value; the System Card saves its RAM. The switches, the wiring and the drive's command log stay the machine's own, and the player's decoded sector is not saved. The unit's identity names the disc by `Disc::state_identity` (the reference's digest of the table of contents, the same hexadecimal string) and says whether an Arcade Card is fitted; the card's names its image, its region and whether it is a Super System Card. A state is not portable to the reference or back. - **Smaller ones**: a `bram` image longer than 2 KiB is cut (the reference's slice assignment would grow the RAM); a sector asked for with no disc in the drive reads as zeros (the reference asserts); `Disc::first_track` of a disc without tracks is 0 (the reference raises). - **Not carried over**: `Disc.from_chd`; the reference's scripts that boot a disc to pictures and drive Geargrafx and Beetle PCE (it has been compared with those; this crate is judged against it). - **Added**: `CdUnit::bram`, `set_bram` (the host keeping backup RAM between sessions), `trace.rs`, the three binaries, `examples/probe_report.rs`. ## Using the crate (the fast fork, the browser page) ```rust use pcenginecd_rust::board::{self, PcEngineCd}; use pcenginecd_rust::disc::{parse_cue, CueSource, Disc}; use pcenginecd_rust::pcengine_rust::pads::{self, Pad2}; use pcenginecd_rust::pcengine_rust::state::{load_state, save_state}; /// `system_card`: the BIOS image. `cue`: the sheet's text. `length_of`: the byte length of a /// file the sheet names. `read`: bytes of file `index` from `offset` into the buffer, returning /// how many (a page slices the user's `File`). `kept_bram`: backup RAM from the last session. fn run( system_card: &[u8], cue: &str, mut length_of: impl FnMut(&str) -> Result, read: impl FnMut(usize, u64, &mut [u8]) -> usize + 'static, kept_bram: Option>, ) -> Result, String> { // The cue sheet without a filesystem, and a disc over any reader. let sheet = parse_cue(cue, &mut length_of)?; let disc = Disc::from_cue(&sheet, Box::new(CueSource::new(&sheet, read))); // The machine: System Card bytes, a disc (or None), the options. let mut machine = PcEngineCd::new(system_card, Some(disc)); machine.arcade_card = true; // fit the Arcade Card (Sapphire, Mad Stalker, Ryuuko no Ken) machine.bram = kept_bram; // None: formatted and empty machine.board.pad = Some(Box::new(Pad2::new())); let mut system = machine.build()?; // One frame, as on the base board: buttons, run, sound, picture. system.board_mut().set_pressed(0, pads::RUN); system.run_frame(); let _samples: Vec<(i16, i16)> = system.board_mut().take_audio(); // PSG + CD audio + ADPCM let _picture = system.board().capture.last_frame.as_ref(); // Save states are the base board's; the disc is named, never stored. let state = save_state(&system); load_state(&mut system, &state)?; // Backup RAM out, for the host to keep (2,048 bytes). let unit = board::unit(system.board_mut()).ok_or("no CD unit")?; Ok(unit.bram().to_vec()) } ``` - **Building a machine**: `PcEngineCd::new(system_card: &[u8], disc: Option)`, then its public fields: `arcade_card`, `bram`, `super_system_card` (`None`: a 256 KiB image is a Super System Card), `region_us` (the id registers a US System Card answers), `switches` (`CdSwitches`), and `board`, the base board's `BoardOptions` (machine row, pad, its own switches). `build()` gives the base board's `System`, `build_board()` the `Board`. Everything of the base board's README then applies: `run_frame`, `take_audio`, `capture.last_frame`, `set_pressed`, `save_state` / `load_state`, `save_snapshot` / `load_snapshot`. - **A disc**: `Disc::new(tracks, sector_count, Box)` is the whole of it. `SectorSource` has one method, `read_sector(&mut self, lba, &mut [u8; 2352])`, called only for `0 <= lba < sector_count` (the disc answers zeros outside by itself). Ready-made: `MemorySource` (a whole image in memory), and `CueSource`, which maps an LBA to a byte range of one of a cue sheet's files; `ImageReader` is `read_at(file, offset, &mut [u8]) -> usize`, implemented by any closure of that shape (a page over `Blob.slice`), by `MemoryImages` (whole files in memory) and, off wasm, by `FileImages`. Reads are synchronous: a page whose file access is asynchronous keeps the sectors it has fetched and feeds the source from them. - **A cue sheet without a filesystem**: `parse_cue(text, &mut |name| -> Result)` gives a `CueSheet { files: [CueFile { name, sectors, first_lba }], tracks, sector_count }`; the closure answers a named file's length in bytes. `CueSheet::locate(lba)` is `(file index, byte offset)`. `Disc::from_cue(&sheet, source)` makes the disc; `Disc::from_cue_path(path)` (not on wasm) is the reference's `Disc.from_cue`. The grammar is the reference's: `FILE`, `TRACK` with `MODE1/2352` or `AUDIO`, `INDEX 00` and `01`, several FILEs end to end; `PREGAP` and other track modes are refused. `Disc::from_memory(vec![(is_data, bytes), ...])` builds a disc from raw tracks (the tests' discs). - **The Arcade Card**: `machine.arcade_card = true`. A state made with it is refused by a machine without, and the other way round. - **Backup RAM**: `board::unit(system.board_mut())` is the `CdUnit`; `unit.bram()` is its 2,048 bytes, `unit.set_bram(&bytes)` puts them back into a running machine, and `PcEngineCd::bram` starts one with them. (A save state carries backup RAM too.) - **Changing the disc**: `unit.insert(Some(disc))` / `insert(None)`. - **The devices**: `board::unit`, `board::card` (the `SystemCard`) and `board::arcade` reach into a `Board`; `unit.bus` is the drive (`record_log` and `log` are its command log), `unit.cdda()` the audio player, `unit.adpcm` the ADPCM unit. For wasm: the library builds for `wasm32-unknown-unknown` (`scripts/check.sh` does it); nothing in it touches a file, a clock or a thread outside `Disc::from_cue_path`, `FileImages` and `trace::Setup` (the first two are not compiled there, the third refuses a disc path). The devices are not `Send` (`Rc`). The only floating point the sound depends on is the fader's linear gain and the base board's mixer; the seek model's doubles decide timing, and are plain `f64` arithmetic with no library function. ## Layout Each `src/*.rs` file is the transcription of the `pcenginecd_python` module of the same name: `disc`, `seek`, `cdda`, `scsi`, `adpcm`, `arcade`, `unit`, `syscard`, `board`. Not from the reference's package: `trace.rs` (the gate's command line and line, `roundtrip` and `runahead` over this machine). Binaries: `pcecd-trace`, `pcecd-state-roundtrip`, `pcecd-bench`. Tests: `tests/common/mod.rs` is the reference's `tests/discs.py` and `helpers.py`; `disc.rs`, `scsi.rs`, `cdda.rs`, `adpcm.rs`, `arcade.rs`, `unit.rs`, `board.rs` and `state.rs` are its `test_*.py`; `reference_notes.rs` is this README's last section. `examples/probe_report.rs` says what a run of the probe card touched (interrupts taken, frames with sound). Not transcribed: the reference's two slow tests as tests (they are rungs 4 and 6 here), `scripts/cd_boot.py` and its picture tools, `beetle_press.py`. ## Notes on the reference Nothing found is a divergence: this crate does what pcenginecd-python `v0.1.0` does in each case, and the gate runs through all of them. They are places where the reference's behaviour looked unintended while it was being transcribed, left for its maintainers: 1. **The drive's clock stands still between events.** `CdUnit.catch_up` runs the bus, and so moves `ScsiBus.now`, only when an event is due or none is pending (`if self._next_event is None or mclk >= self._next_event`). While some event waits in the future (the end of a CD audio track, the next ADPCM sample), a register access does not move `now`, and every timer a write starts (SEL to the command phase, the REQ of the next command byte, an answer's delay, the auto-ACK pulse, a seek) counts from the last time the bus happened to run. `scripts/reference_notes.py` shows it on the reference: SEL to the command phase takes `SEL_TO_COMMAND_PHASE` = 75,000 master clocks on an idle drive and **0** when CD audio has been playing for a second (the timer was queued a second in the past and fires at the next cycle). With ADPCM playing the clock is at most one sample period old. `tests/reference_notes.rs` asserts the same two numbers here. So the drive's tier-5 timings apply in full only while nothing else is pending; the fix would be to run the bus up to `mclk` in every register access. 2. **The unit's own `catch_up` calls change nothing on a board.** `read` and `write` begin with `self.catch_up(mclk)` (and the Arcade Card's path skips it, "no clock"), but the board has run the port device up to the same master clock an instant before every access, so the call finds nothing due. A first version of the seeded-fault list had "an Arcade Card access runs the drive" as a fault; no check could catch it, because it is not one. (Note 1 is the other face of this: neither call moves the bus's clock when nothing is due.) 3. **A power-on reset keeps some of the unit's timers**: `CdUnit.reset` does not clear `_dma_at`, `_next_event` or `_latch_guard_until`, and `Adpcm.power_on` reports the output going idle at time 0, not at the reset, so the event is filed behind later ones (it takes effect at the next mixed sample all the same). `probe-reset-power` and `probe-reset-power-early` run through it, identically. 4. **`ScsiBus.reset` drops its IRQ levels without telling the unit** (`_irq_levels = (False, False)` and then `_update_irq()`, which sees no change): the unit's active bits `$20`/`$40` survive a bus reset unless the caller clears them, which both callers do (`$1804` masks them, a power-on reset zeroes them). Not reachable as a fault, noted because it reads as if the callback did it. 5. Small things: `CdUnit(bram=...)` with more than 2 KiB grows the RAM (slice assignment); `Disc.from_cue` attaches a `TRACK` that comes before any `FILE` to the last file (index -1); `to_bcd` of 160 or more does not fit a byte; `ASC_INVALID_COMMAND` is never used (an unknown command answers Good); the unit's docstring says the board calls `catch_up` "every cycle", and it is called at every advance, several a cycle on a stretched access. ## Reproducing ```text scripts/fetch_reference.sh # pcenginecd-python, pcengine-python, huc6280-python, 6502-python at their pins scripts/rung1.sh scripts/rung2.sh scripts/rung3.sh scripts/rung4.sh scripts/rung5.sh # extracts one disc at a time into scratch/ and removes it scripts/rung6.sh scripts/rung7.sh # after a full gate run (it uses the reference cache) scripts/check.sh # cargo fmt --check, clippy -D warnings, the library for wasm32 scripts/bench_cd.py CASE # frames per second, both sides ``` `$SYSCARD` (default `/data/emu/share/batocera/bios/syscard3.pce`), `$LIBCD` (the disc library, default `/data/emu/roms-retrobat/pcenginecd`), `$PYPY` and `$PCENGINE_RUST` (the base board's checkout, for its scripts; default `../pcengine-rust`) name the user's files. `scripts/make_cdprobe.py` and `scripts/make_discs.py` build the probe card and the synthetic discs into `scratch/`; the gate runs them itself. `JOBS` sets the parallel cases (at most 8). The reference needs no install: the gate runs PyPy with `PYTHONPATH` over the four `src/` directories of `external/`. CI (`.github/workflows/ci.yml`) runs `cargo fmt --check`, `cargo clippy -D warnings`, `cargo test` and the wasm build; the lockstep gate needs the reference, the System Card and the discs and runs by hand. `docs/handoff-brief.md` is the brief this was built from, with what was built appended. ## Licence MIT (see `LICENSE`). The seek model's zone table and shape derive from Dave Shadoff's MIT-licensed `seektime.c`, through the reference: [NOTICE.md](NOTICE.md). Nothing else third-party is committed: the reference, the System Card and the discs are fetched or read in place.