Skip to main content

rustynes_core/
movie.rs

1//! TAS movie (`.rnm`) recording and playback.
2//!
3//! A movie is a *reproducible start point* plus the *per-frame input stream*
4//! applied on top of it. Because the core honours the hard determinism
5//! contract (same seed + ROM + input sequence ⇒ bit-identical framebuffer
6//! and audio — see `CLAUDE.md`), replaying the recorded inputs from the
7//! recorded start point re-derives every pixel and sample bit-for-bit. No
8//! state deltas or frame hashes are stored.
9//!
10//! See `docs/adr/0008-tas-movie-format.md` for the format spec, the
11//! structural references (Mesen2 `.mmo`, FCEUX `.fm2`, `TetaNES` `.replay`),
12//! and the forward-compatibility story (layered on ADR 0003).
13//!
14//! # On-wire layout
15//!
16//! ```text
17//! HEADER:
18//!     magic           : "RNESMOV1"   (8 bytes)
19//!     format version  : u16 LE        (currently 7 = MOVIE_FORMAT_VERSION)
20//!     emulation epoch : u32 LE        (format 5+; `EMULATION_EPOCH`, ADR 0045)
21//!     region          : u8            (0 = NTSC, 1 = PAL, 2 = Dendy)
22//!     flags           : u8            (bit0 = embedded save-state start point,
23//!                                      bit1 = board description recorded)
24//!     rom sha-256     : [u8; 32]      (`Nes::rom_sha256`: the image after its
25//!                                      16-byte header — the ROM identity)
26//!     frame count     : u32 LE
27//!     bytes per frame : u8            (currently 5: P1, P2, P3, P4,
28//!                                      expansion-reserved; 3 before format 3)
29//! OPTIONS (format 3+): u32 LE length + that many bytes:
30//!     the `HardwareOptions` encoding, then (flags bit1) the
31//!     `BoardDescription` encoding — see `crate::hardware_options`
32//! START POINT (only when flags bit0 set):
33//!     length-prefixed `.rns` save-state blob (u32 LE length + bytes)
34//! INPUT STREAM:
35//!     frame_count * bytes_per_frame raw bytes; each frame =
36//!     [p1, p2, p3, p4, expansion]
37//! INPUT EVENTS (format 7+): u32 LE length + that many bytes:
38//!     u32 LE event count, then per event: u32 LE frame index, u8 kind,
39//!     kind-specific payload -- the non-controller inputs (expansion
40//!     devices, microphone, Vs. coin / service, FDS disk, barcode) as the
41//!     changes between frames; see `crate::movie_extra`
42//! RE-RECORD COUNT: u32 LE (optional tail)
43//! ATTESTATION: "RNAT" ... (optional tail)
44//! ```
45//!
46//! This module is `no_std`-clean: it uses only `core` + `alloc` and the
47//! `BinWriter` / `BinReader` primitives from [`crate::save_state`].
48
49use alloc::vec::Vec;
50
51use alloc::string::String;
52
53use crate::Region;
54use crate::controller::Buttons;
55use crate::hardware_options::{BoardDescription, HardwareOptions, OptionsDecodeError};
56use crate::movie_extra::{self, ExtraInput};
57use crate::nes::Nes;
58use crate::save_state::{BinReader, BinWriter, SnapshotError};
59use thiserror::Error;
60
61/// Magic header bytes — first 8 bytes of every `.rnm` movie file.
62pub const MOVIE_MAGIC: &[u8; 8] = b"RNESMOV1";
63
64/// Current movie container-format version.
65///
66/// - v1 (v1.1.0 ..): the format documented above.
67/// - **v2 (v2.0.0 "Timebase" rc.1, ADR 0028)**: on-wire layout unchanged —
68///   this is purely an epoch marker. A `.rnm` with `format_version < 2` was
69///   necessarily recorded on a pre-promote (pre-beta.4) build; per the
70///   determinism contract, its INPUT STREAM still replays fine (nothing
71///   about frame timing or button semantics changed), but the
72///   frame-for-frame bit-identical reproduction guarantee the movie format
73///   depends on is only proven within a single engine timebase — the
74///   one-clock promote changed how master-clock/PPU/CPU phase advances
75///   internally, so a v1-recorded movie's *exact* framebuffer/audio replay
76///   on the v2.0.0-line engine is unverified, not guaranteed. Do NOT
77///   attempt timeline transcoding (re-deriving a v2-native recording from
78///   a v1 one) — that is out of scope; the honest move is surfacing the
79///   epoch, not silently promising equivalence. See
80///   [`recorded_before_v2_timebase`] for the check callers (TAS tooling,
81///   frontend movie-load UI) should use before relying on verify-replay.
82/// - **v3 (v2.9.8, ADR 0028's epoch rule)**: an OPTIONS block follows the
83///   fixed header, carrying every emulation-affecting host option the movie
84///   was recorded with ([`HardwareOptions`]) and, for a recorded movie, the
85///   cartridge board the header described ([`BoardDescription`]). Playback
86///   applies the options before frame 0 and refuses a board or region that
87///   differs, so a replay runs the recorded machine whatever the player's own
88///   settings are. A v1 or v2 movie does not say which machine it ran on, so
89///   it is refused ([`MIN_MOVIE_FORMAT_VERSION`]) rather than replayed on a
90///   guess; the maintainer accepted breaking them (2026-10-01).
91/// - **v4 (v2.9.9, core re-audit NC-10)**: the [`BoardDescription`] gains the
92///   PRG-ROM and CHR-ROM sizes and the raw header nametable bits. v3 could
93///   not tell two headers that split one body differently, or that differ
94///   only in the bits mappers 30 and 218 wire from, so a movie replayed
95///   silently on a different machine. v3 is refused, as v1 and v2 are, under
96///   the same "enduring over compatible" rule.
97/// - **v5 (v3.0.0, ADR 0045)**: the fixed header carries the
98///   [`EMULATION_EPOCH`](crate::EMULATION_EPOCH) the movie was recorded under,
99///   straight after the format version so a tool can read it without parsing
100///   the rest. v2.9.9 and v3.0.0 emulate MMC3 games with the background at
101///   `$1000` differently (T-MMC3-BG-A12), and a format-4 movie does not say
102///   which behaviour it assumes, so v4 is refused. A v5 movie from another
103///   epoch is refused with [`MovieError::EpochMismatch`].
104/// - **v6 (v3.1.0)**: the [`crate::HardwareOptions`] record gains the
105///   CPU-multiplier overclock and the sprite-limit option (`T-CPU-OVERCLOCK`,
106///   `T-SPRITE-LIMIT`). A v5 options record is one field shorter and would
107///   decode as garbage, so v5 is refused. No replayable movie is lost: every
108///   v5 movie was recorded under epoch 1 or 2, which v3.1.0 (epoch 3) refuses
109///   anyway.
110/// - **v7 (v3.5.0, `T-MOVIE-INPUT-STREAM`)**: an INPUT EVENTS block follows
111///   the input stream, carrying every non-controller input [`Nes`] accepts
112///   ([`crate::ExtraInput`]: the expansion devices on both ports, the Famicom
113///   microphone, the Vs. coin acceptors and service button, the inserted FDS
114///   disk side and Datach barcode scans). A v6 movie recorded none of them,
115///   so a Zapper, Vs. or FDS run replayed with the trigger never pulled, no
116///   coin and no disk swap; it is refused rather than replayed on a guess.
117///   The emulation is unchanged ([`EMULATION_EPOCH`](crate::EMULATION_EPOCH)
118///   stays as it was), so a v6 movie of a controller-only game would still
119///   replay -- but its file cannot say it was one, so it is refused as too
120///   old, with the reason, like every earlier format.
121/// - **v8 (v3.6.2, `T-RADRACER-COHERENT-COPY`)**: the
122///   [`crate::HardwareOptions`] record gains the per-game coherent mid-line
123///   copy correction, one byte after the sprite-limit option. A v7 options
124///   record is one byte shorter and would decode as garbage, so v7 is
125///   refused. No replayable movie is lost: every v7 movie was recorded under
126///   epoch 9 or earlier, which v3.6.2 (epoch 10) refuses anyway.
127pub const MOVIE_FORMAT_VERSION: u16 = 8;
128
129/// The oldest container version this build replays: v8.
130///
131/// v8 is the first that records the coherent mid-line copy correction (v7
132/// first recorded the non-controller inputs, v6 first
133/// recorded the CPU overclock and the sprite-limit option, v5 the emulation
134/// epoch, v4 the board, v3 the options). Older movies fail with
135/// [`MovieError::FormatTooOld`].
136pub const MIN_MOVIE_FORMAT_VERSION: u16 = 8;
137
138/// Peek a `.rnm` blob's header to learn its recording epoch.
139///
140/// Checks whether it was recorded on a pre-v2.0.0-timebase build
141/// (`format_version < 2`), WITHOUT fully parsing the movie. Intended for
142/// tooling/UI that wants to warn before relying on the determinism
143/// (verify-replay) guarantee across the v2.0.0 engine-timebase boundary —
144/// see [`MOVIE_FORMAT_VERSION`]'s v2 doc.
145///
146/// Since v2.9.8 [`Movie::deserialize`] refuses every movie older than
147/// [`MIN_MOVIE_FORMAT_VERSION`], so a movie that parses is never pre-v2; the
148/// function survives for tooling that inspects raw files, and still answers
149/// for any header it is shown.
150///
151/// # Errors
152///
153/// Returns [`MovieError::HeaderTruncated`] or [`MovieError::BadMagic`] if
154/// the blob doesn't even have a valid movie header.
155pub fn recorded_before_v2_timebase(bytes: &[u8]) -> Result<bool, MovieError> {
156    const MIN_LEN: usize = 8 + 2;
157    if bytes.len() < MIN_LEN {
158        return Err(MovieError::HeaderTruncated {
159            expected: MIN_LEN,
160            got: bytes.len(),
161        });
162    }
163    let mut magic = [0u8; 8];
164    magic.copy_from_slice(&bytes[..8]);
165    if &magic != MOVIE_MAGIC {
166        return Err(MovieError::BadMagic { got: magic });
167    }
168    let format_version = u16::from_le_bytes([bytes[8], bytes[9]]);
169    Ok(format_version < 2)
170}
171
172/// Bytes stored per recorded frame: players 1-4, then a reserved
173/// expansion-port byte (always `0` today).
174///
175/// Format 3 (v2.9.8) widened the record from 3 bytes (P1, P2, expansion) to 5
176/// so Four Score players 3 and 4 are recorded; the order puts the players
177/// first, so a narrower record (width 2 = two pads, width 4 = four pads) reads
178/// as "the later fields absent". Stored explicitly in the header so a future
179/// device byte can grow the record without a container-version bump.
180pub const BYTES_PER_FRAME: u8 = 5;
181
182/// Header flag: an embedded `.rns` save-state start point follows the header.
183const FLAG_HAS_SAVE_STATE: u8 = 0x01;
184
185/// Header flag (format 3+): the OPTIONS block carries a [`BoardDescription`]
186/// after the [`HardwareOptions`]. Clear for a foreign import, whose source
187/// format records no header.
188const FLAG_HAS_BOARD: u8 = 0x02;
189
190/// The header flags this build understands. Any other bit set is refused, so a
191/// later format cannot be half-read.
192const KNOWN_FLAGS: u8 = FLAG_HAS_SAVE_STATE | FLAG_HAS_BOARD;
193
194/// Per-frame input: four controller ports, a reserved expansion byte, and
195/// (v3.5.0) every non-controller input in [`Self::extra`].
196///
197/// Each port is a `Buttons` value. Bit layout matches FCEUX `.fm2`
198/// (`bit0=A .. bit7=Right`), which is exactly [`Buttons::bits`].
199///
200/// # The non-controller inputs (v3.5.0)
201///
202/// [`Self::extra`] holds the expansion devices, the Famicom microphone, the
203/// Vs. coin and service inputs, the FDS disk side and Datach barcode scans
204/// ([`ExtraInput`]). [`Self::held_on`] always fills it; a frame built with
205/// [`Self::new`], [`Self::four_players`] or [`Default`] leaves it `None`,
206/// which [`Self::apply_to`] reads as "drive the controllers only", exactly
207/// what a frame meant before v3.5.0. So a foreign import, a TAS editor's
208/// blank frame or an input macro does not eject a disk or unplug a Zapper.
209///
210/// # Players 3 and 4 (v2.9.8)
211///
212/// `p3` / `p4` are the Four Score's players, polled through `$4016` / `$4017`
213/// only while the adapter is plugged in (which the movie's
214/// [`HardwareOptions::four_score`] records). Until v2.9.8 the struct held two
215/// ports, so a four-player recording captured half of what drove it and the
216/// `.fm2` importer dropped pads 3 and 4.
217///
218/// # Why `#[non_exhaustive]`
219///
220/// Adding `p3` / `p4` broke every caller that built the struct by literal,
221/// which is why the change waited for a breaking release. The next field is
222/// foreseeable -- an expansion-port device byte, a soft-reset command -- and
223/// `.rnm` already stores its per-frame width so the FORMAT side of such a
224/// field is additive; `#[non_exhaustive]` makes the API side additive too.
225/// Outside this crate a frame is built with [`Self::new`],
226/// [`Self::four_players`] or [`Default`] and then edited through its public
227/// fields, all of which keep compiling when a field is added.
228#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
229#[non_exhaustive]
230pub struct FrameInput {
231    /// Player 1 (`$4016`) button state.
232    pub p1: Buttons,
233    /// Player 2 (`$4017`) button state.
234    pub p2: Buttons,
235    /// Player 3 (Four Score, multiplexed on `$4016`) button state.
236    pub p3: Buttons,
237    /// Player 4 (Four Score, multiplexed on `$4017`) button state.
238    pub p4: Buttons,
239    /// Reserved expansion-port byte (currently always `0`). The expansion
240    /// devices themselves are in [`Self::extra`] since v3.5.0.
241    pub expansion: u8,
242    /// v3.5.0 (`T-MOVIE-INPUT-STREAM`) — the non-controller inputs held for
243    /// this frame, or `None` when the frame does not drive them (see the
244    /// type docs). Recorded in `.rnm` format 7's INPUT EVENTS block.
245    pub extra: Option<ExtraInput>,
246}
247
248impl FrameInput {
249    /// Build a two-controller frame (players 3/4 released, no expansion byte).
250    #[must_use]
251    pub const fn new(p1: Buttons, p2: Buttons) -> Self {
252        Self::four_players(p1, p2, Buttons::empty(), Buttons::empty())
253    }
254
255    /// v2.9.8 — build a four-controller frame (no expansion byte).
256    #[must_use]
257    pub const fn four_players(p1: Buttons, p2: Buttons, p3: Buttons, p4: Buttons) -> Self {
258        Self {
259            p1,
260            p2,
261            p3,
262            p4,
263            expansion: 0,
264            extra: None,
265        }
266    }
267
268    /// v2.9.8 — the buttons on controller `port` (0-3 = players 1-4).
269    ///
270    /// # Panics
271    ///
272    /// Panics if `port` is not in `0..=3`, matching [`Nes::set_buttons`].
273    #[must_use]
274    pub const fn port(&self, port: usize) -> Buttons {
275        match port {
276            0 => self.p1,
277            1 => self.p2,
278            2 => self.p3,
279            3 => self.p4,
280            _ => panic!("controller port out of range"),
281        }
282    }
283
284    /// v2.9.8 — mutable access to controller `port` (0-3 = players 1-4).
285    ///
286    /// # Panics
287    ///
288    /// Panics if `port` is not in `0..=3`.
289    pub const fn port_mut(&mut self, port: usize) -> &mut Buttons {
290        match port {
291            0 => &mut self.p1,
292            1 => &mut self.p2,
293            2 => &mut self.p3,
294            3 => &mut self.p4,
295            _ => panic!("controller port out of range"),
296        }
297    }
298
299    /// v2.9.8 — drive all four controller ports of `nes` from this frame,
300    /// and (v3.5.0) its non-controller inputs when [`Self::extra`] holds
301    /// them ([`ExtraInput::apply`]).
302    ///
303    /// Ports 2 and 3 are only polled while the Four Score is plugged in, so
304    /// setting them on a two-pad machine changes nothing it reads.
305    ///
306    /// No longer a `const fn` (v3.5.0): attaching an expansion device and
307    /// inserting a disk side are not.
308    pub fn apply_to(&self, nes: &mut Nes) {
309        nes.set_buttons(0, self.p1);
310        nes.set_buttons(1, self.p2);
311        nes.set_buttons(2, self.p3);
312        nes.set_buttons(3, self.p4);
313        if let Some(extra) = &self.extra {
314            extra.apply(nes);
315        }
316    }
317
318    /// v2.9.8 — the input currently held on all four ports of `nes`, and
319    /// (v3.5.0) every non-controller input it holds ([`ExtraInput::capture`]),
320    /// so [`Self::extra`] is always `Some`.
321    ///
322    /// No longer a `const fn` (v3.5.0).
323    #[must_use]
324    pub fn held_on(nes: &Nes) -> Self {
325        let mut frame = Self::four_players(
326            nes.buttons(0),
327            nes.buttons(1),
328            nes.buttons(2),
329            nes.buttons(3),
330        );
331        frame.extra = Some(ExtraInput::capture(nes));
332        frame
333    }
334
335    /// v3.5.0 — encode a frame list as `.rnm` format 7 encodes its input:
336    /// a `u32` LE frame count, the 5-byte records, then the length-prefixed
337    /// INPUT EVENTS block. For a host that stores an input log outside a
338    /// movie (the desktop `TAStudio` project, `.rnmproj` version 2) and must
339    /// not lose what a movie keeps: players 3 and 4 and every
340    /// [`Self::extra`].
341    ///
342    /// # Panics
343    ///
344    /// Panics if `frames` holds more than `u32::MAX` frames.
345    #[must_use]
346    pub fn encode_log(frames: &[Self]) -> Vec<u8> {
347        let mut w = BinWriter::with_capacity(8 + frames.len() * usize::from(BYTES_PER_FRAME));
348        w.u32(u32::try_from(frames.len()).expect("frame count exceeds u32"));
349        write_frames(&mut w, frames);
350        w.into_vec()
351    }
352
353    /// v3.6.1 (`T-TAS-PROJECT-DECODE-BOUND`) — an upper bound on the memory
354    /// [`Self::decode_log`] needs for `bytes` at its peak, from the log's
355    /// declared counts alone, before anything is decoded or reserved: the
356    /// frame vector, the per-frame `Option<ExtraInput>` vector the INPUT
357    /// EVENTS block decodes into while the frames are still live, and the
358    /// event list itself. A host that stores logs outside a movie (the
359    /// desktop `TAStudio` project) charges this against its own budget before
360    /// it decodes, and before it saves, so it never writes a log it would
361    /// refuse to read back. A truncated log costs what its counts say;
362    /// [`Self::decode_log`] then refuses it.
363    #[must_use]
364    pub fn decode_log_cost(bytes: &[u8]) -> u64 {
365        let Some(c) = bytes.get(..4) else {
366            return 0;
367        };
368        let frames = u64::from(u32::from_le_bytes([c[0], c[1], c[2], c[3]]));
369        let per_frame =
370            (core::mem::size_of::<Self>() + core::mem::size_of::<Option<ExtraInput>>()) as u64;
371        let mut cost = frames.saturating_mul(per_frame);
372        // The INPUT EVENTS block follows the records, length-prefixed.
373        let records = usize::try_from(frames)
374            .ok()
375            .and_then(|f| f.checked_mul(usize::from(BYTES_PER_FRAME)))
376            .and_then(|n| n.checked_add(4));
377        if let Some(block_at) = records
378            && let Some(len) = bytes.get(block_at..block_at + 4)
379        {
380            let len = u32::from_le_bytes([len[0], len[1], len[2], len[3]]) as usize;
381            let start = block_at + 4;
382            // A truncated block is charged on what is there; `decode_log`
383            // refuses it. `start` is in range: the length was read below it.
384            let end = start.saturating_add(len).min(bytes.len());
385            let block = &bytes[start..end];
386            cost = cost.saturating_add(movie_extra::decoded_events_bytes(block));
387        }
388        cost
389    }
390
391    /// v3.5.0 — decode what [`Self::encode_log`] wrote, exactly (trailing
392    /// bytes are refused).
393    ///
394    /// # Errors
395    ///
396    /// [`MovieError::Eof`] for a truncated log, [`MovieError::BadInputEvents`]
397    /// for a malformed INPUT EVENTS block, and [`MovieError::BadOptions`] for
398    /// bytes after the log. Never panics, and never reserves more than the
399    /// input could hold.
400    pub fn decode_log(bytes: &[u8]) -> Result<Vec<Self>, MovieError> {
401        let mut r = BinReader::new(bytes);
402        let count = r.u32().map_err(map_eof)? as usize;
403        let frames = read_frames(&mut r, count, usize::from(BYTES_PER_FRAME))?;
404        if r.remaining() != 0 {
405            return Err(MovieError::BadOptions(
406                "unexpected bytes after the input log",
407            ));
408        }
409        Ok(frames)
410    }
411}
412
413/// Write the input stream (one 5-byte record per frame) and, since format 7,
414/// the INPUT EVENTS block carrying each frame's [`FrameInput::extra`] as the
415/// changes between frames, length-prefixed so the decoder can bound it and
416/// confirm it consumed exactly what was written.
417fn write_frames(w: &mut BinWriter, frames: &[FrameInput]) {
418    for f in frames {
419        w.u8(f.p1.bits());
420        w.u8(f.p2.bits());
421        w.u8(f.p3.bits());
422        w.u8(f.p4.bits());
423        w.u8(f.expansion);
424    }
425    w.lp_bytes(&movie_extra::encode_events(
426        frames.iter().map(|f| f.extra.as_ref()),
427    ));
428}
429
430/// Read `frame_count` records of `width` bytes (`width >= 1`), then the
431/// INPUT EVENTS block, which a format-7 stream always carries (an empty one
432/// holds a zero count).
433///
434/// SECURITY: `frame_count` is an untrusted 4-byte field (up to ~4.3
435/// billion). Pre-sizing `Vec::with_capacity(frame_count)` from it lets a
436/// 53-byte header claim a multi-gigabyte allocation -- an OOM `DoS` (found by
437/// the `movie` fuzz target). A real stream carries exactly
438/// `frame_count * width` more bytes, so the reservation is capped at what the
439/// remaining input could actually hold: for a valid file this equals
440/// `frame_count` (identical allocation, byte-for-byte the same result), and
441/// for a truncated / hostile one the `r.take(width)` below still fails
442/// cleanly with an EOF error once the real bytes run out.
443fn read_frames(
444    r: &mut BinReader<'_>,
445    frame_count: usize,
446    width: usize,
447) -> Result<Vec<FrameInput>, MovieError> {
448    let max_plausible_frames = r.remaining() / width;
449    let mut frames = Vec::with_capacity(frame_count.min(max_plausible_frames));
450    for _ in 0..frame_count {
451        let rec = r.take(width).map_err(map_eof)?;
452        // Format 3: rec = [p1, p2, p3, p4, expansion]. A narrower record
453        // defaults the fields it does not reach (released pads, no expansion
454        // byte).
455        let pad = |i: usize| Buttons::from_bits_truncate(rec.get(i).copied().unwrap_or(0));
456        let mut frame = FrameInput::four_players(pad(0), pad(1), pad(2), pad(3));
457        frame.expansion = rec.get(4).copied().unwrap_or(0);
458        frames.push(frame);
459    }
460    let block = r.lp_bytes().map_err(map_eof)?;
461    let extras =
462        movie_extra::decode_events(block, frames.len()).map_err(MovieError::BadInputEvents)?;
463    for (frame, extra) in frames.iter_mut().zip(extras) {
464        frame.extra = extra;
465    }
466    Ok(frames)
467}
468
469/// Marker for the optional attestation tail: `"RNAT"` little-endian.
470///
471/// Read as a `u32` after the re-record count. A movie with no attestation simply
472/// ends there, so the marker is what distinguishes "no attestation recorded" from
473/// "attestation present" — absence is a fact, not a parse failure.
474pub const ATTESTATION_MAGIC: u32 = u32::from_le_bytes(*b"RNAT");
475
476/// Attestation tail schema version.
477///
478/// 2 (v2.9.8): each frame folds in all four players' bytes, not two, so a
479/// version-1 tail describes a different hash and is not compared.
480///
481/// 3 (v3.5.0): each frame also folds in its non-controller inputs
482/// ([`FrameInput::extra`]), so an edited Zapper aim or a removed disk swap
483/// fails verification the way an edited button does. A version-2 tail is not
484/// compared (and every movie that carried one is format 6, refused anyway).
485pub const ATTESTATION_VERSION: u16 = 3;
486
487/// Frames between recorded checkpoint hashes.
488///
489/// The final hash alone would answer "did this run reproduce?"; the checkpoints
490/// answer "and if not, roughly where did it stop reproducing?", which is the
491/// difference between a verdict and a diagnosis. At 8 bytes per checkpoint a
492/// ten-minute run costs about 4.5 KiB.
493pub const ATTESTATION_CHECKPOINT_INTERVAL: u32 = 64;
494
495/// A rolling hash of a run's video output, and the checkpoints along the way.
496///
497/// # What is attested
498///
499/// Per frame, **the input applied and the framebuffer it produced**, folded into
500/// one rolling hash. Both halves are load-bearing:
501///
502/// - The framebuffer is the user-visible output the determinism contract
503///   promises is bit-identical for the same ROM, seed, and input sequence.
504/// - The input is folded in because output alone does not pin the input stream.
505///   A ROM that ignores the controller — a test ROM, an attract-mode demo, a
506///   cutscene — produces identical video no matter what buttons the movie
507///   claims were pressed, so an output-only hash would confirm a tampered input
508///   log as genuine. Found by exactly that: an end-to-end tamper test flipped a
509///   button bit in a movie for an input-ignoring ROM and the run still verified.
510///
511/// Together they attest the real claim: *these inputs, applied to this ROM,
512/// produced this output.*
513///
514/// Hashing the core snapshot instead would be strictly stronger at detecting
515/// divergence, and was rejected for one reason: the snapshot schema is versioned
516/// and bumps between releases (`PPU_SNAPSHOT_VERSION` has reached 8), so every
517/// schema bump would silently invalidate every previously-recorded attestation.
518/// A 256x240 RGBA framebuffer is stable for as long as the NES is the NES. An
519/// attestation is only worth recording if it can still be checked years later.
520///
521/// Audio is **not** covered: samples are drained by the host as they are
522/// produced, so the core cannot see a whole run's audio without the frontend
523/// cooperating. Saying so is better than implying coverage that is not there.
524#[derive(Clone, Debug, Eq, PartialEq)]
525pub struct Attestation {
526    /// Number of frames the attestation covers. Cross-checked against the input
527    /// stream on load, so a tail that describes a different run is rejected
528    /// rather than compared against the wrong frame count.
529    pub frame_count: u32,
530    /// Rolling hash after the final frame.
531    pub final_hash: u64,
532    /// Rolling hash after frames `INTERVAL-1`, `2*INTERVAL-1`, ... in order.
533    pub checkpoints: Vec<u64>,
534}
535
536/// FNV-1a-style rolling hash over 64-bit words.
537///
538/// # This is a tamper-EVIDENT digest, not a cryptographic one
539///
540/// 64-bit FNV-1a is not collision resistant, and its round function is
541/// invertible (`PRIME` is odd, so multiplication is a bijection mod 2^64). It
542/// reliably detects accidental divergence — a different build, a real
543/// nondeterminism bug, a truncated file — and casual edits, which is what
544/// [`Movie::verify`] is for. It does **not** resist a motivated forger: anyone
545/// who edits the movie can recompute the digest, and nothing here binds the
546/// record to an author.
547///
548/// Say "reproduces the recorded run", not "proves the run is genuine". Making a
549/// forgery-resistant claim would need a signature over the whole record with a
550/// key the verifier trusts, which is a different feature. Flagged in review on
551/// PR #356, where the surrounding prose had drifted into the stronger claim.
552///
553/// Written here rather than reused: the two existing `fnv1a64` helpers in this
554/// workspace are behind `rustynes-ppu`'s `ppu-state-trace` feature and in the
555/// test harness respectively, and neither is reachable from `no_std` core code
556/// on the default build. It is six lines; taking a feature dependency to avoid
557/// them would cost more than it saves.
558///
559/// Words rather than bytes because a framebuffer is 245,760 bytes and this runs
560/// once per frame during both recording and verification.
561#[derive(Clone, Copy, Debug)]
562struct RollingHash(u64);
563
564impl RollingHash {
565    const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
566    const PRIME: u64 = 0x0000_0100_0000_01b3;
567
568    const fn new() -> Self {
569        Self(Self::OFFSET_BASIS)
570    }
571
572    /// Fold a byte slice in, 8 bytes at a time. A trailing partial word is
573    /// zero-padded, which is unambiguous here because every input is a
574    /// fixed-size framebuffer.
575    fn write(&mut self, bytes: &[u8]) {
576        let (words, rem) = bytes.as_chunks::<8>();
577        for w in words {
578            self.0 = (self.0 ^ u64::from_le_bytes(*w)).wrapping_mul(Self::PRIME);
579        }
580        if !rem.is_empty() {
581            let mut buf = [0u8; 8];
582            buf[..rem.len()].copy_from_slice(rem);
583            self.0 = (self.0 ^ u64::from_le_bytes(buf)).wrapping_mul(Self::PRIME);
584        }
585    }
586}
587
588/// Accumulates an [`Attestation`] one frame at a time.
589///
590/// Feed it the framebuffer after each `run_frame`; it maintains the rolling hash
591/// and emits a checkpoint every [`ATTESTATION_CHECKPOINT_INTERVAL`] frames.
592#[derive(Clone, Debug)]
593pub struct AttestationBuilder {
594    hash: RollingHash,
595    frame_count: u32,
596    checkpoints: Vec<u64>,
597}
598
599impl AttestationBuilder {
600    /// Start a fresh attestation.
601    #[must_use]
602    pub const fn new() -> Self {
603        Self {
604            hash: RollingHash::new(),
605            frame_count: 0,
606            checkpoints: Vec::new(),
607        }
608    }
609
610    /// Fold in one frame: the input applied, then the video it produced.
611    pub fn push_frame(&mut self, input: FrameInput, framebuffer: &[u8]) {
612        self.hash.write(&[
613            input.p1.bits(),
614            input.p2.bits(),
615            input.p3.bits(),
616            input.p4.bits(),
617            input.expansion,
618        ]);
619        // v3.5.0 (attestation version 3) — the non-controller inputs, as a
620        // fixed-size canonical record (`None` folds in as all zeros).
621        self.hash
622            .write(&movie_extra::attestation_bytes(input.extra.as_ref()));
623        self.hash.write(framebuffer);
624        self.frame_count = self.frame_count.saturating_add(1);
625        if self
626            .frame_count
627            .is_multiple_of(ATTESTATION_CHECKPOINT_INTERVAL)
628        {
629            self.checkpoints.push(self.hash.0);
630        }
631    }
632
633    /// Frames folded in so far.
634    #[must_use]
635    pub const fn frame_count(&self) -> u32 {
636        self.frame_count
637    }
638
639    /// The rolling hash as it stands.
640    #[must_use]
641    pub const fn current_hash(&self) -> u64 {
642        self.hash.0
643    }
644
645    /// Finish and produce the attestation.
646    #[must_use]
647    pub fn finish(self) -> Attestation {
648        Attestation {
649            frame_count: self.frame_count,
650            final_hash: self.hash.0,
651            checkpoints: self.checkpoints,
652        }
653    }
654}
655
656impl Default for AttestationBuilder {
657    fn default() -> Self {
658        Self::new()
659    }
660}
661
662/// The result of replaying an attested movie and comparing it to its record.
663#[derive(Clone, Debug, Eq, PartialEq)]
664pub enum VerifyOutcome {
665    /// The replay reproduced the recorded run exactly.
666    Match {
667        /// Frames replayed.
668        frames: u32,
669        /// The hash both the record and the replay produced.
670        hash: u64,
671    },
672    /// The replay diverged.
673    Mismatch {
674        /// Frames replayed.
675        frames: u32,
676        /// The hash the movie claims.
677        expected: u64,
678        /// The hash this replay produced.
679        got: u64,
680        /// Index of the first checkpoint that disagreed, if any did. The
681        /// divergence began somewhere in the
682        /// [`ATTESTATION_CHECKPOINT_INTERVAL`] frames ending at
683        /// `(index + 1) * INTERVAL - 1`. `None` means every recorded checkpoint
684        /// matched and only the final hash differs — i.e. the divergence is in
685        /// the tail after the last checkpoint.
686        first_bad_checkpoint: Option<u32>,
687    },
688    /// The movie carries no attestation, so there is nothing to verify against.
689    /// Not an error: most movies are recorded without one.
690    NotAttested,
691}
692
693/// Read the optional attestation tail, if one is present and coherent.
694///
695/// Returns `None` — never an error — for every way the tail can be absent or
696/// unusable: no bytes left, a different marker, a schema version this build does
697/// not know, a truncated body, or a frame count that disagrees with the input
698/// stream. A movie without a usable attestation is a perfectly good movie; the
699/// only wrong answer would be to report an attestation that does not describe
700/// this run, so a `frame_count` mismatch drops it rather than comparing against
701/// the wrong length.
702///
703/// The checkpoint count is bounded by what the remaining input could actually
704/// hold before reserving, for the same reason `frame_count` is: a hostile
705/// four-byte field must not be able to request a multi-gigabyte allocation.
706fn read_attestation(r: &mut BinReader<'_>, frames: usize) -> Option<Attestation> {
707    if r.u32().ok()? != ATTESTATION_MAGIC {
708        return None;
709    }
710    if r.u16().ok()? != ATTESTATION_VERSION {
711        return None;
712    }
713    let frame_count = r.u32().ok()?;
714    if frame_count as usize != frames {
715        return None;
716    }
717    let final_hash = r.u64().ok()?;
718    let declared = r.u32().ok()? as usize;
719    let max_plausible = r.remaining() / core::mem::size_of::<u64>();
720    let mut checkpoints = Vec::with_capacity(declared.min(max_plausible));
721    for _ in 0..declared {
722        checkpoints.push(r.u64().ok()?);
723    }
724    Some(Attestation {
725        frame_count,
726        final_hash,
727        checkpoints,
728    })
729}
730
731/// Where a movie begins. Clean-room analogue of Mesen2's `RecordMovieFrom`.
732#[derive(Clone, Debug, Eq, PartialEq)]
733pub enum StartPoint {
734    /// Power-on the ROM fresh, then apply inputs from frame 0. The most
735    /// durable start point across version transitions (depends only on the
736    /// ROM and the deterministic power-on).
737    PowerOn,
738    /// Restore this embedded `.rns` snapshot, then apply inputs from there.
739    /// Enables save-state branching (a movie that begins mid-game).
740    SaveState(Vec<u8>),
741}
742
743/// Errors produced by movie encode / decode / playback.
744#[derive(Debug, Error)]
745#[non_exhaustive]
746pub enum MovieError {
747    /// The blob is shorter than the fixed header.
748    #[error("movie truncated: header needs {expected} bytes, got {got}")]
749    HeaderTruncated {
750        /// Expected byte count.
751        expected: usize,
752        /// Actual byte count.
753        got: usize,
754    },
755
756    /// The magic prefix is wrong.
757    #[error("movie magic mismatch: expected {:?}, got {got:?}", MOVIE_MAGIC)]
758    BadMagic {
759        /// Bytes observed at the magic offset.
760        got: [u8; 8],
761    },
762
763    /// The container format version is outside the range we understand.
764    #[error("movie container format version {got} not supported (max {max})")]
765    UnsupportedFormat {
766        /// Version we read.
767        got: u16,
768        /// Highest version we accept.
769        max: u16,
770    },
771
772    /// v2.9.8 — the movie was written by an older release whose format does
773    /// not record everything a faithful replay needs: before format 3 the
774    /// emulation options, before 4 the full board, before 5 (v3.0.0) the
775    /// emulation epoch. (Until v3.0.0 the message named only the options,
776    /// which stopped being the whole story at format 4.)
777    #[error(
778        "movie format version {got} was written by an older release of RustyNES \
779         (this version replays format {min} and later), and it does not record \
780         everything a faithful replay needs; re-record it with this version"
781    )]
782    FormatTooOld {
783        /// Version we read.
784        got: u16,
785        /// Oldest version this build replays.
786        min: u16,
787    },
788
789    /// v2.9.8 — the header flags carry a bit this build does not know.
790    #[error("movie header flags {0:#04x} carry bits this build does not understand")]
791    UnknownFlags(u8),
792
793    /// v2.9.8 — the OPTIONS block is malformed (an unknown enum byte, a bad
794    /// Game Genie code, a truncated field).
795    #[error("movie emulation options are malformed: {0}")]
796    BadOptions(OptionsDecodeError),
797
798    /// v2.9.8 — the movie was recorded on another region (from a header that
799    /// said PAL, say, where this one says NTSC). A region is built into the
800    /// machine at load, so it cannot be applied; the movie is refused.
801    #[error(
802        "movie was recorded on {movie:?} timing but this ROM runs as {host:?}; \
803         load a dump whose header declares {movie:?}"
804    )]
805    RegionMismatch {
806        /// The movie's region.
807        movie: Region,
808        /// The running machine's region.
809        host: Region,
810    },
811
812    /// v2.9.8 — same ROM, different header: the cartridge the movie ran on
813    /// had another mapper, submapper, mirroring, RAM size, battery or
814    /// trainer. Since v2.9.8 the ROM identity excludes the header, so this is
815    /// what tells a re-headered dump (or a changed database correction)
816    /// apart.
817    #[error(
818        "movie was recorded on the same ROM with a different header: the {field} \
819         differs; load the dump (or game-database correction) it was made with"
820    )]
821    BoardMismatch {
822        /// The first board field that differs.
823        field: &'static str,
824    },
825
826    /// v2.9.8 — an option could not be applied to this machine (a Game Genie
827    /// code that does not decode, in a hand-built movie).
828    #[error("movie emulation option could not be applied: Game Genie code {0:?}")]
829    OptionNotApplicable(String),
830
831    /// v2.9.8 — the movie's embedded start-point save state predates the
832    /// `.rns` container epoch 3 (ADR 0042), which v2.9.8 refuses. Kept apart
833    /// from [`MovieError::BadSaveState`] so the message says what to do, in
834    /// the same words as [`MovieError::FormatTooOld`].
835    #[error(
836        "movie starts from a save state written by an older release (container \
837         version {got}, this build reads {min} and later); re-record it with this \
838         version"
839    )]
840    StartStateTooOld {
841        /// The embedded state's container version.
842        got: u16,
843        /// Oldest container version this build reads.
844        min: u16,
845    },
846
847    /// The header declared more bytes-per-frame than this build understands.
848    #[error("movie declares {got} bytes/frame; this build understands {max}")]
849    UnsupportedFrameWidth {
850        /// Declared width.
851        got: u8,
852        /// Width this build can parse.
853        max: u8,
854    },
855
856    /// The region byte is not a value this build understands.
857    #[error("movie region byte {0} is not a known region")]
858    BadRegion(u8),
859
860    /// v3.5.0 — the INPUT EVENTS block (format 7) is malformed: an unknown
861    /// event kind or device, events out of order or past the last frame, a
862    /// value no input can hold, or an event that changes nothing.
863    #[error("movie non-controller input events are malformed: {0}")]
864    BadInputEvents(&'static str),
865
866    /// The body (start point and/or input stream) ran past EOF.
867    #[error("movie truncated mid-body at offset {0}")]
868    Eof(usize),
869
870    /// The embedded start-point save state failed to apply.
871    #[error("movie start-point save state invalid: {0}")]
872    BadSaveState(#[from] SnapshotError),
873
874    /// The running ROM's hash does not match the movie's recorded hash.
875    #[error("movie ROM hash mismatch (this movie was recorded against a different ROM)")]
876    RomMismatch,
877
878    /// v3.0.0 (ADR 0045) — the movie was recorded by a version of `RustyNES`
879    /// that emulates differently: its [`EMULATION_EPOCH`](crate::EMULATION_EPOCH)
880    /// is not this build's. Replaying it would run the recorded inputs on
881    /// different timing, so it is refused rather than allowed to diverge.
882    #[error(
883        "movie was recorded by a version of RustyNES that emulates differently \
884         (emulation epoch {movie}; this version is epoch {core}); replay it with \
885         that version, or re-record it with this one"
886    )]
887    EpochMismatch {
888        /// The epoch the movie records.
889        movie: u32,
890        /// This build's [`EMULATION_EPOCH`](crate::EMULATION_EPOCH).
891        core: u32,
892    },
893}
894
895/// A complete TAS movie: a versioned header, a start point, and the
896/// per-frame input stream.
897///
898/// `#[non_exhaustive]` since v3.0.0 (T-API-EXTENSIBLE): build one with
899/// [`Movie::new`] (or a [`MovieRecorder`] / an importer), then set the public
900/// fields that differ from its defaults. A later field is then not a break.
901#[derive(Clone, Debug, Eq, PartialEq)]
902#[non_exhaustive]
903pub struct Movie {
904    /// Cartridge region the movie was recorded under. Checked, not applied:
905    /// [`Movie::seek_to_start`] refuses a machine of another region.
906    pub region: Region,
907    /// [`Nes::rom_sha256`] of the ROM the movie was recorded against.
908    pub rom_sha256: [u8; 32],
909    /// v3.0.0 (ADR 0045) — the [`EMULATION_EPOCH`](crate::EMULATION_EPOCH)
910    /// the movie was recorded under. [`Movie::new`] and every recorder and
911    /// importer stamp the current one; [`Movie::deserialize`] refuses
912    /// another.
913    pub epoch: u32,
914    /// v2.9.8 — every emulation-affecting host option the movie was recorded
915    /// with. [`Movie::seek_to_start`] applies them before frame 0, so the
916    /// replay does not depend on the player's settings. A foreign import
917    /// records [`HardwareOptions::default`], the stock NES.
918    pub options: HardwareOptions,
919    /// v2.9.8 — the cartridge board the recording machine was built from.
920    /// `None` for a foreign import (its format records no header), in which
921    /// case only the ROM identity and the region are checked.
922    pub board: Option<BoardDescription>,
923    /// Where playback begins.
924    pub start: StartPoint,
925    /// Per-frame controller inputs, in playback order.
926    pub frames: Vec<FrameInput>,
927    /// TAS re-record count — how many times the author re-recorded a frame
928    /// (the TAS piano-roll editor's edit tally; 0 for a straight linear
929    /// recording). Round-trips through `.rnm` (appended after the input stream,
930    /// so older readers ignore it) and the `.fm2` / `.bk2` `rerecordCount` header.
931    pub rerecord_count: u32,
932    /// Optional replay attestation (v2.3.2 "Lucid"): a rolling hash of the run's
933    /// video output plus periodic checkpoints, letting a third party replay the
934    /// movie and prove it reproduces the recorded run.
935    ///
936    /// `None` for every movie recorded without one, which is most of them.
937    /// Appended after [`Self::rerecord_count`] behind [`ATTESTATION_MAGIC`], so
938    /// an older reader stops at the re-record count and never sees it — the same
939    /// additive-tail trick that field itself used, and the reason no container
940    /// version bump was needed.
941    pub attestation: Option<Attestation>,
942}
943
944impl Movie {
945    /// v3.0.0 — a movie at the current [`EMULATION_EPOCH`](crate::EMULATION_EPOCH)
946    /// with no re-records and no attestation. Set
947    /// [`Self::rerecord_count`] or [`Self::attestation`] afterwards when they
948    /// apply; the struct is `#[non_exhaustive]`, so this is how code outside
949    /// `rustynes-core` builds one.
950    #[must_use]
951    pub const fn new(
952        region: Region,
953        rom_sha256: [u8; 32],
954        options: HardwareOptions,
955        board: Option<BoardDescription>,
956        start: StartPoint,
957        frames: Vec<FrameInput>,
958    ) -> Self {
959        Self {
960            region,
961            rom_sha256,
962            epoch: crate::EMULATION_EPOCH,
963            options,
964            board,
965            start,
966            frames,
967            rerecord_count: 0,
968            attestation: None,
969        }
970    }
971
972    /// Number of input frames in the movie.
973    #[must_use]
974    pub const fn len(&self) -> usize {
975        self.frames.len()
976    }
977
978    /// `true` if the movie has no input frames.
979    #[must_use]
980    pub const fn is_empty(&self) -> bool {
981        self.frames.is_empty()
982    }
983
984    /// Serialize the movie to its `.rnm` byte representation.
985    ///
986    /// Deterministic: the same `Movie` always produces identical bytes.
987    #[must_use]
988    pub fn serialize(&self) -> Vec<u8> {
989        let frame_count = u32::try_from(self.frames.len()).expect("frame count exceeds u32");
990        let body_hint = self.frames.len() * usize::from(BYTES_PER_FRAME);
991        let mut w = BinWriter::with_capacity(48 + body_hint);
992        w.bytes(MOVIE_MAGIC);
993        w.u16(MOVIE_FORMAT_VERSION);
994        // v3.0.0 (format 5, ADR 0045): the emulation epoch, beside the
995        // version so a tool can read both without parsing further.
996        w.u32(self.epoch);
997        w.u8(region_to_byte(self.region));
998        let mut flags = match &self.start {
999            StartPoint::PowerOn => 0,
1000            StartPoint::SaveState(_) => FLAG_HAS_SAVE_STATE,
1001        };
1002        if self.board.is_some() {
1003            flags |= FLAG_HAS_BOARD;
1004        }
1005        w.u8(flags);
1006        w.bytes(&self.rom_sha256);
1007        w.u32(frame_count);
1008        w.u8(BYTES_PER_FRAME);
1009        // v2.9.8 (format 3) — the OPTIONS block, length-prefixed so the
1010        // decoder can bound it and confirm it consumed exactly what was
1011        // written.
1012        let mut opts = BinWriter::with_capacity(48);
1013        self.options.write_to(&mut opts);
1014        if let Some(board) = &self.board {
1015            board.write_to(&mut opts);
1016        }
1017        w.lp_bytes(&opts.into_vec());
1018        if let StartPoint::SaveState(blob) = &self.start {
1019            w.lp_bytes(blob);
1020        }
1021        write_frames(&mut w, &self.frames);
1022        // Trailing re-record count (v1.8.9). Appended AFTER the fixed-count input
1023        // stream so a reader that stops at `frame_count` records — including older
1024        // builds — simply ignores it; deserialize below reads it when present and
1025        // defaults to 0 otherwise. No format-version bump needed.
1026        w.u32(self.rerecord_count);
1027        // Optional attestation tail (v2.3.2 "Lucid"). Written only when present,
1028        // so a movie without one is byte-for-byte what previous versions wrote.
1029        if let Some(att) = &self.attestation {
1030            w.u32(ATTESTATION_MAGIC);
1031            w.u16(ATTESTATION_VERSION);
1032            w.u32(att.frame_count);
1033            w.u64(att.final_hash);
1034            w.u32(u32::try_from(att.checkpoints.len()).unwrap_or(u32::MAX));
1035            for &c in &att.checkpoints {
1036                w.u64(c);
1037            }
1038        }
1039        w.into_vec()
1040    }
1041
1042    /// Parse a `.rnm` movie from its byte representation.
1043    ///
1044    /// # Errors
1045    ///
1046    /// Returns [`MovieError`] for a bad magic, an unsupported container
1047    /// version, an unknown region byte, a frame width this build can't
1048    /// parse, or a truncated body. Never panics on malformed input.
1049    pub fn deserialize(bytes: &[u8]) -> Result<Self, MovieError> {
1050        // Fixed header: magic(8) + version(2) + epoch(4, format 5+) +
1051        // region(1) + flags(1) + sha256(32) + frame_count(4) +
1052        // bytes_per_frame(1) = 53 bytes.
1053        const HEADER_LEN: usize = 8 + 2 + 4 + 1 + 1 + 32 + 4 + 1;
1054        if bytes.len() < HEADER_LEN {
1055            return Err(MovieError::HeaderTruncated {
1056                expected: HEADER_LEN,
1057                got: bytes.len(),
1058            });
1059        }
1060        let mut r = BinReader::new(bytes);
1061        // Magic.
1062        let mut magic = [0u8; 8];
1063        r.read_into(&mut magic).map_err(map_eof)?;
1064        if &magic != MOVIE_MAGIC {
1065            return Err(MovieError::BadMagic { got: magic });
1066        }
1067        // Version.
1068        let format_version = r.u16().map_err(map_eof)?;
1069        if format_version > MOVIE_FORMAT_VERSION {
1070            return Err(MovieError::UnsupportedFormat {
1071                got: format_version,
1072                max: MOVIE_FORMAT_VERSION,
1073            });
1074        }
1075        if format_version < MIN_MOVIE_FORMAT_VERSION {
1076            return Err(MovieError::FormatTooOld {
1077                got: format_version,
1078                min: MIN_MOVIE_FORMAT_VERSION,
1079            });
1080        }
1081        // v3.0.0 (format 5, ADR 0045): the emulation epoch. Checked before
1082        // anything else is parsed: a movie from a core that emulates
1083        // differently is refused whatever the rest of it holds.
1084        let epoch = r.u32().map_err(map_eof)?;
1085        if epoch != crate::EMULATION_EPOCH {
1086            return Err(MovieError::EpochMismatch {
1087                movie: epoch,
1088                core: crate::EMULATION_EPOCH,
1089            });
1090        }
1091        // Region + flags.
1092        let region = region_from_byte(r.u8().map_err(map_eof)?)?;
1093        let flags = r.u8().map_err(map_eof)?;
1094        if flags & !KNOWN_FLAGS != 0 {
1095            return Err(MovieError::UnknownFlags(flags));
1096        }
1097        // ROM hash.
1098        let mut rom_sha256 = [0u8; 32];
1099        r.read_into(&mut rom_sha256).map_err(map_eof)?;
1100        // Frame count + width.
1101        let frame_count = r.u32().map_err(map_eof)? as usize;
1102        let bytes_per_frame = r.u8().map_err(map_eof)?;
1103        if bytes_per_frame == 0 || bytes_per_frame > BYTES_PER_FRAME {
1104            // A newer movie packs more device bytes than we understand; we
1105            // fail cleanly rather than mis-parse (the reserved byte exists
1106            // precisely so this stays a graceful error, not a corruption).
1107            //
1108            // SECURITY: a `bytes_per_frame` of 0 is likewise rejected. With a
1109            // zero-width record each frame read (`r.take(0)`) consumes no input,
1110            // so the `for _ in 0..frame_count` loop below would push
1111            // `frame_count` (an untrusted u32, up to ~4.3 billion) empty frames
1112            // out of a finite file — an OOM DoS (found by the `movie` fuzz
1113            // target). A real movie always writes the fixed `BYTES_PER_FRAME`
1114            // (>= 1), so rejecting 0 costs no legitimate file.
1115            return Err(MovieError::UnsupportedFrameWidth {
1116                got: bytes_per_frame,
1117                max: BYTES_PER_FRAME,
1118            });
1119        }
1120        // v2.9.8 — the OPTIONS block. Decoded from its own bounded slice, and
1121        // required to be consumed exactly: trailing bytes would mean a later
1122        // format added a field this build would otherwise silently ignore.
1123        let block = r.lp_bytes().map_err(map_eof)?;
1124        let mut br = BinReader::new(block);
1125        let options = HardwareOptions::read_from(&mut br).map_err(MovieError::BadOptions)?;
1126        let board = if flags & FLAG_HAS_BOARD != 0 {
1127            Some(BoardDescription::read_from(&mut br).map_err(MovieError::BadOptions)?)
1128        } else {
1129            None
1130        };
1131        if br.remaining() != 0 {
1132            return Err(MovieError::BadOptions("unexpected bytes after the options"));
1133        }
1134        // Start point.
1135        let start = if flags & FLAG_HAS_SAVE_STATE != 0 {
1136            let blob = r.lp_bytes().map_err(map_eof)?;
1137            StartPoint::SaveState(blob.to_vec())
1138        } else {
1139            StartPoint::PowerOn
1140        };
1141        // Input stream: `frame_count` records of `bytes_per_frame` bytes
1142        // (`width >= 1`, enforced above).
1143        let width = usize::from(bytes_per_frame);
1144        // SECURITY: `frame_count` is untrusted; `read_frames` bounds the
1145        // reservation by what the input holds (see it for the full note).
1146        let frames = read_frames(&mut r, frame_count, width)?;
1147        // Optional trailing re-record count (v1.8.9). Absent in pre-v1.8.9 `.rnm`
1148        // files, which stop exactly at the input stream — default to 0.
1149        let rerecord_count = r.u32().unwrap_or(0);
1150        // Optional attestation tail (v2.3.2 "Lucid"). Absent in every movie
1151        // recorded before it existed, and in any recorded without it — so a
1152        // missing or unrecognized marker yields `None` rather than an error.
1153        let attestation = read_attestation(&mut r, frames.len());
1154        Ok(Self {
1155            region,
1156            rom_sha256,
1157            epoch,
1158            options,
1159            board,
1160            start,
1161            frames,
1162            rerecord_count,
1163            attestation,
1164        })
1165    }
1166
1167    /// Rewind a running emulator to this movie's start point, ready to replay
1168    /// from frame 0.
1169    ///
1170    /// Checks first, then changes the machine: the ROM identity, the region
1171    /// and (for a recorded movie) the [`BoardDescription`] must match, or the
1172    /// call fails with `nes` untouched. Then it applies the movie's
1173    /// [`HardwareOptions`] -- v2.9.8: the recorded console model, die
1174    /// revisions, power-on fills, overclock, Four Score, Vs. settings,
1175    /// mirroring override and Game Genie codes replace the player's -- and
1176    /// moves to the start point: for [`StartPoint::PowerOn`] a power cycle
1177    /// with cleared cartridge RAM ([`power_on_for_movie`]), for
1178    /// [`StartPoint::SaveState`] the embedded snapshot.
1179    ///
1180    /// A start refused after the checks -- an old or malformed start state,
1181    /// an undecodable code -- also leaves `nes` as it was: the call takes a
1182    /// rollback point first and restores it on any error.
1183    ///
1184    /// After a successful start the player's options are not restored here;
1185    /// a host that wants them back captures them first ([`HardwareOptions::capture`]) and calls
1186    /// [`HardwareOptions::restore_after_playback`] when playback ends.
1187    ///
1188    /// # Errors
1189    ///
1190    /// [`MovieError::EpochMismatch`] for a movie recorded under another
1191    /// emulation epoch (ADR 0045); [`MovieError::RomMismatch`],
1192    /// [`MovieError::RegionMismatch`] or [`MovieError::BoardMismatch`] for a
1193    /// different machine;
1194    /// [`MovieError::OptionNotApplicable`] for a Game Genie code that does
1195    /// not decode; [`MovieError::BadSaveState`] if the embedded snapshot is
1196    /// malformed.
1197    pub fn seek_to_start(&self, nes: &mut Nes) -> Result<(), MovieError> {
1198        self.check_epoch()?;
1199        if nes.rom_sha256() != &self.rom_sha256 {
1200            return Err(MovieError::RomMismatch);
1201        }
1202        if nes.region() != self.region {
1203            return Err(MovieError::RegionMismatch {
1204                movie: self.region,
1205                host: nes.region(),
1206            });
1207        }
1208        if let Some(board) = &self.board
1209            && let Some(field) = board.first_difference(&BoardDescription::capture(nes))
1210        {
1211            return Err(MovieError::BoardMismatch { field });
1212        }
1213        // A refused start must leave the player's game as it was. The options
1214        // are applied before the start point is reached, and `apply` rewrites
1215        // work RAM and palette RAM, so take a rollback point first. A
1216        // snapshot per movie start costs one serialisation; seeking is not a
1217        // per-frame call.
1218        let prior_options = HardwareOptions::capture(nes);
1219        let prior_state = nes.snapshot();
1220        let result = self.enter_start(nes);
1221        if result.is_err() {
1222            // This order: the player's `apply` rewrites the fills, then the
1223            // restore puts the running game's RAM and palette back over them.
1224            // Neither can fail: the codes decoded when they were captured,
1225            // and the blob is this machine's own snapshot.
1226            let options_back = prior_options.apply(nes);
1227            let state_back = nes.restore_quiet(&prior_state);
1228            debug_assert!(options_back.is_ok() && state_back.is_ok());
1229        }
1230        result
1231    }
1232
1233    /// v3.0.0 (ADR 0045): refuse a movie recorded under another emulation
1234    /// epoch. [`Self::deserialize`] checks the field it parses; this checks
1235    /// the field as it stands, because `epoch` is public and a [`Movie`] can
1236    /// be built or edited in memory, and playback must not trust that it came
1237    /// through `deserialize` (a review finding on #588).
1238    const fn check_epoch(&self) -> Result<(), MovieError> {
1239        if self.epoch != crate::EMULATION_EPOCH {
1240            return Err(MovieError::EpochMismatch {
1241                movie: self.epoch,
1242                core: crate::EMULATION_EPOCH,
1243            });
1244        }
1245        Ok(())
1246    }
1247
1248    /// The mutating half of [`Self::seek_to_start`], after the identity
1249    /// checks; its caller rolls the machine back if this fails.
1250    fn enter_start(&self, nes: &mut Nes) -> Result<(), MovieError> {
1251        // Applied BEFORE the start point is reached. For a power-on start the
1252        // power cycle must see the movie's stored power-on knobs (fills,
1253        // console model, die revision); for a save-state start the restore
1254        // then replaces whatever RAM / palette the fills wrote.
1255        self.options
1256            .apply(nes)
1257            .map_err(MovieError::OptionNotApplicable)?;
1258        match &self.start {
1259            StartPoint::PowerOn => power_on_for_movie(nes),
1260            StartPoint::SaveState(blob) => {
1261                nes.restore(blob).map_err(|e| match e {
1262                    SnapshotError::FormatTooOld { got, min } => {
1263                        MovieError::StartStateTooOld { got, min }
1264                    }
1265                    other => MovieError::BadSaveState(other),
1266                })?;
1267                // The options are configuration, not save-state, so a restore
1268                // leaves them alone; re-asserting the live ones is cheap and
1269                // keeps that a checked fact rather than an assumption.
1270                self.options
1271                    .apply_live(nes)
1272                    .map_err(MovieError::OptionNotApplicable)?;
1273            }
1274        }
1275        Ok(())
1276    }
1277
1278    /// v2.3.2 "Lucid" — replay this movie and check it reproduces its
1279    /// attestation.
1280    ///
1281    /// Seeks `nes` to the movie's start point, replays the whole input stream,
1282    /// and compares the resulting rolling hash (and every checkpoint along the
1283    /// way) against what the movie recorded. Anyone with the ROM and the `.rnm`
1284    /// can run it and get the same answer, so an accidental divergence — a
1285    /// different build, a nondeterminism bug, a corrupted file — or a casual
1286    /// edit to the input stream, the start point, or the claimed hash shows up
1287    /// as a [`VerifyOutcome::Mismatch`].
1288    ///
1289    /// **Reproducibility, not provenance.** The digest is a 64-bit FNV-1a
1290    /// variant: tamper-evident, not forgery-resistant. A `Match` means "these inputs,
1291    /// applied to this ROM, on a verifier configured like the recorder, produce
1292    /// this video". It does not establish who produced the movie, and a
1293    /// motivated forger can edit the movie and recompute the digest.
1294    ///
1295    /// Consumes real emulation time — it runs every frame of the movie.
1296    ///
1297    /// # Errors
1298    ///
1299    /// [`MovieError::EpochMismatch`] for a movie from another emulation epoch
1300    /// (checked first, attested or not), [`MovieError::RomMismatch`] if `nes`
1301    /// is running a different ROM, or [`MovieError::BadSaveState`] if an
1302    /// embedded start point is malformed.
1303    /// A movie with no attestation is **not** an error; it returns
1304    /// [`VerifyOutcome::NotAttested`], because "this movie makes no claim" and
1305    /// "this movie makes a false claim" are different answers.
1306    pub fn verify(&self, nes: &mut Nes) -> Result<VerifyOutcome, MovieError> {
1307        // Before the attestation question: a movie from another epoch cannot
1308        // be replayed here at all, which is a stronger answer than "makes no
1309        // claim".
1310        self.check_epoch()?;
1311        let Some(att) = self.attestation.as_ref() else {
1312            return Ok(VerifyOutcome::NotAttested);
1313        };
1314        self.seek_to_start(nes)?;
1315        let mut builder = AttestationBuilder::new();
1316        let mut first_bad_checkpoint = None;
1317        let mut player = MoviePlayer::new(self);
1318        let mut idx = 0usize;
1319        while player.apply_next(nes) {
1320            let input = self.frames.get(idx).copied().unwrap_or_default();
1321            idx += 1;
1322            let fb = nes.run_frame();
1323            builder.push_frame(input, fb);
1324            // Compare each checkpoint as it is produced rather than collecting
1325            // and diffing afterwards: the first disagreement is the useful one,
1326            // and it localizes the divergence to a 64-frame window.
1327            if builder
1328                .frame_count()
1329                .is_multiple_of(ATTESTATION_CHECKPOINT_INTERVAL)
1330                && first_bad_checkpoint.is_none()
1331            {
1332                let idx = builder.frame_count() / ATTESTATION_CHECKPOINT_INTERVAL - 1;
1333                // Compare ONLY against a checkpoint the movie actually recorded.
1334                // `get()` returning `None` means "no recorded value here", not
1335                // "mismatch": treating absence as disagreement made a short
1336                // checkpoint list report a divergence even when every hash the
1337                // movie does carry — including the final one — matched. The
1338                // final hash is the gate; the checkpoints only localize.
1339                if let Some(&want) = att.checkpoints.get(idx as usize)
1340                    && want != builder.current_hash()
1341                {
1342                    first_bad_checkpoint = Some(idx);
1343                }
1344            }
1345        }
1346        let got = builder.current_hash();
1347        let frames = builder.frame_count();
1348        if got == att.final_hash && first_bad_checkpoint.is_none() {
1349            Ok(VerifyOutcome::Match { frames, hash: got })
1350        } else {
1351            Ok(VerifyOutcome::Mismatch {
1352                frames,
1353                expected: att.final_hash,
1354                got,
1355                first_bad_checkpoint,
1356            })
1357        }
1358    }
1359}
1360
1361/// Records the per-frame input stream applied to an emulator.
1362///
1363/// Usage (caller-driven, mirrors the frontend's per-frame loop):
1364///
1365/// ```ignore
1366/// let mut rec = MovieRecorder::power_on(&nes);
1367/// loop {
1368///     nes.set_buttons(0, p1);
1369///     nes.set_buttons(1, p2);
1370///     rec.capture(&nes); // BEFORE run_frame — captures the inputs it consumes
1371///     nes.run_frame();
1372/// }
1373/// let movie = rec.finish();
1374/// ```
1375#[derive(Clone, Debug)]
1376pub struct MovieRecorder {
1377    region: Region,
1378    rom_sha256: [u8; 32],
1379    options: HardwareOptions,
1380    board: BoardDescription,
1381    start: StartPoint,
1382    frames: Vec<FrameInput>,
1383    /// v2.3.2 "Lucid" — optional attestation accumulator. `None` (the default)
1384    /// records a plain movie, byte-for-byte what previous versions produced.
1385    attestation: Option<AttestationBuilder>,
1386}
1387
1388/// v2.9.0 — the state every [`StartPoint::PowerOn`] movie starts from.
1389///
1390/// A power cycle, then cartridge RAM zeroed: what a fresh load with no save
1391/// file holds (every board allocates it zeroed).
1392///
1393/// # Why this is not just `power_cycle`
1394///
1395/// From v2.9.0 [`Nes::power_cycle`] KEEPS battery-backed RAM, as a console
1396/// does. Before, it rebuilt the mapper with all cartridge RAM cleared, which
1397/// made a Power Cycle erase the player's `.sav` once the desktop began
1398/// persisting saves (v2.7.3). A power-on movie still has to start from clean
1399/// save RAM -- the maintainer's decision of 2026-09-26, `TASVideos`'
1400/// convention -- or it would replay differently with and without a save. So
1401/// hosts call this before [`MovieRecorder::power_on`], and
1402/// [`Movie::seek_to_start`] calls it on playback.
1403///
1404/// Only the emulator's copy is cleared. The `.sav` file on disk is untouched,
1405/// but a host that persists save RAM will write the cleared contents back if
1406/// the movie session runs long enough to reach the game's own save routine --
1407/// the same as that routine running during the movie. FDS disk sides are not
1408/// cartridge RAM and are not reset by this.
1409///
1410/// # The options survive the power cycle (v2.9.8)
1411///
1412/// Before v2.9.8 [`Nes::power_cycle`] rebuilt the PPU and dropped the
1413/// PPU-held knobs (OAM decay, the overclock, the fast dot path) to their
1414/// defaults, so a recording started with OAM decay off whatever the player
1415/// had set, and nothing recorded that. The options are captured first and the
1416/// live ones re-applied after the cycle, so the machine a movie starts on is
1417/// the one its [`HardwareOptions`] describe, on the recording side and the
1418/// playback side alike. Since v2.9.8 the cycle keeps every setting itself
1419/// (the PPU and APU ones as well as the bus-held console model, die
1420/// revisions, power-on fills, Four Score, Game Genie ...), so the
1421/// re-application is a guarantee rather than a repair: it holds whatever a
1422/// future cycle might drop. The power-on fills are not re-applied: the cycle
1423/// itself already filled RAM and palette RAM from the stored selection.
1424pub fn power_on_for_movie(nes: &mut Nes) {
1425    let options = HardwareOptions::capture(nes);
1426    nes.power_cycle();
1427    // Not `sram_mut().fill(0)`: on a flash board (v2.9.6) the save is the PRG
1428    // image, and a never-saved flash is the ROM as loaded, not zeros.
1429    nes.clear_save_data();
1430    // Codes captured from this same machine always decode again.
1431    let reapplied = options.apply_live(nes);
1432    debug_assert!(reapplied.is_ok(), "captured options re-apply");
1433    // The fast dot path is not an option (it selects a code path, not a
1434    // behaviour) and the cycle keeps it since v2.9.8, so starting a movie does
1435    // not change which PPU path the player runs. Until v2.9.8 it was captured
1436    // and re-set here by hand.
1437}
1438
1439impl MovieRecorder {
1440    /// Begin recording a movie that starts from a fresh power-on of the ROM
1441    /// `nes` is running. The caller is responsible for calling
1442    /// [`power_on_for_movie`] on `nes` before the first captured frame so the
1443    /// recording starts from the same state a replay will reconstruct.
1444    ///
1445    /// v2.9.8: the machine's [`HardwareOptions`] and [`BoardDescription`] are
1446    /// captured here and written into the movie, so a host must set its
1447    /// options before this call, not after.
1448    #[must_use]
1449    pub fn power_on(nes: &Nes) -> Self {
1450        Self {
1451            region: nes.region(),
1452            rom_sha256: *nes.rom_sha256(),
1453            options: HardwareOptions::capture(nes),
1454            board: BoardDescription::capture(nes),
1455            start: StartPoint::PowerOn,
1456            frames: Vec::new(),
1457            attestation: None,
1458        }
1459    }
1460
1461    /// Begin recording a movie that starts from `nes`'s *current* state (a
1462    /// branch point). Captures a snapshot now and embeds it as the start
1463    /// point; the input stream is recorded from here forward.
1464    #[must_use]
1465    pub fn from_current_state(nes: &Nes) -> Self {
1466        Self {
1467            region: nes.region(),
1468            rom_sha256: *nes.rom_sha256(),
1469            options: HardwareOptions::capture(nes),
1470            board: BoardDescription::capture(nes),
1471            start: StartPoint::SaveState(nes.snapshot()),
1472            frames: Vec::new(),
1473            attestation: None,
1474        }
1475    }
1476
1477    /// Record the controller inputs currently held on `nes`. Call this each
1478    /// frame *before* [`Nes::run_frame`], after the frontend has applied its
1479    /// `set_buttons` calls — this captures exactly the inputs the upcoming
1480    /// frame consumes.
1481    ///
1482    /// # All four ports (v2.9.8)
1483    ///
1484    /// Reads `nes.buttons(0..=3)`. Until v2.9.8 [`FrameInput`] modelled ports
1485    /// 0 and 1 only, so a four-player session recorded half of what drove it
1486    /// and diverged on playback; the `.rnm` format 3 epoch widened the record
1487    /// and the struct together. Since v3.5.0 (format 7) the inputs that are
1488    /// not controller buttons -- expansion devices, the Famicom microphone,
1489    /// Vs. coins / service, FDS disk swaps, Datach scans -- are recorded too
1490    /// ([`FrameInput::held_on`] fills [`FrameInput::extra`]); see
1491    /// `docs/frontend.md` § "The non-controller inputs".
1492    pub fn capture(&mut self, nes: &Nes) {
1493        self.frames.push(FrameInput::held_on(nes));
1494    }
1495
1496    /// Record an explicit frame of input (for callers that drive input
1497    /// programmatically rather than through `set_buttons`).
1498    pub fn capture_input(&mut self, input: FrameInput) {
1499        self.frames.push(input);
1500    }
1501
1502    /// Number of frames captured so far.
1503    #[must_use]
1504    pub const fn len(&self) -> usize {
1505        self.frames.len()
1506    }
1507
1508    /// `true` if no frames have been captured.
1509    #[must_use]
1510    pub const fn is_empty(&self) -> bool {
1511        self.frames.is_empty()
1512    }
1513
1514    /// v2.9.8 — the options this recording was started with, which the movie
1515    /// will carry. A host holds them in place for the length of the recording
1516    /// ([`HardwareOptions::apply_live`] each frame), because the movie records
1517    /// them once, at the start.
1518    #[must_use]
1519    pub const fn options(&self) -> &HardwareOptions {
1520        &self.options
1521    }
1522
1523    /// v2.3.2 "Lucid" — start accumulating a replay attestation.
1524    ///
1525    /// Call before the first frame. The caller must then call
1526    /// [`Self::attest_frame`] after every `run_frame`, in lockstep with
1527    /// [`Self::capture`], or the recorded hash will describe a different run
1528    /// than the input stream does — which [`Movie::verify`] would then report as
1529    /// a mismatch, correctly but unhelpfully.
1530    pub fn enable_attestation(&mut self) {
1531        self.attestation = Some(AttestationBuilder::new());
1532    }
1533
1534    /// Abandon an in-progress attestation, keeping the recording itself.
1535    ///
1536    /// For a host that rewinds or otherwise moves the emulator off the timeline
1537    /// the accumulated hash describes. Once dropped it is not resumed: the
1538    /// prefix already folded in cannot be un-folded, and a partial hash that
1539    /// silently covers only part of the run would be worse than none.
1540    pub fn disable_attestation(&mut self) {
1541        self.attestation = None;
1542    }
1543
1544    /// Fold this frame's video output into the attestation.
1545    ///
1546    /// A no-op unless [`Self::enable_attestation`] was called. Pass the slice
1547    /// `Nes::run_frame` returned (or `Nes::framebuffer()`), AFTER the frame ran.
1548    ///
1549    /// Uses the input recorded by the matching [`Self::capture`], so the two
1550    /// must stay in lockstep — one `capture` then one `attest_frame` per frame.
1551    /// If they drift the recorded frame counts disagree and `Movie::deserialize`
1552    /// drops the tail, which is the safe direction.
1553    pub fn attest_frame(&mut self, framebuffer: &[u8]) {
1554        // The input for THIS frame is the one `capture` just pushed.
1555        let input = self.frames.last().copied().unwrap_or_default();
1556        if let Some(a) = self.attestation.as_mut() {
1557            a.push_frame(input, framebuffer);
1558        }
1559    }
1560
1561    /// Finish recording and produce the [`Movie`].
1562    #[must_use]
1563    pub fn finish(self) -> Movie {
1564        Movie {
1565            region: self.region,
1566            rom_sha256: self.rom_sha256,
1567            epoch: crate::EMULATION_EPOCH,
1568            options: self.options,
1569            board: Some(self.board),
1570            start: self.start,
1571            frames: self.frames,
1572            // A linear recording has no re-records by construction; TAStudio
1573            // sets a real count when it exports an edited movie.
1574            rerecord_count: 0,
1575            attestation: self.attestation.map(AttestationBuilder::finish),
1576        }
1577    }
1578}
1579
1580/// Plays a movie back, feeding its recorded inputs into an emulator one frame
1581/// at a time.
1582///
1583/// Usage (caller-driven; the player applies `set_buttons`, the caller runs
1584/// the frame):
1585///
1586/// ```ignore
1587/// movie.seek_to_start(&mut nes)?;
1588/// let mut player = MoviePlayer::new(&movie);
1589/// while player.apply_next(&mut nes) {
1590///     nes.run_frame();
1591/// }
1592/// ```
1593#[derive(Clone, Debug)]
1594pub struct MoviePlayer<'a> {
1595    movie: &'a Movie,
1596    cursor: usize,
1597}
1598
1599impl<'a> MoviePlayer<'a> {
1600    /// Create a player positioned at frame 0 of `movie`.
1601    #[must_use]
1602    pub const fn new(movie: &'a Movie) -> Self {
1603        Self { movie, cursor: 0 }
1604    }
1605
1606    /// Total frames in the movie.
1607    #[must_use]
1608    pub const fn len(&self) -> usize {
1609        self.movie.frames.len()
1610    }
1611
1612    /// `true` if the movie has no frames.
1613    #[must_use]
1614    pub const fn is_empty(&self) -> bool {
1615        self.movie.frames.is_empty()
1616    }
1617
1618    /// Index of the frame that [`Self::apply_next`] will apply next.
1619    #[must_use]
1620    pub const fn cursor(&self) -> usize {
1621        self.cursor
1622    }
1623
1624    /// `true` if every frame has been played.
1625    #[must_use]
1626    pub const fn is_finished(&self) -> bool {
1627        self.cursor >= self.movie.frames.len()
1628    }
1629
1630    /// Peek the next frame's input without advancing.
1631    #[must_use]
1632    pub fn peek(&self) -> Option<FrameInput> {
1633        self.movie.frames.get(self.cursor).copied()
1634    }
1635
1636    /// Apply the next frame's recorded input to `nes` via `set_buttons` and
1637    /// advance the cursor. Returns `false` (without applying anything) once
1638    /// the movie is exhausted — the caller stops its replay loop on `false`.
1639    ///
1640    /// Call this *before* [`Nes::run_frame`], mirroring the record-side
1641    /// `capture` ordering, so the same inputs are applied to the same frame.
1642    pub fn apply_next(&mut self, nes: &mut Nes) -> bool {
1643        let Some(input) = self.movie.frames.get(self.cursor).copied() else {
1644            return false;
1645        };
1646        input.apply_to(nes);
1647        self.cursor += 1;
1648        true
1649    }
1650
1651    /// Reset the cursor back to frame 0 (the caller is responsible for
1652    /// re-seeking `nes` via [`Movie::seek_to_start`]).
1653    pub const fn rewind(&mut self) {
1654        self.cursor = 0;
1655    }
1656}
1657
1658const fn region_to_byte(region: Region) -> u8 {
1659    match region {
1660        Region::Ntsc => 0,
1661        Region::Pal => 1,
1662        Region::Dendy => 2,
1663    }
1664}
1665
1666const fn region_from_byte(b: u8) -> Result<Region, MovieError> {
1667    match b {
1668        0 => Ok(Region::Ntsc),
1669        1 => Ok(Region::Pal),
1670        2 => Ok(Region::Dendy),
1671        other => Err(MovieError::BadRegion(other)),
1672    }
1673}
1674
1675/// Map a `SnapshotError::Eof`-style truncation reading the movie body into a
1676/// movie-level [`MovieError::Eof`]. Other snapshot errors cannot arise from
1677/// the `BinReader` calls in this module (they only read fixed primitives).
1678fn map_eof(e: SnapshotError) -> MovieError {
1679    match e {
1680        SnapshotError::Eof(off) => MovieError::Eof(off),
1681        other => MovieError::BadSaveState(other),
1682    }
1683}
1684
1685#[cfg(test)]
1686mod tests {
1687    use super::*;
1688    use crate::nes::PowerOnRam;
1689    use alloc::vec;
1690
1691    // ----------------------------------------------------------------- v2.3.2
1692    // Replay attestation ("Lucid" phase 4)
1693    // -------------------------------------------------------------------------
1694
1695    /// Record a short attested run and prove it replays to the same hash.
1696    ///
1697    /// This is the whole feature in one test: the claim is not "the hash is
1698    /// stable" but "an independent replay re-derives it", which is what makes
1699    /// the record evidence rather than decoration.
1700    #[test]
1701    fn attested_movie_verifies_against_an_independent_replay() {
1702        let rom = synth_nrom();
1703        let mut nes = Nes::from_rom(&rom).expect("parse");
1704        let mut rec = MovieRecorder::power_on(&nes);
1705        rec.enable_attestation();
1706        for _ in 0..8 {
1707            rec.capture(&nes);
1708            let fb = nes.run_frame().to_vec();
1709            rec.attest_frame(&fb);
1710        }
1711        let movie = rec.finish();
1712        let att = movie.attestation.as_ref().expect("attestation recorded");
1713        assert_eq!(att.frame_count, 8);
1714
1715        // A SEPARATE emulator instance, as a third party would use.
1716        let mut fresh = Nes::from_rom(&rom).expect("parse");
1717        match movie.verify(&mut fresh).expect("verify runs") {
1718            VerifyOutcome::Match { frames, hash } => {
1719                assert_eq!(frames, 8);
1720                assert_eq!(hash, att.final_hash);
1721            }
1722            other => panic!("expected a match, got {other:?}"),
1723        }
1724    }
1725
1726    /// The attestation survives the `.rnm` round-trip, and a movie WITHOUT one
1727    /// still serializes to exactly the bytes it did before this feature existed.
1728    #[test]
1729    fn attestation_round_trips_and_is_absent_when_not_recorded() {
1730        let rom = synth_nrom();
1731        let mut nes = Nes::from_rom(&rom).expect("parse");
1732
1733        // Plain recording: no attestation, and the tail is not written.
1734        let mut plain = MovieRecorder::power_on(&nes);
1735        plain.capture(&nes);
1736        let _ = nes.run_frame();
1737        let plain = plain.finish();
1738        assert!(plain.attestation.is_none());
1739        let plain_bytes = plain.serialize();
1740        let reparsed = Movie::deserialize(&plain_bytes).expect("round-trip");
1741        assert_eq!(reparsed, plain);
1742        assert!(reparsed.attestation.is_none());
1743
1744        // Attested recording: the tail round-trips intact.
1745        let mut nes2 = Nes::from_rom(&rom).expect("parse");
1746        let mut rec = MovieRecorder::power_on(&nes2);
1747        rec.enable_attestation();
1748        // Enough frames to cross a checkpoint boundary.
1749        for _ in 0..(ATTESTATION_CHECKPOINT_INTERVAL + 3) {
1750            rec.capture(&nes2);
1751            let fb = nes2.run_frame().to_vec();
1752            rec.attest_frame(&fb);
1753        }
1754        let attested = rec.finish();
1755        assert_eq!(attested.attestation.as_ref().unwrap().checkpoints.len(), 1);
1756        let bytes = attested.serialize();
1757        assert_eq!(Movie::deserialize(&bytes).expect("round-trip"), attested);
1758
1759        // The attested file is strictly longer, and the plain one is unchanged
1760        // by this feature existing.
1761        assert!(bytes.len() > plain_bytes.len());
1762    }
1763
1764    /// A reader that stops at the re-record count — i.e. every build before this
1765    /// feature — must still parse an attested movie as a plain one. Simulated by
1766    /// truncating the tail, which is exactly what such a reader sees.
1767    #[test]
1768    fn attested_movie_stays_readable_as_a_plain_movie() {
1769        let rom = synth_nrom();
1770        let mut nes = Nes::from_rom(&rom).expect("parse");
1771        let mut rec = MovieRecorder::power_on(&nes);
1772        rec.enable_attestation();
1773        for _ in 0..4 {
1774            rec.capture(&nes);
1775            let fb = nes.run_frame().to_vec();
1776            rec.attest_frame(&fb);
1777        }
1778        let attested = rec.finish();
1779        let full = attested.serialize();
1780
1781        // Everything an older reader consumes: header + inputs + rerecord count.
1782        // The attestation tail is 4 + 2 + 4 + 8 + 4 = 22 bytes plus checkpoints
1783        // (none here, 4 frames < the interval).
1784        let tail_len = 4 + 2 + 4 + 8 + 4;
1785        let older_view = &full[..full.len() - tail_len];
1786        let parsed = Movie::deserialize(older_view).expect("older readers still parse it");
1787        assert_eq!(parsed.frames, attested.frames);
1788        assert_eq!(parsed.rerecord_count, attested.rerecord_count);
1789        assert!(parsed.attestation.is_none());
1790    }
1791
1792    /// Tampering with the input stream must be detected. This is the property
1793    /// that makes an attestation worth anything.
1794    #[test]
1795    fn tampering_with_the_input_stream_fails_verification() {
1796        let rom = synth_nrom();
1797        let mut nes = Nes::from_rom(&rom).expect("parse");
1798        let mut rec = MovieRecorder::power_on(&nes);
1799        rec.enable_attestation();
1800        for _ in 0..6 {
1801            rec.capture(&nes);
1802            let fb = nes.run_frame().to_vec();
1803            rec.attest_frame(&fb);
1804        }
1805        let mut movie = rec.finish();
1806
1807        // Forge the claimed hash. A replay must refuse to confirm it.
1808        let real = movie.attestation.as_ref().unwrap().final_hash;
1809        movie.attestation.as_mut().unwrap().final_hash = real ^ 1;
1810        let mut fresh = Nes::from_rom(&rom).expect("parse");
1811        match movie.verify(&mut fresh).expect("verify runs") {
1812            VerifyOutcome::Mismatch { expected, got, .. } => {
1813                assert_eq!(expected, real ^ 1);
1814                assert_eq!(got, real, "the replay re-derives the TRUE hash");
1815            }
1816            other => panic!("a forged hash must not verify, got {other:?}"),
1817        }
1818    }
1819
1820    /// A flipped INPUT bit must fail verification even when the ROM ignores
1821    /// input entirely and the video output is therefore unchanged.
1822    ///
1823    /// This is the case an output-only hash gets wrong, and it is not
1824    /// hypothetical: an end-to-end `rustynes verify` run against a test ROM that
1825    /// never reads the controller happily confirmed a movie whose input log had
1826    /// been edited. The fix was to fold the per-frame input into the hash; this
1827    /// test is what keeps it folded in.
1828    #[test]
1829    fn flipped_input_fails_even_when_the_rom_ignores_input() {
1830        // `synth_nrom` is an infinite `JMP` — it never reads $4016, so its video
1831        // output is identical for every possible input stream.
1832        let rom = synth_nrom();
1833        let mut nes = Nes::from_rom(&rom).expect("parse");
1834        let mut rec = MovieRecorder::power_on(&nes);
1835        rec.enable_attestation();
1836        for _ in 0..6 {
1837            rec.capture(&nes);
1838            let fb = nes.run_frame().to_vec();
1839            rec.attest_frame(&fb);
1840        }
1841        let mut movie = rec.finish();
1842
1843        // Sanity: the honest movie verifies.
1844        let mut fresh = Nes::from_rom(&rom).expect("parse");
1845        assert!(matches!(
1846            movie.verify(&mut fresh).expect("verify runs"),
1847            VerifyOutcome::Match { .. }
1848        ));
1849
1850        // Now edit the input log. The video output will be bit-identical,
1851        // because this ROM never looks at the controller.
1852        movie.frames[3].p1 = Buttons::A;
1853        let mut fresh = Nes::from_rom(&rom).expect("parse");
1854        match movie.verify(&mut fresh).expect("verify runs") {
1855            VerifyOutcome::Mismatch { .. } => {}
1856            other => panic!("an edited input log must not verify, got {other:?}"),
1857        }
1858    }
1859
1860    /// v3.5.0 (attestation version 3): an edited NON-controller input fails
1861    /// verification too, on a ROM that reads nothing at all -- the Zapper aim
1862    /// and the microphone are folded into the hash beside the buttons.
1863    #[test]
1864    fn an_edited_extra_input_fails_verification() {
1865        let rom = synth_nrom();
1866        let mut nes = Nes::from_rom(&rom).expect("parse");
1867        let mut rec = MovieRecorder::power_on(&nes);
1868        rec.enable_attestation();
1869        for i in 0..6u16 {
1870            nes.set_zapper(1, i, 100, false);
1871            rec.capture(&nes);
1872            let fb = nes.run_frame().to_vec();
1873            rec.attest_frame(&fb);
1874        }
1875        let honest = rec.finish();
1876        let mut fresh = Nes::from_rom(&rom).expect("parse");
1877        assert!(matches!(
1878            honest.verify(&mut fresh).expect("verify runs"),
1879            VerifyOutcome::Match { .. }
1880        ));
1881        let edits: [fn(&mut crate::ExtraInput); 2] = [
1882            |e| e.microphone = true,
1883            |e| {
1884                e.devices[1] = crate::DeviceInput::Zapper {
1885                    x: 200,
1886                    y: 100,
1887                    trigger: false,
1888                };
1889            },
1890        ];
1891        for edit in edits {
1892            let mut movie = honest.clone();
1893            edit(movie.frames[3].extra.as_mut().expect("recorded"));
1894            let mut fresh = Nes::from_rom(&rom).expect("parse");
1895            assert!(
1896                matches!(
1897                    movie.verify(&mut fresh).expect("verify runs"),
1898                    VerifyOutcome::Mismatch { .. }
1899                ),
1900                "an edited extra input must not verify"
1901            );
1902        }
1903    }
1904
1905    /// An attestation whose frame count disagrees with the input stream
1906    /// describes a different run, so it is dropped rather than compared against
1907    /// the wrong length.
1908    #[test]
1909    fn attestation_with_a_mismatched_frame_count_is_rejected_on_load() {
1910        let rom = synth_nrom();
1911        let mut nes = Nes::from_rom(&rom).expect("parse");
1912        let mut rec = MovieRecorder::power_on(&nes);
1913        rec.enable_attestation();
1914        for _ in 0..3 {
1915            rec.capture(&nes);
1916            let fb = nes.run_frame().to_vec();
1917            rec.attest_frame(&fb);
1918        }
1919        let mut movie = rec.finish();
1920        movie.attestation.as_mut().unwrap().frame_count = 999;
1921        let bytes = movie.serialize();
1922        let parsed = Movie::deserialize(&bytes).expect("the movie itself is fine");
1923        assert_eq!(parsed.frames.len(), 3);
1924        assert!(
1925            parsed.attestation.is_none(),
1926            "a tail describing a different run must be dropped, not trusted"
1927        );
1928    }
1929
1930    /// Drive `first_bad_checkpoint` to `Some(_)` — the path bug #12 lived on,
1931    /// which no test previously exercised.
1932    #[test]
1933    fn a_corrupted_checkpoint_is_localized() {
1934        let rom = synth_nrom();
1935        let mut nes = Nes::from_rom(&rom).expect("parse");
1936        let mut rec = MovieRecorder::power_on(&nes);
1937        rec.enable_attestation();
1938        // Three checkpoint windows.
1939        for _ in 0..(ATTESTATION_CHECKPOINT_INTERVAL * 3) {
1940            rec.capture(&nes);
1941            let fb = nes.run_frame().to_vec();
1942            rec.attest_frame(&fb);
1943        }
1944        let mut movie = rec.finish();
1945        assert_eq!(movie.attestation.as_ref().unwrap().checkpoints.len(), 3);
1946
1947        // Corrupt the SECOND checkpoint only. The final hash still matches, so
1948        // the checkpoint comparison is the only thing that can catch this.
1949        movie.attestation.as_mut().unwrap().checkpoints[1] ^= 0xFF;
1950        let mut fresh = Nes::from_rom(&rom).expect("parse");
1951        match movie.verify(&mut fresh).expect("verify runs") {
1952            VerifyOutcome::Mismatch {
1953                first_bad_checkpoint,
1954                expected,
1955                got,
1956                ..
1957            } => {
1958                assert_eq!(
1959                    first_bad_checkpoint,
1960                    Some(1),
1961                    "the SECOND checkpoint is the first bad one"
1962                );
1963                assert_eq!(expected, got, "the final hash still agrees");
1964            }
1965            other => panic!("a corrupted checkpoint must not verify, got {other:?}"),
1966        }
1967    }
1968
1969    /// A short checkpoint list must NOT manufacture a mismatch.
1970    ///
1971    /// Regression for bug #12: `checkpoints.get(idx)` returning `None` was
1972    /// compared against `Some(&hash)` and read as disagreement, so an
1973    /// attestation carrying fewer checkpoints than the replay produces failed
1974    /// even when every hash it did record — and the final hash — matched.
1975    #[test]
1976    fn a_short_checkpoint_list_still_verifies() {
1977        let rom = synth_nrom();
1978        let mut nes = Nes::from_rom(&rom).expect("parse");
1979        let mut rec = MovieRecorder::power_on(&nes);
1980        rec.enable_attestation();
1981        for _ in 0..(ATTESTATION_CHECKPOINT_INTERVAL * 2) {
1982            rec.capture(&nes);
1983            let fb = nes.run_frame().to_vec();
1984            rec.attest_frame(&fb);
1985        }
1986        let mut movie = rec.finish();
1987        assert_eq!(movie.attestation.as_ref().unwrap().checkpoints.len(), 2);
1988
1989        // Drop the trailing checkpoint, leaving the final hash intact.
1990        movie.attestation.as_mut().unwrap().checkpoints.pop();
1991        let mut fresh = Nes::from_rom(&rom).expect("parse");
1992        match movie.verify(&mut fresh).expect("verify runs") {
1993            VerifyOutcome::Match { frames, .. } => {
1994                assert_eq!(frames, ATTESTATION_CHECKPOINT_INTERVAL * 2);
1995            }
1996            other => panic!(
1997                "a missing checkpoint is 'nothing recorded here', not a \
1998                 disagreement; got {other:?}"
1999            ),
2000        }
2001    }
2002
2003    /// A rewind mid-recording must drop the attestation rather than ship one
2004    /// that describes a timeline the input log no longer encodes.
2005    #[test]
2006    fn disabling_attestation_mid_recording_yields_an_unattested_movie() {
2007        let rom = synth_nrom();
2008        let mut nes = Nes::from_rom(&rom).expect("parse");
2009        let mut rec = MovieRecorder::power_on(&nes);
2010        rec.enable_attestation();
2011        for _ in 0..4 {
2012            rec.capture(&nes);
2013            let fb = nes.run_frame().to_vec();
2014            rec.attest_frame(&fb);
2015        }
2016        // What the frontend does on a successful `rewind_step_back`.
2017        rec.disable_attestation();
2018        for _ in 0..4 {
2019            rec.capture(&nes);
2020            let fb = nes.run_frame().to_vec();
2021            rec.attest_frame(&fb);
2022        }
2023        let movie = rec.finish();
2024        assert!(
2025            movie.attestation.is_none(),
2026            "a partial hash covering only part of the run is worse than none"
2027        );
2028        assert_eq!(movie.frames.len(), 8, "the recording itself is unaffected");
2029    }
2030
2031    /// A movie with no attestation reports that, rather than passing or failing.
2032    #[test]
2033    fn unattested_movie_reports_not_attested() {
2034        let rom = synth_nrom();
2035        let mut nes = Nes::from_rom(&rom).expect("parse");
2036        let mut rec = MovieRecorder::power_on(&nes);
2037        rec.capture(&nes);
2038        let _ = nes.run_frame();
2039        let movie = rec.finish();
2040        let mut fresh = Nes::from_rom(&rom).expect("parse");
2041        assert_eq!(
2042            movie.verify(&mut fresh).expect("verify runs"),
2043            VerifyOutcome::NotAttested
2044        );
2045    }
2046
2047    /// Minimal NROM ROM that runs an infinite loop (same shape as the
2048    /// `nes.rs` test fixture). Deterministic boot, no input dependence in
2049    /// the program itself — the movie machinery is what we exercise.
2050    fn synth_nrom() -> Vec<u8> {
2051        let mut bytes = Vec::new();
2052        bytes.extend_from_slice(b"NES\x1A");
2053        bytes.push(1); // 16 KiB PRG
2054        bytes.push(1); // 8 KiB CHR
2055        bytes.push(0);
2056        bytes.push(0);
2057        bytes.extend_from_slice(&[0u8; 8]);
2058        let mut prg = vec![0u8; 16 * 1024];
2059        prg[0] = 0x4C; // JMP $C000
2060        prg[1] = 0x00;
2061        prg[2] = 0xC0;
2062        let len = prg.len();
2063        prg[len - 4] = 0x00;
2064        prg[len - 3] = 0xC0;
2065        prg[len - 6] = 0x00;
2066        prg[len - 5] = 0xC0;
2067        prg[len - 2] = 0x00;
2068        prg[len - 1] = 0xC0;
2069        bytes.extend_from_slice(&prg);
2070        bytes.extend_from_slice(&vec![0u8; 8 * 1024]);
2071        bytes
2072    }
2073
2074    fn fnv(bytes: &[u8]) -> u64 {
2075        let mut h: u64 = 0xCBF2_9CE4_8422_2325;
2076        for &b in bytes {
2077            h ^= u64::from(b);
2078            h = h.wrapping_mul(0x0000_0100_0000_01B3);
2079        }
2080        h
2081    }
2082
2083    fn audio_fnv(samples: &[f32]) -> u64 {
2084        let mut h: u64 = 0xCBF2_9CE4_8422_2325;
2085        for s in samples {
2086            for &b in &s.to_le_bytes() {
2087                h ^= u64::from(b);
2088                h = h.wrapping_mul(0x0000_0100_0000_01B3);
2089            }
2090        }
2091        h
2092    }
2093
2094    /// A fixed, varied synthetic input sequence (deterministic, no RNG).
2095    fn synthetic_inputs(n: usize) -> Vec<FrameInput> {
2096        (0..n)
2097            .map(|i| {
2098                let i = u8::try_from(i % 256).unwrap();
2099                let p1 = Buttons::from_bits_truncate(i.wrapping_mul(37));
2100                let p2 = Buttons::from_bits_truncate(i.wrapping_mul(101).rotate_left(3));
2101                FrameInput::new(p1, p2)
2102            })
2103            .collect()
2104    }
2105
2106    /// v2.9.0 (maintainer decision 2026-09-26) — a power-on movie starts from
2107    /// cleared cartridge RAM. `power_cycle` keeps cartridge RAM, as a console
2108    /// keeps a battery save; since v2.7.3 the desktop also loads a `.sav` into
2109    /// it at ROM load, so a power-on movie recorded without a save diverged on
2110    /// a machine that had one. Seeking to a `PowerOn` start must therefore
2111    /// leave cartridge RAM exactly as a fresh load with no save does: zeroed.
2112    /// `synth_nrom` with the header's battery bit set. The battery matters:
2113    /// `power_cycle` keeps battery-backed RAM (v2.9.0) and clears volatile
2114    /// RAM, so only a battery cart can show whether the MOVIE clears it.
2115    fn synth_nrom_battery() -> Vec<u8> {
2116        let mut rom = synth_nrom();
2117        rom[6] |= 0x02;
2118        rom
2119    }
2120
2121    #[test]
2122    fn seeking_a_power_on_movie_clears_cartridge_ram() {
2123        let mut nes = Nes::from_rom(&synth_nrom_battery()).unwrap();
2124        assert!(nes.has_battery());
2125        assert!(!nes.sram().is_empty(), "NROM exposes its PRG-RAM");
2126        nes.sram_mut().fill(0xA5); // a loaded .sav, or a previous session
2127        let movie = Movie {
2128            epoch: crate::EMULATION_EPOCH,
2129            region: nes.region(),
2130            rom_sha256: *nes.rom_sha256(),
2131            options: crate::HardwareOptions::default(),
2132            board: None,
2133            start: StartPoint::PowerOn,
2134            frames: synthetic_inputs(1),
2135            rerecord_count: 0,
2136            attestation: None,
2137        };
2138        movie.seek_to_start(&mut nes).unwrap();
2139        assert!(nes.sram().iter().all(|&b| b == 0), "cartridge RAM cleared");
2140    }
2141
2142    /// The same rule on the RECORDING side: `power_on_for_movie` is what a
2143    /// host calls before `MovieRecorder::power_on`, so what is recorded and
2144    /// what `seek_to_start` reconstructs are the same state.
2145    #[test]
2146    fn power_on_for_movie_matches_a_fresh_load() {
2147        let fresh = Nes::from_rom(&synth_nrom_battery()).unwrap();
2148        let mut nes = Nes::from_rom(&synth_nrom_battery()).unwrap();
2149        nes.sram_mut().fill(0x5A);
2150        nes.power_cycle();
2151        assert_eq!(nes.sram()[0], 0x5A, "a plain power cycle keeps battery RAM");
2152        power_on_for_movie(&mut nes);
2153        assert_eq!(nes.sram(), fresh.sram());
2154    }
2155
2156    #[test]
2157    fn format_round_trip_power_on() {
2158        let inputs = synthetic_inputs(120);
2159        let movie = Movie {
2160            epoch: crate::EMULATION_EPOCH,
2161            region: Region::Ntsc,
2162            rom_sha256: [0xAB; 32],
2163            options: crate::HardwareOptions::default(),
2164            board: None,
2165            start: StartPoint::PowerOn,
2166            frames: inputs,
2167            rerecord_count: 0,
2168            attestation: None,
2169        };
2170        let bytes = movie.serialize();
2171        let back = Movie::deserialize(&bytes).expect("round-trip");
2172        assert_eq!(movie, back);
2173    }
2174
2175    #[test]
2176    fn rerecord_count_round_trips_and_defaults_for_legacy_rnm() {
2177        let movie = Movie {
2178            epoch: crate::EMULATION_EPOCH,
2179            region: Region::Ntsc,
2180            rom_sha256: [0x5A; 32],
2181            options: crate::HardwareOptions::default(),
2182            board: None,
2183            start: StartPoint::PowerOn,
2184            frames: synthetic_inputs(10),
2185            rerecord_count: 4242,
2186            attestation: None,
2187        };
2188        let bytes = movie.serialize();
2189        // A full round-trip preserves the count.
2190        assert_eq!(Movie::deserialize(&bytes).unwrap().rerecord_count, 4242);
2191        // A pre-v1.8.9 `.rnm` ends exactly at the input stream (no trailing
2192        // count). Dropping the appended u32 must still parse, defaulting the
2193        // count to 0 rather than erroring — the back-compat contract.
2194        let legacy = &bytes[..bytes.len() - 4];
2195        let back = Movie::deserialize(legacy).expect("legacy .rnm still parses");
2196        assert_eq!(back.rerecord_count, 0);
2197        assert_eq!(back.frames.len(), 10);
2198    }
2199
2200    #[test]
2201    fn format_round_trip_with_save_state_start() {
2202        let movie = Movie {
2203            epoch: crate::EMULATION_EPOCH,
2204            region: Region::Pal,
2205            rom_sha256: [0x11; 32],
2206            options: crate::HardwareOptions::default(),
2207            board: None,
2208            start: StartPoint::SaveState(vec![1, 2, 3, 4, 5, 6, 7, 8]),
2209            frames: synthetic_inputs(8),
2210            rerecord_count: 0,
2211            attestation: None,
2212        };
2213        let bytes = movie.serialize();
2214        let back = Movie::deserialize(&bytes).expect("round-trip");
2215        assert_eq!(movie, back);
2216    }
2217
2218    #[test]
2219    fn deserialize_rejects_bad_magic_cleanly() {
2220        let mut bytes = vec![0u8; 53];
2221        bytes[..8].copy_from_slice(b"NOTAMOVI");
2222        assert!(matches!(
2223            Movie::deserialize(&bytes),
2224            Err(MovieError::BadMagic { .. })
2225        ));
2226    }
2227
2228    #[test]
2229    fn deserialize_rejects_too_new_format_cleanly() {
2230        let movie = Movie {
2231            epoch: crate::EMULATION_EPOCH,
2232            region: Region::Ntsc,
2233            rom_sha256: [0; 32],
2234            options: crate::HardwareOptions::default(),
2235            board: None,
2236            start: StartPoint::PowerOn,
2237            frames: Vec::new(),
2238            rerecord_count: 0,
2239            attestation: None,
2240        };
2241        let mut bytes = movie.serialize();
2242        // Bump the format-version field (offset 8) past what we support.
2243        bytes[8] = 0xFF;
2244        bytes[9] = 0xFF;
2245        assert!(matches!(
2246            Movie::deserialize(&bytes),
2247            Err(MovieError::UnsupportedFormat { .. })
2248        ));
2249    }
2250
2251    #[test]
2252    fn deserialize_rejects_truncated_header() {
2253        assert!(matches!(
2254            Movie::deserialize(&[0u8; 10]),
2255            Err(MovieError::HeaderTruncated { .. })
2256        ));
2257    }
2258
2259    #[test]
2260    fn deserialize_hostile_frame_count_does_not_oom() {
2261        // frame_count is the 4-byte LE field right after the 32-byte rom hash
2262        // (offset 8 + 2 + 1 + 1 + 32 = 44).
2263        // magic + version + epoch (format 5) + region + flags + sha256.
2264        const FRAME_COUNT_OFF: usize = 8 + 2 + 4 + 1 + 1 + 32;
2265        // A tiny (header-only) movie whose `frame_count` field claims ~4.3
2266        // billion frames. The old `Vec::with_capacity(frame_count)` would try to
2267        // reserve multiple gigabytes before the input-stream read failed (an OOM
2268        // DoS found by the `movie` fuzz target). It must now reject cleanly with
2269        // an EOF: the capacity is capped at the remaining bytes / width.
2270        let movie = Movie {
2271            epoch: crate::EMULATION_EPOCH,
2272            region: Region::Ntsc,
2273            rom_sha256: [0; 32],
2274            options: crate::HardwareOptions::default(),
2275            board: None,
2276            start: StartPoint::PowerOn,
2277            frames: Vec::new(),
2278            rerecord_count: 0,
2279            attestation: None,
2280        };
2281        let mut bytes = movie.serialize();
2282        bytes[FRAME_COUNT_OFF..FRAME_COUNT_OFF + 4].copy_from_slice(&u32::MAX.to_le_bytes());
2283        // Deserialize must return promptly with an error, not exhaust memory.
2284        assert!(matches!(
2285            Movie::deserialize(&bytes),
2286            Err(MovieError::Eof(_))
2287        ));
2288    }
2289
2290    #[test]
2291    fn deserialize_rejects_truncated_input_stream() {
2292        let movie = Movie {
2293            epoch: crate::EMULATION_EPOCH,
2294            region: Region::Ntsc,
2295            rom_sha256: [0; 32],
2296            options: crate::HardwareOptions::default(),
2297            board: None,
2298            start: StartPoint::PowerOn,
2299            frames: synthetic_inputs(10),
2300            rerecord_count: 0,
2301            attestation: None,
2302        };
2303        let bytes = movie.serialize();
2304        // Lop off the last few input bytes — must error, not panic.
2305        let truncated = &bytes[..bytes.len() - 5];
2306        assert!(matches!(
2307            Movie::deserialize(truncated),
2308            Err(MovieError::Eof(_))
2309        ));
2310    }
2311
2312    /// Drive a ROM with a fixed input sequence, recording as we go; then
2313    /// replay from the movie's start point and assert framebuffer + audio +
2314    /// cycle count are byte-identical.
2315    #[test]
2316    fn determinism_round_trip_power_on() {
2317        let rom = synth_nrom();
2318        let inputs = synthetic_inputs(30);
2319
2320        // ----- Original run (recording). -----
2321        let mut nes = Nes::from_rom(&rom).expect("boot");
2322        nes.power_cycle(); // start point a replay will reconstruct
2323        let mut rec = MovieRecorder::power_on(&nes);
2324        let mut orig_fb = 0u64;
2325        let mut orig_audio = Vec::new();
2326        for f in &inputs {
2327            nes.set_buttons(0, f.p1);
2328            nes.set_buttons(1, f.p2);
2329            rec.capture(&nes);
2330            orig_fb = fnv(nes.run_frame());
2331            orig_audio.extend(nes.drain_audio());
2332        }
2333        let orig_cycle = nes.cycle();
2334        let orig_audio_hash = audio_fnv(&orig_audio);
2335        let movie = rec.finish();
2336        assert_eq!(movie.len(), inputs.len());
2337
2338        // ----- Replay from the movie's start point. -----
2339        let mut replay = Nes::from_rom(&rom).expect("boot");
2340        movie.seek_to_start(&mut replay).expect("seek");
2341        let mut player = MoviePlayer::new(&movie);
2342        let mut replay_fb = 0u64;
2343        let mut replay_audio = Vec::new();
2344        while player.apply_next(&mut replay) {
2345            replay_fb = fnv(replay.run_frame());
2346            replay_audio.extend(replay.drain_audio());
2347        }
2348
2349        assert_eq!(orig_fb, replay_fb, "framebuffer must replay bit-identical");
2350        assert_eq!(
2351            orig_audio_hash,
2352            audio_fnv(&replay_audio),
2353            "audio must replay bit-identical"
2354        );
2355        assert_eq!(
2356            orig_cycle,
2357            replay.cycle(),
2358            "cumulative cycle count must replay bit-identical"
2359        );
2360    }
2361
2362    /// Replaying the same movie twice must yield identical output (the movie
2363    /// itself is internally deterministic).
2364    #[test]
2365    fn replay_is_internally_deterministic() {
2366        let rom = synth_nrom();
2367        let movie = Movie {
2368            epoch: crate::EMULATION_EPOCH,
2369            region: Region::Ntsc,
2370            rom_sha256: *Nes::from_rom(&rom).unwrap().rom_sha256(),
2371            options: crate::HardwareOptions::default(),
2372            board: None,
2373            start: StartPoint::PowerOn,
2374            frames: synthetic_inputs(20),
2375            rerecord_count: 0,
2376            attestation: None,
2377        };
2378
2379        let run = |movie: &Movie| -> (u64, u64, u64) {
2380            let mut nes = Nes::from_rom(&rom).unwrap();
2381            movie.seek_to_start(&mut nes).unwrap();
2382            let mut player = MoviePlayer::new(movie);
2383            let mut fb = 0u64;
2384            let mut audio = Vec::new();
2385            while player.apply_next(&mut nes) {
2386                fb = fnv(nes.run_frame());
2387                audio.extend(nes.drain_audio());
2388            }
2389            (fb, audio_fnv(&audio), nes.cycle())
2390        };
2391
2392        assert_eq!(run(&movie), run(&movie));
2393    }
2394
2395    /// Save-state branch: run a base movie partway, snapshot, start a new
2396    /// branch recorder from that snapshot, and assert the branch replay is
2397    /// internally deterministic and reconstructs the branch start point.
2398    #[test]
2399    fn save_state_branch_round_trip() {
2400        let rom = synth_nrom();
2401
2402        // Base run: advance some frames with a fixed input, then branch.
2403        let base_inputs = synthetic_inputs(10);
2404        let mut nes = Nes::from_rom(&rom).unwrap();
2405        nes.power_cycle();
2406        for f in &base_inputs {
2407            nes.set_buttons(0, f.p1);
2408            nes.set_buttons(1, f.p2);
2409            nes.run_frame();
2410        }
2411        let branch_cycle = nes.cycle();
2412        let branch_fb = fnv(nes.framebuffer());
2413
2414        // Start a branch recorder from the current state, record more frames.
2415        let mut branch_rec = MovieRecorder::from_current_state(&nes);
2416        let branch_inputs = synthetic_inputs(15);
2417        for f in &branch_inputs {
2418            nes.set_buttons(0, f.p1);
2419            nes.set_buttons(1, f.p2);
2420            branch_rec.capture(&nes);
2421            nes.run_frame();
2422        }
2423        let branch_end_cycle = nes.cycle();
2424        let branch_end_fb = fnv(nes.framebuffer());
2425        let branch_movie = branch_rec.finish();
2426        assert!(matches!(branch_movie.start, StartPoint::SaveState(_)));
2427
2428        // Replay the branch from its embedded snapshot.
2429        let run_branch = || -> (u64, u64) {
2430            let mut replay = Nes::from_rom(&rom).unwrap();
2431            branch_movie.seek_to_start(&mut replay).unwrap();
2432            // After seeking, we are back at the branch start point.
2433            assert_eq!(replay.cycle(), branch_cycle, "branch start cycle");
2434            assert_eq!(fnv(replay.framebuffer()), branch_fb, "branch start fb");
2435            let mut player = MoviePlayer::new(&branch_movie);
2436            let mut fb = 0u64;
2437            while player.apply_next(&mut replay) {
2438                fb = fnv(replay.run_frame());
2439            }
2440            (fb, replay.cycle())
2441        };
2442
2443        let first = run_branch();
2444        let second = run_branch();
2445        assert_eq!(first, second, "branch replay internally deterministic");
2446        // And it reconstructs the live branch end state bit-identically.
2447        assert_eq!(first.0, branch_end_fb, "branch end fb matches live run");
2448        assert_eq!(
2449            first.1, branch_end_cycle,
2450            "branch end cycle matches live run"
2451        );
2452
2453        // Format round-trip survives the embedded save state.
2454        let bytes = branch_movie.serialize();
2455        let back = Movie::deserialize(&bytes).unwrap();
2456        assert_eq!(branch_movie, back);
2457    }
2458
2459    #[test]
2460    fn seek_rejects_rom_mismatch() {
2461        let rom = synth_nrom();
2462        let movie = Movie {
2463            epoch: crate::EMULATION_EPOCH,
2464            region: Region::Ntsc,
2465            rom_sha256: [0xFF; 32], // deliberately wrong
2466            options: crate::HardwareOptions::default(),
2467            board: None,
2468            start: StartPoint::PowerOn,
2469            frames: Vec::new(),
2470            rerecord_count: 0,
2471            attestation: None,
2472        };
2473        let mut nes = Nes::from_rom(&rom).unwrap();
2474        assert!(matches!(
2475            movie.seek_to_start(&mut nes),
2476            Err(MovieError::RomMismatch)
2477        ));
2478    }
2479
2480    #[test]
2481    fn frame_input_bit_layout_matches_buttons() {
2482        // The on-wire byte for a frame is exactly Buttons::bits() (FCEUX
2483        // .fm2 layout). Verify the serialize path preserves it.
2484        let movie = Movie {
2485            epoch: crate::EMULATION_EPOCH,
2486            region: Region::Ntsc,
2487            rom_sha256: [0; 32],
2488            options: crate::HardwareOptions::default(),
2489            board: None,
2490            start: StartPoint::PowerOn,
2491            frames: vec![FrameInput::four_players(
2492                Buttons::A | Buttons::RIGHT,
2493                Buttons::B | Buttons::START,
2494                Buttons::UP,
2495                Buttons::SELECT,
2496            )],
2497            rerecord_count: 0,
2498            attestation: None,
2499        };
2500        let bytes = movie.serialize();
2501        // Input stream begins after the 53-byte fixed header and the
2502        // length-prefixed OPTIONS block (no board, no save state).
2503        let at = 53 + 4 + crate::HardwareOptions::default().to_bytes().len();
2504        assert_eq!(bytes[at], (Buttons::A | Buttons::RIGHT).bits());
2505        assert_eq!(bytes[at + 1], (Buttons::B | Buttons::START).bits());
2506        assert_eq!(bytes[at + 2], Buttons::UP.bits(), "player 3");
2507        assert_eq!(bytes[at + 3], Buttons::SELECT.bits(), "player 4");
2508        assert_eq!(bytes[at + 4], 0, "expansion byte reserved/zero");
2509        assert_eq!(bytes[52], BYTES_PER_FRAME, "the header states the width");
2510    }
2511
2512    /// A narrower record still reads: the fields it does not reach default.
2513    /// (Format 3 writes 5 bytes; the width field is what lets a later build
2514    /// grow the record additively.)
2515    #[test]
2516    fn a_two_byte_record_defaults_players_three_and_four() {
2517        let movie = Movie {
2518            epoch: crate::EMULATION_EPOCH,
2519            region: Region::Ntsc,
2520            rom_sha256: [0; 32],
2521            options: crate::HardwareOptions::default(),
2522            board: None,
2523            start: StartPoint::PowerOn,
2524            frames: vec![FrameInput::four_players(
2525                Buttons::A,
2526                Buttons::B,
2527                Buttons::UP,
2528                Buttons::DOWN,
2529            )],
2530            rerecord_count: 0,
2531            attestation: None,
2532        };
2533        let mut bytes = movie.serialize();
2534        let at = 53 + 4 + crate::HardwareOptions::default().to_bytes().len();
2535        bytes[52] = 2; // bytes_per_frame, the fixed header's last byte
2536        bytes.drain(at + 2..at + 5);
2537        let back = Movie::deserialize(&bytes).expect("narrow record");
2538        assert_eq!(back.frames, [FrameInput::new(Buttons::A, Buttons::B)]);
2539    }
2540
2541    /// v3.0.0 (ADR 0045): a movie records the emulation epoch beside its
2542    /// format version, and a movie from another epoch is refused before
2543    /// anything else is parsed, naming both epochs. Without the check, a
2544    /// movie recorded by a core that emulates differently (v2.9.9's MMC3
2545    /// timing, say) would replay its inputs on the new timing and diverge
2546    /// with no explanation.
2547    #[test]
2548    fn a_movie_from_another_emulation_epoch_is_refused() {
2549        let movie = Movie::new(
2550            Region::Ntsc,
2551            [7; 32],
2552            crate::HardwareOptions::default(),
2553            None,
2554            StartPoint::PowerOn,
2555            vec![FrameInput::new(Buttons::A, Buttons::B)],
2556        );
2557        assert_eq!(movie.epoch, crate::EMULATION_EPOCH);
2558        let bytes = movie.serialize();
2559        // The epoch sits straight after the format version (bytes 10..14).
2560        assert_eq!(&bytes[8..10], &MOVIE_FORMAT_VERSION.to_le_bytes());
2561        assert_eq!(&bytes[10..14], &crate::EMULATION_EPOCH.to_le_bytes());
2562        assert_eq!(
2563            Movie::deserialize(&bytes).expect("same epoch").epoch,
2564            crate::EMULATION_EPOCH
2565        );
2566
2567        let mut other = bytes;
2568        other[10..14].copy_from_slice(&(crate::EMULATION_EPOCH + 1).to_le_bytes());
2569        assert!(matches!(
2570            Movie::deserialize(&other),
2571            Err(MovieError::EpochMismatch { movie, core })
2572                if movie == crate::EMULATION_EPOCH + 1 && core == crate::EMULATION_EPOCH
2573        ));
2574    }
2575
2576    /// v3.0.0: the epoch is enforced on PLAYBACK too, not only when parsing.
2577    /// `Movie::epoch` is a public field and a `Movie` can be built in memory,
2578    /// so a deserialize-only check left `seek_to_start` and `verify` open to
2579    /// a movie from another epoch (a review finding on #588). Both refuse it, with
2580    /// the machine untouched, and `verify` refuses it before reporting that
2581    /// the movie is unattested.
2582    #[test]
2583    fn playback_refuses_a_movie_from_another_epoch() {
2584        let mut nes = Nes::from_rom(&synth_nrom_battery()).unwrap();
2585        let mut movie = Movie::new(
2586            nes.region(),
2587            *nes.rom_sha256(),
2588            crate::HardwareOptions::default(),
2589            None,
2590            StartPoint::PowerOn,
2591            synthetic_inputs(1),
2592        );
2593        movie.epoch = crate::EMULATION_EPOCH + 1;
2594        nes.sram_mut().fill(0xA5);
2595        let refused = |r: &Result<(), MovieError>| {
2596            matches!(r, Err(MovieError::EpochMismatch { movie, core })
2597                if *movie == crate::EMULATION_EPOCH + 1 && *core == crate::EMULATION_EPOCH)
2598        };
2599        assert!(
2600            refused(&movie.seek_to_start(&mut nes)),
2601            "seek_to_start refuses"
2602        );
2603        assert!(
2604            nes.sram().iter().all(|&b| b == 0xA5),
2605            "the machine is untouched"
2606        );
2607        assert!(
2608            refused(&movie.verify(&mut nes).map(|_| ())),
2609            "verify refuses before NotAttested"
2610        );
2611    }
2612
2613    /// v3.0.0: a format-4 movie (v2.9.9) does not record the epoch, so it is
2614    /// refused as too old rather than replayed under a timing it may not
2615    /// have been recorded on.
2616    #[test]
2617    fn a_format_4_movie_is_refused_as_too_old() {
2618        let mut bytes = Movie::new(
2619            Region::Ntsc,
2620            [0; 32],
2621            crate::HardwareOptions::default(),
2622            None,
2623            StartPoint::PowerOn,
2624            vec![],
2625        )
2626        .serialize();
2627        bytes[8..10].copy_from_slice(&4u16.to_le_bytes());
2628        assert!(matches!(
2629            Movie::deserialize(&bytes),
2630            Err(MovieError::FormatTooOld {
2631                got: 4,
2632                min: MIN_MOVIE_FORMAT_VERSION
2633            })
2634        ));
2635    }
2636
2637    /// v3.1.0: a format-5 movie (v3.0.x) carries the options record without
2638    /// the CPU overclock and the sprite-limit option, so it is refused as too
2639    /// old rather than decoded one field short.
2640    #[test]
2641    fn a_format_5_movie_is_refused_as_too_old() {
2642        let mut bytes = Movie::new(
2643            Region::Ntsc,
2644            [0; 32],
2645            crate::HardwareOptions::default(),
2646            None,
2647            StartPoint::PowerOn,
2648            vec![],
2649        )
2650        .serialize();
2651        bytes[8..10].copy_from_slice(&5u16.to_le_bytes());
2652        assert!(matches!(
2653            Movie::deserialize(&bytes),
2654            Err(MovieError::FormatTooOld {
2655                got: 5,
2656                min: MIN_MOVIE_FORMAT_VERSION
2657            })
2658        ));
2659    }
2660
2661    /// v3.5.0 (`T-MOVIE-INPUT-STREAM`): a format-6 movie (v3.1.0 to v3.4.x)
2662    /// records the controllers only, so a Zapper, Vs. or FDS run in one
2663    /// would replay without its trigger, coins or disk swaps; and v3.6.2
2664    /// (`T-RADRACER-COHERENT-COPY`): a format-7 movie (v3.5.0 to v3.6.1) has
2665    /// no coherent mid-line copy byte in its options record. Both are
2666    /// refused as too old, with the reason the message gives, rather than
2667    /// replayed.
2668    #[test]
2669    fn a_format_6_or_7_movie_is_refused_as_too_old_with_its_reason() {
2670        assert_eq!(MIN_MOVIE_FORMAT_VERSION, 8);
2671        for old in [6u16, 7] {
2672            let mut bytes = Movie::new(
2673                Region::Ntsc,
2674                [0; 32],
2675                crate::HardwareOptions::default(),
2676                None,
2677                StartPoint::PowerOn,
2678                vec![FrameInput::default(); 3],
2679            )
2680            .serialize();
2681            bytes[8..10].copy_from_slice(&old.to_le_bytes());
2682            let err = Movie::deserialize(&bytes).expect_err("an old format is refused");
2683            assert!(
2684                matches!(err, MovieError::FormatTooOld { got, min: 8 } if got == old),
2685                "{err:?}"
2686            );
2687            let text = alloc::string::ToString::to_string(&err);
2688            assert!(
2689                text.contains(&alloc::format!("format version {old}"))
2690                    && text.contains("does not record everything a faithful replay needs")
2691                    && text.contains("re-record it"),
2692                "the refusal says why and what to do: {text}"
2693            );
2694        }
2695    }
2696
2697    #[test]
2698    fn recorded_before_v2_timebase_flags_pre_promote_movies() {
2699        // ADR 0028: a freshly-serialized movie carries the current
2700        // MOVIE_FORMAT_VERSION (>= 2) and must NOT be flagged.
2701        let movie = Movie {
2702            epoch: crate::EMULATION_EPOCH,
2703            region: Region::Ntsc,
2704            rom_sha256: [0; 32],
2705            options: crate::HardwareOptions::default(),
2706            board: None,
2707            start: StartPoint::PowerOn,
2708            frames: vec![],
2709            rerecord_count: 0,
2710            attestation: None,
2711        };
2712        let bytes = movie.serialize();
2713        assert!(matches!(recorded_before_v2_timebase(&bytes), Ok(false)));
2714
2715        // A v1-tagged blob (format_version = 1, the only value that existed
2716        // pre-v2.0.0) must be flagged. Since v2.9.8 it no longer parses: it
2717        // predates the options record (MIN_MOVIE_FORMAT_VERSION).
2718        let mut v1_bytes = bytes;
2719        v1_bytes[8..10].copy_from_slice(&1u16.to_le_bytes());
2720        assert!(matches!(recorded_before_v2_timebase(&v1_bytes), Ok(true)));
2721        assert!(matches!(
2722            Movie::deserialize(&v1_bytes),
2723            Err(MovieError::FormatTooOld {
2724                got: 1,
2725                min: MIN_MOVIE_FORMAT_VERSION
2726            })
2727        ));
2728
2729        // Malformed input still surfaces the normal header errors.
2730        assert!(matches!(
2731            recorded_before_v2_timebase(&[0u8; 4]),
2732            Err(MovieError::HeaderTruncated { .. })
2733        ));
2734        assert!(matches!(
2735            recorded_before_v2_timebase(&[0xFFu8; 10]),
2736            Err(MovieError::BadMagic { .. })
2737        ));
2738    }
2739
2740    // ----------------------------------------------------------------- v2.9.8
2741    // Emulation options travel with the movie (maintainer decision 2026-10-01)
2742    // -------------------------------------------------------------------------
2743
2744    /// Record `frames` frames on `nes` (already configured by the caller) from
2745    /// a power-on start, returning the movie and the machine's full snapshot at
2746    /// the end. The snapshot is the strongest available "replays identically"
2747    /// oracle: it covers work RAM, the PPU's warm-up counter and every other
2748    /// piece of serialized state, so a difference a test ROM never draws on
2749    /// screen still shows up.
2750    ///
2751    /// Returned as an FNV hash so a failing comparison prints two numbers
2752    /// rather than two multi-kilobyte byte arrays.
2753    fn record_power_on(nes: &mut Nes, frames: usize) -> (Movie, u64) {
2754        power_on_for_movie(nes);
2755        let mut rec = MovieRecorder::power_on(nes);
2756        for f in synthetic_inputs(frames) {
2757            nes.set_buttons(0, f.p1);
2758            nes.set_buttons(1, f.p2);
2759            rec.capture(nes);
2760            nes.run_frame();
2761        }
2762        (rec.finish(), fnv(&nes.snapshot()))
2763    }
2764
2765    /// Replay `movie` on `nes` from its start point and return the snapshot's
2766    /// hash.
2767    fn replay(movie: &Movie, nes: &mut Nes) -> u64 {
2768        movie.seek_to_start(nes).expect("seek");
2769        let mut player = MoviePlayer::new(movie);
2770        while player.apply_next(nes) {
2771            nes.run_frame();
2772        }
2773        fnv(&nes.snapshot())
2774    }
2775
2776    /// `synth_nrom` whose reset handler writes `$1E` to PPUMASK before it
2777    /// loops. On the NES model that write lands inside the PPU's warm-up and
2778    /// is ignored; on the Famicom model the warm-up is already over and it
2779    /// takes effect -- so the two console models leave different PPU state.
2780    fn synth_nrom_ppumask() -> Vec<u8> {
2781        let mut rom = synth_nrom();
2782        // LDA #$1E ; STA $2001 ; JMP $C005
2783        let prog = [0xA9, 0x1E, 0x8D, 0x01, 0x20, 0x4C, 0x05, 0xC0];
2784        rom[16..16 + prog.len()].copy_from_slice(&prog);
2785        rom
2786    }
2787
2788    /// A movie recorded on the Famicom console model replays identically on a
2789    /// player whose own setting is the NES model, through a `.rnm` round trip.
2790    #[test]
2791    fn a_famicom_movie_replays_identically_on_an_nes_configured_player() {
2792        let rom = synth_nrom_ppumask();
2793        let mut rec_nes = Nes::from_rom(&rom).unwrap();
2794        rec_nes.set_console_model(crate::ConsoleModel::Famicom);
2795        let (movie, recorded) = record_power_on(&mut rec_nes, 12);
2796        let movie = Movie::deserialize(&movie.serialize()).expect("round trip");
2797
2798        let mut player = Nes::from_rom(&rom).unwrap();
2799        assert_eq!(player.console_model(), crate::ConsoleModel::Nes);
2800        assert_eq!(replay(&movie, &mut player), recorded);
2801    }
2802
2803    /// A movie recorded with a seeded power-on RAM fill replays identically on
2804    /// a player configured with a different fill, through a `.rnm` round trip.
2805    #[test]
2806    fn a_seeded_power_on_ram_movie_replays_identically_on_a_differently_configured_player() {
2807        let rom = synth_nrom();
2808        let mut rec_nes = Nes::from_rom(&rom).unwrap();
2809        rec_nes.set_power_on_ram(crate::PowerOnRam::Seeded(0x5EED_1234));
2810        let (movie, recorded) = record_power_on(&mut rec_nes, 12);
2811        let movie = Movie::deserialize(&movie.serialize()).expect("round trip");
2812
2813        let mut player = Nes::from_rom(&rom).unwrap();
2814        player.set_power_on_ram(crate::PowerOnRam::Filled(0xFF));
2815        assert_eq!(replay(&movie, &mut player), recorded);
2816    }
2817
2818    /// Every other option travels too: OAM decay, both die revisions, the
2819    /// power-up palette, the overclock, the Four Score, the Zapper light model
2820    /// and a Game Genie code, recorded on one machine and replayed on a player
2821    /// whose settings are all at their defaults.
2822    #[test]
2823    fn every_recorded_option_replays_on_a_default_player() {
2824        let rom = synth_nrom();
2825        let mut rec_nes = Nes::from_rom(&rom).unwrap();
2826        rec_nes.set_oam_decay(true);
2827        rec_nes.set_ppu_revision(crate::PpuRevision::Rp2c02G);
2828        rec_nes.set_cpu_2a03_revision(crate::Cpu2A03Revision::Rp2A03H);
2829        rec_nes.set_power_up_palette(crate::PaletteInit::Blargg);
2830        rec_nes.set_extra_scanlines(20);
2831        rec_nes.set_four_score(true);
2832        rec_nes.set_zapper_temporal_light(false);
2833        rec_nes.add_genie_code("SXIOPO").unwrap();
2834        let (movie, recorded) = record_power_on(&mut rec_nes, 12);
2835        let movie = Movie::deserialize(&movie.serialize()).expect("round trip");
2836
2837        let mut player = Nes::from_rom(&rom).unwrap();
2838        assert_eq!(replay(&movie, &mut player), recorded);
2839        assert!(player.oam_decay_enabled());
2840        assert_eq!(player.extra_scanlines(), 20);
2841        assert_eq!(player.genie_codes().count(), 1);
2842    }
2843
2844    /// A movie written before the options were recorded is refused with a
2845    /// clear error rather than replayed under whatever the player has set.
2846    #[test]
2847    fn a_movie_older_than_the_options_epoch_is_rejected() {
2848        let movie = Movie {
2849            epoch: crate::EMULATION_EPOCH,
2850            region: Region::Ntsc,
2851            rom_sha256: [0; 32],
2852            options: crate::HardwareOptions::default(),
2853            board: None,
2854            start: StartPoint::PowerOn,
2855            frames: synthetic_inputs(2),
2856            rerecord_count: 0,
2857            attestation: None,
2858        };
2859        let mut bytes = movie.serialize();
2860        bytes[8..10].copy_from_slice(&2u16.to_le_bytes());
2861        let err = Movie::deserialize(&bytes).expect_err("a v2 movie must be refused");
2862        let text = alloc::format!("{err}");
2863        assert!(
2864            text.contains("re-record"),
2865            "the error says what to do: {text}"
2866        );
2867    }
2868
2869    /// v2.9.8 — a movie whose embedded start state predates the `.rns`
2870    /// epoch 3 is refused with the same "re-record" advice as an old movie.
2871    #[test]
2872    fn a_movie_with_an_old_start_state_says_to_re_record() {
2873        let rom = synth_nrom();
2874        let nes = Nes::from_rom(&rom).unwrap();
2875        let mut movie = MovieRecorder::from_current_state(&nes).finish();
2876        if let StartPoint::SaveState(blob) = &mut movie.start {
2877            // The container version follows the 8-byte "RUSTYNES" magic.
2878            blob[8..10].copy_from_slice(&2u16.to_le_bytes());
2879        }
2880        let movie = Movie::deserialize(&movie.serialize()).expect("the movie itself parses");
2881        let mut player = Nes::from_rom(&rom).unwrap();
2882        let err = movie
2883            .seek_to_start(&mut player)
2884            .expect_err("old start state");
2885        assert!(
2886            matches!(err, MovieError::StartStateTooOld { got: 2, .. }),
2887            "got {err:?}"
2888        );
2889        assert!(alloc::format!("{err}").contains("re-record"));
2890    }
2891
2892    /// v2.9.8 (`CodeRabbit` on the review slice #580) — a refused start leaves
2893    /// the player's machine as it was. `seek_to_start` applies the movie's
2894    /// options before it reaches the start point, and `apply` refills work RAM
2895    /// and palette RAM; without a rollback, a movie refused for an old start
2896    /// state or an undecodable Game Genie code still left the running game
2897    /// with the movie's RAM fill and configuration.
2898    #[test]
2899    fn a_refused_start_leaves_the_player_untouched() {
2900        let rom = synth_nrom();
2901        let nes = Nes::from_rom(&rom).unwrap();
2902        let recorded = MovieRecorder::from_current_state(&nes).finish();
2903
2904        let mut old_start = recorded.clone();
2905        if let StartPoint::SaveState(blob) = &mut old_start.start {
2906            blob[8..10].copy_from_slice(&2u16.to_le_bytes());
2907        }
2908        let mut bad_code = recorded;
2909        bad_code.options.genie_codes.push("QQQQQQ".into());
2910
2911        for (what, movie) in [("old start state", old_start), ("bad code", bad_code)] {
2912            // A player configured differently from the movie, mid-game.
2913            let mut player = Nes::from_rom(&rom).unwrap();
2914            player.set_four_score(true);
2915            player.set_power_on_ram(PowerOnRam::Filled(0xA5));
2916            player.run_frame();
2917            let before_state = player.snapshot();
2918            let before_options = HardwareOptions::capture(&player);
2919
2920            movie.seek_to_start(&mut player).expect_err(what);
2921            assert_eq!(
2922                HardwareOptions::capture(&player),
2923                before_options,
2924                "{what}: the player's options changed"
2925            );
2926            assert!(
2927                player.snapshot() == before_state,
2928                "{what}: the player's machine state changed"
2929            );
2930        }
2931    }
2932}