1use alloc::string::String;
62use alloc::vec::Vec;
63use alloc::{format, vec};
64
65use crate::{Nes, Region};
66
67#[must_use]
70pub const fn is_apu_register(addr: u16) -> bool {
71 matches!(addr, 0x4000..=0x4013 | 0x4015 | 0x4017)
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum CallKind {
77 Jsr,
79 Nmi,
81 Irq,
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct Call {
88 pub kind: CallKind,
90 pub target: u16,
92 pub frame: u64,
94}
95
96#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct ApuWrite {
99 pub frame: u64,
101 pub addr: u16,
103 pub value: u8,
105 pub pc: u16,
107 pub chain: Vec<u32>,
109}
110
111pub struct Tracer {
113 stack: Vec<(u32, u8)>,
115 calls: Vec<Call>,
116 writes: Vec<ApuWrite>,
117 frames: u64,
118}
119
120const MAX_STEPS_PER_FRAME: u32 = 80_000;
124
125impl Tracer {
126 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 #[must_use]
140 pub fn calls(&self) -> &[Call] {
141 &self.calls
142 }
143
144 #[must_use]
146 pub fn writes(&self) -> &[ApuWrite] {
147 &self.writes
148 }
149
150 #[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 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 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 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 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 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 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 #[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 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#[derive(Clone, Debug, PartialEq, Eq)]
296pub struct PlayEvidence {
297 pub addr: u16,
299 pub frames_with_writes: u64,
301 pub frames_enclosed: u64,
303 pub frames_called: u64,
305 pub calls_per_frame: u32,
307 pub writes_enclosed: u64,
309 pub writes_total: u64,
311}
312
313#[derive(Clone, Debug, PartialEq, Eq)]
315pub enum InitEvidence {
316 Routine {
318 addr: u16,
320 writes: u64,
322 calls: u64,
324 },
325 None {
328 writes_outside_play: u64,
330 },
331}
332
333#[derive(Clone, Debug, PartialEq, Eq)]
335pub struct Proposal {
336 pub play: PlayEvidence,
338 pub init: InitEvidence,
340}
341
342#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
344pub enum RipError {
345 #[error("the run made no APU register writes; nothing to rip")]
347 NoWrites,
348 #[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 #[error("{0}")]
357 Unsupported(String),
358}
359
360fn 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
373fn pick_play(t: &Tracer, frames: &[u64]) -> Result<(u16, u64), RipError> {
378 let mut enclosed: Vec<(u16, u64)> = Vec::new(); let mut depth: Vec<(u16, usize)> = Vec::new(); 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
418fn 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
446fn 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
472pub fn propose(t: &Tracer) -> Result<Proposal, RipError> {
478 if t.writes.is_empty() {
479 return Err(RipError::NoWrites);
480 }
481 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
506const HEADER: usize = 0x80;
508
509#[derive(Clone, Debug, Default)]
512pub struct NsfInfo {
513 pub name: String,
515 pub artist: String,
517 pub copyright: String,
519}
520
521fn put_str(out: &mut [u8], s: &str) {
522 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
530pub 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 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; out[0x06] = 1; out[0x07] = 1; 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 out[0x6E..0x70].copy_from_slice(&16_639u16.to_le_bytes());
619 out[0x78..0x7A].copy_from_slice(&19_997u16.to_le_bytes());
621 out[0x7A] = u8::from(matches!(region, Region::Pal));
622 out[0x7B] = 0; out.extend_from_slice(&image);
624 Ok((out, noop))
625}
626
627#[derive(Clone, Copy, Debug, PartialEq, Eq)]
629pub struct NoOpInit {
630 pub addr: u16,
632}
633
634pub mod example {
637 pub const INIT: u16 = 0xC045;
639 pub const PLAY: u16 = 0xC059;
641 pub const BODY: u16 = 0xC02E;
643 pub const NMI: u16 = 0xC020;
645 pub const LOOP: u16 = 0xC019;
648}
649
650pub fn example_music_rom() -> Vec<u8> {
669 let code: &[u8] = &[
670 0x78, 0xD8, 0xA2, 0xFF, 0x9A, 0xA9, 0x00, 0x20, 0x45, 0xC0, 0x2C, 0x02, 0x20, 0x10, 0xFB, 0x2C, 0x02, 0x20, 0x10, 0xFB, 0xA9, 0x80, 0x8D, 0x00, 0x20, 0x20, 0x1F, 0xC0, 0x4C, 0x19, 0xC0, 0x60, 0x48, 0x8A, 0x48, 0x98, 0x48, 0x20, 0x2E, 0xC0, 0x68, 0xA8, 0x68, 0xAA, 0x68, 0x40, 0xA9, 0x02, 0x8D, 0x14, 0x40, 0x20, 0x3A, 0xC0, 0x20, 0x59, 0xC0, 0x60, 0xA9, 0x01, 0x8D, 0x16, 0x40, 0xA9, 0x00, 0x8D, 0x16, 0x40, 0x60, 0xA9, 0x0F, 0x8D, 0x15, 0x40, 0xA9, 0x30, 0x8D, 0x04, 0x40, 0x8D, 0x0C, 0x40, 0xA9, 0x00, 0x85, 0x00, 0x85, 0x01, 0x60, 0xC6, 0x01, 0x10, 0x20, 0xA9, 0x07, 0x85, 0x01, 0xA6, 0x00, 0xA9, 0xBF, 0x8D, 0x00, 0x40, 0xBD, 0x8F, 0xC0, 0x8D, 0x02, 0x40, 0xBD, 0x97, 0xC0, 0x8D, 0x03, 0x40, 0x20, 0x7E, 0xC0, 0xE8, 0x8A, 0x29, 0x07, 0x85, 0x00, 0x60, 0xA9, 0xC0, 0x8D, 0x08, 0x40, 0xBD, 0x8F, 0xC0, 0x8D, 0x0A, 0x40, 0xA9, 0x08, 0x8D, 0x0B, 0x40, 0x60, 0xFD, 0xE2, 0xC9, 0xBD, 0xA9, 0x96, 0x86, 0x7E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, ];
757 let mut prg = vec![0u8; 0x4000];
758 prg[..code.len()].copy_from_slice(code);
759 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 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 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 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 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 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 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; 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 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 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 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 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}