Skip to main content

rustynes_core/
movie_extra.rs

1//! v3.5.0 (`T-MOVIE-INPUT-STREAM`, backlog CR-03) — the non-controller half
2//! of a movie frame: expansion devices, the Famicom microphone, the Vs.
3//! System coin and service inputs, the FDS disk, and Datach barcode scans.
4//!
5//! # Why this exists
6//!
7//! Until v3.5.0 a `.rnm` movie recorded the four controller ports and nothing
8//! else (ADR 0044 listed the rest as "Neutral"), so a run of a Zapper, Vs. or
9//! FDS title replayed with the trigger never pulled, no coin ever inserted and
10//! the disk never swapped: it diverged on the first frame that input mattered.
11//! [`ExtraInput`] is every other input [`Nes`] accepts from a host, read off
12//! the machine by [`ExtraInput::capture`] and driven back by
13//! [`ExtraInput::apply`]. The set was enumerated from `Nes`'s own setters,
14//! not from a list of devices:
15//!
16//! | `Nes` setter | recorded as |
17//! | --- | --- |
18//! | `set_expansion_device`, `set_zapper`, `set_paddle`, `set_power_pad`, `set_family_trainer`, `set_snes_mouse`, `set_family_keyboard`, `set_subor_keyboard`, `set_konami_hyper_shot`, `set_bandai_hyper_shot` | [`ExtraInput::devices`] (per port, [`DeviceInput`]) |
19//! | `set_microphone` | [`ExtraInput::microphone`] |
20//! | `insert_coin`, `clear_coin` | [`ExtraInput::vs_coin`] |
21//! | `set_vs_service` | [`ExtraInput::vs_service`] |
22//! | `set_disk_side` | [`ExtraInput::disk_side`] |
23//! | `scan_barcode` | [`ExtraInput::barcode`] |
24//!
25//! Not inputs, and so not here: the Vs. DIP switches, the Four Score and the
26//! Vs. PPU type are configuration, recorded once in the movie's
27//! [`crate::HardwareOptions`]; `set_disk_write_protected` is a property of
28//! the medium the host persists, never set during play by any frontend; and
29//! the Zapper's photodiode is computed from the picture, not supplied.
30//! Reset and Power Cycle are still not recorded (a movie session refuses
31//! them, `docs/frontend.md`).
32//!
33//! # Levels, not events, in memory
34//!
35//! Every field is the level the machine held when the frame started, which
36//! is what a recorder can read back without the host's cooperation and what
37//! a TAS editor can show and edit per frame. The one true event, a barcode
38//! swipe, is carried as "a scan was made before this frame" and is never
39//! repeated.
40//!
41//! On disk the levels are stored as the changes between frames (the INPUT
42//! EVENTS block, [`encode_events`]), so a movie whose devices sit still costs
43//! a few bytes, not a few dozen per frame.
44//!
45//! # `None` means "this frame does not drive these inputs"
46//!
47//! [`crate::FrameInput::extra`] is an `Option`. A recorded frame always
48//! carries `Some`; a frame built by an importer (`.fm2`, `.bk2`, the legacy
49//! containers), a TAS editor's inserted blank frame, or an input macro
50//! carries `None`, and playback leaves the machine's non-controller inputs as
51//! they are. That keeps every pre-v3.5.0 producer meaning what it meant
52//! (controllers only), and stops a blank frame from ejecting the FDS disk or
53//! unplugging the Zapper: the neutral value of [`ExtraInput`] says "no device,
54//! disk ejected", which is a real input, not an absence of one.
55
56use alloc::vec::Vec;
57
58use crate::input_device::InputDevice;
59use crate::nes::Nes;
60use crate::save_state::{BinReader, BinWriter};
61use rustynes_mappers::Barcode;
62
63/// What one controller port's expansion device is doing in a movie frame.
64///
65/// One variant per [`InputDevice`] kind, holding exactly the fields a host
66/// sets through that device's `Nes` setter -- never the device's internal
67/// shift registers or strobe latch, which the emulation derives. A replay
68/// that sets these fields at the same point the host did reproduces the
69/// device's reads.
70///
71/// `#[non_exhaustive]`: a device added later is an additive change.
72#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
73#[non_exhaustive]
74pub enum DeviceInput {
75    /// No expansion device: the port reads its standard controller (or the
76    /// Four Score).
77    #[default]
78    None,
79    /// NES Zapper: aim point and trigger ([`Nes::set_zapper`]). The light
80    /// sense is computed from the picture, not recorded.
81    Zapper {
82        /// Aim X, 0..256 (out of range = aimed off-screen).
83        x: u16,
84        /// Aim Y, 0..240 (out of range = aimed off-screen).
85        y: u16,
86        /// Trigger pulled.
87        trigger: bool,
88    },
89    /// Arkanoid "Vaus" paddle ([`Nes::set_paddle`]).
90    Vaus {
91        /// Raw potentiometer position.
92        position: u8,
93        /// Fire button held.
94        fire: bool,
95    },
96    /// NES Power Pad mat: the 12-button mask ([`Nes::set_power_pad`]).
97    PowerPad(u16),
98    /// Bandai Family Trainer mat: the 12-button mask
99    /// ([`Nes::set_family_trainer`]).
100    FamilyTrainer(u16),
101    /// SNES-style mouse ([`Nes::set_snes_mouse`]).
102    SnesMouse {
103        /// Delta X as the host set it (clamped by the device on latch).
104        dx: i16,
105        /// Delta Y as the host set it.
106        dy: i16,
107        /// Left button held.
108        left: bool,
109        /// Right button held.
110        right: bool,
111        /// Reported sensitivity, 0..=3 (the device keeps two bits).
112        sensitivity: u8,
113    },
114    /// Family BASIC keyboard: one byte per matrix row
115    /// ([`Nes::set_family_keyboard`]).
116    FamilyKeyboard([u8; 9]),
117    /// Subor keyboard: one byte per matrix row ([`Nes::set_subor_keyboard`]).
118    SuborKeyboard([u8; 9]),
119    /// Konami Hyper Shot: the 4-button mask ([`Nes::set_konami_hyper_shot`]).
120    KonamiHyperShot(u8),
121    /// Bandai Hyper Shot: the 8-sensor mask ([`Nes::set_bandai_hyper_shot`]).
122    BandaiHyperShot(u8),
123}
124
125/// The largest [`DeviceInput`] payload, in bytes (a keyboard's 9 rows).
126const DEVICE_PAYLOAD_MAX: usize = 9;
127
128impl DeviceInput {
129    /// Read the host-set fields of the device attached to a port.
130    #[must_use]
131    pub const fn capture(device: &Option<InputDevice>) -> Self {
132        match device {
133            None => Self::None,
134            Some(InputDevice::Zapper(z)) => Self::Zapper {
135                x: z.x,
136                y: z.y,
137                trigger: z.trigger,
138            },
139            Some(InputDevice::Vaus(v)) => Self::Vaus {
140                position: v.position,
141                fire: v.fire,
142            },
143            Some(InputDevice::PowerPad(p)) => Self::PowerPad(p.buttons),
144            Some(InputDevice::FamilyTrainer(p)) => Self::FamilyTrainer(p.buttons),
145            Some(InputDevice::SnesMouse(m)) => Self::SnesMouse {
146                dx: m.dx,
147                dy: m.dy,
148                left: m.left,
149                right: m.right,
150                sensitivity: m.sensitivity,
151            },
152            Some(InputDevice::FamilyKeyboard(k)) => Self::FamilyKeyboard(k.keys),
153            Some(InputDevice::SuborKeyboard(k)) => Self::SuborKeyboard(k.keys),
154            Some(InputDevice::KonamiHyperShot(h)) => Self::KonamiHyperShot(h.buttons),
155            Some(InputDevice::BandaiHyperShot(b)) => Self::BandaiHyperShot(b.sensors),
156        }
157    }
158
159    /// Drive `port` of `nes` to this device input.
160    ///
161    /// A different device kind is attached fresh (exactly what the `Nes`
162    /// convenience setters do when the kind is absent); the same kind keeps
163    /// its internal state and only has its host-set fields written, as the
164    /// host's own per-frame call did. [`Self::None`] unplugs a device.
165    ///
166    /// # Panics
167    ///
168    /// Panics if `port` is not 0 or 1.
169    pub fn apply(self, nes: &mut Nes, port: usize) {
170        match self {
171            Self::None => {
172                if nes.expansion_device(port).is_some() {
173                    nes.set_expansion_device(port, None);
174                }
175            }
176            Self::Zapper { x, y, trigger } => nes.set_zapper(port, x, y, trigger),
177            Self::Vaus { position, fire } => nes.set_paddle(port, position, fire),
178            Self::PowerPad(b) => nes.set_power_pad(port, b),
179            Self::FamilyTrainer(b) => nes.set_family_trainer(port, b),
180            Self::SnesMouse {
181                dx,
182                dy,
183                left,
184                right,
185                sensitivity,
186            } => nes.set_snes_mouse(port, dx, dy, left, right, sensitivity),
187            Self::FamilyKeyboard(k) => nes.set_family_keyboard(port, k),
188            Self::SuborKeyboard(k) => nes.set_subor_keyboard(port, k),
189            Self::KonamiHyperShot(b) => nes.set_konami_hyper_shot(port, b),
190            Self::BandaiHyperShot(b) => nes.set_bandai_hyper_shot(port, b),
191        }
192    }
193
194    /// The on-disk device tag.
195    const fn tag(self) -> u8 {
196        match self {
197            Self::None => 0,
198            Self::Zapper { .. } => 1,
199            Self::Vaus { .. } => 2,
200            Self::PowerPad(_) => 3,
201            Self::FamilyTrainer(_) => 4,
202            Self::SnesMouse { .. } => 5,
203            Self::FamilyKeyboard(_) => 6,
204            Self::SuborKeyboard(_) => 7,
205            Self::KonamiHyperShot(_) => 8,
206            Self::BandaiHyperShot(_) => 9,
207        }
208    }
209
210    /// Encode the payload into `out`, returning its length.
211    fn payload(self, out: &mut [u8; DEVICE_PAYLOAD_MAX]) -> usize {
212        match self {
213            Self::None => 0,
214            Self::Zapper { x, y, trigger } => {
215                out[..2].copy_from_slice(&x.to_le_bytes());
216                out[2..4].copy_from_slice(&y.to_le_bytes());
217                out[4] = u8::from(trigger);
218                5
219            }
220            Self::Vaus { position, fire } => {
221                out[0] = position;
222                out[1] = u8::from(fire);
223                2
224            }
225            // Masked as the device's setter masks them, so a value built by
226            // hand encodes to one the decoder accepts (and replays the same:
227            // the setter would have dropped those bits anyway).
228            Self::PowerPad(b) | Self::FamilyTrainer(b) => {
229                out[..2].copy_from_slice(&(b & 0x0FFF).to_le_bytes());
230                2
231            }
232            Self::SnesMouse {
233                dx,
234                dy,
235                left,
236                right,
237                sensitivity,
238            } => {
239                out[..2].copy_from_slice(&dx.to_le_bytes());
240                out[2..4].copy_from_slice(&dy.to_le_bytes());
241                out[4] = u8::from(left) | (u8::from(right) << 1);
242                out[5] = sensitivity & 0b11;
243                6
244            }
245            Self::FamilyKeyboard(k) | Self::SuborKeyboard(k) => {
246                out.copy_from_slice(&k);
247                9
248            }
249            Self::KonamiHyperShot(b) => {
250                out[0] = b & 0x0F;
251                1
252            }
253            Self::BandaiHyperShot(b) => {
254                out[0] = b;
255                1
256            }
257        }
258    }
259
260    fn write(self, w: &mut BinWriter) {
261        let mut buf = [0u8; DEVICE_PAYLOAD_MAX];
262        let n = self.payload(&mut buf);
263        w.u8(self.tag());
264        w.bytes(&buf[..n]);
265    }
266
267    /// Decode a tag and its payload. Only the values a device can actually
268    /// hold are accepted (the masks its setter applies), so a decoded
269    /// movie re-encodes to the same bytes.
270    fn read(r: &mut BinReader<'_>) -> Result<Self, &'static str> {
271        let tag = r.u8().map_err(|_| EOF)?;
272        let dev = match tag {
273            0 => Self::None,
274            1 => Self::Zapper {
275                x: r.u16().map_err(|_| EOF)?,
276                y: r.u16().map_err(|_| EOF)?,
277                trigger: read_flag(r)?,
278            },
279            2 => Self::Vaus {
280                position: r.u8().map_err(|_| EOF)?,
281                fire: read_flag(r)?,
282            },
283            3 | 4 => {
284                let b = r.u16().map_err(|_| EOF)?;
285                if b > 0x0FFF {
286                    return Err("a mat button mask has bits above button 12");
287                }
288                if tag == 3 {
289                    Self::PowerPad(b)
290                } else {
291                    Self::FamilyTrainer(b)
292                }
293            }
294            5 => {
295                let dx = r.i16().map_err(|_| EOF)?;
296                let dy = r.i16().map_err(|_| EOF)?;
297                let buttons = r.u8().map_err(|_| EOF)?;
298                if buttons & !0b11 != 0 {
299                    return Err("a mouse button byte has bits beyond left and right");
300                }
301                let sensitivity = r.u8().map_err(|_| EOF)?;
302                if sensitivity > 3 {
303                    return Err("a mouse sensitivity is above 3");
304                }
305                Self::SnesMouse {
306                    dx,
307                    dy,
308                    left: buttons & 1 != 0,
309                    right: buttons & 2 != 0,
310                    sensitivity,
311                }
312            }
313            6 | 7 => {
314                let mut k = [0u8; 9];
315                r.read_into(&mut k).map_err(|_| EOF)?;
316                if tag == 6 {
317                    Self::FamilyKeyboard(k)
318                } else {
319                    Self::SuborKeyboard(k)
320                }
321            }
322            8 => {
323                let b = r.u8().map_err(|_| EOF)?;
324                if b > 0x0F {
325                    return Err("a Konami Hyper Shot mask has bits above button 4");
326                }
327                Self::KonamiHyperShot(b)
328            }
329            9 => Self::BandaiHyperShot(r.u8().map_err(|_| EOF)?),
330            _ => return Err("an expansion device tag this build does not know"),
331        };
332        Ok(dev)
333    }
334}
335
336/// Every non-controller input of one movie frame. See the module docs.
337///
338/// [`Default`] is the neutral machine: no device on either port, microphone
339/// released, no coin, service released, **disk ejected**, no scan. It is the
340/// baseline the on-disk changes are taken against, not "nothing recorded"
341/// (that is [`crate::FrameInput::extra`] being `None`).
342///
343/// `#[non_exhaustive]`: build one with [`Self::capture`] or [`Default`] and
344/// set fields.
345#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
346#[non_exhaustive]
347pub struct ExtraInput {
348    /// The expansion device on port 0 (`$4016`) and port 1 (`$4017`).
349    pub devices: [DeviceInput; 2],
350    /// Famicom microphone asserted (`$4016` bit 2).
351    pub microphone: bool,
352    /// Vs. System coin acceptors latched: bit 0 = #1, bit 1 = #2.
353    pub vs_coin: u8,
354    /// Vs. System service button held.
355    pub vs_service: bool,
356    /// The inserted FDS disk side (0-based), or `None` when ejected -- and
357    /// always `None` on a cartridge, which has no disk. Side 255 cannot be
358    /// stored (its byte means "ejected"); no FDS image comes near it.
359    pub disk_side: Option<u8>,
360    /// A Datach barcode swiped just before this frame (an event: set on the
361    /// one frame the scan was made before, `None` on every other).
362    pub barcode: Option<Barcode>,
363}
364
365impl ExtraInput {
366    /// Read every non-controller input `nes` holds now. Called by
367    /// [`crate::FrameInput::held_on`], after the host's input calls and
368    /// before the frame.
369    ///
370    /// A disk side beyond 254 cannot be stored; no FDS image has that many
371    /// (a side is 65,500 bytes), and such a side records as ejected.
372    #[must_use]
373    pub fn capture(nes: &Nes) -> Self {
374        Self {
375            devices: [
376                DeviceInput::capture(nes.expansion_device(0)),
377                DeviceInput::capture(nes.expansion_device(1)),
378            ],
379            microphone: nes.microphone(),
380            vs_coin: nes.vs_coin(),
381            vs_service: nes.vs_service(),
382            disk_side: nes
383                .inserted_disk_side()
384                .and_then(|s| u8::try_from(s).ok())
385                .filter(|&s| s != DISK_EJECTED),
386            barcode: nes.barcode_this_frame(),
387        }
388    }
389
390    /// Drive `nes` to these inputs, before the frame runs.
391    ///
392    /// Levels the host sets every frame (devices, microphone, coin, service)
393    /// are written every frame, as the host wrote them. The disk is changed
394    /// only when it differs, because inserting a side is an act with
395    /// consequences (it resets the head and opens the drive's not-ready
396    /// window), and a host only does it once. A barcode is swiped when
397    /// present.
398    ///
399    /// A scan the machine cannot take (no reader) is ignored: the movie's
400    /// board check ([`crate::Movie::seek_to_start`]) already refused a
401    /// machine without the cartridge it was recorded on.
402    pub fn apply(&self, nes: &mut Nes) {
403        self.devices[0].apply(nes, 0);
404        self.devices[1].apply(nes, 1);
405        nes.set_microphone(self.microphone);
406        if nes.vs_coin() != self.vs_coin {
407            nes.clear_coin();
408            for acceptor in 0..2u8 {
409                if self.vs_coin & (1 << acceptor) != 0 {
410                    nes.insert_coin(acceptor);
411                }
412            }
413        }
414        nes.set_vs_service(self.vs_service);
415        let want = self.disk_side.map(usize::from);
416        if nes.inserted_disk_side() != want {
417            nes.set_disk_side(want);
418        }
419        if let Some(code) = &self.barcode {
420            let _ = nes.scan_barcode_code(code);
421        }
422    }
423
424    /// This frame's inputs with the barcode event removed: what the next
425    /// frame starts from when it records no change.
426    #[must_use]
427    pub const fn held(mut self) -> Self {
428        self.barcode = None;
429        self
430    }
431}
432
433/// The disk byte meaning "ejected".
434const DISK_EJECTED: u8 = 0xFF;
435
436/// The decode error for a truncated INPUT EVENTS block.
437const EOF: &str = "the input events end mid-event";
438
439fn read_flag(r: &mut BinReader<'_>) -> Result<bool, &'static str> {
440    match r.u8().map_err(|_| EOF)? {
441        0 => Ok(false),
442        1 => Ok(true),
443        _ => Err("a boolean input is neither 0 nor 1"),
444    }
445}
446
447// ---------------------------------------------------------------------------
448// The INPUT EVENTS block (`.rnm` format 7)
449// ---------------------------------------------------------------------------
450
451/// From this frame on, frames carry no [`ExtraInput`] (`extra` is `None`).
452const EV_EXTRA_OFF: u8 = 0x00;
453/// From this frame on, frames carry an [`ExtraInput`], starting from the
454/// neutral value; the changes that follow in the same frame set it.
455const EV_EXTRA_ON: u8 = 0x01;
456/// `port: u8`, then a [`DeviceInput`] (tag + payload).
457const EV_DEVICE: u8 = 0x02;
458/// `asserted: u8` (0 or 1).
459const EV_MICROPHONE: u8 = 0x03;
460/// `coin bits: u8` (0..=3).
461const EV_VS_COIN: u8 = 0x04;
462/// `held: u8` (0 or 1).
463const EV_VS_SERVICE: u8 = 0x05;
464/// `side: u8`, `0xFF` = ejected.
465const EV_DISK: u8 = 0x06;
466/// `digit count: u8` (8 or 13), then that many digits 0..=9.
467const EV_BARCODE: u8 = 0x07;
468
469/// Smallest event on disk: frame (4) + kind (1), for the allocation bound.
470const MIN_EVENT_LEN: usize = 5;
471
472/// v3.6.1 — the most memory [`decode_events`] would reserve for `block`'s
473/// event list, from its declared count alone and before anything is decoded:
474/// the count, bounded by what the block's bytes could hold (the bound
475/// `decode_events` itself applies), times one decoded event. A block too
476/// short to carry a count costs nothing here; `decode_events` refuses it.
477pub fn decoded_events_bytes(block: &[u8]) -> u64 {
478    let Some(c) = block.get(..4) else {
479        return 0;
480    };
481    let declared = u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as usize;
482    let held = declared.min((block.len() - 4) / MIN_EVENT_LEN);
483    (held as u64).saturating_mul(core::mem::size_of::<(usize, Event)>() as u64)
484}
485
486/// Encode the non-controller half of `frames` as the INPUT EVENTS block body:
487/// `u32` event count, then each event as `u32` frame index, `u8` kind and a
488/// kind-specific payload, in frame order and, within a frame, in kind (then
489/// port) order.
490///
491/// An event is written only where a frame differs from the one before it
492/// (the first frame from "nothing recorded"), plus every barcode scan.
493pub fn encode_events<'a>(frames: impl Iterator<Item = Option<&'a ExtraInput>>) -> Vec<u8> {
494    let mut body = BinWriter::new();
495    let mut count = 0u32;
496    let mut prev: Option<ExtraInput> = None;
497    for (i, cur) in frames.enumerate() {
498        let frame = u32::try_from(i).expect("frame count exceeds u32");
499        let mut ev = |kind: u8, body: &mut BinWriter| {
500            body.u32(frame);
501            body.u8(kind);
502            count += 1;
503        };
504        match (prev, cur) {
505            (None, None) => {}
506            (Some(_), None) => ev(EV_EXTRA_OFF, &mut body),
507            (p, Some(c)) => {
508                let base = p.unwrap_or_else(|| {
509                    ev(EV_EXTRA_ON, &mut body);
510                    ExtraInput::default()
511                });
512                for port in 0..2u8 {
513                    let p = usize::from(port);
514                    if c.devices[p] != base.devices[p] {
515                        ev(EV_DEVICE, &mut body);
516                        body.u8(port);
517                        c.devices[p].write(&mut body);
518                    }
519                }
520                if c.microphone != base.microphone {
521                    ev(EV_MICROPHONE, &mut body);
522                    body.u8(u8::from(c.microphone));
523                }
524                // Masked to the two acceptors `insert_coin` can latch.
525                if c.vs_coin & 0b11 != base.vs_coin & 0b11 {
526                    ev(EV_VS_COIN, &mut body);
527                    body.u8(c.vs_coin & 0b11);
528                }
529                if c.vs_service != base.vs_service {
530                    ev(EV_VS_SERVICE, &mut body);
531                    body.u8(u8::from(c.vs_service));
532                }
533                if c.disk_side != base.disk_side {
534                    ev(EV_DISK, &mut body);
535                    body.u8(c.disk_side.unwrap_or(DISK_EJECTED));
536                }
537                if let Some(code) = &c.barcode {
538                    ev(EV_BARCODE, &mut body);
539                    let digits = code.digits();
540                    body.u8(digit_count(digits));
541                    body.bytes(digits);
542                }
543            }
544        }
545        prev = cur.map(|c| c.held());
546    }
547    let mut out = BinWriter::with_capacity(4 + body.len());
548    out.u32(count);
549    out.bytes(&body.into_vec());
550    out.into_vec()
551}
552
553/// Decode an INPUT EVENTS block body into one `extra` value per frame.
554///
555/// Strict, so that every block this accepts is one [`encode_events`] could
556/// have written (decode then encode returns the same bytes): events must be
557/// in increasing (frame, kind, port) order and inside the movie; a field
558/// event must change the value it sets; the presence events must actually
559/// switch presence; and every value must be one the input can hold.
560///
561/// # Errors
562///
563/// A static description of the first violation, wrapped by the caller in
564/// [`crate::MovieError::BadInputEvents`].
565pub fn decode_events(
566    block: &[u8],
567    frame_count: usize,
568) -> Result<Vec<Option<ExtraInput>>, &'static str> {
569    let mut r = BinReader::new(block);
570    let declared = r.u32().map_err(|_| EOF)? as usize;
571    // SECURITY: `declared` is untrusted; bound any reservation by what the
572    // block could hold (the `frame_count` reservation is bounded by the
573    // caller, which has already read that many frame records).
574    let mut events = Vec::with_capacity(declared.min(r.remaining() / MIN_EVENT_LEN));
575    let mut last_key: Option<(usize, u8, u8)> = None;
576    for _ in 0..declared {
577        let (frame, kind, ev) = read_event(&mut r, frame_count)?;
578        // Checked here, in file order, so the replay loop below can rely on
579        // the list being sorted and consume every event.
580        let port = if let Event::Device(p, _) = ev { p } else { 0 };
581        let key = (frame, kind, port);
582        if last_key.is_some_and(|k| k >= key) {
583            return Err("input events are out of order or repeated");
584        }
585        last_key = Some(key);
586        events.push((frame, ev));
587    }
588    if r.remaining() != 0 {
589        return Err("unexpected bytes after the input events");
590    }
591
592    let mut out = Vec::with_capacity(frame_count);
593    let mut cur: Option<ExtraInput> = None;
594    let mut pending = events.into_iter().peekable();
595    for frame in 0..frame_count {
596        let mut presence_changed = false;
597        while let Some((_, ev)) = pending.next_if(|&(f, _)| f == frame) {
598            if let Event::Presence(on) = ev {
599                if presence_changed || cur.is_some() == on {
600                    return Err("an input presence event does not change presence");
601                }
602                presence_changed = true;
603                cur = on.then(ExtraInput::default);
604                continue;
605            }
606            let Some(state) = cur.as_mut() else {
607                return Err("an input event arrives while no input is recorded");
608            };
609            if !apply_event(state, ev) {
610                return Err("an input event repeats the value already held");
611            }
612        }
613        out.push(cur);
614        cur = cur.map(ExtraInput::held);
615    }
616    // Every event lies before `frame_count` and the list is sorted, so the
617    // loop above consumed them all; checked anyway, because silently dropping
618    // an input is the one outcome this block exists to prevent.
619    if pending.next().is_some() {
620        return Err("an input event was not reached");
621    }
622    Ok(out)
623}
624
625/// Read one event: frame index, kind and payload, validated.
626fn read_event(
627    r: &mut BinReader<'_>,
628    frame_count: usize,
629) -> Result<(usize, u8, Event), &'static str> {
630    let frame = r.u32().map_err(|_| EOF)? as usize;
631    if frame >= frame_count {
632        return Err("an input event lies past the last frame");
633    }
634    let kind = r.u8().map_err(|_| EOF)?;
635    let ev = match kind {
636        EV_EXTRA_OFF | EV_EXTRA_ON => Event::Presence(kind == EV_EXTRA_ON),
637        EV_DEVICE => {
638            let port = r.u8().map_err(|_| EOF)?;
639            if port > 1 {
640                return Err("an expansion device event names a port other than 0 or 1");
641            }
642            Event::Device(port, DeviceInput::read(r)?)
643        }
644        EV_MICROPHONE => Event::Microphone(read_flag(r)?),
645        EV_VS_COIN => {
646            let bits = r.u8().map_err(|_| EOF)?;
647            if bits > 0b11 {
648                return Err("a Vs. coin event sets acceptors other than #1 and #2");
649            }
650            Event::Coin(bits)
651        }
652        EV_VS_SERVICE => Event::Service(read_flag(r)?),
653        EV_DISK => {
654            let side = r.u8().map_err(|_| EOF)?;
655            Event::Disk((side != DISK_EJECTED).then_some(side))
656        }
657        EV_BARCODE => Event::Barcode(read_barcode(r)?),
658        _ => return Err("an input event kind this build does not know"),
659    };
660    Ok((frame, kind, ev))
661}
662
663/// Read a barcode event's payload: a digit count (8 or 13) and the digits,
664/// validated as [`Barcode::parse`] validates a typed code.
665fn read_barcode(r: &mut BinReader<'_>) -> Result<Barcode, &'static str> {
666    let len = usize::from(r.u8().map_err(|_| EOF)?);
667    if len != 8 && len != 13 {
668        return Err("a barcode event is neither 8 nor 13 digits");
669    }
670    let digits = r.take(len).map_err(|_| EOF)?;
671    let mut text = [0u8; 13];
672    for (t, &d) in text.iter_mut().zip(digits) {
673        if d > 9 {
674            return Err("a barcode event holds a digit above 9");
675        }
676        *t = b'0' + d;
677    }
678    let text = core::str::from_utf8(&text[..len]).map_err(|_| EOF)?;
679    Barcode::parse(text).map_err(|_| "a barcode event fails its check digit")
680}
681
682/// Apply one field event to `state`, reporting whether it changed anything
683/// (a barcode, being an event, always does).
684fn apply_event(state: &mut ExtraInput, ev: Event) -> bool {
685    match ev {
686        Event::Device(p, d) => replace(&mut state.devices[usize::from(p)], d),
687        Event::Microphone(v) => replace(&mut state.microphone, v),
688        Event::Coin(v) => replace(&mut state.vs_coin, v),
689        Event::Service(v) => replace(&mut state.vs_service, v),
690        Event::Disk(v) => replace(&mut state.disk_side, v),
691        Event::Barcode(code) => {
692            state.barcode = Some(code);
693            true
694        }
695        // The caller handles presence before calling this.
696        Event::Presence(_) => false,
697    }
698}
699
700/// A validated barcode's digit count, 8 or 13.
701fn digit_count(digits: &[u8]) -> u8 {
702    u8::try_from(digits.len()).unwrap_or(u8::MAX)
703}
704
705/// Set `slot` to `value`, reporting whether it changed.
706fn replace<T: PartialEq>(slot: &mut T, value: T) -> bool {
707    if *slot == value {
708        false
709    } else {
710        *slot = value;
711        true
712    }
713}
714
715#[derive(Clone, Copy)]
716enum Event {
717    Presence(bool),
718    Device(u8, DeviceInput),
719    Microphone(bool),
720    Coin(u8),
721    Service(bool),
722    Disk(Option<u8>),
723    Barcode(Barcode),
724}
725
726/// Bytes [`attestation_bytes`] produces per frame.
727pub const ATTESTATION_EXTRA_LEN: usize = 1 + 2 * (1 + DEVICE_PAYLOAD_MAX) + 4 + 1 + 13;
728
729/// A fixed-size, canonical encoding of a frame's `extra` for the replay
730/// attestation hash, so a tampered non-controller input is detected the way
731/// a tampered button is.
732pub fn attestation_bytes(extra: Option<&ExtraInput>) -> [u8; ATTESTATION_EXTRA_LEN] {
733    let mut out = [0u8; ATTESTATION_EXTRA_LEN];
734    let Some(e) = extra else {
735        return out;
736    };
737    out[0] = 1;
738    let mut at = 1;
739    for dev in e.devices {
740        out[at] = dev.tag();
741        let mut buf = [0u8; DEVICE_PAYLOAD_MAX];
742        let n = dev.payload(&mut buf);
743        out[at + 1..at + 1 + n].copy_from_slice(&buf[..n]);
744        at += 1 + DEVICE_PAYLOAD_MAX;
745    }
746    out[at] = u8::from(e.microphone);
747    // Masked as the `.rnm` encoder masks it and as replay reads it (bits 0-1,
748    // the two acceptors), so an in-memory value with stray high bits attests
749    // as it will after a save and reload (Antigravity on #624, round 3).
750    out[at + 1] = e.vs_coin & 0b11;
751    out[at + 2] = u8::from(e.vs_service);
752    out[at + 3] = e.disk_side.unwrap_or(DISK_EJECTED);
753    at += 4;
754    if let Some(code) = &e.barcode {
755        let d = code.digits();
756        out[at] = digit_count(d);
757        out[at + 1..at + 1 + d.len()].copy_from_slice(d);
758    }
759    out
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765    use alloc::vec;
766
767    fn zapper(x: u16, trigger: bool) -> DeviceInput {
768        DeviceInput::Zapper { x, y: 7, trigger }
769    }
770
771    /// A mixed stream: nothing recorded, then recorded inputs changing in
772    /// every field, then nothing again, then recorded from neutral.
773    fn mixed() -> Vec<Option<ExtraInput>> {
774        let mut a = ExtraInput::default();
775        a.devices[1] = zapper(3, false);
776        a.disk_side = Some(0);
777        let mut b = a;
778        b.devices[1] = zapper(4, true);
779        b.devices[0] = DeviceInput::SnesMouse {
780            dx: -3,
781            dy: 9,
782            left: true,
783            right: false,
784            sensitivity: 2,
785        };
786        b.microphone = true;
787        b.vs_coin = 0b10;
788        b.vs_service = true;
789        b.disk_side = None;
790        b.barcode = Some(Barcode::parse("4901234567894").unwrap());
791        let mut c = b.held();
792        c.devices[0] = DeviceInput::FamilyKeyboard([9; 9]);
793        vec![
794            None,
795            Some(a),
796            Some(a),
797            Some(b),
798            Some(c),
799            None,
800            Some(ExtraInput::default()),
801        ]
802    }
803
804    #[test]
805    fn a_mixed_stream_round_trips_exactly() {
806        let frames = mixed();
807        let block = encode_events(frames.iter().map(Option::as_ref));
808        let back = decode_events(&block, frames.len()).expect("decodes");
809        assert_eq!(back, frames);
810        // And it is canonical: re-encoding gives the same bytes.
811        assert_eq!(encode_events(back.iter().map(Option::as_ref)), block);
812    }
813
814    #[test]
815    fn a_barcode_is_one_frame_long() {
816        let frames = mixed();
817        let back = decode_events(&encode_events(frames.iter().map(Option::as_ref)), 7).unwrap();
818        assert!(back[3].unwrap().barcode.is_some());
819        assert!(back[4].unwrap().barcode.is_none(), "not carried forward");
820    }
821
822    #[test]
823    fn controller_only_movies_cost_four_bytes() {
824        let frames = vec![None; 100];
825        let block = encode_events(frames.iter().map(Option::as_ref));
826        assert_eq!(block, 0u32.to_le_bytes());
827        assert_eq!(decode_events(&block, 100).unwrap(), frames);
828    }
829
830    /// Build a block from raw events: (frame, kind, payload).
831    fn raw(events: &[(u32, u8, &[u8])]) -> Vec<u8> {
832        let mut w = BinWriter::new();
833        w.u32(u32::try_from(events.len()).unwrap());
834        for (f, k, p) in events {
835            w.u32(*f);
836            w.u8(*k);
837            w.bytes(p);
838        }
839        w.into_vec()
840    }
841
842    #[test]
843    fn malformed_blocks_are_refused_with_a_reason() {
844        let on = (0, EV_EXTRA_ON, &[][..]);
845        let cases: &[(&str, Vec<u8>, usize)] = &[
846            ("truncated count", vec![1, 0], 4),
847            ("truncated event", raw(&[(0, EV_MICROPHONE, &[])]), 4),
848            ("past the end", raw(&[(4, EV_EXTRA_ON, &[])]), 4),
849            ("unknown kind", raw(&[on, (0, 0x7E, &[])]), 4),
850            ("field while off", raw(&[(0, EV_MICROPHONE, &[1])]), 4),
851            ("redundant value", raw(&[on, (0, EV_MICROPHONE, &[0])]), 4),
852            ("bad bool", raw(&[on, (0, EV_MICROPHONE, &[2])]), 4),
853            ("bad port", raw(&[on, (0, EV_DEVICE, &[2, 0])]), 4),
854            ("bad device", raw(&[on, (0, EV_DEVICE, &[1, 42])]), 4),
855            ("bad mat", raw(&[on, (0, EV_DEVICE, &[1, 3, 0, 0x10])]), 4),
856            ("bad coin", raw(&[on, (0, EV_VS_COIN, &[4])]), 4),
857            (
858                "bad barcode length",
859                raw(&[on, (0, EV_BARCODE, &[3, 1, 2, 3])]),
860                4,
861            ),
862            (
863                "bad check digit",
864                // 1234567 has check digit 0, so ending in 1 is wrong.
865                raw(&[on, (0, EV_BARCODE, &[8, 1, 2, 3, 4, 5, 6, 7, 1])]),
866                4,
867            ),
868            ("off while off", raw(&[(0, EV_EXTRA_OFF, &[])]), 4),
869            ("on twice", raw(&[on, (1, EV_EXTRA_ON, &[])]), 4),
870            (
871                "out of order",
872                raw(&[on, (2, EV_MICROPHONE, &[1]), (1, EV_VS_SERVICE, &[1])]),
873                4,
874            ),
875            (
876                "repeated",
877                raw(&[on, (1, EV_MICROPHONE, &[1]), (1, EV_MICROPHONE, &[0])]),
878                4,
879            ),
880            (
881                "off then on in one frame",
882                raw(&[on, (1, EV_EXTRA_OFF, &[]), (1, EV_EXTRA_ON, &[])]),
883                4,
884            ),
885        ];
886        for (what, block, frames) in cases {
887            assert!(
888                decode_events(block, *frames).is_err(),
889                "{what} must be refused"
890            );
891        }
892        let mut trailing = raw(&[on]);
893        trailing.push(0);
894        assert!(decode_events(&trailing, 4).is_err(), "trailing bytes");
895    }
896
897    #[test]
898    fn a_hostile_event_count_does_not_reserve_memory() {
899        // Claims four billion events, holds none: refused, not allocated.
900        let block = u32::MAX.to_le_bytes();
901        assert!(decode_events(&block, 10).is_err());
902    }
903
904    #[test]
905    fn attestation_bytes_tell_absent_from_neutral_and_see_every_field() {
906        let none = attestation_bytes(None);
907        let neutral = attestation_bytes(Some(&ExtraInput::default()));
908        assert_ne!(none, neutral);
909        let frames = mixed();
910        let mut seen = alloc::collections::BTreeSet::new();
911        for f in &frames {
912            seen.insert(attestation_bytes(f.as_ref()));
913        }
914        // None (twice), a, a, b, c, neutral: five distinct records.
915        assert_eq!(seen.len(), 5);
916        // Only the two acceptor bits are input: stray high bits attest as the
917        // masked value, as they encode and replay.
918        let stray = ExtraInput {
919            vs_coin: 0b1111_0001,
920            ..ExtraInput::default()
921        };
922        let clean = ExtraInput {
923            vs_coin: 0b01,
924            ..ExtraInput::default()
925        };
926        assert_eq!(
927            attestation_bytes(Some(&stray)),
928            attestation_bytes(Some(&clean))
929        );
930    }
931
932    /// `FrameInput::encode_log` / `decode_log` (the `.rnmproj` version 2
933    /// input log) keep players 3 and 4 and every extra input, and refuse
934    /// trailing bytes.
935    #[test]
936    fn the_input_log_codec_keeps_everything() {
937        use crate::{Buttons, FrameInput};
938        let frames: Vec<FrameInput> = mixed()
939            .into_iter()
940            .enumerate()
941            .map(|(i, extra)| {
942                let b = Buttons::from_bits_truncate(u8::try_from(i * 37 % 256).unwrap());
943                let mut f = FrameInput::four_players(b, b, b, b);
944                f.extra = extra;
945                f
946            })
947            .collect();
948        let bytes = FrameInput::encode_log(&frames);
949        assert_eq!(FrameInput::decode_log(&bytes).unwrap(), frames);
950        let mut long = bytes;
951        long.push(0);
952        assert!(FrameInput::decode_log(&long).is_err());
953        assert!(FrameInput::decode_log(&u32::MAX.to_le_bytes()).is_err());
954    }
955}