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
//! SDL-free headless playback for autorun recordings.
//!
//! This module provides [`run_headless_playback`] which replays a recording and verifies
//! screen CRCs at every checkpoint. It has no SDL dependencies and can be called from
//! integration tests or other non-SDL frontends (e.g. web).

use super::types::AutorunFile;
use crate::console::{Nes, SaveState};

/// Summary of a headless playback run.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)]
pub struct HeadlessPlaybackResult {
    /// Number of checkpoint CRC mismatches detected.
    pub crc_mismatches: usize,
    /// Total number of checkpoints verified.
    pub total_checkpoints_verified: usize,
}

impl HeadlessPlaybackResult {
    /// Returns `true` if all checkpoint CRCs matched.
    #[allow(dead_code)]
    pub fn is_ok(&self) -> bool {
        self.crc_mismatches == 0
    }
}

/// Run a full headless playback of `file` on `nes`.
///
/// If `start_checkpoint` is `Some(n)`, the emulator state is restored from checkpoint `n`
/// and playback begins from that checkpoint's `frame_index`. Otherwise playback starts
/// from frame 0.
///
/// At every checkpoint frame, the screen CRC is computed and compared against the stored
/// value. The result contains the mismatch count and the total number of checkpoints
/// verified.
///
/// The `nes` must already have the correct cartridge loaded and be reset before calling.
#[allow(dead_code)]
pub fn run_headless_playback(
    nes: &mut Nes,
    file: &AutorunFile,
    start_checkpoint: Option<usize>,
) -> Result<HeadlessPlaybackResult, String> {
    let (start_frame, first_checkpoint_idx) = if let Some(cp_idx) = start_checkpoint {
        let cp = file
            .checkpoints
            .get(cp_idx)
            .ok_or_else(|| format!("Checkpoint index {cp_idx} out of range"))?;
        let state = SaveState::from_bytes(&cp.state_bytes)
            .map_err(|e| format!("Failed to deserialize checkpoint {cp_idx} state: {e}"))?;
        nes.load_state(&state)
            .map_err(|e| format!("Failed to load checkpoint {cp_idx} state: {e}"))?;
        // State is captured AFTER frame cp.frame_index; start playing from the next frame
        // and verify from the checkpoint after the start checkpoint.
        (cp.frame_index as usize + 1, cp_idx + 1)
    } else {
        (0, 0)
    };

    let mut frame_idx = start_frame;
    let mut cp_idx = first_checkpoint_idx;
    let mut crc_mismatches = 0usize;
    let mut total_verified = 0usize;

    for frame in file.frames.iter().skip(start_frame) {
        // Apply controller input
        nes.set_joypad_button_states(1, frame.player1);
        nes.set_joypad_button_states(2, frame.player2);

        // Emulate one full frame
        run_one_frame(nes);

        // Check if this frame is a checkpoint
        while cp_idx < file.checkpoints.len()
            && file.checkpoints[cp_idx].frame_index as usize == frame_idx
        {
            let cp = &file.checkpoints[cp_idx];
            let actual_crc = nes.ppu().borrow().screen_buffer().crc32();
            if actual_crc != cp.screen_crc {
                crc_mismatches += 1;
            }
            total_verified += 1;
            cp_idx += 1;
        }

        frame_idx += 1;
    }

    Ok(HeadlessPlaybackResult {
        crc_mismatches,
        total_checkpoints_verified: total_verified,
    })
}

/// Run a full headless playback of `file` and rewrite checkpoint screen CRCs.
///
/// Returns the number of checkpoints updated.
#[allow(dead_code)]
pub fn recalculate_checkpoint_crcs(
    nes: &mut Nes,
    file: &mut AutorunFile,
    start_checkpoint: Option<usize>,
) -> Result<usize, String> {
    recalculate_checkpoint_crcs_with_progress(nes, file, start_checkpoint, |_, _| {})
}

/// Run a full headless playback of `file`, rewrite checkpoint screen CRCs,
/// and report progress via callback as `(done, total)`.
pub fn recalculate_checkpoint_crcs_with_progress<F>(
    nes: &mut Nes,
    file: &mut AutorunFile,
    start_checkpoint: Option<usize>,
    mut on_progress: F,
) -> Result<usize, String>
where
    F: FnMut(usize, usize),
{
    let (start_frame, first_checkpoint_idx) = if let Some(cp_idx) = start_checkpoint {
        let cp = file
            .checkpoints
            .get(cp_idx)
            .ok_or_else(|| format!("Checkpoint index {cp_idx} out of range"))?;
        let state = SaveState::from_bytes(&cp.state_bytes)
            .map_err(|e| format!("Failed to deserialize checkpoint {cp_idx} state: {e}"))?;
        nes.load_state(&state)
            .map_err(|e| format!("Failed to load checkpoint {cp_idx} state: {e}"))?;
        (cp.frame_index as usize + 1, cp_idx + 1)
    } else {
        (0, 0)
    };

    let mut frame_idx = start_frame;
    let mut cp_idx = first_checkpoint_idx;
    let mut updated = 0usize;
    let total_to_update = file.checkpoints.len().saturating_sub(first_checkpoint_idx);

    for frame in file.frames.iter().skip(start_frame) {
        nes.set_joypad_button_states(1, frame.player1);
        nes.set_joypad_button_states(2, frame.player2);

        run_one_frame(nes);

        while cp_idx < file.checkpoints.len()
            && file.checkpoints[cp_idx].frame_index as usize == frame_idx
        {
            let actual_crc = nes.ppu().borrow().screen_buffer().crc32();
            file.checkpoints[cp_idx].screen_crc = actual_crc;
            updated += 1;
            on_progress(updated, total_to_update);
            cp_idx += 1;
        }

        frame_idx += 1;
    }

    Ok(updated)
}

