neser 0.1.1

NESER - NES Emulator in Rust - is a NES emulator written in Rust. It aims to be a high-quality, hardware-accurate emulator that is also easy to use and extend. It supports a wide range of NES games and features, including various mappers, audio processing, and input handling. NESER is designed to be modular and extensible, allowing developers to easily add new features or support for additional hardware. It can be run using one of two frontends: a native desktop application using SDL2, or a web application using WebAssembly. The desktop application provides a high-performance, feature-rich experience with support for various input devices and display options, while the web application allows users to play NES games directly in their browsers without needing to install any software in a BYOR manner (Bring Your Own Roms).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
// Helper functions for NES2 size parsing were moved to the centralized parser
// in `src/cartridge/ines.rs`. The local copies were removed to avoid
// dead-code warnings.

use neser::cartridge::{ConsoleType, ParsedRom, RomDb, RomParseError, TimingMode};

const DEFAULT_LIST_ROOT: &str = "roms/games";

#[derive(Debug, Clone, PartialEq, Eq)]
enum Command {
    List(std::path::PathBuf),
    Info(std::path::PathBuf),
    InfoAll,
}

fn parse_command(args: &[String]) -> Result<Command, String> {
    match args {
        [command] if command == "list" => {
            Ok(Command::List(std::path::PathBuf::from(DEFAULT_LIST_ROOT)))
        }
        [command, path] if command == "list" => Ok(Command::List(std::path::PathBuf::from(path))),
        [command, path] if command == "info" => {
            let path = std::path::PathBuf::from(path);
            if !path.is_file() {
                return Err(format!(
                    "info requires an existing file path: {}",
                    path.display()
                ));
            }
            Ok(Command::Info(path))
        }
        [command] if command == "info" => Ok(Command::InfoAll),
        _ => Err("Usage: roms list [path] | roms info <path>".to_string()),
    }
}

fn read_rom_from_file(
    path: &std::path::Path,
    rom_db: &RomDb,
) -> Result<(ParsedRom, usize), String> {
    let data = std::fs::read(path).map_err(|err| err.to_string())?;

    let parsed = ParsedRom::parse(&data, Some(rom_db)).map_err(|err| match err {
        RomParseError::InvalidHeader => "Invalid iNES header".to_string(),
        RomParseError::FileTooSmall { expected, actual } => format!(
            "!!! WARNING: FILE LENGTH DOES NOT MATCH DB/HEADER DECLARATION !!! actual={} expected={} (file too small for PRG/CHR ROM data)",
            actual, expected
        ),
    })?;

    Ok((parsed, data.len()))
}

fn console_type_label(console_type: ConsoleType) -> String {
    match console_type {
        ConsoleType::NesFamicom => "NES/Famicom".to_string(),
        ConsoleType::VsSystem => "Vs. System".to_string(),
        ConsoleType::Playchoice10 => "PlayChoice-10".to_string(),
        ConsoleType::Extended(value) => format!("Extended ({value})"),
    }
}

fn timing_mode_label(timing: TimingMode) -> String {
    match timing {
        TimingMode::Ntsc => "NTSC".to_string(),
        TimingMode::Pal => "PAL".to_string(),
        TimingMode::MultiRegion => "Multi-region".to_string(),
        TimingMode::Dendy => "Dendy".to_string(),
        TimingMode::Unknown(value) => format!("Unknown ({value})"),
    }
}

fn timing_mode_short_label(timing: TimingMode) -> char {
    match timing {
        TimingMode::Pal => 'P',
        TimingMode::Ntsc => 'N',
        TimingMode::MultiRegion | TimingMode::Dendy | TimingMode::Unknown(_) => '?',
    }
}

fn expected_file_size_bytes(parsed: &ParsedRom) -> usize {
    let trainer_offset = if parsed.header.has_trainer { 512 } else { 0 };
    16 + trainer_offset + parsed.header.prg_rom_size_bytes + parsed.header.chr_rom_size_bytes
}

