//! famicom-rust as a libretro core. //! //! The libretro API (libretro.h, the parts a cartridge console needs) by hand: //! no bindings crate. One frame of [`System::run_frames`] per `retro_run`; //! video as XRGB8888 through the machine's pally palette (read from the //! frontend's system directory, `famicom-rust/.pal`, or grey without //! it: the palettes are not shipped); audio at 44,100 Hz, the board's mono //! samples duplicated to stereo 16-bit; four players; battery RAM as //! the frontend's save RAM; save states (famicom-rust's state.rs, length- //! prefixed in the frontend's fixed buffer); the Disk System's sides through //! the disk control interface and AutoDisk ([`disk`]); the peripherals through //! famicom-rust's `host` ([`input`]); the Turbo File's RAM and the Data //! Recorder's tape as files in the frontend's save directory ([`storage`]). //! //! The FDS BIOS comes from the system directory (`disksys.rom`), handed to //! the board's loader through `FAMICOM_FDS_BIOS`; nes20db, which says which //! board a dump really is, from `famicom-rust/nes20db.xml` there (the XML //! unpacked from the reference's pinned 7z), through `FAMICOM_NES20DB`. #![allow(clippy::missing_safety_doc)] mod disk; mod input; mod storage; use famicom_rust::host; use famicom_rust::peripherals::Plugged; use famicom_rust::video::load_palette; use famicom_rust::{Machine, System}; use std::ffi::{c_char, c_uint, c_void, CStr}; use std::path::PathBuf; use std::ptr; use std::sync::Mutex; // -- libretro.h, the parts used ------------------------------------------------- pub const RETRO_API_VERSION: c_uint = 1; const RETRO_ENVIRONMENT_SET_MESSAGE: c_uint = 6; const RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY: c_uint = 9; const RETRO_ENVIRONMENT_SET_PIXEL_FORMAT: c_uint = 10; const RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS: c_uint = 11; const RETRO_ENVIRONMENT_GET_VARIABLE: c_uint = 15; const RETRO_ENVIRONMENT_SET_VARIABLES: c_uint = 16; const RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE: c_uint = 17; const RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY: c_uint = 31; const RETRO_PIXEL_FORMAT_XRGB8888: c_uint = 1; const RETRO_DEVICE_JOYPAD: c_uint = 1; const RETRO_MEMORY_SAVE_RAM: c_uint = 0; const RETRO_REGION_NTSC: c_uint = 0; const RETRO_REGION_PAL: c_uint = 1; // RETRO_DEVICE_ID_JOYPAD_* const ID_B: c_uint = 0; const ID_SELECT: c_uint = 2; const ID_START: c_uint = 3; const ID_UP: c_uint = 4; const ID_DOWN: c_uint = 5; const ID_LEFT: c_uint = 6; const ID_RIGHT: c_uint = 7; const ID_A: c_uint = 8; pub type EnvironmentFn = unsafe extern "C" fn(cmd: c_uint, data: *mut c_void) -> bool; pub type VideoRefreshFn = unsafe extern "C" fn(data: *const c_void, width: c_uint, height: c_uint, pitch: usize); pub type AudioSampleFn = unsafe extern "C" fn(left: i16, right: i16); pub type AudioSampleBatchFn = unsafe extern "C" fn(data: *const i16, frames: usize) -> usize; pub type InputPollFn = unsafe extern "C" fn(); pub type InputStateFn = unsafe extern "C" fn(port: c_uint, device: c_uint, index: c_uint, id: c_uint) -> i16; #[repr(C)] pub struct RetroSystemInfo { pub library_name: *const c_char, pub library_version: *const c_char, pub valid_extensions: *const c_char, pub need_fullpath: bool, pub block_extract: bool, } #[repr(C)] pub struct RetroGameGeometry { pub base_width: c_uint, pub base_height: c_uint, pub max_width: c_uint, pub max_height: c_uint, pub aspect_ratio: f32, } #[repr(C)] pub struct RetroSystemTiming { pub fps: f64, pub sample_rate: f64, } #[repr(C)] pub struct RetroSystemAvInfo { pub geometry: RetroGameGeometry, pub timing: RetroSystemTiming, } #[repr(C)] pub struct RetroGameInfo { pub path: *const c_char, pub data: *const c_void, pub size: usize, pub meta: *const c_char, } #[repr(C)] struct RetroVariable { key: *const c_char, value: *const c_char, } #[repr(C)] struct RetroMessage { msg: *const c_char, frames: c_uint, } /// The core option: AutoDisk on or off (on, as in the reference's window). const AUTO_DISK_KEY: &CStr = c"famicom_auto_disk"; /// The core option: the peripheral (the reference window's `--device`). const DEVICE_KEY: &CStr = c"famicom_device"; #[repr(C)] struct RetroInputDescriptor { port: c_uint, device: c_uint, index: c_uint, id: c_uint, description: *const c_char, } // -- the core's state ------------------------------------------------------------- pub const SAMPLE_RATE: i64 = 44_100; struct Callbacks { environment: Option, video: Option, audio_batch: Option, input_poll: Option, input_state: Option, } struct Core { system: System, palette: Vec<[u8; 3]>, frame: Vec, audio: Vec, /// The frontend's view of the battery RAM, synced each frame. save: Vec, save_pushed: bool, /// The fixed size `retro_serialize_size` reports (state::size_bound). state_size: usize, /// The peripheral plugged at load (famicom_rust::host). plugged: Plugged, /// The Turbo File's and the tape's files. storage: storage::Storage, } // SAFETY: libretro calls a core from one thread; the lock only gives the // statics a Rust-sound home. unsafe impl Send for Core {} static CALLBACKS: Mutex = Mutex::new(Callbacks { environment: None, video: None, audio_batch: None, input_poll: None, input_state: None, }); static CORE: Mutex> = Mutex::new(None); fn system_directory() -> Option { directory(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY) } fn save_directory() -> Option { directory(RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY) } /// A directory the frontend names (GET_SYSTEM_DIRECTORY, GET_SAVE_DIRECTORY). fn directory(command: c_uint) -> Option { let environment = CALLBACKS.lock().unwrap().environment?; let mut dir: *const c_char = ptr::null(); // SAFETY: the command writes a C string pointer the frontend owns. let ok = unsafe { environment(command, &mut dir as *mut _ as *mut c_void) }; if !ok || dir.is_null() { return None; } // SAFETY: a NUL-terminated string from the frontend. let text = unsafe { CStr::from_ptr(dir) } .to_string_lossy() .into_owned(); Some(PathBuf::from(text)) } /// The reference's grey stand-in (`peripherals.grey_palette`): each 9-bit /// value as its row's luma, columns $D-$F black. fn grey_palette() -> Vec<[u8; 3]> { let levels = [102u8, 173, 255, 255]; (0..512usize) .map(|value| { let (column, row) = (value & 0x0F, (value >> 4) & 3); let grey = if column >= 0x0D { 0 } else { levels[row] }; [grey, grey, grey] }) .collect() } // -- the API ---------------------------------------------------------------------- #[no_mangle] pub extern "C" fn retro_api_version() -> c_uint { RETRO_API_VERSION } #[no_mangle] pub unsafe extern "C" fn retro_get_system_info(info: *mut RetroSystemInfo) { *info = RetroSystemInfo { library_name: c"famicom-rust".as_ptr(), library_version: c"0.1.0".as_ptr(), // No "zip": the frontend unpacks archives and hands over the ROM's // bytes; a core that lists zip is given the archive itself. valid_extensions: c"nes|fds|qd".as_ptr(), need_fullpath: false, block_extract: false, }; } #[no_mangle] pub unsafe extern "C" fn retro_get_system_av_info(info: *mut RetroSystemAvInfo) { let core = CORE.lock().unwrap(); let timing = match core.as_ref() { Some(core) => core.system.cpu.bus.machine.timing.clone(), None => Machine::famicom().timing, }; // Frames a second: master clock / (dots per frame x master ticks a dot); // NTSC's odd frames are a dot short with rendering on, ignored here. let fps = timing.master_hz / (timing.lines as f64 * 341.0 * timing.dot_divider as f64); *info = RetroSystemAvInfo { geometry: RetroGameGeometry { base_width: 256, base_height: 240, max_width: 256, max_height: 240, aspect_ratio: 4.0 / 3.0, }, timing: RetroSystemTiming { fps, sample_rate: SAMPLE_RATE as f64, }, }; } #[no_mangle] pub unsafe extern "C" fn retro_set_environment(callback: EnvironmentFn) { CALLBACKS.lock().unwrap().environment = Some(callback); let mut variables = [ RetroVariable { key: AUTO_DISK_KEY.as_ptr(), value: c"FDS: change disk sides automatically; enabled|disabled".as_ptr(), }, RetroVariable { key: DEVICE_KEY.as_ptr(), value: c"Peripheral (applies when a game loads); auto|pads|four-score|famicom-four-players|zapper|two-zappers|power-pad|family-trainer|vaus|hyper-shot|keyboard|subor-keyboard|snes-mouse|snes-pads|turbo-file|rob".as_ptr(), }, RetroVariable { key: ptr::null(), value: ptr::null(), }, ]; callback( RETRO_ENVIRONMENT_SET_VARIABLES, variables.as_mut_ptr() as *mut c_void, ); let ext = &disk::CONTROL as *const disk::DiskControlExt as *mut c_void; if !callback(disk::RETRO_ENVIRONMENT_SET_DISK_CONTROL_EXT_INTERFACE, ext) { let base = &disk::CONTROL.base as *const disk::DiskControl as *mut c_void; callback(disk::RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, base); } } /// A core option's value from the frontend, if it gives one. fn option(key: &CStr) -> Option { let environment = CALLBACKS.lock().unwrap().environment?; let mut variable = RetroVariable { key: key.as_ptr(), value: ptr::null(), }; // SAFETY: GET_VARIABLE fills `value` with a string the frontend owns. unsafe { if !environment( RETRO_ENVIRONMENT_GET_VARIABLE, &mut variable as *mut _ as *mut c_void, ) || variable.value.is_null() { return None; } Some( CStr::from_ptr(variable.value) .to_string_lossy() .into_owned(), ) } } /// The AutoDisk option (enabled without one). fn auto_disk_option() -> bool { option(AUTO_DISK_KEY).as_deref() != Some("disabled") } /// The peripheral option's expansion number (None: the cartridge's own). fn device_option() -> Option { let name = option(DEVICE_KEY)?; input::DEVICES .iter() .find(|(key, _)| *key == name) .and_then(|(_, number)| *number) } /// AutoDisk on the board when the option says so and the cartridge is a Disk System. fn apply_auto_disk(system: &mut System, enabled: bool) { let board = system.board(); if !enabled { board.auto_disk = None; } else if board.auto_disk.is_none() { if let Some(fds) = board.ppu.cart.fds() { board.auto_disk = Some(Box::new(famicom_rust::fds_auto::AutoDisk::new(fds))); } } } /// A short message on the frontend's screen. fn show(environment: EnvironmentFn, text: &str) { let Ok(text) = std::ffi::CString::new(text) else { return; }; let mut message = RetroMessage { msg: text.as_ptr(), frames: 180, }; // SAFETY: the frontend copies the message during the call. unsafe { environment( RETRO_ENVIRONMENT_SET_MESSAGE, &mut message as *mut _ as *mut c_void, ); } } #[no_mangle] pub extern "C" fn retro_set_video_refresh(callback: VideoRefreshFn) { CALLBACKS.lock().unwrap().video = Some(callback); } #[no_mangle] pub extern "C" fn retro_set_audio_sample(_callback: AudioSampleFn) {} #[no_mangle] pub extern "C" fn retro_set_audio_sample_batch(callback: AudioSampleBatchFn) { CALLBACKS.lock().unwrap().audio_batch = Some(callback); } #[no_mangle] pub extern "C" fn retro_set_input_poll(callback: InputPollFn) { CALLBACKS.lock().unwrap().input_poll = Some(callback); } #[no_mangle] pub extern "C" fn retro_set_input_state(callback: InputStateFn) { CALLBACKS.lock().unwrap().input_state = Some(callback); } #[no_mangle] pub extern "C" fn retro_set_controller_port_device(_port: c_uint, _device: c_uint) {} #[no_mangle] pub extern "C" fn retro_init() {} #[no_mangle] pub extern "C" fn retro_deinit() { retro_unload_game(); } #[no_mangle] pub unsafe extern "C" fn retro_load_game(game: *const RetroGameInfo) -> bool { if game.is_null() || (*game).data.is_null() { return false; } let data = std::slice::from_raw_parts((*game).data as *const u8, (*game).size).to_vec(); let game_path = (!(*game).path.is_null()) .then(|| PathBuf::from(CStr::from_ptr((*game).path).to_string_lossy().into_owned())); let environment = CALLBACKS.lock().unwrap().environment; if let Some(environment) = environment { let mut format = RETRO_PIXEL_FORMAT_XRGB8888; if !environment( RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &mut format as *mut _ as *mut c_void, ) { return false; } let names: [(c_uint, &CStr); 8] = [ (ID_LEFT, c"Left"), (ID_UP, c"Up"), (ID_DOWN, c"Down"), (ID_RIGHT, c"Right"), (ID_B, c"B"), (ID_A, c"A"), (ID_SELECT, c"Select"), (ID_START, c"Start"), ]; let mut descriptors: Vec = (0..2) .flat_map(|port| { names.iter().map(move |&(id, name)| RetroInputDescriptor { port, device: RETRO_DEVICE_JOYPAD, index: 0, id, description: name.as_ptr(), }) }) .collect(); descriptors.push(RetroInputDescriptor { port: 0, device: 0, index: 0, id: 0, description: ptr::null(), }); environment( RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, descriptors.as_mut_ptr() as *mut c_void, ); } let system_dir = system_directory(); if let Some(dir) = &system_dir { let bios = dir.join("disksys.rom"); if bios.is_file() && std::env::var_os("FAMICOM_FDS_BIOS").is_none() { std::env::set_var("FAMICOM_FDS_BIOS", bios); } // nes20db, unpacked (a handheld has no 7z program): before the first // load, which reads it once. let db = dir.join("famicom-rust").join("nes20db.xml"); if db.is_file() && std::env::var_os("FAMICOM_NES20DB").is_none() { std::env::set_var("FAMICOM_NES20DB", db); } } let machine = match System::machine_for(&data) { Ok(machine) => machine, Err(_) => return false, }; let mut system = match System::from_rom(&data, machine.clone(), None) { Ok(system) => system, Err(_) => return false, }; system.board().set_sample_rate(SAMPLE_RATE); apply_auto_disk(&mut system, auto_disk_option()); // The window's power-on choice: the option's device, else the cartridge's // (nes20db or the header), the NES Vaus as the Famicom's on a Famicom, // and a Famicom's players 3 and 4 when the expansion port is free. let device = device_option().unwrap_or_else(|| system.image.as_ref().map_or(0, |i| i.board.expansion)); let famicom = system.cpu.bus.machine.famicom_expansion_port; let timing = &machine.timing; let palette = system_dir .map(|dir| dir.join("famicom-rust").join(timing.palette)) .and_then(|path| load_palette(&path, timing.swapped_emphasis).ok()) .unwrap_or_else(grey_palette); // The light guns judge light on the picture's palette: the reference's // pally palette when the system directory has it, as in its window. let plugged = host::plug_for_host(system.board(), device, famicom, Some(palette.clone())); let storage = storage::Storage::load(system.board(), save_directory(), game_path.as_deref()); *disk::CHOSEN.lock().unwrap() = 0; let save = system.board().cart().battery_ram().unwrap_or_default(); let state_size = 4 + famicom_rust::state::size_bound(&system); *CORE.lock().unwrap() = Some(Core { system, palette, frame: vec![0; 256 * 240], audio: Vec::new(), save, save_pushed: false, state_size, plugged, storage, }); true } #[no_mangle] pub extern "C" fn retro_load_game_special( _type: c_uint, _info: *const RetroGameInfo, _num: usize, ) -> bool { false } #[no_mangle] pub extern "C" fn retro_unload_game() { if let Some(mut core) = CORE.lock().unwrap().take() { core.storage.save(core.system.board()); } } #[no_mangle] pub extern "C" fn retro_get_region() -> c_uint { match CORE.lock().unwrap().as_ref() { Some(core) if core.system.cpu.bus.machine.timing.lines != 262 => RETRO_REGION_PAL, _ => RETRO_REGION_NTSC, } } #[no_mangle] pub extern "C" fn retro_reset() { if let Some(core) = CORE.lock().unwrap().as_mut() { core.system.reset(); } } #[no_mangle] pub unsafe extern "C" fn retro_run() { let (callbacks, environment) = { let c = CALLBACKS.lock().unwrap(); ( (c.video, c.audio_batch, c.input_poll, c.input_state), c.environment, ) }; let mut updated = false; if let Some(environment) = environment { environment( RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &mut updated as *mut bool as *mut c_void, ); } let auto_disk = updated.then(auto_disk_option); let mut guard = CORE.lock().unwrap(); let Some(core) = guard.as_mut() else { return }; let (video, audio_batch, input_poll, input_state) = callbacks; if let Some(enabled) = auto_disk { apply_auto_disk(&mut core.system, enabled); } if !core.save_pushed { // The frontend fills the save RAM after loading the game: hand it to the cartridge once. core.save_pushed = true; if !core.save.is_empty() { let save = core.save.clone(); core.system.board().cart().restore_battery(&save); } } if let Some(poll) = input_poll { poll(); } if let Some(state) = input_state { let input = input::read(state); host::apply( core.system.board(), &mut core.plugged, &input, host::VAUS_LOW, ); if let Some(message) = core.storage.frame(core.system.board(), &input) { if let Some(environment) = environment { show(environment, message); } } } core.system.run_frames(1); if let Some(command) = host::after_frame(core.system.board(), &mut core.plugged) { if let Some(environment) = environment { show(environment, &format!("R.O.B.: {command}")); } } if let Some(auto) = core.system.board().auto_disk.as_mut() { for message in auto.messages.drain(..) { if let Some(environment) = environment { show(environment, &message); } } } let picture = &core.system.cpu.bus.ppu.picture; for (pixel, &value) in core.frame.iter_mut().zip(picture.iter()) { let [r, g, b] = core.palette[value as usize & 0x1FF]; *pixel = (r as u32) << 16 | (g as u32) << 8 | b as u32; } if let Some(video) = video { video(core.frame.as_ptr() as *const c_void, 256, 240, 256 * 4); } let samples = core.system.take_samples(); core.audio.clear(); for sample in samples { let value = (sample * 32767.0) .round_ties_even() .clamp(-32768.0, 32767.0) as i16; core.audio.push(value); core.audio.push(value); } if let Some(batch) = audio_batch { let mut done = 0; let frames = core.audio.len() / 2; while done < frames { let wrote = batch(core.audio.as_ptr().add(done * 2), frames - done); if wrote == 0 { break; } done += wrote; } } if let Some(ram) = core.system.board().cart().battery_ram() { if ram.len() == core.save.len() { core.save.copy_from_slice(&ram); } } } #[no_mangle] pub extern "C" fn retro_serialize_size() -> usize { match CORE.lock().unwrap().as_ref() { Some(core) => core.state_size, None => 0, } } /// A state: its length (4 bytes, little-endian), then famicom-rust's state. #[no_mangle] pub unsafe extern "C" fn retro_serialize(data: *mut c_void, size: usize) -> bool { let guard = CORE.lock().unwrap(); let Some(core) = guard.as_ref() else { return false; }; let state = famicom_rust::state::save_state(&core.system); if data.is_null() || state.len() + 4 > size { return false; } let out = std::slice::from_raw_parts_mut(data as *mut u8, size); out[..4].copy_from_slice(&(state.len() as u32).to_le_bytes()); out[4..4 + state.len()].copy_from_slice(&state); out[4 + state.len()..].fill(0); true } #[no_mangle] pub unsafe extern "C" fn retro_unserialize(data: *const c_void, size: usize) -> bool { let mut guard = CORE.lock().unwrap(); let Some(core) = guard.as_mut() else { return false; }; if data.is_null() || size < 4 { return false; } let bytes = std::slice::from_raw_parts(data as *const u8, size); let length = u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize; if 4 + length > size { return false; } famicom_rust::state::load_state(&mut core.system, &bytes[4..4 + length]).is_ok() } #[no_mangle] pub extern "C" fn retro_cheat_reset() {} #[no_mangle] pub extern "C" fn retro_cheat_set(_index: c_uint, _enabled: bool, _code: *const c_char) {} #[no_mangle] pub extern "C" fn retro_get_memory_data(id: c_uint) -> *mut c_void { let mut guard = CORE.lock().unwrap(); match guard.as_mut() { Some(core) if id == RETRO_MEMORY_SAVE_RAM && !core.save.is_empty() => { core.save.as_mut_ptr() as *mut c_void } _ => ptr::null_mut(), } } #[no_mangle] pub extern "C" fn retro_get_memory_size(id: c_uint) -> usize { match CORE.lock().unwrap().as_ref() { Some(core) if id == RETRO_MEMORY_SAVE_RAM => core.save.len(), _ => 0, } }