Skip to main content

rustynes_core/
nsf_rip.rs

1//! v3.6.0 (`T-AUDIO-STEMS`) — trace-assisted NSF ripping: find a game's music
2//! driver from what the CPU does, propose its `init` and `play` addresses, and
3//! write an NSF that drives it.
4//!
5//! An NSF file (nesdev "NSF") is a music engine lifted out of a game plus a
6//! header that says how to drive it: load the program image at `load`, call
7//! `init` once with the song number in A, then call `play` once per frame. A
8//! ripper's job is to find those two routines. This one finds them by
9//! watching the game run.
10//!
11//! # How the routines are found
12//!
13//! [`Tracer`] steps the console one instruction at a time and keeps a
14//! **shadow call stack**: a `JSR` pushes its target; an interrupt (a step
15//! that pushed three bytes and landed on the NMI or IRQ/BRK vector's target)
16//! pushes the vector; and an entry is popped when the stack pointer climbs back to
17//! where it was before the call, which is what `RTS` and `RTI` do (and also
18//! what a routine that discards its own return address does). The CPU bus
19//! access log (`Nes::set_access_logging`) names every write an instruction
20//! made; each write to an APU register (`$4000-$4013`, `$4015`, `$4017`: not
21//! `$4014`, which is OAM DMA, nor `$4016`, the controller strobe) is recorded
22//! with the shadow stack it happened under.
23//!
24//! [`propose`] then reads the evidence:
25//!
26//! - **play** is the routine that encloses every APU write of a frame. For
27//!   each frame, the common prefix of its writes' call chains is taken; a
28//!   routine that is in that prefix in the most frames is the driver, and of
29//!   several such (the NMI handler's body calling the driver, say) the
30//!   innermost is chosen, because an outer one also does the game's other
31//!   per-frame work. The evidence reported is how many frames it enclosed
32//!   every write in, how many times it was called per frame, and how many of
33//!   the run's APU writes it enclosed.
34//! - **init** is the routine that encloses every APU write made outside a
35//!   `play` call, if there is one: that is the code that silences the
36//!   channels and sets the engine up before the first frame plays. When the
37//!   game makes no such writes from a subroutine (its reset code writes the
38//!   APU inline, or not at all), no init is proposed and the NSF gets a no-op
39//!   one, said so in the report: the NSF player zeroes RAM before init, which
40//!   is often all the engine needed.
41//!
42//! These are heuristics over one run, and the report says which: the proposal
43//! is what the evidence supports, with the counts to judge it by. The gate is
44//! that the NSF plays the tune — `rustynes-core`'s tests and
45//! `docs/audio-stems.md` describe it: the NSF's `play` calls make the same
46//! APU writes, call for call, as the game's.
47//!
48//! # What can be ripped
49//!
50//! The program image is the cartridge's PRG-ROM, loaded at `$8000`. That is
51//! only the code the console ran when the PRG is not bank-switched: mapper 0
52//! (NROM) and mapper 3 (CNROM, whose banking is CHR only), up to 32 KiB, a
53//! 16 KiB image mirrored to fill `$8000-$FFFF` as the board does. A
54//! bank-switched board would need the NSF's own 4 KiB bank registers set to
55//! the layout the driver runs under, which this does not infer;
56//! [`build_nsf`] refuses it with that reason rather than write a file that
57//! does not play. It refuses a driver that runs from RAM for the same
58//! reason: the code is not in the image (the game copied it there), and the
59//! NSF player clears RAM before `init`.
60
61use alloc::string::String;
62use alloc::vec::Vec;
63use alloc::{format, vec};
64
65use crate::{Nes, Region};
66
67/// The CPU registers a write in this range is an APU register write for the
68/// purposes of ripping: `$4000-$4013`, `$4015`, `$4017`.
69#[must_use]
70pub const fn is_apu_register(addr: u16) -> bool {
71    matches!(addr, 0x4000..=0x4013 | 0x4015 | 0x4017)
72}
73
74/// How a routine on the shadow call stack was entered.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum CallKind {
77    /// A `JSR` to the target.
78    Jsr,
79    /// The NMI, which entered its vector's target.
80    Nmi,
81    /// An IRQ or `BRK`, which entered its vector's target.
82    Irq,
83}
84
85/// One entry of the shadow call stack, kept for the whole run.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct Call {
88    /// How it was entered.
89    pub kind: CallKind,
90    /// The routine's address.
91    pub target: u16,
92    /// The frame it was entered in (`Nes::frame`).
93    pub frame: u64,
94}
95
96/// One APU register write and the calls it happened under.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct ApuWrite {
99    /// The frame it happened in.
100    pub frame: u64,
101    /// The register.
102    pub addr: u16,
103    /// The byte.
104    pub value: u8,
105    /// The instruction that wrote it.
106    pub pc: u16,
107    /// The call chain, outermost first, as indices into [`Tracer::calls`].
108    pub chain: Vec<u32>,
109}
110
111/// A running trace over one [`Nes`].
112pub struct Tracer {
113    /// The live shadow stack: (index into `calls`, stack pointer before entry).
114    stack: Vec<(u32, u8)>,
115    calls: Vec<Call>,
116    writes: Vec<ApuWrite>,
117    frames: u64,
118}
119
120/// The most instructions [`Tracer::run_frame`] steps before giving up on a
121/// frame (a jammed or interrupt-less program): about five NTSC frames of
122/// two-cycle instructions.
123const MAX_STEPS_PER_FRAME: u32 = 80_000;
124
125impl Tracer {
126    /// Start tracing: turns the console's access log on.
127    pub fn new(nes: &mut Nes) -> Self {
128        nes.set_access_logging(true);
129        nes.bus_mut().clear_accesses();
130        Self {
131            stack: Vec::new(),
132            calls: Vec::new(),
133            writes: Vec::new(),
134            frames: 0,
135        }
136    }
137
138    /// Every call entered so far.
139    #[must_use]
140    pub fn calls(&self) -> &[Call] {
141        &self.calls
142    }
143
144    /// Every APU write so far.
145    #[must_use]
146    pub fn writes(&self) -> &[ApuWrite] {
147        &self.writes
148    }
149
150    /// Frames traced so far.
151    #[must_use]
152    pub const fn frames(&self) -> u64 {
153        self.frames
154    }
155
156    fn vector(nes: &mut Nes, at: u16) -> u16 {
157        u16::from(nes.cpu_bus_peek(at)) | (u16::from(nes.cpu_bus_peek(at + 1)) << 8)
158    }
159
160    /// Step one instruction and record what it did.
161    pub fn step(&mut self, nes: &mut Nes) {
162        let pc = nes.cpu().pc;
163        let s_before = nes.cpu().s;
164        let opcode = nes.cpu_bus_peek(pc);
165        let jsr_target = (opcode == 0x20).then(|| {
166            u16::from(nes.cpu_bus_peek(pc.wrapping_add(1)))
167                | (u16::from(nes.cpu_bus_peek(pc.wrapping_add(2))) << 8)
168        });
169        let frame = nes.frame();
170        nes.step_instruction();
171
172        // The writes the instruction made belong to the context it ran in:
173        // the stack as it was before this step's own call or return.
174        let chain: Vec<u32> = self.stack.iter().map(|&(i, _)| i).collect();
175        for a in nes.accesses() {
176            if a.write && is_apu_register(a.addr) {
177                self.writes.push(ApuWrite {
178                    frame,
179                    addr: a.addr,
180                    value: a.value,
181                    pc,
182                    chain: chain.clone(),
183                });
184            }
185        }
186        nes.bus_mut().clear_accesses();
187
188        let pc_after = nes.cpu().pc;
189        let s_after = nes.cpu().s;
190        // The CPU services an interrupt as a step of its own (the seven-cycle
191        // sequence, no instruction), so on such a step the opcode at `pc` was
192        // NOT executed: it is the instruction the interrupt returns to, and a
193        // `JSR` there must not be taken for a call. An interrupt step pushed
194        // exactly three bytes (P and the return address) and landed on a
195        // vector's target, which tells it apart from the two lookalikes: a
196        // jump onto a handler (it pushes nothing, or two bytes for `JSR`) and
197        // code that falls through onto the address a vector names (nothing).
198        // `BRK` makes the same push onto the IRQ vector and is recorded as
199        // the IRQ entry it is.
200        let nmi = Self::vector(nes, 0xFFFA);
201        let irq = Self::vector(nes, 0xFFFE);
202        let pushed_three = s_before.wrapping_sub(s_after) == 3;
203        let entered = if !pushed_three {
204            None
205        } else if pc_after == nmi {
206            Some(CallKind::Nmi)
207        } else if pc_after == irq {
208            Some(CallKind::Irq)
209        } else {
210            None
211        };
212        let called = if entered.is_none() { jsr_target } else { None };
213
214        // Pop every call the stack pointer has climbed back past.
215        if entered.is_none() {
216            while let Some(&(_, s_entry)) = self.stack.last() {
217                if s_after >= s_entry {
218                    self.stack.pop();
219                } else {
220                    break;
221                }
222            }
223        }
224        if let Some(target) = called {
225            self.push(CallKind::Jsr, target, frame, s_before);
226        } else if let Some(kind) = entered {
227            self.push(kind, pc_after, frame, s_before);
228        }
229    }
230
231    fn push(&mut self, kind: CallKind, target: u16, frame: u64, s_entry: u8) {
232        // A program that never returns from its calls (a reset routine that
233        // JSRs into a main loop, a handler that resets the stack) would grow
234        // the shadow stack forever; past the 6502's own 128 return addresses
235        // the oldest entries are dropped, as the hardware stack would wrap.
236        if self.stack.len() >= 128 {
237            self.stack.remove(0);
238        }
239        let idx = u32::try_from(self.calls.len()).unwrap_or(u32::MAX);
240        self.calls.push(Call {
241            kind,
242            target,
243            frame,
244        });
245        self.stack.push((idx, s_entry));
246    }
247
248    /// Step until the console's frame counter advances (one frame), or a cap
249    /// of steps is reached. Returns `false` when the cap was hit or the CPU
250    /// jammed.
251    pub fn run_frame(&mut self, nes: &mut Nes) -> bool {
252        let start = nes.frame();
253        for _ in 0..MAX_STEPS_PER_FRAME {
254            if nes.is_jammed() {
255                return false;
256            }
257            self.step(nes);
258            if nes.frame() != start {
259                self.frames += 1;
260                return true;
261            }
262        }
263        false
264    }
265
266    /// The writes each call to `target` made (directly or in routines it
267    /// called), in call order: one list per call, each `(register, byte)`.
268    /// A call that wrote nothing is an empty list.
269    #[must_use]
270    pub fn writes_per_call(&self, target: u16) -> Vec<Vec<(u16, u8)>> {
271        let mut out: Vec<Vec<(u16, u8)>> = Vec::new();
272        let mut index: Vec<Option<usize>> = vec![None; self.calls.len()];
273        for (i, c) in self.calls.iter().enumerate() {
274            if c.target == target && c.kind == CallKind::Jsr {
275                index[i] = Some(out.len());
276                out.push(Vec::new());
277            }
278        }
279        for w in &self.writes {
280            // The innermost enclosing call to `target` owns the write.
281            if let Some(slot) = w
282                .chain
283                .iter()
284                .rev()
285                .find_map(|&c| index.get(c as usize).copied().flatten())
286            {
287                out[slot].push((w.addr, w.value));
288            }
289        }
290        out
291    }
292}
293
294/// What the trace says about the `play` routine.
295#[derive(Clone, Debug, PartialEq, Eq)]
296pub struct PlayEvidence {
297    /// The proposed address.
298    pub addr: u16,
299    /// Frames that made at least one APU write.
300    pub frames_with_writes: u64,
301    /// Of those, frames in which this routine enclosed every write.
302    pub frames_enclosed: u64,
303    /// Frames in which it was called.
304    pub frames_called: u64,
305    /// The most common number of calls per frame it was called in.
306    pub calls_per_frame: u32,
307    /// The run's APU writes it enclosed.
308    pub writes_enclosed: u64,
309    /// Every APU write of the run.
310    pub writes_total: u64,
311}
312
313/// What the trace says about the `init` routine.
314#[derive(Clone, Debug, PartialEq, Eq)]
315pub enum InitEvidence {
316    /// A routine encloses every APU write made outside `play`.
317    Routine {
318        /// Its address.
319        addr: u16,
320        /// The writes it enclosed.
321        writes: u64,
322        /// How many times it was called in the run.
323        calls: u64,
324    },
325    /// No routine does (the reset code writes the APU inline, or never
326    /// outside play); the NSF gets a no-op init.
327    None {
328        /// APU writes made outside `play`.
329        writes_outside_play: u64,
330    },
331}
332
333/// The proposal [`propose`] makes.
334#[derive(Clone, Debug, PartialEq, Eq)]
335pub struct Proposal {
336    /// The `play` routine.
337    pub play: PlayEvidence,
338    /// The `init` routine, or why there is none.
339    pub init: InitEvidence,
340}
341
342/// Why no proposal could be made.
343#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
344pub enum RipError {
345    /// The run made no APU writes at all.
346    #[error("the run made no APU register writes; nothing to rip")]
347    NoWrites,
348    /// The writes are not inside any subroutine (the driver runs inline in an
349    /// interrupt handler or the main loop), so there is no `play` to call.
350    #[error(
351        "the APU writes are not inside a subroutine (the driver runs inline, \
352         in an interrupt handler or the main loop), so there is no play routine to call"
353    )]
354    NoSubroutine,
355    /// The cartridge's PRG is bank-switched, or too large, for a flat image.
356    #[error("{0}")]
357    Unsupported(String),
358}
359
360/// The common prefix of several call chains.
361fn common_prefix<'a>(mut chains: impl Iterator<Item = &'a [u32]>) -> Vec<u32> {
362    let Some(first) = chains.next() else {
363        return Vec::new();
364    };
365    let mut prefix = first.to_vec();
366    for c in chains {
367        let n = prefix.iter().zip(c).take_while(|(a, b)| a == b).count();
368        prefix.truncate(n);
369    }
370    prefix
371}
372
373/// The routine that encloses every APU write of a frame in the most frames,
374/// and in how many. Of several (an NMI body that calls the driver encloses
375/// the same writes as the driver does), the innermost: the deepest position
376/// on the stack any of them was seen at.
377fn pick_play(t: &Tracer, frames: &[u64]) -> Result<(u16, u64), RipError> {
378    let mut enclosed: Vec<(u16, u64)> = Vec::new(); // (target, frames)
379    let mut depth: Vec<(u16, usize)> = Vec::new(); // deepest position seen
380    for &f in frames {
381        let prefix = common_prefix(
382            t.writes
383                .iter()
384                .filter(|w| w.frame == f)
385                .map(|w| w.chain.as_slice()),
386        );
387        let mut seen: Vec<u16> = Vec::new();
388        for (pos, &ci) in prefix.iter().enumerate() {
389            let c = t.calls[ci as usize];
390            if c.kind != CallKind::Jsr || seen.contains(&c.target) {
391                continue;
392            }
393            seen.push(c.target);
394            match enclosed.iter_mut().find(|(a, _)| *a == c.target) {
395                Some((_, n)) => *n += 1,
396                None => enclosed.push((c.target, 1)),
397            }
398            match depth.iter_mut().find(|(a, _)| *a == c.target) {
399                Some((_, d)) => *d = (*d).max(pos),
400                None => depth.push((c.target, pos)),
401            }
402        }
403    }
404    let best = enclosed
405        .iter()
406        .map(|&(_, n)| n)
407        .max()
408        .ok_or(RipError::NoSubroutine)?;
409    let play = enclosed
410        .iter()
411        .filter(|&&(_, n)| n == best)
412        .map(|&(a, _)| a)
413        .max_by_key(|a| depth.iter().find(|(d, _)| d == a).map_or(0, |&(_, p)| p))
414        .ok_or(RipError::NoSubroutine)?;
415    Ok((play, best))
416}
417
418/// How many frames `play` was called in, and the most common number of
419/// calls in such a frame (the smaller on a tie).
420fn cadence(t: &Tracer, play: u16) -> (u64, u32) {
421    let mut per_frame: Vec<(u64, u32)> = Vec::new();
422    for c in t
423        .calls
424        .iter()
425        .filter(|c| c.kind == CallKind::Jsr && c.target == play)
426    {
427        match per_frame.iter_mut().find(|(f, _)| *f == c.frame) {
428            Some((_, n)) => *n += 1,
429            None => per_frame.push((c.frame, 1)),
430        }
431    }
432    let mut counts: Vec<(u32, u64)> = Vec::new();
433    for &(_, n) in &per_frame {
434        match counts.iter_mut().find(|(k, _)| *k == n) {
435            Some((_, m)) => *m += 1,
436            None => counts.push((n, 1)),
437        }
438    }
439    let calls_per_frame = counts
440        .iter()
441        .max_by_key(|&&(k, m)| (m, core::cmp::Reverse(k)))
442        .map_or(0, |&(k, _)| k);
443    (per_frame.len() as u64, calls_per_frame)
444}
445
446/// The innermost subroutine enclosing every write in `outside` (the writes
447/// made outside `play`), if one does.
448fn pick_init(t: &Tracer, outside: &[&ApuWrite]) -> InitEvidence {
449    let none = InitEvidence::None {
450        writes_outside_play: outside.len() as u64,
451    };
452    if outside.is_empty() {
453        return none;
454    }
455    let prefix = common_prefix(outside.iter().map(|w| w.chain.as_slice()));
456    prefix
457        .iter()
458        .rev()
459        .map(|&c| t.calls[c as usize])
460        .find(|c| c.kind == CallKind::Jsr)
461        .map_or(none, |c| InitEvidence::Routine {
462            addr: c.target,
463            writes: outside.len() as u64,
464            calls: t
465                .calls
466                .iter()
467                .filter(|k| k.kind == CallKind::Jsr && k.target == c.target)
468                .count() as u64,
469        })
470}
471
472/// Propose `init` and `play` from a finished trace.
473///
474/// # Errors
475///
476/// [`RipError::NoWrites`] or [`RipError::NoSubroutine`].
477pub fn propose(t: &Tracer) -> Result<Proposal, RipError> {
478    if t.writes.is_empty() {
479        return Err(RipError::NoWrites);
480    }
481    // The frames with writes, in order (the writes are recorded in order).
482    let mut frames: Vec<u64> = t.writes.iter().map(|w| w.frame).collect();
483    frames.dedup();
484    let (play, frames_enclosed) = pick_play(t, &frames)?;
485    let (frames_called, calls_per_frame) = cadence(t, play);
486    let inside_play = |w: &ApuWrite| {
487        w.chain.iter().any(|&c| {
488            t.calls[c as usize].kind == CallKind::Jsr && t.calls[c as usize].target == play
489        })
490    };
491    let outside: Vec<&ApuWrite> = t.writes.iter().filter(|w| !inside_play(w)).collect();
492    Ok(Proposal {
493        play: PlayEvidence {
494            addr: play,
495            frames_with_writes: frames.len() as u64,
496            frames_enclosed,
497            frames_called,
498            calls_per_frame,
499            writes_enclosed: (t.writes.len() - outside.len()) as u64,
500            writes_total: t.writes.len() as u64,
501        },
502        init: pick_init(t, &outside),
503    })
504}
505
506/// NSF header length.
507const HEADER: usize = 0x80;
508
509/// The metadata strings an NSF carries (32 bytes each, NUL-padded; longer
510/// text is cut at a character boundary).
511#[derive(Clone, Debug, Default)]
512pub struct NsfInfo {
513    /// Song / game name.
514    pub name: String,
515    /// Artist.
516    pub artist: String,
517    /// Copyright.
518    pub copyright: String,
519}
520
521fn put_str(out: &mut [u8], s: &str) {
522    // 31 bytes of text, at least one NUL.
523    let mut end = s.len().min(31);
524    while !s.is_char_boundary(end) {
525        end -= 1;
526    }
527    out[..end].copy_from_slice(&s.as_bytes()[..end]);
528}
529
530/// Write an NSF (version 1, one song) that drives `proposal` over the
531/// cartridge `rom`'s PRG.
532///
533/// When the proposal has no init routine, the init address is a `$60` (RTS)
534/// byte found in the image, so init returns at once; the returned
535/// [`NoOpInit`] says where. `region` sets the file's timing byte and speed word.
536///
537/// # Errors
538///
539/// [`RipError::Unsupported`] for a board this cannot image (see the module
540/// docs), or an image with no `RTS` byte to use as a no-op init.
541pub fn build_nsf(
542    rom: &[u8],
543    proposal: &Proposal,
544    region: Region,
545    info: &NsfInfo,
546) -> Result<(Vec<u8>, Option<NoOpInit>), RipError> {
547    let header = rustynes_mappers::parse_header(rom)
548        .map_err(|e| RipError::Unsupported(format!("the ROM header does not parse: {e}")))?;
549    let mapper = header.mapper_id;
550    if !matches!(mapper, 0 | 3) {
551        return Err(RipError::Unsupported(format!(
552            "mapper {mapper} bank-switches its PRG; ripping needs the NSF bank layout \
553             the driver runs under, which is not inferred (mappers 0 and 3 only)"
554        )));
555    }
556    let prg_len = header.prg_size;
557    let start = 16 + if header.has_trainer { 512 } else { 0 };
558    let prg = rom
559        .get(start..start + prg_len)
560        .ok_or_else(|| RipError::Unsupported("the PRG-ROM is truncated".into()))?;
561    let image: Vec<u8> = match prg_len {
562        0x4000 => prg.iter().chain(prg).copied().collect(),
563        0x8000 => prg.to_vec(),
564        n => {
565            return Err(RipError::Unsupported(format!(
566                "a {n}-byte PRG-ROM is neither 16 nor 32 KiB"
567            )));
568        }
569    };
570
571    // The image is the ROM at $8000. A driver the game copied into RAM
572    // (some engines run from $0000-$07FF or cartridge RAM) is not in it, and
573    // the NSF player clears RAM before init, so its play would call zeroes.
574    let in_image = |a: u16| a >= 0x8000;
575    if !in_image(proposal.play.addr) {
576        return Err(RipError::Unsupported(format!(
577            "play ${:04X} runs from RAM, which the NSF player clears before init; \
578             the driver is not in the ROM image",
579            proposal.play.addr
580        )));
581    }
582    if let InitEvidence::Routine { addr, .. } = proposal.init
583        && !in_image(addr)
584    {
585        return Err(RipError::Unsupported(format!(
586            "init ${addr:04X} runs from RAM, which the NSF player clears before init"
587        )));
588    }
589    let (init, noop) = match proposal.init {
590        InitEvidence::Routine { addr, .. } => (addr, None),
591        InitEvidence::None { .. } => {
592            let at = image
593                .iter()
594                .position(|&b| b == 0x60)
595                .ok_or_else(|| RipError::Unsupported("no RTS byte for a no-op init".into()))?;
596            let addr = 0x8000 + u16::try_from(at).unwrap_or(0);
597            (addr, Some(NoOpInit { addr }))
598        }
599    };
600
601    let mut out = vec![0u8; HEADER];
602    out[..5].copy_from_slice(b"NESM\x1A");
603    out[0x05] = 1; // version
604    out[0x06] = 1; // songs
605    out[0x07] = 1; // starting song
606    out[0x08..0x0A].copy_from_slice(&0x8000u16.to_le_bytes());
607    out[0x0A..0x0C].copy_from_slice(&init.to_le_bytes());
608    out[0x0C..0x0E].copy_from_slice(&proposal.play.addr.to_le_bytes());
609    put_str(&mut out[0x0E..0x2E], &info.name);
610    put_str(&mut out[0x2E..0x4E], &info.artist);
611    put_str(&mut out[0x4E..0x6E], &info.copyright);
612    // Play speed in microseconds per call: the hardware frame (nesdev's
613    // 16639 NTSC, 19997 PAL), the rate a once-per-frame driver runs at. A
614    // driver the trace saw called more than once a frame
615    // (`PlayEvidence::calls_per_frame`) is still filed at the frame rate,
616    // and the report says so: a faster divider would change the tempo of
617    // a driver that counts its own ticks.
618    out[0x6E..0x70].copy_from_slice(&16_639u16.to_le_bytes());
619    // $70-$77 bank registers: all zero, no bank switching.
620    out[0x78..0x7A].copy_from_slice(&19_997u16.to_le_bytes());
621    out[0x7A] = u8::from(matches!(region, Region::Pal));
622    out[0x7B] = 0; // no expansion chips on mappers 0 and 3
623    out.extend_from_slice(&image);
624    Ok((out, noop))
625}
626
627/// Where [`build_nsf`] pointed a no-op init.
628#[derive(Clone, Copy, Debug, PartialEq, Eq)]
629pub struct NoOpInit {
630    /// The `RTS` byte's address.
631    pub addr: u16,
632}
633
634/// The routines of [`example_music_rom`]'s program, for the tests and docs
635/// that drive it.
636pub mod example {
637    /// `INIT` (reset calls it with A = 0).
638    pub const INIT: u16 = 0xC045;
639    /// `PLAY`, the driver.
640    pub const PLAY: u16 = 0xC059;
641    /// `BODY`, the NMI's per-frame work, which calls `PLAY`.
642    pub const BODY: u16 = 0xC02E;
643    /// The NMI handler.
644    pub const NMI: u16 = 0xC020;
645    /// The main loop the reset code falls into (`JSR IDLE; JMP LOOP`), which
646    /// is also the IRQ vector's target.
647    pub const LOOP: u16 = 0xC019;
648}
649
650/// A homebrew NROM with a tiny music driver, written for the ripper's tests
651/// and docs.
652///
653/// No commercial code: the program is this function, assembled at `$C000`
654/// of a 16 KiB image, so the board also shows it at `$8000`.
655///
656/// Reset calls `INIT` (A = song, ignored), which turns the channels on and
657/// zeroes the driver's two RAM bytes, waits two vblanks (the PPU ignores
658/// `$2000` until it has warmed up), enables the vblank NMI and spins. The NMI
659/// handler saves the registers and calls `BODY`, the game's per-frame work,
660/// which starts an OAM DMA (`$4014`), strobes the controller (`$4016`) and
661/// calls `PLAY`; the main loop calls an empty `IDLE` routine forever, so the
662/// NMI often arrives just as a `JSR` is next. Every eighth call `PLAY` steps an eight-note scale on pulse 1
663/// and, through a nested `TRI` routine, on the triangle. So a trace of it has
664/// a driver that is not the NMI handler, an enclosing routine that is not the
665/// driver, a nested routine inside it, two non-APU writes in `$4000-$4017`,
666/// and reset code that falls through onto the address the IRQ vector names.
667/// The addresses are in [`example`].
668pub fn example_music_rom() -> Vec<u8> {
669    let code: &[u8] = &[
670        // RESET: $C000
671        0x78, // $C000 SEI
672        0xD8, // $C001 CLD
673        0xA2, 0xFF, // $C002 LDX #$FF
674        0x9A, // $C004 TXS
675        0xA9, 0x00, // $C005 LDA #$00
676        0x20, 0x45, 0xC0, // $C007 JSR INIT
677        // VW1: $C00A
678        0x2C, 0x02, 0x20, // $C00A BIT $2002
679        0x10, 0xFB, // $C00D BPL VW1
680        // VW2: $C00F
681        0x2C, 0x02, 0x20, // $C00F BIT $2002
682        0x10, 0xFB, // $C012 BPL VW2
683        0xA9, 0x80, // $C014 LDA #$80
684        0x8D, 0x00, 0x20, // $C016 STA $2000
685        // LOOP: $C019
686        0x20, 0x1F, 0xC0, // $C019 JSR IDLE
687        0x4C, 0x19, 0xC0, // $C01C JMP LOOP
688        // IDLE: $C01F
689        0x60, // $C01F RTS
690        // NMI: $C020
691        0x48, // $C020 PHA
692        0x8A, // $C021 TXA
693        0x48, // $C022 PHA
694        0x98, // $C023 TYA
695        0x48, // $C024 PHA
696        0x20, 0x2E, 0xC0, // $C025 JSR BODY
697        0x68, // $C028 PLA
698        0xA8, // $C029 TAY
699        0x68, // $C02A PLA
700        0xAA, // $C02B TAX
701        0x68, // $C02C PLA
702        0x40, // $C02D RTI
703        // BODY: $C02E
704        0xA9, 0x02, // $C02E LDA #$02
705        0x8D, 0x14, 0x40, // $C030 STA $4014
706        0x20, 0x3A, 0xC0, // $C033 JSR JOY
707        0x20, 0x59, 0xC0, // $C036 JSR PLAY
708        0x60, // $C039 RTS
709        // JOY: $C03A
710        0xA9, 0x01, // $C03A LDA #$01
711        0x8D, 0x16, 0x40, // $C03C STA $4016
712        0xA9, 0x00, // $C03F LDA #$00
713        0x8D, 0x16, 0x40, // $C041 STA $4016
714        0x60, // $C044 RTS
715        // INIT: $C045
716        0xA9, 0x0F, // $C045 LDA #$0F
717        0x8D, 0x15, 0x40, // $C047 STA $4015
718        0xA9, 0x30, // $C04A LDA #$30
719        0x8D, 0x04, 0x40, // $C04C STA $4004
720        0x8D, 0x0C, 0x40, // $C04F STA $400C
721        0xA9, 0x00, // $C052 LDA #$00
722        0x85, 0x00, // $C054 STA $00
723        0x85, 0x01, // $C056 STA $01
724        0x60, // $C058 RTS
725        // PLAY: $C059
726        0xC6, 0x01, // $C059 DEC $01
727        0x10, 0x20, // $C05B BPL DONE
728        0xA9, 0x07, // $C05D LDA #$07
729        0x85, 0x01, // $C05F STA $01
730        0xA6, 0x00, // $C061 LDX $00
731        0xA9, 0xBF, // $C063 LDA #$BF
732        0x8D, 0x00, 0x40, // $C065 STA $4000
733        0xBD, 0x8F, 0xC0, // $C068 LDA LO,X
734        0x8D, 0x02, 0x40, // $C06B STA $4002
735        0xBD, 0x97, 0xC0, // $C06E LDA HI,X
736        0x8D, 0x03, 0x40, // $C071 STA $4003
737        0x20, 0x7E, 0xC0, // $C074 JSR TRI
738        0xE8, // $C077 INX
739        0x8A, // $C078 TXA
740        0x29, 0x07, // $C079 AND #$07
741        0x85, 0x00, // $C07B STA $00
742        // DONE: $C07D
743        0x60, // $C07D RTS
744        // TRI: $C07E
745        0xA9, 0xC0, // $C07E LDA #$C0
746        0x8D, 0x08, 0x40, // $C080 STA $4008
747        0xBD, 0x8F, 0xC0, // $C083 LDA LO,X
748        0x8D, 0x0A, 0x40, // $C086 STA $400A
749        0xA9, 0x08, // $C089 LDA #$08
750        0x8D, 0x0B, 0x40, // $C08B STA $400B
751        0x60, // $C08E RTS
752        // LO: $C08F
753        0xFD, 0xE2, 0xC9, 0xBD, 0xA9, 0x96, 0x86, 0x7E, // $C08F .db
754        // HI: $C097
755        0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, // $C097 .db
756    ];
757    let mut prg = vec![0u8; 0x4000];
758    prg[..code.len()].copy_from_slice(code);
759    // Vectors: NMI, RESET, IRQ. The IRQ is never enabled, and its vector
760    // names the spin loop on purpose: the reset code falls through onto that
761    // address, which the tracer must not take for an interrupt entry.
762    prg[0x3FFA..0x3FFC].copy_from_slice(&example::NMI.to_le_bytes());
763    prg[0x3FFC..0x3FFE].copy_from_slice(&0xC000u16.to_le_bytes());
764    prg[0x3FFE..0x4000].copy_from_slice(&example::LOOP.to_le_bytes());
765    let mut rom = vec![b'N', b'E', b'S', 0x1A, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
766    rom.extend_from_slice(&prg);
767    rom.extend(core::iter::repeat_n(0u8, 0x2000));
768    rom
769}
770
771#[cfg(test)]
772mod tests {
773    use super::*;
774
775    use super::example::{BODY, INIT, NMI, PLAY};
776
777    fn music_rom() -> Vec<u8> {
778        example_music_rom()
779    }
780
781    fn trace(nes: &mut Nes, frames: u32) -> Tracer {
782        let mut t = Tracer::new(nes);
783        for _ in 0..frames {
784            assert!(t.run_frame(nes), "a frame completes");
785        }
786        t
787    }
788
789    #[test]
790    fn the_driver_and_its_init_are_found() {
791        let mut nes = Nes::from_rom(&music_rom()).expect("loads");
792        let t = trace(&mut nes, 120);
793        let p = propose(&t).expect("a proposal");
794        assert_eq!(p.play.addr, PLAY, "play, not the enclosing {BODY:04X}");
795        assert_eq!(p.play.calls_per_frame, 1);
796        assert!(p.play.frames_with_writes >= 14, "{p:?}");
797        assert_eq!(
798            p.play.frames_enclosed,
799            p.play.frames_with_writes - 1,
800            "{p:?}"
801        );
802        assert_eq!(
803            p.init,
804            InitEvidence::Routine {
805                addr: INIT,
806                writes: 3,
807                calls: 1
808            }
809        );
810        // The shadow stack saw only what the program did: one NMI per frame
811        // and never an IRQ (the reset code falls through onto the address
812        // the IRQ vector names, which is not an interrupt).
813        assert!(
814            t.calls().iter().all(|c| c.kind != CallKind::Irq),
815            "no IRQ was taken"
816        );
817        let nmis = t.calls().iter().filter(|c| c.kind == CallKind::Nmi).count();
818        assert!((115..=119).contains(&nmis), "{nmis} NMIs in 120 frames");
819        // The OAM DMA and controller strobe were not taken for APU writes.
820        assert!(
821            t.writes()
822                .iter()
823                .all(|w| w.addr != 0x4014 && w.addr != 0x4016)
824        );
825    }
826
827    #[test]
828    fn the_ripped_nsf_plays_the_same_tune() {
829        let rom = music_rom();
830        let mut nes = Nes::from_rom(&rom).expect("loads");
831        let game = trace(&mut nes, 200);
832        let proposal = propose(&game).expect("a proposal");
833        let (nsf, noop) =
834            build_nsf(&rom, &proposal, nes.region(), &NsfInfo::default()).expect("an NSF");
835        assert_eq!(noop, None);
836        assert_eq!(&nsf[..5], b"NESM\x1A");
837        assert_eq!(nsf.len(), 0x80 + 0x8000, "a 16 KiB PRG fills $8000-$FFFF");
838
839        // Play it in the NSF player and trace that run the same way.
840        let mut player = Nes::from_nsf(&nsf).expect("the NSF parses");
841        let played = trace(&mut player, 200);
842        let replay = propose(&played).expect("the NSF's own run has a driver");
843        assert_eq!(replay.play.addr, PLAY, "the player calls the proposed play");
844
845        // Call for call, the NSF's play makes the game's APU writes.
846        let ours = game.writes_per_call(PLAY);
847        let theirs = played.writes_per_call(PLAY);
848        let n = ours.len().min(theirs.len());
849        assert!(n >= 150, "{n} play calls compared");
850        assert_eq!(ours[..n], theirs[..n], "the same tune");
851        let notes = ours[..n].iter().filter(|c| !c.is_empty()).count();
852        assert!(notes >= 18, "{notes} calls played a note");
853
854        // And the player is audible.
855        let audio = player.drain_audio();
856        let peak = audio.iter().fold(0.0f32, |m, &v| m.max(v.abs()));
857        assert!(peak > 0.05, "peak {peak}");
858    }
859
860    #[test]
861    fn a_driver_in_ram_is_refused() {
862        // A play routine at $0300: code the game copied to RAM, which the
863        // ROM image does not hold and the NSF player clears.
864        let t = synthetic(
865            &[(CallKind::Nmi, NMI), (CallKind::Jsr, 0x0300)],
866            &[(1, &[0, 1])],
867        );
868        let p = propose(&t).expect("a proposal");
869        assert_eq!(p.play.addr, 0x0300);
870        let e = build_nsf(&music_rom(), &p, Region::Ntsc, &NsfInfo::default()).unwrap_err();
871        assert!(
872            matches!(e, RipError::Unsupported(ref m) if m.contains("runs from RAM")),
873            "{e}"
874        );
875        let t = synthetic(
876            &[
877                (CallKind::Jsr, 0x6000),
878                (CallKind::Nmi, NMI),
879                (CallKind::Jsr, PLAY),
880            ],
881            &[(0, &[0]), (1, &[1, 2])],
882        );
883        let p = propose(&t).expect("a proposal");
884        let e = build_nsf(&music_rom(), &p, Region::Ntsc, &NsfInfo::default()).unwrap_err();
885        assert!(
886            matches!(e, RipError::Unsupported(ref m) if m.contains("init $6000")),
887            "{e}"
888        );
889    }
890
891    #[test]
892    fn a_bank_switched_board_is_refused() {
893        let mut rom = music_rom();
894        rom[6] = 0x20; // mapper 2 (UxROM)
895        let mut nes = Nes::from_rom(&music_rom()).expect("loads");
896        let p = propose(&trace(&mut nes, 30)).expect("a proposal");
897        let e = build_nsf(&rom, &p, Region::Ntsc, &NsfInfo::default()).unwrap_err();
898        assert!(
899            matches!(e, RipError::Unsupported(ref m) if m.contains("mapper 2")),
900            "{e}"
901        );
902    }
903
904    fn synthetic(calls: &[(CallKind, u16)], writes: &[(u64, &[u32])]) -> Tracer {
905        Tracer {
906            stack: Vec::new(),
907            calls: calls
908                .iter()
909                .map(|&(kind, target)| Call {
910                    kind,
911                    target,
912                    frame: 0,
913                })
914                .collect(),
915            writes: writes
916                .iter()
917                .map(|&(frame, chain)| ApuWrite {
918                    frame,
919                    addr: 0x4000,
920                    value: 0,
921                    pc: 0,
922                    chain: chain.to_vec(),
923                })
924                .collect(),
925            frames: 2,
926        }
927    }
928
929    #[test]
930    fn an_inline_driver_has_no_play_routine() {
931        // Writes straight from the NMI handler: no subroutine encloses them.
932        let t = synthetic(
933            &[(CallKind::Nmi, NMI), (CallKind::Nmi, NMI)],
934            &[(1, &[0]), (2, &[1])],
935        );
936        assert_eq!(propose(&t), Err(RipError::NoSubroutine));
937        assert_eq!(propose(&synthetic(&[], &[])), Err(RipError::NoWrites));
938    }
939
940    #[test]
941    fn reset_code_that_writes_inline_gets_a_no_op_init() {
942        // One write with an empty chain (the reset code itself), then the
943        // driver's writes under NMI -> JSR play.
944        let t = synthetic(
945            &[(CallKind::Nmi, NMI), (CallKind::Jsr, PLAY)],
946            &[(0, &[]), (1, &[0, 1])],
947        );
948        let p = propose(&t).expect("a proposal");
949        assert_eq!(p.play.addr, PLAY);
950        assert_eq!(
951            p.init,
952            InitEvidence::None {
953                writes_outside_play: 1
954            }
955        );
956        let (nsf, noop) =
957            build_nsf(&music_rom(), &p, Region::Ntsc, &NsfInfo::default()).expect("an NSF");
958        let at = noop.expect("a no-op init").addr;
959        assert_eq!(u16::from_le_bytes([nsf[0x0A], nsf[0x0B]]), at);
960        assert_eq!(nsf[0x80 + usize::from(at - 0x8000)], 0x60, "init is an RTS");
961    }
962
963    #[test]
964    fn init_is_the_innermost_routine_enclosing_the_setup_writes() {
965        // Reset code calls a setup routine, which calls the engine's init:
966        // both enclose the writes made outside play; the innermost is init.
967        let t = synthetic(
968            &[
969                (CallKind::Jsr, 0xC100),
970                (CallKind::Jsr, INIT),
971                (CallKind::Nmi, NMI),
972                (CallKind::Jsr, PLAY),
973            ],
974            &[(0, &[0, 1]), (0, &[0, 1]), (1, &[2, 3])],
975        );
976        let p = propose(&t).expect("a proposal");
977        assert_eq!(p.play.addr, PLAY);
978        assert_eq!(
979            p.init,
980            InitEvidence::Routine {
981                addr: INIT,
982                writes: 2,
983                calls: 1
984            }
985        );
986    }
987
988    #[test]
989    fn the_header_carries_the_metadata_cut_to_31_bytes() {
990        let t = synthetic(&[(CallKind::Jsr, PLAY)], &[(1, &[0])]);
991        let p = propose(&t).expect("a proposal");
992        let info = NsfInfo {
993            name: "x".repeat(40),
994            artist: "Ä".repeat(20),
995            copyright: String::from("2026 test"),
996        };
997        let (nsf, _) = build_nsf(&music_rom(), &p, Region::Pal, &info).expect("an NSF");
998        assert_eq!(&nsf[0x0E..0x0E + 31], "x".repeat(31).as_bytes());
999        assert_eq!(nsf[0x0E + 31], 0, "NUL-terminated");
1000        // 'Ä' is two bytes: 15 fit in 31, the 16th would split.
1001        assert_eq!(&nsf[0x2E..0x2E + 30], "Ä".repeat(15).as_bytes());
1002        assert_eq!(nsf[0x2E + 30], 0);
1003        assert_eq!(&nsf[0x4E..0x4E + 9], b"2026 test");
1004        assert_eq!(nsf[0x7A], 1, "PAL");
1005        assert_eq!(u16::from_le_bytes([nsf[0x6E], nsf[0x6F]]), 16_639);
1006        assert_eq!(u16::from_le_bytes([nsf[0x78], nsf[0x79]]), 19_997);
1007    }
1008}