rustynes_core/hardware_options.rs
1//! v2.9.8 — the emulation options a movie or a netplay session must agree on.
2//!
3//! The determinism contract is "same ROM + same seed + same input ⇒
4//! bit-identical output". Until v2.9.8 a `.rnm` movie recorded the ROM and the
5//! input and nothing else, and netplay compared only the ROM, so every host
6//! knob that changes what the console *does* was left to whatever the player
7//! happened to have configured: record on the Famicom model, replay on the NES
8//! model, and the replay silently ran a different machine. The maintainer's
9//! decision of 2026-10-01 is that a replay or a peer must never silently
10//! diverge, so this module gives that knob set one canonical, serialisable
11//! form, [`HardwareOptions`], which the movie stores in its header and netplay
12//! folds into its handshake.
13//!
14//! Two kinds of fact are kept apart here because they are enforced
15//! differently:
16//!
17//! - **[`HardwareOptions`] are host settings** — a console model, a die
18//! revision, a power-on fill, an overclock, a Game Genie code. The host can
19//! change them, so a movie *applies* them before frame 0 whatever the
20//! player's own settings are.
21//! - **[`BoardDescription`] is what the cartridge header says** — mapper,
22//! submapper, mirroring, RAM sizes. Since v2.9.8 `Nes::rom_sha256` excludes
23//! the 16-byte header, so two images with the same PRG/CHR but different
24//! (or differently corrected) headers share an identity while building
25//! different machines. A host cannot apply a header, so a movie *checks* the
26//! description and refuses on a mismatch, naming the field.
27//!
28//! # What is deliberately not here
29//!
30//! The survey behind this list is in `docs/frontend.md` § "What a movie
31//! records". In short: presentation (custom palette, the APU channel mask,
32//! gain and analog filter model, the sample rate), performance selectors that
33//! are proven byte-identical (the fast dot path), debug observability
34//! (tracing, logging, breakpoints, provenance), and **inputs** — the two
35//! standard pads are in the movie's input stream, while Four Score players
36//! 3/4, expansion devices, the Famicom microphone, Vs. coins / service and FDS
37//! disk swaps are per-frame inputs a `.rnm` does not carry (a documented limit
38//! of the input stream, not an option).
39//!
40//! This module is `no_std`-clean: `core` + `alloc` and the save-state
41//! `BinWriter` / `BinReader` primitives only.
42
43use alloc::string::{String, ToString};
44use alloc::vec::Vec;
45
46use rustynes_mappers::{ConsoleType, Mirroring, VsPpuType};
47use sha2::{Digest, Sha256};
48
49use crate::Cpu2A03Revision;
50use crate::Region;
51use crate::genie::GenieCode;
52use crate::nes::{ConsoleModel, Nes, PowerOnRam};
53use crate::save_state::{BinReader, BinWriter};
54use rustynes_ppu::{PaletteInit, PpuRevision};
55
56/// Why an options or board block could not be decoded.
57///
58/// Carried by `MovieError::BadOptions`; a `&'static str` because every case
59/// is a fixed fact about the bytes ("an unknown console-model byte"), never a
60/// value worth echoing back from an untrusted file.
61pub type OptionsDecodeError = &'static str;
62
63/// The most Game Genie codes one record may carry. A real cheat list is a
64/// handful of codes; the bound exists so a hostile count byte cannot ask the
65/// decoder to loop or allocate without limit. 255 is what the count byte can
66/// express, so it costs no legitimate list.
67const MAX_GENIE_CODES: usize = u8::MAX as usize;
68
69/// v3.0.0 (ADR 0045) — which emulator *behaviour* a movie or a netplay peer
70/// expects, beside the options and the board that [`HardwareOptions`] and
71/// [`BoardDescription`] describe.
72///
73/// Two builds with identical options can still emulate a game differently
74/// whenever an accuracy fix lands: v3.0.0's T-MMC3-BG-A12, for instance,
75/// moves the MMC3 IRQ for games with the background at `$1000`. Without a
76/// record of which behaviour a recording assumes, a movie replays under the
77/// new timing and a mixed-version netplay session desyncs, and neither says
78/// why. `.rnm` format 5 records this number, and netplay protocol 6 sends it
79/// in the handshake; a mismatch is refused, naming both epochs.
80///
81/// **The bump rule.** Increment it, in the same change, whenever a change
82/// makes the core produce a different framebuffer, audio sample or bus cycle
83/// from the same inputs than the last release did. Every such change already
84/// re-blesses a golden or moves a commercial snapshot, so that is the
85/// trigger to look for. Refactors, byte-identical performance work, frontend
86/// features and new mapper families (which have no earlier output to differ
87/// from) do not bump it. A release that moved goldens without raising it
88/// breaks the promise this constant exists to keep.
89///
90/// It was 1 at v3.0.0, the first release to carry it. Earlier builds have no
91/// epoch, and are refused by the movie format (5) and the protocol (6)
92/// instead.
93///
94/// | epoch | release | what moved |
95/// | --- | --- | --- |
96/// | 1 | v3.0.0 | the MMC3 background-at-`$1000` A12 rule (T-MMC3-BG-A12) |
97/// | 2 | v3.0.1 | mapper 45 CHR-RAM unbanked (T-GA23C-CHRRAM; *Famicom Yarou Vol.1*) |
98/// | 3 | v3.1.0 | a DMC load DMA refused by a write takes four cycles; sprite evaluation starts at OAMADDR as of dot 65 and keeps a misaligned OAMADDR when X is in range (AccuracyCoin re-sync to `f5f41dc2`) |
99/// | 4 | v3.2.0 | mapper 290's 32 KiB PRG mode maps both halves in order (*Asder 20-in-1* boots); a 24C02 keeps its word address across a START (mapper 16, 157); VRC4's IRQ mode bit reads 1 = cycle, 0 = scanline (mappers 21, 23, 25); VRC2 mirroring ignores bit 1, and 23 / 25 submapper 3 are built as VRC2; mapper 71 submapper 0 detects *Fire Hawk*'s `$9000` single-screen register |
100/// | 5 | v3.3.0 | a CHR-RAM write goes through the bank registers its read does (T-VRC4-CHRRAM-BANKING: mappers 19, 21-26, 34 NINA-001, 69, 75, 151); mapper 71's bank select answers only at `$C000-$FFFF`, and *Fire Hawk*'s (submapper 1) mirroring register at `$8000-$9FFF` (T-MAPPER71-DECODE) |
101/// | 6 | v3.5.0 | the MMC5 detects scanlines from the PPU's reads (`nesdev_wiki/MMC5.xhtml`): a `$5203` = N IRQ rises at line N dot 4, not line N - 1 dot 0, and nothing counts with rendering off (*Uchuu Keibitai SDF*'s playfield moves down one line; *Castlevania III*, *Gemfire* and *L'Empereur* audio) |
102/// | 7 | v3.5.1 | the MMC5's split-screen and extended-attribute CHR banks apply only to fetches made while the PPU renders (T-MMC5-LATCH-VBLANK): a `$2007` CHR read in vertical blank, or with rendering off, reads the bank registers, not the last tile's latched bank. No golden or snapshot moved and a probe found no affected access in three MMC5 games; raised anyway, by the maintainer's call (2026-10-23), because the bus value changes for software that makes that read |
103/// | 8 | v3.6.0 | NSF playback: a 60 Hz NSF's `play` routine runs every frame again (the driver inhibits the APU frame IRQ and enables the NMI after the PPU's warm-up, T-AUDIO-STEMS), and the driver moved from `$5000` to `$5100`, clear of the MMC5 status port, so an MMC5 NSF plays. No golden or fingerprint covers an NSF, so nothing recorded moved; raised by the maintainer's call (2026-10-24) because NSF audio and bus traffic change from the same inputs. The same epoch carries the noise-channel fix: the LFSR now shifts every table period in CPU cycles, as the NESdev page gives it, instead of every 2 x (N + 1); 112 commercial and test-ROM audio hashes moved, no frame or cycle count |
104/// | 9 | v3.6.1 | the MMC5's background-fetch window closes on the in-frame flag's idle rule while rendering (a few dots into line 240) and at a vertical blank whose flag a `$2002` read suppressed (T-MMC5-WINDOW-END), so a `$2007` CHR access there reads the bank registers; and the MMC5 split's first two tiles of a frame, fetched on the pre-render line, take row `$5201 + 0` instead of `($5201 + 261) % 240` (`+ 311` on PAL and Dendy). No golden, snapshot or fingerprint moved (4,048 tests, *Uchuu Keibitai SDF* included); raised by v3.5.1's precedent, because a frame and a bus value change from the same inputs for software that splits the first two columns with `$5201` set or reads CHR on line 240 |
105/// | 10 | v3.6.2 | *Rad Racer*'s per-game coherent mid-line copy correction (`coherent_midline_copy`, ADR 0051), on by default for the game's three dumps only: a delayed `$2006` copy whose countdown ends inside a background fetch group is held to the end of that group, so no tile is fetched from two addresses. A deliberate departure from hardware; its 8-pixel dash in the sand on line 139, about one race frame in eleven, is gone, and the game's default frames change. Recorded in movies (`.rnm` format 8, minimum 8) and the netplay digest; protocol 9 unchanged, since a v3.6.1 peer is refused on the epoch. The attribute-read rule this release first carried was withdrawn (ADR 0030, 2026-11-06), so no other game's output moves |
106pub const EMULATION_EPOCH: u32 = 10;
107
108/// Every host-settable option that changes what the emulated console does.
109///
110/// [`Default`] is the stock NES: the configuration every release before the
111/// option existed emulated, and what a foreign movie import (`.fm2`, `.bk2`,
112/// `.fcm`, `.fmv`, `.vmv`, `.mc2`) records, because those formats cannot say
113/// anything else.
114///
115/// One exception to "all defaults are the default build": the Vs. PPU type is
116/// a property of the cartridge header that a host may override, so its
117/// default is `None`, meaning "whatever the header declares" — applying a
118/// stock `VsPpuType::None` to a Vs. cartridge would strip its RGB PPU.
119///
120/// `#[non_exhaustive]` since v3.0.0 (T-API-EXTENSIBLE): outside this crate,
121/// start from [`HardwareOptions::default`] (the stock NES) or
122/// [`HardwareOptions::capture`] and set the fields that differ. A later
123/// option is then not a break.
124#[derive(Clone, Debug, Eq, PartialEq, Hash)]
125#[non_exhaustive]
126// Five independent switches (OAM decay, Four Score, the Zapper light model,
127// the sprite limit, the per-game coherent mid-line copy correction), each
128// mirroring one `Nes` setter one-to-one; no two are
129// states of one thing, so an enum or bitflags would only obscure the mapping.
130#[allow(clippy::struct_excessive_bools)]
131pub struct HardwareOptions {
132 /// Which console's reset wiring is modelled ([`Nes::set_console_model`]).
133 pub console_model: ConsoleModel,
134 /// The 2C02 die revision ([`Nes::set_ppu_revision`]).
135 pub ppu_revision: PpuRevision,
136 /// The 2A03 die revision ([`Nes::set_cpu_2a03_revision`]).
137 pub cpu_2a03_revision: Cpu2A03Revision,
138 /// The optional OAM-decay model ([`Nes::set_oam_decay`]).
139 pub oam_decay: bool,
140 /// The power-on work-RAM fill ([`Nes::set_power_on_ram`]).
141 pub power_on_ram: PowerOnRam,
142 /// The power-up palette-RAM contents ([`Nes::set_power_up_palette`]).
143 pub power_up_palette: PaletteInit,
144 /// The extra-vblank-scanline overclock ([`Nes::set_extra_scanlines`]).
145 pub extra_scanlines: u16,
146 /// The CPU-multiplier overclock, `1..=MAX_CPU_OVERCLOCK`
147 /// ([`Nes::set_cpu_overclock`]); `1` is stock. v3.1.0. A value outside
148 /// that range never reaches the core as written: decoding a record
149 /// refuses it, and applying one clamps it (`0` to `1`, anything above to
150 /// the maximum), as `Nes::set_cpu_overclock` does.
151 pub cpu_overclock: u8,
152 /// Draw the sprites beyond the eighth on a scanline
153 /// ([`Nes::set_sprite_limit_disabled`]); render-only. v3.1.0.
154 pub sprite_limit_disabled: bool,
155 /// The per-game coherent mid-line copy correction
156 /// ([`Nes::set_coherent_midline_copy`]); render-only, a deliberate
157 /// departure from hardware, on by default for *Rad Racer*. v3.6.2.
158 pub coherent_midline_copy: bool,
159 /// A forced MMC3 IRQ revision ([`Nes::set_mmc3_revision_override`]);
160 /// `None` = the header's. v3.1.0.
161 pub mmc3_revision: Option<rustynes_mappers::Mmc3Revision>,
162 /// Whether the Four Score adapter is plugged in ([`Nes::set_four_score`]).
163 /// It changes `$4016` / `$4017` reads 9-24 even with players 3/4 idle.
164 pub four_score: bool,
165 /// The beam-relative Zapper light model
166 /// ([`Nes::set_zapper_temporal_light`]).
167 pub zapper_temporal_light: bool,
168 /// The Vs. System DIP-switch bank ([`Nes::set_vs_dip`]); read through
169 /// `$4016` / `$4017` on Vs. carts, inert elsewhere.
170 pub vs_dip: u8,
171 /// The Vs. System PPU type ([`Nes::set_vs_ppu_type`]); `None` = the
172 /// header's. See the type-level note.
173 pub vs_ppu_type: Option<VsPpuType>,
174 /// The per-game nametable mirroring override
175 /// ([`Nes::set_mirroring_override`]); `None` = the mapper decides.
176 pub mirroring_override: Option<Mirroring>,
177 /// The active Game Genie codes, canonical upper-case strings in address
178 /// order ([`Nes::add_genie_code`]).
179 pub genie_codes: Vec<String>,
180}
181
182impl Default for HardwareOptions {
183 fn default() -> Self {
184 Self {
185 console_model: ConsoleModel::default(),
186 ppu_revision: PpuRevision::default(),
187 cpu_2a03_revision: Cpu2A03Revision::default(),
188 oam_decay: false,
189 power_on_ram: PowerOnRam::default(),
190 power_up_palette: PaletteInit::default(),
191 extra_scanlines: 0,
192 cpu_overclock: 1,
193 sprite_limit_disabled: false,
194 coherent_midline_copy: false,
195 mmc3_revision: None,
196 four_score: false,
197 // The core's own default since v2.2.x (`zapper_temporal_light`
198 // is on in a freshly-built `Nes`); the stock machine, not `false`.
199 zapper_temporal_light: true,
200 vs_dip: 0,
201 vs_ppu_type: None,
202 mirroring_override: None,
203 genie_codes: Vec::new(),
204 }
205 }
206}
207
208impl HardwareOptions {
209 /// The options `nes` is running with right now.
210 #[must_use]
211 pub fn capture(nes: &Nes) -> Self {
212 Self {
213 console_model: nes.console_model(),
214 ppu_revision: nes.ppu_revision(),
215 cpu_2a03_revision: nes.cpu_2a03_revision(),
216 oam_decay: nes.oam_decay_enabled(),
217 power_on_ram: nes.power_on_ram(),
218 power_up_palette: nes.power_up_palette(),
219 extra_scanlines: nes.extra_scanlines(),
220 cpu_overclock: nes.cpu_overclock(),
221 sprite_limit_disabled: nes.sprite_limit_disabled(),
222 coherent_midline_copy: nes.coherent_midline_copy(),
223 mmc3_revision: nes.mmc3_revision_override(),
224 four_score: nes.four_score(),
225 zapper_temporal_light: nes.zapper_temporal_light(),
226 vs_dip: nes.vs_dip(),
227 vs_ppu_type: Some(nes.vs_ppu_type()),
228 mirroring_override: nes.mirroring_override(),
229 genie_codes: nes.genie_codes().map(|g| g.code().to_string()).collect(),
230 }
231 }
232
233 /// Apply every option to `nes`, including the two power-on fills.
234 ///
235 /// The fills **write live state**: [`Nes::set_power_on_ram`] refills work
236 /// RAM and the open-bus latch, and [`Nes::set_power_up_palette`] rewrites
237 /// palette RAM. That is right before a power cycle or a save-state restore
238 /// (which replace that state anyway) and wrong in the middle of a game,
239 /// where [`Self::apply_live`] is the call to make.
240 ///
241 /// # Errors
242 ///
243 /// Returns the offending code if a Game Genie string does not decode.
244 /// Codes read through [`Self::read_from`] are validated there, so this
245 /// can only fail for a hand-built value.
246 pub fn apply(&self, nes: &mut Nes) -> Result<(), String> {
247 nes.set_power_on_ram(self.power_on_ram);
248 nes.set_power_up_palette(self.power_up_palette);
249 self.apply_live(nes)
250 }
251
252 /// Apply every option except the two power-on fills, never writing work
253 /// RAM or palette RAM. Each knob is compared first and set only if it
254 /// differs, so calling this once per frame to hold a movie's options in
255 /// place costs a handful of comparisons.
256 ///
257 /// The fills are excluded because they act only at the next power cycle
258 /// and applying them writes the running game's RAM; see [`Self::apply`].
259 ///
260 /// # Errors
261 ///
262 /// Returns the offending code if a Game Genie string does not decode.
263 pub fn apply_live(&self, nes: &mut Nes) -> Result<(), String> {
264 if nes.console_model() != self.console_model {
265 nes.set_console_model(self.console_model);
266 }
267 if nes.ppu_revision() != self.ppu_revision {
268 nes.set_ppu_revision(self.ppu_revision);
269 }
270 if nes.cpu_2a03_revision() != self.cpu_2a03_revision {
271 nes.set_cpu_2a03_revision(self.cpu_2a03_revision);
272 }
273 if nes.oam_decay_enabled() != self.oam_decay {
274 nes.set_oam_decay(self.oam_decay);
275 }
276 if nes.extra_scanlines() != self.extra_scanlines {
277 nes.set_extra_scanlines(self.extra_scanlines);
278 }
279 if nes.cpu_overclock() != self.cpu_overclock {
280 nes.set_cpu_overclock(self.cpu_overclock);
281 }
282 if nes.sprite_limit_disabled() != self.sprite_limit_disabled {
283 nes.set_sprite_limit_disabled(self.sprite_limit_disabled);
284 }
285 if nes.coherent_midline_copy() != self.coherent_midline_copy {
286 nes.set_coherent_midline_copy(self.coherent_midline_copy);
287 }
288 if nes.mmc3_revision_override() != self.mmc3_revision {
289 nes.set_mmc3_revision_override(self.mmc3_revision);
290 }
291 if nes.four_score() != self.four_score {
292 nes.set_four_score(self.four_score);
293 }
294 if nes.zapper_temporal_light() != self.zapper_temporal_light {
295 nes.set_zapper_temporal_light(self.zapper_temporal_light);
296 }
297 if nes.vs_dip() != self.vs_dip {
298 nes.set_vs_dip(self.vs_dip);
299 }
300 if let Some(t) = self.vs_ppu_type
301 && nes.vs_ppu_type() != t
302 {
303 nes.set_vs_ppu_type(t);
304 }
305 if nes.mirroring_override() != self.mirroring_override {
306 nes.set_mirroring_override(self.mirroring_override);
307 }
308 // The live codes iterate in address order, as `capture` records them,
309 // so an unchanged list compares equal without sorting.
310 if !nes
311 .genie_codes()
312 .map(GenieCode::code)
313 .eq(self.genie_codes.iter().map(String::as_str))
314 {
315 nes.clear_genie_codes();
316 for code in &self.genie_codes {
317 nes.add_genie_code(code).map_err(|_| code.clone())?;
318 }
319 }
320 Ok(())
321 }
322
323 /// Put `nes` back on these options after a movie ran on others, without
324 /// disturbing the game in progress.
325 ///
326 /// [`Self::apply_live`] alone would leave the movie's power-on fills
327 /// stored, so the player's next power cycle would boot with the movie's
328 /// RAM pattern. Storing the player's fills means calling their setters,
329 /// which write work RAM and palette RAM, so this takes a snapshot first
330 /// and restores it afterwards: the snapshot carries RAM, the open-bus
331 /// latch and palette RAM but not configuration, so the restore puts the
332 /// running game back exactly while the stored fills stay the player's.
333 /// Skipped when the fills already match, which is the common case.
334 ///
335 /// # Errors
336 ///
337 /// Returns the offending code if a Game Genie string does not decode.
338 pub fn restore_after_playback(&self, nes: &mut Nes) -> Result<(), String> {
339 if nes.power_on_ram() != self.power_on_ram
340 || nes.power_up_palette() != self.power_up_palette
341 {
342 let snap = nes.snapshot();
343 nes.set_power_on_ram(self.power_on_ram);
344 nes.set_power_up_palette(self.power_up_palette);
345 // A snapshot this build just took of this machine always
346 // restores; `restore_quiet` keeps the rewind history, which still
347 // describes the timeline the player is on.
348 let restored = nes.restore_quiet(&snap);
349 debug_assert!(restored.is_ok(), "own snapshot must restore");
350 }
351 self.apply_live(nes)
352 }
353
354 /// Append the canonical encoding to `w`.
355 ///
356 /// Layout (all little-endian): console model, PPU revision, 2A03
357 /// revision, OAM decay, power-on RAM kind + `u64` payload, power-up
358 /// palette, extra scanlines (`u16`), CPU overclock, the sprite-limit flag
359 /// and the MMC3 revision override (`0` = header, `1` = Sharp, `2` = the
360 /// alternate; all three since `.rnm` format 6 and netplay protocol 7,
361 /// v3.1.0; the coherent mid-line copy flag follows the sprite-limit flag
362 /// since `.rnm` format 8, v3.6.2), Four Score, Zapper light model, Vs.
363 /// DIP, Vs. PPU type (`0xFF` = the header's), mirroring override (`0` =
364 /// none, else variant + 1), then a code count and each Game Genie code as
365 /// a length byte plus ASCII. Every enum is an explicit byte, never a
366 /// discriminant cast, so reordering a Rust enum cannot silently change
367 /// what an old file means.
368 pub fn write_to(&self, w: &mut BinWriter) {
369 w.u8(match self.console_model {
370 ConsoleModel::Nes => 0,
371 ConsoleModel::Famicom => 1,
372 });
373 w.u8(match self.ppu_revision {
374 PpuRevision::Rp2c02H => 0,
375 PpuRevision::Rp2c02G => 1,
376 });
377 w.u8(match self.cpu_2a03_revision {
378 Cpu2A03Revision::Rp2A03G => 0,
379 Cpu2A03Revision::Rp2A03H => 1,
380 });
381 w.u8(u8::from(self.oam_decay));
382 let (kind, value) = match self.power_on_ram {
383 PowerOnRam::Zeroed => (0u8, 0u64),
384 PowerOnRam::Seeded(seed) => (1, seed),
385 PowerOnRam::Filled(byte) => (2, u64::from(byte)),
386 };
387 w.u8(kind);
388 w.u64(value);
389 w.u8(match self.power_up_palette {
390 PaletteInit::Zeroed => 0,
391 PaletteInit::Blargg => 1,
392 });
393 w.u16(self.extra_scanlines);
394 w.u8(self.cpu_overclock);
395 w.u8(u8::from(self.sprite_limit_disabled));
396 w.u8(u8::from(self.coherent_midline_copy));
397 w.u8(match self.mmc3_revision {
398 None => 0,
399 Some(rustynes_mappers::Mmc3Revision::Sharp) => 1,
400 Some(rustynes_mappers::Mmc3Revision::Nec) => 2,
401 });
402 w.u8(u8::from(self.four_score));
403 w.u8(u8::from(self.zapper_temporal_light));
404 w.u8(self.vs_dip);
405 w.u8(self.vs_ppu_type.map_or(0xFF, vs_ppu_to_byte));
406 w.u8(self
407 .mirroring_override
408 .map_or(0, |m| mirroring_to_byte(m) + 1));
409 let count = self.genie_codes.len().min(MAX_GENIE_CODES);
410 w.u8(u8::try_from(count).unwrap_or(u8::MAX));
411 for code in self.genie_codes.iter().take(count) {
412 let bytes = code.as_bytes();
413 w.u8(u8::try_from(bytes.len()).unwrap_or(u8::MAX));
414 w.bytes(&bytes[..bytes.len().min(usize::from(u8::MAX))]);
415 }
416 }
417
418 /// Decode what [`Self::write_to`] wrote. Strict: an unknown enum byte, a
419 /// boolean other than 0 or 1, or a Game Genie code that does not decode is
420 /// an error, never a silent default, because a default here is exactly
421 /// the silent divergence this record exists to prevent.
422 ///
423 /// # Errors
424 ///
425 /// A fixed description of the first malformed field, or `"truncated"`.
426 pub fn read_from(r: &mut BinReader<'_>) -> Result<Self, OptionsDecodeError> {
427 let console_model = match byte(r)? {
428 0 => ConsoleModel::Nes,
429 1 => ConsoleModel::Famicom,
430 _ => return Err("unknown console-model byte"),
431 };
432 let ppu_revision = match byte(r)? {
433 0 => PpuRevision::Rp2c02H,
434 1 => PpuRevision::Rp2c02G,
435 _ => return Err("unknown PPU-revision byte"),
436 };
437 let cpu_2a03_revision = match byte(r)? {
438 0 => Cpu2A03Revision::Rp2A03G,
439 1 => Cpu2A03Revision::Rp2A03H,
440 _ => return Err("unknown 2A03-revision byte"),
441 };
442 let oam_decay = flag(r, "OAM-decay flag is not 0 or 1")?;
443 let kind = byte(r)?;
444 let value = r.u64().map_err(|_| "truncated")?;
445 let power_on_ram = match kind {
446 0 if value == 0 => PowerOnRam::Zeroed,
447 1 => PowerOnRam::Seeded(value),
448 2 => {
449 PowerOnRam::Filled(u8::try_from(value).map_err(|_| "power-on fill is not a byte")?)
450 }
451 _ => return Err("unknown power-on RAM kind"),
452 };
453 let power_up_palette = match byte(r)? {
454 0 => PaletteInit::Zeroed,
455 1 => PaletteInit::Blargg,
456 _ => return Err("unknown power-up palette byte"),
457 };
458 let extra_scanlines = r.u16().map_err(|_| "truncated")?;
459 // NC-11 (v2.9.9): the core clamps the overclock, so a larger value
460 // could only come from an edited file, and would not replay as
461 // written.
462 if extra_scanlines > crate::nes::MAX_EXTRA_SCANLINES {
463 return Err("extra-scanline overclock is above the core's maximum");
464 }
465 // The core clamps the multiplier to 1..=MAX_CPU_OVERCLOCK, so any other
466 // byte could not replay as written.
467 let cpu_overclock = byte(r)?;
468 if cpu_overclock == 0 || cpu_overclock > crate::nes::MAX_CPU_OVERCLOCK {
469 return Err("CPU overclock is outside 1..=MAX_CPU_OVERCLOCK");
470 }
471 let sprite_limit_disabled = flag(r, "sprite-limit flag is not 0 or 1")?;
472 let coherent_midline_copy = flag(r, "coherent mid-line copy flag is not 0 or 1")?;
473 let mmc3_revision = match byte(r)? {
474 0 => None,
475 1 => Some(rustynes_mappers::Mmc3Revision::Sharp),
476 2 => Some(rustynes_mappers::Mmc3Revision::Nec),
477 _ => return Err("unknown MMC3 revision byte"),
478 };
479 let four_score = flag(r, "Four Score flag is not 0 or 1")?;
480 let zapper_temporal_light = flag(r, "Zapper light flag is not 0 or 1")?;
481 let vs_dip = byte(r)?;
482 let vs_ppu_type = match byte(r)? {
483 0xFF => None,
484 b => Some(vs_ppu_from_byte(b).ok_or("unknown Vs. PPU type byte")?),
485 };
486 let mirroring_override = match byte(r)? {
487 0 => None,
488 b => Some(mirroring_from_byte(b - 1).ok_or("unknown mirroring byte")?),
489 };
490 let count = usize::from(byte(r)?);
491 // Canonical form, as `capture` records it and the console holds it:
492 // one code per address, the later one winning, in address order.
493 // A list in any other shape never compared equal to the live one,
494 // so `apply_live` cleared and re-added every code on every frame
495 // (NC-13, v2.9.9).
496 let mut by_addr = alloc::collections::BTreeMap::new();
497 for _ in 0..count {
498 let len = usize::from(byte(r)?);
499 let raw = r.take(len).map_err(|_| "truncated")?;
500 let text = core::str::from_utf8(raw).map_err(|_| "Game Genie code is not text")?;
501 let code = GenieCode::new(text).map_err(|_| "Game Genie code does not decode")?;
502 by_addr.insert(code.addr(), code.code().to_string());
503 }
504 let genie_codes: Vec<String> = by_addr.into_values().collect();
505 Ok(Self {
506 console_model,
507 ppu_revision,
508 cpu_2a03_revision,
509 oam_decay,
510 power_on_ram,
511 power_up_palette,
512 extra_scanlines,
513 cpu_overclock,
514 sprite_limit_disabled,
515 coherent_midline_copy,
516 mmc3_revision,
517 four_score,
518 zapper_temporal_light,
519 vs_dip,
520 vs_ppu_type,
521 mirroring_override,
522 genie_codes,
523 })
524 }
525
526 /// The canonical encoding as a byte vector.
527 #[must_use]
528 pub fn to_bytes(&self) -> Vec<u8> {
529 let mut w = BinWriter::with_capacity(32);
530 self.write_to(&mut w);
531 w.into_vec()
532 }
533
534 /// Every option that differs between `self` and `other`, by name, in
535 /// field order. Empty when they agree. For an error message a person can
536 /// act on: "OAM decay, console model" rather than "the options differ".
537 #[must_use]
538 pub fn differences(&self, other: &Self) -> Vec<&'static str> {
539 let mut out = Vec::new();
540 let mut check = |differs: bool, name: &'static str| {
541 if differs {
542 out.push(name);
543 }
544 };
545 check(self.console_model != other.console_model, "console model");
546 check(self.ppu_revision != other.ppu_revision, "PPU revision");
547 check(
548 self.cpu_2a03_revision != other.cpu_2a03_revision,
549 "2A03 revision",
550 );
551 check(self.oam_decay != other.oam_decay, "OAM decay");
552 check(self.power_on_ram != other.power_on_ram, "power-on RAM");
553 check(
554 self.power_up_palette != other.power_up_palette,
555 "power-up palette",
556 );
557 check(
558 self.extra_scanlines != other.extra_scanlines,
559 "overclock scanlines",
560 );
561 check(self.cpu_overclock != other.cpu_overclock, "CPU overclock");
562 check(
563 self.sprite_limit_disabled != other.sprite_limit_disabled,
564 "sprite limit",
565 );
566 check(
567 self.coherent_midline_copy != other.coherent_midline_copy,
568 "coherent mid-line copy",
569 );
570 check(self.mmc3_revision != other.mmc3_revision, "MMC3 revision");
571 check(self.four_score != other.four_score, "Four Score");
572 check(
573 self.zapper_temporal_light != other.zapper_temporal_light,
574 "Zapper light model",
575 );
576 check(self.vs_dip != other.vs_dip, "Vs. DIP switches");
577 check(self.vs_ppu_type != other.vs_ppu_type, "Vs. PPU type");
578 check(
579 self.mirroring_override != other.mirroring_override,
580 "mirroring override",
581 );
582 check(self.genie_codes != other.genie_codes, "Game Genie codes");
583 out
584 }
585}
586
587/// What the cartridge header told the core to build, after any load-time
588/// correction: the facts that change emulation and that a host cannot apply.
589///
590/// Region is not here: a movie has always recorded it in its fixed header,
591/// and netplay folds it into [`config_digest`] beside this.
592///
593/// `#[non_exhaustive]` since v3.0.0 (T-API-EXTENSIBLE): build one with
594/// [`BoardDescription::capture`]. v2.9.9 added three fields to it, each a
595/// break; a later field no longer is.
596#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
597#[non_exhaustive]
598pub struct BoardDescription {
599 /// iNES / NES 2.0 mapper number.
600 pub mapper_id: u16,
601 /// NES 2.0 submapper (0 for iNES 1.0).
602 pub submapper: u8,
603 /// Header mirroring.
604 pub mirroring: Mirroring,
605 /// Console type (NES / Vs. System / PlayChoice-10 / extended).
606 pub console_type: ConsoleType,
607 /// Whether the header marks a Vs. `DualSystem` board.
608 pub vs_dual_system: bool,
609 /// PRG-RAM bytes (volatile + battery).
610 pub prg_ram_size: u32,
611 /// CHR-RAM bytes.
612 pub chr_ram_size: u32,
613 /// Battery-backed save RAM present.
614 pub has_battery: bool,
615 /// 512-byte trainer present.
616 pub has_trainer: bool,
617 /// PRG-ROM bytes. The ROM identity hashes the body after the header, so
618 /// the same body split differently between PRG and CHR (2 x 16 KiB +
619 /// 4 x 8 KiB against 1 x 16 KiB + 6 x 8 KiB) shared an identity and a
620 /// description until v2.9.9 (core re-audit NC-10).
621 pub prg_rom_len: u32,
622 /// CHR-ROM bytes (0 for CHR-RAM boards); see `prg_rom_len`.
623 pub chr_rom_len: u32,
624 /// The raw header nametable bits mappers 30 and 218 wire from
625 /// ([`rustynes_mappers::Cartridge::nametable_wiring_bits`]); v2.9.9.
626 pub nametable_wiring_bits: u8,
627}
628
629impl BoardDescription {
630 /// The board `nes` was built from.
631 #[must_use]
632 #[allow(clippy::cast_possible_truncation)] // ROM sizes are far below 4 GiB
633 pub fn capture(nes: &Nes) -> Self {
634 let c = nes.cartridge();
635 Self {
636 mapper_id: c.mapper_id,
637 submapper: c.submapper,
638 mirroring: c.mirroring,
639 console_type: c.console_type,
640 vs_dual_system: c.vs_dual_system,
641 prg_ram_size: c.prg_ram_size,
642 chr_ram_size: c.chr_ram_size,
643 has_battery: c.has_battery,
644 has_trainer: c.has_trainer,
645 prg_rom_len: c.prg_rom.len() as u32,
646 chr_rom_len: c.chr_rom.len() as u32,
647 nametable_wiring_bits: c.nametable_wiring_bits,
648 }
649 }
650
651 /// The first field that differs between `self` (recorded) and `other`
652 /// (the host's), or `None` when the boards agree.
653 #[must_use]
654 pub fn first_difference(&self, other: &Self) -> Option<&'static str> {
655 [
656 (self.mapper_id != other.mapper_id, "mapper"),
657 (self.submapper != other.submapper, "submapper"),
658 (self.mirroring != other.mirroring, "mirroring"),
659 (self.console_type != other.console_type, "console type"),
660 (
661 self.vs_dual_system != other.vs_dual_system,
662 "Vs. DualSystem",
663 ),
664 (self.prg_ram_size != other.prg_ram_size, "PRG-RAM size"),
665 (self.chr_ram_size != other.chr_ram_size, "CHR-RAM size"),
666 (self.has_battery != other.has_battery, "battery"),
667 (self.has_trainer != other.has_trainer, "trainer"),
668 (self.prg_rom_len != other.prg_rom_len, "PRG-ROM size"),
669 (self.chr_rom_len != other.chr_rom_len, "CHR-ROM size"),
670 (
671 self.nametable_wiring_bits != other.nametable_wiring_bits,
672 "header nametable wiring",
673 ),
674 ]
675 .into_iter()
676 .find_map(|(differs, name)| differs.then_some(name))
677 }
678
679 /// Append the canonical encoding to `w` (`u16` mapper, submapper,
680 /// mirroring, console type, `DualSystem`, `u32` PRG-RAM, `u32` CHR-RAM,
681 /// battery, trainer, and from v2.9.9 `u32` PRG-ROM, `u32` CHR-ROM and the
682 /// wiring byte).
683 pub fn write_to(&self, w: &mut BinWriter) {
684 w.u16(self.mapper_id);
685 w.u8(self.submapper);
686 w.u8(mirroring_to_byte(self.mirroring));
687 w.u8(match self.console_type {
688 ConsoleType::Nes => 0,
689 ConsoleType::VsSystem => 1,
690 ConsoleType::Playchoice10 => 2,
691 ConsoleType::Extended => 3,
692 });
693 w.u8(u8::from(self.vs_dual_system));
694 w.u32(self.prg_ram_size);
695 w.u32(self.chr_ram_size);
696 w.u8(u8::from(self.has_battery));
697 w.u8(u8::from(self.has_trainer));
698 w.u32(self.prg_rom_len);
699 w.u32(self.chr_rom_len);
700 w.u8(self.nametable_wiring_bits);
701 }
702
703 /// Decode what [`Self::write_to`] wrote. Strict, as
704 /// [`HardwareOptions::read_from`].
705 ///
706 /// # Errors
707 ///
708 /// A fixed description of the first malformed field, or `"truncated"`.
709 pub fn read_from(r: &mut BinReader<'_>) -> Result<Self, OptionsDecodeError> {
710 let mapper_id = r.u16().map_err(|_| "truncated")?;
711 let submapper = byte(r)?;
712 let mirroring = mirroring_from_byte(byte(r)?).ok_or("unknown board mirroring byte")?;
713 let console_type = match byte(r)? {
714 0 => ConsoleType::Nes,
715 1 => ConsoleType::VsSystem,
716 2 => ConsoleType::Playchoice10,
717 3 => ConsoleType::Extended,
718 _ => return Err("unknown console-type byte"),
719 };
720 let vs_dual_system = flag(r, "DualSystem flag is not 0 or 1")?;
721 let prg_ram_size = r.u32().map_err(|_| "truncated")?;
722 let chr_ram_size = r.u32().map_err(|_| "truncated")?;
723 let has_battery = flag(r, "battery flag is not 0 or 1")?;
724 let has_trainer = flag(r, "trainer flag is not 0 or 1")?;
725 let prg_rom_len = r.u32().map_err(|_| "truncated")?;
726 let chr_rom_len = r.u32().map_err(|_| "truncated")?;
727 let nametable_wiring_bits = byte(r)?;
728 if nametable_wiring_bits & !0x09 != 0 {
729 return Err("header nametable wiring byte has bits other than 0 and 3");
730 }
731 Ok(Self {
732 mapper_id,
733 submapper,
734 mirroring,
735 console_type,
736 vs_dual_system,
737 prg_ram_size,
738 chr_ram_size,
739 has_battery,
740 has_trainer,
741 prg_rom_len,
742 chr_rom_len,
743 nametable_wiring_bits,
744 })
745 }
746}
747
748/// SHA-256 over everything two machines must share to run one timeline from
749/// the same ROM: the region, the [`BoardDescription`] and the
750/// [`HardwareOptions`], each in its canonical encoding.
751///
752/// Netplay sends it in the handshake beside the ROM hash, so peers on the
753/// same game with different settings (or differently corrected headers)
754/// refuse with a reason instead of connecting and desyncing at the first
755/// frame the difference reaches. SHA-256 rather than a 64-bit hash because the
756/// value is compared, never searched, and 32 bytes on a once-per-session
757/// message cost nothing.
758#[must_use]
759pub fn config_digest(nes: &Nes) -> [u8; 32] {
760 let mut w = BinWriter::with_capacity(64);
761 w.u8(match nes.region() {
762 Region::Ntsc => 0,
763 Region::Pal => 1,
764 Region::Dendy => 2,
765 });
766 BoardDescription::capture(nes).write_to(&mut w);
767 HardwareOptions::capture(nes).write_to(&mut w);
768 let mut out = [0u8; 32];
769 out.copy_from_slice(&Sha256::digest(w.into_vec()));
770 out
771}
772
773fn byte(r: &mut BinReader<'_>) -> Result<u8, OptionsDecodeError> {
774 r.u8().map_err(|_| "truncated")
775}
776
777fn flag(r: &mut BinReader<'_>, what: OptionsDecodeError) -> Result<bool, OptionsDecodeError> {
778 match byte(r)? {
779 0 => Ok(false),
780 1 => Ok(true),
781 _ => Err(what),
782 }
783}
784
785const fn mirroring_to_byte(m: Mirroring) -> u8 {
786 match m {
787 Mirroring::Horizontal => 0,
788 Mirroring::Vertical => 1,
789 Mirroring::SingleScreenA => 2,
790 Mirroring::SingleScreenB => 3,
791 Mirroring::FourScreen => 4,
792 Mirroring::MapperControlled => 5,
793 }
794}
795
796const fn mirroring_from_byte(b: u8) -> Option<Mirroring> {
797 Some(match b {
798 0 => Mirroring::Horizontal,
799 1 => Mirroring::Vertical,
800 2 => Mirroring::SingleScreenA,
801 3 => Mirroring::SingleScreenB,
802 4 => Mirroring::FourScreen,
803 5 => Mirroring::MapperControlled,
804 _ => return None,
805 })
806}
807
808const fn vs_ppu_to_byte(t: VsPpuType) -> u8 {
809 match t {
810 VsPpuType::None => 0,
811 VsPpuType::Rp2C03 => 1,
812 VsPpuType::Rp2C04_0001 => 2,
813 VsPpuType::Rp2C04_0002 => 3,
814 VsPpuType::Rp2C04_0003 => 4,
815 VsPpuType::Rp2C04_0004 => 5,
816 VsPpuType::Rc2C05_01 => 6,
817 VsPpuType::Rc2C05_02 => 7,
818 VsPpuType::Rc2C05_03 => 8,
819 VsPpuType::Rc2C05_04 => 9,
820 }
821}
822
823const fn vs_ppu_from_byte(b: u8) -> Option<VsPpuType> {
824 Some(match b {
825 0 => VsPpuType::None,
826 1 => VsPpuType::Rp2C03,
827 2 => VsPpuType::Rp2C04_0001,
828 3 => VsPpuType::Rp2C04_0002,
829 4 => VsPpuType::Rp2C04_0003,
830 5 => VsPpuType::Rp2C04_0004,
831 6 => VsPpuType::Rc2C05_01,
832 7 => VsPpuType::Rc2C05_02,
833 8 => VsPpuType::Rc2C05_03,
834 9 => VsPpuType::Rc2C05_04,
835 _ => return None,
836 })
837}
838
839#[cfg(test)]
840mod tests {
841 use super::*;
842
843 /// A minimal NROM image (an infinite `JMP`), as `movie.rs` uses.
844 fn synth_nrom() -> Vec<u8> {
845 let mut bytes = alloc::vec![b'N', b'E', b'S', 0x1A, 1, 1, 0, 0];
846 bytes.extend_from_slice(&[0u8; 8]);
847 let mut prg = alloc::vec![0u8; 16 * 1024];
848 prg[..3].copy_from_slice(&[0x4C, 0x00, 0xC0]);
849 let len = prg.len();
850 prg[len - 6..].copy_from_slice(&[0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0]);
851 bytes.extend_from_slice(&prg);
852 bytes.extend_from_slice(&[0u8; 8 * 1024]);
853 bytes
854 }
855
856 fn non_default() -> HardwareOptions {
857 HardwareOptions {
858 console_model: ConsoleModel::Famicom,
859 ppu_revision: PpuRevision::Rp2c02G,
860 cpu_2a03_revision: Cpu2A03Revision::Rp2A03H,
861 oam_decay: true,
862 power_on_ram: PowerOnRam::Seeded(0x0123_4567_89AB_CDEF),
863 power_up_palette: PaletteInit::Blargg,
864 extra_scanlines: 40,
865 cpu_overclock: 3,
866 sprite_limit_disabled: true,
867 coherent_midline_copy: true,
868 mmc3_revision: Some(rustynes_mappers::Mmc3Revision::Nec),
869 four_score: true,
870 zapper_temporal_light: false,
871 vs_dip: 0xA5,
872 vs_ppu_type: Some(VsPpuType::Rc2C05_03),
873 mirroring_override: Some(Mirroring::SingleScreenB),
874 // Address order, the canonical form `read_from` produces.
875 genie_codes: alloc::vec!["AAEAULPA".to_string(), "SXIOPO".to_string()],
876 }
877 }
878
879 /// NC-13 (v2.9.9 re-audit): a list in file order, or with a duplicate,
880 /// decodes to the console's own form, so `capture` of the machine it
881 /// configures compares equal and `apply_live` stops re-adding the codes.
882 #[test]
883 fn genie_codes_decode_to_the_canonical_order_without_duplicates() {
884 let canonical = non_default();
885 for list in [
886 alloc::vec!["SXIOPO", "AAEAULPA"],
887 alloc::vec!["AAEAULPA", "SXIOPO", "SXIOPO"],
888 alloc::vec!["sxiopo", "AAEAULPA"],
889 ] {
890 let opts = HardwareOptions {
891 genie_codes: list.iter().map(|c| (*c).to_string()).collect(),
892 ..non_default()
893 };
894 let decoded = HardwareOptions::read_from(&mut BinReader::new(&opts.to_bytes()));
895 assert_eq!(decoded, Ok(canonical.clone()), "list {list:?}");
896 }
897 }
898
899 /// NC-11 (v2.9.9 re-audit): an overclock above the core's maximum is
900 /// refused rather than replayed, and the maximum itself decodes.
901 #[test]
902 fn an_overclock_above_the_maximum_is_refused() {
903 for (lines, ok) in [
904 (crate::nes::MAX_EXTRA_SCANLINES, true),
905 (crate::nes::MAX_EXTRA_SCANLINES + 1, false),
906 (u16::MAX, false),
907 ] {
908 let opts = HardwareOptions {
909 extra_scanlines: lines,
910 ..HardwareOptions::default()
911 };
912 let decoded = HardwareOptions::read_from(&mut BinReader::new(&opts.to_bytes()));
913 assert_eq!(decoded.is_ok(), ok, "extra_scanlines {lines}");
914 }
915 }
916
917 #[test]
918 fn options_round_trip_through_their_encoding() {
919 for opts in [HardwareOptions::default(), non_default()] {
920 let bytes = opts.to_bytes();
921 let mut r = BinReader::new(&bytes);
922 assert_eq!(HardwareOptions::read_from(&mut r), Ok(opts));
923 assert_eq!(r.remaining(), 0, "the decoder consumes exactly the record");
924 }
925 let filled = HardwareOptions {
926 power_on_ram: PowerOnRam::Filled(0xFF),
927 ..HardwareOptions::default()
928 };
929 let bytes = filled.to_bytes();
930 assert_eq!(
931 HardwareOptions::read_from(&mut BinReader::new(&bytes)),
932 Ok(filled)
933 );
934 }
935
936 #[test]
937 fn every_truncation_is_an_error_not_a_default() {
938 let bytes = non_default().to_bytes();
939 for len in 0..bytes.len() {
940 assert!(
941 HardwareOptions::read_from(&mut BinReader::new(&bytes[..len])).is_err(),
942 "a record cut at {len} bytes must not decode"
943 );
944 }
945 }
946
947 #[test]
948 fn an_unknown_byte_is_refused() {
949 let mut bytes = HardwareOptions::default().to_bytes();
950 bytes[0] = 7; // console model
951 assert_eq!(
952 HardwareOptions::read_from(&mut BinReader::new(&bytes)),
953 Err("unknown console-model byte")
954 );
955 let mut bytes = HardwareOptions::default().to_bytes();
956 bytes[3] = 2; // OAM decay flag
957 assert!(HardwareOptions::read_from(&mut BinReader::new(&bytes)).is_err());
958 }
959
960 #[test]
961 fn differences_name_each_differing_option() {
962 let a = HardwareOptions::default();
963 assert_eq!(a.differences(&a), [] as [&str; 0]);
964 let b = HardwareOptions {
965 oam_decay: true,
966 console_model: ConsoleModel::Famicom,
967 ..HardwareOptions::default()
968 };
969 assert_eq!(a.differences(&b), ["console model", "OAM decay"]);
970 }
971
972 #[test]
973 fn a_fresh_machine_captures_the_stock_options_and_its_own_vs_type() {
974 let rom = synth_nrom();
975 let nes = Nes::from_rom(&rom).unwrap();
976 let captured = HardwareOptions::capture(&nes);
977 assert_eq!(
978 captured,
979 HardwareOptions {
980 vs_ppu_type: Some(VsPpuType::None),
981 ..HardwareOptions::default()
982 }
983 );
984 }
985
986 #[test]
987 fn board_round_trips_and_names_the_differing_field() {
988 let rom = synth_nrom();
989 let nes = Nes::from_rom(&rom).unwrap();
990 let board = BoardDescription::capture(&nes);
991 let mut w = BinWriter::new();
992 board.write_to(&mut w);
993 let bytes = w.into_vec();
994 assert_eq!(
995 BoardDescription::read_from(&mut BinReader::new(&bytes)),
996 Ok(board)
997 );
998 let other = BoardDescription {
999 submapper: board.submapper + 1,
1000 ..board
1001 };
1002 assert_eq!(board.first_difference(&other), Some("submapper"));
1003 assert_eq!(board.first_difference(&board), None);
1004 }
1005
1006 #[test]
1007 fn the_config_digest_follows_every_option() {
1008 let rom = synth_nrom();
1009 let mut nes = Nes::from_rom(&rom).unwrap();
1010 let base = config_digest(&nes);
1011 assert_eq!(base, config_digest(&Nes::from_rom(&rom).unwrap()));
1012 nes.set_oam_decay(true);
1013 assert_ne!(config_digest(&nes), base);
1014 }
1015
1016 /// NC-10 (v2.9.9 re-audit): the identity hashes the body after the
1017 /// header, so headers that build different machines from one body must
1018 /// differ in the board description, which movies and netplay check.
1019 #[test]
1020 fn headers_that_build_different_machines_differ_in_the_description() {
1021 // One 64 KiB body: CNROM read as 2 x 16 KiB PRG + 4 x 8 KiB CHR, and
1022 // as 1 x 16 KiB PRG + 6 x 8 KiB CHR.
1023 let body: Vec<u8> = (0u32..64 * 1024).map(|i| (i % 251) as u8).collect();
1024 let image = |prg16: u8, chr8: u8, flags6: u8, mapper: u8| {
1025 let mut v = alloc::vec![
1026 b'N',
1027 b'E',
1028 b'S',
1029 0x1A,
1030 prg16,
1031 chr8,
1032 flags6 | (mapper << 4),
1033 mapper & 0xF0
1034 ];
1035 v.extend_from_slice(&[0u8; 8]);
1036 v.extend_from_slice(&body);
1037 v
1038 };
1039 let a = Nes::from_rom(&image(2, 4, 0, 3)).unwrap();
1040 let b = Nes::from_rom(&image(1, 6, 0, 3)).unwrap();
1041 assert_eq!(a.rom_sha256(), b.rom_sha256(), "one identity");
1042 assert_eq!(
1043 BoardDescription::capture(&a).first_difference(&BoardDescription::capture(&b)),
1044 Some("PRG-ROM size")
1045 );
1046 assert_ne!(config_digest(&a), config_digest(&b));
1047
1048 // Mapper 218: four-screen with bit 0 set or clear wires CIRAM A10 to
1049 // a different PPU line; both read as `FourScreen`.
1050 let c = Nes::from_rom(&image(2, 0, 0x08, 218)).unwrap();
1051 let d = Nes::from_rom(&image(2, 0, 0x09, 218)).unwrap();
1052 assert_eq!(
1053 BoardDescription::capture(&c).first_difference(&BoardDescription::capture(&d)),
1054 Some("header nametable wiring")
1055 );
1056 }
1057
1058 #[test]
1059 fn a_wiring_byte_with_other_bits_is_refused() {
1060 let board = BoardDescription::capture(&Nes::from_rom(&synth_nrom()).unwrap());
1061 let mut w = BinWriter::with_capacity(32);
1062 board.write_to(&mut w);
1063 let mut bytes = w.into_vec();
1064 let last = bytes.len() - 1;
1065 bytes[last] = 0x02;
1066 assert!(BoardDescription::read_from(&mut BinReader::new(&bytes)).is_err());
1067 }
1068}