// SPDX-License-Identifier: MIT //! The wasm-bindgen surface: a cartridge's bytes in, frames of pixels and sound out, the //! player's controllers and the console's switches in, save states out and back. Numbers, //! strings and typed arrays only, so the page needs no glue beyond wasm-bindgen's. //! //! The board is a2600-rust-fast (crate `a2600`), unchanged, used through its public surface //! (its docs/api.md): `System::from_rom`, the controllers of controllers.rs, the RIOT's port //! levels, `state::save_state` / `load_state`. This is a host (charter "The tiers"): it decides //! nothing about the hardware. Its own choices are presentation and are said where they are: //! which lines of a frame are shown, how a console region is guessed when the player has not //! chosen one, how sound is resampled for the page. The page's shape, rewind and run-ahead are //! play-gb's (and through it play-nes's). use std::cell::RefCell; use std::collections::VecDeque; use std::io::{Cursor, Read, Write}; use std::rc::Rc; use wasm_bindgen::prelude::*; use a2600::cartridge::{Options, Rom, ROM_SUFFIXES}; use a2600::controllers::{DrivingController, Joystick, Keypads, Paddles, Stick}; use a2600::machine::Machine; use a2600::palettes::palette; use a2600::state::{load_state, save_state}; use a2600::television::{HBLANK_CLOCKS, MAX_LINES}; use a2600::tia::TIA; use a2600::{System, VCS_NTSC, VCS_PAL, VCS_SECAM}; // The page's joystick bits, per port. pub const UP: u32 = 1 << 0; pub const DOWN: u32 = 1 << 1; pub const LEFT: u32 = 1 << 2; pub const RIGHT: u32 = 1 << 3; pub const FIRE: u32 = 1 << 4; /// A line is 228 colour clocks, 76 CPU cycles (the board's machine.rs). const LINE_CYCLES: u64 = 76; /// A frame that has not ended after this many CPU cycles is given up on for this call (the /// television cuts a frame at MAX_LINES lines anyway, so this only bounds a stuck host loop). const FRAME_CAP_CYCLES: u64 = 2 * MAX_LINES as u64 * LINE_CYCLES; /// The lines of a frame the page shows, counted from the end of VSYNC as the board's /// television counts them: (first line, number of lines). Presentation, not hardware: chosen /// to hold every drawn line of the games probed on 2026-11-19 (NTSC: Pitfall!, River Raid, /// Space Invaders, Kaboom!, Pac-Man, Adventure, Yars' Revenge, Frostbite drew between lines /// 34 and 258; PAL: Space Invaders (Europe) between 46 and 306). A game that draws outside /// the window loses those lines here, not in the emulation. fn view(machine: &Machine) -> (usize, usize) { if machine.timing.nominal_lines > 262 { (30, 280) } else { (24, 234) } } /// The page's own line collector: the board's television rule (television.rs: a new frame /// when VSYNC ends, or after MAX_LINES lines without one; each line the 160 clocks after the /// horizontal blank), kept here so that its state can be copied for run-ahead and rewind /// (the board's `TelevisionState` keeps its line buffer private). #[derive(Clone, Default)] struct Screen { lines: Vec, count: usize, vsync: bool, frame: Vec, frame_lines: usize, completed: u64, } impl Screen { fn line(&mut self, tia: &TIA) { let vsync = tia.vsync; if (self.vsync && !vsync) || self.count >= MAX_LINES { std::mem::swap(&mut self.frame, &mut self.lines); self.frame_lines = self.count; self.lines.clear(); self.count = 0; self.completed += 1; } self.vsync = vsync; self.lines.extend_from_slice(&tia.pixels[HBLANK_CLOCKS..]); self.count += 1; } } /// What is plugged into the two ports. enum Devices { Joysticks, Paddles(Paddles), Driving(DrivingController), Keypads(Keypads), } const CONTROLLERS: [&str; 4] = ["joystick", "paddles", "driving", "keypad"]; /// The console switches as the player has set them. #[derive(Clone, Copy)] struct Switches { select: bool, reset: bool, colour: bool, left_a: bool, right_a: bool, } /// One rewind step: the board's state (deflated) and the host's own state beside it. struct Snapshot { board: Vec, screen: Screen, driving: i64, } /// Rewind keeps a snapshot every this many frames, so holding it goes back this many times /// faster than the game runs (play-nes's numbers). const REWIND_EVERY: u32 = 4; /// About a minute of snapshots at 60 frames a second... const REWIND_KEEP: usize = 900; /// ...unless they take more memory than this. const REWIND_BUDGET: usize = 48 << 20; /// The page's save-state header: the board's state follows the host's own fields. const STATE_MAGIC: &[u8; 8] = b"P2600S01"; fn is_rom(name: &str) -> bool { let lower = name.to_lowercase(); ROM_SUFFIXES.iter().any(|s| lower.ends_with(s)) } fn stem(name: &str) -> String { let last = name.rsplit(['/', '\\']).next().unwrap_or(name); match last.rfind('.') { Some(dot) if dot > 0 => last[..dot].to_string(), _ => last.to_string(), } } /// The ROM bytes and a name: the file itself, or the one ROM inside a .zip or .7z (the /// board's `read_image` does this for files on disk; a browser has bytes only). pub fn unpack(bytes: Vec, name: &str) -> Result<(Vec, String), String> { if bytes.starts_with(b"PK\x03\x04") { let mut archive = zip::ZipArchive::new(Cursor::new(&bytes)).map_err(|e| format!("{name}: {e}"))?; let mut members = Vec::new(); for i in 0..archive.len() { let member = archive.by_index(i).map_err(|e| e.to_string())?.name().to_string(); if is_rom(&member) { members.push(member); } } if members.len() != 1 { return Err(format!("{name}: expected one ROM (.a26, .bin, .rom), found {members:?}")); } let mut entry = archive.by_name(&members[0]).map_err(|e| e.to_string())?; let mut data = Vec::new(); entry.read_to_end(&mut data).map_err(|e| e.to_string())?; return Ok((data, stem(&members[0]))); } if bytes.starts_with(&[b'7', b'z', 0xBC, 0xAF, 0x27, 0x1C]) { use sevenz_rust2::{ArchiveReader, Password}; let mut reader = ArchiveReader::new(Cursor::new(&bytes), Password::empty()) .map_err(|e| format!("{name}: could not read the 7z archive: {e}"))?; let members: Vec = reader .archive() .files .iter() .filter(|f| f.has_stream() && !f.is_directory() && is_rom(f.name())) .map(|f| f.name().to_string()) .collect(); if members.len() != 1 { return Err(format!("{name}: expected one ROM (.a26, .bin, .rom), found {members:?}")); } let data = reader .read_file(&members[0]) .map_err(|e| format!("{name}: could not unpack {}: {e}", members[0]))?; return Ok((data, stem(&members[0]))); } Ok((bytes, stem(name))) } fn machine_for(key: &str) -> Option { match key { "ntsc" => Some(VCS_NTSC), "pal" => Some(VCS_PAL), "secam" => Some(VCS_SECAM), _ => None, } } /// The console a file's name asks for, by the No-Intro naming convention: an explicit /// "PAL", "SECAM" or "NTSC" in the name first, then the release countries. A guess about the /// file, not the hardware; None when the name says nothing. pub fn region_from_name(name: &str) -> Option<&'static str> { if name.contains("SECAM") { return Some("secam"); } if name.contains("PAL") { return Some("pal"); } if name.contains("NTSC") { return Some("ntsc"); } const NTSC_LANDS: [&str; 6] = ["USA", "Japan", "World", "Canada", "Brazil", "Korea"]; const PAL_LANDS: [&str; 11] = [ "Europe", "Germany", "France", "UK", "Italy", "Spain", "Sweden", "Australia", "Netherlands", "Scandinavia", "Asia", ]; let tags: Vec<&str> = name .split('(') .skip(1) .filter_map(|t| t.split(')').next()) .flat_map(|t| t.split(',').map(str::trim)) .collect(); if tags.iter().any(|t| NTSC_LANDS.contains(t)) { return Some("ntsc"); } if tags.iter().any(|t| PAL_LANDS.contains(t)) { return Some("pal"); } None } /// Run the program for a while on an NTSC console and see how many lines its frames have: a /// program that draws 290 or more is made for a 50 Hz television. The host's guess (the /// board has no region detection: docs/issues/0001), used only when the name says nothing. fn probe_lines(image: &[u8]) -> Option { let mut system = System::from_rom(Rom::Bytes(image), VCS_NTSC, None, Options::default()).ok()?; let screen = Rc::new(RefCell::new(Screen::default())); let shared = screen.clone(); system.board_mut().tia.on_line = Some(Box::new(move |tia: &TIA| shared.borrow_mut().line(tia))); let mut lengths = Vec::new(); for _ in 0..90 { let target = screen.borrow().completed + 1; let watch = screen.clone(); system.run_until(move |_| watch.borrow().completed >= target, FRAME_CAP_CYCLES); system.board_mut().tia.audio.take_samples(); lengths.push(screen.borrow().frame_lines); } let mut late = lengths[30..].to_vec(); late.sort_unstable(); Some(late[late.len() / 2]) } /// One console with one cartridge. #[wasm_bindgen] pub struct Console { system: System, screen: Rc>, /// a2600-bench's checksum (every finished line, every audio sample), for the headless check check: Option>>, title: String, machine_key: String, region_source: String, controllers: String, devices: Devices, lut: [[u8; 3]; 256], view: (usize, usize), rgba: Vec, // input ports: [u32; 2], paddles: [f64; 4], paddle_fire: [bool; 4], keypads: [u16; 2], switches: Switches, // sound sample_rate: f64, tick_rate: f64, phase: f64, previous: f64, dc_in: f64, dc_out: f64, sound: Vec, last_frame_cycles: u64, messages: Vec, rewind: VecDeque, rewind_bytes: usize, frames_since_snapshot: u32, } #[wasm_bindgen] impl Console { /// Power on with a cartridge: `bytes` as the file holds them (a .zip or .7z is fine), /// `name` the file's name, `sample_rate` the page's sound rate, `machine_key` "ntsc", "pal", /// "secam" or "" (guessed: the file's name, else the program's line count), `controllers` /// "joystick", "paddles", "driving" or "keypad" ("" is joysticks). The cartridge's scheme is /// the board's own detection (`cartridge::load`; in a browser there is no MAME software list /// to read, so it is the board's detector). #[wasm_bindgen(constructor)] pub fn new( bytes: Vec, name: &str, sample_rate: u32, machine_key: &str, controllers: &str, ) -> Result { let (image, rom_name) = unpack(bytes, name).map_err(|e| JsError::new(&e))?; let (key, region_source) = if machine_key.is_empty() { match region_from_name(&rom_name).or_else(|| region_from_name(name)) { Some(key) => (key.to_string(), "the file's name".to_string()), None => match probe_lines(&image) { Some(lines) if lines >= 290 => ("pal".to_string(), format!("{lines} lines a frame")), Some(lines) => ("ntsc".to_string(), format!("{lines} lines a frame")), None => ("ntsc".to_string(), "the default".to_string()), }, } } else { (machine_key.to_string(), "your choice".to_string()) }; let row = machine_for(&key).ok_or_else(|| JsError::new(&format!("unknown console {key}")))?; let controllers = if controllers.is_empty() { "joystick" } else { controllers }; if !CONTROLLERS.contains(&controllers) { return Err(JsError::new(&format!("unknown controllers {controllers}"))); } let mut system = System::from_rom(Rom::Bytes(&image), row, None, Options::default()) .map_err(|e| JsError::new(&e))?; let screen = Rc::new(RefCell::new(Screen::default())); let shared = screen.clone(); system.board_mut().tia.on_line = Some(Box::new(move |tia: &TIA| shared.borrow_mut().line(tia))); let devices = { let clock = row.timing.colour_clock_hz; let board = system.board_mut(); let riot = board.riot.clone(); let tia = &mut board.tia; match controllers { "paddles" => { let paddles = Paddles::new(tia, clock); *paddles.position.borrow_mut() = [Some(0.5); 4]; Devices::Paddles(paddles) } "driving" => Devices::Driving(DrivingController::new(tia, &mut riot.borrow_mut(), 0)), "keypad" => Devices::Keypads(Keypads::new(tia, riot)), _ => Devices::Joysticks, } }; let pal = palette(row.palette); let mut lut = [[0u8; 3]; 256]; for (value, entry) in lut.iter_mut().enumerate() { if value & 1 != 0 { let (r, g, b) = pal.rgb(value as u8); *entry = [r, g, b]; } } let view = view(&row); let switches = Switches { select: false, reset: false, colour: row.switches & 0x08 != 0, left_a: row.switches & 0x40 != 0, right_a: row.switches & 0x80 != 0, }; let mut console = Console { system, screen, check: None, title: rom_name, machine_key: key, region_source, controllers: controllers.to_string(), devices, lut, view, rgba: vec![255; 160 * view.1 * 4], ports: [0; 2], paddles: [0.5; 4], paddle_fire: [false; 4], keypads: [0; 2], switches, sample_rate: sample_rate as f64, tick_rate: 2.0 * row.timing.colour_clock_hz / 228.0, // two audio ticks a line phase: 0.0, previous: 0.0, dc_in: 0.0, dc_out: 0.0, sound: Vec::new(), last_frame_cycles: 0, messages: Vec::new(), rewind: VecDeque::new(), rewind_bytes: 0, frames_since_snapshot: 0, }; console.paint(); Ok(console) } pub fn title(&self) -> String { self.title.clone() } /// "ntsc", "pal" or "secam". pub fn machine(&self) -> String { self.machine_key.clone() } /// The board's machine row and how it was chosen. pub fn machine_name(&self) -> String { format!("{} (by {})", self.system.machine.name, self.region_source) } /// The cartridge's scheme, as the board's detection chose it. pub fn cartridge(&self) -> String { match &self.system.loaded { Some(info) => format!("{} ({})", info.scheme, info.source), None => "?".to_string(), } } pub fn controllers(&self) -> String { self.controllers.clone() } /// Frames a second at the machine's nominal line count (59.94 NTSC, 49.86 PAL and SECAM). pub fn rate(&self) -> f64 { let timing = self.system.machine.timing; timing.colour_clock_hz / 228.0 / timing.nominal_lines as f64 } /// How long the last frame took on the console, in milliseconds (a program's frames need /// not have the nominal line count; the page paces by this). pub fn last_frame_ms(&self) -> f64 { if self.last_frame_cycles == 0 { 1000.0 / self.rate() } else { self.last_frame_cycles as f64 * 1000.0 / self.system.machine.timing.cpu_hz() } } pub fn width(&self) -> u32 { 160 } pub fn height(&self) -> u32 { self.view.1 as u32 } // -- input ------------------------------------------------------------------------- /// A joystick's switches on `port` (0 left, 1 right): the bits above. With a Driving /// controller, port 0's left and right turn the knob and FIRE is its button. pub fn set_joystick(&mut self, port: usize, mask: u32) { if port < 2 { self.ports[port] = mask; } } /// Paddle `i` (0-3; 0 and 1 on the left port), 0.0 to 1.0 as the board takes it (its pot's /// resistance, 0 the low end), and its button. pub fn set_paddle(&mut self, i: usize, position: f64, fire: bool) { if i < 4 { self.paddles[i] = position.clamp(0.0, 1.0); self.paddle_fire[i] = fire; } } /// The keys held on keypad `port`: bit `row * 3 + column`, rows top first. pub fn set_keypad(&mut self, port: usize, mask: u32) { if port < 2 { self.keypads[port] = (mask & 0xFFF) as u16; } } /// Game Select and Game Reset, held while true. pub fn set_buttons(&mut self, select: bool, reset: bool) { self.switches.select = select; self.switches.reset = reset; } /// The colour / black-and-white switch (a SECAM console has none: its D3 is grounded). pub fn set_colour(&mut self, colour: bool) { self.switches.colour = colour; } /// The difficulty switches: true is A. pub fn set_difficulty(&mut self, left_a: bool, right_a: bool) { self.switches.left_a = left_a; self.switches.right_a = right_a; } pub fn colour(&self) -> bool { self.switches.colour } pub fn left_a(&self) -> bool { self.switches.left_a } pub fn right_a(&self) -> bool { self.switches.right_a } pub fn has_colour_switch(&self) -> bool { self.system.machine.switches & 0x08 != 0 } /// The held inputs onto the ports and the switches onto SWCHB, before a frame. fn apply_inputs(&mut self) { let stick = |mask: u32| Stick { up: mask & UP != 0, down: mask & DOWN != 0, left: mask & LEFT != 0, right: mask & RIGHT != 0, fire: mask & FIRE != 0, }; let machine_switches = self.system.machine.switches; let board = self.system.board_mut(); let riot_rc = board.riot.clone(); let mut riot = riot_rc.borrow_mut(); let tia = &mut board.tia; match &mut self.devices { Devices::Joysticks => { for port in 0..2 { Joystick::new(port).set(tia, &mut riot, stick(self.ports[port])); } } Devices::Paddles(paddles) => { let mut position = paddles.position.borrow_mut(); for i in 0..4 { position[i] = Some(self.paddles[i]); } // Paddle buttons are SWCHA D7 and D6 (left pair), D3 and D2 (right): DOC nocash, // as the board's window reads them. let mut levels = 0xFFu8; for (i, bit) in [0x80u8, 0x40, 0x08, 0x04].into_iter().enumerate() { if self.paddle_fire[i] { levels &= !bit; } } if riot.input_a != levels { riot.set_input_a(levels); } } Devices::Driving(wheel) => { let mask = self.ports[0]; let clicks = (mask & RIGHT != 0) as i64 - (mask & LEFT != 0) as i64; if clicks != 0 { wheel.turn(tia, &mut riot, clicks); } if wheel.fire != (mask & FIRE != 0) { wheel.press(tia, &mut riot, mask & FIRE != 0); } Joystick::new(1).set(tia, &mut riot, stick(self.ports[1])); } Devices::Keypads(keypads) => { let mut pressed = keypads.pressed.borrow_mut(); for port in 0..2 { pressed[port].clear(); for key in 0..12u8 { if self.keypads[port] >> key & 1 != 0 { pressed[port].insert((key / 3, key % 3)); } } } } } // SWCHB: D0 Game Reset and D1 Game Select read 0 while held, D3 colour (1) or B&W, // D6 and D7 the left and right difficulty (1 = A) (DOC: Stella Programmer's Guide, as // the board's window drives them); the other bits stay as the machine row has them, // and a SECAM console's D3 stays grounded (its row's switches, machine.rs). let s = self.switches; let colour = s.colour && machine_switches & 0x08 != 0; riot.input_b = (machine_switches & 0x34) | !s.reset as u8 | (!s.select as u8) << 1 | (colour as u8) << 3 | (s.left_a as u8) << 6 | (s.right_a as u8) << 7; } // -- running ----------------------------------------------------------------------- /// Run until the television has a new frame (VSYNC ended, or MAX_LINES lines passed). fn run_to_frame(&mut self) { let before = self.system.cycles(); let target = self.screen.borrow().completed + 1; let watch = self.screen.clone(); self.system .run_until(move |_| watch.borrow().completed >= target, FRAME_CAP_CYCLES); self.last_frame_cycles = self.system.cycles() - before; } /// Run one frame; `draw` false skips the picture (catching up). pub fn run_frame(&mut self, draw: bool) { self.real_frame(); if draw { self.paint(); } } /// Run one frame and show the picture of `ahead` frames later (play-nes's run-ahead): /// the console's own frame runs and gives the sound; then it is saved, run `ahead` /// frames further with the same inputs, painted, and loaded back. False if the state /// could not be loaded back (the caller should stop asking). pub fn run_frame_ahead(&mut self, ahead: u32) -> bool { self.real_frame(); if ahead == 0 { self.paint(); return true; } let board = save_state(&self.system); let screen = self.screen.borrow().clone(); let driving = self.driving_position(); let last = self.last_frame_cycles; for _ in 0..ahead { self.apply_inputs(); self.run_to_frame(); } self.paint(); self.last_frame_cycles = last; match self.restore(&board, screen, driving) { Ok(()) => true, Err(error) => { self.messages.push(format!("Run-ahead off: {error}")); false } } } /// The console's own next frame: inputs, the frame, a rewind snapshot now and then, the sound. fn real_frame(&mut self) { self.apply_inputs(); self.run_to_frame(); self.frames_since_snapshot += 1; if self.frames_since_snapshot >= REWIND_EVERY { self.frames_since_snapshot = 0; self.keep_snapshot(); } let samples = self.system.board_mut().tia.audio.take_samples(); self.resample(&samples); } /// The TIA's samples (0..1, two a line) to the page's rate: linear interpolation (as the /// board's window resamples), then a one-pole high-pass at about 20 Hz to take out the /// TIA output's standing level, interleaved stereo. A host's choice, not the console's /// analogue output stage, which is not modelled. fn resample(&mut self, samples: &[f64]) { self.sound.clear(); let step = self.tick_rate / self.sample_rate; let pole = (-2.0 * std::f64::consts::PI * 20.0 / self.sample_rate).exp(); let mut t = self.phase; let n = samples.len() as f64; // t indexes [previous, samples...]: 0 is the last sample of the previous frame while t < n { let i = t as usize; let a = if i == 0 { self.previous } else { samples[i - 1] }; let b = samples[i]; let f = t - i as f64; let v = a * (1.0 - f) + b * f; let out = v - self.dc_in + pole * self.dc_out; self.dc_in = v; self.dc_out = out; let s = (out * 0.9) as f32; self.sound.push(s); self.sound.push(s); t += step; } if let Some(&last) = samples.last() { self.previous = last; } self.phase = t - n; } fn driving_position(&self) -> i64 { match &self.devices { Devices::Driving(wheel) => wheel.position, _ => 0, } } /// The board's state back, with the host's line collector and Driving knob beside it. fn restore(&mut self, board: &[u8], screen: Screen, driving: i64) -> Result<(), String> { load_state(&mut self.system, board)?; *self.screen.borrow_mut() = screen; if let Devices::Driving(wheel) = &mut self.devices { wheel.position = driving; } Ok(()) } /// One snapshot onto the rewind window, the oldest dropped past its limits. fn keep_snapshot(&mut self) { let raw = save_state(&self.system); let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::fast()); encoder.write_all(&raw).expect("compressing to memory"); let board = encoder.finish().expect("compressing to memory"); let screen = { // the collector between frames holds a line or two; the last frame is not needed let s = self.screen.borrow(); Screen { lines: s.lines.clone(), count: s.count, vsync: s.vsync, frame: Vec::new(), frame_lines: 0, completed: s.completed, } }; self.rewind_bytes += board.len() + screen.lines.len(); self.rewind.push_back(Snapshot { board, screen, driving: self.driving_position(), }); while self.rewind.len() > REWIND_KEEP || (self.rewind_bytes > REWIND_BUDGET && self.rewind.len() > 1) { if let Some(old) = self.rewind.pop_front() { self.rewind_bytes -= old.board.len() + old.screen.lines.len(); } } } /// The last complete frame into the RGBA buffer, through the machine's palette. fn paint(&mut self) { let screen = self.screen.borrow(); let (first, rows) = self.view; for row in 0..rows { let line = first + row; let out = &mut self.rgba[row * 160 * 4..(row + 1) * 160 * 4]; if line < screen.frame_lines { let pixels = &screen.frame[line * 160..(line + 1) * 160]; for (pixel, &value) in out.chunks_exact_mut(4).zip(pixels) { pixel[..3].copy_from_slice(&self.lut[value as usize]); } } else { for pixel in out.chunks_exact_mut(4) { pixel[..3].copy_from_slice(&[0, 0, 0]); } } } } /// The last frame's RGBA bytes, 160 × height × 4, in the module's memory: a view that a /// later call may move, so copy it before calling again. pub fn frame_ptr(&self) -> *const u8 { self.rgba.as_ptr() } pub fn frame_len(&self) -> usize { self.rgba.len() } /// The last frame's sound, interleaved stereo floats at the page's rate. pub fn sound(&self) -> Vec { self.sound.clone() } /// The next message to show, or "". pub fn take_message(&mut self) -> String { if self.messages.is_empty() { String::new() } else { self.messages.remove(0) } } // -- rewind ------------------------------------------------------------------------ /// One step back in place of a frame, while rewind is held (play-nes's): the newest /// snapshot kept is loaded, painted and forgotten; the oldest stays. No sound. False /// when nothing is kept (or a snapshot would not load). pub fn rewind_step(&mut self) -> bool { let snapshot = if self.rewind.len() > 1 { let snapshot = self.rewind.pop_back().expect("not empty"); self.rewind_bytes -= snapshot.board.len() + snapshot.screen.lines.len(); snapshot } else if let Some(only) = self.rewind.back() { Snapshot { board: only.board.clone(), screen: only.screen.clone(), driving: only.driving, } } else { return false; }; let mut raw = Vec::new(); if flate2::read::DeflateDecoder::new(snapshot.board.as_slice()) .read_to_end(&mut raw) .is_err() { return false; } // keep the picture on screen: the snapshot holds no finished frame let mut screen = snapshot.screen; { let shown = self.screen.borrow(); screen.frame = shown.frame.clone(); screen.frame_lines = shown.frame_lines; } if let Err(error) = self.restore(&raw, screen, snapshot.driving) { self.messages.push(format!("Rewind: {error}")); self.rewind.clear(); self.rewind_bytes = 0; return false; } // run the snapshot's frame so the picture is the moment rewound to self.system.board_mut().tia.audio.take_samples(); self.frames_since_snapshot = 0; self.sound.clear(); self.paint_after_rewind(); true } /// The picture at a rewound moment: one frame run from the snapshot and loaded back, so /// that the console's own state stays at the snapshot. fn paint_after_rewind(&mut self) { let board = save_state(&self.system); let screen = self.screen.borrow().clone(); let driving = self.driving_position(); let last = self.last_frame_cycles; self.run_to_frame(); self.paint(); self.last_frame_cycles = last; if let Err(error) = self.restore(&board, screen, driving) { self.messages.push(format!("Rewind: {error}")); } } /// Seconds of the past the rewind window holds. pub fn rewind_seconds(&self) -> f64 { self.rewind.len() as f64 * REWIND_EVERY as f64 / self.rate() } /// The rewind window's memory, in bytes. pub fn rewind_memory(&self) -> usize { self.rewind_bytes } // -- save states ------------------------------------------------------------------- /// The whole machine: the page's header (its Driving knob and the lines of the frame in /// progress), then a2600-rust-fast's state. pub fn save_state(&self) -> Vec { let mut out = STATE_MAGIC.to_vec(); out.extend_from_slice(&self.driving_position().to_le_bytes()); let s = self.screen.borrow(); out.push(s.vsync as u8); out.extend_from_slice(&(s.count as u32).to_le_bytes()); out.extend_from_slice(&s.lines); out.extend(save_state(&self.system)); out } pub fn load_state(&mut self, data: &[u8]) -> Result<(), JsError> { let bad = || JsError::new("not a play-2600 save state"); if data.len() < 21 || &data[..8] != STATE_MAGIC { return Err(bad()); } let driving = i64::from_le_bytes(data[8..16].try_into().expect("8 bytes")); let vsync = data[16] != 0; let count = u32::from_le_bytes(data[17..21].try_into().expect("4 bytes")) as usize; let end = 21 + count * 160; if count > MAX_LINES || data.len() < end { return Err(bad()); } let mut screen = self.screen.borrow().clone(); screen.vsync = vsync; screen.count = count; screen.lines = data[21..end].to_vec(); self.restore(&data[end..], screen, driving).map_err(|e| JsError::new(&e))?; self.system.board_mut().tia.audio.take_samples(); self.rewind.clear(); self.rewind_bytes = 0; self.paint_after_rewind(); Ok(()) } // -- the headless check -------------------------------------------------------------- /// Install a2600-bench's checksum: every line the TIA finishes (all 228 clocks) and, after /// each `run_check_frame`, every audio sample of it, as a2600-bench and the board's /// examples/wasm_bench.rs compute it. Call before running. pub fn enable_check(&mut self) { let crc = Rc::new(RefCell::new(crc32fast::Hasher::new())); let (shared, screen) = (crc.clone(), self.screen.clone()); self.system.board_mut().tia.on_line = Some(Box::new(move |tia: &TIA| { screen.borrow_mut().line(tia); shared.borrow_mut().update(&tia.pixels); })); self.check = Some(crc); } /// One frame as a2600-bench runs one (`System::run_frames(1)`: until the next VSYNC /// starts), the inputs applied first, the samples into the checksum. No run-ahead, no /// rewind snapshot: the checksum is the board's alone. pub fn run_check_frame(&mut self) { self.apply_inputs(); let target = self.system.board().tia.frame + 1; // A program's first frame can be long (River Raid runs 278,112 cycles from power-on // to its first VSYNC), so the cap is in chunks, up to about a hundred frames: // continuing in chunks takes the same steps as one call. for _ in 0..50 { if self .system .run_until(move |s| s.board().tia.frame >= target, FRAME_CAP_CYCLES) { break; } } let samples = self.system.board_mut().tia.audio.take_samples(); if let Some(crc) = &self.check { let mut crc = crc.borrow_mut(); for sample in &samples { crc.update(&sample.to_le_bytes()); } } } pub fn checksum(&self) -> u32 { self.check.as_ref().map(|c| c.borrow().clone().finalize()).unwrap_or(0) } /// CPU cycles since power-on. pub fn cycles(&self) -> f64 { self.system.cycles() as f64 } pub fn cpu_hz(&self) -> f64 { self.system.machine.timing.cpu_hz() } /// CRC-32 of the last complete frame's lines (the page's collector), for comparing runs. pub fn frame_crc(&self) -> u32 { let s = self.screen.borrow(); crc32fast::hash(&s.frame[..s.frame_lines * 160]) } } #[cfg(test)] mod tests { use super::region_from_name; #[test] fn regions_from_no_intro_names() { assert_eq!(region_from_name("Combat (USA)"), Some("ntsc")); assert_eq!(region_from_name("Combat (Europe)"), Some("pal")); assert_eq!(region_from_name("Sheep It Up! - SECAM (World) (Aftermarket) (Unl)"), Some("secam")); assert_eq!(region_from_name("Halo 2600 (Europe) (PAL) (Aftermarket) (Unl)"), Some("pal")); assert_eq!(region_from_name("RealSports Boxing (USA, Europe) (En,Fr,De,Es,It)"), Some("ntsc")); assert_eq!(region_from_name("kleine Bar, Der (Germany)"), Some("pal")); assert_eq!(region_from_name("homebrew"), None); } }