//! A minimal libretro frontend: load the built core as a shared library, as //! RetroArch does, feed it a cartridge, run frames, check the picture moves //! and the sound arrives. Needs a dump: FAMICOM_LIBRETRO_ROM (skipped without); //! FAMICOM_LIBRETRO_SYSTEM is the system directory it reports (none without); //! FAMICOM_LIBRETRO_FRAMES how many frames it runs before the checks (600); //! FAMICOM_LIBRETRO_OPTIONS core options as "key=value,key=value". //! The save directory it reports is a fresh one under target/; with the //! Turbo File plugged (famicom_device=turbo-file) it checks the file is read //! and written back, with a Data Recorder (keyboard) the tape likewise //! through the deck's F9 key. use std::ffi::{c_char, c_uint, c_void}; use std::sync::atomic::{AtomicUsize, Ordering}; #[repr(C)] struct GameInfo { path: *const c_char, data: *const c_void, size: usize, meta: *const c_char, } #[repr(C)] #[derive(Default)] struct AvInfo { base_width: c_uint, base_height: c_uint, max_width: c_uint, max_height: c_uint, aspect: f32, fps: f64, sample_rate: f64, } static FRAMES: AtomicUsize = AtomicUsize::new(0); static QUIET: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); static SAMPLES: AtomicUsize = AtomicUsize::new(0); static LAST_HASH: AtomicUsize = AtomicUsize::new(0); static CHANGES: AtomicUsize = AtomicUsize::new(0); static HASHES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); /// The frontend's system directory: FAMICOM_LIBRETRO_SYSTEM, else none. fn system_directory() -> &'static std::ffi::CStr { static DIR: std::sync::OnceLock = std::sync::OnceLock::new(); DIR.get_or_init(|| { let dir = std::env::var("FAMICOM_LIBRETRO_SYSTEM").unwrap_or("/nonexistent".into()); std::ffi::CString::new(dir).unwrap() }) } /// The core options FAMICOM_LIBRETRO_OPTIONS sets. fn options() -> &'static [(String, std::ffi::CString)] { static OPTIONS: std::sync::OnceLock> = std::sync::OnceLock::new(); OPTIONS.get_or_init(|| { std::env::var("FAMICOM_LIBRETRO_OPTIONS") .unwrap_or_default() .split(',') .filter_map(|pair| pair.split_once('=')) .map(|(k, v)| (k.to_string(), std::ffi::CString::new(v).unwrap())) .collect() }) } /// The disk control interface the core registered (SET_DISK_CONTROL_EXT_INTERFACE). static DISK: std::sync::atomic::AtomicPtr = std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()); static MESSAGES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); /// The key held down (a RETROK_* code; 0: none). static KEY: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); /// The save directory reported: target/frontend-save, emptied of this test's files. fn save_directory() -> &'static std::ffi::CStr { static DIR: std::sync::OnceLock = std::sync::OnceLock::new(); DIR.get_or_init(|| { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("target/frontend-save"); std::fs::create_dir_all(&dir).unwrap(); std::ffi::CString::new(dir.to_str().unwrap()).unwrap() }) } #[repr(C)] struct DiskControlExt { set_eject_state: unsafe extern "C" fn(bool) -> bool, get_eject_state: unsafe extern "C" fn() -> bool, get_image_index: unsafe extern "C" fn() -> c_uint, set_image_index: unsafe extern "C" fn(c_uint) -> bool, get_num_images: unsafe extern "C" fn() -> c_uint, replace_image_index: unsafe extern "C" fn(c_uint, *const c_void) -> bool, add_image_index: unsafe extern "C" fn() -> bool, set_initial_image: unsafe extern "C" fn(c_uint, *const c_char) -> bool, get_image_path: unsafe extern "C" fn(c_uint, *mut c_char, usize) -> bool, get_image_label: unsafe extern "C" fn(c_uint, *mut c_char, usize) -> bool, } unsafe extern "C" fn environment(cmd: c_uint, data: *mut c_void) -> bool { match cmd { 6 => { // SET_MESSAGE: { const char *msg; unsigned frames; } let text = *(data as *const *const c_char); let text = std::ffi::CStr::from_ptr(text) .to_string_lossy() .into_owned(); eprintln!("message: {text}"); MESSAGES.lock().unwrap().push(text); true } 15 => { // GET_VARIABLE: { const char *key; const char *value; } from // FAMICOM_LIBRETRO_OPTIONS ("key=value,key=value"). let variable = data as *mut [*const c_char; 2]; let key = std::ffi::CStr::from_ptr((*variable)[0]) .to_string_lossy() .into_owned(); match options().iter().find(|(k, _)| *k == key) { Some((_, value)) => { (*variable)[1] = value.as_ptr(); true } None => false, } } 16 => true, 58 => { DISK.store(data as *mut DiskControlExt, Ordering::Relaxed); true } 9 => { *(data as *mut *const c_char) = system_directory().as_ptr(); true } 31 => { *(data as *mut *const c_char) = save_directory().as_ptr(); true } 10 | 11 => true, _ => false, } } unsafe extern "C" fn video(data: *const c_void, width: c_uint, height: c_uint, pitch: usize) { assert_eq!((width, height, pitch), (256, 240, 1024)); let pixels = std::slice::from_raw_parts(data as *const u32, 256 * 240); let hash = pixels .iter() .fold(0usize, |h, &p| h.wrapping_mul(31).wrapping_add(p as usize)); HASHES.lock().unwrap().push(hash); if LAST_HASH.swap(hash, Ordering::Relaxed) != hash { CHANGES.fetch_add(1, Ordering::Relaxed); } FRAMES.fetch_add(1, Ordering::Relaxed); } unsafe extern "C" fn audio_batch(_data: *const i16, frames: usize) -> usize { SAMPLES.fetch_add(frames, Ordering::Relaxed); frames } unsafe extern "C" fn input_poll() {} unsafe extern "C" fn input_state(_port: c_uint, device: c_uint, _index: c_uint, id: c_uint) -> i16 { if device == 3 { return i16::from(id != 0 && id == KEY.load(Ordering::Relaxed)); } // Start, now and then, so a game leaves its title screen. let frame = FRAMES.load(Ordering::Relaxed); i16::from(!QUIET.load(Ordering::Relaxed) && id == 3 && frame % 120 < 4) } #[test] fn runs_as_a_shared_library() { let Ok(rom) = std::env::var("FAMICOM_LIBRETRO_ROM") else { eprintln!("FAMICOM_LIBRETRO_ROM not set: skipped"); return; }; let data = std::fs::read(&rom).unwrap(); let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("target/release/libfamicom_libretro.so"); // cargo test does not always relink the copy here: refuse a stale one. let modified = |p: &std::path::Path| std::fs::metadata(p).and_then(|m| m.modified()).ok(); let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lib.rs"); assert!( modified(&path) >= modified(&source), "the core is older than src/lib.rs: cargo build --release first" ); unsafe { let lib = libloading::Library::new(&path) .expect("build the core with cargo build --release first"); macro_rules! f { ($name:literal, $t:ty) => { *lib.get::<$t>($name).unwrap() }; } f!( b"retro_set_environment", unsafe extern "C" fn(unsafe extern "C" fn(c_uint, *mut c_void) -> bool) )(environment); f!( b"retro_set_video_refresh", unsafe extern "C" fn(unsafe extern "C" fn(*const c_void, c_uint, c_uint, usize)) )(video); f!( b"retro_set_audio_sample_batch", unsafe extern "C" fn(unsafe extern "C" fn(*const i16, usize) -> usize) )(audio_batch); f!( b"retro_set_input_poll", unsafe extern "C" fn(unsafe extern "C" fn()) )(input_poll); f!( b"retro_set_input_state", unsafe extern "C" fn(unsafe extern "C" fn(c_uint, c_uint, c_uint, c_uint) -> i16) )(input_state); f!(b"retro_init", unsafe extern "C" fn())(); // The storage, seeded: a Turbo File's RAM and a tape (in another // spelling of the reference's JSON) for the game. let saves = std::path::Path::new(save_directory().to_str().unwrap()); let turbo_path = saves.join("turbo-file.sav"); let pattern: Vec = (0..0x2000u32).map(|i| (i * 7 + 3) as u8).collect(); std::fs::write(&turbo_path, &pattern).unwrap(); let rom_name = std::path::Path::new(&rom).file_name().unwrap(); let tape_path = saves.join(format!("{}.tape", rom_name.to_string_lossy())); std::fs::write(&tape_path, "[[0,1],\n[100 ,0]]").unwrap(); let rom_c = std::ffi::CString::new(rom.as_str()).unwrap(); let info = GameInfo { path: rom_c.as_ptr(), data: data.as_ptr() as *const c_void, size: data.len(), meta: std::ptr::null(), }; assert!(f!( b"retro_load_game", unsafe extern "C" fn(*const GameInfo) -> bool )(&info)); // The core and this frontend share the process's environment. if let Ok(dir) = std::env::var("FAMICOM_LIBRETRO_SYSTEM") { let db = std::path::Path::new(&dir).join("famicom-rust/nes20db.xml"); if db.is_file() { assert_eq!(std::env::var_os("FAMICOM_NES20DB"), Some(db.into())); println!("nes20db from the system directory"); } } let mut av = AvInfo::default(); f!( b"retro_get_system_av_info", unsafe extern "C" fn(*mut AvInfo) )(&mut av); assert_eq!( (av.base_width, av.base_height, av.sample_rate), (256, 240, 44_100.0) ); let run = f!(b"retro_run", unsafe extern "C" fn()); let began = std::time::Instant::now(); // FAMICOM_LIBRETRO_FRAMES: how long to run first (600). let length: usize = std::env::var("FAMICOM_LIBRETRO_FRAMES") .ok() .and_then(|n| n.parse().ok()) .unwrap_or(600); for _ in 0..length { run(); } let seconds = began.elapsed().as_secs_f64(); let frames = FRAMES.load(Ordering::Relaxed); let samples = SAMPLES.load(Ordering::Relaxed); eprintln!( "{frames} frames ({:.0} fps), {samples} stereo samples ({:.0} a frame), {} picture changes; fps {:.4}", frames as f64 / seconds, samples as f64 / frames as f64, CHANGES.load(Ordering::Relaxed), av.fps ); assert_eq!(frames, length); assert!((samples as f64 / length as f64 - 44_100.0 / av.fps).abs() < 2.0); // The picture moved (a still title screen, Duck Hunt's, changes a few times). assert!(CHANGES.load(Ordering::Relaxed) > 1); // A Disk System: the sides as images, out and in through the interface. let disk = DISK.load(Ordering::Relaxed); assert!( !disk.is_null(), "the core registered no disk control interface" ); let disk = &*disk; let sides = (disk.get_num_images)(); if sides > 0 { let mut label = [0 as c_char; 64]; assert!((disk.get_image_label)( sides - 1, label.as_mut_ptr(), label.len() )); let last = std::ffi::CStr::from_ptr(label.as_ptr()) .to_string_lossy() .into_owned(); assert!(!(disk.get_eject_state)()); let was = (disk.get_image_index)(); assert!( !(disk.set_image_index)(sides - 1), "a side chosen with the disk in" ); assert!((disk.set_eject_state)(true)); assert!((disk.get_eject_state)()); for _ in 0..30 { run(); } assert!((disk.set_image_index)(sides - 1)); assert!(!(disk.set_image_index)(sides), "a side past the last"); assert!((disk.set_eject_state)(false)); assert!(!(disk.get_eject_state)()); assert_eq!((disk.get_image_index)(), sides - 1); for _ in 0..30 { run(); } eprintln!("disk control: {sides} sides; side {was} out, {last} in"); } // The Data Recorder's deck: F9 plays the tape, again stops it and // writes it (as the reference writes it). let key_press = |frames: usize| { KEY.store(290, Ordering::Relaxed); // RETROK_F9 run(); KEY.store(0, Ordering::Relaxed); for _ in 0..frames { run(); } }; MESSAGES.lock().unwrap().clear(); key_press(10); let deck = MESSAGES.lock().unwrap().clone(); if deck.iter().any(|m| m == "tape: playing") { key_press(1); assert!(MESSAGES .lock() .unwrap() .iter() .any(|m| m == "tape: stopped")); assert_eq!( std::fs::read_to_string(&tape_path).unwrap(), "[[0, 1], [100, 0]]", "the tape was not read, or not written back" ); eprintln!("data recorder: tape read, played, stopped and written"); } else { assert!(!deck.iter().any(|m| m.starts_with("tape:")), "{deck:?}"); } // Save states through the API: serialize, run, unserialize, run again // (no input meanwhile, so both runs see the same). QUIET.store(true, Ordering::Relaxed); let size = f!(b"retro_serialize_size", unsafe extern "C" fn() -> usize)(); let mut state = vec![0u8; size]; assert!(f!( b"retro_serialize", unsafe extern "C" fn(*mut c_void, usize) -> bool )(state.as_mut_ptr() as *mut c_void, size)); let length = u32::from_le_bytes(state[..4].try_into().unwrap()); HASHES.lock().unwrap().clear(); for _ in 0..100 { run(); } let first: Vec = std::mem::take(&mut *HASHES.lock().unwrap()); assert!(f!( b"retro_unserialize", unsafe extern "C" fn(*const c_void, usize) -> bool )(state.as_ptr() as *const c_void, size)); for _ in 0..100 { run(); } let second: Vec = std::mem::take(&mut *HASHES.lock().unwrap()); eprintln!("save state: {length} bytes in a {size}-byte buffer; 100 frames replayed"); assert_eq!(first, second, "the frames after loading a state differ"); f!(b"retro_unload_game", unsafe extern "C" fn())(); f!(b"retro_deinit", unsafe extern "C" fn())(); // The Turbo File: read at load, written at unload (a game that never // writes it leaves the pattern; one never read would write zeros). let options = std::env::var("FAMICOM_LIBRETRO_OPTIONS").unwrap_or_default(); if options.contains("famicom_device=turbo-file") { assert_eq!(std::fs::read(&turbo_path).unwrap(), pattern); eprintln!("turbo file: read and written back"); } } }