/// Emulate the NES until the PPU signals a completed frame, then clear the flag.
#[allow(dead_code)]
fn run_one_frame(nes: &mut Nes) {
    while !nes.is_ready_to_render() && !nes.cpu_ref().is_halted() {
        nes.run_cpu_tick();
        // Drain audio samples to avoid unbounded accumulation
        while nes.sample_ready() {
            nes.get_sample();
        }
    }
    nes.clear_ready_to_render();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app_context::AppContext;
    use crate::autorun::{AUTORUN_VERSION, AutorunCheckpoint, AutorunFile, AutorunFrame};
    use crate::console::{Config, Nes, RamInitMode};

    /// Minimal NROM-128 ROM that just loops forever with no audio/PPU effects.
    fn minimal_nrom_rom() -> Vec<u8> {
        let mut rom = Vec::with_capacity(16 + 16 * 1024);
        rom.extend_from_slice(b"NES\x1A");
        rom.push(1); // 16KB PRG
        rom.push(0); // 0 CHR (CHR RAM)
        rom.push(0x00); // flags6
        rom.push(0x00); // flags7
        rom.extend_from_slice(&[0u8; 8]); // padding
        let mut prg = vec![0xEAu8; 16 * 1024]; // NOPs
        // Reset vector at $FFFC pointing to $C000
        prg[0x3FFC] = 0x00;
        prg[0x3FFD] = 0xC0;
        // Infinite loop at $C000: JMP $C000
        prg[0x0000] = 0x4C;
        prg[0x0001] = 0x00;
        prg[0x0002] = 0xC0;
        rom.extend_from_slice(&prg);
        rom
    }

    fn make_nes() -> Nes {
        let config = Config {
            ram_init_mode: RamInitMode::Zero,
            ..Default::default()
        };
        Nes::new(AppContext::new_with_config(config))
    }

    fn make_nes_with_cart(rom: &[u8]) -> Nes {
        let mut nes = make_nes();
        let cart = crate::cartridge::Cartridge::load_from_file(rom, "test.nes", AppContext::new())
            .expect("load cart");
        nes.insert_cartridge(cart);
        nes.reset(false);
        nes
    }

    fn run_nes_frames(nes: &mut Nes, n: u32) {
        for _ in 0..n {
            run_one_frame(nes);
        }
    }

    #[test]
    fn test_headless_playback_empty_recording_succeeds_with_no_checkpoints() {
        let rom = minimal_nrom_rom();
        let mut nes = make_nes_with_cart(&rom);

        let file = AutorunFile {
            version: AUTORUN_VERSION,
            frames: vec![],
            checkpoints: vec![],
        };

        let result = run_headless_playback(&mut nes, &file, None).expect("playback ok");
        assert_eq!(result.total_checkpoints_verified, 0);
        assert!(result.is_ok());
    }

    #[test]
    fn test_headless_playback_matching_crc_reports_no_mismatches() {
        let rom = minimal_nrom_rom();
        let mut nes = make_nes_with_cart(&rom);

        // Run 1 frame and capture real screen CRC to build a correct recording
        run_nes_frames(&mut nes, 1);
        let state_after_1 = nes.save_state();
        let crc_after_1 = nes.ppu().borrow().screen_buffer().crc32();

        let state_bytes = state_after_1.to_bytes().expect("serialize state");

        let file = AutorunFile {
            version: AUTORUN_VERSION,
            frames: vec![AutorunFrame {
                player1: 0,
                player2: 0,
            }],
            checkpoints: vec![AutorunCheckpoint {
                frame_index: 0,
                screen_crc: crc_after_1,
                state_bytes,
            }],
        };

        // Reset and replay
        nes.reset(false);
        let result = run_headless_playback(&mut nes, &file, None).expect("playback ok");
        assert_eq!(result.total_checkpoints_verified, 1);
        assert_eq!(result.crc_mismatches, 0);
        assert!(result.is_ok());
    }

    #[test]
    fn test_headless_playback_wrong_crc_reports_mismatch() {
        let rom = minimal_nrom_rom();
        let mut nes = make_nes_with_cart(&rom);

        let state_bytes = nes.save_state().to_bytes().expect("serialize state");

        let file = AutorunFile {
            version: AUTORUN_VERSION,
            frames: vec![AutorunFrame {
                player1: 0,
                player2: 0,
            }],
            checkpoints: vec![AutorunCheckpoint {
                frame_index: 0,
                screen_crc: 0xDEADBEEF, // Deliberately wrong
                state_bytes,
            }],
        };

        let result = run_headless_playback(&mut nes, &file, None).expect("playback ok");
        assert_eq!(result.total_checkpoints_verified, 1);
        assert_eq!(result.crc_mismatches, 1);
        assert!(!result.is_ok());
    }

    #[test]
    fn test_headless_playback_from_checkpoint_restores_state() {
        let rom = minimal_nrom_rom();
        let mut nes = make_nes_with_cart(&rom);

        // Run to frame 299 to get a state
        run_nes_frames(&mut nes, 300);
        let state_at_300 = nes.save_state();
        let state_bytes_300 = state_at_300.to_bytes().expect("serialize");

        // Run one more frame from that state to know the expected CRC
        run_nes_frames(&mut nes, 1);
        let crc_at_301 = nes.ppu().borrow().screen_buffer().crc32();

        let file = AutorunFile {
            version: AUTORUN_VERSION,
            // 600 frames total
            frames: vec![
                AutorunFrame {
                    player1: 0,
                    player2: 0
                };
                600
            ],
            checkpoints: vec![
                AutorunCheckpoint {
                    frame_index: 299,
                    screen_crc: 0x0000, // Not checked during this test
                    state_bytes: state_bytes_300.clone(),
                },
                AutorunCheckpoint {
                    frame_index: 300,
                    screen_crc: crc_at_301,
                    state_bytes: vec![], // Not used during this test
                },
            ],
        };

        // Start from checkpoint 0 (frame 299) - only checkpoint index 1 (frame 300) gets verified
        let mut nes2 = make_nes_with_cart(&rom);
        let result = run_headless_playback(&mut nes2, &file, Some(0)).expect("playback ok");
        // Checkpoint at frame 299 (index 0) is the start checkpoint and not re-verified;
        // checkpoint at frame 300 (index 1) should be verified once.
        assert_eq!(result.total_checkpoints_verified, 1);
        assert_eq!(result.crc_mismatches, 0);
    }

    #[test]
    fn test_recalculate_checkpoint_crcs_updates_mismatching_checkpoint_crc() {
        let rom = minimal_nrom_rom();
        let mut nes = make_nes_with_cart(&rom);

        run_nes_frames(&mut nes, 1);
        let state_after_1 = nes.save_state();
        let state_bytes = state_after_1.to_bytes().expect("serialize state");

        let mut file = AutorunFile {
            version: AUTORUN_VERSION,
            frames: vec![AutorunFrame {
                player1: 0,
                player2: 0,
            }],
            checkpoints: vec![AutorunCheckpoint {
                frame_index: 0,
                screen_crc: 0xDEADBEEF,
                state_bytes,
            }],
        };

        nes.reset(false);
        let updated =
            recalculate_checkpoint_crcs(&mut nes, &mut file, None).expect("recalculation succeeds");

        assert_eq!(updated, 1);
        assert_ne!(file.checkpoints[0].screen_crc, 0xDEADBEEF);
    }

    #[test]
    fn test_recalculate_checkpoint_crcs_reports_progress_for_each_checkpoint() {
        let rom = minimal_nrom_rom();
        let mut nes = make_nes_with_cart(&rom);

        run_nes_frames(&mut nes, 1);
        let state_after_1 = nes.save_state();
        let state_bytes = state_after_1.to_bytes().expect("serialize state");

        let mut file = AutorunFile {
            version: AUTORUN_VERSION,
            frames: vec![
                AutorunFrame {
                    player1: 0,
                    player2: 0,
                },
                AutorunFrame {
                    player1: 0,
                    player2: 0,
                },
            ],
            checkpoints: vec![
                AutorunCheckpoint {
                    frame_index: 0,
                    screen_crc: 0,
                    state_bytes: state_bytes.clone(),
                },
                AutorunCheckpoint {
                    frame_index: 1,
                    screen_crc: 0,
                    state_bytes,
                },
            ],
        };

        nes.reset(false);
        let mut progress = Vec::new();
        let updated =
            recalculate_checkpoint_crcs_with_progress(&mut nes, &mut file, None, |done, total| {
                progress.push((done, total))
            })
            .expect("recalculation succeeds");

        assert_eq!(updated, 2);
        assert_eq!(progress, vec![(1, 2), (2, 2)]);
    }
}