rustynes_core/nes.rs
1//! `Nes` facade — the public entry point that owns the entire emulator.
2//!
3//! Per `docs/architecture.md` §Public API surface. Mirrors the surface
4//! that `rustynes-frontend` and `rustynes-test-harness` will consume.
5
6use alloc::vec::Vec;
7use alloc::{format, vec};
8use rustynes_cpu::Cpu;
9use rustynes_mappers::RomError;
10use rustynes_ppu::{PaletteInit, PpuRevision};
11use sha2::{Digest, Sha256};
12
13// `core::time::Duration` is identical to `std::time::Duration` (same Duration
14// type, re-exported through std for convenience). Using the `core` path keeps
15// the public API surface portable to `#![no_std]` consumers without changing
16// any caller. See `docs/architecture.md` §149 (no_std + alloc migration).
17use core::time::Duration;
18
19use crate::Cpu2A03Revision;
20use crate::Region;
21use crate::bus::SystemBus;
22use crate::controller::Buttons;
23use crate::debug::{ApuDebugView, CpuDebugView, MapperDebugView, PpuDebugView};
24use crate::genie::{GenieCode, GenieError};
25use crate::input_device::InputDevice;
26use crate::rewind::{REWIND_DEFAULT_KEYFRAME_PERIOD, REWIND_DEFAULT_MAX_BYTES, RewindRing};
27use crate::save_state::{self, ROM_HASH_TAG_LEN, SnapshotError};
28
29/// Nominal NTSC frame duration: `1 / 60.0988 Hz ≈ 16.6393 ms`.
30///
31/// Real hardware alternates 29780-cycle and 29781-cycle frames (the half
32/// cycle averages to 60.0988 Hz); for wall-clock pacing we treat the
33/// average as a single fixed-point interval and let small slips snap.
34pub const FRAME_DURATION_NTSC: Duration = Duration::from_nanos(16_639_267);
35
36/// Nominal PAL frame duration: `1 / 50.0070 Hz ≈ 19.9972 ms`.
37pub const FRAME_DURATION_PAL: Duration = Duration::from_nanos(19_997_200);
38
39/// Nominal Dendy frame duration: 50 Hz Russian famiclone, same as PAL.
40pub const FRAME_DURATION_DENDY: Duration = Duration::from_nanos(19_997_200);
41
42/// v2.1.7 P5 — power-on 2 KiB CPU work-RAM contents.
43///
44/// Real NES hardware powers up with unreliable RAM (nesdev "CPU power up
45/// state"); a few titles read uninitialized RAM before writing it (*Final
46/// Fantasy*'s RNG seed, *River City Ransom*, *Cybernoid*). This selects what
47/// pattern the work RAM (and the open-bus latch) is filled with at power-on.
48///
49/// **Default-off / deterministic.** [`Default`] ([`Self::Zeroed`]) is the
50/// established all-zero fill CI, the regression oracle, and save-state tests
51/// use; the other variants are opt-in and still fully **deterministic** (no
52/// wall-clock / OS RNG), so the `same config + ROM + input ⇒ bit-identical`
53/// contract holds.
54#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Default)]
55pub enum PowerOnRam {
56 /// Default. Work RAM + open bus power up all-zero (current behavior).
57 #[default]
58 Zeroed,
59 /// Deterministic `xorshift64` randomization keyed on the seed (the existing
60 /// developer mode; see [`Nes::from_rom_with_power_on_seed`]). Surfaces
61 /// software that depends on a particular post-power-on RAM pattern.
62 Seeded(u64),
63 /// Fill every work-RAM byte (and the open-bus latch) with a single uniform
64 /// byte — a documented known pattern (e.g. `0xFF`, the all-ones some
65 /// consoles come up with). Deterministic.
66 Filled(u8),
67}
68
69/// v2.1.7 P5 — power-on hardware configuration for a freshly-constructed or
70/// power-cycled machine.
71///
72/// A small, forward-extensible bundle of the "what state does the silicon come
73/// up in" knobs that are otherwise scattered. Currently just the work-RAM fill
74/// ([`PowerOnRam`]); the PPU-revision and power-up-palette knobs are exposed as
75/// their own setters on [`Nes`] since they live in the PPU. All fields default
76/// to the established behavior, so [`PowerOnConfig::default`] is byte-identical.
77#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Default)]
78pub struct PowerOnConfig {
79 /// Work-RAM power-on fill. Defaults to [`PowerOnRam::Zeroed`].
80 pub ram: PowerOnRam,
81}
82
83/// v2.9.8 — which console wires the PPU's `/RESET` line.
84///
85/// The 2C02 is the same chip in every NTSC console; what differs is the board
86/// around it. The `NESdev` "PPU power up state" page (§Famicom, and its closing
87/// note on front- and top-loaders) documents two wirings:
88///
89/// - **NES (front-loader, NES-001)** — the CPU and PPU are reset together. At
90/// power-on and on every press of Reset the PPU spends about 29,658 CPU
91/// cycles (NTSC) in its warm-up state, ignoring writes to `$2000`, `$2001`,
92/// `$2005` and `$2006`, and Reset clears PPUCTRL, PPUMASK, the scroll/address
93/// latch and the read buffer.
94/// - **Famicom** — the PPU's `/RESET` is tied to 5 V and only the CPU's rides
95/// a 0.47 µF capacitor. At power-on the PPU therefore starts initialising
96/// roughly one frame before the CPU leaves reset, which is longer than the
97/// warm-up window, so the CPU's first instructions can already write the
98/// masked registers. The Reset button reaches only the CPU: the PPU keeps
99/// running and keeps its register state.
100///
101/// What this models, and what it does not:
102///
103/// - Power-on under [`Self::Famicom`] closes the warm-up window before the
104/// first instruction ([`rustynes_ppu::Ppu::end_warmup`]). `NESdev` gives the
105/// lead as "approximately one frame ... the exact timing has not been
106/// measured, and may vary", so the PPU's frame position is left where the NES
107/// model puts it rather than advanced by a guessed amount.
108/// - A warm reset under [`Self::Famicom`] leaves the PPU untouched. The APU,
109/// DMA unit and cartridge reset exactly as under [`Self::Nes`].
110/// - The NES-101 top-loader shares the Famicom's reset wiring, but `NESdev` does
111/// not document its power-on lead, so it is not offered as a separate model.
112///
113/// **Off by default.** [`Self::Nes`] is the model every release before v2.9.8
114/// emulated, so the default build is byte-identical. The selection is a
115/// host/config knob, never derived from the ROM: NES 2.0 has no console type
116/// that distinguishes a Famicom from an NES, and the project does not guess a
117/// console from a per-game list. It is not part of the save-state (the warm-up
118/// counter it acts on already is), and like the other hardware knobs on [`Nes`]
119/// it is re-applied by the host after a load or power-cycle.
120#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Default)]
121pub enum ConsoleModel {
122 /// Default. Front-loading NES: the CPU and PPU share the reset line.
123 #[default]
124 Nes,
125 /// Famicom: the PPU is never held in reset, so it leaves its warm-up before
126 /// the CPU starts and ignores the Reset button.
127 Famicom,
128}
129
130/// v1.1.0 beta.2 (Workstream C, T-110-C2) — one cycle-trace record.
131///
132/// The CPU register file + cycle count captured just before an instruction
133/// executes. Recorded by [`Nes::run_frame`] while tracing is enabled (the
134/// `debug-hooks` feature). The frontend disassembles the instruction at `pc`.
135#[cfg(feature = "debug-hooks")]
136#[derive(Clone, Copy, Debug, Eq, PartialEq)]
137pub struct TraceRec {
138 /// Program counter at instruction fetch.
139 pub pc: u16,
140 /// Accumulator.
141 pub a: u8,
142 /// X index.
143 pub x: u8,
144 /// Y index.
145 pub y: u8,
146 /// Stack pointer.
147 pub s: u8,
148 /// Processor status bits.
149 pub p: u8,
150 /// CPU cycle count at fetch.
151 pub cycle: u64,
152}
153
154/// Why [`Nes::scan_barcode`] refused a scan.
155#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
156pub enum BarcodeScanError {
157 /// The string is not a valid 13- or 8-digit JAN / EAN code.
158 #[error("not a valid JAN/EAN barcode: {0}")]
159 Malformed(rustynes_mappers::BarcodeError),
160 /// The cartridge has no barcode reader (only the Datach, mapper 157,
161 /// does).
162 #[error("this cartridge has no barcode reader")]
163 NoReader,
164}
165
166/// The largest extra-scanline overclock the core accepts.
167///
168/// [`Nes::set_extra_scanlines`] clamps to it, and a movie's options record
169/// above it is refused. 80 lines is the range the desktop's Settings field
170/// has offered since v2.9.7; the value moved here at v2.9.9 (NC-11) so every
171/// host and every file format meets the same bound.
172pub const MAX_EXTRA_SCANLINES: u16 = 80;
173
174/// The largest CPU-multiplier overclock the core accepts (v3.1.0,
175/// `T-CPU-OVERCLOCK`).
176///
177/// [`Nes::set_cpu_overclock`] clamps to `1..=MAX_CPU_OVERCLOCK`, and a movie's
178/// options record outside that range is refused. The bound is the master
179/// clock: the CPU divider must stay at least 3 for the read / write split of
180/// a cycle (NTSC 12 / 4 = 3), and `x4` is already four times the CPU time a
181/// frame has.
182pub const MAX_CPU_OVERCLOCK: u8 = 4;
183
184/// Top-level NES emulator handle.
185///
186/// Owns the CPU and the bus, which holds the PPU, APU, mapper, RAM and the
187/// input devices (Round 2 audit CORE-R2-07: "controller stub" predated
188/// them). Construct via
189/// [`Nes::from_rom`]; drive forward via [`Nes::run_frame`] or
190/// [`Nes::step_instruction`]. The framebuffer can be sampled at any time via
191/// [`Nes::framebuffer`].
192// Several independent debug-hooks toggles (breakpoints / trace / exec log) push
193// the bool count over clippy's threshold; they are genuinely independent flags.
194#[allow(clippy::struct_excessive_bools)]
195pub struct Nes {
196 cpu: Cpu,
197 bus: SystemBus,
198 /// The ROM's persistent identity: SHA-256 of an iNES / NES 2.0 image's
199 /// bytes AFTER its 16-byte header (trainer, PRG, CHR, anything trailing),
200 /// or of the whole image for anything without the `NES\x1A` magic (FDS
201 /// disks, NSF files). See [`Nes::rom_sha256`] for why the header is left
202 /// out.
203 rom_sha256: [u8; 32],
204 /// SHA-256 of the complete image as constructed, header included. Only the
205 /// Vs. System database consults it, as the fallback to its identity key
206 /// ([`Nes::image_sha256`]).
207 image_sha256: [u8; 32],
208 /// Optional rewind ring buffer. Disabled by default — frontend opts in
209 /// via [`Nes::enable_rewind`].
210 rewind: Option<RewindRing>,
211 /// v2.8.0 Phase 3 — when `false`, [`Nes::run_frame`] skips the rewind
212 /// capture even with the ring armed. Run-ahead sets this for its
213 /// hidden + visible frames so only the persistent timeline's frames
214 /// land in the ring. Default `true` (byte-identical legacy behavior).
215 rewind_capture_enabled: bool,
216 /// v2.8.0 Phase 3 — reused scratch for the per-frame rewind capture
217 /// (kills the ~320 KiB snapshot allocation per frame).
218 rewind_snap_buf: Vec<u8>,
219 /// v2.9.0 (re-audit NC-03) — reused scratch for the rollback backup every
220 /// restore takes before it mutates anything (see `restore_inner`). Pooled
221 /// because the quiet path runs once per frame under run-ahead.
222 restore_backup: Vec<u8>,
223 /// Optional per-CPU-instruction boot trace (Session-12 observability).
224 /// Gated on the `cpu-boot-trace` cargo feature so the default build
225 /// pays no memory or codegen cost. See
226 /// `crates/rustynes-core/src/cpu_boot_trace.rs`.
227 #[cfg(feature = "cpu-boot-trace")]
228 cpu_boot_trace: Option<crate::cpu_boot_trace::CpuBootTrace>,
229 /// v1.1.0 beta.2 (Workstream C) — exec/PC breakpoints checked in
230 /// [`Nes::run_frame`]. Gated on `debug-hooks` so the default build's hot
231 /// path is untouched. Output-only: a hit stops the frame early and records
232 /// the PC; it never mutates emulation, so determinism holds.
233 #[cfg(feature = "debug-hooks")]
234 breakpoints: Vec<u16>,
235 /// Whether breakpoints are armed (lets the UI keep its list but pause
236 /// checking). Default `true`.
237 #[cfg(feature = "debug-hooks")]
238 breakpoints_enabled: bool,
239 /// The PC that last hit a breakpoint, taken by the frontend to pause.
240 #[cfg(feature = "debug-hooks")]
241 break_hit: Option<u16>,
242 /// The PC to skip the breakpoint check on for the next step, so a
243 /// "continue" resumes *past* the instruction it stopped on instead of
244 /// re-breaking. Unlike a blind "skip the first iteration", this only skips
245 /// the exact resumed PC — so a breakpoint sitting at the frame's start PC
246 /// (after a reset / save-state load / manual PC change) still fires.
247 #[cfg(feature = "debug-hooks")]
248 skip_breakpoint_at: Option<u16>,
249 /// v1.1.0 beta.2 (T-110-C2) — cycle-trace ring buffer (most-recent
250 /// [`Self::TRACE_CAP`] instructions). Recorded in `run_frame` while
251 /// `trace_enabled`. Output-only.
252 #[cfg(feature = "debug-hooks")]
253 trace: alloc::collections::VecDeque<TraceRec>,
254 /// Whether the cycle-trace logger is recording. Default `false`.
255 #[cfg(feature = "debug-hooks")]
256 trace_enabled: bool,
257 /// v1.1.0 beta.3 (T-110-E2) — per-frame executed-PC log for the Lua
258 /// `onExec` callback. Distinct from [`Self::trace`] (a 50k rolling buffer
259 /// shared with the Trace Logger panel): this is **cleared every frame**, so
260 /// `onExec` replays only this frame's PCs — no stale / duplicate dispatch.
261 /// Output-only; recorded only while `exec_logging`.
262 #[cfg(feature = "debug-hooks")]
263 exec_log: Vec<u16>,
264 /// Whether the per-frame exec-PC log is recording. Default `false`.
265 #[cfg(feature = "debug-hooks")]
266 exec_logging: bool,
267 /// v2.4.0 item B — a monotonic marker that changes whenever this `Nes`
268 /// jumps to a different point on its timeline.
269 ///
270 /// **Session-local, and deliberately NOT serialized.** The counter's only job
271 /// is to be *different* after a discontinuity. Serializing it would put an
272 /// OLD value back on restore, so loading a state saved earlier in the same
273 /// session could hand a consumer a generation it has already seen — and the
274 /// consumer would conclude nothing jumped at the exact moment something did.
275 /// A session-local monotonic counter cannot do that: it only ever increases,
276 /// so any restore produces a value no consumer has seen.
277 ///
278 /// It exists because the alternative — each consumer remembering the last
279 /// `cycle()` it saw and noticing a non-monotonic step — cannot see a restore
280 /// to a LATER state. The counter can, and needs no cooperation from any call
281 /// site, which matters because two of the four timeline jumps (wasm
282 /// load-state, and rewind) are not reachable from a patchable frontend call
283 /// site at all.
284 ///
285 /// # It is NOT part of the save state, deliberately
286 ///
287 /// The counter is session-local: it is not written by `snapshot`, not read by
288 /// `restore`, and a loaded state does not carry its own value across. What a
289 /// restore does instead is **increment the live counter**, which is the
290 /// correct reading of the event — "the timeline you were on has been replaced"
291 /// — and is true regardless of which state was loaded.
292 ///
293 /// Serializing it would be actively wrong in two ways. Loading the same slot
294 /// twice would restore the same generation twice, so a consumer comparing
295 /// against its last-seen value would miss the second load entirely. And a
296 /// value from another session says nothing about this one: the counter is only
297 /// ever meaningful as a comparison against the previous value *this process*
298 /// observed, which is why `timeline_generation()` documents that comparing it
299 /// across two `Nes` instances is meaningless.
300 ///
301 /// A consequence worth stating: because it lives outside the snapshot, the
302 /// `snapshot_schema_audit` test cannot see it, so nothing mechanical will
303 /// notice if this reasoning is ever invalidated.
304 timeline_generation: u64,
305 /// v3.5.0 (`T-MOVIE-INPUT-STREAM`) — the Datach barcode swiped since the
306 /// last [`Nes::run_frame`] began, if any.
307 ///
308 /// A scan is an *event*, not a held level: once [`Nes::scan_barcode`] has
309 /// handed the symbol to the reader, nothing in the machine's state says
310 /// "a scan was issued just now" (the reader only says one is in
311 /// progress). A movie recorder reads its input from the machine
312 /// ([`crate::FrameInput::held_on`]) between the host's input calls and
313 /// the frame, so this field keeps the scan visible exactly that long: set
314 /// by the scan, cleared as the next frame starts.
315 ///
316 /// Host-input staging, not emulation state: nothing reads it during a
317 /// frame, it is not serialized (a restore neither carries nor clears it),
318 /// and the determinism contract is unaffected.
319 barcode_this_frame: Option<rustynes_mappers::Barcode>,
320}
321
322impl Nes {
323 /// The current timeline generation — see the field's documentation.
324 ///
325 /// A consumer holds the last value it saw and clears itself when this
326 /// differs. It is meaningless to compare across two different `Nes`
327 /// instances: a fresh one starts at zero, which is why ROM changes are
328 /// handled by their own hook (`DebuggerOverlay::clear_rom_bound_analysis`)
329 /// rather than by this counter.
330 #[must_use]
331 pub const fn timeline_generation(&self) -> u64 {
332 self.timeline_generation
333 }
334
335 /// Returns a reference to the internal WRAM.
336 pub fn wram(&self) -> &[u8] {
337 self.bus.ram.as_ref()
338 }
339
340 /// Returns a mutable reference to the internal WRAM.
341 pub fn wram_mut(&mut self) -> &mut [u8] {
342 self.bus.ram.as_mut()
343 }
344
345 /// Returns a reference to the cartridge SRAM (if any).
346 pub fn sram(&self) -> &[u8] {
347 self.bus.mapper.sram()
348 }
349
350 /// Returns a mutable reference to the cartridge SRAM (if any).
351 pub fn sram_mut(&mut self) -> &mut [u8] {
352 self.bus.mapper.sram_mut()
353 }
354
355 /// v2.9.6 — the cartridge's non-volatile data, what a battery save
356 /// persists: [`Self::sram`] on almost every board, and the flash image on
357 /// a self-flashable one (GTROM, a flashable UNROM 512), which has no RAM
358 /// at `$6000`. Hosts that persist saves read and restore THIS, gated on
359 /// [`Self::has_battery`]. `sram()` stays the `$6000` RAM that memory maps
360 /// describe. See `Mapper::save_data`.
361 pub fn save_data(&self) -> &[u8] {
362 self.bus.mapper.save_data()
363 }
364
365 /// Mutable [`Self::save_data`], for loading a save.
366 pub fn save_data_mut(&mut self) -> &mut [u8] {
367 self.bus.mapper.save_data_mut()
368 }
369
370 /// v3.4.0 — whether a battery file of `len` bytes is one this cartridge
371 /// can load: its [`Self::save_data`] length, or an earlier layout the
372 /// board still reads (mapper 157's v3.3.0 main-unit-only save). A host
373 /// checks it before reading a file in full. See `Mapper::accepts_save_len`.
374 #[must_use]
375 pub fn accepts_save_len(&self, len: usize) -> bool {
376 self.bus.mapper.accepts_save_len(len)
377 }
378
379 /// v3.4.0 — load a battery file into [`Self::save_data`]. Returns
380 /// `false`, changing nothing, for a length [`Self::accepts_save_len`]
381 /// refuses. Every host loads a save through this, so a board's earlier
382 /// layout is handled in the board and not in each frontend. See
383 /// `Mapper::load_save_data`.
384 pub fn load_save_data(&mut self, bytes: &[u8]) -> bool {
385 self.bus.mapper.load_save_data(bytes)
386 }
387
388 /// v2.9.6 — return the save data to a never-saved cartridge: zeroed RAM,
389 /// or the flash image as loaded.
390 pub fn clear_save_data(&mut self) {
391 self.bus.mapper.clear_save_data();
392 }
393
394 /// Whether the cartridge's save data may have changed since the last
395 /// [`Self::clear_save_data_dirty`]; `None` when the board does not track it
396 /// (the caller then compares bytes). See `Mapper::is_save_data_dirty`.
397 #[must_use]
398 pub fn is_save_data_dirty(&self) -> Option<bool> {
399 self.bus.mapper.is_save_data_dirty()
400 }
401
402 /// Mark the cartridge's save data clean. See `Mapper::clear_save_data_dirty`.
403 pub fn clear_save_data_dirty(&mut self) {
404 self.bus.mapper.clear_save_data_dirty();
405 }
406
407 /// v2.7.3 — whether the cartridge has non-volatile save data: the header
408 /// declares battery-backed PRG-RAM (iNES flags 6 bit 1), or (v2.9.6) the
409 /// board is self-flashable and its flash is the save (GTROM, mapper 111,
410 /// and flashable UNROM 512, mapper 30, whose headers need not set the
411 /// bit). Persist [`Self::save_data`] when this is `true`.
412 ///
413 /// [`Self::sram`] is not the same question: several boards expose their
414 /// work RAM through it whatever the header says (NROM returns its 8 KiB
415 /// PRG-RAM for every image, and MMC1 and MMC3 allocate RAM by default). A
416 /// host that persists save RAM to disk — the desktop frontend's `.sav`
417 /// files — must gate on this, or a volatile cartridge acquires a save it
418 /// never had and restores stale RAM across power cycles. Always `false`
419 /// for an FDS disk (which has its own writable-disk save) and an NSF.
420 #[must_use]
421 pub const fn has_battery(&self) -> bool {
422 self.bus.cart.has_battery
423 }
424
425 /// Returns a reference to the internal VRAM (nametables).
426 pub fn vram(&self) -> &[u8] {
427 self.bus.ppu.vram_ref()
428 }
429
430 /// Returns a mutable reference to the internal VRAM (nametables).
431 pub fn vram_mut(&mut self) -> &mut [u8] {
432 self.bus.ppu.vram_mut()
433 }
434
435 /// Build a new emulator from raw ROM bytes (iNES 1.0 or NES 2.0).
436 ///
437 /// # Errors
438 ///
439 /// Returns the underlying [`RomError`] if the bytes don't parse.
440 pub fn from_rom(bytes: &[u8]) -> Result<Self, RomError> {
441 let mut bus = SystemBus::new(bytes)?;
442 // Cold-boot path: `Cpu::power_on()` seeds `S=$00`; the subsequent
443 // `reset()`'s `S -= 3` (wrapping) lands at `$FD`, matching Mesen2's
444 // power-up state. See `docs/audit/session-13-cpu-boot-fix-2026-05-21.md`.
445 let mut cpu = Cpu::power_on();
446 cpu.reset(&mut bus);
447 Ok(Self {
448 cpu,
449 bus,
450 rom_sha256: rom_identity_sha256(bytes),
451 image_sha256: sha256_of(bytes),
452 rewind: None,
453 rewind_capture_enabled: true,
454 rewind_snap_buf: Vec::new(),
455 restore_backup: Vec::new(),
456 #[cfg(feature = "cpu-boot-trace")]
457 cpu_boot_trace: None,
458 #[cfg(feature = "debug-hooks")]
459 breakpoints: Vec::new(),
460 #[cfg(feature = "debug-hooks")]
461 breakpoints_enabled: true,
462 #[cfg(feature = "debug-hooks")]
463 break_hit: None,
464 #[cfg(feature = "debug-hooks")]
465 skip_breakpoint_at: None,
466 #[cfg(feature = "debug-hooks")]
467 trace: alloc::collections::VecDeque::new(),
468 #[cfg(feature = "debug-hooks")]
469 trace_enabled: false,
470 #[cfg(feature = "debug-hooks")]
471 exec_log: Vec::new(),
472 #[cfg(feature = "debug-hooks")]
473 exec_logging: false,
474 timeline_generation: 0,
475 barcode_this_frame: None,
476 })
477 }
478
479 /// Build an emulator with an explicit audio sample rate (the rate the
480 /// CPAL stream is opened at).
481 ///
482 /// # Errors
483 ///
484 /// Returns the underlying [`RomError`] if the bytes don't parse.
485 pub fn from_rom_with_sample_rate(bytes: &[u8], sample_rate: u32) -> Result<Self, RomError> {
486 let mut bus = SystemBus::with_sample_rate(bytes, sample_rate)?;
487 // Cold-boot path: see comment in `from_rom`.
488 let mut cpu = Cpu::power_on();
489 cpu.reset(&mut bus);
490 Ok(Self {
491 cpu,
492 bus,
493 rom_sha256: rom_identity_sha256(bytes),
494 image_sha256: sha256_of(bytes),
495 rewind: None,
496 rewind_capture_enabled: true,
497 rewind_snap_buf: Vec::new(),
498 restore_backup: Vec::new(),
499 #[cfg(feature = "cpu-boot-trace")]
500 cpu_boot_trace: None,
501 #[cfg(feature = "debug-hooks")]
502 breakpoints: Vec::new(),
503 #[cfg(feature = "debug-hooks")]
504 breakpoints_enabled: true,
505 #[cfg(feature = "debug-hooks")]
506 break_hit: None,
507 #[cfg(feature = "debug-hooks")]
508 skip_breakpoint_at: None,
509 #[cfg(feature = "debug-hooks")]
510 trace: alloc::collections::VecDeque::new(),
511 #[cfg(feature = "debug-hooks")]
512 trace_enabled: false,
513 #[cfg(feature = "debug-hooks")]
514 exec_log: Vec::new(),
515 #[cfg(feature = "debug-hooks")]
516 exec_logging: false,
517 timeline_generation: 0,
518 barcode_this_frame: None,
519 })
520 }
521
522 /// Build an emulator from a Famicom Disk System `.fds` disk image and a
523 /// user-supplied 8 KiB BIOS (`disksys.rom`).
524 ///
525 /// The BIOS is never committed to this repo (it is Nintendo IP); the caller
526 /// supplies it (a frontend BIOS prompt is Stage 2). Construction parses the
527 /// disk container, builds the FDS device as the bus's mapper, and runs the
528 /// standard cold-boot reset (the BIOS reset vector at `$FFFC` drives the
529 /// disk-load sequence).
530 ///
531 /// Uses the default 44.1 kHz audio sample rate; use
532 /// [`Nes::from_disk_with_sample_rate`] to pick the rate.
533 ///
534 /// # Errors
535 ///
536 /// Returns the underlying [`RomError`] if the disk image is unparseable or
537 /// the BIOS is not exactly 8 KiB.
538 pub fn from_disk(disk_bytes: &[u8], bios_bytes: &[u8]) -> Result<Self, RomError> {
539 Self::from_disk_with_sample_rate(disk_bytes, bios_bytes, crate::bus::DEFAULT_SAMPLE_RATE)
540 }
541
542 /// Build an FDS emulator with an explicit audio sample rate. See
543 /// [`Nes::from_disk`].
544 ///
545 /// The reported `rom_sha256` hashes the disk-image bytes (not the BIOS), so
546 /// save-states / movies key off the disk the way cartridge builds key off
547 /// the ROM. A host booting a SAVED (game-written) copy of the disk passes
548 /// the pristine image's hash to [`Nes::set_rom_identity`] afterwards, so
549 /// the identity does not move with the game's disk saves (v2.9.9, NF-17).
550 ///
551 /// # Errors
552 ///
553 /// Returns the underlying [`RomError`] if the disk image is unparseable or
554 /// the BIOS is not exactly 8 KiB.
555 pub fn from_disk_with_sample_rate(
556 disk_bytes: &[u8],
557 bios_bytes: &[u8],
558 sample_rate: u32,
559 ) -> Result<Self, RomError> {
560 let mut bus = SystemBus::with_disk(disk_bytes, bios_bytes, sample_rate)?;
561 // Cold-boot path: see comment in `from_rom`.
562 let mut cpu = Cpu::power_on();
563 cpu.reset(&mut bus);
564 Ok(Self {
565 cpu,
566 bus,
567 rom_sha256: sha256_of(disk_bytes),
568 image_sha256: sha256_of(disk_bytes),
569 rewind: None,
570 rewind_capture_enabled: true,
571 rewind_snap_buf: Vec::new(),
572 restore_backup: Vec::new(),
573 #[cfg(feature = "cpu-boot-trace")]
574 cpu_boot_trace: None,
575 #[cfg(feature = "debug-hooks")]
576 breakpoints: Vec::new(),
577 #[cfg(feature = "debug-hooks")]
578 breakpoints_enabled: true,
579 #[cfg(feature = "debug-hooks")]
580 break_hit: None,
581 #[cfg(feature = "debug-hooks")]
582 skip_breakpoint_at: None,
583 #[cfg(feature = "debug-hooks")]
584 trace: alloc::collections::VecDeque::new(),
585 #[cfg(feature = "debug-hooks")]
586 trace_enabled: false,
587 #[cfg(feature = "debug-hooks")]
588 exec_log: Vec::new(),
589 #[cfg(feature = "debug-hooks")]
590 exec_logging: false,
591 timeline_generation: 0,
592 barcode_this_frame: None,
593 })
594 }
595
596 /// Build an emulator that plays an NSF-family music file: the classic
597 /// `NESM\x1a` container or the chunked `NSFE` one, told apart by their magic
598 /// in [`rustynes_mappers::parse_nsf`]. Expansion-chip audio declared in the
599 /// header (VRC6, VRC7, FDS, MMC5, N163, 5B) is synthesized by the same cores
600 /// the cartridge boards use. (Until v2.9.3 this comment said `NSFe` and
601 /// expansion audio were deferred, which stopped being true in v2.1.x.)
602 ///
603 /// NSF files carry a ripped NES sound engine plus an `init`/`play` address
604 /// pair, not a PPU program. Construction parses the file, installs a
605 /// [`rustynes_mappers::NsfMapper`] (a synthetic 6502 driver + the program
606 /// image) as the bus's mapper, and runs the standard cold-boot reset — the
607 /// driver's reset vector calls `init` for the starting song. At the standard
608 /// 60 Hz rate the driver enables vblank NMI and the NMI calls `play` once per
609 /// frame; at any other header rate a mapper cycle-timer IRQ calls it
610 /// instead (see `docs/mappers.md`). Audio is produced through the unchanged
611 /// lockstep loop; there is no video.
612 ///
613 /// Uses the default 44.1 kHz sample rate; see
614 /// [`Nes::from_nsf_with_sample_rate`].
615 ///
616 /// # Errors
617 ///
618 /// Returns the underlying [`RomError`] when the NSF header is malformed.
619 pub fn from_nsf(nsf_bytes: &[u8]) -> Result<Self, RomError> {
620 Self::from_nsf_with_sample_rate(nsf_bytes, crate::bus::DEFAULT_SAMPLE_RATE)
621 }
622
623 /// Build an NSF player with an explicit audio sample rate. See
624 /// [`Nes::from_nsf`].
625 ///
626 /// # Errors
627 ///
628 /// Returns the underlying [`RomError`] when the NSF header is malformed.
629 pub fn from_nsf_with_sample_rate(nsf_bytes: &[u8], sample_rate: u32) -> Result<Self, RomError> {
630 let mut bus = SystemBus::with_nsf(nsf_bytes, sample_rate)?;
631 let mut cpu = Cpu::power_on();
632 cpu.reset(&mut bus);
633 Ok(Self {
634 cpu,
635 bus,
636 rom_sha256: sha256_of(nsf_bytes),
637 image_sha256: sha256_of(nsf_bytes),
638 rewind: None,
639 rewind_capture_enabled: true,
640 rewind_snap_buf: Vec::new(),
641 restore_backup: Vec::new(),
642 #[cfg(feature = "cpu-boot-trace")]
643 cpu_boot_trace: None,
644 #[cfg(feature = "debug-hooks")]
645 breakpoints: Vec::new(),
646 #[cfg(feature = "debug-hooks")]
647 breakpoints_enabled: true,
648 #[cfg(feature = "debug-hooks")]
649 break_hit: None,
650 #[cfg(feature = "debug-hooks")]
651 skip_breakpoint_at: None,
652 #[cfg(feature = "debug-hooks")]
653 trace: alloc::collections::VecDeque::new(),
654 #[cfg(feature = "debug-hooks")]
655 trace_enabled: false,
656 #[cfg(feature = "debug-hooks")]
657 exec_log: Vec::new(),
658 #[cfg(feature = "debug-hooks")]
659 exec_logging: false,
660 timeline_generation: 0,
661 barcode_this_frame: None,
662 })
663 }
664
665 /// Number of selectable songs in the loaded NSF (0 for a cartridge / disk).
666 #[must_use]
667 pub fn nsf_song_count(&self) -> u8 {
668 self.bus.nsf_song_count()
669 }
670
671 /// The currently-selected 0-based NSF song (0 for a cartridge / disk).
672 #[must_use]
673 pub fn nsf_current_song(&self) -> u8 {
674 self.bus.nsf_current_song()
675 }
676
677 /// Select a 0-based NSF song and restart playback on it (re-runs `init` via
678 /// a warm reset). No-op for a cartridge / disk.
679 pub fn nsf_set_song(&mut self, song: u8) {
680 if self.bus.nsf_set_song(song) {
681 // Re-vector through the driver's reset entry so `init` runs for the
682 // new track. Warm reset preserves the freshly-patched driver state.
683 self.reset();
684 }
685 }
686
687 /// Build an emulator with a **randomized power-on RAM** state (developer
688 /// mode; Phase 7 / T-72-005).
689 ///
690 /// Identical to [`Nes::from_rom`] except the 2 KiB CPU work RAM and the
691 /// open-bus latch are filled from a deterministic `xorshift64` PRNG keyed
692 /// on `seed`, modelling the unreliable power-on RAM of real hardware
693 /// (nesdev "CPU power up state"). Use this to shake out game/test code
694 /// that depends on a particular post-power-on RAM pattern.
695 ///
696 /// The randomization is **seeded and deterministic** — the same `seed`
697 /// yields the same state, so the `same seed + ROM + input ⇒ bit-identical`
698 /// contract still holds. The default [`Nes::from_rom`] (zeroed RAM) is
699 /// what CI, the regression oracle, and save-state tests use.
700 ///
701 /// # Errors
702 ///
703 /// Returns the underlying [`RomError`] if the bytes don't parse.
704 pub fn from_rom_with_power_on_seed(bytes: &[u8], seed: u64) -> Result<Self, RomError> {
705 Self::from_rom_with_power_on_config(
706 bytes,
707 PowerOnConfig {
708 ram: PowerOnRam::Seeded(seed),
709 },
710 )
711 }
712
713 /// v2.1.7 P5 — build an emulator with an explicit [`PowerOnConfig`].
714 ///
715 /// Generalizes [`Nes::from_rom_with_power_on_seed`]: the caller chooses the
716 /// power-on work-RAM fill ([`PowerOnRam::Zeroed`] / [`PowerOnRam::Seeded`] /
717 /// [`PowerOnRam::Filled`]). The config is stored on the bus so a subsequent
718 /// power-cycle re-applies the same fill (keeping `power_cycle == fresh
719 /// boot`). All fills are **deterministic**, so the `same config + ROM + input
720 /// ⇒ bit-identical` contract still holds. [`PowerOnConfig::default`]
721 /// ([`PowerOnRam::Zeroed`]) is byte-identical to [`Nes::from_rom`].
722 ///
723 /// # Errors
724 ///
725 /// Returns the underlying [`RomError`] if the bytes don't parse.
726 pub fn from_rom_with_power_on_config(
727 bytes: &[u8],
728 config: PowerOnConfig,
729 ) -> Result<Self, RomError> {
730 let mut nes = Self::from_rom(bytes)?;
731 // RAM is not consulted during the reset sequence (only the $FFFC/D
732 // vector is), so applying the fill after construction is correct.
733 nes.bus.set_power_on_ram(config.ram);
734 Ok(nes)
735 }
736
737 /// Reset (warm boot). Preserves WRAM; reloads PC from `$FFFC/D`.
738 pub fn reset(&mut self) {
739 // v2.4.0 item B — a warm reset lands somewhere else on the timeline, so a
740 // reconstructed call stack and the access counters describe a run that no
741 // longer exists.
742 self.timeline_generation = self.timeline_generation.wrapping_add(1);
743 self.bus.reset();
744 self.cpu.reset(&mut self.bus);
745 }
746
747 /// Power-cycle (cold boot). Zeroes WRAM, re-rolls phase, reloads vectors.
748 ///
749 /// A cold boot of the CONSOLE, not of its configuration. The PPU and the
750 /// APU are rebuilt to their power-on state, and since v2.9.8 every host
751 /// setting stored on them survives: the custom or generated palette
752 /// ([`Self::set_custom_palette`]), the overclock scanlines
753 /// ([`Self::set_extra_scanlines`]), the fast dot path
754 /// ([`Self::set_fast_dotloop`]), the OAM-decay model
755 /// ([`Self::set_oam_decay`]), the APU channel mask, per-channel gain and
756 /// filter model, and the armed state of the provenance stores (emptied
757 /// below). The settings stored on the bus survived already: the die
758 /// revisions, the console model, the Vs. DIP switches and PPU type, the
759 /// mirroring override and the Four Score. The power-on FILLS
760 /// ([`Self::set_power_on_ram`], [`Self::set_power_up_palette`]) are
761 /// re-applied, as a fresh boot applies them. What a cold boot does clear
762 /// is console state: RAM, registers, the mapper (battery RAM excepted),
763 /// the controllers' latches, and any non-standard input device, which the
764 /// host re-attaches. Until v2.9.8 the PPU and APU settings reverted to
765 /// their defaults, and each host had to re-push them.
766 pub fn power_cycle(&mut self) {
767 // v2.4.0 item B — see `reset`; a cold boot is the larger discontinuity.
768 self.timeline_generation = self.timeline_generation.wrapping_add(1);
769 self.bus.power_cycle();
770 // Cold-boot path: see comment in `from_rom`.
771 self.cpu = Cpu::power_on();
772 self.cpu.reset(&mut self.bus);
773 // v2.3.2 "Lucid" — a cold boot ends the history both provenance stores
774 // describe. Keep them armed (the user asked for them) but empty.
775 #[cfg(feature = "debug-hooks")]
776 {
777 self.bus.ppu.clear_write_attribution();
778 self.bus.ppu.clear_pixel_provenance();
779 // v2.3.7 — same for audio: a cold boot ends the history the
780 // register attribution describes.
781 self.bus.apu.clear_audio_provenance_history();
782 }
783 }
784
785 /// Run until the PPU finishes a frame. Returns the framebuffer slice.
786 ///
787 /// A CPU JAM ends the call early, as the 150,000-cycle budget does: the
788 /// returned framebuffer is whatever the PPU had drawn, and later calls
789 /// return at once until a reset. It does not panic (until v2.9.9 this
790 /// section said it did; NC-15). Check [`Self::cpu`]'s `is_jammed` to tell
791 /// a JAM from a completed frame.
792 pub fn run_frame(&mut self) -> &[u8] {
793 // Hard cap: at NTSC the frame budget is 29,780.5 CPU cycles. Run
794 // up to 5x that before bailing — gives breathing room for late
795 // VBL detection or DMA-stall heavy frames before declaring "stuck".
796 //
797 // v3.1.0: scaled by the CPU overclock, which puts up to
798 // MAX_CPU_OVERCLOCK times as many CPU cycles into one frame.
799 const MAX_CYCLES_PER_FRAME: u64 = 150_000;
800 let max_cycles = MAX_CYCLES_PER_FRAME * u64::from(self.bus.cpu_overclock());
801 // v3.5.0 — a barcode swiped before this frame has now been seen by any
802 // movie recorder that was going to see it (see the field).
803 self.barcode_this_frame = None;
804 let start = self.bus.cycle();
805 // v2.3.7 "Overtone" — anchor this frame's mix trace. The trace is
806 // per-frame (the index IS the cycle offset from here); the REGISTER
807 // attribution deliberately is not, because "which instruction last wrote
808 // $4003" has an answer that legitimately predates this frame.
809 #[cfg(feature = "debug-hooks")]
810 self.bus.apu.begin_audio_provenance_frame(start);
811 // T-110-C3 — the event viewer shows one frame; reset the log per frame.
812 #[cfg(feature = "debug-hooks")]
813 if self.bus.event_logging() {
814 self.bus.clear_events();
815 }
816 // T-110-E2 — the Lua onRead/onWrite access log is per-frame too.
817 #[cfg(feature = "debug-hooks")]
818 if self.bus.access_logging() {
819 self.bus.clear_accesses();
820 }
821 // T-110-E1 — the Lua onNmi/onIrq interrupt-service log is per-frame too
822 // (cleared here so a replay only ever sees this frame's services, never
823 // a stale carry-over — mirrors the exec_log clear below).
824 #[cfg(feature = "debug-hooks")]
825 if self.bus.interrupt_logging() {
826 self.bus.clear_interrupts();
827 }
828 // v1.6.0 Workstream A3 — reset the `TAStudio` lag-log "controller polled"
829 // flag so was_input_polled_this_frame() reflects only this frame (a
830 // frame that ends still-`false` is a lag frame). Output-only.
831 #[cfg(feature = "debug-hooks")]
832 self.bus.clear_controller_polled();
833 // v1.4.0 Workstream D (D2) — start each frame with no event-breakpoint
834 // hit so the frontend's "first hit of the frame" pause is per-frame.
835 #[cfg(feature = "debug-hooks")]
836 if self.bus.event_breakpoints() != 0 {
837 self.bus.clear_event_break_hit();
838 }
839 // T-110-E2 — the Lua onExec exec-PC log is per-frame (cleared here so a
840 // replay only ever sees this frame's PCs, never a stale carry-over).
841 #[cfg(feature = "debug-hooks")]
842 if self.exec_logging {
843 self.exec_log.clear();
844 }
845 while !self.bus.take_frame_complete() {
846 if self.cpu.is_jammed() {
847 break;
848 }
849 if self.bus.cycle().wrapping_sub(start) > max_cycles {
850 break;
851 }
852 #[cfg(feature = "debug-hooks")]
853 {
854 // v1.1.0 beta.2 (Workstream C) — exec/PC breakpoints. The
855 // `skip_breakpoint_at` PC is stepped past exactly once (so a
856 // "continue" resumes off the instruction it stopped on instead
857 // of re-breaking in place); any OTHER breakpoint PC — including
858 // one at the frame's starting PC after a reset / save-state load
859 // / manual PC change — still fires immediately.
860 if self.breakpoints_enabled && self.breakpoints.contains(&self.cpu.pc) {
861 if self.skip_breakpoint_at == Some(self.cpu.pc) {
862 self.skip_breakpoint_at = None;
863 } else {
864 // Hit: stop the (partial) frame and report the PC. No
865 // state mutated; the frame simply isn't completed.
866 self.break_hit = Some(self.cpu.pc);
867 self.skip_breakpoint_at = Some(self.cpu.pc);
868 return self.bus.framebuffer();
869 }
870 } else {
871 self.skip_breakpoint_at = None;
872 }
873 // T-110-E2 — per-frame exec-PC log for Lua onExec (bounded by
874 // MAX_CYCLES_PER_FRAME, so no explicit cap needed).
875 if self.exec_logging {
876 self.exec_log.push(self.cpu.pc);
877 }
878 // v2.3.2 "Lucid" — push this instruction's `(pc, cycle)` down to
879 // the PPU so any CIRAM / OAM / palette byte it goes on to write
880 // is stamped with the instruction that caused it. Done here, in
881 // the existing per-instruction debug block, rather than through a
882 // new `CpuBus` hook: `run_frame` already holds both halves, so
883 // this costs two stores and leaves `rustynes-cpu` untouched.
884 //
885 // Unconditional rather than gated on the store being armed: the
886 // "is it armed?" question lives behind a `Box` on the other side
887 // of a crate boundary, so testing it would cost about as much as
888 // the two stores it would skip, in a block that already runs a
889 // breakpoint scan per instruction.
890 self.bus
891 .ppu
892 .set_attrib_context(self.cpu.pc, self.cpu.cycles);
893 // v2.3.7 "Overtone" — the same push-down for audio, so
894 // `Apu::write_register` can attribute a `$4000-$4017` write
895 // without `rustynes-cpu` knowing the feature exists. Same
896 // reasoning as the PPU line above: two unconditional stores are
897 // cheaper than testing an arm behind a `Box` across a crate
898 // boundary, in a block that already scans breakpoints.
899 self.bus
900 .apu
901 .set_attrib_context(self.cpu.pc, self.cpu.cycles);
902 // T-110-C2 — cycle trace: record the about-to-execute
903 // instruction's CPU state (ring-capped, oldest dropped).
904 if self.trace_enabled {
905 if self.trace.len() >= Self::TRACE_CAP {
906 self.trace.pop_front();
907 }
908 self.trace.push_back(TraceRec {
909 pc: self.cpu.pc,
910 a: self.cpu.a,
911 x: self.cpu.x,
912 y: self.cpu.y,
913 s: self.cpu.s,
914 p: self.cpu.p.bits(),
915 cycle: self.cpu.cycles,
916 });
917 }
918 }
919 #[cfg(feature = "cpu-boot-trace")]
920 self.cpu_boot_trace_record();
921 self.cpu.step(&mut self.bus);
922 }
923 // Sample any attached Zapper's light detection from the completed
924 // frame. This is a no-op (and the run loop above is byte-identical)
925 // when no Zapper is attached, so the determinism contract holds.
926 self.bus.sample_zapper_light();
927 // After the frame completes, push state into the rewind ring so
928 // the frontend's hold-F5 UX has somewhere to walk back from.
929 // v2.8.0 Phase 3 — run-ahead suppresses the capture for its hidden
930 // + visible frames via `set_rewind_capture(false)`.
931 if self.rewind.is_some() && self.rewind_capture_enabled {
932 self.rewind_capture();
933 }
934 self.bus.framebuffer()
935 }
936
937 /// v2.8.0 Phase 3 — enable/disable the per-frame rewind capture while
938 /// the ring stays armed. Run-ahead turns it off around its hidden +
939 /// visible frames so only persistent-timeline frames land in the ring.
940 /// Default `true`; with no rewind ring armed this is a no-op.
941 pub const fn set_rewind_capture(&mut self, enabled: bool) {
942 self.rewind_capture_enabled = enabled;
943 }
944
945 /// Whether the per-frame rewind capture is currently armed.
946 ///
947 /// Added in v2.3.6 so a caller that needs to suppress capture temporarily can
948 /// save and restore the *caller's* setting rather than assume the default.
949 /// `rustynes-probe` does exactly that around a trial: its replayed frames
950 /// never happened on the user's timeline, so they must not enter the ring —
951 /// but nor may re-enabling capture afterwards turn it on for someone who had
952 /// deliberately turned it off. Run-ahead predates this and still restores an
953 /// unconditional `true`, which is correct only because nothing else disables
954 /// capture today.
955 #[must_use]
956 pub const fn rewind_capture_enabled(&self) -> bool {
957 self.rewind_capture_enabled
958 }
959
960 /// Step exactly one CPU instruction. For debuggers / step-through tools.
961 pub fn step_instruction(&mut self) -> u8 {
962 #[cfg(feature = "cpu-boot-trace")]
963 self.cpu_boot_trace_record();
964 // v2.3.2 "Lucid" — mirror `run_frame`'s write-attribution context push,
965 // so single-stepping through a `$2007` store in the debugger attributes
966 // the byte to the stepped instruction and not to whatever `run_frame`
967 // last left latched.
968 #[cfg(feature = "debug-hooks")]
969 self.bus
970 .ppu
971 .set_attrib_context(self.cpu.pc, self.cpu.cycles);
972 #[cfg(feature = "debug-hooks")]
973 self.bus
974 .apu
975 .set_attrib_context(self.cpu.pc, self.cpu.cycles);
976 self.cpu.step(&mut self.bus)
977 }
978
979 /// v1.1.0 beta.2 (Workstream C) — add an exec/PC breakpoint at `addr`.
980 /// [`Nes::run_frame`] stops the frame the next time the program counter
981 /// reaches `addr` (reportable via [`Nes::take_break_hit`]). Idempotent.
982 /// `debug-hooks` only.
983 #[cfg(feature = "debug-hooks")]
984 pub fn add_breakpoint(&mut self, addr: u16) {
985 if !self.breakpoints.contains(&addr) {
986 self.breakpoints.push(addr);
987 }
988 }
989
990 /// Remove a previously-added exec breakpoint (no-op if absent).
991 #[cfg(feature = "debug-hooks")]
992 pub fn remove_breakpoint(&mut self, addr: u16) {
993 self.breakpoints.retain(|&a| a != addr);
994 }
995
996 /// Remove all breakpoints.
997 #[cfg(feature = "debug-hooks")]
998 pub fn clear_breakpoints(&mut self) {
999 self.breakpoints.clear();
1000 }
1001
1002 /// The current exec breakpoints (insertion order).
1003 #[cfg(feature = "debug-hooks")]
1004 #[must_use]
1005 // `Vec` -> slice deref coercion is not const, so this can't be `const fn`
1006 // (clippy's `missing_const_for_fn` is a false positive here).
1007 #[allow(clippy::missing_const_for_fn)]
1008 pub fn breakpoints(&self) -> &[u16] {
1009 &self.breakpoints
1010 }
1011
1012 /// Arm/disarm breakpoint checking without discarding the list. Default on.
1013 #[cfg(feature = "debug-hooks")]
1014 pub const fn set_breakpoints_enabled(&mut self, enabled: bool) {
1015 self.breakpoints_enabled = enabled;
1016 }
1017
1018 /// Whether breakpoint checking is armed.
1019 #[cfg(feature = "debug-hooks")]
1020 #[must_use]
1021 pub const fn breakpoints_enabled(&self) -> bool {
1022 self.breakpoints_enabled
1023 }
1024
1025 /// Take the PC that last hit a breakpoint (cleared on read). The frontend
1026 /// polls this after [`Nes::run_frame`] to pause when a breakpoint fired.
1027 #[cfg(feature = "debug-hooks")]
1028 pub const fn take_break_hit(&mut self) -> Option<u16> {
1029 self.break_hit.take()
1030 }
1031
1032 /// v1.4.0 Workstream D (D2) — arm the event-driven breakpoint categories
1033 /// (a bit-OR of [`crate::EventBpKind::bit`]). `0` (default) disarms every
1034 /// category — the per-access taps are then a single cheap `mask == 0`
1035 /// early-out. Output-only: a hit pauses + reports but never mutates state.
1036 /// `debug-hooks` only.
1037 #[cfg(feature = "debug-hooks")]
1038 pub const fn set_event_breakpoints(&mut self, mask: u16) {
1039 self.bus.set_event_breakpoints(mask);
1040 }
1041
1042 /// The armed event-breakpoint category mask.
1043 #[cfg(feature = "debug-hooks")]
1044 #[must_use]
1045 pub const fn event_breakpoints(&self) -> u16 {
1046 self.bus.event_breakpoints()
1047 }
1048
1049 /// Take the first event-breakpoint hit of the current frame (cleared on
1050 /// read). The frontend polls this after [`Nes::run_frame`] to pause when an
1051 /// armed hardware event fired, reporting its kind + frame/cycle/scanline/dot.
1052 #[cfg(feature = "debug-hooks")]
1053 pub const fn take_event_break_hit(&mut self) -> Option<crate::EventBreakHit> {
1054 self.bus.take_event_break_hit()
1055 }
1056
1057 /// Maximum cycle-trace ring depth (oldest records drop past this).
1058 #[cfg(feature = "debug-hooks")]
1059 pub const TRACE_CAP: usize = 50_000;
1060
1061 /// v1.1.0 beta.2 (T-110-C2) — start/stop the cycle-trace logger. While on,
1062 /// each executed instruction's CPU state is pushed to a ring buffer (capped
1063 /// at [`Self::TRACE_CAP`]). Default off.
1064 #[cfg(feature = "debug-hooks")]
1065 pub const fn set_trace_enabled(&mut self, enabled: bool) {
1066 self.trace_enabled = enabled;
1067 }
1068
1069 /// Whether the cycle-trace logger is recording.
1070 #[cfg(feature = "debug-hooks")]
1071 #[must_use]
1072 pub const fn trace_enabled(&self) -> bool {
1073 self.trace_enabled
1074 }
1075
1076 /// Number of records currently in the trace ring.
1077 #[cfg(feature = "debug-hooks")]
1078 #[must_use]
1079 pub fn trace_len(&self) -> usize {
1080 self.trace.len()
1081 }
1082
1083 /// Clear the trace ring.
1084 #[cfg(feature = "debug-hooks")]
1085 pub fn clear_trace(&mut self) {
1086 self.trace.clear();
1087 }
1088
1089 /// Copy the trace ring oldest-first (for the trace panel / file export).
1090 #[cfg(feature = "debug-hooks")]
1091 #[must_use]
1092 pub fn trace_records(&self) -> alloc::vec::Vec<TraceRec> {
1093 self.trace.iter().copied().collect()
1094 }
1095
1096 /// Copy the most recent `n` trace records (oldest-first) — for the live
1097 /// trace panel's tail view, cheaper than [`Self::trace_records`] on a full
1098 /// ring.
1099 #[cfg(feature = "debug-hooks")]
1100 #[must_use]
1101 pub fn trace_tail_vec(&self, n: usize) -> alloc::vec::Vec<TraceRec> {
1102 let skip = self.trace.len().saturating_sub(n);
1103 self.trace.iter().skip(skip).copied().collect()
1104 }
1105
1106 /// v1.1.0 beta.2 (T-110-C3) — start/stop the event viewer. While on, the bus
1107 /// records this frame's PPU/APU/mapper writes (with their PPU position); the
1108 /// log is reset at each [`Self::run_frame`]. Default off; output-only.
1109 #[cfg(feature = "debug-hooks")]
1110 pub const fn set_event_logging(&mut self, enabled: bool) {
1111 self.bus.set_event_logging(enabled);
1112 }
1113
1114 /// Whether the event viewer is recording.
1115 #[cfg(feature = "debug-hooks")]
1116 #[must_use]
1117 pub const fn event_logging(&self) -> bool {
1118 self.bus.event_logging()
1119 }
1120
1121 /// The current frame's captured events (for the event-viewer panel).
1122 #[cfg(feature = "debug-hooks")]
1123 #[must_use]
1124 #[allow(clippy::missing_const_for_fn)] // slice deref is not const.
1125 pub fn events(&self) -> &[crate::bus::EventRec] {
1126 self.bus.events()
1127 }
1128
1129 /// v2.3.2 "Lucid" — arm or disarm per-byte **write attribution** for the
1130 /// PPU's own memories (CIRAM, OAM, palette RAM).
1131 ///
1132 /// While armed, every write to those memories is stamped with the program
1133 /// counter and CPU cycle of the instruction that performed it, which is the
1134 /// edge the pixel-provenance panel walks to answer "which instruction put
1135 /// this byte here?". The Event Viewer records the CPU-side `$2000-$3FFF`
1136 /// write and the memory-access counter records a cycle stamp, but neither
1137 /// carries the PC *and* the resolved destination — see
1138 /// [`rustynes_ppu::provenance`] for why the two halves are recorded on
1139 /// opposite sides of the bus.
1140 ///
1141 /// Default off. Arming allocates
1142 /// [`rustynes_ppu::WriteAttribution::HEAP_BYTES`]; disarming frees it.
1143 /// Output-only, so emulation is bit-identical either way.
1144 #[cfg(feature = "debug-hooks")]
1145 pub fn set_write_attribution(&mut self, enabled: bool) {
1146 self.bus.ppu.set_write_attribution(enabled);
1147 }
1148
1149 /// The write-attribution store, or `None` when not armed.
1150 #[cfg(feature = "debug-hooks")]
1151 #[must_use]
1152 pub fn write_attribution(&self) -> Option<&rustynes_ppu::WriteAttribution> {
1153 self.bus.ppu.write_attribution()
1154 }
1155
1156 /// Forget the current frame's per-pixel provenance, keeping it armed.
1157 ///
1158 /// Called automatically on power-cycle and on both restore paths; exposed so
1159 /// a host that rewinds by other means can do the same.
1160 #[cfg(feature = "debug-hooks")]
1161 pub fn clear_pixel_provenance(&mut self) {
1162 self.bus.ppu.clear_pixel_provenance();
1163 }
1164
1165 /// Forget every recorded write attribution, keeping the store armed.
1166 ///
1167 /// Call this after a save-state restore or a power-cycle: the restored bytes
1168 /// were not written by any instruction this session executed, and reporting
1169 /// the PCs that wrote those offsets before the restore would be a
1170 /// confidently wrong answer rather than an absent one.
1171 #[cfg(feature = "debug-hooks")]
1172 pub fn clear_write_attribution(&mut self) {
1173 self.bus.ppu.clear_write_attribution();
1174 }
1175
1176 /// v2.3.2 "Lucid" phase 2 — arm or disarm **per-pixel provenance**.
1177 ///
1178 /// While armed, every emitted pixel records the layer that won the priority
1179 /// decision, the exact `$3Fxx` palette address behind its color, and the
1180 /// nametable / attribute / pattern addresses of the tile **actually on
1181 /// screen** — which `v` cannot answer, because by display time it has
1182 /// advanced two tiles past the pixel.
1183 ///
1184 /// Composes with [`Self::set_write_attribution`]: provenance says which
1185 /// bytes produced a pixel, attribution says which instruction wrote them.
1186 /// Each is useful alone; together they are the full causal chain.
1187 ///
1188 /// Default off. Arming allocates
1189 /// [`rustynes_ppu::PixelProvenanceFrame::HEAP_BYTES`]. Output-only, so
1190 /// emulation is bit-identical either way.
1191 #[cfg(feature = "debug-hooks")]
1192 pub fn set_pixel_provenance(&mut self, enabled: bool) {
1193 self.bus.ppu.set_pixel_provenance(enabled);
1194 }
1195
1196 /// The current frame's per-pixel provenance, or `None` when not armed.
1197 #[cfg(feature = "debug-hooks")]
1198 #[must_use]
1199 pub fn pixel_provenance(&self) -> Option<&rustynes_ppu::PixelProvenanceFrame> {
1200 self.bus.ppu.pixel_provenance()
1201 }
1202
1203 /// Arm or disarm **audio** provenance (v2.3.7 "Overtone").
1204 ///
1205 /// Off by default. Arming allocates the per-register write attribution and
1206 /// the per-CPU-cycle mix trace; disarming frees both. Output-only — nothing
1207 /// recorded is read back into synthesis or carried in the save state, so the
1208 /// deterministic audio contract is unaffected either way.
1209 #[cfg(feature = "debug-hooks")]
1210 pub fn set_audio_provenance(&mut self, enabled: bool) {
1211 self.bus.apu.set_audio_provenance(enabled);
1212 }
1213
1214 /// Whether audio provenance is armed.
1215 #[cfg(feature = "debug-hooks")]
1216 #[must_use]
1217 pub const fn audio_provenance_armed(&self) -> bool {
1218 self.bus.apu.audio_provenance_armed()
1219 }
1220
1221 /// The per-register write attribution — which instruction last wrote each of
1222 /// `$4000-$4017` — or `None` when disarmed.
1223 #[cfg(feature = "debug-hooks")]
1224 #[must_use]
1225 pub fn register_attribution(&self) -> Option<&rustynes_apu::provenance::RegisterAttribution> {
1226 self.bus.apu.register_attribution()
1227 }
1228
1229 /// This frame's per-CPU-cycle mix trace, or `None` when disarmed.
1230 #[cfg(feature = "debug-hooks")]
1231 #[must_use]
1232 pub fn mix_trace(&self) -> Option<&rustynes_apu::provenance::MixTrace> {
1233 self.bus.apu.mix_trace()
1234 }
1235
1236 /// Lift the audio provenance stores out for a same-timeline restore.
1237 ///
1238 /// The audio counterpart of [`Self::take_provenance`], and it exists for the
1239 /// identical reason: run-ahead's rollback runs AFTER the visible frame is
1240 /// produced and BEFORE the frontend releases the emulator lock, so a store
1241 /// the restore clears can never be observed by the UI. That is exactly how
1242 /// Pixel Provenance shipped non-functional from v2.3.2 to v2.3.6. Take
1243 /// before the restore, [`Self::put_audio_provenance`] after.
1244 ///
1245 /// Save-state loads and netplay rollback still clear, unchanged — those are
1246 /// genuine timeline changes. Run-ahead's rollback is not.
1247 #[cfg(feature = "debug-hooks")]
1248 #[must_use]
1249 pub fn take_audio_provenance(&mut self) -> rustynes_apu::provenance::AudioProvenanceStash {
1250 self.bus.apu.take_audio_provenance()
1251 }
1252
1253 /// Put back stores taken by [`Self::take_audio_provenance`].
1254 #[cfg(feature = "debug-hooks")]
1255 pub fn put_audio_provenance(&mut self, stash: rustynes_apu::provenance::AudioProvenanceStash) {
1256 self.bus.apu.put_audio_provenance(stash);
1257 }
1258
1259 /// v2.3.6 — move both provenance stores out, leaving them unarmed.
1260 ///
1261 /// For a host that performs a **same-timeline** restore whose result the user
1262 /// is about to inspect. [`Self::restore`] and [`Self::restore_quiet`] both
1263 /// clear the stores, which is correct when the restore replaces the timeline
1264 /// the records describe — and wrong for run-ahead, whose rollback is the last
1265 /// thing before the UI reads, so the clear discards the record for the frame
1266 /// actually on screen. Take before the restore, [`Self::put_provenance`]
1267 /// after.
1268 ///
1269 /// A move, not a copy: the stores are boxed, so this is two pointer moves.
1270 /// See [`rustynes_ppu::ProvenanceStash`].
1271 #[cfg(feature = "debug-hooks")]
1272 pub const fn take_provenance(&mut self) -> rustynes_ppu::ProvenanceStash {
1273 self.bus.ppu.take_provenance()
1274 }
1275
1276 /// Put back stores taken by [`Self::take_provenance`].
1277 #[cfg(feature = "debug-hooks")]
1278 pub fn put_provenance(&mut self, stash: rustynes_ppu::ProvenanceStash) {
1279 self.bus.ppu.put_provenance(stash);
1280 }
1281
1282 /// Resolve a PPU-space nametable address (`$2000-$3EFF`) to the physical
1283 /// internal-CIRAM offset it reads, applying the mapper's mirroring and any
1284 /// per-game mirroring override.
1285 ///
1286 /// This is what turns a [`rustynes_ppu::PixelProvenance::nt_addr`] into the
1287 /// key [`rustynes_ppu::WriteAttribution::ciram`] is indexed by, so the
1288 /// provenance panel can go from "this pixel's tile came from `$2002`" to
1289 /// "and instruction X wrote that byte" without reimplementing mirroring.
1290 ///
1291 /// Returns `None` for an address outside the nametable window.
1292 ///
1293 /// # Boards with mapper-supplied nametable memory
1294 ///
1295 /// On `MMC5` (`ExRAM` nametables) and 4-screen boards, some nametable writes are
1296 /// absorbed by the mapper via `PpuBus::write_nametable` and never reach
1297 /// internal CIRAM. This function still returns the CIRAM offset the standard
1298 /// mirroring would select, because the only way to know whether the mapper
1299 /// absorbed a particular write is to *perform* one — `write_nametable` takes
1300 /// `&mut self` and has side effects, and a read-only query has no business
1301 /// inventing one. Callers should treat a missing attribution on such a board
1302 /// as "the mapper owns this byte", which is what it means.
1303 #[cfg(feature = "debug-hooks")]
1304 #[must_use]
1305 pub fn ciram_offset_for_nametable_addr(&self, addr: u16) -> Option<usize> {
1306 let a = addr & 0x3FFF;
1307 if !(0x2000..0x3F00).contains(&a) {
1308 return None;
1309 }
1310 let nt_addr = if a >= 0x3000 { a - 0x1000 } else { a };
1311 Some((self.bus.resolve_nametable_address(nt_addr) as usize) & 0x07FF)
1312 }
1313
1314 /// v1.1.0 beta.3 (T-110-E2) — start/stop the Lua bus-access log. While on,
1315 /// the bus records this frame's CPU reads + writes (with values); the log is
1316 /// reset at each [`Self::run_frame`]. Default off; output-only. Enabled by
1317 /// the scripting engine only while `onRead`/`onWrite` callbacks exist.
1318 #[cfg(feature = "debug-hooks")]
1319 pub const fn set_access_logging(&mut self, enabled: bool) {
1320 self.bus.set_access_logging(enabled);
1321 }
1322
1323 /// Whether the bus-access log is recording.
1324 #[cfg(feature = "debug-hooks")]
1325 #[must_use]
1326 pub const fn access_logging(&self) -> bool {
1327 self.bus.access_logging()
1328 }
1329
1330 /// The current frame's captured CPU bus accesses (for the Lua engine).
1331 #[cfg(feature = "debug-hooks")]
1332 #[must_use]
1333 #[allow(clippy::missing_const_for_fn)] // slice deref is not const.
1334 pub fn accesses(&self) -> &[crate::bus::AccessRec] {
1335 self.bus.accesses()
1336 }
1337
1338 /// v1.1.0 beta.3 (T-110-E2) — start/stop the per-frame exec-PC log for the
1339 /// Lua `onExec` callback. Independent of the Trace Logger (`set_trace_enabled`),
1340 /// so enabling it does not disturb the debugger's trace recording. Cleared
1341 /// every [`Self::run_frame`]; output-only.
1342 #[cfg(feature = "debug-hooks")]
1343 pub const fn set_exec_logging(&mut self, enabled: bool) {
1344 self.exec_logging = enabled;
1345 }
1346
1347 /// Whether the per-frame exec-PC log is recording.
1348 #[cfg(feature = "debug-hooks")]
1349 #[must_use]
1350 pub const fn exec_logging(&self) -> bool {
1351 self.exec_logging
1352 }
1353
1354 /// This frame's executed PCs, in execution order (for the Lua engine).
1355 #[cfg(feature = "debug-hooks")]
1356 #[must_use]
1357 #[allow(clippy::missing_const_for_fn)] // slice deref is not const.
1358 pub fn exec_log(&self) -> &[u16] {
1359 &self.exec_log
1360 }
1361
1362 /// `true` if the running program read a controller port (`$4016`/`$4017`)
1363 /// during the most recent [`Self::run_frame`] — the inverse of a `TAStudio`
1364 /// "lag frame" (v1.6.0 Workstream A3). The greenzone / piano-roll lag log
1365 /// queries this each frame. Output-only; `debug-hooks`-gated, so the
1366 /// shipped build is byte-identical and the determinism contract holds.
1367 #[cfg(feature = "debug-hooks")]
1368 #[must_use]
1369 pub const fn was_input_polled_this_frame(&self) -> bool {
1370 self.bus.controller_polled()
1371 }
1372
1373 /// v1.2.0 (T-110-E1) — start/stop the per-frame interrupt-service log for
1374 /// the Lua `onNmi` / `onIrq` callbacks. The log records this frame's
1375 /// committed NMI / IRQ / BRK service entries (captured at the CPU's
1376 /// service-vector commit point, NOT the speculative poll sampler); it is
1377 /// cleared at each [`Self::run_frame`]. Default off; output-only. Enabled by
1378 /// the scripting engine only while `onNmi`/`onIrq` callbacks exist. Mirrors
1379 /// [`Self::set_exec_logging`].
1380 #[cfg(feature = "debug-hooks")]
1381 pub const fn set_interrupt_logging(&mut self, enabled: bool) {
1382 self.bus.set_interrupt_logging(enabled);
1383 }
1384
1385 /// Whether the per-frame interrupt-service log is recording.
1386 #[cfg(feature = "debug-hooks")]
1387 #[must_use]
1388 pub const fn interrupt_logging(&self) -> bool {
1389 self.bus.interrupt_logging()
1390 }
1391
1392 /// This frame's committed interrupt-service entries, in service order (for
1393 /// the Lua engine). Mirrors [`Self::exec_log`] / [`Self::accesses`].
1394 #[cfg(feature = "debug-hooks")]
1395 #[must_use]
1396 #[allow(clippy::missing_const_for_fn)] // slice deref is not const.
1397 pub fn interrupt_log(&self) -> &[crate::bus::InterruptRec] {
1398 self.bus.interrupts()
1399 }
1400
1401 /// Borrow the framebuffer (RGBA8, 256x240).
1402 #[must_use]
1403 pub fn framebuffer(&self) -> &[u8] {
1404 self.bus.framebuffer()
1405 }
1406
1407 /// v1.7.0 "Forge" Workstream B (B3) — overwrite the RGBA8 output framebuffer
1408 /// (the Lua `emu:setScreenBuffer(t)` paints output only). Output-only; see
1409 /// [`rustynes_ppu::Ppu::debug_set_framebuffer`]. Reached only through the
1410 /// script crate's gated post-frame path, so the shipped build is
1411 /// byte-identical and the determinism contract holds. `debug-hooks`-gated.
1412 #[cfg(feature = "debug-hooks")]
1413 pub fn debug_set_framebuffer(&mut self, rgba: &[u8]) {
1414 self.bus.debug_set_framebuffer(rgba);
1415 }
1416
1417 /// Borrow the parallel palette-index framebuffer (256x240 `u16`s, each
1418 /// `(emphasis << 6) | colour`) for the `NES_NTSC` composite filter.
1419 /// See [`rustynes_ppu::Ppu::index_framebuffer`].
1420 #[must_use]
1421 pub fn index_framebuffer(&self) -> &[u16] {
1422 self.bus.index_framebuffer()
1423 }
1424
1425 /// v1.2.0 C3 (hd-pack) — borrow the per-pixel HD-pack tile-source buffer
1426 /// (256x240 [`rustynes_ppu::HdTileSource`] records). Each entry names the
1427 /// CHR tile that produced the pixel; the frontend HD-pack loader groups
1428 /// these by 8x8 cell, hashes the CHR bytes, and substitutes hi-res tiles.
1429 /// Output-only telemetry; the determinism contract is unaffected. See
1430 /// [`rustynes_ppu::Ppu::hd_tile_source`].
1431 #[cfg(feature = "hd-pack")]
1432 #[must_use]
1433 pub fn hd_tile_source(&self) -> &[rustynes_ppu::HdTileSource] {
1434 self.bus.hd_tile_source()
1435 }
1436
1437 /// The frame's background scroll `(x, y)` in NES pixels, for offsetting
1438 /// parallax HD-pack `<background>` layers (see
1439 /// [`rustynes_ppu::Ppu::hd_bg_scroll`]). Output-only.
1440 #[cfg(feature = "hd-pack")]
1441 #[must_use]
1442 pub const fn hd_bg_scroll(&self) -> (i32, i32) {
1443 self.bus.ppu().hd_bg_scroll()
1444 }
1445
1446 /// The per-frame NTSC composite colour phase consumed by the `NES_NTSC`
1447 /// filter (`0..=2` on NTSC; frame parity `0..=1` on PAL/Dendy). See
1448 /// [`rustynes_ppu::Ppu::ntsc_phase`].
1449 #[must_use]
1450 pub const fn ntsc_phase(&self) -> u8 {
1451 self.bus.ntsc_phase()
1452 }
1453
1454 /// The completed-frame counter (PPU frames since power-on). A monotonic,
1455 /// deterministic, save-state-restored value — the frontend uses it to phase
1456 /// turbo/autofire so the strobe is reproducible under rollback / TAS replay.
1457 #[must_use]
1458 pub const fn frame(&self) -> u64 {
1459 self.bus.ppu().frame()
1460 }
1461
1462 /// Borrow the underlying bus (debugger / tests).
1463 #[must_use]
1464 pub const fn bus(&self) -> &SystemBus {
1465 &self.bus
1466 }
1467
1468 /// Mutably borrow the underlying bus (debugger / tests).
1469 pub const fn bus_mut(&mut self) -> &mut SystemBus {
1470 &mut self.bus
1471 }
1472
1473 /// Assert or release the external /NMI pin. **Co-simulation only.**
1474 ///
1475 /// v2.5.1, [ADR 0038]. Rung 2's interrupt sweep needs the same stimulus on
1476 /// both sides, and this emulator had no way to receive it: its /NMI comes
1477 /// from the PPU and its /IRQ from the APU frame counter or a mapper, none of
1478 /// which exist at the CPU rung of the co-simulation.
1479 ///
1480 /// `true` asserts the pin. It is OR'd into the CPU's existing poll and
1481 /// consumed on the edge exactly as a PPU-generated NMI is, so the CPU cannot
1482 /// tell the two apart -- which is the property that makes the sweep test the
1483 /// CPU rather than the injection. It does **not** bypass the poll, force a
1484 /// vector, or short-circuit the sequence.
1485 ///
1486 /// Gated behind `cosim-interrupt-inject`, which nothing in the workspace
1487 /// enables. A default build does not contain this method or its state.
1488 ///
1489 /// [ADR 0038]: https://github.com/doublegate/RustyNES/blob/main/docs/adr/0038-cosim-interrupt-injection-api.md
1490 #[cfg(feature = "cosim-interrupt-inject")]
1491 pub const fn inject_nmi(&mut self, asserted: bool) {
1492 self.bus.set_inject_nmi(asserted);
1493 }
1494
1495 /// Assert or release the external /IRQ pin. **Co-simulation only.**
1496 ///
1497 /// Level-sensitive, as the pin is: it is masked by `I` through the CPU's own
1498 /// logic, and a pulse shorter than a poll is missed. Holding it asserted
1499 /// across several cycles is how a real device drives it. See
1500 /// [`Self::inject_nmi`] for the contract and the ADR.
1501 #[cfg(feature = "cosim-interrupt-inject")]
1502 pub const fn inject_irq(&mut self, asserted: bool) {
1503 self.bus.set_inject_irq(asserted);
1504 }
1505
1506 /// Borrow the CPU (debugger / tests).
1507 #[must_use]
1508 pub const fn cpu(&self) -> &Cpu {
1509 &self.cpu
1510 }
1511
1512 /// Cumulative CPU cycle count.
1513 #[must_use]
1514 pub const fn cycle(&self) -> u64 {
1515 self.bus.cycle()
1516 }
1517
1518 /// `true` when the CPU has executed a JAM/KIL/STP and is halted.
1519 ///
1520 /// (v2.0.0 beta.5: the `VsDualSystem` soft-lockstep driver guards its
1521 /// per-instruction stepping — the pre-existing debugger
1522 /// [`Self::step_instruction`] — on this.)
1523 #[must_use]
1524 pub const fn is_jammed(&self) -> bool {
1525 self.cpu.is_jammed()
1526 }
1527
1528 /// Cartridge region (NTSC / PAL / Dendy / Multi). Drives wall-clock
1529 /// frame pacing in the frontend and clock dividers in the chip cores.
1530 #[must_use]
1531 pub const fn region(&self) -> Region {
1532 match self.bus.region() {
1533 rustynes_mappers::Region::Pal => Region::Pal,
1534 rustynes_mappers::Region::Dendy => Region::Dendy,
1535 // iNES 1.0 "Multi" cartridges are treated as NTSC for pacing
1536 // (matches the PPU / APU init in `SystemBus::with_sample_rate`).
1537 _ => Region::Ntsc,
1538 }
1539 }
1540
1541 /// Length in bytes of the loaded cartridge's PRG-ROM (read-only metadata).
1542 ///
1543 /// Exposed for the Lua scripting `cart:prg_size()` query (and any other
1544 /// read-only consumer); does not touch deterministic state.
1545 #[must_use]
1546 pub const fn prg_rom_len(&self) -> usize {
1547 self.bus.prg_rom_len()
1548 }
1549
1550 /// Length in bytes of the loaded cartridge's CHR-ROM (0 when the board uses
1551 /// CHR-RAM). Read-only metadata; backs the Lua `cart:chr_size()` query.
1552 #[must_use]
1553 pub const fn chr_rom_len(&self) -> usize {
1554 self.bus.chr_rom_len()
1555 }
1556
1557 /// The loaded cartridge's iNES / NES 2.0 mapper id, after any load-time
1558 /// header correction (backs the Lua `cart:mapper_id()`, the ROM-info
1559 /// panel and the mobile `RomInfo`). A Famicom Disk System image reports
1560 /// 20 and an NSF 31, the ids their synthetic cartridges carry.
1561 ///
1562 /// v2.9.8 — read from the cartridge. It used to read the mapper's debug
1563 /// view, whose default `debug_info` names mapper 0, so every board
1564 /// without its own override (`UxROM`, CNROM, `AxROM`, ...) reported 0, and
1565 /// an NSF reported 0 rather than 31.
1566 #[must_use]
1567 pub const fn mapper_id(&self) -> u16 {
1568 self.bus.cart.mapper_id
1569 }
1570
1571 /// v2.9.8 — the loaded cartridge's NES 2.0 submapper (0 for an iNES 1.0
1572 /// image, which has none), after any load-time header correction.
1573 #[must_use]
1574 pub const fn submapper(&self) -> u8 {
1575 self.bus.cart.submapper
1576 }
1577
1578 /// Wall-clock frame duration for this cartridge's region. The frontend
1579 /// uses this to pace emulator advance independently of monitor refresh
1580 /// rate — without it, `Fifo` present mode on a 144 Hz monitor would
1581 /// run the emulator 2.4× too fast.
1582 #[must_use]
1583 pub const fn frame_duration(&self) -> Duration {
1584 match self.region() {
1585 Region::Pal => FRAME_DURATION_PAL,
1586 Region::Dendy => FRAME_DURATION_DENDY,
1587 Region::Ntsc => FRAME_DURATION_NTSC,
1588 }
1589 }
1590
1591 /// Drain accumulated audio samples at the host sample rate. Call once per
1592 /// frame from the frontend's audio thread or batch driver.
1593 ///
1594 /// The samples are **bipolar and DC-blocked**, not the mixer's raw
1595 /// `[0.0, ~1.0]`: measured over 900 frames (v2.8.1), the 2A03 alone spans
1596 /// about `-0.385..0.223` with a zero mean, and expansion audio reaches
1597 /// further (a Namco 163 channel, `+/-0.870`). Nothing measured passes
1598 /// `+/-1.0`, so a frontend converting to `i16` should put full scale at
1599 /// `1.0`. This comment said `[0.0, ~1.0]` until v2.8.1.
1600 pub fn drain_audio(&mut self) -> Vec<f32> {
1601 self.bus.drain_audio()
1602 }
1603
1604 /// Set the buttons currently held on player `port`. Ports 0/1 are the
1605 /// standard controllers (`$4016`/`$4017`); ports 2/3 are players 3/4 on
1606 /// the Four Score adapter (only polled when [`Self::set_four_score`] is
1607 /// on). The change takes effect on the next strobe edge.
1608 ///
1609 /// # Panics
1610 ///
1611 /// Panics if `port` is not in `0..=3`.
1612 pub const fn set_buttons(&mut self, port: usize, buttons: Buttons) {
1613 self.bus.set_buttons(port, buttons);
1614 }
1615
1616 /// Get the buttons currently held on player `port` (0/1 = `$4016`/`$4017`;
1617 /// 2/3 = Four Score players 3/4). Read-only; does not advance emulator
1618 /// state.
1619 ///
1620 /// Used by the TAS movie recorder (`crate::movie`) to capture the inputs
1621 /// applied before each [`Self::run_frame`]. (Movies record all four
1622 /// ports since v2.9.8, and the non-controller inputs since v3.5.0.)
1623 ///
1624 /// # Panics
1625 ///
1626 /// Panics if `port` is not in `0..=3`.
1627 #[must_use]
1628 pub const fn buttons(&self, port: usize) -> Buttons {
1629 self.bus.controller(port).buttons()
1630 }
1631
1632 /// Enable/disable the Four Score 4-player adapter. Off by default; while
1633 /// off, controller reads are byte-identical to the standard two-pad
1634 /// behavior (the determinism contract and save-states are unaffected).
1635 /// When on, players 3/4 (ports 2/3) are multiplexed onto `$4016`/`$4017`
1636 /// across a 24-read serial sequence.
1637 pub const fn set_four_score(&mut self, enabled: bool) {
1638 self.bus.set_four_score(enabled);
1639 }
1640
1641 /// Whether the Four Score adapter is currently enabled.
1642 #[must_use]
1643 pub const fn four_score(&self) -> bool {
1644 self.bus.four_score()
1645 }
1646
1647 // --- Vs. System DIP switches + coin/service inputs ---
1648
1649 /// True when the running cart is Nintendo Vs. System arcade hardware
1650 /// (NES 2.0 console type = Vs. System). The RGB PPU + DIP/coin inputs only
1651 /// take effect on such carts.
1652 #[must_use]
1653 pub fn is_vs_system(&self) -> bool {
1654 self.bus.is_vs_system()
1655 }
1656
1657 /// True when the cart's header marks a Vs. `DualSystem` board (two CPUs /
1658 /// two PPUs; NES 2.0 byte-13 high nibble = Vs. hardware type 5/6).
1659 ///
1660 /// Detection only: this single-system core cannot boot a `DualSystem` title
1661 /// past its attract handshake, so the frontend uses this to surface a clear
1662 /// note. The two-CPU/two-PPU emulation is a documented v2.0 deferral
1663 /// (`docs/audit/vs-dualsystem-design-2026-06-11.md`).
1664 #[must_use]
1665 pub const fn is_vs_dual_system(&self) -> bool {
1666 self.bus.is_vs_dual_system()
1667 }
1668
1669 /// Set the Vs. System 8-bit DIP-switch bank (switch 1 = bit 0 .. switch 8 =
1670 /// bit 7). Read through the upper bits of `$4016`/`$4017`. No effect on
1671 /// non-Vs. carts; the standard controller read stays byte-identical.
1672 pub const fn set_vs_dip(&mut self, dip: u8) {
1673 self.bus.set_vs_dip(dip);
1674 }
1675
1676 /// Current Vs. System DIP-switch bank.
1677 #[must_use]
1678 pub const fn vs_dip(&self) -> u8 {
1679 self.bus.vs_dip()
1680 }
1681
1682 /// Override the Vs. System PPU type and re-apply the output palette.
1683 ///
1684 /// iNES-1.0 Vs. dumps default to the 2C03 palette (no NES 2.0 byte-13);
1685 /// the per-game database ([`crate::vs_db`]) supplies the correct
1686 /// 2C04-000x / 2C05 type, which the frontend applies through this setter.
1687 /// Mostly the colour LUT the PPU emits through, but a 2C05 also returns
1688 /// its identification bits in `$2002` and swaps `$2000` / `$2001`, which
1689 /// game code reads -- so it is emulation state, and movies and netplay
1690 /// carry it (v2.9.8, [`crate::HardwareOptions`]). (Until v2.9.8 this said
1691 /// "never game logic", which the 2C05 path contradicts.) No effect on
1692 /// non-Vs. carts.
1693 pub const fn set_vs_ppu_type(&mut self, t: rustynes_mappers::VsPpuType) {
1694 self.bus.set_vs_ppu_type(t);
1695 }
1696
1697 /// v2.9.8 — the Vs. System PPU type in effect: the header's, or the one a
1698 /// later [`Self::set_vs_ppu_type`] installed. [`rustynes_mappers::VsPpuType::None`]
1699 /// on every non-Vs. cart.
1700 ///
1701 /// Read by [`crate::HardwareOptions::capture`]: on a 2C05 the type also
1702 /// sets the `$2002` identification bits and swaps `$2000` / `$2001`, which
1703 /// game code reads, so a movie or a netplay peer must run the same one.
1704 #[must_use]
1705 pub const fn vs_ppu_type(&self) -> rustynes_mappers::VsPpuType {
1706 self.bus.cart.vs_ppu_type
1707 }
1708
1709 /// v2.9.8 — the parsed cartridge description the machine was built from
1710 /// (mapper, submapper, mirroring, RAM sizes, console type ...), after any
1711 /// load-time header correction. Crate-internal: read by
1712 /// [`crate::BoardDescription::capture`].
1713 #[must_use]
1714 pub(crate) const fn cartridge(&self) -> &rustynes_mappers::Cartridge {
1715 &self.bus.cart
1716 }
1717
1718 /// Latch a Vs. System coin insertion on the given acceptor (0 = #1, 1 = #2).
1719 /// Reads true for a real-hardware ~40-70 ms window; the frontend should
1720 /// clear it (see [`Self::clear_coin`]) after a few frames.
1721 pub const fn insert_coin(&mut self, acceptor: u8) {
1722 self.bus.insert_coin(acceptor);
1723 }
1724
1725 /// Clear all latched Vs. System coin-insert signals.
1726 pub const fn clear_coin(&mut self) {
1727 self.bus.clear_coin();
1728 }
1729
1730 /// Set / clear the Vs. System service button.
1731 pub const fn set_vs_service(&mut self, pressed: bool) {
1732 self.bus.set_vs_service(pressed);
1733 }
1734
1735 /// v3.5.0 — the latched Vs. System coin-insert signals: bit 0 = acceptor
1736 /// #1, bit 1 = acceptor #2 (what [`Self::insert_coin`] sets and
1737 /// [`Self::clear_coin`] clears). Read by a movie recorder.
1738 #[must_use]
1739 pub const fn vs_coin(&self) -> u8 {
1740 self.bus.vs_coin()
1741 }
1742
1743 /// v3.5.0 — whether the Vs. System service button is held (what
1744 /// [`Self::set_vs_service`] set). Read by a movie recorder.
1745 #[must_use]
1746 pub const fn vs_service(&self) -> bool {
1747 self.bus.vs_service()
1748 }
1749
1750 /// v3.5.0 — whether the Famicom microphone is asserted (what
1751 /// [`Self::set_microphone`] set). Read by a movie recorder.
1752 #[must_use]
1753 pub const fn microphone(&self) -> bool {
1754 self.bus.microphone()
1755 }
1756
1757 // --- Famicom Disk System disk control (Stage 2b) ---
1758
1759 /// Number of disk sides in the inserted FDS image. Returns 0 for cartridge
1760 /// builds (so a frontend can branch on "is this an FDS game?").
1761 #[must_use]
1762 pub fn disk_side_count(&self) -> usize {
1763 self.bus.disk_side_count()
1764 }
1765
1766 /// The currently inserted FDS disk side index, or `None` when ejected (or
1767 /// for a cartridge build). A game that prompts "insert side B" is asking the
1768 /// user to call [`Self::set_disk_side`].
1769 #[must_use]
1770 pub fn inserted_disk_side(&self) -> Option<usize> {
1771 self.bus.inserted_disk_side()
1772 }
1773
1774 /// Insert FDS side `i` (`Some(i)`) or eject the disk (`None`). Inserting
1775 /// resets the head and opens a short deterministic "not ready" window (the
1776 /// BIOS polls `$4032` and waits for ready); an out-of-range index is
1777 /// ignored. No-op on cartridge builds. This is how the user complies with a
1778 /// game's "insert side N" prompt.
1779 pub fn set_disk_side(&mut self, side: Option<usize>) {
1780 self.bus.set_disk_side(side);
1781 }
1782
1783 // --- Datach barcode reader (mapper 157, v3.2.0) ---
1784
1785 /// Whether the cartridge has a barcode reader. Only the Bandai Datach
1786 /// Joint ROM System (mapper 157) does; a frontend shows its "scan a
1787 /// barcode" control only when this is `true`.
1788 #[must_use]
1789 pub fn has_barcode_reader(&self) -> bool {
1790 self.bus.has_barcode_reader()
1791 }
1792
1793 /// Swipe a barcode past the Datach reader.
1794 ///
1795 /// `code` is a JAN / EAN code of 13 or 8 digits (spaces and hyphens are
1796 /// skipped), validated here at the boundary, check digit included. The
1797 /// reader then presents the symbol's bars to the CPU over the following
1798 /// CPU cycles, deterministically: the same scan at the same cycle yields
1799 /// the same frames, and a save state taken mid-scan restores mid-scan.
1800 /// A scan replaces any scan still in flight.
1801 ///
1802 /// A scan is an input that changes emulation. Since v3.5.0 a `.rnm` movie
1803 /// records it ([`crate::ExtraInput::barcode`]: [`Self::barcode_this_frame`]
1804 /// holds it until the next frame starts, so a recorder sees it). Netplay
1805 /// still does not carry it: a caller running a netplay session must
1806 /// refuse it rather than desynchronise (the desktop frontend does).
1807 ///
1808 /// # Errors
1809 ///
1810 /// [`BarcodeScanError::Malformed`] for a string that is not a valid
1811 /// 13- or 8-digit code, and [`BarcodeScanError::NoReader`] when the
1812 /// cartridge has no barcode reader.
1813 pub fn scan_barcode(&mut self, code: &str) -> Result<(), BarcodeScanError> {
1814 let code = rustynes_mappers::Barcode::parse(code).map_err(BarcodeScanError::Malformed)?;
1815 self.scan_barcode_code(&code)
1816 }
1817
1818 /// v3.5.0 — [`Self::scan_barcode`] for a code already validated (a
1819 /// movie's recorded scan, or a host holding a parsed [`crate::Barcode`]).
1820 ///
1821 /// # Errors
1822 ///
1823 /// [`BarcodeScanError::NoReader`] when the cartridge has no barcode
1824 /// reader.
1825 pub fn scan_barcode_code(
1826 &mut self,
1827 code: &rustynes_mappers::Barcode,
1828 ) -> Result<(), BarcodeScanError> {
1829 if self.bus.scan_barcode(code) {
1830 self.barcode_this_frame = Some(*code);
1831 Ok(())
1832 } else {
1833 Err(BarcodeScanError::NoReader)
1834 }
1835 }
1836
1837 /// v3.5.0 — the barcode swiped since the current (or next) frame began,
1838 /// if any: set by [`Self::scan_barcode`], cleared when [`Self::run_frame`]
1839 /// starts. Read by [`crate::FrameInput::held_on`] so a movie records the
1840 /// scan on the frame it was made before.
1841 #[must_use]
1842 pub const fn barcode_this_frame(&self) -> Option<rustynes_mappers::Barcode> {
1843 self.barcode_this_frame
1844 }
1845
1846 /// Whether a barcode scan is still being presented to the CPU.
1847 #[must_use]
1848 pub fn barcode_scan_in_progress(&self) -> bool {
1849 self.bus.barcode_scan_in_progress()
1850 }
1851
1852 /// Start recording the diagnostic FDS read-stream trace (the `$4031` disk-byte
1853 /// stream + `$4025` control writes + side changes). Off by default and
1854 /// observation-only — it never affects emulation, so the determinism contract
1855 /// holds. Drain it with [`Self::take_fds_trace`]. No-op on cartridge builds.
1856 /// Used by the `fds_trace` diagnostic harness to debug disk-read / side-swap
1857 /// failures (e.g. the Kid Icarus side-B `ERR.07` stall).
1858 pub fn enable_fds_trace(&mut self) {
1859 self.bus.enable_fds_trace();
1860 }
1861
1862 /// Drain the accumulated FDS read-stream trace records. Empty for cartridge
1863 /// builds or when [`Self::enable_fds_trace`] was never called.
1864 #[must_use]
1865 pub fn take_fds_trace(&mut self) -> Vec<rustynes_mappers::FdsTraceRec> {
1866 self.bus.take_fds_trace()
1867 }
1868
1869 /// Re-serialize the (possibly-modified) FDS disk image to the headerless
1870 /// `.fds` byte layout so the host can write it to a side-car `.fds.sav`
1871 /// (keyed by [`Self::rom_sha256`]; a console booted from that file reports
1872 /// the same key once the host calls [`Self::set_rom_identity`]). Empty for
1873 /// cartridge builds.
1874 #[must_use]
1875 pub fn disk_image_bytes(&self) -> Vec<u8> {
1876 self.bus.disk_image_bytes()
1877 }
1878
1879 /// Whether the FDS disk image has unsaved writes since the last
1880 /// [`Self::clear_disk_dirty`]. A frontend checks this on quit / periodically
1881 /// to decide whether to persist the disk.
1882 #[must_use]
1883 pub fn disk_is_dirty(&self) -> bool {
1884 self.bus.disk_is_dirty()
1885 }
1886
1887 /// Clear the FDS disk dirty flag after persisting the image.
1888 pub fn clear_disk_dirty(&mut self) {
1889 self.bus.clear_disk_dirty();
1890 }
1891
1892 /// Mark the inserted FDS disk read-only (`true`) or writable (`false`,
1893 /// the default). Drives the `$4032` write-protect flag; a write-protected
1894 /// disk drops bytes in write mode without modifying the medium.
1895 pub fn set_disk_write_protected(&mut self, protected: bool) {
1896 self.bus.set_disk_write_protected(protected);
1897 }
1898
1899 /// Attach a non-standard overlay input device on `port` (0 = `$4016`, 1 =
1900 /// `$4017`). Pass `None` to unplug it and return the port to the standard
1901 /// controller / Four Score path (byte-identical reads). Devices are
1902 /// unplugged on power-cycle.
1903 ///
1904 /// # Panics
1905 ///
1906 /// Panics if `port` is not in `0..=1`.
1907 pub fn set_expansion_device(&mut self, port: usize, device: Option<InputDevice>) {
1908 self.bus.set_expansion_device(port, device);
1909 }
1910
1911 /// Borrow the overlay device attached to `port` (0 = `$4016`, 1 =
1912 /// `$4017`), if any.
1913 ///
1914 /// # Panics
1915 ///
1916 /// Panics if `port` is not in `0..=1`.
1917 #[must_use]
1918 pub const fn expansion_device(&self, port: usize) -> &Option<InputDevice> {
1919 self.bus.expansion_device(port)
1920 }
1921
1922 /// Attach an Arkanoid "Vaus" paddle on `port` (typically port 1 / `$4017`)
1923 /// and set its position + fire state. `position` is the raw 8-bit
1924 /// potentiometer value (`$00` far-left .. `$FF` far-right); `fire` is the
1925 /// single button. Convenience wrapper that attaches the device if absent
1926 /// then updates it.
1927 ///
1928 /// # Panics
1929 ///
1930 /// Panics if `port` is not in `0..=1`.
1931 pub fn set_paddle(&mut self, port: usize, position: u8, fire: bool) {
1932 if !matches!(self.bus.expansion_device(port), Some(InputDevice::Vaus(_))) {
1933 self.bus.set_expansion_device(
1934 port,
1935 Some(InputDevice::Vaus(crate::input_device::VausState::new())),
1936 );
1937 }
1938 self.bus.set_paddle(port, position, fire);
1939 }
1940
1941 /// Attach an NES Zapper light gun on `port` (typically port 1 / `$4017`)
1942 /// and set its aim point + trigger. `(x, y)` is the screen pixel the gun is
1943 /// aimed at (0..256, 0..240; out of range = off-screen); `trigger` is the
1944 /// trigger state. Convenience wrapper that attaches the device if absent
1945 /// then updates it.
1946 ///
1947 /// Light detection is sampled from the framebuffer at the end of each
1948 /// [`Self::run_frame`]; the determinism contract holds because the sample
1949 /// only runs when a Zapper is attached (the no-device path is unchanged).
1950 ///
1951 /// # Panics
1952 ///
1953 /// Panics if `port` is not in `0..=1`.
1954 pub fn set_zapper(&mut self, port: usize, x: u16, y: u16, trigger: bool) {
1955 if !matches!(
1956 self.bus.expansion_device(port),
1957 Some(InputDevice::Zapper(_))
1958 ) {
1959 self.bus.set_expansion_device(
1960 port,
1961 Some(InputDevice::Zapper(crate::input_device::ZapperState::new())),
1962 );
1963 }
1964 self.bus.set_zapper(port, x, y, trigger);
1965 }
1966
1967 /// A3 (v2.2.3): enable the **beam-relative** Zapper light model.
1968 ///
1969 /// **Default ON since v2.3.6** (was off in v2.2.3-v2.3.5). See
1970 /// [`crate::bus::SystemBus::set_zapper_temporal_light`] for the model and
1971 /// for why it was promoted; in short, the light bit is a function of where
1972 /// the CRT beam is at the moment of the read (dark before the beam paints
1973 /// the aim row, lit for the ~19-26-scanline photodiode hold, dark after)
1974 /// instead of one answer for the whole frame — and the frame model made a
1975 /// *Duck Hunt* hit impossible.
1976 ///
1977 /// Pass `false` to restore the pre-v2.3.6 frame-granular behaviour.
1978 ///
1979 /// Deterministic either way: the temporal answer is a pure function of
1980 /// framebuffer + aim + current scanline and holds no extra state, so it
1981 /// adds nothing to serialize and cannot desync a save state or a netplay
1982 /// rollback.
1983 pub const fn set_zapper_temporal_light(&mut self, on: bool) {
1984 self.bus.set_zapper_temporal_light(on);
1985 }
1986
1987 /// Whether the beam-relative Zapper light model is enabled (A3).
1988 #[must_use]
1989 pub const fn zapper_temporal_light(&self) -> bool {
1990 self.bus.zapper_temporal_light()
1991 }
1992
1993 /// Drive the Famicom built-in **microphone** (read on `$4016` bit 2).
1994 ///
1995 /// The hardwired second Famicom controller carries a push-to-talk mic that
1996 /// games poll on `$4016.D2` (e.g. *Zelda*'s Pols Voice, *Kid Icarus*). Pass
1997 /// `pressed = true` while the frontend's mic key is held / an audio source
1998 /// crosses the loudness threshold. Additive and opt-in: `false` (the
1999 /// default) keeps the `$4016` read byte-identical to a stock NES.
2000 pub const fn set_microphone(&mut self, pressed: bool) {
2001 self.bus.set_microphone(pressed);
2002 }
2003
2004 /// Attach an NES Power Pad / Family Fun Fitness mat on `port` (typically
2005 /// port 1 / `$4017`) and set its live button mask (bit `i` = mat button
2006 /// `i+1`, 0..=11). Convenience wrapper that attaches the device if absent
2007 /// then updates it. Opt-in: the no-device path stays byte-identical.
2008 ///
2009 /// # Panics
2010 ///
2011 /// Panics if `port` is not in `0..=1`.
2012 pub fn set_power_pad(&mut self, port: usize, buttons: u16) {
2013 if !matches!(
2014 self.bus.expansion_device(port),
2015 Some(InputDevice::PowerPad(_))
2016 ) {
2017 self.bus.set_expansion_device(
2018 port,
2019 Some(InputDevice::PowerPad(
2020 crate::input_device::PowerPadState::new(),
2021 )),
2022 );
2023 }
2024 self.bus.set_power_pad(port, buttons);
2025 }
2026
2027 /// v1.6.0 B3 — the latched standard-controller button bitmask for `port`
2028 /// (`0` = P1 / `$4016`, `1` = P2 / `$4017`; `2`/`3` are the Four Score
2029 /// players), in [`Buttons`](crate::Buttons) bit order (A = bit 0 .. Right =
2030 /// bit 7). Read-only and side-effect-free — it reads the latched state, not
2031 /// the shift register, so it never perturbs a controller poll. Exposed for
2032 /// the Lua `joypad.get` query.
2033 ///
2034 /// # Panics
2035 ///
2036 /// Panics if `port` is not in `0..=3`.
2037 #[must_use]
2038 pub fn controller_buttons(&self, port: usize) -> u8 {
2039 assert!(port <= 3, "controller port {port} out of range (0..=3)");
2040 self.bus.controller(port).buttons().bits()
2041 }
2042
2043 /// v1.2.0 Workstream D — attach a SNES-style serial mouse on `port` (0 =
2044 /// `$4016`, 1 = `$4017`) and set its movement / buttons / sensitivity.
2045 /// `(dx, dy)` are the signed per-frame deltas (clamped to +/-127 on latch);
2046 /// `sensitivity` is 0 (low) / 1 (medium) / 2 (high). Convenience wrapper
2047 /// that attaches the device if absent then updates it. Opt-in: the no-device
2048 /// path stays byte-identical.
2049 ///
2050 /// # Panics
2051 ///
2052 /// Panics if `port` is not in `0..=1`.
2053 pub fn set_snes_mouse(
2054 &mut self,
2055 port: usize,
2056 dx: i16,
2057 dy: i16,
2058 left: bool,
2059 right: bool,
2060 sensitivity: u8,
2061 ) {
2062 if !matches!(
2063 self.bus.expansion_device(port),
2064 Some(InputDevice::SnesMouse(_))
2065 ) {
2066 self.bus.set_expansion_device(
2067 port,
2068 Some(InputDevice::SnesMouse(
2069 crate::input_device::SnesMouseState::new(),
2070 )),
2071 );
2072 }
2073 self.bus
2074 .set_snes_mouse(port, dx, dy, left, right, sensitivity);
2075 }
2076
2077 /// v1.2.0 Workstream D — attach a Famicom Family BASIC keyboard on `port`
2078 /// (typically port 1 / `$4017`) and set its pressed-key bitmap. `keys` is
2079 /// one byte per matrix row (`keys[row]` bits 0..=3 = column-half 0 keys,
2080 /// bits 4..=7 = column-half 1 keys); the frontend builds it from host keys.
2081 /// Convenience wrapper that attaches the device if absent then updates it.
2082 /// Opt-in: the no-device path stays byte-identical.
2083 ///
2084 /// # Panics
2085 ///
2086 /// Panics if `port` is not in `0..=1`.
2087 pub fn set_family_keyboard(&mut self, port: usize, keys: [u8; 9]) {
2088 if !matches!(
2089 self.bus.expansion_device(port),
2090 Some(InputDevice::FamilyKeyboard(_))
2091 ) {
2092 self.bus.set_expansion_device(
2093 port,
2094 Some(InputDevice::FamilyKeyboard(
2095 crate::input_device::FamilyKeyboardState::new(),
2096 )),
2097 );
2098 }
2099 self.bus.set_family_keyboard(port, keys);
2100 }
2101
2102 /// v1.3.0 Workstream F1 — attach a Bandai **Family Trainer** mat on `port`
2103 /// and set its 12-button mask (bit `i` = mat button `i+1`). The Family
2104 /// Trainer is layout-equivalent to the Power Pad and reuses its scan; this
2105 /// attaches the [`InputDevice::FamilyTrainer`] variant (distinct from
2106 /// [`Self::set_power_pad`] so the selected device round-trips through a
2107 /// save-state). Opt-in: the no-device path stays byte-identical.
2108 ///
2109 /// # Panics
2110 ///
2111 /// Panics if `port` is not in `0..=1`.
2112 pub fn set_family_trainer(&mut self, port: usize, buttons: u16) {
2113 if !matches!(
2114 self.bus.expansion_device(port),
2115 Some(InputDevice::FamilyTrainer(_))
2116 ) {
2117 self.bus.set_expansion_device(
2118 port,
2119 Some(InputDevice::FamilyTrainer(
2120 crate::input_device::PowerPadState::new(),
2121 )),
2122 );
2123 }
2124 self.bus.set_family_trainer(port, buttons);
2125 }
2126
2127 /// v1.3.0 Workstream F1 — attach a **Subor keyboard** on `port` and set its
2128 /// pressed-key bitmap (one byte per matrix row, like
2129 /// [`Self::set_family_keyboard`]). The Subor keyboard reuses the Family
2130 /// BASIC keyboard matrix scan; this attaches the
2131 /// [`InputDevice::SuborKeyboard`] variant. Opt-in: the no-device path stays
2132 /// byte-identical.
2133 ///
2134 /// # Panics
2135 ///
2136 /// Panics if `port` is not in `0..=1`.
2137 pub fn set_subor_keyboard(&mut self, port: usize, keys: [u8; 9]) {
2138 if !matches!(
2139 self.bus.expansion_device(port),
2140 Some(InputDevice::SuborKeyboard(_))
2141 ) {
2142 self.bus.set_expansion_device(
2143 port,
2144 Some(InputDevice::SuborKeyboard(
2145 crate::input_device::FamilyKeyboardState::new(),
2146 )),
2147 );
2148 }
2149 self.bus.set_subor_keyboard(port, keys);
2150 }
2151
2152 /// v1.3.0 Workstream F1 — attach a **Konami Hyper Shot** on `port` and set
2153 /// its 4-button mask (bit 0 = P1 Run, 1 = P1 Jump, 2 = P2 Run, 3 = P2 Jump).
2154 /// Opt-in: the no-device path stays byte-identical.
2155 ///
2156 /// # Panics
2157 ///
2158 /// Panics if `port` is not in `0..=1`.
2159 pub fn set_konami_hyper_shot(&mut self, port: usize, buttons: u8) {
2160 if !matches!(
2161 self.bus.expansion_device(port),
2162 Some(InputDevice::KonamiHyperShot(_))
2163 ) {
2164 self.bus.set_expansion_device(
2165 port,
2166 Some(InputDevice::KonamiHyperShot(
2167 crate::input_device::KonamiHyperShotState::new(),
2168 )),
2169 );
2170 }
2171 self.bus.set_konami_hyper_shot(port, buttons);
2172 }
2173
2174 /// v1.3.0 Workstream F1 — attach a **Bandai Hyper Shot** (Exciting Boxing
2175 /// punching bag) on `port` and set its 8-sensor mask (bits 0..=3 = the A=0
2176 /// group, bits 4..=7 = the A=1 group). Opt-in: the no-device path stays
2177 /// byte-identical.
2178 ///
2179 /// # Panics
2180 ///
2181 /// Panics if `port` is not in `0..=1`.
2182 pub fn set_bandai_hyper_shot(&mut self, port: usize, sensors: u8) {
2183 if !matches!(
2184 self.bus.expansion_device(port),
2185 Some(InputDevice::BandaiHyperShot(_))
2186 ) {
2187 self.bus.set_expansion_device(
2188 port,
2189 Some(InputDevice::BandaiHyperShot(
2190 crate::input_device::BandaiHyperShotState::new(),
2191 )),
2192 );
2193 }
2194 self.bus.set_bandai_hyper_shot(port, sensors);
2195 }
2196
2197 /// v1.1.0 beta.1 (T-110-B4) — set (`Some`) or clear (`None`) a per-game
2198 /// **nametable mirroring override**, a load-time correction for ROMs whose
2199 /// iNES header carries the wrong mirroring flag (supplied by the frontend's
2200 /// game database). `None` (default) defers to the mapper — byte-identical,
2201 /// so the determinism / `AccuracyCoin` contract and the core test suites are
2202 /// unaffected (they never set it). Persisted in the save-state. Does not
2203 /// affect mappers with on-cart VRAM (4-screen).
2204 pub const fn set_mirroring_override(&mut self, m: Option<rustynes_mappers::Mirroring>) {
2205 self.bus.set_mirroring_override(m);
2206 }
2207
2208 /// v2.9.8 — the per-game nametable mirroring override in effect (`None` =
2209 /// the mapper decides). See [`Self::set_mirroring_override`].
2210 #[must_use]
2211 pub const fn mirroring_override(&self) -> Option<rustynes_mappers::Mirroring> {
2212 self.bus.mirroring_override()
2213 }
2214
2215 /// Whether the loaded mapper's nametable mirroring is **hardwired** by the
2216 /// cartridge (solder pads / header bit) rather than controlled by the
2217 /// mapper's own registers at runtime.
2218 ///
2219 /// The frontend consults this before honoring a game-database mirroring
2220 /// correction: a static override is only valid for a hardwired board, and
2221 /// force-applying one to a mapper that switches mirroring itself (MMC1/3/5,
2222 /// `AxROM`, VRC, …) corrupts its rendering. See
2223 /// [`rustynes_mappers::Mapper::has_hardwired_mirroring`].
2224 #[must_use]
2225 pub fn mapper_has_hardwired_mirroring(&self) -> bool {
2226 self.bus.mapper_has_hardwired_mirroring()
2227 }
2228
2229 /// Write a byte directly into CPU work RAM (`$0000-$1FFF`). Used by the
2230 /// frontend's raw RAM cheats (GameShark-style); applied *after*
2231 /// [`Self::run_frame`], so the deterministic core run loop is unchanged
2232 /// (the determinism contract holds for the no-cheat path). No-op outside
2233 /// system RAM.
2234 pub fn poke_ram(&mut self, addr: u16, value: u8) {
2235 self.bus.poke_ram(addr, value);
2236 }
2237
2238 /// v1.7.0 "Forge" Workstream A1 — debugger writeback into the PPU bus
2239 /// (`$0000-$3FFF`): CHR pattern bytes (mapper `ppu_write`, a no-op on
2240 /// CHR-ROM), nametable tiles/attributes (mapper-absorbed, else CIRAM via the
2241 /// active mirroring), and palette RAM. The PPU-bus counterpart of
2242 /// [`Self::poke_ram`].
2243 ///
2244 /// Reached only through the frontend's gated post-frame poke path (the same
2245 /// caller-side, after-[`Self::run_frame`] stage the raw RAM cheats use), so
2246 /// the deterministic core run loop is unchanged and the no-edit path is
2247 /// byte-identical. `debug-hooks`-gated.
2248 #[cfg(feature = "debug-hooks")]
2249 pub fn debug_poke_ppu(&mut self, addr: u16, value: u8) {
2250 self.bus.debug_poke_ppu(addr, value);
2251 }
2252
2253 /// v1.7.0 "Forge" Workstream A1 — debugger writeback for one OAM byte
2254 /// (`idx` = 0..256: byte 0 = Y, 1 = tile, 2 = attributes, 3 = X per
2255 /// sprite). `debug-hooks`-gated; reached only through the gated post-frame
2256 /// poke path, so the default build is byte-identical.
2257 #[cfg(feature = "debug-hooks")]
2258 pub const fn poke_oam_byte(&mut self, idx: u8, value: u8) {
2259 self.bus.debug_poke_oam(idx, value);
2260 }
2261
2262 /// v3.7.0 — the length of one ROM section as the debugger can edit it
2263 /// (`None`: the board does not offer it). See [`crate::RomSpace`].
2264 #[cfg(feature = "debug-hooks")]
2265 pub fn debug_rom_len(&mut self, space: crate::RomSpace) -> Option<usize> {
2266 self.bus.debug_rom_len(space)
2267 }
2268
2269 /// v3.7.0 — one ROM byte by image offset, side-effect-free (`None`:
2270 /// unsupported section or past its end).
2271 #[cfg(feature = "debug-hooks")]
2272 pub fn debug_peek_rom(&mut self, space: crate::RomSpace, offset: usize) -> Option<u8> {
2273 self.bus.debug_peek_rom(space, offset)
2274 }
2275
2276 /// v3.7.0 (`T-HACK-BPS-RECORDER`) — write one PRG-ROM or CHR-ROM byte in
2277 /// place by image offset, visible to the next CPU fetch / PPU pattern
2278 /// fetch. The live ROM editor's write; reached only through the
2279 /// frontend's gated post-frame poke path. See
2280 /// `SystemBus::debug_poke_rom`.
2281 ///
2282 /// # Errors
2283 ///
2284 /// [`crate::RomWriteError`] when the board does not offer the section or
2285 /// the offset is past its end; nothing changes then.
2286 #[cfg(feature = "debug-hooks")]
2287 pub fn debug_poke_rom(
2288 &mut self,
2289 space: crate::RomSpace,
2290 offset: usize,
2291 value: u8,
2292 ) -> Result<(), crate::RomWriteError> {
2293 self.bus.debug_poke_rom(space, offset, value)
2294 }
2295
2296 /// v1.7.0 "Forge" Workstream B (Lua API parity) — debugger/scripted
2297 /// writeback of the CPU register file (`a`/`x`/`y`/`s`/`p` bits/`pc`). The
2298 /// structured-state counterpart of [`Self::poke_ram`], backing the Lua
2299 /// `emu:setState(t)` field map (Mesen2 parity).
2300 ///
2301 /// Reached only through the frontend / script crate's gated post-frame poke
2302 /// path (the same caller-side, after-[`Self::run_frame`] stage the raw RAM
2303 /// cheats + the other `debug_poke_*` writebacks use), so the deterministic
2304 /// core run loop is unchanged and the no-edit path is byte-identical.
2305 /// `debug-hooks`-gated. `p` is taken as a raw status-bits byte (truncated to
2306 /// the defined flags, mirroring a `PLP` / save-state restore).
2307 #[cfg(feature = "debug-hooks")]
2308 // This is a runtime register-file mutator (the structured-state counterpart
2309 // of `poke_ram`); `const` adds no value and would needlessly constrain the
2310 // body, so the `missing_const_for_fn` suggestion is declined here.
2311 #[allow(clippy::missing_const_for_fn)]
2312 pub fn debug_set_cpu_state(&mut self, a: u8, x: u8, y: u8, s: u8, p_bits: u8, pc: u16) {
2313 self.cpu.a = a;
2314 self.cpu.x = x;
2315 self.cpu.y = y;
2316 self.cpu.s = s;
2317 self.cpu.p = rustynes_cpu::Status::from_bits_truncate(p_bits);
2318 self.cpu.pc = pc;
2319 }
2320
2321 /// Read a byte from the CPU address space (`$0000-$FFFF`) for inspection,
2322 /// **without** the register side effects of a real CPU read — reading
2323 /// `$2002` does not clear the VBL flag / address latch and `$2007` does not
2324 /// advance the PPU read buffer. Used by the debugger and the Lua scripting
2325 /// API (`emu.read`); it observes state without advancing the emulator,
2326 /// preserving determinism.
2327 #[must_use]
2328 pub fn peek(&mut self, addr: u16) -> u8 {
2329 self.bus.debug_peek_cpu(addr)
2330 }
2331
2332 /// v1.2.0 C3 (hd-pack) — side-effect-free read of the PPU bus
2333 /// (`$0000-$3FFF`): CHR pattern data, nametables, palette RAM. Used by the
2334 /// HD-pack compositor to hash a tile's 16 CHR bytes. Observes state without
2335 /// advancing the emulator, preserving determinism.
2336 #[cfg(feature = "hd-pack")]
2337 #[must_use]
2338 pub fn peek_ppu(&mut self, addr: u16) -> u8 {
2339 self.bus.debug_peek_ppu(addr)
2340 }
2341
2342 /// Add a Game Genie code (6 or 8 characters, case-insensitive) that
2343 /// substitutes a byte the CPU reads from PRG-ROM (`$8000-$FFFF`).
2344 ///
2345 /// Codes are a runtime overlay — they are **not** part of the save-state
2346 /// and do not perturb the determinism contract when none are active. With
2347 /// codes active, the substituted bytes are part of the deterministic
2348 /// input (record a movie with the same codes to reproduce a run).
2349 ///
2350 /// # Errors
2351 ///
2352 /// Returns [`GenieError`] if the code string cannot be decoded.
2353 pub fn add_genie_code(&mut self, code: &str) -> Result<(), GenieError> {
2354 self.bus.add_genie_code(code)
2355 }
2356
2357 /// Remove the active Game Genie code whose canonical (upper-case) string
2358 /// matches `code`. No-op if no such code is active.
2359 pub fn remove_genie_code(&mut self, code: &str) {
2360 self.bus.remove_genie_code(code);
2361 }
2362
2363 /// Remove all active Game Genie codes.
2364 pub fn clear_genie_codes(&mut self) {
2365 self.bus.clear_genie_codes();
2366 }
2367
2368 /// Iterate the active Game Genie codes (address-sorted).
2369 pub fn genie_codes(&self) -> impl Iterator<Item = &GenieCode> {
2370 self.bus.genie_codes()
2371 }
2372
2373 /// Drain into a slice; returns the count copied. Samples that do not fit
2374 /// are KEPT for the next drain, so a caller discarding audio must loop
2375 /// until a drain returns less than `out.len()`. Until v3.5.0 this comment
2376 /// said the excess was dropped, which the buffer never did, and one
2377 /// caller (`rustynes-mcp`) trusted it.
2378 pub fn drain_audio_into(&mut self, out: &mut [f32]) -> usize {
2379 self.bus.drain_audio_into(out)
2380 }
2381
2382 /// The ROM's persistent identity: SHA-256 of an iNES / NES 2.0 image's
2383 /// bytes after its 16-byte header, or of the whole image for FDS and NSF.
2384 ///
2385 /// Everything that persists per game is keyed by it: save-state slot
2386 /// directories, the battery `.sav`, cheats, the `.rns` header's ROM tag
2387 /// ([`Self::rom_hash_tag`]), movies and netplay's ROM match. Computed once
2388 /// at construction; subsequent calls are O(1). A host that boots a saved
2389 /// copy of an FDS disk replaces it with the pristine disk's hash
2390 /// ([`Self::set_rom_identity`], v2.9.9), so a game's own disk saves never
2391 /// move its identity.
2392 ///
2393 /// **Why the header is excluded (v2.9.8).** Until v2.9.8 this hashed the
2394 /// whole image as constructed, which on the desktop is the image AFTER the
2395 /// game database corrected its header. Any change to those corrections
2396 /// therefore renamed a game's saves and invalidated its states, and v2.9.8
2397 /// alone changed them three times (the dirty-tail mapper nibble, the NES 2.0
2398 /// guard, the region promotion). The header is the one part of an image
2399 /// that load-time corrections rewrite; PRG and CHR never change, so an
2400 /// identity built from them survives every past and future correction, and
2401 /// two dumps of the same game with different headers share their saves.
2402 /// The maintainer accepted the one-time break this causes (2026-10-01).
2403 #[must_use]
2404 pub const fn rom_sha256(&self) -> &[u8; 32] {
2405 &self.rom_sha256
2406 }
2407
2408 /// The identity [`Self::rom_sha256`] reports for a console built from
2409 /// `image`, computed without building one: SHA-256 of the bytes after the
2410 /// 16-byte header of an iNES / NES 2.0 image, of the whole image otherwise
2411 /// (FDS, NSF, UNIF).
2412 ///
2413 /// For a host that keys stores before, or without, constructing a console
2414 /// -- a library import that must not need the FDS BIOS, or a key
2415 /// migration (v2.9.9 re-audit NF-21: the mobile hosts keyed saves by the
2416 /// whole file's hash). It is the same function every constructor uses, so
2417 /// the two cannot drift. It does not include a later
2418 /// [`Self::set_rom_identity`].
2419 #[must_use]
2420 pub fn rom_identity_of(image: &[u8]) -> [u8; 32] {
2421 rom_identity_sha256(image)
2422 }
2423
2424 /// SHA-256 of the complete image as constructed, header included.
2425 ///
2426 /// The Vs. System database ([`crate::vs_db`]) keeps a whole-file key on
2427 /// each row as a fallback to its identity key ([`Self::rom_sha256`]), so a
2428 /// row added from a dump that was never staged stays reachable;
2429 /// [`crate::vs_db::lookup`] consults both. Nothing else is keyed by it.
2430 /// Identical to [`Self::rom_sha256`] for FDS and NSF.
2431 #[must_use]
2432 pub const fn image_sha256(&self) -> &[u8; 32] {
2433 &self.image_sha256
2434 }
2435
2436 /// Replace this console's persistent identity ([`Self::rom_sha256`]) with
2437 /// `sha256`, for a host that boots a game from a SAVED copy of its image.
2438 ///
2439 /// The case it exists for is a Famicom Disk System disk. FDS games save by
2440 /// writing to the disk, so a host persists the written image
2441 /// ([`Self::disk_image_bytes`]) and boots from THAT file on the next
2442 /// launch, which is how a disk game's progress carries over. Every
2443 /// constructor hashes the bytes it is given, so from the game's first disk
2444 /// save on, an `Nes` booted that way reported the MODIFIED disk's hash, and
2445 /// everything keyed on [`Self::rom_sha256`] changed identity with it:
2446 /// save-state slots and the `.rns` ROM tag ([`Self::rom_hash_tag`]),
2447 /// cheats, movies and `TAStudio`, netplay's ROM match, the HD-pack and
2448 /// per-game keys, the RA progress sidecar (v2.9.9 re-audit NF-17). The
2449 /// host knows the pristine image's hash (it keys the saved disk with it),
2450 /// so it passes that here, right after construction, and the console then
2451 /// reports the identity of the game rather than of one of its saves.
2452 ///
2453 /// Only the identity moves. [`Self::image_sha256`] stays the hash of the
2454 /// bytes actually loaded: its one consumer is the Vs. System database's
2455 /// whole-file fallback, which must describe the image in hand (and a disk
2456 /// never matches it). Emulation is untouched: nothing in the chips reads
2457 /// the identity.
2458 ///
2459 /// A setter rather than a constructor variant because the identity is the
2460 /// one field the host has to supply, and each image kind already has two
2461 /// constructors (with and without a sample rate); a setter covers all of
2462 /// them, including a host that builds the console through `Emu`. It is the
2463 /// host's word: the core cannot check that `sha256` belongs to an earlier
2464 /// state of the loaded image. Call it before anything is keyed on the
2465 /// identity (a movie recorded before the call stamps the old one).
2466 pub const fn set_rom_identity(&mut self, sha256: [u8; 32]) {
2467 self.rom_sha256 = sha256;
2468 }
2469
2470 /// Truncated ROM hash tag stored in the save-state header.
2471 #[must_use]
2472 pub fn rom_hash_tag(&self) -> [u8; ROM_HASH_TAG_LEN] {
2473 let mut t = [0u8; ROM_HASH_TAG_LEN];
2474 t.copy_from_slice(&self.rom_sha256[..ROM_HASH_TAG_LEN]);
2475 t
2476 }
2477
2478 /// Encode the entire emulator state into a `.rns` snapshot blob.
2479 ///
2480 /// Includes a versioned container header and the four chip + bus
2481 /// sections (`CPU `, `PPU `, `APU `, `MAP `, `BUS `), plus an optional
2482 /// `THM ` thumbnail section (128x120 RGBA8 nearest-neighbor downsample
2483 /// of the current framebuffer). The thumbnail is for UI slot pickers
2484 /// only -- per ADR 0003 it is NOT part of the deterministic save-state
2485 /// contract.
2486 #[must_use]
2487 pub fn snapshot(&self) -> Vec<u8> {
2488 let tag = self.rom_hash_tag();
2489 // The bus knows how to emit BUS / PPU / APU / MAP sections; we
2490 // splice the CPU section in at the end.
2491 let mut out = self.bus.snapshot(tag);
2492 let cpu_body = self.cpu.snapshot();
2493 save_state::write_section(
2494 &mut out,
2495 save_state::tag::CPU,
2496 rustynes_cpu::CPU_SNAPSHOT_VERSION,
2497 &cpu_body,
2498 );
2499 // Optional thumbnail. Body layout: width(u16 le) + height(u16 le) +
2500 // length(u32 le) + raw RGBA8. The fixed THUMBNAIL_LEN is what we
2501 // emit but the body carries the dimensions explicitly so future
2502 // bumps (different thumbnail sizes) can be detected by the reader.
2503 let thumb = self.thumbnail();
2504 let mut body = Vec::with_capacity(2 + 2 + 4 + save_state::THUMBNAIL_LEN);
2505 body.extend_from_slice(
2506 &u16::try_from(save_state::THUMBNAIL_WIDTH)
2507 .unwrap()
2508 .to_le_bytes(),
2509 );
2510 body.extend_from_slice(
2511 &u16::try_from(save_state::THUMBNAIL_HEIGHT)
2512 .unwrap()
2513 .to_le_bytes(),
2514 );
2515 body.extend_from_slice(&u32::try_from(thumb.len()).unwrap().to_le_bytes());
2516 body.extend_from_slice(&thumb);
2517 save_state::write_section(
2518 &mut out,
2519 save_state::tag::THM,
2520 save_state::THUMBNAIL_VERSION,
2521 &body,
2522 );
2523 out
2524 }
2525
2526 /// v2.8.0 Phase 3 — [`Self::snapshot`] minus the `THM ` thumbnail
2527 /// section, encoded into a caller-owned reused buffer. The fast path
2528 /// for per-frame consumers (run-ahead, the netplay save-state ring):
2529 /// no allocation in steady state and no 61 KiB thumbnail build. The
2530 /// output parses with [`Self::restore`] / [`Self::restore_quiet`]
2531 /// exactly like a full snapshot (`THM ` is optional by format).
2532 pub fn snapshot_core_into(&self, out: &mut Vec<u8>) {
2533 let tag = self.rom_hash_tag();
2534 self.bus.snapshot_into(out, tag);
2535 let cpu_body = self.cpu.snapshot();
2536 save_state::write_section(
2537 out,
2538 save_state::tag::CPU,
2539 rustynes_cpu::CPU_SNAPSHOT_VERSION,
2540 &cpu_body,
2541 );
2542 }
2543
2544 /// v2.3.3 — [`Self::snapshot_core_into`] with the PPU encoded **slim**
2545 /// (no framebuffer), for the rewind ring.
2546 ///
2547 /// The ring snapshots on every frame inside the frame budget and then XORs
2548 /// and LZ4-compresses the result. The framebuffer is 245,760 of the ~250 KB
2549 /// and is the worst possible payload for that scheme, since it changes
2550 /// every frame: the XOR never zeroes and the delta never compresses.
2551 /// Measured, that made rewind roughly double the produce-interval p95 and
2552 /// it was the cause of a user-visible judder report — see
2553 /// `docs/performance.md` v2.3.3 F3/F4.
2554 ///
2555 /// A blob written here restores every field except the framebuffer, so the
2556 /// caller must regenerate the image; [`Self::rewind_step_back`] runs one
2557 /// frame to do exactly that.
2558 pub fn snapshot_core_into_slim(&self, out: &mut Vec<u8>) {
2559 let tag = self.rom_hash_tag();
2560 self.bus.snapshot_into_slim(out, tag);
2561 let cpu_body = self.cpu.snapshot();
2562 save_state::write_section(
2563 out,
2564 save_state::tag::CPU,
2565 rustynes_cpu::CPU_SNAPSHOT_VERSION,
2566 &cpu_body,
2567 );
2568 }
2569
2570 /// Generate a 128x120 RGBA8 thumbnail of the current framebuffer.
2571 ///
2572 /// Nearest-neighbor downsample (sample every 2nd pixel of every 2nd row).
2573 /// The 1/4-resolution result is small enough that storing it in slot
2574 /// files is cheap (61,440 bytes uncompressed, ~10-20 KiB after the
2575 /// LZ4 path the rewind ring uses if it is ever wired through there).
2576 ///
2577 /// Per ADR 0003: NOT part of the deterministic save-state contract.
2578 /// Different builds may produce different pixel-perfect framebuffers
2579 /// at the same cycle if post-pass filters change.
2580 #[must_use]
2581 pub fn thumbnail(&self) -> Vec<u8> {
2582 // Native NES framebuffer is 256x240 RGBA8 = 245,760 bytes. Source
2583 // stride is 256 * 4 = 1024 bytes.
2584 const SRC_W: usize = 256;
2585 let fb = self.bus.framebuffer();
2586 let mut out = Vec::with_capacity(save_state::THUMBNAIL_LEN);
2587 for ty in 0..save_state::THUMBNAIL_HEIGHT {
2588 let sy = ty * 2;
2589 for tx in 0..save_state::THUMBNAIL_WIDTH {
2590 let sx = tx * 2;
2591 let i = (sy * SRC_W + sx) * 4;
2592 // Source framebuffer is always at least 256*240*4 bytes
2593 // (allocated by Ppu::new), so this index is in-bounds.
2594 out.extend_from_slice(&fb[i..i + 4]);
2595 }
2596 }
2597 debug_assert_eq!(out.len(), save_state::THUMBNAIL_LEN);
2598 out
2599 }
2600
2601 /// Extract a thumbnail from an `.rns` save-state blob without restoring
2602 /// it. Used by frontends to populate slot pickers.
2603 ///
2604 /// Returns `Ok(None)` if the blob is well-formed but contains no
2605 /// thumbnail section (older v0.9.0 slot files).
2606 ///
2607 /// # Errors
2608 ///
2609 /// Returns [`SnapshotError`] when the container header is malformed.
2610 pub fn extract_thumbnail(data: &[u8]) -> Result<Option<Vec<u8>>, SnapshotError> {
2611 let (_h, body_off) = save_state::parse_header(data)?;
2612 for s in save_state::SectionIter::new(&data[body_off..]) {
2613 let s = s?;
2614 if s.tag == save_state::tag::THM {
2615 // Body: width(u16) + height(u16) + length(u32) + bytes.
2616 if s.body.len() < 8 {
2617 continue;
2618 }
2619 let w = u16::from_le_bytes([s.body[0], s.body[1]]) as usize;
2620 let h = u16::from_le_bytes([s.body[2], s.body[3]]) as usize;
2621 let n = u32::from_le_bytes([s.body[4], s.body[5], s.body[6], s.body[7]]) as usize;
2622 // Sanity: dimensions match what we currently emit, and the
2623 // declared length matches the body suffix.
2624 if w != save_state::THUMBNAIL_WIDTH
2625 || h != save_state::THUMBNAIL_HEIGHT
2626 || n != save_state::THUMBNAIL_LEN
2627 || s.body.len() < 8 + n
2628 {
2629 continue;
2630 }
2631 return Ok(Some(s.body[8..8 + n].to_vec()));
2632 }
2633 }
2634 Ok(None)
2635 }
2636
2637 /// Apply a previously [`Self::snapshot`]ed blob.
2638 ///
2639 /// Loading from a different ROM is allowed (the embedded hash tag is
2640 /// only a sanity check), but the result is undefined unless the chip
2641 /// section bodies are appropriate for the running mapper.
2642 ///
2643 /// The header's ROM hash tag is NOT compared with the running ROM, by
2644 /// decision (v2.9.0 re-audit NL-01): the paragraph above has always
2645 /// allowed a load from a different ROM. (The decision first rested on a
2646 /// second reason too, that the tag hashed the whole file including its
2647 /// iNES header, so a header-only correction of the same dump would have
2648 /// refused every state. Since v2.9.8 the tag is the leading bytes of
2649 /// [`Self::rom_sha256`], which leaves the header out, so that reason no
2650 /// longer applies; the first still does.) The section-level validation is what keeps a foreign state from
2651 /// crashing the core; see `docs/frontend.md` § "Save state files".
2652 ///
2653 /// # Errors
2654 ///
2655 /// Returns [`SnapshotError`] for malformed inputs; the machine is then
2656 /// unchanged.
2657 pub fn restore(&mut self, data: &[u8]) -> Result<(), SnapshotError> {
2658 self.restore_inner(data, true)
2659 }
2660
2661 /// Shared restore body; `clear_rewind` distinguishes user-driven loads
2662 /// ([`Self::restore`] — the ring is invalidated) from same-timeline
2663 /// machine restores ([`Self::restore_quiet`] — the ring stays).
2664 fn restore_inner(&mut self, data: &[u8], clear_rewind: bool) -> Result<(), SnapshotError> {
2665 // v2.4.0 item B — a timeline jump, but only when this is a LOUD restore.
2666 //
2667 // `clear_rewind` already draws exactly the distinction the counter needs,
2668 // so it is reused rather than duplicated: `true` means a user-driven load
2669 // that invalidates the rewind history, `false` means a same-timeline
2670 // machine-driven restore (run-ahead's per-frame rollback, netplay's
2671 // rollback-resimulate) where the history stays valid.
2672 //
2673 // A same-timeline restore must NOT bump. That is the same rule the
2674 // provenance stash follows from the other direction — every same-timeline
2675 // restore has to carry the state that lives outside the save state — and
2676 // getting it wrong here would clear a consumer's telemetry sixty times a
2677 // second under run-ahead, which is worse than the stale-telemetry defect
2678 // this counter exists to fix.
2679 //
2680 // Bumped BEFORE the restore can fail, deliberately. Before v2.7.4 a
2681 // failed restore could leave the machine partially applied, which is a
2682 // discontinuity whether or not it completed. A loud restore now rolls
2683 // back on failure (below), so a failed one leaves the timeline intact
2684 // and the bump costs a consumer one telemetry reset; keeping it
2685 // unconditional keeps this counter's rule simple.
2686 if clear_rewind {
2687 self.timeline_generation = self.timeline_generation.wrapping_add(1);
2688 }
2689 // v2.7.4 (frontend audit MOB-08) — a load is all-or-nothing. The stages
2690 // in `apply_snapshot` mutate as they go (the bus sections first, then
2691 // the CPU, then the clock check), so a blob rejected at a later stage
2692 // used to leave the earlier stages from the blob and the rest from the
2693 // running game: a machine that was neither, which the next frame
2694 // emulated. So the running machine is snapshotted first and put back
2695 // on failure.
2696 //
2697 // v2.9.0 (re-audit NC-03 / NL-01) — on BOTH paths. v2.7.4 skipped the
2698 // backup for quiet restores, on the stated premise that they "only ever
2699 // restore snapshots this core just wrote, which cannot fail these
2700 // checks". That premise was false: the libretro core routes EVERY
2701 // `retro_unserialize` through `restore_quiet` — a user's Load State, a
2702 // state written by an older core, a netplay peer's state, a truncated
2703 // or corrupt file — and the re-audit demonstrated a rejected CPU
2704 // section leaving the bus, PPU, APU and mapper from the rejected file
2705 // under the running game's CPU. The premise is also unenforceable: the
2706 // quiet/loud split is about the REWIND RING (same timeline or not), and
2707 // nothing about that choice says the bytes are trusted.
2708 //
2709 // The backup is the THM-less `snapshot_core_into` (the thumbnail is
2710 // ignored on restore) into a buffer pooled on the `Nes`, so the hot
2711 // path — run-ahead's and netplay's per-frame rollbacks — pays one
2712 // state copy and no allocation for the buffer in steady state. The
2713 // measured cost is recorded in `docs/frontend.md` § "Save state files".
2714 let mut backup = core::mem::take(&mut self.restore_backup);
2715 self.snapshot_core_into(&mut backup);
2716 let applied = self.apply_snapshot(data);
2717 if applied.is_err() {
2718 // Our own fresh snapshot always restores (the round-trip
2719 // invariant every save-state test pins); if it somehow did not,
2720 // the original error is still the one worth reporting. The core
2721 // has no logger (`no_std`), so the invariant is asserted in debug
2722 // and test builds rather than silently assumed.
2723 //
2724 // The invariant needs every value a running machine can hold to
2725 // pass the validators. v2.9.9's re-audit (NC-09) found one that
2726 // did not: a restored APU filter value accepted as merely finite
2727 // overflowed to NaN, after which this backup's own APU section was
2728 // refused part-way through the rollback. The validator now bounds
2729 // that state, so the backup is again a state the core produced.
2730 let rolled_back = self.apply_snapshot(&backup);
2731 debug_assert!(
2732 rolled_back.is_ok(),
2733 "rolling back to this core's own snapshot failed: {rolled_back:?}"
2734 );
2735 }
2736 self.restore_backup = backup;
2737 applied?;
2738 // Loading invalidates the rewind ring (the new state is unrelated
2739 // to what was buffered before).
2740 if clear_rewind && let Some(r) = &mut self.rewind {
2741 r.clear();
2742 }
2743 // v2.3.2 "Lucid" — and it invalidates write attribution for the same
2744 // reason, on BOTH restore paths. The restored bytes were not written by
2745 // any instruction this session executed, so the PCs recorded against
2746 // those offsets describe a timeline that no longer exists. Reporting
2747 // them would be a confidently wrong answer; reporting nothing until the
2748 // program writes again is the honest one.
2749 //
2750 // v2.3.6 CORRECTION. This comment used to end by claiming that under
2751 // run-ahead the clear "fires once per displayed frame, leaving exactly
2752 // the visible frame's writes — which is the timeline the user is looking
2753 // at". That was false about the two lines below it, which empty both
2754 // stores completely; and because run-ahead's rollback is the LAST thing
2755 // before the frontend releases the emulator lock, the wipe landed on the
2756 // visible frame's records before any UI could read them. The shipped
2757 // Pixel Provenance inspector therefore rendered an empty report for every
2758 // user with the default `run_ahead = 1`. The clear here is right and
2759 // stays; run-ahead now carries the stores AROUND it (`RunAhead::finish`
2760 // → `Nes::take_provenance` / `put_provenance`), which is what this
2761 // comment always claimed was happening.
2762 //
2763 // The per-pixel provenance frame is cleared for the same reason, and it
2764 // needs saying separately because the obvious analogy is wrong: the
2765 // framebuffer IS serialized and comes back consistent with the restored
2766 // state, while this frame is not. A restore landing mid-frame would
2767 // otherwise leave pre-restore tile and palette addresses for every pixel
2768 // above the current scanline, unmarked. (Review catch on PR #356.)
2769 #[cfg(feature = "debug-hooks")]
2770 {
2771 self.bus.ppu.clear_write_attribution();
2772 self.bus.ppu.clear_pixel_provenance();
2773 // v2.3.7 — the audio register attribution is the same kind of claim
2774 // about the same replaced timeline: a restored state's APU registers
2775 // were not written by any instruction this session executed, so
2776 // keeping their PCs would report a timeline that no longer exists.
2777 //
2778 // This was MISSING when audio provenance first landed, while
2779 // `docs/audio-provenance.md` already asserted that "save-state loads
2780 // and netplay rollback still clear" — prose describing behaviour the
2781 // code did not have, which is the exact failure that let Pixel
2782 // Provenance ship broken for four releases. Caught in review.
2783 //
2784 // Harmless for run-ahead: `RunAhead::finish` TAKES the store before
2785 // `restore_quiet` and puts it back after, so `audio_prov` is `None`
2786 // here and this call is a no-op on that path.
2787 self.bus.apu.clear_audio_provenance_history();
2788 }
2789 Ok(())
2790 }
2791
2792 /// The mutating stages of a restore: the bus sections, then the CPU
2793 /// section, then the cross-section clock check. Not atomic by itself; see
2794 /// the backup in [`Self::restore_inner`], which both public restore paths
2795 /// go through.
2796 fn apply_snapshot(&mut self, data: &[u8]) -> Result<(), SnapshotError> {
2797 // Restore bus first — it consumes BUS / PPU / APU / MAP sections.
2798 self.bus.restore(data)?;
2799 // Then walk the sections again to find the CPU body.
2800 let (_h, body_off) = save_state::parse_header(data)?;
2801 let mut saw_cpu = false;
2802 for s in save_state::SectionIter::new(&data[body_off..]) {
2803 let s = s?;
2804 if s.tag == save_state::tag::CPU {
2805 if s.version != rustynes_cpu::CPU_SNAPSHOT_VERSION {
2806 return Err(SnapshotError::VersionMismatch {
2807 tag: save_state::tag_string(s.tag),
2808 file_version: s.version,
2809 chip_supports: rustynes_cpu::CPU_SNAPSHOT_VERSION,
2810 });
2811 }
2812 self.cpu
2813 .restore(s.body)
2814 .map_err(|e| SnapshotError::SectionInvalid {
2815 tag: save_state::tag_string(s.tag),
2816 reason: format!("{e}"),
2817 })?;
2818 saw_cpu = true;
2819 }
2820 }
2821 if !saw_cpu {
2822 return Err(SnapshotError::MissingSection("CPU ".into()));
2823 }
2824 // v2.7.0 -- the one cross-section invariant: the CPU's master clock and
2825 // the bus's PPU clock must be close enough that the next catch-up
2826 // terminates (see `SystemBus::check_restored_clocks`).
2827 self.bus.check_restored_clocks(self.cpu.master_clock())?;
2828 Ok(())
2829 }
2830
2831 /// v2.8.0 Phase 3 — [`Self::restore`] WITHOUT clearing the rewind ring.
2832 ///
2833 /// For internal, machine-driven restores on the same timeline —
2834 /// run-ahead's per-frame rollback and netplay's rollback-resimulate —
2835 /// where the buffered rewind history remains exactly as valid as
2836 /// before. User-driven loads (save-state slots) keep using
2837 /// [`Self::restore`], which invalidates the ring.
2838 ///
2839 /// "Quiet" says nothing about whether the bytes are trusted: the libretro
2840 /// core routes every `retro_unserialize` here, including user state files.
2841 /// Since v2.9.0 a rejected blob therefore leaves the machine exactly as it
2842 /// was, on this path as on [`Self::restore`].
2843 ///
2844 /// # Errors
2845 ///
2846 /// Returns [`SnapshotError`] for malformed inputs; the machine is then
2847 /// unchanged.
2848 pub fn restore_quiet(&mut self, data: &[u8]) -> Result<(), SnapshotError> {
2849 self.restore_inner(data, false)
2850 }
2851
2852 /// Enable the rewind ring buffer with default capacity (32 MiB) and
2853 /// keyframe period (60).
2854 pub fn enable_rewind(&mut self) {
2855 self.enable_rewind_with(REWIND_DEFAULT_MAX_BYTES, REWIND_DEFAULT_KEYFRAME_PERIOD);
2856 }
2857
2858 /// Enable rewind with explicit byte budget + keyframe period.
2859 pub fn enable_rewind_with(&mut self, max_bytes: usize, keyframe_period: u32) {
2860 self.rewind = Some(RewindRing::new(max_bytes, keyframe_period));
2861 }
2862
2863 /// Disable rewind and free the buffer.
2864 pub fn disable_rewind(&mut self) {
2865 self.rewind = None;
2866 }
2867
2868 /// Enable the per-CPU-instruction boot trace fixture with the given
2869 /// [`CpuBootTrace`](crate::cpu_boot_trace::CpuBootTrace). Records past
2870 /// the trace's capacity are silently dropped (see
2871 /// [`CpuBootTrace::overflow`](crate::cpu_boot_trace::CpuBootTrace::overflow)).
2872 /// See `crates/rustynes-core/src/cpu_boot_trace.rs` for usage.
2873 #[cfg(feature = "cpu-boot-trace")]
2874 pub fn enable_cpu_boot_trace(&mut self, trace: crate::cpu_boot_trace::CpuBootTrace) {
2875 self.cpu_boot_trace = Some(trace);
2876 }
2877
2878 /// Take the accumulated CPU boot trace, leaving the slot empty.
2879 /// Returns `None` if tracing was never enabled.
2880 #[cfg(feature = "cpu-boot-trace")]
2881 #[must_use]
2882 pub const fn take_cpu_boot_trace(&mut self) -> Option<crate::cpu_boot_trace::CpuBootTrace> {
2883 self.cpu_boot_trace.take()
2884 }
2885
2886 /// Borrow the in-flight CPU boot trace for inspection.
2887 #[cfg(feature = "cpu-boot-trace")]
2888 #[must_use]
2889 pub const fn cpu_boot_trace(&self) -> Option<&crate::cpu_boot_trace::CpuBootTrace> {
2890 self.cpu_boot_trace.as_ref()
2891 }
2892
2893 /// Snapshot the current `(CPU register file + bus cycle + PPU
2894 /// position + opcode preview)` tuple into the CPU boot trace.
2895 ///
2896 /// Called from `run_frame` / `step_instruction` BEFORE the
2897 /// `Cpu::step` call. The opcode + 2 operand bytes are peeked
2898 /// side-effect-free via `SystemBus::debug_peek_cpu` so the
2899 /// trace is non-perturbing.
2900 ///
2901 /// No-op if the trace was never enabled.
2902 #[cfg(feature = "cpu-boot-trace")]
2903 fn cpu_boot_trace_record(&mut self) {
2904 use crate::cpu_boot_trace::CpuBootRecord;
2905 let Some(trace) = self.cpu_boot_trace.as_mut() else {
2906 return;
2907 };
2908 let cycle = self.bus.cycle();
2909 // Range pre-check: skip the peek bookkeeping entirely if this
2910 // cycle is outside the configured window. The trace's own
2911 // `maybe_push` re-checks; the pre-check is the hot-path
2912 // optimisation.
2913 if !trace.config().contains(cycle) {
2914 return;
2915 }
2916 let pc = self.cpu.pc;
2917 let opcode = self.bus.debug_peek_cpu(pc);
2918 let op1 = self.bus.debug_peek_cpu(pc.wrapping_add(1));
2919 let op2 = self.bus.debug_peek_cpu(pc.wrapping_add(2));
2920 let ppu = self.bus.ppu();
2921 let mut flags: u8 = 0;
2922 // Mesen2 exposes `cpu.nmiFlag` and `cpu.irqFlag` (its
2923 // own pending-interrupt latches) but not the
2924 // armed-vs-pending distinction; flag bit 0 means "PPU is
2925 // driving NMI line high" which is observable on both
2926 // sides at instruction-fetch boundary.
2927 if ppu.nmi_line() {
2928 flags |= 0x01;
2929 }
2930 let rec = CpuBootRecord {
2931 cycle,
2932 frame: u32::try_from(ppu.frame()).unwrap_or(u32::MAX),
2933 scanline: ppu.scanline(),
2934 dot: ppu.dot(),
2935 pc,
2936 a: self.cpu.a,
2937 x: self.cpu.x,
2938 y: self.cpu.y,
2939 p: self.cpu.p.bits(),
2940 s: self.cpu.s,
2941 opcode,
2942 op1,
2943 op2,
2944 flags,
2945 };
2946 trace.maybe_push(rec);
2947 }
2948
2949 /// Push the current state onto the rewind ring. Frontends call this
2950 /// at the end of each completed frame.
2951 ///
2952 /// No-op if rewind is disabled.
2953 pub fn rewind_capture(&mut self) {
2954 if self.rewind.is_none() {
2955 return;
2956 }
2957 let frame = self.bus.ppu().frame();
2958 // v2.8.0 Phase 3 — the core fast path: no THM thumbnail (the ring
2959 // is never shown in a slot picker) and a reused buffer instead of
2960 // a fresh ~320 KiB allocation per frame. The ring still LZ4s /
2961 // delta-encodes the bytes itself.
2962 let mut buf = core::mem::take(&mut self.rewind_snap_buf);
2963 // v2.3.3 — SLIM: omit the framebuffer. See `snapshot_core_into_slim`.
2964 self.snapshot_core_into_slim(&mut buf);
2965 if let Some(ring) = &mut self.rewind {
2966 ring.push(frame, &buf);
2967 }
2968 self.rewind_snap_buf = buf;
2969 }
2970
2971 /// Pop the most recent rewind entry and restore it. Returns `true` on
2972 /// success, `false` if the ring is empty (or rewind is disabled).
2973 pub fn rewind_step_back(&mut self) -> bool {
2974 let Some(ring) = self.rewind.as_mut() else {
2975 return false;
2976 };
2977 let Some(result) = ring.pop_back() else {
2978 return false;
2979 };
2980 let bytes = match result {
2981 Ok(b) => b,
2982 Err(_e) => return false,
2983 };
2984 // Restore but keep the ring alive (don't let `restore` clear it,
2985 // because the user is mid-rewind).
2986 let saved_ring = self.rewind.take();
2987 let r = self.restore(&bytes);
2988 // Reattach the (possibly cleared, but cleared-by-us is fine) ring.
2989 self.rewind = saved_ring;
2990 if r.is_err() {
2991 return false;
2992 }
2993 // v2.3.3 — ring entries are SLIM, so the restore above left the
2994 // framebuffer holding whatever was last displayed; without an image the
2995 // picture would freeze while the state rewound. Regenerate it WITHOUT
2996 // changing the state this call is contracted to land on:
2997 //
2998 // 1. state is at frame N (restored above), framebuffer stale
2999 // 2. run one frame -> renders exactly frame N's image, state N+1
3000 // 3. restore the same bytes -> state back to N
3001 //
3002 // Step 3 is what makes this exact rather than approximate, and it works
3003 // *because* the blob is slim: a slim restore does not touch the
3004 // framebuffer, so the image rendered in step 2 survives. The observable
3005 // contract is unchanged from before v2.3.3 — `cycle()` lands on the
3006 // snapshotted frame — which the `rewind_step_back_returns_prior_frames`
3007 // harness test pins.
3008 //
3009 // Capture is suppressed across step 2, or stepping back would push the
3010 // frame it just rendered and the ring would never drain.
3011 let saved_capture = self.rewind_capture_enabled;
3012 self.rewind_capture_enabled = false;
3013 self.run_frame();
3014 let saved_ring = self.rewind.take();
3015 let re = self.restore(&bytes);
3016 self.rewind = saved_ring;
3017 self.rewind_capture_enabled = saved_capture;
3018 re.is_ok()
3019 }
3020
3021 /// Drop every buffered rewind entry. Called when the user releases
3022 /// the rewind key, so subsequent forward play overwrites — there's
3023 /// nothing to overwrite, but we want forward play to capture into a
3024 /// fresh ring rather than tail-of-old-history.
3025 pub fn rewind_clear(&mut self) {
3026 if let Some(r) = &mut self.rewind {
3027 r.clear();
3028 }
3029 }
3030
3031 /// `true` if rewind is enabled.
3032 #[must_use]
3033 pub const fn rewind_enabled(&self) -> bool {
3034 self.rewind.is_some()
3035 }
3036
3037 /// Number of buffered rewind entries.
3038 #[must_use]
3039 pub fn rewind_len(&self) -> usize {
3040 self.rewind.as_ref().map_or(0, RewindRing::len)
3041 }
3042
3043 /// Approximate memory used by the rewind ring, in bytes.
3044 #[must_use]
3045 pub fn rewind_bytes_used(&self) -> usize {
3046 self.rewind.as_ref().map_or(0, RewindRing::bytes_used)
3047 }
3048
3049 // -------------------------------------------------------------------
3050 // Debugger inspection API (Sprint 5-3). All read-only — these methods
3051 // MUST NOT advance emulator-visible state.
3052 // -------------------------------------------------------------------
3053
3054 /// Snapshot the CPU register file.
3055 #[must_use]
3056 #[allow(clippy::missing_const_for_fn)] // `is_jammed` is const-callable but we're const-conservative.
3057 pub fn cpu_snapshot(&self) -> CpuDebugView {
3058 let c = &self.cpu;
3059 CpuDebugView {
3060 a: c.a,
3061 x: c.x,
3062 y: c.y,
3063 s: c.s,
3064 pc: c.pc,
3065 p: c.p.bits(),
3066 jammed: c.is_jammed(),
3067 cycles: c.cycles,
3068 }
3069 }
3070
3071 /// Snapshot PPU state for the debugger.
3072 #[must_use]
3073 #[allow(clippy::missing_const_for_fn)]
3074 pub fn ppu_snapshot(&self) -> PpuDebugView {
3075 let ppu = self.bus.ppu();
3076 let regs = ppu.debug_registers();
3077 let (v, t, fine_x, w) = ppu.debug_scroll();
3078 PpuDebugView {
3079 dot: ppu.dot(),
3080 scanline: ppu.scanline(),
3081 frame: ppu.frame(),
3082 ctrl: regs[0],
3083 mask: regs[1],
3084 status: regs[2],
3085 oam_addr: regs[3],
3086 v,
3087 t,
3088 fine_x,
3089 w_toggle: w,
3090 sprite_size_16: ppu.sprite_size_16(),
3091 bg_pattern_base: ppu.bg_pattern_base(),
3092 sprite_pattern_base: ppu.sprite_pattern_base(),
3093 nmi_line: ppu.nmi_line(),
3094 }
3095 }
3096
3097 /// Snapshot APU channel outputs and IRQ flags.
3098 #[must_use]
3099 pub fn apu_snapshot(&self) -> ApuDebugView {
3100 let apu = self.bus.apu();
3101 ApuDebugView {
3102 pulse1: apu.pulse1_out(),
3103 pulse2: apu.pulse2_out(),
3104 triangle: apu.triangle_out(),
3105 noise: apu.noise_out(),
3106 dmc: apu.dmc_out(),
3107 external: apu.external_out(),
3108 frame_irq: apu.frame_irq_pending(),
3109 dmc_irq: apu.dmc_irq_pending(),
3110 }
3111 }
3112
3113 /// Set the APU per-channel enable mask (a UI playback overlay, NOT NES
3114 /// hardware state). Bit 0 = pulse 1, 1 = pulse 2, 2 = triangle, 3 = noise,
3115 /// 4 = DMC, 5 = external/mapper audio. A cleared bit mutes that channel.
3116 ///
3117 /// The default ([`rustynes_apu::CHANNEL_MASK_ALL`]) is byte-identical to
3118 /// the un-masked mixer — the deterministic per-frame audio is unchanged
3119 /// unless the frontend explicitly mutes a channel. This is never written
3120 /// into the save state, so it never affects determinism or round-trips.
3121 pub const fn set_apu_channel_mask(&mut self, mask: u8) {
3122 self.bus.apu_mut().set_channel_mask(mask);
3123 }
3124
3125 /// Current APU per-channel enable mask. See [`Self::set_apu_channel_mask`].
3126 #[must_use]
3127 pub const fn apu_channel_mask(&self) -> u8 {
3128 self.bus.apu().channel_mask()
3129 }
3130
3131 /// v1.4.0 Workstream C — set the APU per-channel output gain (a UI mixing
3132 /// overlay, NOT NES hardware state), generalizing [`Self::set_apu_channel_mask`].
3133 /// Index 0 = pulse 1, 1 = pulse 2, 2 = triangle, 3 = noise, 4 = DMC,
3134 /// 5 = external/mapper audio. Each gain is clamped to `0.0..=2.0`.
3135 ///
3136 /// The default ([`rustynes_apu::CHANNEL_GAIN_UNITY`], all `1.0`) is
3137 /// byte-identical to the un-scaled mixer — the deterministic per-frame audio
3138 /// is unchanged unless the frontend explicitly changes a gain. Never written
3139 /// into the save state, so it never affects determinism or round-trips.
3140 pub fn set_apu_channel_gain(&mut self, gain: [f32; 6]) {
3141 self.bus.apu_mut().set_channel_gain(gain);
3142 }
3143
3144 /// v2.1.3 — select the APU analog output-filter model (see
3145 /// [`rustynes_apu::FilterModel`]). The default
3146 /// [`rustynes_apu::FilterModel::NesRf`] (NES front-loader: 90 + 440 Hz HPF +
3147 /// 14 kHz LPF) is byte-identical to the pre-v2.1.3 output; `Famicom` (37 Hz
3148 /// HPF) and `Clean` (~10 Hz DC-block) drop the aggressive 440 Hz high-pass
3149 /// for a fuller low end. Tonal only — channel content is unchanged, and the
3150 /// model is never written into the save state (a frontend/config concern,
3151 /// re-applied at load), so determinism and round-trips are unaffected.
3152 pub fn set_apu_filter_model(&mut self, model: rustynes_apu::FilterModel) {
3153 self.bus.apu_mut().set_filter_model(model);
3154 }
3155
3156 /// v2.9.8 — the APU analog output-filter model last selected with
3157 /// [`Self::set_apu_filter_model`] (the default until one is). Survives a
3158 /// [`Self::power_cycle`].
3159 #[must_use]
3160 pub const fn apu_filter_model(&self) -> rustynes_apu::FilterModel {
3161 self.bus.apu().filter_model()
3162 }
3163
3164 /// Current APU per-channel output gain. See [`Self::set_apu_channel_gain`].
3165 #[must_use]
3166 pub const fn apu_channel_gain(&self) -> [f32; 6] {
3167 self.bus.apu().channel_gain()
3168 }
3169
3170 /// Borrow OAM (256 bytes = 64 sprites x 4 bytes).
3171 ///
3172 /// Returns a cloned `[u8; 256]` so the caller doesn't have to manage
3173 /// a borrow lifetime against `&self`.
3174 #[must_use]
3175 pub fn oam(&self) -> [u8; 256] {
3176 let mut out = [0u8; 256];
3177 let oam = self.bus.ppu().oam();
3178 out.copy_from_slice(&oam[..256]);
3179 out
3180 }
3181
3182 /// One OAM byte (`index` = `0..=255`), without copying the whole 256-byte
3183 /// array — for single-byte readers (e.g. the Lua `memory:read_oam`) that
3184 /// would otherwise pay a full `oam()` copy per access. Read-only.
3185 #[must_use]
3186 pub fn oam_byte(&self, index: u8) -> u8 {
3187 self.bus.ppu().oam()[index as usize]
3188 }
3189
3190 /// Borrow palette RAM (32 bytes).
3191 #[must_use]
3192 pub const fn palette_ram(&self) -> [u8; 32] {
3193 *self.bus.ppu().palette_ram()
3194 }
3195
3196 /// v1.1.0 beta.1 — install (`Some`) or clear (`None`) a custom 64-entry base
3197 /// palette loaded from a `.pal` file. A frontend presentation override: it
3198 /// re-tints the displayed RGBA framebuffer via the PPU's colour LUT but does
3199 /// not touch any logical core state. `None` (the default) is byte-identical to
3200 /// the built-in palette, so `AccuracyCoin` + the commercial oracle (which never
3201 /// set one) are unaffected. Not part of the save-state.
3202 pub const fn set_custom_palette(&mut self, base: Option<[[u8; 3]; 64]>) {
3203 self.bus.set_custom_palette(base);
3204 }
3205
3206 /// v2.9.8 — the custom base palette installed by
3207 /// [`Self::set_custom_palette`], or `None` for the built-in one. Survives a
3208 /// [`Self::power_cycle`].
3209 #[must_use]
3210 pub const fn custom_palette(&self) -> Option<[[u8; 3]; 64]> {
3211 self.bus.ppu().custom_palette()
3212 }
3213
3214 /// v1.7.0 "Forge" Workstream F3 — set the PPU extra-scanlines overclock: the
3215 /// number of EXTRA idle vblank scanlines the PPU inserts per frame (at the
3216 /// existing dot resolution, Mesen2 `UpdateTimings`). Each extra line is pure
3217 /// additional CPU run-time — it renders nothing, sets/clears no PPU flag, and
3218 /// fires no VBL/NMI/A12 event, so the visible image is unchanged. `0` (the
3219 /// default) is **byte-identical** to stock NES timing — `AccuracyCoin`, the
3220 /// commercial oracle, and nestest (which never set it) are unaffected.
3221 /// **Off by default**; a frontend config knob, not part of the save-state.
3222 /// Distinct from the CPU-multiplier overclock ([`Self::set_cpu_overclock`],
3223 /// v3.1.0), which shortens the CPU cycle instead of lengthening the frame.
3224 ///
3225 /// Clamped to [`MAX_EXTRA_SCANLINES`] (v2.9.9, NC-11): the cap used to
3226 /// live only in the desktop frontend, so a movie's options record could
3227 /// set 65,535 lines and leave every `run_frame` ending on its cycle
3228 /// budget with no frame.
3229 pub const fn set_extra_scanlines(&mut self, lines: u16) {
3230 let lines = if lines > MAX_EXTRA_SCANLINES {
3231 MAX_EXTRA_SCANLINES
3232 } else {
3233 lines
3234 };
3235 self.bus.set_extra_scanlines(lines);
3236 }
3237
3238 /// v3.1.0 (`T-CPU-OVERCLOCK`, FE-01) — set the CPU-multiplier overclock:
3239 /// the CPU runs `k` times faster against an unchanged PPU, so a game gets
3240 /// `k` times the CPU time per frame.
3241 ///
3242 /// It splits the region's master-clock CPU divider into `k` cycles whose
3243 /// lengths sum to exactly one stock cycle (NTSC 12 -> 6 / 4 / 3; PAL 16 at
3244 /// `x3` is 5, 5, 6 and Dendy 15 at `x4` is 3, 4, 4, 4), so the multiplier is
3245 /// exact on every region. Until the v3.1.0 review it divided with integer
3246 /// division, which made PAL `x3` run x3.2 and Dendy `x4` x5. The APU, the
3247 /// DMC, every mapper's CPU-cycle hook (the VRC / FME-7 / N163 IRQ
3248 /// counters) and the PPU's open-bus and post-reset timers stay at the
3249 /// STOCK rate, so the pitch, the music tempo and the cycle-timed raster
3250 /// IRQs are unchanged: what speeds up is the game's own code. DMA follows
3251 /// the APU's get/put phase, so a DMA takes about `k` times as many CPU
3252 /// cycles and the same real time.
3253 ///
3254 /// `1` (the default) is stock and byte-identical to a build without the
3255 /// option. `0` is treated as `1`, and values above [`MAX_CPU_OVERCLOCK`]
3256 /// clamp to it. Configuration, not save-state: the host re-applies it,
3257 /// and movies and netplay carry it in [`crate::HardwareOptions`]. Not
3258 /// hardware behaviour: no real console runs its CPU faster than its APU.
3259 pub const fn set_cpu_overclock(&mut self, k: u8) {
3260 let k = if k == 0 {
3261 1
3262 } else if k > MAX_CPU_OVERCLOCK {
3263 MAX_CPU_OVERCLOCK
3264 } else {
3265 k
3266 };
3267 self.bus.set_cpu_overclock(k);
3268 }
3269
3270 /// v3.1.0 — the CPU-multiplier overclock (`1` = stock).
3271 #[must_use]
3272 pub const fn cpu_overclock(&self) -> u8 {
3273 self.bus.cpu_overclock()
3274 }
3275
3276 /// v3.1.0 (`T-SPRITE-LIMIT`, FE-02) — draw the sprites beyond the eighth
3277 /// on a scanline, removing sprite flicker.
3278 ///
3279 /// **Render-only.** Sprite evaluation, secondary OAM, the overflow flag,
3280 /// sprite-0 hit and every real sprite fetch (with its A12 edges, which an
3281 /// MMC3 counts) are exactly stock, so the game sees no difference; only
3282 /// the picture does. The extra sprites draw behind all eight hardware ones.
3283 /// On the boards whose CHR reads have an effect (MMC2, MMC4, the J.Y.
3284 /// ASIC, Bandai 96, Nanjing 163; `Mapper::chr_reads_are_pure`) the option
3285 /// draws eight, as stock, because the extra pattern reads would change
3286 /// emulation there.
3287 ///
3288 /// Off by default. Configuration, not save-state; carried across a power
3289 /// cycle, and in movies and netplay by [`crate::HardwareOptions`] (the
3290 /// picture differs, so a movie's frame hashes and a netplay peer's desync
3291 /// checks depend on it).
3292 pub const fn set_sprite_limit_disabled(&mut self, disabled: bool) {
3293 self.bus.set_sprite_limit_disabled(disabled);
3294 }
3295
3296 /// v3.1.0 — whether the sprites beyond the eighth are drawn.
3297 #[must_use]
3298 pub const fn sprite_limit_disabled(&self) -> bool {
3299 self.bus.sprite_limit_disabled()
3300 }
3301
3302 /// v3.6.2 (`T-RADRACER-COHERENT-COPY`) — the per-game coherent mid-line
3303 /// copy correction: a delayed `$2006` copy that would land inside a
3304 /// background fetch group is held to the next group boundary, so no tile
3305 /// is fetched from two addresses.
3306 ///
3307 /// **A deliberate departure from hardware.** A real NES draws the split
3308 /// tile; *Rad Racer* shows it as an 8-pixel wrong tile right of the road
3309 /// and at the horizon on about one frame in eleven. On by default for the
3310 /// dumps [`crate::game_corrections::COHERENT_MIDLINE_COPY_DUMPS`] lists,
3311 /// off for everything else; a host may turn it off to see the hardware's
3312 /// picture. Configuration, not save-state; carried across a power cycle,
3313 /// and in movies and netplay by [`crate::HardwareOptions`] (the picture
3314 /// differs, so frame hashes and desync checks depend on it).
3315 pub const fn set_coherent_midline_copy(&mut self, on: bool) {
3316 self.bus.set_coherent_midline_copy(on);
3317 }
3318
3319 /// v3.6.2 — whether the coherent mid-line copy correction is on.
3320 #[must_use]
3321 pub const fn coherent_midline_copy(&self) -> bool {
3322 self.bus.coherent_midline_copy()
3323 }
3324
3325 /// v3.1.0 (`T-MMC3-NEC-OVERRIDE`, ACC-13) — run an MMC3 (mapper 4) under
3326 /// a chosen IRQ revision, or `None` for the one its header selects.
3327 ///
3328 /// The MMC3's two IRQ behaviours are mutually exclusive: the Sharp MMC3B
3329 /// / MMC3C (the default) asserts IRQ whenever a clock leaves the counter at
3330 /// 0 with IRQs enabled, so a latch of 0 fires every scanline. The MMC3A
3331 /// and non-Sharp MMC3B (`Mmc3Revision::Nec`) assert on a 1 -> 0 decrement
3332 /// and on a `$C001` reload to 0 (one IRQ per `$C001` write while `$C000`
3333 /// is 0, even if the counter was already 0), but not when the counter,
3334 /// already 0, reloads 0 by itself. A NES 2.0 header can say which (submapper 4); an iNES 1.0
3335 /// dump cannot, so this override is how a player runs a game, or blargg's
3336 /// `mmc3_test_2/6-MMC3_alt`, on the other chip. The default (`None`) is
3337 /// unchanged. Configuration, re-applied when a power cycle rebuilds the
3338 /// board, and carried in [`crate::HardwareOptions`]. Returns whether the
3339 /// board is one that applies it.
3340 pub fn set_mmc3_revision_override(
3341 &mut self,
3342 revision: Option<rustynes_mappers::Mmc3Revision>,
3343 ) -> bool {
3344 self.bus.set_mmc3_revision_override(revision)
3345 }
3346
3347 /// v3.1.0 — the forced MMC3 IRQ revision (`None` = the header's).
3348 #[must_use]
3349 pub const fn mmc3_revision_override(&self) -> Option<rustynes_mappers::Mmc3Revision> {
3350 self.bus.mmc3_revision_override()
3351 }
3352
3353 /// v1.7.0 F3 — the configured extra-scanline overclock count (`0` = stock).
3354 #[must_use]
3355 pub const fn extra_scanlines(&self) -> u16 {
3356 self.bus.extra_scanlines()
3357 }
3358
3359 /// v2.1.8 A1 — enable or disable the specialized visible-scanline fast dot
3360 /// path (a pure performance optimization for the PPU's hottest per-dot
3361 /// case).
3362 ///
3363 /// The PPU dot FSM (`Ppu::tick`) is the emulator's single hottest function
3364 /// (~46% of a representative frame's self-time). This knob dispatches the
3365 /// common "clean" visible BG-render dots (visible scanline, dots `1..=256`,
3366 /// rendering stably enabled, no sub-dot disturbance) to a straight-line
3367 /// handler that runs the identical helper sequence with the statically-dead
3368 /// event branches pruned. **On by default since v2.2.3** (OFF through
3369 /// v2.2.2) and **byte-identical** to the exact path — proven bit-for-bit
3370 /// every frame by the differential test (`fast_dotloop_diff`) and the full
3371 /// `AccuracyCoin` / visual-regression / nestest oracle, and measured at
3372 /// **-11.3%** on the rendering-heavy `full_frame` bench. Setting it `false`
3373 /// selects the fully-general per-dot path and remains the fallback. A
3374 /// frontend/config knob, NOT part of the save-state.
3375 pub const fn set_fast_dotloop(&mut self, enabled: bool) {
3376 self.bus.set_fast_dotloop(enabled);
3377 }
3378
3379 /// v2.1.8 A1 — whether the visible-scanline fast dot path is enabled
3380 /// (`true` = default since v2.2.3; both settings produce identical frames).
3381 #[must_use]
3382 pub const fn fast_dotloop(&self) -> bool {
3383 self.bus.fast_dotloop()
3384 }
3385
3386 /// v2.1.4 F2.3 — enable or disable the optional OAM-decay accuracy model.
3387 ///
3388 /// The 2C02's OAM is dynamic RAM refreshed by sprite evaluation; with rendering
3389 /// disabled for a while its un-refreshed 8-byte rows decay to a fixed garbage
3390 /// pattern. This models that (à la Mesen2's `EnableOamDecay`): a row un-touched
3391 /// for > 3000 CPU cycles decays on the next read. **Off by default** and
3392 /// **byte-identical** to a decay-free core when off — `AccuracyCoin`, the
3393 /// commercial oracle, and the visual regression suites are unaffected. It is
3394 /// NTSC/Dendy-only (PAL's refresh cadence masks decay). Deterministic when on
3395 /// (driven off the PPU's monotonic dot counter — no wall-clock / OS RNG), and a
3396 /// frontend/config knob re-applied on load, NOT part of the save-state (the
3397 /// in-flight per-row ages are serialized as a relative age so a rollback stays
3398 /// deterministic; the enable flag is not).
3399 pub const fn set_oam_decay(&mut self, enabled: bool) {
3400 self.bus.set_oam_decay(enabled);
3401 }
3402
3403 /// v2.1.4 F2.3 — whether the optional OAM-decay model is enabled (`false` =
3404 /// default, byte-identical to a decay-free core).
3405 #[must_use]
3406 pub const fn oam_decay_enabled(&self) -> bool {
3407 self.bus.oam_decay_enabled()
3408 }
3409
3410 /// v2.1.7 P5 — select the emulated 2C02 die revision (see [`PpuRevision`]).
3411 ///
3412 /// The [`PpuRevision::default`] ([`PpuRevision::Rp2c02H`]) models no extra
3413 /// quirks, so at the default this is inert and the core is **byte-identical**
3414 /// to a build without it — `AccuracyCoin`, the commercial oracle, and the
3415 /// visual / audio regression suites are unaffected. Selecting
3416 /// [`PpuRevision::Rp2c02G`] additionally models the OAMADDR (`$2003`)
3417 /// write-during-rendering OAM corruption glitch (*Huge Insect*). The
3418 /// selection is stored so a power-cycle re-applies it; it is config, not
3419 /// save-state (the corruption *state* it can arm already round-trips via the
3420 /// v6 PPU snapshot tail). Deterministic. A frontend/config knob re-applied on
3421 /// load, mirroring [`Nes::set_oam_decay`].
3422 pub const fn set_ppu_revision(&mut self, revision: PpuRevision) {
3423 self.bus.set_ppu_revision(revision);
3424 }
3425
3426 /// v2.1.7 P5 — the currently-selected 2C02 die revision (default
3427 /// [`PpuRevision::Rp2c02H`], byte-identical).
3428 #[must_use]
3429 pub const fn ppu_revision(&self) -> PpuRevision {
3430 self.bus.ppu_revision()
3431 }
3432
3433 /// v2.9.8 — select the console whose reset wiring is modelled (see
3434 /// [`ConsoleModel`]).
3435 ///
3436 /// The selection is stored, so every later [`Nes::power_cycle`] and
3437 /// [`Nes::reset`] follows it. It also takes effect at once in one respect:
3438 /// selecting [`ConsoleModel::Famicom`] ends any PPU warm-up still in
3439 /// progress, because a Famicom's PPU is never held in reset while its CPU
3440 /// runs. A host that applies its configuration straight after building the
3441 /// machine (as the frontend does on every ROM load and power-cycle) thereby
3442 /// gets the Famicom power-on. Selecting [`ConsoleModel::Nes`] never re-arms
3443 /// a window that has already closed; it applies from the next reset.
3444 ///
3445 /// [`ConsoleModel::Nes`] is the default and is byte-identical to every
3446 /// earlier release. Deterministic; config, not save-state.
3447 pub const fn set_console_model(&mut self, model: ConsoleModel) {
3448 self.bus.set_console_model(model);
3449 }
3450
3451 /// v2.9.8 — the currently-selected console reset wiring (default
3452 /// [`ConsoleModel::Nes`], byte-identical).
3453 #[must_use]
3454 pub const fn console_model(&self) -> ConsoleModel {
3455 self.bus.console_model()
3456 }
3457
3458 /// v2.1.7 P5 — apply a power-up palette-RAM pattern (see [`PaletteInit`]).
3459 ///
3460 /// The 2C02's palette RAM is not cleared at power-on; this selects the
3461 /// power-up contents. [`PaletteInit::default`] ([`PaletteInit::Zeroed`])
3462 /// keeps the established all-zero power-up palette, so at the default this is
3463 /// **byte-identical**. [`PaletteInit::Blargg`] loads the canonical blargg
3464 /// power-up dump for software that samples uninitialized palette RAM. Writes
3465 /// only palette RAM (already part of the snapshot), so no snapshot change is
3466 /// needed; the selection is stored so a power-cycle re-applies it. Best
3467 /// called at power-on (palette RAM is preserved across a warm reset, like
3468 /// real hardware).
3469 pub const fn set_power_up_palette(&mut self, init: PaletteInit) {
3470 self.bus.set_power_up_palette(init);
3471 }
3472
3473 /// v2.1.7 P5 — the currently-selected power-up palette pattern (default
3474 /// [`PaletteInit::Zeroed`], byte-identical).
3475 #[must_use]
3476 pub const fn power_up_palette(&self) -> PaletteInit {
3477 self.bus.power_up_palette()
3478 }
3479
3480 /// v2.1.7 P5 — select the power-on work-RAM fill (see [`PowerOnRam`]).
3481 ///
3482 /// Applies the fill to the current 2 KiB work RAM (and open-bus latch)
3483 /// immediately and stores it so a power-cycle re-applies the same fill
3484 /// (`power_cycle == fresh boot`). [`PowerOnRam::default`]
3485 /// ([`PowerOnRam::Zeroed`]) is the established all-zero power-up state
3486 /// (**byte-identical**); the other variants are opt-in and deterministic,
3487 /// surfacing software that reads uninitialized RAM (*Final Fantasy* RNG,
3488 /// *River City Ransom*, *Cybernoid*). RAM is not consulted during reset, so
3489 /// applying it here is safe.
3490 pub fn set_power_on_ram(&mut self, ram: PowerOnRam) {
3491 self.bus.set_power_on_ram(ram);
3492 }
3493
3494 /// v2.1.7 P5 — the currently-selected power-on work-RAM fill (default
3495 /// [`PowerOnRam::Zeroed`], byte-identical).
3496 #[must_use]
3497 pub const fn power_on_ram(&self) -> PowerOnRam {
3498 self.bus.power_on_ram()
3499 }
3500
3501 /// v2.1.7 "Hardware Revisions & DMA Frontier" — select the emulated Ricoh
3502 /// 2A03 die revision, which gates the DMA unit's "unexpected DMA" extra
3503 /// halt-read on the DMC-halt-overlaps-OAM-halt cycle.
3504 ///
3505 /// **[`Cpu2A03Revision::Rp2A03G`] is the default** and is byte-identical to
3506 /// the core as it shipped before v2.1.7 (`AccuracyCoin` 141/141, nestest
3507 /// 0-diff, every committed DMA oracle ROM `Passed`).
3508 /// [`Cpu2A03Revision::Rp2A03H`] is a purely additive, opt-in accuracy knob
3509 /// that omits the extra read; its direction is an **unverified hypothesis**
3510 /// (no public reference emulator or test ROM models the 2A03 die-revision
3511 /// DMA difference — see the type docs and ADR 0033). It is deterministic and
3512 /// a config knob re-applied on load, NOT part of the save-state.
3513 pub const fn set_cpu_2a03_revision(&mut self, revision: Cpu2A03Revision) {
3514 self.bus.set_cpu_2a03_revision(revision);
3515 }
3516
3517 /// v2.1.7 — the configured 2A03 die revision (default
3518 /// [`Cpu2A03Revision::Rp2A03G`], byte-identical to the pre-v2.1.7 core).
3519 #[must_use]
3520 pub const fn cpu_2a03_revision(&self) -> Cpu2A03Revision {
3521 self.bus.cpu_2a03_revision()
3522 }
3523
3524 /// Mapper debug info (bank registers, IRQ counters, mirroring, ...).
3525 #[must_use]
3526 pub fn mapper_info(&self) -> MapperDebugView {
3527 self.bus.mapper_debug_info()
3528 }
3529
3530 /// v1.4.0 Workstream C — the loaded mapper's on-cart expansion-audio chip
3531 /// name (e.g. `"VRC6"`, `"VRC7 (OPLL)"`, `"MMC5"`, `"Namco 163"`,
3532 /// `"Sunsoft 5B"`, `"FDS"`), or `None` when the board has no expansion audio
3533 /// (or the `mapper-audio` feature is compiled out). Used by the frontend to
3534 /// show the expansion-channel volume slider only when present, with a label.
3535 ///
3536 /// Discovery is dynamic: it consults the cached [`rustynes_mappers::MapperCaps`]
3537 /// `audio` flag (true only when the mapper overrides `mix_audio` with the
3538 /// feature on) and the mapper id to name the chip family.
3539 #[must_use]
3540 pub const fn expansion_audio_chip(&self) -> Option<&'static str> {
3541 if !self.bus.mapper_caps().audio {
3542 return None;
3543 }
3544 // The cartridge's id, not the debug view's (v2.9.8, see `mapper_id`).
3545 // Every board that overrides `mix_audio` also names its id in
3546 // `debug_info` today, so no label changes; the debug view simply is
3547 // not the place the mapper id is defined.
3548 Some(match self.mapper_id() {
3549 5 => "MMC5",
3550 19 | 210 => "Namco 163",
3551 20 => "FDS",
3552 24 | 26 => "VRC6",
3553 69 => "Sunsoft 5B",
3554 85 => "VRC7 (OPLL)",
3555 // The board overrides `mix_audio` but isn't one of the named
3556 // families above — surface a generic label so the slider still
3557 // appears (e.g. a future expansion-audio mapper).
3558 _ => "Expansion audio",
3559 })
3560 }
3561
3562 /// Side-effect-free CPU bus peek (for the hex viewer).
3563 pub fn cpu_bus_peek(&mut self, addr: u16) -> u8 {
3564 self.bus.debug_peek_cpu(addr)
3565 }
3566
3567 /// Side-effect-free PPU bus peek (for the hex viewer + visualizers).
3568 pub fn ppu_bus_peek(&mut self, addr: u16) -> u8 {
3569 self.bus.debug_peek_ppu(addr)
3570 }
3571
3572 /// Render the 256 tiles of a CHR pattern table as RGBA8 (128x128).
3573 ///
3574 /// `table` selects which of the two pattern tables: 0 -> `$0000`,
3575 /// 1 -> `$1000`. Uses BG palette 0 ($3F00-$3F03) for grayscale-ish
3576 /// rendering. ~80 KiB cloned; only call when the PPU pattern viewer
3577 /// is open.
3578 pub fn pattern_table_rgba(&mut self, table: u8) -> Vec<u8> {
3579 const TILE_W: usize = 8;
3580 const SHEET_W: usize = 128;
3581 const SHEET_H: usize = 128;
3582 let base: u16 = if table & 1 == 0 { 0 } else { 0x1000 };
3583 let mut out = vec![0u8; SHEET_W * SHEET_H * 4];
3584 for tile_y in 0..16u16 {
3585 for tile_x in 0..16u16 {
3586 let tile_index = tile_y * 16 + tile_x;
3587 for row in 0..8u16 {
3588 let lo = self.ppu_bus_peek(base + tile_index * 16 + row);
3589 let hi = self.ppu_bus_peek(base + tile_index * 16 + row + 8);
3590 for col in 0..8u16 {
3591 let bit = 7 - col;
3592 let p = ((hi >> bit) & 1) << 1 | ((lo >> bit) & 1);
3593 let palette_byte = self.ppu_bus_peek(0x3F00 + u16::from(p));
3594 let rgba = rustynes_ppu::nes_color_to_rgba(palette_byte & 0x3F);
3595 let px = usize::from(tile_x) * TILE_W + usize::from(col);
3596 let py = usize::from(tile_y) * TILE_W + usize::from(row);
3597 let off = (py * SHEET_W + px) * 4;
3598 out[off..off + 4].copy_from_slice(&rgba);
3599 }
3600 }
3601 }
3602 }
3603 out
3604 }
3605
3606 /// Render a nametable as RGBA8 (256x240).
3607 ///
3608 /// `nt` selects 0..=3 logical nametable. Uses the current
3609 /// BG pattern table base, attribute palette, and CHR data.
3610 pub fn nametable_rgba(&mut self, nt: u8) -> Vec<u8> {
3611 const FB_W: usize = 256;
3612 const FB_H: usize = 240;
3613 let nt = nt & 0x03;
3614 let nt_base = 0x2000u16 + u16::from(nt) * 0x400;
3615 let attr_base = nt_base + 0x3C0;
3616 let bg_base = self.bus.ppu().bg_pattern_base();
3617 let mut out = vec![0u8; FB_W * FB_H * 4];
3618 for ty in 0..30u16 {
3619 for tx in 0..32u16 {
3620 let nt_addr = nt_base + ty * 32 + tx;
3621 let tile_idx = self.ppu_bus_peek(nt_addr);
3622 let attr_addr = attr_base + (ty / 4) * 8 + (tx / 4);
3623 let attr_byte = self.ppu_bus_peek(attr_addr);
3624 let shift = ((ty & 2) << 1) | (tx & 2);
3625 let palette = u16::from((attr_byte >> shift) & 0x03);
3626 for row in 0..8u16 {
3627 let lo = self.ppu_bus_peek(bg_base + u16::from(tile_idx) * 16 + row);
3628 let hi = self.ppu_bus_peek(bg_base + u16::from(tile_idx) * 16 + row + 8);
3629 for col in 0..8u16 {
3630 let bit = 7 - col;
3631 let p = ((hi >> bit) & 1) << 1 | ((lo >> bit) & 1);
3632 let final_idx = if p == 0 {
3633 self.ppu_bus_peek(0x3F00)
3634 } else {
3635 self.ppu_bus_peek(0x3F00 + palette * 4 + u16::from(p))
3636 };
3637 let rgba = rustynes_ppu::nes_color_to_rgba(final_idx & 0x3F);
3638 let px = usize::from(tx * 8 + col);
3639 let py = usize::from(ty * 8 + row);
3640 let off = (py * FB_W + px) * 4;
3641 out[off..off + 4].copy_from_slice(&rgba);
3642 }
3643 }
3644 }
3645 }
3646 out
3647 }
3648}
3649
3650/// The persistent identity of a cartridge image: SHA-256 of everything after
3651/// the 16-byte iNES / NES 2.0 header, or of the whole image when the `NES\x1A`
3652/// magic is absent. See [`Nes::rom_sha256`].
3653fn rom_identity_sha256(bytes: &[u8]) -> [u8; 32] {
3654 match bytes {
3655 [b'N', b'E', b'S', 0x1A, ..] if bytes.len() >= 16 => sha256_of(&bytes[16..]),
3656 _ => sha256_of(bytes),
3657 }
3658}
3659
3660fn sha256_of(bytes: &[u8]) -> [u8; 32] {
3661 let mut h = Sha256::new();
3662 h.update(bytes);
3663 let out = h.finalize();
3664 let mut a = [0u8; 32];
3665 a.copy_from_slice(&out);
3666 a
3667}
3668
3669#[cfg(test)]
3670mod tests {
3671 use super::*;
3672
3673 /// 16-byte iNES header for a synthetic NROM ROM with `prg_kib`/`chr_kib`
3674 /// content, vertical mirroring.
3675 fn synth_nrom(prg_kib: usize, chr_kib: usize) -> Vec<u8> {
3676 let mut bytes = Vec::with_capacity(16 + prg_kib * 1024 + chr_kib * 1024);
3677 bytes.extend_from_slice(b"NES\x1A");
3678 bytes.push(u8::try_from(prg_kib / 16).unwrap());
3679 bytes.push(u8::try_from(chr_kib / 8).unwrap());
3680 bytes.push(0); // flags6
3681 bytes.push(0); // flags7
3682 bytes.extend_from_slice(&[0u8; 8]);
3683
3684 // PRG payload: a tiny program at $C000 that loops forever (JMP $C000).
3685 // Since the reset vector reads $FFFC/D, we set those bytes too.
3686 let mut prg = vec![0u8; prg_kib * 1024];
3687 if prg_kib >= 16 {
3688 // 16 KiB PRG: $C000-$FFFF maps to bytes 0..$4000 of PRG.
3689 // JMP $C000 -> $4C $00 $C0
3690 prg[0] = 0x4C;
3691 prg[1] = 0x00;
3692 prg[2] = 0xC0;
3693 // Reset vector at $FFFC/D = end-of-PRG offsets.
3694 let len = prg.len();
3695 prg[len - 4] = 0x00;
3696 prg[len - 3] = 0xC0;
3697 // NMI vector at $FFFA/B: same.
3698 prg[len - 6] = 0x00;
3699 prg[len - 5] = 0xC0;
3700 // IRQ vector at $FFFE/F: same.
3701 prg[len - 2] = 0x00;
3702 prg[len - 1] = 0xC0;
3703 }
3704 bytes.extend_from_slice(&prg);
3705 bytes.extend_from_slice(&vec![0u8; chr_kib * 1024]);
3706 bytes
3707 }
3708
3709 /// Synthetic MMC5 (mapper 5) image, 32 KiB PRG + 8 KiB CHR. MMC5 powers on
3710 /// in PRG mode 3 with the last 8 KiB bank at `$E000`, so the program lives
3711 /// there. It waits two vblanks (past the NES PPU warm-up, where a
3712 /// `$2001` write is ignored), turns rendering on, arms the scanline IRQ
3713 /// at line 20 (`$5203` / `$5204`) and idles with interrupts enabled. The
3714 /// IRQ handler counts into `$0000` and acknowledges by reading `$5204`.
3715 fn synth_mmc5_scanline_irq() -> Vec<u8> {
3716 let mut bytes = Vec::with_capacity(16 + 32 * 1024 + 8 * 1024);
3717 bytes.extend_from_slice(b"NES\x1A");
3718 bytes.push(2); // 2 x 16 KiB PRG
3719 bytes.push(1); // 1 x 8 KiB CHR
3720 bytes.push(0x50); // flags6: mapper low nibble 5
3721 bytes.push(0); // flags7
3722 bytes.extend_from_slice(&[0u8; 8]);
3723 let mut prg = vec![0u8; 32 * 1024];
3724 let base = 0x6000; // $E000 within the last 8 KiB bank
3725 #[rustfmt::skip]
3726 let reset: [u8; 35] = [
3727 0x78, // $E000 SEI
3728 0xA2, 0xFF, // $E001 LDX #$FF
3729 0x9A, // $E003 TXS
3730 0xA9, 0x40, // $E004 LDA #$40
3731 0x8D, 0x17, 0x40, // $E006 STA $4017 (inhibit the APU frame IRQ)
3732 0x2C, 0x02, 0x20, // $E009 BIT $2002
3733 0x10, 0xFB, // $E00C BPL $E009
3734 0x2C, 0x02, 0x20, // $E00E BIT $2002
3735 0x10, 0xFB, // $E011 BPL $E00E
3736 0xA9, 0x1E, // $E013 LDA #$1E
3737 0x8D, 0x01, 0x20, // $E015 STA $2001 (rendering on)
3738 0xA9, 0x14, // $E018 LDA #20
3739 0x8D, 0x03, 0x52, // $E01A STA $5203 (compare = line 20)
3740 0xA9, 0x80, // $E01D LDA #$80
3741 0x8D, 0x04, 0x52, // $E01F STA $5204 (IRQ enable)
3742 0x58, // $E022 CLI
3743 ];
3744 prg[base..base + reset.len()].copy_from_slice(&reset);
3745 // $E023: JMP $E023 (idle)
3746 prg[base + 0x23..base + 0x26].copy_from_slice(&[0x4C, 0x23, 0xE0]);
3747 // $E030: IRQ handler -- INC $00 ; LDA $5204 (ack) ; RTI
3748 prg[base + 0x30..base + 0x36].copy_from_slice(&[0xE6, 0x00, 0xAD, 0x04, 0x52, 0x40]);
3749 // $E040: NMI handler -- RTI (NMI is never enabled; defensive)
3750 prg[base + 0x40] = 0x40;
3751 let len = prg.len();
3752 prg[len - 6..].copy_from_slice(&[0x40, 0xE0, 0x00, 0xE0, 0x30, 0xE0]);
3753 bytes.extend_from_slice(&prg);
3754 bytes.extend_from_slice(&[0u8; 8 * 1024]);
3755 bytes
3756 }
3757
3758 /// The MMC5 scanline IRQ fires through the real `SystemBus`, once per
3759 /// rendered frame. Regression for a v3.2.0 import that moved the
3760 /// scanline detector into `Mmc5::ppu_read` (a nametable-snoop model):
3761 /// the lockstep bus fetches nametables through `peek_nametable`, never
3762 /// `ppu_read`, so the detector never saw a fetch and the IRQ stopped
3763 /// firing in real play (*Castlevania III*, *Uchuu Keibitai SDF* and
3764 /// *Bandit Kings* all went red). The `mmc5` test-ROM gate did not catch
3765 /// it, because none of those ROMs depends on the scanline IRQ.
3766 #[test]
3767 fn mmc5_scanline_irq_fires_through_the_real_bus() {
3768 let mut nes = Nes::from_rom(&synth_mmc5_scanline_irq()).unwrap();
3769 for _ in 0..10 {
3770 nes.run_frame();
3771 }
3772 let count = nes.peek(0x0000);
3773 // Rendering is on from about frame 2; one IRQ per frame after that.
3774 assert!(
3775 (5..=10).contains(&count),
3776 "expected one MMC5 scanline IRQ per rendered frame, counted {count}"
3777 );
3778 }
3779
3780 /// `Nes::scan_barcode` validates at the boundary, refuses a cartridge
3781 /// with no reader, and a scan is part of the save state: a snapshot taken
3782 /// mid-swipe restores mid-swipe and the two runs stay identical.
3783 #[test]
3784 fn datach_barcode_scan_is_validated_and_survives_a_snapshot() {
3785 let mut nrom = Nes::from_rom(&synth_nrom(32, 8)).unwrap();
3786 assert!(!nrom.has_barcode_reader());
3787 assert_eq!(
3788 nrom.scan_barcode("4006381333931"),
3789 Err(BarcodeScanError::NoReader)
3790 );
3791
3792 let rom = synth_board_rom(157, SweepHeader::Nes2 { submapper: 0 }, 32, 0);
3793 let mut nes = Nes::from_rom(&rom).unwrap();
3794 assert!(nes.has_barcode_reader());
3795 assert_eq!(
3796 nes.scan_barcode("4006381333932"),
3797 Err(BarcodeScanError::Malformed(
3798 rustynes_mappers::BarcodeError::BadCheckDigit {
3799 expected: 1,
3800 found: 2
3801 }
3802 ))
3803 );
3804 assert!(
3805 !nes.barcode_scan_in_progress(),
3806 "a refused scan starts nothing"
3807 );
3808 assert_eq!(nes.scan_barcode("4006381333931"), Ok(()));
3809 assert!(nes.barcode_scan_in_progress());
3810 nes.run_frame();
3811 assert!(nes.barcode_scan_in_progress(), "a swipe outlasts a frame");
3812 let mid = nes.snapshot();
3813 let mut other = Nes::from_rom(&rom).unwrap();
3814 other.restore(&mid).unwrap();
3815 assert!(other.barcode_scan_in_progress());
3816 for _ in 0..20 {
3817 nes.run_frame();
3818 other.run_frame();
3819 }
3820 assert!(!nes.barcode_scan_in_progress(), "the swipe ends");
3821 assert_eq!(nes.snapshot(), other.snapshot());
3822 }
3823
3824 /// Synthetic NES 2.0 NROM with console type Vs. System and a byte-13 Vs.
3825 /// PPU type (low nibble).
3826 fn synth_vs_nrom(vs_ppu_low_nibble: u8) -> Vec<u8> {
3827 let mut rom = synth_nrom(16, 8);
3828 // Upgrade the header to NES 2.0 + console type Vs. System.
3829 rom[7] = 0x09; // bits 2-3 = 10 (NES 2.0), bits 0-1 = 01 (Vs. System)
3830 rom[13] = vs_ppu_low_nibble & 0x0F;
3831 rom
3832 }
3833
3834 #[test]
3835 fn a_restored_cpu_ppu_clock_skew_is_rejected() {
3836 // v2.7.0: the fuzz target's first timeout. A `ppu_clock` restored far
3837 // from the CPU's `master_clock` made the next catch-up tick billions of
3838 // dots (behind) or never tick at all (ahead) -- a hang either way.
3839 let rom = synth_nrom(16, 8);
3840 let mut nes = Nes::from_rom(&rom).unwrap();
3841 nes.run_frame();
3842 let master = nes.cpu.master_clock();
3843 let live = nes.bus().ppu_clock_for_test();
3844 let live_skew = master.abs_diff(live);
3845 assert!(
3846 live_skew <= SystemBus::RESTORED_CLOCK_SKEW_MAX,
3847 "the running machine's own skew ({live_skew}) must be inside the bound"
3848 );
3849 assert!(
3850 Nes::from_rom(&rom)
3851 .unwrap()
3852 .restore_quiet(&nes.snapshot())
3853 .is_ok()
3854 );
3855
3856 // Measured: a frame of this ROM leaves the pair a handful of master
3857 // clocks apart (4 at the time of writing), and `master_clock` itself
3858 // small, so the "behind" direction is exercised by moving the PPU
3859 // clock only as far as zero allows and the "ahead" direction carries
3860 // the bound.
3861 let max = SystemBus::RESTORED_CLOCK_SKEW_MAX;
3862 for (label, ppu_clock, ok) in [
3863 ("behind, as far as zero", master.saturating_sub(max), true),
3864 ("at the bound, ahead", master + max, true),
3865 ("past the bound, ahead", master + max + 1, false),
3866 ("far ahead", master + (1 << 40), false),
3867 ("u64::MAX", u64::MAX, false),
3868 ] {
3869 nes.bus_mut().set_ppu_clock_for_test(ppu_clock);
3870 let blob = nes.snapshot();
3871 let got = Nes::from_rom(&rom).unwrap().restore_quiet(&blob);
3872 assert_eq!(got.is_ok(), ok, "{label}: {got:?}");
3873 }
3874 }
3875
3876 /// v2.9.0 re-audit NC-04: the clock check bounds the ABSOLUTE clocks, not
3877 /// only their skew.
3878 ///
3879 /// F-05's check accepted any pair within `RESTORED_CLOCK_SKEW_MAX` of each
3880 /// other, so a crafted state with BOTH clocks ~20,000 master clocks below
3881 /// 2^64 loaded. The CPU advances with `wrapping_add`, so its clock wrapped
3882 /// to a small value within a frame while the PPU's stayed near 2^64, and
3883 /// the catch-up loop (`while ppu_clock + div <= target`) never ran again:
3884 /// the frame counter froze, NMI never fired — the exact state F-05 set out
3885 /// to reject. Both clocks are shifted by the same amount here, so the skew
3886 /// is the running machine's own and only the new ceiling can reject it.
3887 #[test]
3888 fn restored_clocks_near_the_top_of_u64_are_rejected() {
3889 let rom = synth_nrom(16, 8);
3890 let mut nes = Nes::from_rom(&rom).unwrap();
3891 nes.run_frame();
3892 nes.run_frame();
3893 let master = nes.cpu.master_clock();
3894 let ppu = nes.bus().ppu_clock_for_test();
3895
3896 // Shift both clocks by `shift` and return the snapshot. The CPU clock
3897 // has no setter, so its bytes are patched inside the CPU section's
3898 // body, where they must occur exactly once.
3899 let shifted = |nes: &mut Nes, shift: u64| {
3900 nes.bus_mut().set_ppu_clock_for_test(ppu + shift);
3901 let mut blob = nes.snapshot();
3902 let (_h, body_off) = save_state::parse_header(&blob).unwrap();
3903 let cpu_body_off = {
3904 let s = save_state::SectionIter::new(&blob[body_off..])
3905 .map(Result::unwrap)
3906 .find(|s| s.tag == save_state::tag::CPU)
3907 .unwrap();
3908 s.body.as_ptr() as usize - blob.as_ptr() as usize
3909 };
3910 let needle = master.to_le_bytes();
3911 let hits: Vec<usize> = (cpu_body_off..blob.len() - 8)
3912 .filter(|&o| blob[o..o + 8] == needle)
3913 .collect();
3914 assert_eq!(hits.len(), 1, "master_clock must occur once: {hits:?}");
3915 blob[hits[0]..hits[0] + 8].copy_from_slice(&(master + shift).to_le_bytes());
3916 nes.bus_mut().set_ppu_clock_for_test(ppu);
3917 blob
3918 };
3919
3920 let ceiling = SystemBus::RESTORED_CLOCK_MAX;
3921 for (label, shift, ok) in [
3922 ("unshifted", 0, true),
3923 (
3924 "a century of emulation",
3925 100 * 365 * 86_400 * 21_477_272,
3926 true,
3927 ),
3928 ("at the ceiling", ceiling - master.max(ppu), true),
3929 ("past the ceiling", ceiling - master.max(ppu) + 1, false),
3930 (
3931 "20,000 master clocks below 2^64",
3932 u64::MAX - 20_000 - master,
3933 false,
3934 ),
3935 ] {
3936 let blob = shifted(&mut nes, shift);
3937 let mut fresh = Nes::from_rom(&rom).unwrap();
3938 let got = fresh.restore_quiet(&blob);
3939 assert_eq!(got.is_ok(), ok, "{label}: {got:?}");
3940 if ok {
3941 // An accepted state must actually run: the frame counter moves.
3942 let f = fresh.frame();
3943 fresh.run_frame();
3944 fresh.run_frame();
3945 assert!(fresh.frame() > f, "{label}: the PPU stopped");
3946 }
3947 }
3948 }
3949
3950 #[test]
3951 fn nes_cart_4016_read_is_byte_identical_with_and_without_vs_inputs() {
3952 // On a normal NES cart the Vs. DIP/coin/service overlay is a no-op, so
3953 // a $4016/$4017 read is byte-for-byte identical regardless of the Vs.
3954 // input state. Compare two freshly-built buses in lockstep.
3955 let rom = synth_nrom(16, 8);
3956 let mut a = Nes::from_rom(&rom).unwrap();
3957 let mut b = Nes::from_rom(&rom).unwrap();
3958 assert!(!a.is_vs_system());
3959 // Crank the Vs. inputs on `b` only.
3960 b.set_vs_dip(0xFF);
3961 b.insert_coin(0);
3962 b.insert_coin(1);
3963 b.set_vs_service(true);
3964 for addr in [0x4016u16, 0x4017, 0x4016, 0x4017] {
3965 assert_eq!(
3966 a.bus_mut().raw_cpu_read(addr),
3967 b.bus_mut().raw_cpu_read(addr),
3968 "Vs. inputs leaked into a normal-cart read of {addr:#06X}"
3969 );
3970 }
3971 }
3972
3973 /// v1.6.0 Workstream A3 — the `TAStudio` lag-log flag: a frame in which the
3974 /// program never reads `$4016`/`$4017` is a lag frame; a controller read
3975 /// marks the frame polled; and the flag resets at the top of each frame.
3976 #[cfg(feature = "debug-hooks")]
3977 #[test]
3978 fn lag_flag_tracks_controller_reads_per_frame() {
3979 // synth_nrom is a pure `JMP $C000` loop — it never polls input.
3980 let rom = synth_nrom(16, 8);
3981 let mut nes = Nes::from_rom(&rom).unwrap();
3982
3983 // A frame of pure JMP never reads a controller port => lag frame.
3984 nes.run_frame();
3985 assert!(
3986 !nes.was_input_polled_this_frame(),
3987 "a frame with no $4016/$4017 read must be a lag frame"
3988 );
3989
3990 // A controller-port read marks the (current) frame as polled.
3991 let _ = nes.bus_mut().raw_cpu_read(0x4016);
3992 assert!(
3993 nes.was_input_polled_this_frame(),
3994 "a $4016 read must mark the frame polled"
3995 );
3996
3997 // $4017 also counts, and the next frame's clear resets the flag.
3998 nes.run_frame();
3999 assert!(
4000 !nes.was_input_polled_this_frame(),
4001 "the flag must reset at the top of each frame"
4002 );
4003 let _ = nes.bus_mut().raw_cpu_read(0x4017);
4004 assert!(
4005 nes.was_input_polled_this_frame(),
4006 "a $4017 read must also mark the frame polled"
4007 );
4008 }
4009
4010 #[test]
4011 fn vs_dip_switches_read_through_4016_and_4017() {
4012 // 2C03 Vs. cart (low nibble 0).
4013 let rom = synth_vs_nrom(0x0);
4014 let mut nes = Nes::from_rom(&rom).unwrap();
4015 assert!(nes.is_vs_system());
4016 // DIP = 0b1010_1010: sw2,4,6,8 on; sw1,3,5,7 off.
4017 nes.set_vs_dip(0b1010_1010);
4018 let v16 = nes.bus_mut().raw_cpu_read(0x4016);
4019 // $4016: DIP sw1 -> bit3 (off), sw2 -> bit4 (on).
4020 assert_eq!(v16 & 0x08, 0x00, "DIP sw1 off");
4021 assert_eq!(v16 & 0x10, 0x10, "DIP sw2 on");
4022 let v17 = nes.bus_mut().raw_cpu_read(0x4017);
4023 // $4017: DIP sw3..8 -> bits 2..7. DIP bits 2..7 = 0b101010.
4024 assert_eq!(v17 & 0xFC, 0b1010_1000 & 0xFC);
4025 }
4026
4027 #[test]
4028 fn vs_coin_and_service_read_through_4016() {
4029 let rom = synth_vs_nrom(0x0);
4030 let mut nes = Nes::from_rom(&rom).unwrap();
4031 nes.set_vs_dip(0);
4032 // Coin acceptor #1 -> $4016 bit 5.
4033 nes.insert_coin(0);
4034 assert_eq!(nes.bus_mut().raw_cpu_read(0x4016) & 0x20, 0x20);
4035 // Acceptor #2 -> bit 6.
4036 nes.insert_coin(1);
4037 assert_eq!(nes.bus_mut().raw_cpu_read(0x4016) & 0x60, 0x60);
4038 nes.clear_coin();
4039 assert_eq!(nes.bus_mut().raw_cpu_read(0x4016) & 0x60, 0x00);
4040 // Service button -> bit 2.
4041 nes.set_vs_service(true);
4042 assert_eq!(nes.bus_mut().raw_cpu_read(0x4016) & 0x04, 0x04);
4043 nes.set_vs_service(false);
4044 assert_eq!(nes.bus_mut().raw_cpu_read(0x4016) & 0x04, 0x00);
4045 }
4046
4047 #[test]
4048 fn game_genie_substitutes_on_cpu_read_path() {
4049 // 16 KiB NROM; plant the Zelda code's compare byte (0x22) at the PRG
4050 // address it targets ($9F41 -> $8000-$BFFF window -> PRG offset $1F41).
4051 let mut rom = synth_nrom(16, 8);
4052 rom[16 + 0x1F41] = 0x22;
4053 let mut nes = Nes::from_rom(&rom).expect("synthetic NROM parses");
4054
4055 // No codes active: reads are the original byte (determinism contract).
4056 assert_eq!(nes.bus_mut().debug_peek_cpu(0x9F41), 0x22);
4057 assert_eq!(nes.bus_mut().peek_cpu(0x9F41), 0x22);
4058 assert_eq!(nes.genie_codes().count(), 0);
4059
4060 // 8-char code substitutes only when the original matches compare (0x22),
4061 // on BOTH the production read path and the debugger peek path.
4062 nes.add_genie_code("YYKPOYZZ").expect("valid 8-char code");
4063 assert_eq!(
4064 nes.bus_mut().debug_peek_cpu(0x9F41),
4065 0x77,
4066 "debug peek substituted"
4067 );
4068 assert_eq!(
4069 nes.bus_mut().peek_cpu(0x9F41),
4070 0x77,
4071 "production read substituted"
4072 );
4073 assert_eq!(
4074 nes.bus_mut().debug_peek_cpu(0x9F40),
4075 0x00,
4076 "other address untouched"
4077 );
4078
4079 // Removal (case-insensitive) restores the original byte.
4080 nes.remove_genie_code("yykpoyzz");
4081 assert_eq!(nes.bus_mut().debug_peek_cpu(0x9F41), 0x22);
4082
4083 // 6-char code (no compare) always substitutes; $91D9 -> data 0xAD.
4084 nes.add_genie_code("SXIOPO").expect("valid 6-char code");
4085 assert_eq!(nes.bus_mut().debug_peek_cpu(0x91D9), 0xAD);
4086 nes.clear_genie_codes();
4087 assert_eq!(nes.bus_mut().debug_peek_cpu(0x91D9), 0x00);
4088
4089 // A malformed code is rejected without mutating state.
4090 assert!(nes.add_genie_code("BADCODE!").is_err());
4091 }
4092
4093 #[test]
4094 fn debug_peek_cpu_leaves_an_ffe_trainer_boot_armed() {
4095 // Mapper 6 (FFE) with a trainer boots through a one-shot stub at
4096 // $7200 that the CPU's own reads retire. The debugger, disassembler
4097 // and Lua read through `debug_peek_cpu`, which must reach the board's
4098 // `cpu_peek`: through `cpu_read` it retired the stub, and the game
4099 // then never ran its trainer (agy on #604).
4100 let mut rom = Vec::new();
4101 rom.extend_from_slice(b"NES\x1A");
4102 rom.extend_from_slice(&[16, 0, 0x64, 0x00]); // 256 KiB PRG, mapper 6, trainer
4103 rom.extend_from_slice(&[0u8; 8]);
4104 let mut trainer = vec![0u8; 512];
4105 trainer[0] = 0x4C; // JMP, at $7000
4106 rom.extend_from_slice(&trainer);
4107 rom.extend_from_slice(&vec![0u8; 256 * 1024]);
4108 let mut nes = Nes::from_rom(&rom).expect("synthetic FFE ROM parses");
4109 let stub: Vec<u8> = (0..6u16)
4110 .map(|i| nes.bus_mut().debug_peek_cpu(0x7200 + i))
4111 .collect();
4112 assert_eq!(stub[0], 0x20, "the stub begins JSR $7003");
4113 let again: Vec<u8> = (0..6u16)
4114 .map(|i| nes.bus_mut().debug_peek_cpu(0x7200 + i))
4115 .collect();
4116 assert_eq!(again, stub, "a debugger peek retired the boot stub");
4117 }
4118
4119 #[test]
4120 fn poke_ram_writes_system_ram_and_ignores_rom() {
4121 let rom = synth_nrom(16, 8);
4122 let mut nes = Nes::from_rom(&rom).expect("synthetic NROM parses");
4123 nes.poke_ram(0x0042, 0xAB);
4124 assert_eq!(nes.bus_mut().debug_peek_cpu(0x0042), 0xAB);
4125 // Mirrored every $800 within $0000-$1FFF.
4126 assert_eq!(nes.bus_mut().debug_peek_cpu(0x0842), 0xAB);
4127 // A poke outside system RAM is a no-op (no panic; ROM space untouched).
4128 nes.poke_ram(0x8000, 0xFF);
4129 assert_ne!(nes.bus_mut().debug_peek_cpu(0x8000), 0xFF);
4130 }
4131
4132 #[test]
4133 fn nes_set_buttons_then_strobe_reads_bits_in_order() {
4134 // T-51-005: end-to-end controller plumbing — the bus must shift the
4135 // latched button state out via $4016 in canonical order.
4136 //
4137 // Session-24 / Phase 3 update: `$4016` writes are deferred
4138 // (committed at the start of a later cycle by `Bus::cpu_clock`).
4139 // Direct-API callers that bypass CPU stepping must clock the bus
4140 // between the strobe pulse and the shift-out reads so the buffered
4141 // write commits. Two cycles are sufficient (one for the pending=1
4142 // commit, one as a margin in case the test's first write landed on
4143 // the pending=2 path). Until v2.9.8 these tests drove the removed
4144 // pre-v2.0.0 `tick_one_cpu_cycle`, which committed the strobe the
4145 // same way.
4146 use rustynes_cpu::Bus as _;
4147 let rom = synth_nrom(16, 8);
4148 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
4149 nes.set_buttons(0, Buttons::A | Buttons::SELECT | Buttons::DOWN);
4150
4151 // Pulse the strobe latch (write 1 then 0 to $4016), driving the
4152 // bus enough cycles between writes for the deferred-write
4153 // commit to land.
4154 nes.bus_mut().cpu_write(0x4016, 1);
4155 nes.bus_mut().cpu_clock();
4156 nes.bus_mut().cpu_clock();
4157 nes.bus_mut().cpu_write(0x4016, 0);
4158 nes.bus_mut().cpu_clock();
4159 nes.bus_mut().cpu_clock();
4160
4161 // 8 reads of $4016 should yield A, B, Select, Start, Up, Down, Left, Right.
4162 let expected = [1u8, 0, 1, 0, 0, 1, 0, 0];
4163 for &want in &expected {
4164 let v = nes.bus_mut().cpu_read(0x4016) & 1;
4165 assert_eq!(v, want);
4166 }
4167 }
4168
4169 #[test]
4170 fn nes_set_buttons_port1_reads_via_4017_in_order() {
4171 // T-71-004 (Phase 7): player 2 plumbing. The strobe latch is shared
4172 // (writing `$4016` strobes BOTH pads); player 2 shifts out on `$4017`.
4173 // Mirrors `nes_set_buttons_then_strobe_reads_bits_in_order` for port 1.
4174 use rustynes_cpu::Bus as _;
4175 let rom = synth_nrom(16, 8);
4176 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
4177 nes.set_buttons(1, Buttons::B | Buttons::START | Buttons::RIGHT);
4178
4179 nes.bus_mut().cpu_write(0x4016, 1);
4180 nes.bus_mut().cpu_clock();
4181 nes.bus_mut().cpu_clock();
4182 nes.bus_mut().cpu_write(0x4016, 0);
4183 nes.bus_mut().cpu_clock();
4184 nes.bus_mut().cpu_clock();
4185
4186 // A, B, Select, Start, Up, Down, Left, Right.
4187 let expected = [0u8, 1, 0, 1, 0, 0, 0, 1];
4188 for (i, &want) in expected.iter().enumerate() {
4189 let v = nes.bus_mut().cpu_read(0x4017) & 1;
4190 assert_eq!(v, want, "$4017 read #{i}");
4191 }
4192 }
4193
4194 #[test]
4195 fn nes_restrobe_relatches_current_buttons() {
4196 // T-71-004 (Phase 7): a fresh strobe re-samples the live button state
4197 // through the full bus (the per-`Controller` unit test in
4198 // `controller.rs` covers this at the chip level; this confirms it end
4199 // to end via `Nes::set_buttons` + `$4016`).
4200 use rustynes_cpu::Bus as _;
4201 let rom = synth_nrom(16, 8);
4202 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
4203
4204 let strobe = |nes: &mut Nes| {
4205 nes.bus_mut().cpu_write(0x4016, 1);
4206 nes.bus_mut().cpu_clock();
4207 nes.bus_mut().cpu_clock();
4208 nes.bus_mut().cpu_write(0x4016, 0);
4209 nes.bus_mut().cpu_clock();
4210 nes.bus_mut().cpu_clock();
4211 };
4212
4213 nes.set_buttons(0, Buttons::A);
4214 strobe(&mut nes);
4215 assert_eq!(nes.bus_mut().cpu_read(0x4016) & 1, 1, "A latched pressed");
4216
4217 // Change state, then re-strobe: the new state must be visible.
4218 nes.set_buttons(0, Buttons::empty());
4219 strobe(&mut nes);
4220 assert_eq!(nes.bus_mut().cpu_read(0x4016) & 1, 0, "A latched released");
4221 }
4222
4223 #[test]
4224 fn reading_4015_does_not_refresh_external_open_bus() {
4225 // T-72-006 (Phase 7): `$4015` reads return the APU status but do NOT
4226 // drive the external data bus (the APU status port is internal to the
4227 // 2A03 package). So a `$4015` read must leave the open-bus latch
4228 // unchanged — a subsequent open-bus-region read returns the prior
4229 // floating value, not the APU status. Per nesdev "Open bus behavior"
4230 // + AccuracyCoin `CPU Behavior :: Open Bus` Test 7.
4231 use rustynes_cpu::Bus as _;
4232 let rom = synth_nrom(16, 8);
4233 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
4234
4235 // Drive a known value onto the external bus via a normal RAM read.
4236 nes.bus_mut().cpu_write(0x0010, 0xAB);
4237 assert_eq!(nes.bus_mut().cpu_read(0x0010), 0xAB);
4238 // $4018-$401F is open-bus region: returns (and re-latches) the value.
4239 assert_eq!(
4240 nes.bus_mut().cpu_read(0x4018),
4241 0xAB,
4242 "open-bus latch holds 0xAB"
4243 );
4244
4245 // Read $4015 — must NOT refresh the external latch.
4246 let _ = nes.bus_mut().cpu_read(0x4015);
4247
4248 // The latch is still 0xAB, not whatever APU status $4015 returned.
4249 assert_eq!(
4250 nes.bus_mut().cpu_read(0x4018),
4251 0xAB,
4252 "$4015 read must not drive the external data bus"
4253 );
4254 }
4255
4256 #[test]
4257 fn nes_from_rom_constructs_and_resets() {
4258 let rom = synth_nrom(16, 8);
4259 let nes = Nes::from_rom(&rom).expect("parse + boot");
4260 assert_eq!(nes.cpu().pc, 0xC000);
4261 }
4262
4263 #[test]
4264 fn power_on_randomization_is_opt_in_seeded_and_deterministic() {
4265 // T-72-005 (Phase 7): the default path leaves work RAM zeroed; the
4266 // seeded constructor randomizes it deterministically.
4267 let rom = synth_nrom(16, 8);
4268
4269 // Default: RAM is zeroed.
4270 let mut default = Nes::from_rom(&rom).expect("parse + boot");
4271 for addr in (0x0000u16..0x0800).step_by(0x40) {
4272 assert_eq!(default.cpu_bus_peek(addr), 0, "default RAM must be zero");
4273 }
4274
4275 // Seeded: RAM is not all-zero.
4276 let mut a = Nes::from_rom_with_power_on_seed(&rom, 1).expect("parse + boot");
4277 let dump_a: Vec<u8> = (0x0000u16..0x0100).map(|x| a.cpu_bus_peek(x)).collect();
4278 assert!(
4279 dump_a.iter().any(|&b| b != 0),
4280 "seeded RAM must not be all zero"
4281 );
4282
4283 // Same seed -> identical RAM.
4284 let mut a2 = Nes::from_rom_with_power_on_seed(&rom, 1).expect("parse + boot");
4285 let dump_a2: Vec<u8> = (0x0000u16..0x0100).map(|x| a2.cpu_bus_peek(x)).collect();
4286 assert_eq!(
4287 dump_a, dump_a2,
4288 "same seed must yield identical power-on RAM"
4289 );
4290
4291 // Different seed -> different RAM.
4292 let mut b = Nes::from_rom_with_power_on_seed(&rom, 0xDEAD_BEEF).expect("parse + boot");
4293 let dump_b: Vec<u8> = (0x0000u16..0x0100).map(|x| b.cpu_bus_peek(x)).collect();
4294 assert_ne!(dump_a, dump_b, "different seeds should differ");
4295 }
4296
4297 #[test]
4298 fn power_on_config_defaults_byte_identical_and_variants_deterministic() {
4299 // v2.1.7 P5 — the PowerOnConfig surface. Default (Zeroed) must match the
4300 // plain constructor; Filled + Seeded must be deterministic and distinct.
4301 let rom = synth_nrom(16, 8);
4302
4303 // Default config == from_rom (byte-identical work RAM).
4304 let mut zeroed =
4305 Nes::from_rom_with_power_on_config(&rom, PowerOnConfig::default()).expect("boot");
4306 assert_eq!(zeroed.power_on_ram(), PowerOnRam::Zeroed);
4307 for addr in (0x0000u16..0x0800).step_by(0x40) {
4308 assert_eq!(zeroed.cpu_bus_peek(addr), 0, "Zeroed config: RAM zero");
4309 }
4310
4311 // Filled(0xFF): every work-RAM byte is 0xFF, deterministically.
4312 let mut filled = Nes::from_rom_with_power_on_config(
4313 &rom,
4314 PowerOnConfig {
4315 ram: PowerOnRam::Filled(0xFF),
4316 },
4317 )
4318 .expect("boot");
4319 assert_eq!(filled.power_on_ram(), PowerOnRam::Filled(0xFF));
4320 for addr in (0x0000u16..0x0800).step_by(0x40) {
4321 assert_eq!(filled.cpu_bus_peek(addr), 0xFF, "Filled(0xFF)");
4322 }
4323
4324 // Seeded is deterministic and differs from Zeroed.
4325 let mut seeded = Nes::from_rom_with_power_on_config(
4326 &rom,
4327 PowerOnConfig {
4328 ram: PowerOnRam::Seeded(42),
4329 },
4330 )
4331 .expect("boot");
4332 let dump: Vec<u8> = (0x0000u16..0x0100)
4333 .map(|x| seeded.cpu_bus_peek(x))
4334 .collect();
4335 assert!(dump.iter().any(|&b| b != 0), "Seeded: not all zero");
4336 }
4337
4338 #[test]
4339 fn ppu_revision_and_palette_default_byte_identical() {
4340 // v2.1.7 P5 — the PPU-revision + power-up-palette knobs default to the
4341 // byte-identical state, and toggling them is observable + power-cycle
4342 // durable.
4343 let rom = synth_nrom(16, 8);
4344 let mut nes = Nes::from_rom(&rom).expect("boot");
4345 assert_eq!(nes.ppu_revision(), PpuRevision::Rp2c02H);
4346 assert_eq!(nes.power_up_palette(), PaletteInit::Zeroed);
4347
4348 // Select the opt-in revision + Blargg palette; both must persist across a
4349 // power-cycle (the bus re-applies them after rebuilding the PPU).
4350 nes.set_ppu_revision(PpuRevision::Rp2c02G);
4351 nes.set_power_up_palette(PaletteInit::Blargg);
4352 nes.power_cycle();
4353 assert_eq!(
4354 nes.ppu_revision(),
4355 PpuRevision::Rp2c02G,
4356 "revision survives power-cycle"
4357 );
4358 assert_eq!(
4359 nes.power_up_palette(),
4360 PaletteInit::Blargg,
4361 "palette survives power-cycle"
4362 );
4363 }
4364
4365 /// v2.9.8 — a ROM that writes PPUCTRL and PPUMASK exactly once, as its
4366 /// first four instructions, then idles. Whether those writes land is the
4367 /// whole observable difference between the two console models at power-on.
4368 ///
4369 /// ```text
4370 /// C000: A9 90 LDA #$90 ; NMI on, BG pattern table $1000
4371 /// C002: 8D 00 20 STA $2000
4372 /// C005: A9 01 LDA #$01 ; greyscale only: rendering stays off
4373 /// C007: 8D 01 20 STA $2001
4374 /// C00A: 4C 0A C0 JMP $C00A
4375 /// C00D: 40 RTI ; NMI handler
4376 /// ```
4377 fn one_shot_ppu_write_rom() -> Vec<u8> {
4378 // (Two frames are run per check below, not one: the machine powers up
4379 // with the PPU at the end of the pre-render line, so the first
4380 // `run_frame` completes within a few cycles, before these writes.)
4381 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
4382 bytes[0..4].copy_from_slice(b"NES\x1A");
4383 bytes[4] = 1; // 1x16 KiB PRG, CHR-RAM
4384 let prg = &mut bytes[16..];
4385 prg[0..14].copy_from_slice(&[
4386 0xA9, 0x90, 0x8D, 0x00, 0x20, 0xA9, 0x01, 0x8D, 0x01, 0x20, 0x4C, 0x0A, 0xC0, 0x40,
4387 ]);
4388 let len = prg.len();
4389 prg[len - 6] = 0x0D; // NMI -> $C00D (RTI)
4390 prg[len - 5] = 0xC0;
4391 prg[len - 4] = 0x00; // RESET -> $C000
4392 prg[len - 3] = 0xC0;
4393 prg[len - 2] = 0x0A; // IRQ -> $C00A
4394 prg[len - 1] = 0xC0;
4395 bytes
4396 }
4397
4398 fn run_frames(nes: &mut Nes, n: u32) {
4399 for _ in 0..n {
4400 let _ = nes.run_frame();
4401 }
4402 }
4403
4404 /// v2.9.8 — the console model's two documented effects, from `NESdev` "PPU
4405 /// power up state" (§Famicom and the front-/top-loader note):
4406 ///
4407 /// 1. At power-on the NES ignores `$2000`/`$2001` for ~29,658 CPU cycles,
4408 /// so a write issued in the first few cycles is lost; on the Famicom the
4409 /// PPU left reset about one frame earlier, so the same write lands.
4410 /// 2. The Reset button resets the PPU on the NES (PPUCTRL cleared, the
4411 /// warm-up window re-armed) and does not reach it on the Famicom.
4412 #[test]
4413 fn famicom_console_model_ppu_leaves_reset_before_the_cpu() {
4414 let rom = one_shot_ppu_write_rom();
4415
4416 // Default (NES): the model is NES, and the one-shot writes are dropped
4417 // inside the warm-up window — the established behaviour.
4418 let mut nes = Nes::from_rom(&rom).expect("boot");
4419 assert_eq!(nes.console_model(), ConsoleModel::Nes);
4420 run_frames(&mut nes, 2);
4421 assert_eq!(
4422 nes.bus().ppu().debug_registers()[..2],
4423 [0x00, 0x00],
4424 "NES: writes inside the warm-up window are ignored"
4425 );
4426
4427 // Famicom, selected straight after construction the way the frontend
4428 // applies its config: the same writes land.
4429 let mut fc = Nes::from_rom(&rom).expect("boot");
4430 fc.set_console_model(ConsoleModel::Famicom);
4431 assert_eq!(fc.bus().ppu().warmup_cycles_remaining(), 0);
4432 run_frames(&mut fc, 2);
4433 assert_eq!(
4434 fc.bus().ppu().debug_registers()[..2],
4435 [0x90, 0x01],
4436 "Famicom: the PPU is past its warm-up when the CPU starts"
4437 );
4438
4439 // Reset reaches only the CPU on a Famicom: PPUCTRL/PPUMASK survive and
4440 // no window is re-armed.
4441 fc.reset();
4442 assert_eq!(fc.bus().ppu().debug_registers()[..2], [0x90, 0x01]);
4443 assert_eq!(fc.bus().ppu().warmup_cycles_remaining(), 0);
4444
4445 // On the NES, Reset clears PPUCTRL/PPUMASK and re-arms the window.
4446 let mut nes = Nes::from_rom(&rom).expect("boot");
4447 nes.set_console_model(ConsoleModel::Famicom);
4448 run_frames(&mut nes, 2);
4449 assert_eq!(nes.bus().ppu().debug_registers()[..2], [0x90, 0x01]);
4450 nes.set_console_model(ConsoleModel::Nes);
4451 nes.reset();
4452 assert_eq!(nes.bus().ppu().debug_registers()[..2], [0x00, 0x00]);
4453 assert!(nes.bus().ppu().warmup_cycles_remaining() > 29_000);
4454
4455 // The selection survives a power cycle and is applied to the rebuilt
4456 // PPU before the CPU's first instruction.
4457 fc.power_cycle();
4458 assert_eq!(fc.console_model(), ConsoleModel::Famicom);
4459 assert_eq!(fc.bus().ppu().warmup_cycles_remaining(), 0);
4460 run_frames(&mut fc, 2);
4461 assert_eq!(fc.bus().ppu().debug_registers()[..2], [0x90, 0x01]);
4462 }
4463
4464 #[test]
4465 fn nes_run_frame_completes_and_returns_framebuffer() {
4466 let rom = synth_nrom(16, 8);
4467 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
4468 let fb = nes.run_frame();
4469 assert_eq!(fb.len(), 256 * 240 * 4);
4470 }
4471
4472 #[test]
4473 fn nes_run_two_frames_distinct_completion_latches() {
4474 let rom = synth_nrom(16, 8);
4475 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
4476 nes.run_frame();
4477 let cycles_after_one = nes.cycle();
4478 nes.run_frame();
4479 let cycles_after_two = nes.cycle();
4480 assert!(cycles_after_two > cycles_after_one);
4481 }
4482
4483 #[test]
4484 fn nes_determinism_two_runs_match() {
4485 // T-24-002: same ROM + zero input + 60 frames -> bit-identical
4486 // framebuffer hash via FNV-1a.
4487 fn hash_fb(fb: &[u8]) -> u64 {
4488 let mut h: u64 = 0xCBF2_9CE4_8422_2325;
4489 for &b in fb {
4490 h ^= u64::from(b);
4491 h = h.wrapping_mul(0x0000_0100_0000_01B3);
4492 }
4493 h
4494 }
4495 let rom = synth_nrom(16, 8);
4496 let mut a = Nes::from_rom(&rom).unwrap();
4497 let mut b = Nes::from_rom(&rom).unwrap();
4498 let frames = 4;
4499 let mut hash_a = 0u64;
4500 let mut hash_b = 0u64;
4501 for _ in 0..frames {
4502 hash_a = hash_fb(a.run_frame());
4503 hash_b = hash_fb(b.run_frame());
4504 }
4505 assert_eq!(
4506 hash_a, hash_b,
4507 "two runs must produce identical framebuffer"
4508 );
4509 }
4510
4511 fn fnv_hash(bytes: &[u8]) -> u64 {
4512 let mut h: u64 = 0xCBF2_9CE4_8422_2325;
4513 for &b in bytes {
4514 h ^= u64::from(b);
4515 h = h.wrapping_mul(0x0000_0100_0000_01B3);
4516 }
4517 h
4518 }
4519
4520 #[test]
4521 fn snapshot_round_trip_preserves_framebuffer_and_cycle() {
4522 let rom = synth_nrom(16, 8);
4523 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
4524 for _ in 0..4 {
4525 nes.run_frame();
4526 }
4527 let cycle = nes.cycle();
4528 let fb_hash_before = fnv_hash(nes.framebuffer());
4529 let blob = nes.snapshot();
4530
4531 // Drift the emulator forward 4 more frames so it looks different.
4532 for _ in 0..4 {
4533 nes.run_frame();
4534 }
4535 assert_ne!(nes.cycle(), cycle, "drift must move us off the snapshot");
4536
4537 nes.restore(&blob).expect("restore");
4538 assert_eq!(nes.cycle(), cycle);
4539 assert_eq!(fnv_hash(nes.framebuffer()), fb_hash_before);
4540 }
4541
4542 // ---------------------------------------------------------------------
4543 // Cartridge-RAM save-state sweep (core audit v2.9.2 AUD-02 and its
4544 // follow-up).
4545 //
4546 // The `.rns` container has no SRAM section: the `MAP ` section is the
4547 // mapper's own `save_state` blob and nothing else, so cartridge RAM
4548 // survives a save-state load, rewind step, run-ahead frame or netplay
4549 // rollback ONLY if the board writes it into that blob. AUD-02 found the
4550 // Konami VRC boards leaving theirs out; a one-off sweep then found the
4551 // same omission on boards outside that family. These tests are that sweep
4552 // made durable: they walk EVERY mapper id `rustynes_mappers::parse`
4553 // constructs, so a board added later is checked the day it lands rather
4554 // than the day its RAM goes missing in someone's rewind.
4555 // ---------------------------------------------------------------------
4556
4557 use alloc::{boxed::Box, string::String};
4558
4559 /// How a sweep image's header is encoded.
4560 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
4561 enum SweepHeader {
4562 /// iNES 1.0 (mapper ids 0-255 only). The parser defaults an iNES 1.0
4563 /// cart to 8 KiB PRG-RAM and, with no CHR-ROM, 8 KiB CHR-RAM.
4564 Ines1,
4565 /// NES 2.0 with this submapper, declaring 8 KiB battery PRG-NVRAM and,
4566 /// with no CHR-ROM, 8 KiB CHR-RAM. Covers ids 256-4095 and every
4567 /// submapper-selected variant of the lower ids.
4568 Nes2 { submapper: u8 },
4569 }
4570
4571 /// Synthetic cartridge image for mapper `mapper_id`: `prg_kib` KiB PRG,
4572 /// `chr_kib` KiB CHR-ROM (`0` = none, so the board allocates CHR-RAM),
4573 /// battery flag set so boards that gate `sram()` on the battery bit
4574 /// expose their `$6000-$7FFF` RAM. Every 8 KiB PRG bank ends in a vector
4575 /// table pointing at a `JMP $E000` idle loop, so whichever bank a board
4576 /// maps at `$E000` on power-on, the CPU spins harmlessly.
4577 fn synth_board_rom(
4578 mapper_id: u16,
4579 header: SweepHeader,
4580 prg_kib: usize,
4581 chr_kib: usize,
4582 ) -> Vec<u8> {
4583 let mut bytes = Vec::with_capacity(16 + (prg_kib + chr_kib) * 1024);
4584 bytes.extend_from_slice(b"NES\x1A");
4585 bytes.push(u8::try_from(prg_kib / 16).expect("PRG size fits the header"));
4586 bytes.push(u8::try_from(chr_kib / 8).expect("CHR size fits the header"));
4587 let [id_lo, id_hi] = mapper_id.to_le_bytes();
4588 bytes.push(((id_lo & 0x0F) << 4) | 0x02); // flags6: battery
4589 match header {
4590 SweepHeader::Ines1 => {
4591 assert_eq!(id_hi, 0, "iNES 1.0 carries 8-bit mapper ids only");
4592 bytes.push(id_lo & 0xF0); // flags7: mapper high nibble
4593 bytes.extend_from_slice(&[0u8; 8]);
4594 }
4595 SweepHeader::Nes2 { submapper } => {
4596 bytes.push((id_lo & 0xF0) | 0x08); // flags7: NES 2.0 marker
4597 bytes.push((submapper << 4) | (id_hi & 0x0F)); // byte 8
4598 bytes.push(0); // byte 9: ROM size MSBs
4599 bytes.push(0x70); // byte 10: 8 KiB (64 << 7) battery PRG-NVRAM
4600 bytes.push(if chr_kib == 0 { 0x07 } else { 0x00 }); // byte 11: CHR-RAM
4601 bytes.extend_from_slice(&[0u8; 4]); // bytes 12-15: NTSC, no Vs.
4602 }
4603 }
4604 let mut prg = vec![0u8; prg_kib * 1024];
4605 for bank in prg.chunks_mut(8 * 1024) {
4606 bank[0] = 0x4C; // JMP $E000
4607 bank[1] = 0x00;
4608 bank[2] = 0xE0;
4609 let len = bank.len();
4610 for v in [len - 6, len - 4, len - 2] {
4611 bank[v] = 0x00;
4612 bank[v + 1] = 0xE0;
4613 }
4614 }
4615 bytes.extend_from_slice(&prg);
4616 bytes.extend_from_slice(&vec![0u8; chr_kib * 1024]);
4617 bytes
4618 }
4619
4620 /// Result of trying to build one sweep configuration.
4621 enum SweepBoot {
4622 /// `parse` does not know the mapper id at all.
4623 Unsupported,
4624 /// Built with the first image shape the board accepted.
4625 Built(Box<Nes>),
4626 /// The id is known but no image shape was accepted (last error).
4627 Refused(String),
4628 }
4629
4630 /// Build `mapper_id` under `header`, trying the image shapes in turn
4631 /// until the board's constructor accepts one. Most boards take the first
4632 /// (128 KiB PRG, the shape AUD-02's VRC pins used); a board with a fixed
4633 /// PRG size (NROM's 16/32 KiB, a 32 KiB-only discrete board) takes a later
4634 /// one. RAM sizes come from the header, not the ROM size, so the shape
4635 /// does not change what RAM the board allocates.
4636 fn sweep_boot(mapper_id: u16, header: SweepHeader, chr_ram: bool) -> SweepBoot {
4637 const PRG_KIB: [usize; 8] = [128, 32, 512, 256, 64, 16, 1024, 2048];
4638 const CHR_ROM_KIB: [usize; 5] = [128, 8, 256, 512, 1024];
4639 let chr_shapes: &[usize] = if chr_ram { &[0] } else { &CHR_ROM_KIB };
4640 let mut last = String::new();
4641 for &prg in &PRG_KIB {
4642 for &chr in chr_shapes {
4643 match Nes::from_rom(&synth_board_rom(mapper_id, header, prg, chr)) {
4644 Ok(nes) => return SweepBoot::Built(Box::new(nes)),
4645 Err(RomError::UnsupportedMapper(_)) => return SweepBoot::Unsupported,
4646 Err(e) => last = alloc::format!("{prg} KiB PRG / {chr} KiB CHR: {e}"),
4647 }
4648 }
4649 }
4650 SweepBoot::Refused(last)
4651 }
4652
4653 /// Byte `i` of the sweep's position-dependent pattern, `seed` keeping
4654 /// the PRG and CHR patterns distinct. Position-dependent so a shifted,
4655 /// truncated or aliased copy cannot pass for the real thing.
4656 fn sweep_pattern(i: usize, seed: u8) -> u8 {
4657 let le = i.to_le_bytes();
4658 le[0] ^ seed ^ le[1].rotate_left(3)
4659 }
4660
4661 /// Where a probe found RAM.
4662 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
4663 enum RamSite {
4664 /// PRG-RAM exposed through `Mapper::sram` (the whole buffer).
4665 PrgSram,
4666 /// PRG-RAM reachable at `$6000-$7FFF` but NOT exposed through
4667 /// `sram()` -- checked through the CPU window instead.
4668 PrgWindow,
4669 /// Writable CHR memory reachable at PPU `$0000-$1FFF`.
4670 ChrRam,
4671 }
4672
4673 /// Describe the mismatch between two equal-length buffers, or `None`.
4674 fn sweep_diff(want: &[u8], got: &[u8]) -> Option<String> {
4675 let bad = want.iter().zip(got).filter(|(a, b)| a != b).count();
4676 let first = want.iter().zip(got).position(|(a, b)| a != b)?;
4677 Some(alloc::format!(
4678 "{bad} of {} bytes differ, first at +{first:#06x} (want {:#04x}, got {:#04x})",
4679 want.len(),
4680 want[first],
4681 got[first]
4682 ))
4683 }
4684
4685 /// PRG-RAM round trip through the whole-machine snapshot. Returns the
4686 /// site probed (`None` when the board has no PRG-RAM the probe can reach)
4687 /// and the mismatch, if any.
4688 ///
4689 /// A board that exposes `sram()` is checked on the whole buffer, so RAM
4690 /// the CPU window cannot currently see (an unmapped page of a 32 KiB
4691 /// board, say) is covered too. A board that does not is probed at
4692 /// `$6000-$7FFF`: write the pattern, and if at least 2 KiB of it reads
4693 /// back (the smallest cartridge RAM; a mirrored 2 KiB part returns only
4694 /// its last alias), treat it as RAM and round-trip the window.
4695 fn sweep_prg_ram(nes: &mut Nes) -> (Option<RamSite>, Option<String>) {
4696 if !nes.sram().is_empty() {
4697 for (i, b) in nes.sram_mut().iter_mut().enumerate() {
4698 *b = sweep_pattern(i, 0xA5);
4699 }
4700 let want = nes.sram().to_vec();
4701 let blob = nes.snapshot();
4702 // Scribble with the complement, so every byte differs from what
4703 // the snapshot must bring back.
4704 for b in nes.sram_mut() {
4705 *b = !*b;
4706 }
4707 if let Err(e) = nes.restore(&blob) {
4708 return (
4709 Some(RamSite::PrgSram),
4710 Some(alloc::format!("restore: {e:?}")),
4711 );
4712 }
4713 return (Some(RamSite::PrgSram), sweep_diff(&want, nes.sram()));
4714 }
4715 let window = 0x6000u16..0x8000;
4716 for a in window.clone() {
4717 nes.bus
4718 .mapper
4719 .cpu_write(a, sweep_pattern(usize::from(a - 0x6000), 0xA5));
4720 }
4721 // Snapshot BEFORE reading back: the read below and the one after the
4722 // restore then both start from the snapshot's state, so a board whose
4723 // reads move state cannot make a correct restore look wrong.
4724 let blob = nes.snapshot();
4725 let want: Vec<u8> = window.clone().map(|a| nes.bus.mapper.cpu_read(a)).collect();
4726 let echoed = want
4727 .iter()
4728 .enumerate()
4729 .filter(|&(i, &b)| b == sweep_pattern(i, 0xA5))
4730 .count();
4731 if echoed < 0x800 {
4732 return (None, None);
4733 }
4734 for (a, w) in window.clone().zip(&want) {
4735 nes.bus.mapper.cpu_write(a, !w);
4736 }
4737 if let Err(e) = nes.restore(&blob) {
4738 return (
4739 Some(RamSite::PrgWindow),
4740 Some(alloc::format!("restore: {e:?}")),
4741 );
4742 }
4743 let got: Vec<u8> = window.map(|a| nes.bus.mapper.cpu_read(a)).collect();
4744 (Some(RamSite::PrgWindow), sweep_diff(&want, &got))
4745 }
4746
4747 /// v3.1.0 — `debug_peek_ppu` is the debugger's and the HD-pack
4748 /// compositor's "side-effect-free" CHR read. On the five boards whose CHR
4749 /// reads change them (`Mapper::chr_reads_are_pure`), it used to flip the
4750 /// board: reading all of CHR on MMC2 or MMC4 (the pattern viewer does)
4751 /// passes tiles `$FD`/`$FE` and switches a CHR latch, so opening a debugger
4752 /// panel, or hashing a tile for an HD pack, changed the game. Every board's
4753 /// whole-machine state must be unchanged by a full sweep of peeks.
4754 #[test]
4755 fn debug_peek_ppu_changes_no_board() {
4756 // The five impure families' ids, and MMC3 (4) as a pure control.
4757 for id in [9u16, 10, 35, 90, 96, 163, 209, 211, 4] {
4758 let rom = synth_board_rom(id, SweepHeader::Ines1, 128, 128);
4759 let Ok(mut nes) = Nes::from_rom(&rom) else {
4760 panic!("mapper {id} builds");
4761 };
4762 nes.run_frame();
4763 let before = nes.snapshot();
4764 for a in 0u16..0x2000 {
4765 let _ = nes.bus.debug_peek_ppu(a);
4766 }
4767 let after = nes.snapshot();
4768 assert!(
4769 before == after,
4770 "mapper {id}: peeking CHR changed the machine ({} differing snapshot bytes)",
4771 before.iter().zip(&after).filter(|(a, b)| a != b).count()
4772 );
4773 }
4774 }
4775
4776 /// CHR-RAM round trip through the whole-machine snapshot, through PPU
4777 /// `$0000-$1FFF` (there is no raw CHR accessor on `Mapper`). Returns
4778 /// `None` for the site when fewer than 1 KiB of the pattern reads back,
4779 /// i.e. the board has no writable CHR (a CHR-ROM board).
4780 ///
4781 /// Only the 8 KiB the power-on banking maps is checked; a board with more
4782 /// CHR-RAM than that is checked on its visible part. Every write lands
4783 /// before the snapshot and every read after it, from the same state on
4784 /// both sides: MMC2 and MMC4 flip their CHR latches on PPU reads of
4785 /// `$0FD8`/`$0FE8`, so a read sequence started from different latch
4786 /// states would compare different banks and fail a correct restore.
4787 fn sweep_chr_ram(nes: &mut Nes) -> (Option<RamSite>, Option<String>) {
4788 for a in 0u16..0x2000 {
4789 nes.bus
4790 .mapper
4791 .ppu_write(a, sweep_pattern(usize::from(a), 0x3C));
4792 }
4793 let blob = nes.snapshot();
4794 let want: Vec<u8> = (0u16..0x2000).map(|a| nes.bus.debug_peek_ppu(a)).collect();
4795 let echoed = want
4796 .iter()
4797 .enumerate()
4798 .filter(|&(i, &b)| b == sweep_pattern(i, 0x3C))
4799 .count();
4800 if echoed < 0x400 {
4801 return (None, None);
4802 }
4803 for (a, w) in (0u16..0x2000).zip(&want) {
4804 nes.bus.mapper.ppu_write(a, !w);
4805 }
4806 if let Err(e) = nes.restore(&blob) {
4807 return (
4808 Some(RamSite::ChrRam),
4809 Some(alloc::format!("restore: {e:?}")),
4810 );
4811 }
4812 let got: Vec<u8> = (0u16..0x2000).map(|a| nes.bus.debug_peek_ppu(a)).collect();
4813 (Some(RamSite::ChrRam), sweep_diff(&want, &got))
4814 }
4815
4816 /// Mapper ids `parse` knows but cannot build under ANY sweep
4817 /// configuration, each with the reason. A board on this list is excluded
4818 /// from the sweep by name, never silently.
4819 const SWEEP_UNBUILDABLE: &[(u16, &str)] = &[];
4820
4821 /// The sweep's `--nocapture` report: what was checked where, which built
4822 /// boards had no RAM the probes could reach, and which configurations a
4823 /// board refused (a CHR-ROM-only board refusing a CHR-RAM image, a
4824 /// fixed-size board refusing the larger PRG shapes). Printed, not
4825 /// asserted, so a reader can see the sweep's reach on every run.
4826 fn sweep_print_report(
4827 supported: &alloc::collections::BTreeSet<u16>,
4828 built: &alloc::collections::BTreeSet<u16>,
4829 checked: &alloc::collections::BTreeMap<u16, alloc::collections::BTreeSet<RamSite>>,
4830 refusals: &alloc::collections::BTreeMap<u16, Vec<String>>,
4831 ) {
4832 let no_ram: Vec<u16> = built
4833 .iter()
4834 .copied()
4835 .filter(|m| !checked.contains_key(m))
4836 .collect();
4837 std::println!(
4838 "cartridge-RAM sweep: {} supported ids, {} built, {} with RAM checked",
4839 supported.len(),
4840 built.len(),
4841 checked.len()
4842 );
4843 for site in [RamSite::PrgSram, RamSite::PrgWindow, RamSite::ChrRam] {
4844 let ids: Vec<u16> = checked
4845 .iter()
4846 .filter(|(_, s)| s.contains(&site))
4847 .map(|(m, _)| *m)
4848 .collect();
4849 std::println!(" {site:?} ({}): {ids:?}", ids.len());
4850 }
4851 std::println!(" no RAM reachable ({}): {no_ram:?}", no_ram.len());
4852 for (m, why) in refusals {
4853 std::println!(
4854 " mapper {m}: {} configuration(s) refused, e.g. {}",
4855 why.len(),
4856 why[0]
4857 );
4858 }
4859 }
4860
4861 /// Core audit v2.9.2 AUD-02 and its follow-up: every board's PRG-RAM and
4862 /// CHR-RAM must survive a whole-machine `snapshot` / `restore`.
4863 ///
4864 /// Sweeps every mapper id 0-4095 (NES 2.0, all 16 submappers; iNES 1.0
4865 /// too for 0-255), each with CHR-ROM and with CHR-RAM. For every
4866 /// configuration that builds it fills the board's RAM with a pattern,
4867 /// snapshots the `Nes`, scribbles the RAM with the complement, restores
4868 /// and compares. Supersedes the VRC-only pins AUD-02 added
4869 /// (`vrc_boards_snapshot_carries_{prg,chr}_ram`), and asserts those
4870 /// boards are still among the ones checked, so the sweep can never pass
4871 /// by checking less.
4872 ///
4873 /// Outside the sweep by construction, not by omission: the FDS (mapper
4874 /// 20) and NSF players do not come through `parse` (they load through
4875 /// `Nes::from_disk` / `Nes::from_nsf`), and both write their RAM into
4876 /// their own blobs (the `save_state` of `fds.rs` and `nsf.rs`).
4877 ///
4878 /// What it cannot see: PRG-RAM a board neither exposes through `sram()`
4879 /// nor maps at `$6000-$7FFF` at power-on (RAM behind a board-specific
4880 /// enable register), and CHR-RAM beyond the 8 KiB visible at power-on.
4881 /// The `--nocapture` output lists which boards were checked where.
4882 #[test]
4883 fn every_board_snapshot_carries_cartridge_ram() {
4884 use alloc::collections::{BTreeMap, BTreeSet};
4885
4886 let mut supported: BTreeSet<u16> = BTreeSet::new();
4887 let mut built: BTreeSet<u16> = BTreeSet::new();
4888 let mut checked: BTreeMap<u16, BTreeSet<RamSite>> = BTreeMap::new();
4889 let mut failures: BTreeMap<(u16, RamSite), Vec<String>> = BTreeMap::new();
4890 let mut refusals: BTreeMap<u16, Vec<String>> = BTreeMap::new();
4891
4892 for mapper_id in 0u16..4096 {
4893 let mut headers = Vec::new();
4894 if mapper_id < 256 {
4895 headers.push(SweepHeader::Ines1);
4896 }
4897 headers.extend((0u8..16).map(|submapper| SweepHeader::Nes2 { submapper }));
4898 'headers: for header in headers {
4899 for chr_ram in [false, true] {
4900 let mut nes = match sweep_boot(mapper_id, header, chr_ram) {
4901 // An unknown id: no other header builds it either.
4902 SweepBoot::Unsupported => break 'headers,
4903 SweepBoot::Refused(e) => {
4904 supported.insert(mapper_id);
4905 refusals
4906 .entry(mapper_id)
4907 .or_default()
4908 .push(alloc::format!("{header:?} chr_ram={chr_ram}: {e}"));
4909 continue;
4910 }
4911 SweepBoot::Built(nes) => nes,
4912 };
4913 supported.insert(mapper_id);
4914 built.insert(mapper_id);
4915 let tag = alloc::format!("{header:?} chr_ram={chr_ram}");
4916 for (site, fail) in [sweep_prg_ram(&mut nes), sweep_chr_ram(&mut nes)] {
4917 let Some(site) = site else { continue };
4918 checked.entry(mapper_id).or_default().insert(site);
4919 if let Some(fail) = fail {
4920 failures
4921 .entry((mapper_id, site))
4922 .or_default()
4923 .push(alloc::format!("{tag}: {fail}"));
4924 }
4925 }
4926 }
4927 }
4928 }
4929
4930 sweep_print_report(&supported, &built, &checked, &refusals);
4931
4932 // Nothing is skipped silently: an id that never built is either on
4933 // the explicit list, with its reason, or a failure.
4934 let unbuildable: Vec<u16> = supported.difference(&built).copied().collect();
4935 let listed: Vec<u16> = SWEEP_UNBUILDABLE.iter().map(|&(m, _)| m).collect();
4936 assert_eq!(
4937 unbuildable, listed,
4938 "mapper ids that no sweep configuration builds must be listed in \
4939 SWEEP_UNBUILDABLE with a reason: {refusals:?}"
4940 );
4941
4942 // The sweep must keep covering what AUD-02 pinned by name (PRG-RAM on
4943 // the VRC boards 21-26/73/85, CHR-RAM on 21-26/85) and the boards its
4944 // follow-up fixed, or a regression in the probes could pass by
4945 // checking nothing.
4946 for m in [10u16, 21, 22, 23, 24, 25, 26, 73, 85] {
4947 assert!(
4948 checked
4949 .get(&m)
4950 .is_some_and(|s| s.contains(&RamSite::PrgSram)),
4951 "mapper {m}: PRG-RAM no longer checked through sram()"
4952 );
4953 }
4954 for m in [
4955 9u16, 10, 11, 19, 21, 22, 23, 24, 25, 26, 34, 69, 75, 85, 151,
4956 ] {
4957 assert!(
4958 checked
4959 .get(&m)
4960 .is_some_and(|s| s.contains(&RamSite::ChrRam)),
4961 "mapper {m}: CHR-RAM no longer checked"
4962 );
4963 }
4964
4965 let report: Vec<String> = failures
4966 .iter()
4967 .map(|((m, site), v)| {
4968 alloc::format!("mapper {m} {site:?}: {} config(s), e.g. {}", v.len(), v[0])
4969 })
4970 .collect();
4971 assert!(
4972 failures.is_empty(),
4973 "cartridge RAM not restored from the snapshot on {} board/site pair(s):\n{}",
4974 failures.len(),
4975 report.join("\n")
4976 );
4977 }
4978
4979 #[test]
4980 fn snapshot_is_deterministic_across_two_runs() {
4981 let rom = synth_nrom(16, 8);
4982 let mut a = Nes::from_rom(&rom).unwrap();
4983 let mut b = Nes::from_rom(&rom).unwrap();
4984 for _ in 0..3 {
4985 a.run_frame();
4986 b.run_frame();
4987 }
4988 assert_eq!(a.snapshot(), b.snapshot());
4989 }
4990
4991 #[test]
4992 fn snapshot_header_carries_rom_hash_tag() {
4993 let rom = synth_nrom(16, 8);
4994 let nes = Nes::from_rom(&rom).unwrap();
4995 let blob = nes.snapshot();
4996 let (h, _off) = save_state::parse_header(&blob).unwrap();
4997 assert_eq!(h.rom_hash_tag, nes.rom_hash_tag());
4998 }
4999
5000 /// v2.9.8 (ADR 0042): a `.rns` written by v2.9.7 or earlier carries
5001 /// container format 2 and is refused at the header with one typed error,
5002 /// before any section is looked at -- and the machine is left as it was.
5003 #[test]
5004 fn a_v2_9_7_container_is_refused_at_the_header() {
5005 let rom = synth_nrom(16, 8);
5006 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
5007 nes.run_frame();
5008 let mut old = nes.snapshot();
5009 let before = old.clone();
5010 // The container's format version is the u16 after the 8-byte magic.
5011 old[8..10].copy_from_slice(&2u16.to_le_bytes());
5012 let err = nes.restore(&old).unwrap_err();
5013 assert!(
5014 matches!(err, SnapshotError::FormatTooOld { got: 2, .. }),
5015 "expected FormatTooOld, got {err:?}"
5016 );
5017 assert_eq!(nes.snapshot(), before, "a refused load changed the machine");
5018 }
5019
5020 #[test]
5021 fn restore_rejects_pre_v3_cpu_section_version() {
5022 // ADR 0028 (v2.0.0 rc.1): a slot file whose CPU section predates the
5023 // one-clock promote (schema version < CPU_SNAPSHOT_VERSION) must be
5024 // cleanly rejected via SnapshotError::VersionMismatch, not silently
5025 // accepted or upconverted. Simulate an old slot by taking a
5026 // freshly-emitted (current-version) snapshot and patching only the
5027 // CPU section's version byte down to a stale value -- everything
5028 // else (the body bytes, every other section) is untouched, so this
5029 // isolates the version-gate behavior from any layout difference.
5030 let rom = synth_nrom(16, 8);
5031 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
5032 for _ in 0..3 {
5033 nes.run_frame();
5034 }
5035 let current = nes.snapshot();
5036 let (_h, body_off) = save_state::parse_header(¤t).unwrap();
5037 let mut stale = current[..body_off].to_vec();
5038 for s in save_state::SectionIter::new(¤t[body_off..]) {
5039 let s = s.unwrap();
5040 let version = if s.tag == save_state::tag::CPU {
5041 assert_eq!(
5042 s.version,
5043 rustynes_cpu::CPU_SNAPSHOT_VERSION,
5044 "fixture assumption: current build writes the current CPU version"
5045 );
5046 s.version - 1
5047 } else {
5048 s.version
5049 };
5050 save_state::write_section(&mut stale, s.tag, version, s.body);
5051 }
5052 let err = nes.restore(&stale).unwrap_err();
5053 assert!(
5054 matches!(
5055 err,
5056 SnapshotError::VersionMismatch { ref tag, .. } if tag == "CPU "
5057 ),
5058 "expected a CPU-tagged VersionMismatch, got {err:?}"
5059 );
5060 }
5061
5062 /// v3.0.0: a state from another release fails a section's version
5063 /// check, not the container's (v2.9.9's states carry PPU section 11,
5064 /// where v3.0.0 reads 12), and the message must say which way the
5065 /// versions differ. Until v3.0.0 it gave only the two numbers, which
5066 /// players read as a damaged file.
5067 #[test]
5068 fn a_state_from_another_release_says_older_or_newer() {
5069 let rom = synth_nrom(16, 8);
5070 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
5071 nes.run_frame();
5072 let current = nes.snapshot();
5073 let (_h, body_off) = save_state::parse_header(¤t).unwrap();
5074 for (delta, words) in [(-1i16, "older release"), (1, "newer release")] {
5075 let mut patched = current[..body_off].to_vec();
5076 for s in save_state::SectionIter::new(¤t[body_off..]) {
5077 let s = s.unwrap();
5078 let version = if s.tag == save_state::tag::PPU {
5079 u8::try_from(i16::from(s.version) + delta).unwrap()
5080 } else {
5081 s.version
5082 };
5083 save_state::write_section(&mut patched, s.tag, version, s.body);
5084 }
5085 let err = nes.restore(&patched).unwrap_err();
5086 let text = format!("{err}");
5087 assert!(
5088 matches!(err, SnapshotError::VersionMismatch { ref tag, .. } if tag == "PPU "),
5089 "expected a PPU VersionMismatch, got {err:?}"
5090 );
5091 assert!(text.contains(words), "{text}");
5092 }
5093 }
5094
5095 /// v2.7.4 (frontend audit MOB-08): a load that fails leaves the machine as
5096 /// it was. `restore_inner` applies the bus sections first and checks the
5097 /// CPU section after, so on v2.7.3 a blob rejected at the CPU stage left
5098 /// the bus from the blob and the CPU from the running game -- a machine
5099 /// that was neither, which the next frame then emulated. Every host hit
5100 /// it: desktop, libretro and both mobile apps. The rejected blob here is
5101 /// the stale-CPU-version one from the test above, taken at an earlier frame
5102 /// so its bus state really differs.
5103 #[test]
5104 fn a_failed_restore_leaves_the_machine_untouched() {
5105 let rom = synth_nrom(16, 8);
5106 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
5107 nes.run_frame();
5108 let earlier = nes.snapshot();
5109 for _ in 0..3 {
5110 nes.run_frame();
5111 }
5112 let before = nes.snapshot();
5113 assert_ne!(
5114 earlier, before,
5115 "the fixture must change state between frames"
5116 );
5117
5118 let (_h, body_off) = save_state::parse_header(&earlier).unwrap();
5119 let mut rejected = earlier[..body_off].to_vec();
5120 for s in save_state::SectionIter::new(&earlier[body_off..]) {
5121 let s = s.unwrap();
5122 let version = if s.tag == save_state::tag::CPU {
5123 s.version - 1
5124 } else {
5125 s.version
5126 };
5127 save_state::write_section(&mut rejected, s.tag, version, s.body);
5128 }
5129 assert!(nes.restore(&rejected).is_err());
5130 assert_eq!(nes.snapshot(), before, "a failed load changed the machine");
5131 // And it still runs as the same machine.
5132 nes.run_frame();
5133 }
5134
5135 /// `blob` with the version byte of its `CPU ` section decremented: a
5136 /// well-framed state that every stage before the CPU one accepts.
5137 fn with_stale_cpu_version(blob: &[u8]) -> Vec<u8> {
5138 let (_h, body_off) = save_state::parse_header(blob).unwrap();
5139 let mut out = blob[..body_off].to_vec();
5140 for s in save_state::SectionIter::new(&blob[body_off..]) {
5141 let s = s.unwrap();
5142 let version = if s.tag == save_state::tag::CPU {
5143 s.version - 1
5144 } else {
5145 s.version
5146 };
5147 save_state::write_section(&mut out, s.tag, version, s.body);
5148 }
5149 out
5150 }
5151
5152 /// `blob` with byte `at` of its `MAP ` section's body set to `value`.
5153 fn with_map_byte(blob: &[u8], at: usize, value: u8) -> Vec<u8> {
5154 let (_h, body_off) = save_state::parse_header(blob).unwrap();
5155 let mut out = blob[..body_off].to_vec();
5156 for s in save_state::SectionIter::new(&blob[body_off..]) {
5157 let s = s.unwrap();
5158 if s.tag == save_state::tag::MAP {
5159 let mut body = s.body.to_vec();
5160 body[at] = value;
5161 save_state::write_section(&mut out, s.tag, s.version, &body);
5162 } else {
5163 save_state::write_section(&mut out, s.tag, s.version, s.body);
5164 }
5165 }
5166 out
5167 }
5168
5169 /// v2.9.0 re-audit NC-02, at the whole-machine level: a GTROM (mapper 111)
5170 /// state carrying a bank the board cannot hold is refused by
5171 /// `Nes::restore`, and the machine keeps running. Before, `restore`
5172 /// returned `Ok(())` and the next CPU fetch from `$8000` panicked
5173 /// (`homebrew_boards.rs:570`, index 8,372,319 into 32 KiB in the
5174 /// re-audit's probe) — after the restore, so its rollback could not help.
5175 #[test]
5176 fn a_gtrom_state_with_an_impossible_bank_is_refused_and_the_game_runs_on() {
5177 let mut rom = synth_nrom(32, 0);
5178 rom[6] = 0xF0; // mapper low nibble F
5179 rom[7] = 0x60; // mapper high nibble 6: 0x6F = 111
5180 let mut donor = Nes::from_rom(&rom).expect("GTROM image");
5181 donor.run_frame();
5182 donor.run_frame();
5183 let good = donor.snapshot();
5184 // MAP body: version, prg_bank, chr_bank, nt_bank, ...
5185 for (at, value) in [(1, 0xFF), (2, 0xFF), (3, 0xFF)] {
5186 let bad = with_map_byte(&good, at, value);
5187 let mut nes = Nes::from_rom(&rom).unwrap();
5188 nes.run_frame();
5189 let before = nes.snapshot();
5190 assert!(
5191 nes.restore(&bad).is_err(),
5192 "MAP byte {at} = {value:#04x} must be refused"
5193 );
5194 assert!(
5195 nes.snapshot() == before,
5196 "a refused load changed the machine"
5197 );
5198 nes.run_frame();
5199 nes.run_frame();
5200 }
5201 }
5202
5203 /// v2.9.0 re-audit NC-03 / NL-01: the QUIET restore is all-or-nothing too.
5204 ///
5205 /// v2.7.4 gave only the loud path a rollback, on the premise that a quiet
5206 /// restore "only ever restore[s] snapshots this core just wrote, which
5207 /// cannot fail these checks". libretro breaks that premise: every
5208 /// `retro_unserialize` -- a user's Load State, a state from an older core,
5209 /// a corrupt file -- goes through `restore_quiet`. The re-audit's probe
5210 /// showed a rejected CPU section leaving the bus, PPU, APU and mapper from
5211 /// the rejected file (frame 3000) under the running game's CPU (frame 5).
5212 ///
5213 /// Two rejection points are pinned, because they fail at different depths:
5214 /// the CPU section's version (after all four bus sections applied) and the
5215 /// cross-section clock check (after the CPU applied as well). Both must
5216 /// leave the machine byte-identical and the rewind ring untouched.
5217 #[test]
5218 fn a_failed_quiet_restore_leaves_the_machine_untouched() {
5219 let rom = synth_nrom(16, 8);
5220 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
5221 nes.enable_rewind_with(2 * 1024 * 1024, 1);
5222 nes.run_frame();
5223 nes.run_frame();
5224 let earlier = nes.snapshot();
5225 for _ in 0..3 {
5226 nes.run_frame();
5227 }
5228 let before = nes.snapshot();
5229 let ring_before = nes.rewind.as_ref().map(RewindRing::len);
5230 assert_ne!(
5231 earlier, before,
5232 "the fixture must change state between frames"
5233 );
5234
5235 // A CPU/PPU clock skew the clock check rejects, carried by an
5236 // otherwise valid EARLIER state: every section decodes, so this fails
5237 // at the very last stage.
5238 let skewed = {
5239 let mut other = Nes::from_rom(&rom).unwrap();
5240 other.run_frame();
5241 other.run_frame();
5242 let far = other.cpu.master_clock() + (1 << 40);
5243 other.bus_mut().set_ppu_clock_for_test(far);
5244 other.snapshot()
5245 };
5246
5247 for (label, blob) in [
5248 ("stale CPU version", with_stale_cpu_version(&earlier)),
5249 ("CPU/PPU clock skew", skewed),
5250 ] {
5251 assert!(nes.restore_quiet(&blob).is_err(), "{label}: must reject");
5252 // `assert!` rather than `assert_eq!`: a failure would otherwise
5253 // print two ~300 KB byte arrays.
5254 assert!(
5255 nes.snapshot() == before,
5256 "{label}: a failed quiet restore changed the machine"
5257 );
5258 assert_eq!(
5259 nes.rewind.as_ref().map(RewindRing::len),
5260 ring_before,
5261 "{label}: a quiet restore must leave the rewind ring alone"
5262 );
5263 }
5264 // And it still runs as the same machine.
5265 nes.run_frame();
5266 }
5267
5268 #[test]
5269 fn rewind_step_back_restores_prior_frame() {
5270 let rom = synth_nrom(16, 8);
5271 let mut nes = Nes::from_rom(&rom).unwrap();
5272 nes.enable_rewind_with(2 * 1024 * 1024, 1);
5273 for _ in 0..6 {
5274 nes.run_frame();
5275 }
5276 let cycle_at_6 = nes.cycle();
5277 nes.run_frame();
5278 nes.run_frame();
5279 nes.run_frame();
5280 // 3 entries on the ring (frames 6..=8 captured at the END of each
5281 // run_frame — frame 5 was captured in the loop above).
5282 assert!(nes.rewind_step_back(), "first step back");
5283 assert!(nes.rewind_step_back(), "second step back");
5284 assert!(nes.rewind_step_back(), "third step back");
5285 // We've rewound past the 3 extra frames; cycle should equal the
5286 // state we captured at the end of frame 6 (i.e. frame 5's snap).
5287 assert_ne!(nes.cycle(), cycle_at_6, "captured frame 5, not frame 6");
5288 }
5289
5290 // ---- v2.4.0 item B — the timeline generation counter ----
5291
5292 /// A LOUD restore is a timeline jump and must bump the generation.
5293 ///
5294 /// This is the defect the counter exists for: v2.3.9 cleared stale debug
5295 /// telemetry on a ROM change and could not clear it on a save-state load,
5296 /// because two of the four jump paths are not reachable from a patchable
5297 /// frontend call site.
5298 #[test]
5299 fn a_loud_restore_bumps_the_timeline_generation() {
5300 let rom = synth_nrom(16, 8);
5301 let mut nes = Nes::from_rom(&rom).unwrap();
5302 nes.run_frame();
5303 let blob = nes.snapshot();
5304 let before = nes.timeline_generation();
5305 nes.run_frame();
5306 nes.restore(&blob).expect("restore");
5307 assert!(
5308 nes.timeline_generation() > before,
5309 "a user-driven load did not register as a timeline jump"
5310 );
5311 }
5312
5313 /// A QUIET restore is the SAME timeline and must NOT bump.
5314 ///
5315 /// Run-ahead restores every frame and netplay rollback restores on every
5316 /// correction. Bumping here would clear a consumer's telemetry sixty times a
5317 /// second — worse than the stale-telemetry defect the counter fixes.
5318 #[test]
5319 fn a_quiet_restore_does_not_bump_the_timeline_generation() {
5320 let rom = synth_nrom(16, 8);
5321 let mut nes = Nes::from_rom(&rom).unwrap();
5322 nes.run_frame();
5323 let blob = nes.snapshot();
5324 let before = nes.timeline_generation();
5325 nes.run_frame();
5326 nes.restore_quiet(&blob).expect("quiet restore");
5327 assert_eq!(
5328 nes.timeline_generation(),
5329 before,
5330 "a same-timeline restore was reported as a jump; under run-ahead this \
5331 fires every frame"
5332 );
5333 }
5334
5335 /// Rewind is a jump, and it reaches the counter without its own call site.
5336 #[test]
5337 fn rewind_bumps_the_timeline_generation() {
5338 let rom = synth_nrom(16, 8);
5339 let mut nes = Nes::from_rom(&rom).unwrap();
5340 nes.enable_rewind_with(2 * 1024 * 1024, 1);
5341 for _ in 0..4 {
5342 nes.run_frame();
5343 }
5344 let before = nes.timeline_generation();
5345 assert!(nes.rewind_step_back(), "step back");
5346 assert!(
5347 nes.timeline_generation() > before,
5348 "rewind did not register as a timeline jump"
5349 );
5350 }
5351
5352 /// Reset and power-cycle are discontinuities too.
5353 #[test]
5354 fn reset_and_power_cycle_bump_the_timeline_generation() {
5355 let rom = synth_nrom(16, 8);
5356 let mut nes = Nes::from_rom(&rom).unwrap();
5357 let a = nes.timeline_generation();
5358 nes.reset();
5359 let b = nes.timeline_generation();
5360 assert!(b > a, "warm reset did not bump");
5361 nes.power_cycle();
5362 assert!(nes.timeline_generation() > b, "power cycle did not bump");
5363 }
5364
5365 /// v2.9.8 — a power cycle keeps every host setting stored on the PPU and
5366 /// the APU, on a bare `Nes` with no host to re-push anything.
5367 ///
5368 /// `Nes::power_cycle` rebuilds both chips, and until v2.9.8 each of these
5369 /// reverted to its default there: the desktop re-pushed them after the
5370 /// cycle, the movie power-on (`power_on_for_movie`), libretro and mobile
5371 /// paths did not. One row per setting, each set to a NON-default value,
5372 /// so a row that reverts fails on its own.
5373 #[test]
5374 fn a_power_cycle_keeps_every_ppu_and_apu_setting() {
5375 type Setting = (&'static str, fn(&mut Nes), fn(&Nes) -> bool);
5376 const PAL: [[u8; 3]; 64] = [[0x12, 0x34, 0x56]; 64];
5377 const GAIN: [f32; 6] = [0.5, 1.5, 0.25, 2.0, 0.0, 0.75];
5378 let rows: [Setting; 7] = [
5379 (
5380 "custom palette",
5381 |n| n.set_custom_palette(Some(PAL)),
5382 |n| n.custom_palette() == Some(PAL),
5383 ),
5384 (
5385 "extra scanlines",
5386 |n| n.set_extra_scanlines(7),
5387 |n| n.extra_scanlines() == 7,
5388 ),
5389 (
5390 "fast dot path (off; on is the default)",
5391 |n| n.set_fast_dotloop(false),
5392 |n| !n.fast_dotloop(),
5393 ),
5394 (
5395 "OAM decay",
5396 |n| n.set_oam_decay(true),
5397 |n| n.oam_decay_enabled(),
5398 ),
5399 (
5400 "APU channel mask",
5401 |n| n.set_apu_channel_mask(0x15),
5402 |n| n.apu_channel_mask() == 0x15,
5403 ),
5404 (
5405 "APU channel gain",
5406 |n| n.set_apu_channel_gain(GAIN),
5407 |n| n.apu_channel_gain() == GAIN,
5408 ),
5409 (
5410 "APU filter model",
5411 |n| n.set_apu_filter_model(rustynes_apu::FilterModel::Famicom),
5412 |n| n.apu_filter_model() == rustynes_apu::FilterModel::Famicom,
5413 ),
5414 ];
5415 let rom = synth_nrom(16, 8);
5416 let mut lost = Vec::new();
5417 for (name, set, holds) in rows {
5418 let mut nes = Nes::from_rom(&rom).unwrap();
5419 assert!(!holds(&nes), "{name}: premise -- the default differs");
5420 set(&mut nes);
5421 assert!(holds(&nes), "{name}: the setter applies it");
5422 nes.run_frame();
5423 nes.power_cycle();
5424 if !holds(&nes) {
5425 lost.push(name);
5426 }
5427 }
5428 // Every row is checked before failing, so a regression names every
5429 // setting it drops rather than only the first.
5430 assert!(lost.is_empty(), "lost across a power cycle: {lost:?}");
5431 }
5432
5433 /// v2.9.8 — the kept settings are not just remembered, they are in force:
5434 /// a power-cycled console with them set produces the frame and the audio a
5435 /// FRESH console with the same settings produces (`power_cycle == fresh
5436 /// boot`, with the host's configuration held constant). The palette and
5437 /// the filter change what is emitted, so a setting that was only stored,
5438 /// and not applied to the rebuilt chip, fails here.
5439 ///
5440 /// The channel gain and the OAM-decay model are left out on purpose, and
5441 /// are covered by the table above instead: a FRESH console can only
5442 /// receive a setting after `from_rom`'s reset sequence has run its first
5443 /// cycles at the default, whereas the power-cycled console runs those
5444 /// cycles with the setting already in force. For the gain that moves the
5445 /// last bits of the audio; for OAM decay, enabling the model stamps every
5446 /// row's age with the current cycle, which is 0 on the rebuilt PPU and a
5447 /// few cycles later on the fresh one, so the serialized ages differ. Both
5448 /// differences are the fix working. (Measured for the gain: applying it
5449 /// to both consoles after the cycle matches, carrying it through does not.
5450 /// For decay: the test passes with it removed and fails with it present.)
5451 #[test]
5452 fn a_power_cycled_console_with_settings_runs_as_a_fresh_one() {
5453 fn configure(n: &mut Nes) {
5454 n.set_custom_palette(Some([[0x40, 0x80, 0xC0]; 64]));
5455 n.set_apu_filter_model(rustynes_apu::FilterModel::Clean);
5456 }
5457 let rom = include_bytes!("../../../tests/roms/nestest/nestest.nes");
5458 let mut cycled = Nes::from_rom(rom).unwrap();
5459 configure(&mut cycled);
5460 for _ in 0..5 {
5461 cycled.run_frame();
5462 }
5463 let _ = cycled.drain_audio();
5464 cycled.power_cycle();
5465 let mut fresh = Nes::from_rom(rom).unwrap();
5466 configure(&mut fresh);
5467 for _ in 0..10 {
5468 cycled.run_frame();
5469 fresh.run_frame();
5470 }
5471 assert_eq!(cycled.framebuffer(), fresh.framebuffer(), "frame");
5472 assert_eq!(cycled.drain_audio(), fresh.drain_audio(), "audio");
5473 assert_eq!(cycled.snapshot(), fresh.snapshot(), "state");
5474 }
5475
5476 /// v2.9.8 — the provenance stores stay armed across a power cycle (and
5477 /// are emptied, since a cold boot ends the history they describe), as the
5478 /// comment in `Nes::power_cycle` always said. They were dropped with the
5479 /// rebuilt chips until v2.9.8, which made that comment's clear a no-op.
5480 #[cfg(feature = "debug-hooks")]
5481 #[test]
5482 fn a_power_cycle_keeps_the_provenance_stores_armed() {
5483 let rom = synth_nrom(16, 8);
5484 let mut nes = Nes::from_rom(&rom).unwrap();
5485 nes.set_write_attribution(true);
5486 nes.set_pixel_provenance(true);
5487 nes.set_audio_provenance(true);
5488 nes.run_frame();
5489 nes.power_cycle();
5490 assert!(
5491 nes.bus.ppu.write_attribution().is_some(),
5492 "write attribution"
5493 );
5494 assert!(nes.bus.ppu.pixel_provenance().is_some(), "pixel provenance");
5495 assert!(nes.bus.apu.audio_provenance_armed(), "audio provenance");
5496 }
5497
5498 /// v2.9.8 — a power cycle after a program has polled the controllers is
5499 /// a fresh boot (`power_cycle == fresh boot`).
5500 ///
5501 /// The controller ports remember the bus cycle of their last read
5502 /// (`port_read_cycle`, `u64::MAX` = never), which the CLK-run model
5503 /// compares with the current cycle. A power cycle reset the cycle counter
5504 /// to 0 but left those stamps from the old timeline, so the cycled
5505 /// console's state depended on how long it had run and differed from a
5506 /// fresh one; two netplay peers cycling from different states would carry
5507 /// different stamps.
5508 #[test]
5509 fn a_power_cycle_after_controller_reads_is_a_fresh_boot() {
5510 let mut rom = synth_nrom(16, 8);
5511 // $C000: LDA $4016 ; LDA $4017 ; JMP $C000
5512 rom[16..25].copy_from_slice(&[0xAD, 0x16, 0x40, 0xAD, 0x17, 0x40, 0x4C, 0x00, 0xC0]);
5513 let mut cycled = Nes::from_rom(&rom).unwrap();
5514 for _ in 0..3 {
5515 cycled.run_frame();
5516 }
5517 assert_ne!(
5518 cycled.bus.port_read_cycle(0),
5519 u64::MAX,
5520 "premise: the program polled the pad"
5521 );
5522 cycled.power_cycle();
5523 let fresh = Nes::from_rom(&rom).unwrap();
5524 assert!(
5525 cycled.snapshot() == fresh.snapshot(),
5526 "a power-cycled console must equal a fresh one"
5527 );
5528 }
5529
5530 /// v2.9.8 — `mapper_id` reports the cartridge's mapper on every board.
5531 ///
5532 /// It used to read the mapper's DEBUG view, whose default `debug_info`
5533 /// names mapper 0, so every board without its own override -- `UxROM`,
5534 /// CNROM, `AxROM` among them -- claimed to be NROM to the Lua
5535 /// `cart:mapper_id()`, the ROM-info panel and the mobile `RomInfo`.
5536 #[test]
5537 fn mapper_id_reports_the_cartridge_mapper_on_every_board() {
5538 /// A NES 2.0 image of `mapper` / `submapper`: `prg16` x 16 KiB PRG and
5539 /// `chr8` x 8 KiB CHR-ROM (0 = 8 KiB CHR-RAM).
5540 fn image(mapper: u16, submapper: u8, prg16: u8, chr8: u8) -> Vec<u8> {
5541 let [lo, hi] = mapper.to_le_bytes();
5542 let mut rom = vec![0u8; 16];
5543 rom[..4].copy_from_slice(b"NES\x1A");
5544 rom[4] = prg16;
5545 rom[5] = chr8;
5546 rom[6] = (lo & 0x0F) << 4;
5547 rom[7] = (lo & 0xF0) | 0x08; // NES 2.0
5548 rom[8] = (submapper << 4) | (hi & 0x0F);
5549 if chr8 == 0 {
5550 rom[11] = 0x07; // 64 << 7 = 8 KiB CHR-RAM
5551 }
5552 rom.resize(
5553 16 + usize::from(prg16) * 0x4000 + usize::from(chr8) * 0x2000,
5554 0,
5555 );
5556 rom
5557 }
5558 for (mapper, submapper, prg16, chr8) in [
5559 (0u16, 0u8, 2u8, 1u8),
5560 (2, 1, 8, 0),
5561 (3, 2, 2, 4),
5562 (7, 0, 8, 0),
5563 (4, 0, 8, 8),
5564 ] {
5565 let nes = Nes::from_rom(&image(mapper, submapper, prg16, chr8))
5566 .unwrap_or_else(|e| panic!("mapper {mapper}: {e:?}"));
5567 assert_eq!(nes.mapper_id(), mapper, "mapper {mapper}");
5568 assert_eq!(nes.submapper(), submapper, "mapper {mapper} submapper");
5569 // The debugger's mapper panel reads the same id.
5570 assert_eq!(nes.mapper_info().mapper_id, mapper, "mapper {mapper} view");
5571 }
5572 }
5573
5574 /// **The counter must not be serialized**, and this is the assertion that
5575 /// pins it.
5576 ///
5577 /// Serializing it would put an OLD value back on restore, so loading a state
5578 /// saved earlier in the same session could hand a consumer a generation it
5579 /// has already seen — and the consumer would conclude nothing jumped at the
5580 /// exact moment something did. This test reproduces precisely that shape:
5581 /// snapshot at generation N, advance the generation past N, then restore. If
5582 /// the counter round-tripped, the value would come back as N.
5583 #[test]
5584 fn a_restore_never_hands_back_a_generation_a_consumer_has_seen() {
5585 let rom = synth_nrom(16, 8);
5586 let mut nes = Nes::from_rom(&rom).unwrap();
5587 nes.run_frame();
5588 let blob = nes.snapshot();
5589 let at_snapshot = nes.timeline_generation();
5590
5591 // Advance the generation well past the snapshot's value.
5592 for _ in 0..3 {
5593 nes.reset();
5594 }
5595 let seen = nes.timeline_generation();
5596 assert!(seen > at_snapshot);
5597
5598 nes.restore(&blob).expect("restore");
5599 assert!(
5600 nes.timeline_generation() > seen,
5601 "the generation went BACKWARDS to {} (a consumer had already seen {seen}), \
5602 so the counter is being carried in the save state -- which defeats its \
5603 only purpose",
5604 nes.timeline_generation()
5605 );
5606 }
5607
5608 #[test]
5609 fn rewind_disabled_no_op() {
5610 let rom = synth_nrom(16, 8);
5611 let mut nes = Nes::from_rom(&rom).unwrap();
5612 nes.run_frame();
5613 assert!(!nes.rewind_step_back());
5614 assert_eq!(nes.rewind_len(), 0);
5615 }
5616
5617 #[cfg(feature = "debug-hooks")]
5618 #[test]
5619 fn breakpoint_stops_run_frame_at_pc() {
5620 let rom = synth_nrom(16, 8);
5621 // A PC the CPU provably reaches: the PC after the first 3 executed
5622 // instructions (a fresh run replays the same deterministic sequence).
5623 let mut probe = Nes::from_rom(&rom).expect("parse");
5624 for _ in 0..3 {
5625 probe.step_instruction();
5626 }
5627 let target = probe.cpu.pc;
5628
5629 let mut nes = Nes::from_rom(&rom).expect("parse");
5630 // The PPU's frame-complete latch is set at power-on, so the first
5631 // `run_frame` returns immediately without iterating; warm past it.
5632 let _ = nes.run_frame();
5633 nes.add_breakpoint(target);
5634 nes.add_breakpoint(target); // idempotent
5635 assert_eq!(nes.breakpoints(), &[target]);
5636
5637 let _ = nes.run_frame();
5638 assert_eq!(
5639 nes.take_break_hit(),
5640 Some(target),
5641 "stops at the breakpoint PC"
5642 );
5643 assert_eq!(nes.take_break_hit(), None, "hit cleared on read");
5644
5645 // Resuming ("continue") steps past the stopped PC instead of
5646 // re-breaking in place, then hits the same PC again next loop.
5647 let _ = nes.run_frame();
5648 assert_eq!(
5649 nes.take_break_hit(),
5650 Some(target),
5651 "resume steps past, then re-hits on the next pass"
5652 );
5653
5654 // Disarmed breakpoints don't fire (the frame runs to completion).
5655 nes.set_breakpoints_enabled(false);
5656 let _ = nes.run_frame();
5657 assert_eq!(nes.take_break_hit(), None, "disarmed: no break");
5658
5659 // Removal empties the list.
5660 nes.remove_breakpoint(target);
5661 assert_eq!(nes.breakpoints(), []);
5662
5663 // Regression (gemini #41): a breakpoint sitting at the frame's STARTING
5664 // PC must fire immediately — the old `first_iter` skip missed it.
5665 let mut nes2 = Nes::from_rom(&rom).expect("parse");
5666 let _ = nes2.run_frame(); // warm past the power-on frame-complete latch
5667 let start_pc = nes2.cpu.pc;
5668 nes2.add_breakpoint(start_pc);
5669 let _ = nes2.run_frame();
5670 assert_eq!(
5671 nes2.take_break_hit(),
5672 Some(start_pc),
5673 "breaks immediately when starting already on a breakpoint"
5674 );
5675 }
5676
5677 #[cfg(feature = "debug-hooks")]
5678 #[test]
5679 fn trace_logger_records_while_enabled() {
5680 let rom = synth_nrom(16, 8);
5681 let mut nes = Nes::from_rom(&rom).expect("parse");
5682 let _ = nes.run_frame(); // warm past the power-on frame-complete latch.
5683 assert_eq!(nes.trace_len(), 0, "off by default");
5684 nes.set_trace_enabled(true);
5685 let _ = nes.run_frame();
5686 assert!(nes.trace_len() > 0, "records while enabled");
5687 // Records carry the executed PCs (the synth ROM spins at $C000).
5688 let recs = nes.trace_records();
5689 assert!(recs.iter().any(|r| r.pc == 0xC000), "captured the loop PC");
5690 // The tail copy is bounded.
5691 assert!(nes.trace_tail_vec(4).len() <= 4);
5692 // Disabling stops growth; clearing empties.
5693 nes.set_trace_enabled(false);
5694 let n = nes.trace_len();
5695 let _ = nes.run_frame();
5696 assert_eq!(nes.trace_len(), n, "no new records when disabled");
5697 nes.clear_trace();
5698 assert_eq!(nes.trace_len(), 0);
5699 }
5700
5701 #[cfg(feature = "debug-hooks")]
5702 #[test]
5703 fn event_viewer_records_writes_with_ppu_position() {
5704 use crate::bus::EventKind;
5705 // A tiny NROM that loops `LDA #$00 ; STA $2000 ; JMP $C000`, so it
5706 // generates a PPU-register write ($2000) every iteration.
5707 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
5708 bytes[0..4].copy_from_slice(b"NES\x1A");
5709 bytes[4] = 1; // 1x16KB PRG
5710 bytes[5] = 1; // 1x8KB CHR (unused here)
5711 let prg = &mut bytes[16..16 + 16 * 1024];
5712 // $C000 maps to PRG offset 0.
5713 prg[0..8].copy_from_slice(&[0xA9, 0x00, 0x8D, 0x00, 0x20, 0x4C, 0x00, 0xC0]);
5714 let len = 16 * 1024;
5715 prg[len - 4] = 0x00; // reset vector lo
5716 prg[len - 3] = 0xC0; // reset vector hi -> $C000
5717 // CHR not appended (header says 1 bank but parse tolerates; use 0 banks).
5718 bytes[5] = 0;
5719
5720 let mut nes = Nes::from_rom(&bytes).expect("parse");
5721 let _ = nes.run_frame(); // warm past the power-on frame-complete latch.
5722 assert!(nes.events().is_empty(), "off by default");
5723 nes.set_event_logging(true);
5724 let _ = nes.run_frame();
5725 let evs = nes.events();
5726 assert!(!evs.is_empty(), "the STA $2000 loop produces writes");
5727 assert!(
5728 evs.iter().all(|e| e.kind == EventKind::PpuWrite
5729 && e.addr == 0x2000
5730 && e.dot <= 340
5731 && e.value == 0x00),
5732 "all events are $2000 PPU writes of $00 with a sane dot"
5733 );
5734 // Reset per frame: the count stays one-frame-bounded. The event log is
5735 // capped at `EVENT_CAP` (20_000, private to the bus module) — distinct
5736 // from the looser instruction-trace `TRACE_CAP` — so assert that bound.
5737 let _ = nes.run_frame();
5738 assert!(nes.events().len() <= 20_000, "bounded by EVENT_CAP");
5739 nes.set_event_logging(false);
5740 assert!(!nes.event_logging());
5741 }
5742
5743 /// v2.3.2 "Lucid" Phase 1 — the write-attribution oracle.
5744 ///
5745 /// The claim under test is the whole point of the feature: for a byte in the
5746 /// PPU's own memory, the store reports the PC of the instruction that put it
5747 /// there. The ROM is written so the answer is known independently — a single
5748 /// `STA $2007` at a fixed address — and the expectation is pinned to that
5749 /// address rather than to whatever the implementation happens to record.
5750 #[cfg(feature = "debug-hooks")]
5751 #[test]
5752 fn write_attribution_names_the_instruction_that_wrote_a_nametable_byte() {
5753 // NROM at $C000:
5754 // C000: A9 21 LDA #$21 ; VRAM addr hi
5755 // C002: 8D 06 20 STA $2006
5756 // C005: A9 08 LDA #$08 ; VRAM addr lo -> $2108
5757 // C007: 8D 06 20 STA $2006
5758 // C00A: A9 5A LDA #$5A ; the byte
5759 // C00C: 8D 07 20 STA $2007 <-- the write under test
5760 // C00F: 4C 00 C0 JMP $C000 ; loop the whole sequence
5761 //
5762 // The sequence LOOPS rather than spinning after one pass, and the test
5763 // runs several frames, because the PPU ignores `$2000/$2001/$2005/$2006`
5764 // writes for ~29,658 CPU cycles after reset (the documented post-reset
5765 // mask window, `PpuRegion::post_reset_mask_cycles`). A single pass at
5766 // power-on would have its two `$2006` stores dropped, leaving `v == 0`,
5767 // and the `$2007` write would land in CHR space instead of a nametable.
5768 const STA_2007_PC: u16 = 0xC00C;
5769 const VRAM_ADDR: u16 = 0x2108;
5770 const VALUE: u8 = 0x5A;
5771
5772 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
5773 bytes[0..4].copy_from_slice(b"NES\x1A");
5774 bytes[4] = 1; // 1x16KB PRG
5775 bytes[5] = 0; // no CHR bank appended
5776 let prg = &mut bytes[16..16 + 16 * 1024];
5777 prg[0..18].copy_from_slice(&[
5778 0xA9, 0x21, // LDA #$21
5779 0x8D, 0x06, 0x20, // STA $2006
5780 0xA9, 0x08, // LDA #$08
5781 0x8D, 0x06, 0x20, // STA $2006
5782 0xA9, VALUE, // LDA #$5A
5783 0x8D, 0x07, 0x20, // STA $2007
5784 0x4C, 0x00, 0xC0, // JMP $C000
5785 ]);
5786 let len = 16 * 1024;
5787 prg[len - 4] = 0x00; // reset vector lo
5788 prg[len - 3] = 0xC0; // reset vector hi -> $C000
5789
5790 let mut nes = Nes::from_rom(&bytes).expect("parse");
5791 assert!(
5792 nes.write_attribution().is_none(),
5793 "attribution is off by default"
5794 );
5795 nes.set_write_attribution(true);
5796 // Three frames: one to clear the post-reset write-mask window, the rest
5797 // so the loop's `$2006`/`$2007` sequence lands for real.
5798 for _ in 0..3 {
5799 let _ = nes.run_frame();
5800 }
5801
5802 // Resolve the address the way the emulator does, through the mapper's
5803 // mirroring, rather than hardcoding `& 0x07FF`. The previous version of
5804 // this line claimed to do that and then hardcoded it anyway (review
5805 // catch on PR #356) — which would have masked a mirroring regression.
5806 let off = nes
5807 .ciram_offset_for_nametable_addr(VRAM_ADDR)
5808 .expect("a nametable address resolves to a CIRAM offset");
5809 let attrib = nes.write_attribution().expect("armed");
5810 let rec = attrib
5811 .ciram(off)
5812 .expect("the STA $2007 wrote this CIRAM byte");
5813 assert_eq!(
5814 rec.pc, STA_2007_PC,
5815 "the byte is attributed to the STA $2007, not to the $2006 stores \
5816 that set the address or to the LDA that loaded the value"
5817 );
5818 assert_eq!(rec.value, VALUE);
5819 // The byte really is there — attribution must describe a write that
5820 // actually happened, not a write the tap merely observed being issued.
5821 assert_eq!(nes.vram()[off], VALUE);
5822 // And the cycle stamp is a real one from this run.
5823 assert!(rec.cycle > 0, "cycle stamp taken from the executing CPU");
5824
5825 // An untouched byte reports nothing rather than a plausible-looking zero.
5826 assert_eq!(attrib.ciram(off ^ 0x0400), None);
5827
5828 // Disarming frees the store; re-arming starts clean.
5829 nes.set_write_attribution(false);
5830 assert!(nes.write_attribution().is_none());
5831 }
5832
5833 /// v2.3.2 "Lucid" phase 2 — the per-pixel provenance oracle.
5834 ///
5835 /// Builds a screen out of a known nametable byte and a known palette, then
5836 /// checks that the record for a background pixel names the addresses that
5837 /// actually produced it. The load-bearing assertion is `nt_addr`: it must be
5838 /// the address of the tile ON SCREEN, which is two tiles behind whatever `v`
5839 /// holds at emit time — the single mistake this whole cascade exists to
5840 /// prevent.
5841 #[cfg(feature = "debug-hooks")]
5842 #[test]
5843 fn pixel_provenance_names_the_displayed_tile_not_the_fetch_pointer() {
5844 use rustynes_ppu::PixelLayer;
5845
5846 // NROM with CHR-RAM. The program:
5847 // * fills nametable $2000 with tile $01,
5848 // * writes a non-zero pattern for tile $01 into CHR-RAM,
5849 // * sets palette entry $3F01 to a known color,
5850 // * enables background rendering,
5851 // * spins.
5852 //
5853 // Assembled by hand below; addresses are named so the assertions can
5854 // reference the instruction rather than a magic number.
5855 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
5856 bytes[0..4].copy_from_slice(b"NES\x1A");
5857 bytes[4] = 1; // 1x16KB PRG
5858 bytes[5] = 0; // 0 CHR banks => CHR-RAM, so the pattern is writable
5859 let prg = &mut bytes[16..16 + 16 * 1024];
5860
5861 #[rustfmt::skip]
5862 let code: &[u8] = &[
5863 // --- Delay ~328k cycles (~11 frames) BEFORE touching any PPU
5864 // register. The PPU ignores $2000/$2001/$2005/$2006 writes for
5865 // ~29,658 CPU cycles after reset; setup that runs inside that window
5866 // has its $2006 address writes silently dropped, so every subsequent
5867 // $2007 lands somewhere unintended. Found by this test failing.
5868 0xA2, 0x00, // C000 LDX #$00
5869 0xA0, 0x00, // C002 LDY #$00
5870 0x88, // C004 DEY
5871 0xD0, 0xFD, // C005 BNE $C004
5872 0xCA, // C007 DEX
5873 0xD0, 0xF8, // C008 BNE $C002
5874 // --- CHR-RAM: tile $01 rows 0..7 low plane = $FF (all pixels idx 1)
5875 0xA9, 0x00, 0x8D, 0x06, 0x20, // C00A LDA #$00 / STA $2006
5876 0xA9, 0x10, 0x8D, 0x06, 0x20, // C00F LDA #$10 / STA $2006 -> $0010
5877 0xA2, 0x08, // C014 LDX #$08
5878 0xA9, 0xFF, // C016 LDA #$FF
5879 0x8D, 0x07, 0x20, // C018 STA $2007 (8x low plane)
5880 0xCA, 0xD0, 0xFA, // C01B DEX / BNE $C018
5881 // --- palette: $3F00 = $0F (black), $3F01 = $16 (red)
5882 0xA9, 0x3F, 0x8D, 0x06, 0x20, // C01E LDA #$3F / STA $2006
5883 0xA9, 0x00, 0x8D, 0x06, 0x20, // C023 LDA #$00 / STA $2006 -> $3F00
5884 0xA9, 0x0F, 0x8D, 0x07, 0x20, // C028 LDA #$0F / STA $2007
5885 0xA9, 0x16, 0x8D, 0x07, 0x20, // C02D LDA #$16 / STA $2007
5886 // --- nametable + attributes $2000..$23FF = $01
5887 0xA9, 0x20, 0x8D, 0x06, 0x20, // C032 LDA #$20 / STA $2006
5888 0xA9, 0x00, 0x8D, 0x06, 0x20, // C037 LDA #$00 / STA $2006 -> $2000
5889 0xA0, 0x04, // C03C LDY #$04 (4 x 256)
5890 0xA2, 0x00, // C03E LDX #$00
5891 0xA9, 0x01, // C040 LDA #$01
5892 0x8D, 0x07, 0x20, // C042 STA $2007
5893 0xCA, 0xD0, 0xFA, // C045 DEX / BNE $C042
5894 0x88, 0xD0, 0xF3, // C048 DEY / BNE $C03E
5895 // --- enable BG: $2000 = $00 (BG pattern table $0000, NT $2000),
5896 // $2001 = $08 (show BG, but NOT the leftmost 8 px)
5897 0xA9, 0x00, 0x8D, 0x00, 0x20, // C04B LDA #$00 / STA $2000
5898 0xA9, 0x08, 0x8D, 0x01, 0x20, // C050 LDA #$08 / STA $2001
5899 0x4C, 0x55, 0xC0, // C055 JMP $C055 (spin)
5900 ];
5901 prg[..code.len()].copy_from_slice(code);
5902 let len = 16 * 1024;
5903 prg[len - 4] = 0x00; // reset vector -> $C000
5904 prg[len - 3] = 0xC0;
5905
5906 let mut nes = Nes::from_rom(&bytes).expect("parse");
5907 // Enough frames for the delay loop, then the setup loops, to complete
5908 // and for rendering to be running steadily.
5909 for _ in 0..16 {
5910 let _ = nes.run_frame();
5911 }
5912 assert!(nes.pixel_provenance().is_none(), "off by default");
5913 nes.set_pixel_provenance(true);
5914 let _ = nes.run_frame();
5915
5916 let prov = nes.pixel_provenance().expect("armed");
5917
5918 // Pixel (16, 0) sits in tile column 2 of row 0, i.e. nametable $2002.
5919 let rec = prov.get(16, 0).expect("on-screen");
5920 assert_eq!(
5921 rec.layer,
5922 PixelLayer::Background,
5923 "the all-$FF pattern makes every BG pixel opaque"
5924 );
5925 assert_eq!(
5926 rec.nt_addr, 0x2002,
5927 "the record must name the tile ON SCREEN at x=16; `v` at emit time \
5928 has already advanced two tiles past it, so a value near $2004 here \
5929 would mean the cascade is not tracking the shifters"
5930 );
5931 assert_eq!(rec.at_addr, 0x23C0, "tile (2,0) -> attribute byte 0");
5932 assert_eq!(rec.bg_idx, 1, "low plane $FF, high plane $00 -> index 1");
5933 assert_eq!(rec.palette_addr, 0x3F01, "palette group 0, index 1");
5934 assert_eq!(rec.palette_index, 1);
5935 assert_eq!(rec.color, 0x16, "the red we wrote to $3F01");
5936 assert_eq!(rec.scanline, 0);
5937 assert_eq!(rec.dot, 17, "screen X is dot - 1");
5938 assert_eq!(
5939 rec.sprite_slot,
5940 rustynes_ppu::SPRITE_SLOT_NONE,
5941 "no sprites in this ROM"
5942 );
5943 // Fine-Y is 2, not 0, and that is correct: the ROM sets the scroll only
5944 // via `$2006 = $20, $00`, which loads `v = t = $2000` — and bits 12-14 of
5945 // a VRAM address ARE the fine-Y field, so `$2000` means fine-Y = 2. A ROM
5946 // that wanted row 0 would have written `$2005` afterwards. The record
5947 // reports what the hardware is actually displaying.
5948 assert_eq!(rec.fine_y, 2, "$2006 = $2000 puts fine-Y at 2");
5949 // Tile $01 base $0010, plus fine-Y 2.
5950 assert_eq!(rec.pattern_addr, 0x0012);
5951
5952 // The cascade advances ONE TILE PER GROUP across the scanline — it is
5953 // not a single address held for the whole line, and not skewed by the
5954 // two dummy nametable fetches at dots 337-340.
5955 for (x, want_nt) in [(0usize, 0x2000u16), (8, 0x2001), (24, 0x2003), (40, 0x2005)] {
5956 assert_eq!(
5957 prov.get(x, 0).expect("on-screen").nt_addr,
5958 want_nt,
5959 "tile column at x={x}"
5960 );
5961 }
5962
5963 // Off-screen queries answer `None` rather than clamping to a pixel the
5964 // caller did not ask about.
5965 assert_eq!(prov.get(256, 0), None);
5966 assert_eq!(prov.get(0, 240), None);
5967
5968 nes.set_pixel_provenance(false);
5969 assert!(nes.pixel_provenance().is_none());
5970 }
5971
5972 /// The two halves compose: provenance gives the palette index, attribution
5973 /// gives the instruction that wrote it. This is the end-to-end claim the
5974 /// feature exists to support.
5975 #[cfg(feature = "debug-hooks")]
5976 #[test]
5977 fn provenance_and_attribution_compose_into_a_causal_chain() {
5978 // Minimal ROM: set $3F00 (backdrop) to a known color from a known PC,
5979 // then spin. Rendering stays off, so every pixel is the backdrop and the
5980 // chain is unambiguous.
5981 // C000: LDA #$3F / STA $2006
5982 // C005: LDA #$00 / STA $2006 -> v = $3F00
5983 // C00A: LDA #$21 / STA $2007 <-- the palette write
5984 // C00F: JMP $C000
5985 const STA_2007_PC: u16 = 0xC00C;
5986 const COLOR: u8 = 0x21;
5987
5988 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
5989 bytes[0..4].copy_from_slice(b"NES\x1A");
5990 bytes[4] = 1;
5991 bytes[5] = 0;
5992 let prg = &mut bytes[16..16 + 16 * 1024];
5993 prg[0..18].copy_from_slice(&[
5994 0xA9, 0x3F, 0x8D, 0x06, 0x20, // LDA #$3F / STA $2006
5995 0xA9, 0x00, 0x8D, 0x06, 0x20, // LDA #$00 / STA $2006
5996 0xA9, COLOR, 0x8D, 0x07, 0x20, // LDA #$21 / STA $2007
5997 0x4C, 0x00, 0xC0, // JMP $C000
5998 ]);
5999 let len = 16 * 1024;
6000 prg[len - 4] = 0x00;
6001 prg[len - 3] = 0xC0;
6002
6003 let mut nes = Nes::from_rom(&bytes).expect("parse");
6004 let _ = nes.run_frame();
6005 nes.set_pixel_provenance(true);
6006 nes.set_write_attribution(true);
6007 for _ in 0..3 {
6008 let _ = nes.run_frame();
6009 }
6010
6011 // Step 1: which palette entry produced this pixel?
6012 let rec = nes
6013 .pixel_provenance()
6014 .and_then(|p| p.get(100, 100))
6015 .expect("armed and on-screen");
6016 assert_eq!(rec.layer, rustynes_ppu::PixelLayer::Backdrop);
6017 assert_eq!(rec.palette_index, 0, "the universal backdrop");
6018 assert_eq!(rec.color, COLOR);
6019
6020 // Step 2: who wrote that palette entry?
6021 let who = nes
6022 .write_attribution()
6023 .and_then(|a| a.palette(rec.palette_index as usize))
6024 .expect("the STA $2007 wrote it");
6025 assert_eq!(
6026 who.pc, STA_2007_PC,
6027 "the chain closes: pixel -> palette entry -> writing instruction"
6028 );
6029 assert_eq!(who.value, COLOR);
6030 }
6031
6032 /// An OAM DMA burst moves 256 bytes but has exactly one cause. The store
6033 /// must say so — attributing all 256 to the `STA $4014` that triggered them
6034 /// rather than inventing a per-byte PC that no instruction ever had.
6035 #[cfg(feature = "debug-hooks")]
6036 #[test]
6037 fn oam_dma_attributes_all_256_bytes_to_the_triggering_store() {
6038 // NROM at $C000:
6039 // C000: A9 02 LDA #$02
6040 // C002: 8D 14 40 STA $4014 <-- one instruction, 256 OAM bytes
6041 // C005: 4C 00 C0 JMP $C000
6042 //
6043 // `$4014` is not subject to the PPU's post-reset write-mask window, so
6044 // this lands on the first pass; the loop just keeps it landing.
6045 const STA_4014_PC: u16 = 0xC002;
6046
6047 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
6048 bytes[0..4].copy_from_slice(b"NES\x1A");
6049 bytes[4] = 1;
6050 bytes[5] = 0;
6051 let prg = &mut bytes[16..16 + 16 * 1024];
6052 prg[0..8].copy_from_slice(&[
6053 0xA9, 0x02, // LDA #$02
6054 0x8D, 0x14, 0x40, // STA $4014
6055 0x4C, 0x00, 0xC0, // JMP $C000
6056 ]);
6057 let len = 16 * 1024;
6058 prg[len - 4] = 0x00;
6059 prg[len - 3] = 0xC0;
6060
6061 let mut nes = Nes::from_rom(&bytes).expect("parse");
6062 // The first `run_frame` after power-on returns on the already-latched
6063 // frame-complete flag, executing almost no instructions — the same
6064 // warm-up the event-viewer tests need. Arm AFTER it, so the assertion
6065 // below is about a frame that actually ran code.
6066 let _ = nes.run_frame();
6067 nes.set_write_attribution(true);
6068 let _ = nes.run_frame();
6069
6070 let attrib = nes.write_attribution().expect("armed");
6071 for idx in 0..=u8::MAX {
6072 let rec = attrib
6073 .oam(idx)
6074 .unwrap_or_else(|| panic!("OAM byte {idx} unattributed after a full DMA burst"));
6075 assert_eq!(
6076 rec.pc, STA_4014_PC,
6077 "OAM byte {idx} must name the STA $4014, not a synthesized PC"
6078 );
6079 }
6080 }
6081
6082 /// A save-state restore must invalidate attribution: the restored bytes were
6083 /// not written by anything this session ran, so the honest answer is "no
6084 /// record", not the PC that wrote that offset on the abandoned timeline.
6085 #[cfg(feature = "debug-hooks")]
6086 #[test]
6087 fn write_attribution_is_invalidated_by_restore() {
6088 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
6089 bytes[0..4].copy_from_slice(b"NES\x1A");
6090 bytes[4] = 1;
6091 bytes[5] = 0;
6092 let prg = &mut bytes[16..16 + 16 * 1024];
6093 // Same looping `$2006`/`$2007` ROM as the test above; see its comment for
6094 // why it loops and why three frames are needed.
6095 prg[0..18].copy_from_slice(&[
6096 0xA9, 0x21, 0x8D, 0x06, 0x20, 0xA9, 0x08, 0x8D, 0x06, 0x20, 0xA9, 0x5A, 0x8D, 0x07,
6097 0x20, 0x4C, 0x00, 0xC0,
6098 ]);
6099 let len = 16 * 1024;
6100 prg[len - 4] = 0x00;
6101 prg[len - 3] = 0xC0;
6102
6103 let mut nes = Nes::from_rom(&bytes).expect("parse");
6104 nes.set_write_attribution(true);
6105 for _ in 0..3 {
6106 let _ = nes.run_frame();
6107 }
6108 let off = 0x0108usize;
6109 assert!(
6110 nes.write_attribution().and_then(|a| a.ciram(off)).is_some(),
6111 "precondition: the write was attributed"
6112 );
6113
6114 let snap = nes.snapshot();
6115 nes.restore(&snap).expect("round-trip");
6116 assert!(
6117 nes.write_attribution().is_some(),
6118 "the store stays armed across a restore"
6119 );
6120 assert_eq!(
6121 nes.write_attribution().and_then(|a| a.ciram(off)),
6122 None,
6123 "but its records are dropped — they describe a timeline that the \
6124 restore replaced"
6125 );
6126 }
6127
6128 #[cfg(feature = "debug-hooks")]
6129 #[test]
6130 fn event_viewer_records_ppu_reads() {
6131 use crate::bus::EventKind;
6132 // A tiny NROM that loops `LDA $2002 ; JMP $C000`, generating a PPU
6133 // STATUS read ($2002) every iteration (v1.5.0 Workstream A2 read tap).
6134 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
6135 bytes[0..4].copy_from_slice(b"NES\x1A");
6136 bytes[4] = 1; // 1x16KB PRG
6137 let prg = &mut bytes[16..16 + 16 * 1024];
6138 // $C000: LDA $2002 ; JMP $C000
6139 prg[0..6].copy_from_slice(&[0xAD, 0x02, 0x20, 0x4C, 0x00, 0xC0]);
6140 let len = 16 * 1024;
6141 prg[len - 4] = 0x00;
6142 prg[len - 3] = 0xC0;
6143
6144 let mut nes = Nes::from_rom(&bytes).expect("parse");
6145 let _ = nes.run_frame();
6146 nes.set_event_logging(true);
6147 let _ = nes.run_frame();
6148 let evs = nes.events();
6149 assert!(
6150 evs.iter()
6151 .any(|e| e.kind == EventKind::PpuRead && e.addr == 0x2002),
6152 "the LDA $2002 loop produces PPU reads"
6153 );
6154 assert!(
6155 evs.iter()
6156 .all(|e| e.kind.is_read() == (e.kind == EventKind::PpuRead)),
6157 "is_read is true only for PpuRead"
6158 );
6159 nes.set_event_logging(false);
6160 }
6161
6162 #[cfg(feature = "debug-hooks")]
6163 #[test]
6164 fn event_breakpoint_fires_on_armed_category_only() {
6165 use crate::EventBpKind;
6166 // The same `LDA #$00 ; STA $2000 ; JMP $C000` loop — it issues a PPU
6167 // write every iteration but never an APU write or interrupt service.
6168 let mut bytes = alloc::vec![0u8; 16 + 16 * 1024];
6169 bytes[0..4].copy_from_slice(b"NES\x1A");
6170 bytes[4] = 1;
6171 bytes[5] = 0;
6172 let prg = &mut bytes[16..16 + 16 * 1024];
6173 prg[0..8].copy_from_slice(&[0xA9, 0x00, 0x8D, 0x00, 0x20, 0x4C, 0x00, 0xC0]);
6174 let len = 16 * 1024;
6175 prg[len - 4] = 0x00;
6176 prg[len - 3] = 0xC0;
6177
6178 let mut nes = Nes::from_rom(&bytes).expect("parse");
6179 let _ = nes.run_frame(); // warm past the power-on frame-complete latch.
6180
6181 // Default: nothing armed, no hits.
6182 assert_eq!(nes.event_breakpoints(), 0, "disarmed by default");
6183 let _ = nes.run_frame();
6184 assert_eq!(nes.take_event_break_hit(), None, "no hit while disarmed");
6185
6186 // Arm an UNRELATED category (APU write): the $2000 loop never trips it.
6187 nes.set_event_breakpoints(EventBpKind::ApuWrite.bit());
6188 let _ = nes.run_frame();
6189 assert_eq!(
6190 nes.take_event_break_hit(),
6191 None,
6192 "wrong category does not fire"
6193 );
6194
6195 // Arm PPU write: the very next frame must latch a hit with sane context.
6196 nes.set_event_breakpoints(EventBpKind::PpuWrite.bit());
6197 let _ = nes.run_frame();
6198 let hit = nes.take_event_break_hit().expect("PPU write fires");
6199 assert_eq!(hit.kind, EventBpKind::PpuWrite);
6200 assert_eq!(hit.addr, 0x2000, "the STA $2000 target");
6201 assert!(hit.dot <= 340, "dot in range");
6202 assert!(
6203 hit.scanline >= -1 && hit.scanline <= 260,
6204 "scanline in range"
6205 );
6206 // Cleared on read + only one (first) hit recorded per frame.
6207 assert_eq!(nes.take_event_break_hit(), None, "cleared on read");
6208
6209 // Disarming all stops it firing again.
6210 nes.set_event_breakpoints(0);
6211 let _ = nes.run_frame();
6212 assert_eq!(nes.take_event_break_hit(), None, "disarmed: silent");
6213 }
6214
6215 #[cfg(feature = "debug-hooks")]
6216 #[test]
6217 fn event_bp_kind_mask_and_labels_are_distinct() {
6218 use crate::EventBpKind;
6219 let all = EventBpKind::all();
6220 // Every category has a distinct bit and a non-empty label.
6221 let mut seen = 0u16;
6222 for k in all {
6223 assert_eq!(seen & k.bit(), 0, "{} bit collides", k.label());
6224 seen |= k.bit();
6225 assert_ne!(k.label(), "");
6226 }
6227 assert_eq!(seen.count_ones() as usize, all.len(), "11 distinct bits");
6228 }
6229
6230 #[test]
6231 fn debug_snapshots_are_read_only() {
6232 // T-53-002+ -- inspection must not advance emulator state.
6233 let rom = synth_nrom(16, 8);
6234 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
6235 for _ in 0..2 {
6236 nes.run_frame();
6237 }
6238 let cycle_before = nes.cycle();
6239 let _cpu = nes.cpu_snapshot();
6240 let _ppu = nes.ppu_snapshot();
6241 let _apu = nes.apu_snapshot();
6242 let _oam = nes.oam();
6243 let _pal = nes.palette_ram();
6244 let _mapper = nes.mapper_info();
6245 // cpu_bus_peek and pattern_table_rgba take &mut so we exercise them too.
6246 let _byte = nes.cpu_bus_peek(0xC000);
6247 let _byte = nes.ppu_bus_peek(0x2000);
6248 let pt = nes.pattern_table_rgba(0);
6249 assert_eq!(pt.len(), 128 * 128 * 4, "pattern table RGBA size");
6250 let nt = nes.nametable_rgba(0);
6251 assert_eq!(nt.len(), 256 * 240 * 4, "nametable RGBA size");
6252 assert_eq!(nes.cycle(), cycle_before, "inspection MUST NOT tick CPU");
6253 }
6254
6255 #[test]
6256 fn disassembler_round_trips_against_cpu_bus() {
6257 // Walk a small synthesized program through the disassembler.
6258 let rom = synth_nrom(16, 8);
6259 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
6260 let pc = nes.cpu().pc;
6261 // Take a fixed-size byte window via the peek API first; disasm
6262 // wants a `Fn`, and our peek is `FnMut`.
6263 let mut buf = [0u8; 16];
6264 for (i, b) in buf.iter_mut().enumerate() {
6265 *b = nes.cpu_bus_peek(pc.wrapping_add(u16::try_from(i).unwrap_or(0)));
6266 }
6267 let lines = rustynes_cpu::disassemble_at(
6268 |a| {
6269 let off = a.wrapping_sub(pc) as usize;
6270 buf.get(off).copied().unwrap_or(0)
6271 },
6272 pc,
6273 4,
6274 );
6275 assert_eq!(lines.len(), 4);
6276 // First instruction is JMP $C000 (0x4C 0x00 0xC0).
6277 assert_eq!(lines[0].addr, pc);
6278 assert_eq!(lines[0].mnemonic, "JMP");
6279 }
6280
6281 #[test]
6282 fn rom_sha256_is_deterministic() {
6283 let rom = synth_nrom(16, 8);
6284 let nes_a = Nes::from_rom(&rom).unwrap();
6285 let nes_b = Nes::from_rom(&rom).unwrap();
6286 assert_eq!(nes_a.rom_sha256(), nes_b.rom_sha256());
6287 // Different ROM -> different hash.
6288 let mut other = synth_nrom(16, 8);
6289 other[0x10] = 0x99;
6290 let nes_c = Nes::from_rom(&other).unwrap();
6291 assert_ne!(nes_a.rom_sha256(), nes_c.rom_sha256());
6292 }
6293
6294 /// v2.9.8: the persistent identity ignores the 16-byte header, so a
6295 /// load-time header correction cannot rename a game's saves; the
6296 /// whole-image hash (the Vs. database's fallback key) still sees the header.
6297 #[test]
6298 fn rom_identity_ignores_the_header_and_image_hash_does_not() {
6299 let rom = synth_nrom(16, 8);
6300 let mut reheaded = rom.clone();
6301 // Bytes 10-15 are unused padding in an iNES 1.0 header, so this is a
6302 // pure header edit on the same board.
6303 reheaded[12] = 0x01;
6304 let a = Nes::from_rom(&rom).unwrap();
6305 let b = Nes::from_rom(&reheaded).unwrap();
6306 assert_eq!(
6307 a.rom_sha256(),
6308 b.rom_sha256(),
6309 "header edit renamed the ROM"
6310 );
6311 assert_eq!(a.rom_hash_tag(), b.rom_hash_tag());
6312 assert_ne!(a.image_sha256(), b.image_sha256());
6313 // Exactly the body: the identity is SHA-256 of bytes[16..].
6314 assert_eq!(*a.rom_sha256(), sha256_of(&rom[16..]));
6315 assert_eq!(*a.image_sha256(), sha256_of(&rom));
6316 }
6317
6318 /// v2.9.9 (NF-21) — `rom_identity_of` is the identity a console built
6319 /// from the same image reports, for each image kind.
6320 #[test]
6321 fn rom_identity_of_matches_the_built_console() {
6322 let rom = synth_nrom(16, 8);
6323 assert_eq!(
6324 Nes::rom_identity_of(&rom),
6325 *Nes::from_rom(&rom).unwrap().rom_sha256()
6326 );
6327 let disk = synth_fds_disk();
6328 let fds = Nes::from_disk(&disk, &synth_fds_bios()).unwrap();
6329 assert_eq!(Nes::rom_identity_of(&disk), *fds.rom_sha256());
6330 let nsf = synth_tone_nsf();
6331 let tune = Nes::from_nsf(&nsf).unwrap();
6332 assert_eq!(Nes::rom_identity_of(&nsf), *tune.rom_sha256());
6333 // And it is not the whole-file hash for a cartridge.
6334 assert_ne!(Nes::rom_identity_of(&rom), sha256_of(&rom));
6335 }
6336
6337 /// A synthetic 8 KiB FDS BIOS: `JMP $E000` at the reset vector and an
6338 /// `RTI` for NMI / IRQ. Enough for the disk constructors to boot.
6339 fn synth_fds_bios() -> Vec<u8> {
6340 let mut bios = vec![0u8; 8 * 1024];
6341 bios[..3].copy_from_slice(&[0x4C, 0x00, 0xE0]); // $E000: JMP $E000
6342 bios[0x80] = 0x40; // $E080: RTI
6343 bios[0x1FFA..].copy_from_slice(&[0x80, 0xE0, 0x00, 0xE0, 0x80, 0xE0]);
6344 bios
6345 }
6346
6347 /// A one-sided fwNES-headed disk: the disk-info block signature is all the
6348 /// container parser needs.
6349 fn synth_fds_disk() -> Vec<u8> {
6350 let mut disk = vec![0u8; 16 + 65_500];
6351 disk[..4].copy_from_slice(b"FDS\x1A");
6352 disk[4] = 1;
6353 disk[16] = 0x01;
6354 disk[17..31].copy_from_slice(b"*NINTENDO-HVC*");
6355 disk
6356 }
6357
6358 /// v2.9.9 (NF-17) — a console booted from a saved copy of an FDS disk
6359 /// reports the pristine disk's identity once the host supplies it, so
6360 /// everything keyed on `rom_sha256` (slots and the `.rns` tag, cheats,
6361 /// movies, netplay, per-game keys, RA progress) survives the game's own
6362 /// disk saves. `image_sha256` keeps describing the bytes in hand.
6363 #[test]
6364 fn a_saved_disk_boot_reports_the_pristine_identity() {
6365 let bios = synth_fds_bios();
6366 let pristine = synth_fds_disk();
6367 let pristine_sha = *Nes::from_disk(&pristine, &bios).unwrap().rom_sha256();
6368 // The game wrote to its disk; the host boots the written image.
6369 let mut saved = pristine;
6370 saved[16 + 0x40] = 0x5A;
6371 let mut booted = Nes::from_disk(&saved, &bios).unwrap();
6372 let saved_sha = *booted.rom_sha256();
6373 assert_ne!(saved_sha, pristine_sha, "fixture: the images differ");
6374
6375 booted.set_rom_identity(pristine_sha);
6376 assert_eq!(
6377 *booted.rom_sha256(),
6378 pristine_sha,
6379 "a disk save moved the game's identity"
6380 );
6381 assert_eq!(booted.rom_hash_tag()[..], pristine_sha[..ROM_HASH_TAG_LEN]);
6382 assert_eq!(
6383 *booted.image_sha256(),
6384 saved_sha,
6385 "the image hash must stay the bytes actually loaded"
6386 );
6387 // The identity is not state: a cold boot keeps it.
6388 booted.power_cycle();
6389 assert_eq!(*booted.rom_sha256(), pristine_sha);
6390 }
6391
6392 #[test]
6393 fn thumbnail_has_expected_dimensions() {
6394 let rom = synth_nrom(16, 8);
6395 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
6396 nes.run_frame();
6397 let thumb = nes.thumbnail();
6398 assert_eq!(thumb.len(), save_state::THUMBNAIL_LEN);
6399 assert_eq!(
6400 save_state::THUMBNAIL_LEN,
6401 save_state::THUMBNAIL_WIDTH * save_state::THUMBNAIL_HEIGHT * 4
6402 );
6403 }
6404
6405 #[test]
6406 fn snapshot_includes_thumbnail_section_extractable() {
6407 let rom = synth_nrom(16, 8);
6408 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
6409 for _ in 0..2 {
6410 nes.run_frame();
6411 }
6412 let blob = nes.snapshot();
6413 let extracted = Nes::extract_thumbnail(&blob).expect("blob is valid");
6414 let thumb = extracted.expect("snapshot must include THM section");
6415 assert_eq!(thumb.len(), save_state::THUMBNAIL_LEN);
6416 // Round-trip: thumbnail bytes must match the live framebuffer
6417 // downsample taken at the same cycle.
6418 assert_eq!(thumb, nes.thumbnail());
6419 }
6420
6421 #[test]
6422 fn snapshot_round_trip_still_works_with_thumbnail() {
6423 // ADR-0003 invariant: adding THM must not perturb deterministic
6424 // restore. Re-runs the snapshot_round_trip test with the new
6425 // thumbnail section present in the blob.
6426 let rom = synth_nrom(16, 8);
6427 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
6428 for _ in 0..4 {
6429 nes.run_frame();
6430 }
6431 let cycle = nes.cycle();
6432 let fb_hash_before = fnv_hash(nes.framebuffer());
6433 let blob = nes.snapshot();
6434 for _ in 0..4 {
6435 nes.run_frame();
6436 }
6437 assert_ne!(nes.cycle(), cycle);
6438 nes.restore(&blob)
6439 .expect("restore must succeed with THM present");
6440 assert_eq!(nes.cycle(), cycle);
6441 assert_eq!(fnv_hash(nes.framebuffer()), fb_hash_before);
6442 }
6443
6444 #[test]
6445 fn restore_accepts_v0_9_0_blob_without_thumbnail() {
6446 // ADR-0003 invariant: older slot files without a THM section must
6447 // still restore. Simulate a v0.9.0 blob by stripping the THM
6448 // section out of a freshly-emitted snapshot.
6449 let rom = synth_nrom(16, 8);
6450 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
6451 for _ in 0..3 {
6452 nes.run_frame();
6453 }
6454 let cycle = nes.cycle();
6455 let fb_hash = fnv_hash(nes.framebuffer());
6456 let with_thumb = nes.snapshot();
6457
6458 // Reconstruct a blob without the THM section.
6459 let (_h, body_off) = save_state::parse_header(&with_thumb).unwrap();
6460 let mut without_thumb = with_thumb[..body_off].to_vec();
6461 for s in save_state::SectionIter::new(&with_thumb[body_off..]) {
6462 let s = s.unwrap();
6463 if s.tag == save_state::tag::THM {
6464 continue;
6465 }
6466 save_state::write_section(&mut without_thumb, s.tag, s.version, s.body);
6467 }
6468 assert!(without_thumb.len() < with_thumb.len());
6469 // Extract on the v0.9.0-shaped blob returns None for the thumbnail.
6470 let extracted = Nes::extract_thumbnail(&without_thumb).unwrap();
6471 assert!(extracted.is_none(), "v0.9.0 blob has no THM section");
6472
6473 // Drift then restore from the v0.9.0-shaped blob.
6474 for _ in 0..2 {
6475 nes.run_frame();
6476 }
6477 nes.restore(&without_thumb)
6478 .expect("v0.9.0 blob must restore");
6479 assert_eq!(nes.cycle(), cycle);
6480 assert_eq!(fnv_hash(nes.framebuffer()), fb_hash);
6481 }
6482
6483 #[test]
6484 fn restore_accepts_a_snapshot_followed_by_zero_padding() {
6485 // v2.8.0 (libretro audit §2.2, with §2.1). The libretro core reports a
6486 // `retro_serialize_size` with headroom for expansion devices, so the
6487 // frontend hands `retro_unserialize` this core's own state followed by
6488 // zeros. Both restore paths walk the sections (`SystemBus::restore`
6489 // for BUS/PPU/APU/MAP, then `apply_snapshot` for CPU), so both must end
6490 // at the padding rather than report it as a damaged section.
6491 let rom = synth_nrom(16, 8);
6492 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
6493 for _ in 0..3 {
6494 nes.run_frame();
6495 }
6496 let cycle = nes.cycle();
6497 let fb_hash = fnv_hash(nes.framebuffer());
6498 let mut blob = Vec::new();
6499 nes.snapshot_core_into(&mut blob);
6500 for pad in [1, 8, 9, 10, 26, 160] {
6501 let mut padded = blob.clone();
6502 padded.resize(blob.len() + pad, 0);
6503 nes.run_frame();
6504 nes.restore_quiet(&padded)
6505 .unwrap_or_else(|e| panic!("{pad} bytes of zero padding: {e:?}"));
6506 assert_eq!(nes.cycle(), cycle, "{pad}: cycle restored");
6507 assert_eq!(
6508 fnv_hash(nes.framebuffer()),
6509 fb_hash,
6510 "{pad}: framebuffer restored"
6511 );
6512 }
6513 }
6514
6515 #[test]
6516 fn restore_rejects_every_truncation_even_with_the_zero_tail_rule() {
6517 // v2.8.0, review on #556 (agy). `SectionIter` now ends at an all-zero
6518 // tail, so the question is whether a TRUNCATED state (a short file:
6519 // a frontend passes `retro_unserialize` a buffer of the file's size
6520 // and does not pad it) could now pass as a complete one that happens
6521 // to end in zeros. Every proper prefix of a real snapshot is tried:
6522 // a cut inside a section leaves a tail that starts with a non-zero
6523 // tag and a length the remaining bytes cannot satisfy, and a cut on a
6524 // section boundary drops a required section. Every one is an error.
6525 let rom = synth_nrom(16, 8);
6526 let mut nes = Nes::from_rom(&rom).expect("parse + boot");
6527 for _ in 0..3 {
6528 nes.run_frame();
6529 }
6530 let mut blob = Vec::new();
6531 nes.snapshot_core_into(&mut blob);
6532 let accepted: Vec<usize> = (0..blob.len())
6533 .filter(|&k| nes.restore_quiet(&blob[..k]).is_ok())
6534 .collect();
6535 assert!(
6536 accepted.is_empty(),
6537 "{} of {} truncations restored, first at {:?}",
6538 accepted.len(),
6539 blob.len(),
6540 accepted.first()
6541 );
6542 // The full state still restores after all those rejections.
6543 nes.restore_quiet(&blob)
6544 .expect("the untruncated state restores");
6545 }
6546
6547 /// Build a minimal NSF (3 songs) whose `init` enables all APU channels and
6548 /// programs a steady pulse-1 tone, and whose `play` is a bare `RTS`. Loaded
6549 /// at $8000; init=$8000, play=$800C.
6550 fn synth_tone_nsf() -> Vec<u8> {
6551 let mut f = vec![0u8; 0x80];
6552 f[0..5].copy_from_slice(b"NESM\x1A");
6553 f[0x05] = 1; // version
6554 f[0x06] = 3; // total songs
6555 f[0x07] = 1; // starting song
6556 f[0x08] = 0x00;
6557 f[0x09] = 0x80; // load $8000
6558 f[0x0A] = 0x00;
6559 f[0x0B] = 0x80; // init $8000
6560 f[0x0C] = 0x0C;
6561 f[0x0D] = 0x80; // play $800C
6562 let program: &[u8] = &[
6563 // init ($8000): enable channels + a constant-volume pulse-1 tone.
6564 0xA9, 0x0F, 0x8D, 0x15, 0x40, // LDA #$0F; STA $4015
6565 0xA9, 0xBF, 0x8D, 0x00, 0x40, // LDA #$BF; STA $4000 (duty/const vol)
6566 0x60, // RTS
6567 0xA0, // padding so play lands at $800C
6568 // play ($800C):
6569 0x60, // RTS
6570 ];
6571 f.extend_from_slice(program);
6572 f
6573 }
6574
6575 #[test]
6576 fn nsf_constructs_runs_and_selects_tracks() {
6577 let mut nes = Nes::from_nsf(&synth_tone_nsf()).expect("valid nsf builds");
6578 assert_eq!(nes.nsf_song_count(), 3);
6579 assert_eq!(nes.nsf_current_song(), 0);
6580
6581 // Run several frames: the driver's reset vector runs `init` (enabling
6582 // the APU + pulse-1), then vblank NMI calls `play` each frame. Audio
6583 // must be produced and the run must not panic.
6584 let mut produced = 0usize;
6585 for _ in 0..8 {
6586 nes.run_frame();
6587 produced += nes.drain_audio().len();
6588 }
6589 assert!(produced > 0, "NSF playback must produce audio samples");
6590
6591 // Track select clamps + restarts on the new song.
6592 nes.nsf_set_song(2);
6593 assert_eq!(nes.nsf_current_song(), 2);
6594 nes.run_frame();
6595 nes.nsf_set_song(99);
6596 assert_eq!(nes.nsf_current_song(), 2, "clamped to last song");
6597 }
6598
6599 /// v3.6.0 — a standard 60 Hz NSF must have its `play` called once per
6600 /// frame. It was not, from v2.9.8 to v3.5.x: the driver enabled the vblank
6601 /// NMI with its very first `$2000` write, inside the PPU's post-reset
6602 /// warm-up window (v2.9.8 modelled it), so the write was dropped and no
6603 /// NMI ever came; and it ran `CLI` without inhibiting the APU frame IRQ,
6604 /// so the CPU then spun in the driver's `RTI` stub. Only `init` ever ran.
6605 /// Found by the NSF ripper's gate (`nsf_rip`), which plays a ripped tune
6606 /// back. The 50 Hz timer driver below already inhibited the frame IRQ and
6607 /// needs no NMI, so it was unaffected.
6608 #[test]
6609 fn nsf_standard_rate_calls_play_every_frame() {
6610 let mut f = synth_counting_nsf_50hz();
6611 // Back to the hardware 60 Hz divider (0 = default): the NMI driver.
6612 f[0x6E] = 0;
6613 f[0x6F] = 0;
6614 let mut nes = Nes::from_nsf(&f).expect("valid nsf");
6615 for _ in 0..120 {
6616 nes.run_frame();
6617 }
6618 // `play` increments $00. Two frames go to the warm-up wait, one to
6619 // power-on's empty first frame; every other frame calls play once.
6620 let calls = nes.peek(0x0000);
6621 assert!(
6622 (114..=118).contains(&calls),
6623 "play ran {calls} times in 120 frames"
6624 );
6625 assert!(!nes.is_jammed());
6626 // The frame IRQ is inhibited before `CLI`. Without that the NMI still
6627 // reaches `play`, but between frames the CPU services an IRQ nobody
6628 // acknowledges, through the `RTI` stub, for the rest of the run.
6629 assert!(
6630 !nes.apu_snapshot().frame_irq,
6631 "the frame IRQ is never raised under the driver"
6632 );
6633 }
6634
6635 /// v3.6.0: the same 60 Hz NSF declaring MMC5 audio (header `$7B` bit 3).
6636 /// The player's driver image sat at `$5000-$504F` with its NMI entry at
6637 /// `$5015`, which is also the MMC5's status port; `NsfExpansion` answers
6638 /// that port first, so the NMI fetched the status byte as its first
6639 /// opcode and `play` never ran on any MMC5 NSF.
6640 #[test]
6641 fn an_mmc5_nsf_calls_play_every_frame() {
6642 let mut f = synth_counting_nsf_50hz();
6643 f[0x6E] = 0;
6644 f[0x6F] = 0;
6645 f[0x7B] = 0x08;
6646 let mut nes = Nes::from_nsf(&f).expect("valid nsf");
6647 for _ in 0..120 {
6648 nes.run_frame();
6649 }
6650 let calls = nes.peek(0x0000);
6651 assert!(
6652 (114..=118).contains(&calls),
6653 "play ran {calls} times in 120 frames on an MMC5 NSF"
6654 );
6655 assert!(!nes.is_jammed());
6656 }
6657
6658 /// A minimal non-60-Hz NSF whose `play` routine increments zero-page `$00`,
6659 /// so a test can count how many times the cycle-timer IRQ drove `play`.
6660 fn synth_counting_nsf_50hz() -> Vec<u8> {
6661 let mut f = vec![0u8; 0x80];
6662 f[0..5].copy_from_slice(b"NESM\x1A");
6663 f[0x05] = 1; // version
6664 f[0x06] = 1; // 1 song
6665 f[0x07] = 1; // starting song
6666 f[0x08] = 0x00;
6667 f[0x09] = 0x80; // load $8000
6668 f[0x0A] = 0x00;
6669 f[0x0B] = 0x80; // init $8000
6670 f[0x0C] = 0x06;
6671 f[0x0D] = 0x80; // play $8006
6672 // NTSC play-speed divider $6E-$6F = 20000 µs (~50 Hz) — a non-standard
6673 // rate that selects the cycle-timer IRQ driver instead of vblank-NMI.
6674 f[0x6E] = 0x20;
6675 f[0x6F] = 0x4E; // 0x4E20 = 20000
6676 let program: &[u8] = &[
6677 // init ($8000): enable APU channels, RTS. (6 bytes)
6678 0xA9, 0x0F, 0x8D, 0x15, 0x40, 0x60, // play ($8006): INC $00; RTS
6679 0xE6, 0x00, 0x60,
6680 ];
6681 f.extend_from_slice(program);
6682 f
6683 }
6684
6685 #[test]
6686 fn nsf_nonstandard_rate_drives_play_via_timer_irq() {
6687 let mut nes = Nes::from_nsf(&synth_counting_nsf_50hz()).expect("valid nsf");
6688 // 12 NTSC frames ≈ 0.2 s. A ~50 Hz play-timer IRQ must fire `play`
6689 // (INC $00) several times — proving the cycle-timer IRQ path works
6690 // end-to-end through `run_frame` — but FEWER than the 12 frames, since
6691 // 50 Hz is slower than the 60 Hz once-per-vblank rate.
6692 for _ in 0..12 {
6693 nes.run_frame();
6694 }
6695 let calls = nes.cpu_bus_peek(0x0000);
6696 assert!(
6697 calls > 0,
6698 "timer IRQ must drive `play` at the non-standard rate"
6699 );
6700 assert!(
6701 calls < 12,
6702 "50 Hz must call `play` fewer times than 60 Hz frames (got {calls})"
6703 );
6704 }
6705
6706 /// v2.3.7: `$4014` and `$4016` must actually be attributed.
6707 ///
6708 /// Both sit inside the `$4000-$4017` window the audio-provenance table
6709 /// reserves slots for, and both are handled entirely on the bus — `Bus::write`
6710 /// routes only `$4000-$4013 | $4015 | $4017` to `Apu::write_register`, which
6711 /// is where attribution was recorded. So the two reserved slots could never
6712 /// be filled, while `docs/audio-provenance.md` and the `REG_COUNT` doc
6713 /// comment both stated they were "tracked anyway".
6714 ///
6715 /// Caught by the `Antigravity` reviewer on PR #404. This test fails without
6716 /// `Apu::record_bus_handled_register_write` being called from both bus arms:
6717 /// remove either call and the corresponding `get()` returns `None`.
6718 #[cfg(feature = "debug-hooks")]
6719 #[test]
6720 fn bus_handled_apu_window_writes_are_attributed() {
6721 // `Bus::write` is the ordinary CPU write path both addresses travel.
6722 use rustynes_cpu::Bus as _;
6723
6724 let mut nes = Nes::from_rom(&synth_nrom(16, 8)).expect("nrom builds");
6725 nes.set_audio_provenance(true);
6726 assert!(nes.audio_provenance_armed(), "premise: armed");
6727
6728 // Pin a known attribution context, then write both bus-handled
6729 // addresses through the ordinary CPU write path.
6730 nes.bus.apu.set_attrib_context(0xC123, 4_242);
6731 nes.bus.write(0x4014, 0x02); // OAM DMA page
6732 nes.bus.write(0x4016, 0x01); // controller strobe
6733
6734 let attrib = nes
6735 .bus
6736 .apu
6737 .register_attribution()
6738 .expect("armed, so the table exists");
6739
6740 let dma = attrib
6741 .get(0x4014)
6742 .expect("$4014 must be attributed — it is inside the reserved window");
6743 assert_eq!(dma.pc, 0xC123, "$4014 attributed to the wrong instruction");
6744 assert_eq!(dma.value, 0x02, "$4014 recorded the wrong value");
6745
6746 let strobe = attrib
6747 .get(0x4016)
6748 .expect("$4016 must be attributed — it is inside the reserved window");
6749 assert_eq!(
6750 strobe.pc, 0xC123,
6751 "$4016 attributed to the wrong instruction"
6752 );
6753 assert_eq!(strobe.value, 0x01, "$4016 recorded the wrong value");
6754
6755 // A genuine APU register still works — the new path is additive, not a
6756 // replacement for the one inside `write_register`.
6757 nes.bus.write(0x4015, 0x0F);
6758 assert_eq!(
6759 attrib_value(&nes, 0x4015),
6760 Some(0x0F),
6761 "the normal write_register attribution path must be unaffected"
6762 );
6763 }
6764
6765 /// Small helper so the assertion above reads as one line.
6766 #[cfg(feature = "debug-hooks")]
6767 fn attrib_value(nes: &Nes, addr: u16) -> Option<u8> {
6768 nes.bus
6769 .apu
6770 .register_attribution()
6771 .and_then(|a| a.get(addr))
6772 .map(|w| w.value)
6773 }
6774
6775 #[test]
6776 fn nsf_song_apis_are_inert_on_a_cartridge() {
6777 let mut nes = Nes::from_rom(&synth_nrom(16, 8)).expect("nrom builds");
6778 assert_eq!(nes.nsf_song_count(), 0);
6779 assert_eq!(nes.nsf_current_song(), 0);
6780 nes.nsf_set_song(1); // no-op, must not panic or reset spuriously
6781 assert_eq!(nes.nsf_current_song(), 0);
6782 }
6783
6784 /// v2.3.6: the beam-relative Zapper model is ON by default.
6785 ///
6786 /// It shipped OFF in v2.2.3-v2.3.5 on the reasoning that no light-gun test
6787 /// ROM could adjudicate it and the supported titles were satisfied either
6788 /// way. The second half was false: under the frame-granular model *Duck
6789 /// Hunt* receives its "dark frame then bright frame" probe inverted and can
6790 /// never register a hit. See `SystemBus::set_zapper_temporal_light`.
6791 #[test]
6792 fn zapper_temporal_light_is_on_by_default() {
6793 let mut nes = Nes::from_rom(&synth_nrom(16, 8)).expect("nrom builds");
6794 assert!(
6795 nes.zapper_temporal_light(),
6796 "the beam-relative model must default ON from v2.3.6"
6797 );
6798 nes.set_zapper(1, 100, 120, false);
6799 // Toggling it off and back on must restore the default exactly.
6800 nes.set_zapper_temporal_light(false);
6801 assert!(!nes.zapper_temporal_light());
6802 nes.set_zapper_temporal_light(true);
6803 assert!(nes.zapper_temporal_light());
6804 }
6805
6806 /// The timeline counter is session-local: a save state neither carries it nor
6807 /// restores it, and loading one ADVANCES the live counter instead.
6808 ///
6809 /// Documented on the field, and untestable by `snapshot_schema_audit` for the
6810 /// very reason that makes it true -- the counter lives outside the snapshot,
6811 /// so that audit cannot see it. Pinned here instead, because the two ways
6812 /// serializing it would be wrong are both silent: loading the same slot twice
6813 /// would restore the same generation twice and a consumer would miss the
6814 /// second load, and a value from another session means nothing in this one.
6815 #[test]
6816 fn the_timeline_counter_is_session_local_and_advances_on_restore() {
6817 let rom = synth_nrom(16, 8);
6818 let mut nes = Nes::from_rom(&rom).expect("parse");
6819 nes.run_frame();
6820 let state = nes.snapshot();
6821 let before = nes.timeline_generation();
6822
6823 nes.restore(&state).expect("restore");
6824 let after_first = nes.timeline_generation();
6825 assert!(
6826 after_first > before,
6827 "a restore must advance the timeline counter: {before} -> {after_first}"
6828 );
6829
6830 // The SECOND load of the SAME slot must advance it again. This is the
6831 // assertion that would fail if the counter were serialized -- the restored
6832 // value would be identical both times and a consumer comparing against its
6833 // last-seen value would never notice the second load.
6834 nes.restore(&state).expect("restore again");
6835 assert!(
6836 nes.timeline_generation() > after_first,
6837 "reloading the same slot must still register as a new timeline"
6838 );
6839
6840 // And a snapshot taken now must not encode it: a fresh `Nes` restored from
6841 // this state starts its own count rather than adopting ours.
6842 let mut fresh = Nes::from_rom(&rom).expect("parse");
6843 assert_eq!(
6844 fresh.timeline_generation(),
6845 0,
6846 "a fresh Nes must start at zero"
6847 );
6848 fresh.restore(&nes.snapshot()).expect("restore into fresh");
6849 assert_eq!(
6850 fresh.timeline_generation(),
6851 1,
6852 "the fresh instance must count its own restores, not inherit a stored value"
6853 );
6854 }
6855
6856 /// A `UxROM` (mapper 2) image written for the live-ROM-write tests
6857 /// (public-domain by construction): 64 KiB PRG in four 16 KiB banks, the
6858 /// last fixed at `$C000`, and 8 KiB of CHR-ROM. The program, in the fixed
6859 /// bank, selects bank 1 at `$8000` (storing `$01` over a ROM byte that
6860 /// holds `$01`, so a bus conflict changes nothing), then every pass loads
6861 /// `$8010` into `$10` and, through `$2006` / `$2007`, the PPU's byte at
6862 /// `$0010` into `$11`. Gated like its two callers: without `debug-hooks`
6863 /// (e.g. `-p rustynes-core --features cpu-boot-trace`) it is dead code.
6864 #[cfg(feature = "debug-hooks")]
6865 fn romwrite_uxrom() -> Vec<u8> {
6866 const FIXED: usize = 3 * 0x4000; // PRG offset of `$C000`.
6867 const PROGRAM: [u8; 34] = [
6868 0x78, // SEI
6869 0xA9, 0x01, 0x8D, 0x40, 0xC0, // LDA #$01 ; STA $C040 (select bank 1)
6870 0xAD, 0x10, 0x80, 0x85, 0x10, // loop: LDA $8010 ; STA $10
6871 0xAD, 0x02, 0x20, // LDA $2002 (reset the address latch)
6872 0xA9, 0x00, 0x8D, 0x06, 0x20, // LDA #$00 ; STA $2006
6873 0xA9, 0x10, 0x8D, 0x06, 0x20, // LDA #$10 ; STA $2006
6874 0xAD, 0x07, 0x20, // LDA $2007 (fills the read buffer)
6875 0xAD, 0x07, 0x20, 0x85, 0x11, // LDA $2007 ; STA $11
6876 0x4C, 0x06, // JMP loop ($C006), low byte ...
6877 ];
6878 let mut rom = b"NES\x1A\x04\x01\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00".to_vec();
6879 let mut prg = vec![0u8; 0x10000];
6880 prg[FIXED..FIXED + PROGRAM.len()].copy_from_slice(&PROGRAM);
6881 prg[FIXED + PROGRAM.len()] = 0xC0; // ... and high byte.
6882 prg[FIXED + 0x40] = 0x01;
6883 // Bank 0 and bank 1 hold different bytes at offset $10.
6884 prg[0x0010] = 0x11;
6885 prg[0x4010] = 0x22;
6886 for v in [0xFFFA, 0xFFFC, 0xFFFE] {
6887 prg[v] = 0x00;
6888 prg[v + 1] = 0xC0;
6889 }
6890 rom.extend_from_slice(&prg);
6891 let mut chr = vec![0u8; 0x2000];
6892 chr[0x10] = 0x33;
6893 rom.extend_from_slice(&chr);
6894 rom
6895 }
6896
6897 /// v3.7.0 (`T-HACK-BPS-RECORDER`): a PRG-ROM byte written by image offset
6898 /// is the byte the CPU fetches at the address the current bank maps it
6899 /// to, and only there; a CHR-ROM byte is the byte the PPU reads at its
6900 /// pattern address, through a real `$2007` read by the program.
6901 #[cfg(feature = "debug-hooks")]
6902 #[test]
6903 fn a_live_rom_write_is_read_through_the_current_banking() {
6904 use crate::{RomSpace, RomWriteError};
6905 let rom = romwrite_uxrom();
6906 let mut nes = Nes::from_rom(&rom).expect("uxrom");
6907 assert_eq!(nes.debug_rom_len(RomSpace::Prg), Some(0x10000));
6908 assert_eq!(nes.debug_rom_len(RomSpace::Chr), Some(0x2000));
6909 nes.run_frame();
6910 nes.run_frame();
6911 assert_eq!((nes.peek(0x10), nes.peek(0x11)), (0x22, 0x33), "clean");
6912 // Bank 0 is not mapped at $8000 (bank 1 is): editing it changes
6913 // nothing the program reads.
6914 nes.debug_poke_rom(RomSpace::Prg, 0x0010, 0xAA)
6915 .expect("in range");
6916 nes.run_frame();
6917 assert_eq!(nes.peek(0x10), 0x22, "bank 0 is not mapped");
6918 assert_eq!(nes.debug_peek_rom(RomSpace::Prg, 0x0010), Some(0xAA));
6919 // Bank 1's byte is: the next frame's fetch of $8010 returns it.
6920 nes.debug_poke_rom(RomSpace::Prg, 0x4010, 0xBB)
6921 .expect("in range");
6922 assert_eq!(nes.cpu_bus_peek(0x8010), 0xBB);
6923 nes.run_frame();
6924 assert_eq!(nes.peek(0x10), 0xBB, "the CPU fetches the edited byte");
6925 // CHR: the program's $2007 read of $0010 returns the edit.
6926 nes.debug_poke_rom(RomSpace::Chr, 0x0010, 0xCC)
6927 .expect("in range");
6928 assert_eq!(nes.ppu_bus_peek(0x0010), 0xCC);
6929 nes.run_frame();
6930 assert_eq!(
6931 nes.peek(0x11),
6932 0xCC,
6933 "the PPU reads the edited pattern byte"
6934 );
6935 // Past the end: refused, nothing changes.
6936 assert_eq!(
6937 nes.debug_poke_rom(RomSpace::Prg, 0x10000, 0),
6938 Err(RomWriteError::OutOfRange {
6939 space: RomSpace::Prg,
6940 offset: 0x10000,
6941 len: 0x10000
6942 })
6943 );
6944 assert_eq!(nes.debug_peek_rom(RomSpace::Chr, 0x2000), None);
6945 // A CHR-RAM board offers no CHR-ROM.
6946 let mut ram = rom;
6947 ram[5] = 0;
6948 ram.truncate(16 + 0x10000);
6949 let mut nes = Nes::from_rom(&ram).expect("uxrom, CHR-RAM");
6950 assert_eq!(nes.debug_rom_len(RomSpace::Chr), None);
6951 assert_eq!(
6952 nes.debug_poke_rom(RomSpace::Chr, 0, 1),
6953 Err(RomWriteError::Unsupported(RomSpace::Chr))
6954 );
6955 }
6956
6957 /// v3.7.0: save states carry no ROM. A state taken on a patched session
6958 /// and restored into a console built from the clean image runs the clean
6959 /// ROM (the edit is not in the state), and restoring a state into the
6960 /// patched console keeps the edit (a rewind does not undo it). The
6961 /// state is the same bytes with or without the edit.
6962 #[cfg(feature = "debug-hooks")]
6963 #[test]
6964 fn save_states_carry_no_rom_edit() {
6965 use crate::RomSpace;
6966 let rom = romwrite_uxrom();
6967 let mut clean = Nes::from_rom(&rom).expect("uxrom");
6968 let mut patched = Nes::from_rom(&rom).expect("uxrom");
6969 clean.run_frame();
6970 patched.run_frame();
6971 patched
6972 .debug_poke_rom(RomSpace::Prg, 0x4010, 0xBB)
6973 .expect("in range");
6974 let state = patched.snapshot();
6975 assert_eq!(state, clean.snapshot(), "the edit is not in the state");
6976 let mut fresh = Nes::from_rom(&rom).expect("uxrom");
6977 fresh.restore(&state).expect("restores");
6978 fresh.run_frame();
6979 assert_eq!(fresh.peek(0x10), 0x22, "the clean ROM runs");
6980 patched.restore(&state).expect("restores");
6981 patched.run_frame();
6982 assert_eq!(patched.peek(0x10), 0xBB, "the edit survives a restore");
6983 assert_eq!(
6984 patched.rom_sha256(),
6985 fresh.rom_sha256(),
6986 "the identity stays the clean image's"
6987 );
6988 }
6989}