fn print_rom_info(path: &std::path::Path, parsed: &ParsedRom, actual_file_size_bytes: usize) {
    println!("ROM: {}", path.display());
    println!("Header version: {}", parsed.header.header_version);
    println!(
        "Mapper: {} ({})",
        parsed.header.mapper, parsed.header.submapper
    );
    println!(
        "Console type: {}",
        console_type_label(parsed.header.console_type)
    );
    println!("PRG ROM size: {} bytes", parsed.header.prg_rom_size_bytes);
    println!("CHR ROM size: {} bytes", parsed.header.chr_rom_size_bytes);
    if let Some(prg_ram_size_bytes) = parsed.header.prg_ram_size_bytes {
        println!("PRG-RAM size: {} bytes", prg_ram_size_bytes);
    }
    if let Some(prg_nvram_size_bytes) = parsed.header.prg_nvram_size_bytes {
        println!("PRG-NVRAM size: {} bytes", prg_nvram_size_bytes);
    }
    if let Some(chr_ram_size_bytes) = parsed.header.chr_ram_size_bytes {
        println!("CHR-RAM size: {} bytes", chr_ram_size_bytes);
    }
    if let Some(chr_nvram_size_bytes) = parsed.header.chr_nvram_size_bytes {
        println!("CHR-NVRAM size: {} bytes", chr_nvram_size_bytes);
    }
    println!(
        "Timing mode: {}",
        timing_mode_label(parsed.header.timing_mode)
    );
    println!("PRG+CHR CRC32: {:08X}", parsed.crc32);
    if let Some(vs_ppu_type) = parsed.header.vs_ppu_type {
        println!("Vs. PPU type: {vs_ppu_type}");
    }
    if let Some(vs_hardware_type) = parsed.header.vs_hardware_type {
        println!("Vs. hardware type: {vs_hardware_type}");
    }
    if parsed.header.misc_roms > 0 {
        println!("Misc ROMs: {}", parsed.header.misc_roms);
    }
    if parsed.header.default_expansion_device > 0 {
        println!(
            "Default expansion device: {}",
            parsed.header.default_expansion_device
        );
    }
    println!("Mirroring: {:?}", parsed.header.mirroring);
    println!(
        "Trainer: {}",
        if parsed.header.has_trainer {
            "yes"
        } else {
            "no"
        }
    );
    println!(
        "Battery-backed PRG RAM: {}",
        if parsed.header.battery_backed_prg_ram {
            "yes"
        } else {
            "no"
        }
    );

    let expected_file_size_bytes = expected_file_size_bytes(parsed);
    if actual_file_size_bytes != expected_file_size_bytes {
        println!("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        println!("!!! WARNING: FILE LENGTH DOES NOT MATCH HEADER DECLARATION !!!");
        println!(
            "!!! Actual size: {} bytes | Expected from DB/header: {} bytes !!!",
            actual_file_size_bytes, expected_file_size_bytes
        );
        println!("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }
}

fn collect_roms(root: &std::path::Path) -> Result<Vec<std::path::PathBuf>, std::io::Error> {
    let mut roms = Vec::new();
    let entries = match std::fs::read_dir(root) {
        Ok(entries) => entries,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(roms),
        Err(err) => return Err(err),
    };
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            roms.extend(collect_roms(&path)?);
        } else if path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext.eq_ignore_ascii_case("nes"))
            .unwrap_or(false)
        {
            roms.push(path);
        }
    }
    Ok(roms)
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let command = parse_command(&args).map_err(|err| {
        eprintln!("{err}");
        err
    })?;

    match command {
        Command::List(root) => {
            let rom_db = RomDb::new()?;
            let mut roms = collect_roms(&root)?;
            roms.sort();

            for rom in roms {
                match read_rom_from_file(&rom, &rom_db) {
                    Ok((parsed, _)) => {
                        let display_path = rom.strip_prefix(&root).unwrap_or(&rom);
                        println!(
                            "{:03} {} {}",
                            parsed.header.mapper,
                            timing_mode_short_label(parsed.header.timing_mode),
                            display_path.display()
                        );
                    }
                    Err(err) => {
                        let display_path = rom.strip_prefix(&root).unwrap_or(&rom);
                        eprintln!("{}: {err}", display_path.display());
                    }
                }
            }
        }
        Command::Info(path) => {
            let rom_db = RomDb::new()?;
            let (parsed, actual_file_size_bytes) = read_rom_from_file(&path, &rom_db)
                .map_err(|err| format!("{}: {err}", path.display()))?;
            print_rom_info(&path, &parsed, actual_file_size_bytes);
        }
        Command::InfoAll => {
            let rom_db = RomDb::new()?;
            let root = std::path::Path::new(DEFAULT_LIST_ROOT);
            let mut roms = collect_roms(root)?;
            roms.sort();

            let mut first = true;
            for rom in roms {
                if !first {
                    println!("============================");
                }
                first = false;

                match read_rom_from_file(&rom, &rom_db) {
                    Ok((parsed, actual_file_size_bytes)) => {
                        print_rom_info(&rom, &parsed, actual_file_size_bytes)
                    }
                    Err(err) => eprintln!("{}: {err}", rom.display()),
                }
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_collect_roms_filters_nes_files() {
        let root = std::path::Path::new("roms/games");
        let roms = collect_roms(root).expect("collect roms");
        assert!(roms.iter().all(|path| {
            path.extension()
                .and_then(|ext| ext.to_str())
                .map(|ext| ext.eq_ignore_ascii_case("nes"))
                .unwrap_or(false)
        }));
    }

    #[test]
    fn test_collect_roms_missing_directory_returns_empty() {
        let root = std::path::Path::new("roms/does-not-exist");
        let roms = collect_roms(root).expect("collect roms");
        assert!(roms.is_empty());
    }

    #[test]
    fn test_parse_command_list() {
        let args = vec!["list".to_string()];
        let command = parse_command(&args).expect("parse command");
        assert_eq!(command, Command::List(PathBuf::from(DEFAULT_LIST_ROOT)));
    }

    #[test]
    fn test_parse_command_list_with_path() {
        let args = vec!["list".to_string(), "roms".to_string()];
        let command = parse_command(&args).expect("parse command");
        assert_eq!(command, Command::List(PathBuf::from("roms")));
    }

    #[test]
    fn test_parse_command_info_without_path_lists_all() {
        let args = vec!["info".to_string()];
        let command = parse_command(&args).expect("parse command");
        assert!(matches!(command, Command::InfoAll));
    }

    #[test]
    fn test_parse_command_info_requires_existing_file() {
        let missing_path = PathBuf::from("roms/does-not-exist/missing.nes");
        let args = vec!["info".to_string(), missing_path.display().to_string()];
        let err = parse_command(&args).expect_err("should fail with missing file");
        assert!(err.to_lowercase().contains("file"));
    }

    #[test]
    fn test_read_rom_from_file_sets_crc32() {
        let mut header = [0u8; 16];
        header[0..4].copy_from_slice(b"NES\x1A");
        header[4] = 1;
        header[5] = 1;

        let prg_rom = vec![0xAA; 16 * 1024];
        let chr_rom = vec![0xBB; 8 * 1024];
        let expected_crc = neser::cartridge::calculate_rom_crc32(&prg_rom, &chr_rom);

        let mut rom_bytes = header.to_vec();
        rom_bytes.extend_from_slice(&prg_rom);
        rom_bytes.extend_from_slice(&chr_rom);

        let mut path = std::env::temp_dir();
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        path.push(format!("neser-rom-crc-{nonce}.nes"));

        std::fs::write(&path, &rom_bytes).expect("write temp rom");
        let rom_db = RomDb::new().expect("load rom db");
        let (parsed, actual_file_size_bytes) =
            read_rom_from_file(&path, &rom_db).expect("read temp rom");
        let _ = std::fs::remove_file(&path);

        assert_eq!(parsed.crc32, expected_crc);
        assert_eq!(actual_file_size_bytes, rom_bytes.len());
        assert_eq!(
            expected_file_size_bytes(&parsed),
            16 + parsed.header.prg_rom_size_bytes + parsed.header.chr_rom_size_bytes
        );
        assert_eq!(actual_file_size_bytes, expected_file_size_bytes(&parsed));
    }

    #[test]
    fn test_read_rom_from_file_detects_trailing_bytes_length_mismatch() {
        let mut header = [0u8; 16];
        header[0..4].copy_from_slice(b"NES\x1A");
        header[4] = 1;
        header[5] = 1;

        let prg_rom = vec![0xAA; 16 * 1024];
        let chr_rom = vec![0xBB; 8 * 1024];
        let trailer = vec![0xCC; 128];

        let mut rom_bytes = header.to_vec();
        rom_bytes.extend_from_slice(&prg_rom);
        rom_bytes.extend_from_slice(&chr_rom);
        rom_bytes.extend_from_slice(&trailer);

        let mut path = std::env::temp_dir();
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        path.push(format!("neser-rom-len-{nonce}.nes"));

        std::fs::write(&path, &rom_bytes).expect("write temp rom");
        let rom_db = RomDb::new().expect("load rom db");
        let (parsed, actual_file_size_bytes) =
            read_rom_from_file(&path, &rom_db).expect("read temp rom");
        let _ = std::fs::remove_file(&path);

        assert_eq!(actual_file_size_bytes, rom_bytes.len());
        assert_ne!(actual_file_size_bytes, expected_file_size_bytes(&parsed));
    }

    #[test]
    fn test_read_rom_from_file_uses_db_sizes_when_mismatching_header() {
        let mut header = [0u8; 16];
        header[0..4].copy_from_slice(b"NES\x1A");
        header[4] = 1;
        header[5] = 1;

        let prg_rom = vec![0xAA; 16 * 1024];
        let chr_rom = vec![0xBB; 8 * 1024];
        let expected_crc = neser::cartridge::calculate_rom_crc32(&prg_rom, &chr_rom);

        let mut rom_bytes = header.to_vec();
        rom_bytes.extend_from_slice(&prg_rom);
        rom_bytes.extend_from_slice(&chr_rom);

        let mut rom_path = std::env::temp_dir();
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        rom_path.push(format!("neser-rom-db-override-{nonce}.nes"));
        std::fs::write(&rom_path, &rom_bytes).expect("write temp rom");

        let mut csv_path = std::env::temp_dir();
        csv_path.push(format!("neser-rom-db-override-{nonce}.csv"));
        let columns = vec![
            "1".to_string(),
            "Test".to_string(),
            "".to_string(),
            format!("{expected_crc:08X}"),
            "".to_string(),
            "Licensed Test".to_string(),
            "4".to_string(),
            "".to_string(),
            "H".to_string(),
            "16384".to_string(),
            "00000000".to_string(),
            "".to_string(),
            "".to_string(),
            "0".to_string(),
            "00000000".to_string(),
            "".to_string(),
            "".to_string(),
            "".to_string(),
            "".to_string(),
            "".to_string(),
            "1".to_string(),
        ];
        let csv = format!("{}\n", columns.join(","));
        std::fs::write(&csv_path, csv).expect("write temp db");

        let rom_db = RomDb::from_path(&csv_path).expect("load temp db");
        let (parsed, actual_file_size_bytes) =
            read_rom_from_file(&rom_path, &rom_db).expect("read temp rom");

        let _ = std::fs::remove_file(&rom_path);
        let _ = std::fs::remove_file(&csv_path);

        assert_eq!(parsed.header.prg_rom_size_bytes, 16 * 1024);
        assert_eq!(parsed.header.chr_rom_size_bytes, 0);
        assert_eq!(parsed.header.mapper, 4);
        assert_ne!(actual_file_size_bytes, expected_file_size_bytes(&parsed));
    }
}