// SPDX-License-Identifier: MIT //! The A78 header: parse it into description fields, and write one (the converter). //! //! Specification: the 7800 Development Wiki's "A78 Header Specification" //! (`reference/8bitdev-wiki/a78-header-spec.txt` of the reference, page revision 1120) //! and its reference assembly header `a78header.asm` v4.2. `7800header.c` (GPL) is //! not consulted. Offsets: //! //! ```text //! 0 version | 1-16 "ATARI7800" + zeros | 17-48 title | 49-52 payload size (big //! endian) | 53-54 cart type (big endian bits) | 55, 56 controllers | 57 TV | //! 58 save device | 63 pass-through (bit 0 XM) | v4: 64 mapper, 65 mapper //! options, 66-67 audio, 68-69 interrupt | 100-127 "ACTUAL CART DATA STARTS HERE" //! ``` //! //! v4 fields win over v3 fields in a v4 header (the specification says so). //! //! Every offset, bit and table below is the file format as the specification gives it //! (DOC: the wiki's A78 header specification, page revision 1120); none is a console //! behaviour. //! //! Rust-forced differences (a7800-python `cartridge/a78.py` at d6b220d): `Header.fields` //! is an ordered list of `(name, Value)` (the reference's dict, in its insertion //! order); `HeaderError` is an error value; the title is decoded as Latin-1 by bytes. use super::description::{CartDescription, Value}; pub const HEADER: usize = 128; pub const MAGIC: &[u8] = b"ATARI7800"; pub const END_MAGIC: &[u8] = b"ACTUAL CART DATA STARTS HERE"; pub const CART_TYPE_BITS: [&str; 16] = [ "pokey@4000", "supergame", "ram@4000", "rom@4000", "bank6@4000", "banked-ram", "pokey@450", "mirror-ram@4000", "activision", "absolute", "pokey@440", "ym2151@460", "souper", "banksets", "halt-banked-ram", "pokey@800", ]; pub const CONTROLLERS: [&str; 13] = [ "none", "proline", "lightgun", "paddle", "trakball", "joystick2600", "driving", "keypad", "st-mouse", "amiga-mouse", "savekey", "snes2atari", "mega7800", ]; pub const MAPPERS: [&str; 5] = ["linear", "supergame", "activision", "absolute", "souper"]; pub const LINEAR_4000: [&str; 4] = ["none", "ram16", "ram8-mirror", "ram32-halt"]; pub const SUPERGAME_4000: [&str; 7] = [ "none", "ram16", "ram8-mirror", "ram32-halt", "rom", "fixed-bank", "ram32-latch", ]; pub const AUDIO_POKEY: [&[u16]; 6] = [&[], &[0x440], &[0x450], &[0x450, 0x440], &[0x800], &[0x4000]]; /// A header whose fields cannot be built (contradictory cart-type bits, a bad size). #[derive(Clone, Debug, PartialEq, Eq)] pub struct HeaderError(pub String); impl std::fmt::Display for HeaderError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Header { pub version: u8, pub title: String, pub size: usize, pub fields: Vec<(&'static str, Value)>, // description fields this header states pub raw_cart_type: u16, } impl Header { pub fn field(&self, name: &str) -> Option<&Value> { self.fields.iter().find(|(n, _)| *n == name).map(|(_, v)| v) } fn put(&mut self, name: &'static str, value: Value) { match self.fields.iter_mut().find(|(n, _)| *n == name) { Some(entry) => entry.1 = value, None => self.fields.push((name, value)), } } } pub fn is_a78(data: &[u8]) -> bool { data.len() >= HEADER && &data[1..10] == MAGIC } fn latin1(bytes: &[u8]) -> String { bytes.iter().map(|&b| b as char).collect() } fn str_of(value: Option<&Value>) -> String { match value { Some(Value::Str(s)) => s.clone(), _ => String::new(), } } /// The header's statements as CartDescription fields (strictly what it says). pub fn parse(data: &[u8]) -> Result { if !is_a78(data) { return Err(HeaderError("not an A78 header".to_string())); } let version = data[0]; let raw_title = &data[17..49]; let end = raw_title.iter().position(|&b| b == 0).unwrap_or(raw_title.len()); let title = latin1(&raw_title[..end]).trim().to_string(); let size = u32::from_be_bytes([data[49], data[50], data[51], data[52]]) as usize; let bits = (data[53] as u16) << 8 | data[54] as u16; let names: Vec<&str> = CART_TYPE_BITS .iter() .enumerate() .filter(|(i, _)| bits >> i & 1 != 0) .map(|(_, n)| *n) .collect(); let has = |n: &str| names.contains(&n); let mut header = Header { version, title, size, fields: Vec::new(), raw_cart_type: bits, }; // v3 cart type let scheme = if has("souper") { "souper" } else if has("activision") { "activision" } else if has("absolute") { "absolute" } else if has("supergame") { "supergame" } else { "linear" }; let schemes = ["activision", "absolute", "souper"].iter().filter(|n| has(n)).count(); if schemes > 1 { let mut sorted: Vec<&str> = names.clone(); sorted.sort(); return Err(HeaderError(format!( "cart type ${bits:04X}: more than one bank scheme ({sorted:?})" ))); } let at: Vec<&str> = ["ram@4000", "rom@4000", "bank6@4000", "mirror-ram@4000", "pokey@4000"] .into_iter() .filter(|n| has(n)) .collect(); if at.len() > 1 { return Err(HeaderError(format!( "cart type ${bits:04X}: more than one device at $4000 ({at:?})" ))); } let mut at_4000 = match at.first().copied().unwrap_or("") { "ram@4000" => "ram16", "rom@4000" => "rom", "bank6@4000" => "fixed-bank", "mirror-ram@4000" => "mirror-ram-2k", "pokey@4000" => "pokey", _ => "none", }; if at_4000 == "ram16" && has("banked-ram") { at_4000 = "ram32-latch"; } if (at_4000 == "ram16" || at_4000 == "none") && has("halt-banked-ram") { // DOC, the wiki's bankset page: bit 14 alone marks the bankset RAM at $4000 at_4000 = "ram32-halt"; } let pokey: Vec = [ ("pokey@450", 0x450), ("pokey@440", 0x440), ("pokey@800", 0x800), ("pokey@4000", 0x4000), ] .into_iter() .filter(|(n, _)| has(n)) .map(|(_, a)| a) .collect(); header.put("scheme", Value::s(scheme)); header.put("at_4000", Value::s(at_4000)); header.put("pokey", Value::Pokey(pokey)); header.put("bankset", Value::Bool(has("banksets"))); header.put("ym2151", Value::Bool(has("ym2151@460"))); if version >= 4 { let mapper = data[64] as usize; if mapper >= MAPPERS.len() { return Err(HeaderError(format!("v4 mapper {mapper} is not defined"))); } let options = data[65]; header.put("scheme", Value::s(MAPPERS[mapper])); header.put("bankset", Value::Bool(options & 0x80 != 0)); if mapper == 0 { let choice = (options & 0x03) as usize; header.put("at_4000", Value::s(LINEAR_4000[choice])); } else if mapper == 1 { let choice = (options & 0x07) as usize; if choice >= SUPERGAME_4000.len() { return Err(HeaderError(format!("v4 SuperGame option {choice} is not defined"))); } header.put("at_4000", Value::s(SUPERGAME_4000[choice])); } let audio = (data[66] as u16) << 8 | data[67] as u16; if (audio & 7) as usize >= AUDIO_POKEY.len() { return Err(HeaderError(format!( "v4 audio POKEY field {} is not defined", audio & 7 ))); } let pokey = AUDIO_POKEY[(audio & 7) as usize].to_vec(); header.put("pokey", Value::Pokey(pokey.clone())); if pokey == [0x4000] && str_of(header.field("at_4000")) == "none" { header.put("at_4000", Value::s("pokey")); } header.put("ym2151", Value::Bool(audio & 0x08 != 0)); header.put("covox", Value::Bool(audio & 0x10 != 0)); header.put("adpcm", Value::Bool(audio & 0x20 != 0)); let irq = (data[68] as u16) << 8 | data[69] as u16; let sources: Vec = ["pokey1", "pokey2", "ym2151"] .iter() .enumerate() .filter(|(i, _)| irq >> i & 1 != 0) .map(|(_, n)| n.to_string()) .collect(); header.put("irq_sources", Value::Strings(sources)); } let bupchip = str_of(header.field("scheme")) == "souper"; header.put("bupchip", Value::Bool(bupchip)); let controller = |c: u8| { if (c as usize) < CONTROLLERS.len() { CONTROLLERS[c as usize].to_string() } else { format!("unknown-{c}") } }; header.put("controllers", Value::Pair(controller(data[55]), controller(data[56]))); let tv = data[57]; let region = if tv & 4 != 0 { "both" } else if tv & 1 != 0 { "pal" } else { "ntsc" }; header.put("region", Value::s(region)); header.put("composite_artifacts", Value::Bool(tv & 2 != 0)); header.put("hsc", Value::Bool(data[58] & 1 != 0)); header.put("save", Value::s(if data[58] & 2 != 0 { "savekey" } else { "none" })); header.put("xm", Value::Bool(data[63] & 1 != 0)); Ok(header) } /// A v4 header (with the v3 fields filled for older readers) stating `desc`. pub fn build(desc: &CartDescription, version: u8) -> Result, HeaderError> { if desc.console != "7800" { return Err(HeaderError("an A78 header describes 7800 cartridges only".to_string())); } let mut bits: u16 = 0; let mut bit = |name: &str| { bits |= 1 << CART_TYPE_BITS.iter().position(|n| *n == name).expect("a cart-type bit"); }; if desc.scheme == "supergame" { bit("supergame"); } else if ["activision", "absolute", "souper"].contains(&desc.scheme.as_str()) { bit(&desc.scheme); } let v3_at: &[&str] = match desc.at_4000.as_str() { "ram16" => &["ram@4000"], "ram32-latch" => &["ram@4000", "banked-ram"], "ram32-halt" => &["ram@4000", "halt-banked-ram"], "rom" => &["rom@4000"], "fixed-bank" => &["bank6@4000"], "mirror-ram-2k" => &["mirror-ram@4000"], "ram8-mirror" => &["ram@4000"], _ => &[], }; for name in v3_at { bit(name); } for (address, name) in [ (0x4000, "pokey@4000"), (0x450, "pokey@450"), (0x440, "pokey@440"), (0x800, "pokey@800"), ] { if desc.pokey.contains(&address) { bit(name); } } if desc.ym2151 { bit("ym2151@460"); } if desc.bankset { bit("banksets"); } let mut out = vec![0u8; HEADER]; out[0] = version; out[1..10].copy_from_slice(MAGIC); let mut title: Vec = desc .title .chars() .map(|c| if (c as u32) < 256 { c as u8 } else { b'?' }) .collect(); title.truncate(32); title.resize(32, 0); out[17..49].copy_from_slice(&title); out[49..53].copy_from_slice(&(desc.payload.len() as u32).to_be_bytes()); out[53..55].copy_from_slice(&bits.to_be_bytes()); let index = |name: &str| { CONTROLLERS .iter() .position(|n| *n == name) .map(|i| i as u8) .unwrap_or(1) }; out[55] = index(&desc.controllers.0); out[56] = index(&desc.controllers.1); out[57] = (desc.region == "pal") as u8 | (desc.composite_artifacts as u8) << 1 | ((desc.region == "both") as u8) << 2; out[58] = desc.hsc as u8 | ((desc.save == "savekey") as u8) << 1; out[63] = desc.xm as u8; if version >= 4 { out[64] = MAPPERS.iter().position(|m| *m == desc.scheme).expect("a mapper") as u8; let table: &[&str] = if desc.scheme == "linear" { &LINEAR_4000 } else { &SUPERGAME_4000 }; let option = table.iter().position(|o| *o == desc.at_4000).unwrap_or(0) as u8; out[65] = option | if desc.bankset { 0x80 } else { 0 }; let mut audio = AUDIO_POKEY .iter() .position(|p| *p == desc.pokey.as_slice()) .unwrap_or(0) as u16; audio |= (desc.ym2151 as u16) << 3 | (desc.covox as u16) << 4 | (desc.adpcm as u16) << 5; out[66..68].copy_from_slice(&audio.to_be_bytes()); let irq: u16 = ["pokey1", "pokey2", "ym2151"] .iter() .enumerate() .filter(|(_, n)| desc.irq_sources.iter().any(|s| s == *n)) .map(|(i, _)| 1u16 << i) .sum(); out[68..70].copy_from_slice(&irq.to_be_bytes()); } out[100..128].copy_from_slice(END_MAGIC); Ok(out) }