// SPDX-License-Identifier: MIT //! Cartridge files: reading them, identifying the scheme, building the scheme. //! //! There is no header in a 2600 dump, so the scheme comes from, in order //! (docs/cartridge.md "File formats and identification"): //! //! 1. an explicit choice by the caller (`scheme`, and `super_chip`); //! 2. MAME's software list (CC0), read at run time, never committed: the file //! `$MAME_HASHPATH/a2600.xml` if that variable is set, else the copy fetched //! into `reference/src/mame/hash/` (no machine path: without either, this //! step is skipped); the part's //! `slot` feature, a `ram` data area meaning Super Chip, by SHA-1; //! 3. this package's own detector (`detect.rs`), written from the scheme //! descriptions, and for F8/F6/F4 the Super Chip test below. //! //! Every scheme the licensed dumps use is built (milestone 5): 2K, 4K, F8, F6, //! F4 and their Super Chip forms, FA, E0, 3F, FE, E7, CV, UA, F0, 32IN1, DPC and //! the Supercharger (AR). //! //! Rust-forced differences (a2600-python `cartridge/__init__.py` at 28fb095): //! Python's `**options` are an [`Options`] struct (a scheme takes the fields //! it has and ignores the rest, where Python would raise `TypeError`), and //! the keyword `cpu_hz` of `build` and `load` is its field `cpu_hz`; `CLOCKED` //! is an array, not a frozenset; a ROM //! is a [`Rom`] (a path or bytes); `ElementTree` is replaced by a small reader //! of the software list's elements (`softlist`) that keeps the same rules //! (the part's first `slot` feature, any `ram` data area, the software's first //! `description` or else its name, later entries overwriting earlier ones); //! the default softlist path is resolved against this crate's root, as the //! reference resolves it against its checkout, and fixed at first use as the //! reference fixes it at import. Errors are `Result`s; `UnsupportedCartridge` //! is an error type. pub mod atari; pub mod connector; pub mod detect; pub mod dpc; pub mod licensed; pub mod supercharger; use std::collections::HashMap; use std::fmt; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::{Arc, Mutex, OnceLock}; use sha1::{Digest, Sha1}; use self::atari::{Banked, Plain}; use self::connector::Cartridge; use self::detect::detect; use self::dpc::{DPC, MUSIC_HZ, NTSC_CPU_HZ}; use self::licensed::{ActivisionFE, CommaVid, MNetworkE7, MegaboyF0, ThirtyTwoInOne, Tigervision3F, E0, UA}; use self::supercharger::{Supercharger, TapeLevel}; fn mame_hash_default() -> PathBuf { match std::env::var("MAME_HASHPATH") { Ok(over) if !over.is_empty() => Path::new(&over).join("a2600.xml"), _ => Path::new(env!("CARGO_MANIFEST_DIR")).join("reference/src/mame/hash/a2600.xml"), } } /// `MAME_HASH`: the software list's path, fixed at first use. pub fn mame_hash() -> PathBuf { static MAME_HASH: OnceLock = OnceLock::new(); MAME_HASH.get_or_init(mame_hash_default).clone() } pub const ROM_SUFFIXES: [&str; 3] = [".a26", ".bin", ".rom"]; // DOC: nocash 2k6specs file extensions /// Plain sizes: DOC: Horton's 2012 mapper document (F8 8K, F6 16K, F4 32K). pub const SIZE_SCHEMES: [(usize, &str); 5] = [ (0x800, "2K"), (0x1000, "4K"), (0x2000, "F8"), (0x4000, "F6"), (0x8000, "F4"), ]; /// MAME slot names -> ours (DOC: MAME 0.285's CC0 hash/a2600.xml slot names). pub const MAME_SLOTS: [(&str, Option<&str>); 16] = [ ("a26_2k_4k", None), ("a26_f8", Some("F8")), ("a26_f8sw", Some("F8")), ("a26_f6", Some("F6")), ("a26_f4", Some("F4")), ("a26_fa", Some("FA")), ("a26_e0", Some("E0")), ("a26_3f", Some("3F")), ("a26_fe", Some("FE")), ("a26_e7", Some("E7")), ("a26_cv", Some("CV")), ("a26_ua", Some("UA")), ("a26_dc", Some("F0")), ("a26_32in1", Some("32IN1")), ("a26_dpc", Some("DPC")), ("a26_ss", Some("AR")), ]; /// Scheme names with a builder beyond the 4K-bank ones (each builder's module carries its evidence). pub const SCHEMES: [&str; 11] = ["FA", "E0", "3F", "FE", "E7", "CV", "UA", "F0", "32IN1", "DPC", "AR"]; #[derive(Clone, Debug, PartialEq, Eq)] pub struct UnsupportedCartridge(pub String); impl fmt::Display for UnsupportedCartridge { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.0) } } impl std::error::Error for UnsupportedCartridge {} /// A scheme's options (Python's keyword arguments to the builders). #[derive(Default)] pub struct Options { pub start_bank: Option, pub ram_fill: Option, pub start_slices: Option<(usize, usize, usize)>, pub start_page: Option, pub game: Option, pub bios: Option>, pub tape_level: Option, pub cpu_hz: Option, pub music_hz: Option, } pub struct Loaded { pub cartridge: Box, pub scheme: String, // e.g. "F6SC" pub source: String, // "explicit", "MAME softlist", "detector" pub title: Option, // MAME's description when the list carries the dump pub sha1: String, } /// What a [`Loaded`] says, without the cartridge (which the board owns). #[derive(Clone, Debug, PartialEq, Eq)] pub struct LoadedInfo { pub scheme: String, pub source: String, pub title: Option, pub sha1: String, } impl Loaded { pub fn info(&self) -> LoadedInfo { LoadedInfo { scheme: self.scheme.clone(), source: self.source.clone(), title: self.title.clone(), sha1: self.sha1.clone(), } } } /// A ROM to load: a file (plain, `.zip` or `.7z`) or its bytes. pub enum Rom<'a> { Path(&'a Path), Bytes(&'a [u8]), } fn suffix_lower(name: &str) -> String { Path::new(name) .extension() .map(|e| format!(".{}", e.to_string_lossy().to_lowercase())) .unwrap_or_default() } fn is_rom_name(name: &str) -> bool { ROM_SUFFIXES.iter().any(|s| name.to_lowercase().ends_with(s)) } fn stem(name: &str) -> String { Path::new(name) .file_stem() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_default() } /// The ROM bytes and a name: a plain file, or the one ROM inside a .zip or .7z. pub fn read_image(path: &Path) -> Result<(Vec, String), String> { let shown = path.display(); let suffix = suffix_lower(&path.to_string_lossy()); if suffix == ".zip" { let file = std::fs::File::open(path).map_err(|e| format!("{shown}: {e}"))?; let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("{shown}: {e}"))?; let members: Vec = archive .file_names() .filter(|n| is_rom_name(n)) .map(String::from) .collect(); // file_names() is in hash order: put the members in the archive's order. let mut ordered = Vec::new(); for i in 0..archive.len() { let name = archive.by_index(i).map_err(|e| e.to_string())?.name().to_string(); if members.contains(&name) { ordered.push(name); } } if ordered.len() != 1 { return Err(format!("{shown}: expected one ROM, found {ordered:?}")); } let mut data = Vec::new(); archive .by_name(&ordered[0]) .map_err(|e| e.to_string())? .read_to_end(&mut data) .map_err(|e| e.to_string())?; return Ok((data, stem(&ordered[0]))); } if suffix == ".7z" { let listing = Command::new("7z") .args(["l", "-slt"]) .arg(path) .output() .map_err(|e| e.to_string())?; if !listing.status.success() { return Err(format!("{shown}: 7z l failed")); } let text = String::from_utf8_lossy(&listing.stdout); let members: Vec = text .lines() .filter(|line| line.starts_with("Path = ") && is_rom_name(line)) .map(|line| line[7..].to_string()) .collect(); if members.len() != 1 { return Err(format!("{shown}: expected one ROM, found {members:?}")); } let data = Command::new("7z") .args(["x", "-so"]) .arg(path) .arg(&members[0]) .output() .map_err(|e| e.to_string())?; if !data.status.success() { return Err(format!("{shown}: 7z x failed")); } return Ok((data.stdout, stem(&members[0]))); } let data = std::fs::read(path).map_err(|e| format!("{shown}: {e}"))?; Ok((data, stem(&path.to_string_lossy()))) } /// SHA-1 -> (slot, has RAM, description). pub type SoftList = HashMap; /// SHA-1 -> (slot, has RAM, description) from MAME's software list (cached by path). pub fn mame_list(path: &Path) -> Arc { static CACHE: OnceLock>>> = OnceLock::new(); let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); let mut cache = cache.lock().unwrap(); if let Some(table) = cache.get(path) { return table.clone(); } let table = Arc::new(match std::fs::read_to_string(path) { Ok(text) if path.is_file() => softlist::parse(&text), _ => SoftList::new(), }); cache.insert(path.to_path_buf(), table.clone()); table } /// Every 4K bank's first 256 bytes (the RAM's two windows) hold one value. pub fn detect_super_chip(image: &[u8]) -> bool { if image.len() < 0x2000 { return false; } (0..image.len()).step_by(0x1000).all(|bank| { let window = &image[bank..(bank + 0x100).min(image.len())]; window.iter().all(|&b| b == window[0]) }) } pub fn sha1_hex(image: &[u8]) -> String { Sha1::digest(image).iter().map(|b| format!("{b:02x}")).collect() } /// (family, super chip, source, title) for `image`. pub fn identify( image: &[u8], mame_hash: &Path, ) -> Result<(String, bool, String, Option), UnsupportedCartridge> { let sha1 = sha1_hex(image); let list = mame_list(mame_hash); let entry = list.get(&sha1); if let Some((slot, ram, title)) = entry { if !slot.is_empty() { let Some((_, ours)) = MAME_SLOTS.iter().find(|(name, _)| name == slot) else { return Err(UnsupportedCartridge(format!("{title}: MAME slot {slot} is not built"))); }; let family = match ours { Some(f) => f.to_string(), None => SIZE_SCHEMES .iter() .find(|(s, _)| *s == image.len()) .map(|(_, f)| *f) .unwrap_or("?") .to_string(), }; let sc = *ram && ["F8", "F6", "F4"].contains(&family.as_str()); return Ok((family, sc, "MAME softlist".to_string(), Some(title.clone()))); } } let title = entry.map(|e| e.2.clone()); let family = detect(image).map_err(UnsupportedCartridge)?; let sc = ["F8", "F6", "F4"].contains(&family) && detect_super_chip(image); Ok((family.to_string(), sc, "detector".to_string(), title)) } // Schemes with an oscillator of their own (DPC's music: an RC on the cartridge, // DOC Horton; "an internally generated asynchronous clock", DOC Crane's patent // US 4,644,495; the slot carries no clock, DOC nocash), which so need the // console's CPU clock to count it in CPU cycles: its hertz are fixed, its ticks // per CPU cycle are not. Every other scheme counts CPU cycles only. // System::from_rom passes the row's clock; a host building through load() or // build() passes its own row's (None means the NTSC console's). pub const CLOCKED: [&str; 1] = ["DPC"]; /// `options.cpu_hz`: the console's CPU clock, handed to the [`CLOCKED`] schemes /// and ignored by the rest; None leaves each its NTSC default. pub fn build( image: &[u8], family: &str, super_chip: bool, mut options: Options, ) -> Result, UnsupportedCartridge> { if !CLOCKED.contains(&family) { options.cpu_hz = None; } let err = |e: String| UnsupportedCartridge(e); let ram_fill = options.ram_fill.unwrap_or(0); if family == "2K" || family == "4K" { return Ok(Box::new(Plain::new(image).map_err(err)?)); } if ["F8", "F6", "F4"].contains(&family) { return Ok(Box::new( Banked::new(image, family, super_chip, options.start_bank, ram_fill).map_err(err)?, )); } if !SCHEMES.contains(&family) { return Err(UnsupportedCartridge(format!("scheme {family} is not built"))); } let cartridge: Box = match family { "FA" => Box::new(Banked::new(image, "FA", false, options.start_bank, ram_fill).map_err(err)?), "E0" => Box::new(E0::new(image, options.start_slices.unwrap_or((4, 5, 6))).map_err(err)?), "3F" => Box::new(Tigervision3F::new(image, options.start_page).map_err(err)?), "FE" => Box::new(ActivisionFE::new(image, options.start_bank.unwrap_or(0)).map_err(err)?), "E7" => Box::new(MNetworkE7::new(image, options.start_page.unwrap_or(0), ram_fill).map_err(err)?), "CV" => Box::new(CommaVid::new(image, ram_fill).map_err(err)?), "UA" => Box::new(UA::new(image, options.start_bank.unwrap_or(0)).map_err(err)?), "F0" => Box::new(MegaboyF0::new(image, options.start_bank.unwrap_or(0)).map_err(err)?), "32IN1" => Box::new(ThirtyTwoInOne::new(image, options.game.unwrap_or(0)).map_err(err)?), "DPC" => Box::new( DPC::new( image, options.start_bank.unwrap_or(1), options.cpu_hz.unwrap_or(NTSC_CPU_HZ), options.music_hz.unwrap_or(MUSIC_HZ), ) .map_err(err)?, ), _ => Box::new(Supercharger::new(image, options.bios.as_deref(), options.tape_level, ram_fill).map_err(err)?), }; Ok(cartridge) } /// Read, identify and build a cartridge; `options` go to the scheme (`start_bank`). /// /// `options.cpu_hz` is the console's CPU clock for a clocked scheme ([`build`]), /// safe to pass for any cartridge: a host passes its row's /// `machine.timing.cpu_hz()`. pub fn load( rom: Rom, scheme: Option<&str>, super_chip: Option, mame_hash: &Path, options: Options, ) -> Result { let image: Vec = match rom { Rom::Bytes(bytes) => bytes.to_vec(), Rom::Path(path) => read_image(path).map_err(UnsupportedCartridge)?.0, }; let sha1 = sha1_hex(&image); let (family, sc, source, title) = match scheme { Some(scheme) => { let family = scheme.strip_suffix("SC").unwrap_or(scheme).to_string(); let sc = super_chip.unwrap_or(scheme.ends_with("SC")); (family, sc, "explicit".to_string(), None) } None => { let (family, mut sc, source, title) = identify(&image, mame_hash)?; if let Some(s) = super_chip { sc = s; } (family, sc, source, title) } }; let cartridge = build(&image, &family, sc, options)?; let scheme = cartridge.name().to_string(); Ok(Loaded { cartridge, scheme, source, title, sha1, }) } /// `load(rom)` with the defaults: identified, the default software list, no options. pub fn load_default(rom: Rom) -> Result { load(rom, None, None, &mame_hash(), Options::default()) } /// The software list's elements, read as `ElementTree` reads them for `_mame_list`. mod softlist { use super::SoftList; fn decode(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut rest = text; while let Some(at) = rest.find('&') { out.push_str(&rest[..at]); rest = &rest[at..]; let Some(end) = rest.find(';') else { break }; let entity = &rest[1..end]; let ch = match entity { "amp" => Some('&'), "lt" => Some('<'), "gt" => Some('>'), "quot" => Some('"'), "apos" => Some('\''), _ if entity.starts_with("#x") => u32::from_str_radix(&entity[2..], 16).ok().and_then(char::from_u32), _ if entity.starts_with('#') => entity[1..].parse().ok().and_then(char::from_u32), _ => None, }; match ch { Some(c) => { out.push(c); rest = &rest[end + 1..]; } None => { out.push('&'); rest = &rest[1..]; } } } out.push_str(rest); out } fn attributes(body: &str) -> Vec<(String, String)> { let mut out = Vec::new(); let mut rest = body; while let Some(eq) = rest.find('=') { let key = rest[..eq].trim().to_string(); let after = rest[eq + 1..].trim_start(); let Some(quote) = after.chars().next() else { break }; if quote != '"' && quote != '\'' { break; } let Some(close) = after[1..].find(quote) else { break }; out.push((key, decode(&after[1..1 + close]))); rest = &after[close + 2..]; } out } fn get<'a>(attrs: &'a [(String, String)], key: &str) -> Option<&'a str> { attrs.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()) } struct Part { slot: Option, ram: bool, roms: Vec, } pub fn parse(text: &str) -> SoftList { let mut table = SoftList::new(); let mut stack: Vec = Vec::new(); let mut software_name = String::new(); let mut description: Option = None; let mut in_description = false; let mut description_text = String::new(); let mut parts: Vec = Vec::new(); let mut part: Option = None; let mut rest = text; while let Some(open) = rest.find('<') { if in_description { description_text.push_str(&rest[..open]); } rest = &rest[open..]; if rest.starts_with("").map(|e| e + 3).unwrap_or(rest.len()); rest = &rest[end..]; continue; } if rest.starts_with("').map(|e| e + 1).unwrap_or(rest.len()); rest = &rest[end..]; continue; } let Some(close) = rest.find('>') else { break }; let tag = &rest[1..close]; rest = &rest[close + 1..]; if let Some(name) = tag.strip_prefix('/') { let name = name.trim(); stack.pop(); match name { "description" if in_description => { in_description = false; description = Some(decode(&description_text)); } "part" => { if let Some(p) = part.take() { parts.push(p); } } "software" => { let shown = match &description { Some(d) if !d.is_empty() => d.clone(), _ => software_name.clone(), }; for p in parts.drain(..) { for sha1 in p.roms { table.insert(sha1, (p.slot.clone().unwrap_or_default(), p.ram, shown.clone())); } } } _ => {} } continue; } let self_closing = tag.ends_with('/'); let body = tag.trim_end_matches('/'); let (name, attrs) = match body.find(char::is_whitespace) { Some(at) => (&body[..at], attributes(&body[at..])), None => (body, Vec::new()), }; let parent = stack.last().map(String::as_str); match name { "software" => { software_name = get(&attrs, "name").unwrap_or("").to_string(); description = None; parts.clear(); } "description" if parent == Some("software") && description.is_none() => { if self_closing { description = Some(String::new()); } else { in_description = true; description_text.clear(); } } "part" => { part = Some(Part { slot: None, ram: false, roms: Vec::new(), }) } "feature" => { if let Some(p) = part.as_mut() { if p.slot.is_none() && get(&attrs, "name") == Some("slot") { p.slot = get(&attrs, "value").map(String::from); } } } "dataarea" => { if let Some(p) = part.as_mut() { if get(&attrs, "name") == Some("ram") { p.ram = true; } } } "rom" => { if let (Some(p), Some(sha1)) = (part.as_mut(), get(&attrs, "sha1")) { if !sha1.is_empty() { p.roms.push(sha1.to_string()); } } } _ => {} } if !self_closing { stack.push(name.to_string()); } } table } }