Skip to main content

rustynes_core/
lib.rs

1//! Cycle-accurate NES emulator core.
2//!
3//! This crate is the public entry point for embedders (frontend, test harness,
4//! future ports). It owns the scheduler, the bus, save-state serialization,
5//! the rewind ring, and the `Nes` facade. Per-chip implementations live in
6//! `rustynes-cpu`, `rustynes-ppu`, `rustynes-apu`, and `rustynes-mappers`, and are re-exported
7//! from this crate so downstream consumers depend on `rustynes-core` only.
8//!
9//! See `docs/architecture.md` and `docs/scheduler.md` for the design.
10
11#![no_std]
12// The chip stack carries no `unsafe`; `forbid` makes that a compile-time
13// guarantee rather than an observation (core audit section 2.1). The FFI
14// and platform `unsafe` lives in the frontend, cheevos and mobile crates.
15#![forbid(unsafe_code)]
16#![warn(missing_docs)]
17
18extern crate alloc;
19
20#[cfg(test)]
21extern crate std;
22
23pub use rustynes_apu;
24pub use rustynes_cpu;
25pub use rustynes_mappers;
26pub use rustynes_ppu;
27
28mod bus;
29// v2.0 R1c-1 diagnostic — per-instruction (PC, cpu_cycle) trace ring (gated).
30#[cfg(feature = "cpu-instr-cycle-trace")]
31pub use bus::instr_trace;
32pub mod bk2_interop;
33mod bus_snapshot;
34mod controller;
35#[cfg(feature = "cpu-boot-trace")]
36pub mod cpu_boot_trace;
37pub mod debug;
38pub mod game_corrections;
39pub mod genie;
40// v3.5.0 (`FE-06`) — the host-facing warning codes every frontend shares
41// (moved from the mobile bridge, which re-exports them to Kotlin / Swift).
42pub mod host_warning;
43pub mod input_device;
44#[cfg(feature = "irq-timing-trace")]
45pub mod irq_trace;
46// v1.7.0 "Forge" G4 — legacy NES TAS movie importers (.fcm / .fmv / .vmv;
47// .mc2 is PC Engine and rejected). `no_std`-clean byte parsers, mirroring the
48// `.fm2`/`.bk2` interop design; reuse the canonical power-on alignment.
49pub mod legacy_movie;
50// v2.9.8 — the emulation options a movie or a netplay session must agree on.
51mod hardware_options;
52mod movie;
53// v3.5.0 (`T-MOVIE-INPUT-STREAM`) — the non-controller half of a movie frame.
54mod movie_extra;
55pub mod movie_interop;
56mod nes;
57mod rewind;
58pub mod save_state;
59pub mod scheduler;
60// v3.5.0 (`T-SPEEDRUN-MEMIF`) — speedrun auto-timing: RetroAchievements-
61// grammar RAM predicates, times in master-clock cycles. Read-only over `Nes`.
62pub mod speedrun;
63// v3.6.0 (`T-AUDIO-STEMS`) — per-channel stems re-rendered offline from the
64// APU's mix trace; output-only, so it needs the `debug-hooks` recording.
65#[cfg(feature = "debug-hooks")]
66pub mod stems;
67// v3.6.0 (`T-AUDIO-STEMS`) — trace-assisted NSF ripping (needs the access log).
68#[cfg(feature = "debug-hooks")]
69pub mod nsf_rip;
70pub mod vs_db;
71// v2.0.0 beta.5 (Workstream C) — the Vs. DualSystem dual-core wrapper: two
72// complete Nes instances + the cabinet's $4016-bit-1 comms protocol, the
73// shared 2 KiB WRAM swap, and the 5-CPU-cycle soft-lockstep. See
74// `docs/audit/vs-dualsystem-design-2026-06-11.md`.
75pub mod vs_dualsystem;
76// v1.7.0 "Forge" Workstream D2 — the Zwinder-class compressed, density-tiered
77// state manager (XOR-delta + LZ4 over the v1.6.0 uncompressed greenzone, with
78// reserved anchors), scaling the TAStudio greenzone to feature-length TASes.
79// Determinism-neutral: lossless round-trip, no timebase change. See
80// `docs/rewind.md` §Zwinder.
81pub mod zwinder;
82
83/// The APU sample rate `Nes::from_rom` and friends build with when no explicit
84/// rate is given (`44_100` Hz).
85///
86/// Re-exported so a downstream consumer that must *declare* the rate it produces
87/// — the libretro core does, in `retro_get_system_av_info` — can state the real
88/// value instead of transcribing a literal that could silently fall out of step
89/// with the samples actually emitted.
90pub use bus::DEFAULT_SAMPLE_RATE;
91pub use bus::SystemBus;
92#[cfg(feature = "debug-hooks")]
93pub use bus::{AccessRec, EventBpKind, EventBreakHit, EventKind, EventRec, InterruptRec};
94pub use bus_snapshot::{EXPANSION_DEVICE_MAX_LEN, SAVE_STATE_DEVICE_HEADROOM};
95pub use controller::{Buttons, Controller};
96pub use debug::{
97    ApuDebugView, CpuDebugView, MapperDebugView, PpuDebugView, RomSpace, RomWriteError,
98};
99pub use genie::{GenieCode, GenieError};
100pub use hardware_options::{
101    BoardDescription, EMULATION_EPOCH, HardwareOptions, OptionsDecodeError, config_digest,
102};
103pub use host_warning::HostWarning;
104pub use input_device::{
105    BandaiHyperShotState, FamilyKeyboardState, InputDevice, KonamiHyperShotState, PowerPadState,
106    SnesMouseState, VausState, ZapperState,
107};
108pub use legacy_movie::{
109    LegacyMeta, LegacyMovieError, import_fcm, import_fmv, import_mc2, import_vmv,
110};
111pub use movie::{
112    ATTESTATION_CHECKPOINT_INTERVAL, ATTESTATION_MAGIC, ATTESTATION_VERSION, Attestation,
113    AttestationBuilder, BYTES_PER_FRAME, FrameInput, MIN_MOVIE_FORMAT_VERSION,
114    MOVIE_FORMAT_VERSION, MOVIE_MAGIC, Movie, MovieError, MoviePlayer, MovieRecorder, StartPoint,
115    VerifyOutcome, power_on_for_movie, recorded_before_v2_timebase,
116};
117pub use movie_extra::{DeviceInput, ExtraInput};
118#[cfg(feature = "debug-hooks")]
119pub use nes::TraceRec;
120pub use nes::{
121    BarcodeScanError, ConsoleModel, FRAME_DURATION_DENDY, FRAME_DURATION_NTSC, FRAME_DURATION_PAL,
122    MAX_CPU_OVERCLOCK, MAX_EXTRA_SCANLINES, Nes, PowerOnConfig, PowerOnRam,
123};
124// v2.1.7 P5 — re-export the PPU-side hardware-revision knobs at the core surface
125// so downstream consumers (frontend, test-harness) depend on `rustynes-core`.
126pub use rewind::{
127    REWIND_DEFAULT_KEYFRAME_PERIOD, REWIND_DEFAULT_MAX_BYTES, RewindError, RewindRing,
128};
129pub use rustynes_mappers::{Barcode, BarcodeError};
130pub use rustynes_ppu::{PaletteInit, PpuRevision};
131pub use save_state::{
132    BinReader, BinWriter, FORMAT_VERSION, HEADER_LEN, Header, MAGIC, MIN_FORMAT_VERSION,
133    ROM_HASH_TAG_LEN, Section, SectionIter, SnapshotError, THUMBNAIL_HEIGHT, THUMBNAIL_LEN,
134    THUMBNAIL_VERSION, THUMBNAIL_WIDTH, parse_header, tag, tag_string, write_header, write_section,
135};
136pub use scheduler::M2Phase;
137pub use vs_db::{VsDbEntry, lookup as vs_db_lookup};
138pub use vs_dualsystem::{Emu, VsDualSystem};
139pub use zwinder::{
140    ZWINDER_DEFAULT_BUDGET_BYTES, ZWINDER_DEFAULT_KEYFRAME_INTERVAL, ZwinderError,
141    ZwinderStateManager,
142};
143
144/// Returns the crate version string.
145#[must_use]
146pub const fn version() -> &'static str {
147    env!("CARGO_PKG_VERSION")
148}
149
150/// NES region (governs clock dividers, scanline counts, audio rate tables).
151///
152/// See `docs/glossary.md` for definitions.
153#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
154pub enum Region {
155    /// NTSC (Japan, North America, Australia). 60 Hz, 262 scanlines.
156    Ntsc,
157    /// PAL (Europe). 50 Hz, 312 scanlines.
158    Pal,
159    /// Dendy (Russian PAL famiclone). 50 Hz, 312 scanlines, NTSC-style timing.
160    Dendy,
161}
162
163/// Ricoh 2A03 CPU/APU die revision, selecting the hardware-revision difference
164/// in the DMA unit's **"unexpected DMA" extra halt-read** (v2.1.7 "Hardware
165/// Revisions & DMA Frontier").
166///
167/// # The frontier — read this before trusting the non-default arm
168///
169/// The 2A03 shipped in several mask revisions. nesdev
170/// ([DMA](https://www.nesdev.org/wiki/DMA)) documents that when a DMC DMA halt
171/// is requested on a CPU cycle where an OAM (`$4014`) DMA is *also* halting —
172/// the "double-halt" overlap — some silicon performs an **extra** re-read of
173/// the parked 6502 address bus before the transfer resumes (the "unexpected
174/// DMA" read), and this differs by die revision.
175///
176/// **No public reference emulator models this die-revision difference, and no
177/// public test ROM verifies it.** A survey of Mesen2, ares, `BizHawk`,
178/// `TriCNES`, fceux, nestopia, `GeraNES`, and higan (v2.1.7, see ADR 0033)
179/// found that *none*
180/// branch DMA cycle behavior on 2A03 die stepping — the only revision-like
181/// switch any of them models is the orthogonal **console-type** distinction
182/// (Mesen2 `isNesBehavior`: NES-001/AV-Famicom clock a controller only on the
183/// *first* DMA idle read, original Famicom on *every* one), which is a
184/// different axis and is already reflected in this core's default
185/// register-readout model. The die-revision extra-read is therefore a genuine
186/// open frontier: this enum provides the **config surface** for it and a
187/// conservative, deterministic model, but the [`Rp2A03H`](Self::Rp2A03H) arm's
188/// direction is an **unverified hypothesis**, not an oracle-proven behavior.
189///
190/// # Contract
191///
192/// * **Default = [`Rp2A03G`](Self::Rp2A03G)** is **byte-identical** to the core
193///   as it shipped before v2.1.7 (`AccuracyCoin` 141/141, nestest 0-diff, and
194///   every committed DMA oracle ROM — the five `dmc_dma_during_read4` ROMs and
195///   both `sprdma_and_dmc_dma` ROMs — still `Passed`).
196/// * **[`Rp2A03H`](Self::Rp2A03H)** is a purely additive, opt-in knob that
197///   *omits* the double-halt extra read in the model. It is deterministic and
198///   reachable only when explicitly selected; the shipped/default build never
199///   touches it. **On this engine the extra-read gate is a documented no-op on
200///   every committed oracle**, so today `Rp2A03H` produces a **byte-identical**
201///   result to `Rp2A03G` across the entire committed DMA corpus (proven by the
202///   `cpu_2a03_revision` tests): the halted-DMC overlap-read fires but its
203///   parked address is always the post-`$4014` instruction fetch, never a
204///   side-effect register (see below). The revision difference is therefore a
205///   mechanism-level *model*, not an observable divergence — ADR 0033.
206///
207/// The revision is a **config knob re-applied on load, not part of the
208/// save-state** (like the optional OAM-decay model): the only state it
209/// influences is fully re-derived from the deterministic timeline, so a
210/// save/restore round-trip stays byte-identical for a fixed revision. See
211/// `docs/adr/0033-cpu-2a03-revision-dma-frontier.md`.
212#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Default)]
213pub enum Cpu2A03Revision {
214    /// RP2A03G — the common early/mid die the accuracy oracles were captured
215    /// against. **Performs** the double-halt "unexpected DMA" extra read.
216    /// This is the **default** and the byte-identical baseline.
217    #[default]
218    Rp2A03G,
219    /// RP2A03H — a later die modeled as **omitting** the double-halt extra
220    /// read. Opt-in, additive, deterministic — but an **unverified** direction
221    /// (no reference / no ROM proves it; see the type-level docs and ADR 0033).
222    Rp2A03H,
223}
224
225impl Cpu2A03Revision {
226    /// Whether this revision performs the "unexpected DMA" extra re-read of the
227    /// parked address bus on the DMC-halt-coincides-with-OAM-halt overlap
228    /// cycle. `true` for [`Rp2A03G`](Self::Rp2A03G) (the default /
229    /// byte-identical baseline), `false` for [`Rp2A03H`](Self::Rp2A03H).
230    #[must_use]
231    pub const fn has_unexpected_dma_extra_read(self) -> bool {
232        matches!(self, Self::Rp2A03G)
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn version_is_non_empty() {
242        assert_ne!(version(), "");
243    }
244}