Skip to main content

rustynes_core/
stems.rs

1//! v3.6.0 (`T-AUDIO-STEMS`) — per-channel audio stems, rendered offline from
2//! the APU's own per-cycle mix trace.
3//!
4//! A *stem* is one sound source rendered on its own: pulse 1, pulse 2, the
5//! triangle, the noise channel, the DMC, and the cartridge's expansion audio
6//! (VRC6, VRC7, Namco 163, Sunsoft 5B, MMC5, FDS, or an NSF's chips). A
7//! musician wants them as separate files that line up sample for sample with
8//! the mixed output, so they can be remixed, and a researcher wants them to
9//! hear what one channel is doing under the others.
10//!
11//! # How they are made: one emulation pass, re-rendered offline
12//!
13//! The emulation runs **once**, unchanged, with the APU's audio provenance
14//! armed (`Nes::set_audio_provenance`, the v2.3.7 "Overtone" debug facility).
15//! While armed, the APU records, for every CPU cycle, the five raw channel
16//! outputs it handed the mixer and the raw expansion sample (`MixRecord`).
17//! [`StemCapture`] reads that trace after each frame and pushes each source,
18//! **alone**, through a private copy of the same output pipeline the console
19//! audio goes through: the same lookup-table mixer, a band-limited buffer
20//! built with the same sample rate and CPU clock, and the same analog filter
21//! model. Nothing is added to the APU's per-cycle work, and nothing in the
22//! emulation changes: the stems are a function of a trace the core already
23//! knew how to record. With provenance disarmed (every other run) the core is
24//! exactly what it was; with it armed, the recording is output-only and is
25//! never read back into synthesis (see `rustynes_apu::provenance`).
26//!
27//! The capture also re-renders the **mix** itself from the trace, through its
28//! own pipeline, and compares it with what the core produced
29//! ([`StemCapture::mix_mismatches`]). The two are bit-identical: the same
30//! values were added to buffers built the same way in the same order. That
31//! comparison is what licenses the stems — it shows the private pipeline is
32//! the console's pipeline, rather than a lookalike.
33//!
34//! # What "the stems sum to the mix" means, precisely
35//!
36//! The 2A03 mixer is **not linear** (nesdev "APU Mixer"):
37//!
38//! ```text
39//! out = pulse_table[p1 + p2] + tnd_table[3*tri + 2*noise + dmc] + expansion
40//! pulse_table[n] = 95.52 / (8128 / n + 100)
41//! tnd_table[n]   = 163.67 / (24329 / n + 100)
42//! ```
43//!
44//! Both tables are concave, so two channels sounding together come out quieter
45//! than the two alone added up. Each stem here is its channel **rendered alone
46//! through that same mixer** — pulse 1's stem is `pulse_table[p1]`, the
47//! noise's is `tnd_table[2*noise]`, and so on — because that is what the
48//! channel sounds like on the console with every other channel silent. The
49//! sum of the six source stems is therefore not the mix; it differs by the
50//! mixer's **interaction term**
51//!
52//! ```text
53//! interaction = out - (pulse_table[p1] + pulse_table[p2]
54//!                      + tnd_table[3*tri] + tnd_table[2*noise] + tnd_table[dmc]
55//!                      + expansion)
56//! ```
57//!
58//! which is zero whenever at most one channel of each group is non-zero, and
59//! never positive before the filter (concavity). The capture renders that term
60//! as a seventh track, [`Stem::Interaction`], through the same pipeline. The
61//! band-limited buffer and the filter chain are linear, so
62//!
63//! ```text
64//! mix = Σ six source stems + interaction      (to f32 rounding)
65//! ```
66//!
67//! and the residual is measured, not assumed: [`StemCapture::max_sum_error`]
68//! holds the largest `|mix - Σ all seven|` seen, which the gate in this
69//! module's tests and in `rustynes-test-harness/tests/audio_stems.rs` bounds
70//! (measured at about `1e-6` against a signal near `±0.2`; see
71//! `docs/audio-stems.md`). The expansion stem enters the mixer linearly, so it
72//! has no interaction term of its own.
73//!
74//! # What is not split
75//!
76//! The expansion stem is the cartridge's whole expansion output, the value the
77//! board's `mix_audio` returns. A board with one chip (every cartridge) gets
78//! one stem named after it. An NSF that enables several chips at once gets
79//! them summed into the one stem, because the trace records only their sum;
80//! splitting them would need a per-chip record in the mapper's per-cycle
81//! path, which this design deliberately does not add. Nor are a chip's own
82//! voices (VRC6's two pulses and saw, N163's eight channels) split.
83
84use alloc::vec::Vec;
85
86use rustynes_apu::provenance::MixRecord;
87use rustynes_apu::{BlipBuf, CPU_HZ_NTSC, CPU_HZ_PAL, FilterModel, Mixer};
88
89use crate::{Nes, Region};
90
91/// The number of tracks a [`StemCapture`] renders ([`Stem::ALL`]).
92pub const STEM_COUNT: usize = 7;
93
94/// One rendered track.
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
96pub enum Stem {
97    /// Pulse 1, alone through the pulse table.
98    Pulse1,
99    /// Pulse 2, alone through the pulse table.
100    Pulse2,
101    /// The triangle, alone through the TND table (`tnd_table[3 * tri]`).
102    Triangle,
103    /// The noise channel, alone (`tnd_table[2 * noise]`).
104    Noise,
105    /// The DMC, alone (`tnd_table[dmc]`).
106    Dmc,
107    /// The cartridge's expansion audio, which the mixer adds linearly.
108    Expansion,
109    /// The mixer's interaction term: the mix minus the six stems above, so
110    /// that all seven sum to the mix. See the module docs.
111    Interaction,
112}
113
114impl Stem {
115    /// Every track, in file order.
116    pub const ALL: [Self; STEM_COUNT] = [
117        Self::Pulse1,
118        Self::Pulse2,
119        Self::Triangle,
120        Self::Noise,
121        Self::Dmc,
122        Self::Expansion,
123        Self::Interaction,
124    ];
125
126    /// A short, stable, file-name-safe name (`"pulse1"`, `"dmc"`, ...).
127    #[must_use]
128    pub const fn name(self) -> &'static str {
129        match self {
130            Self::Pulse1 => "pulse1",
131            Self::Pulse2 => "pulse2",
132            Self::Triangle => "triangle",
133            Self::Noise => "noise",
134            Self::Dmc => "dmc",
135            Self::Expansion => "expansion",
136            Self::Interaction => "interaction",
137        }
138    }
139
140    /// The track's index in [`Self::ALL`].
141    #[must_use]
142    pub const fn index(self) -> usize {
143        self as usize
144    }
145}
146
147/// Why a capture could not continue.
148#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
149pub enum StemError {
150    /// The capture was started after the console had already produced audio,
151    /// so the private pipeline would start at a different phase from the
152    /// console's and every sample would differ. Start it before the first
153    /// frame.
154    #[error("the stem capture must start before the first frame is run")]
155    StartedLate,
156    /// The APU's provenance was disarmed while the capture ran.
157    #[error("audio provenance was disarmed during the capture")]
158    Disarmed,
159    /// A frame ran more CPU cycles than the mix trace holds, so cycles were
160    /// dropped and the stems would be silently short.
161    #[error("the mix trace was truncated in a frame (too many cycles)")]
162    Truncated,
163    /// The trace did not start where the previous frame ended: a frame was run
164    /// without being captured, or the console was reset under the capture.
165    #[error("the mix trace skipped cycles {expected}..{found}")]
166    Gap {
167        /// The first cycle the capture expected.
168        expected: u64,
169        /// The first cycle the trace actually holds.
170        found: u64,
171    },
172}
173
174/// The most CPU cycles a console may have run before a capture starts: the
175/// reset sequence's own (8 when measured), with headroom. A capture refuses
176/// to start past it ([`StemError::StartedLate`]).
177const MAX_PRE_CYCLES: u64 = 64;
178
179/// One output pipeline: a band-limited buffer with its filter, as the APU
180/// builds its own.
181fn pipeline(sample_rate: u32, region: Region, filter: FilterModel) -> BlipBuf {
182    // Mirrors `Apu::new`: only true PAL runs the PAL CPU clock; NTSC, Dendy
183    // and the treated-as-NTSC "Multi" all build at the NTSC rate.
184    let cpu_rate = match region {
185        Region::Pal => CPU_HZ_PAL,
186        _ => CPU_HZ_NTSC,
187    };
188    let mut b = BlipBuf::new(sample_rate, cpu_rate);
189    b.set_filter_model(filter);
190    b
191}
192
193/// The per-cycle value each track receives for one mix record.
194///
195/// Returns the six source values and the interaction term, in [`Stem::ALL`]
196/// order. Each source goes through the same `Mixer::mix` the APU calls, with
197/// every other channel at zero — so a stem is exactly what the console would
198/// mix for that channel playing alone.
199#[must_use]
200pub fn stem_values(mixer: &Mixer, r: &MixRecord) -> [f32; STEM_COUNT] {
201    let p1 = mixer.mix(r.pulse1, 0, 0, 0, 0);
202    let p2 = mixer.mix(0, r.pulse2, 0, 0, 0);
203    let tri = mixer.mix(0, 0, r.triangle, 0, 0);
204    let noise = mixer.mix(0, 0, 0, r.noise, 0);
205    let dmc = mixer.mix(0, 0, 0, 0, r.dmc);
206    let ext = r.external;
207    let interaction = r.mixed - (p1 + p2 + tri + noise + dmc + ext);
208    [p1, p2, tri, noise, dmc, ext, interaction]
209}
210
211/// A running stem capture over one [`Nes`].
212///
213/// Create it right after the console is built and before its first frame
214/// ([`Self::start`]); then, after every `run_frame`, call
215/// [`Self::after_frame`], which returns that frame's samples for the mix and
216/// each track. All eight streams always have the same length.
217pub struct StemCapture {
218    mixer: Mixer,
219    /// The re-rendered mix, compared against the core's own output.
220    mix: alloc::boxed::Box<BlipBuf>,
221    /// One pipeline per track, in [`Stem::ALL`] order. Heap-allocated one
222    /// by one: a pipeline holds its band-limited ring inline (about 16 KiB),
223    /// and eight of them built in place would put over 130 KiB on the stack.
224    tracks: Vec<BlipBuf>,
225    /// The cycle the next frame's trace must start at.
226    next_cycle: Option<u64>,
227    frame_mix: Vec<f32>,
228    frame_core: Vec<f32>,
229    frame_tracks: [Vec<f32>; STEM_COUNT],
230    mix_mismatches: u64,
231    trace_mismatches: u64,
232    max_sum_error: f32,
233    samples: u64,
234}
235
236/// One frame's samples, borrowed from the capture.
237#[derive(Debug)]
238pub struct StemFrame<'a> {
239    /// The console's own mixed output for the frame (what a host would play).
240    pub mix: &'a [f32],
241    /// Each track's samples, indexed by [`Stem::index`].
242    pub tracks: [&'a [f32]; STEM_COUNT],
243}
244
245impl StemCapture {
246    /// Arm the console's audio provenance and start a capture at the sample
247    /// rate the console was built with (`sample_rate` must be that rate: the
248    /// `Nes` does not report it, and a different one fails the mix check on
249    /// the first frame).
250    ///
251    /// # Errors
252    ///
253    /// [`StemError::StartedLate`] if the console has already produced audio.
254    pub fn start(nes: &mut Nes, sample_rate: u32) -> Result<Self, StemError> {
255        // The reset sequence ticks the APU a few cycles inside the
256        // constructor (8 on every board measured), before any trace can be
257        // armed. Those cycles are replayed below; a capture started after a
258        // frame has run would have thousands to replay, from values nobody
259        // recorded.
260        let pre = nes.bus().cycle();
261        if pre > MAX_PRE_CYCLES {
262            return Err(StemError::StartedLate);
263        }
264        nes.set_audio_provenance(true);
265        let region = nes.region();
266        let filter = nes.apu_filter_model();
267        let mut cap = Self {
268            mixer: Mixer::new(),
269            mix: alloc::boxed::Box::new(pipeline(sample_rate, region, filter)),
270            tracks: (0..STEM_COUNT)
271                .map(|_| pipeline(sample_rate, region, filter))
272                .collect(),
273            // The first frame's trace must begin where the constructor left
274            // off, or the replay below is of the wrong cycles.
275            next_cycle: Some(pre),
276            frame_mix: Vec::new(),
277            frame_core: Vec::new(),
278            frame_tracks: core::array::from_fn(|_| Vec::new()),
279            mix_mismatches: 0,
280            trace_mismatches: 0,
281            max_sum_error: 0.0,
282            samples: 0,
283        };
284        // Replay the constructor's cycles. Nothing has been written to an
285        // APU register yet, so every channel has held its power-on output
286        // through them: the outputs the APU presents now are the ones it
287        // mixed then. The bit-exact mix check proves it on the first frame,
288        // and fails loudly if a board ever ticks something audible there.
289        let v = nes.apu_snapshot();
290        let rec = MixRecord {
291            mixed: cap
292                .mixer
293                .mix(v.pulse1, v.pulse2, v.triangle, v.noise, v.dmc)
294                + v.external,
295            external: v.external,
296            pulse1: v.pulse1,
297            pulse2: v.pulse2,
298            triangle: v.triangle,
299            noise: v.noise,
300            dmc: v.dmc,
301        };
302        for _ in 0..pre {
303            cap.push(&rec);
304        }
305        Ok(cap)
306    }
307
308    /// Feed one CPU cycle's record to the re-rendered mix and every track.
309    fn push(&mut self, r: &MixRecord) {
310        self.mix.add_sample(r.mixed);
311        for (buf, v) in self.tracks.iter_mut().zip(stem_values(&self.mixer, r)) {
312            buf.add_sample(v);
313        }
314    }
315
316    /// Read the frame the console just ran: its mix trace and its audio.
317    ///
318    /// Drains the console's audio buffer (the returned [`StemFrame::mix`] is
319    /// that audio), so a host that plays the audio takes it from here.
320    ///
321    /// # Errors
322    ///
323    /// See [`StemError`]; a frame that fails leaves the capture unusable.
324    pub fn after_frame(&mut self, nes: &mut Nes) -> Result<StemFrame<'_>, StemError> {
325        let trace = nes.mix_trace().ok_or(StemError::Disarmed)?;
326        if trace.truncated() {
327            return Err(StemError::Truncated);
328        }
329        if let Some(expected) = self.next_cycle
330            && trace.first_cycle() != expected
331        {
332            return Err(StemError::Gap {
333                expected,
334                found: trace.first_cycle(),
335            });
336        }
337        self.next_cycle = Some(trace.first_cycle() + trace.records().len() as u64);
338        for r in trace.records() {
339            // The record must describe the mix it carries: the same five
340            // arguments through the same mixer, plus the expansion sample.
341            // Counted rather than asserted, so a host can report it.
342            let all = self
343                .mixer
344                .mix(r.pulse1, r.pulse2, r.triangle, r.noise, r.dmc)
345                + r.external;
346            if all.to_bits() != r.mixed.to_bits() {
347                self.trace_mismatches += 1;
348            }
349            self.push(r);
350        }
351
352        self.frame_core.clear();
353        self.frame_core.extend(nes.drain_audio());
354        self.frame_mix.clear();
355        self.frame_mix.extend(self.mix.drain_all());
356        for (out, buf) in self.frame_tracks.iter_mut().zip(self.tracks.iter_mut()) {
357            out.clear();
358            out.extend(buf.drain_all());
359        }
360
361        // Compare the re-rendered mix with the console's, bit for bit, and
362        // the seven tracks' sum with the mix.
363        let n = self.frame_core.len();
364        if self.frame_mix.len() != n {
365            self.mix_mismatches += n.abs_diff(self.frame_mix.len()) as u64;
366        }
367        for (i, (&core, &ours)) in self.frame_core.iter().zip(&self.frame_mix).enumerate() {
368            if core.to_bits() != ours.to_bits() {
369                self.mix_mismatches += 1;
370            }
371            let sum: f32 = self.frame_tracks.iter().map(|t| t[i]).sum();
372            let err = (core - sum).abs();
373            if err > self.max_sum_error || err.is_nan() {
374                self.max_sum_error = err;
375            }
376        }
377        self.samples += n as u64;
378
379        Ok(StemFrame {
380            mix: &self.frame_core,
381            tracks: core::array::from_fn(|i| self.frame_tracks[i].as_slice()),
382        })
383    }
384
385    /// How many output samples of the re-rendered mix differed (in bits, or in
386    /// count) from the console's own output. Zero on every run so far; a
387    /// non-zero value means the private pipeline is not the console's, and the
388    /// stems should not be trusted.
389    #[must_use]
390    pub const fn mix_mismatches(&self) -> u64 {
391        self.mix_mismatches
392    }
393
394    /// How many trace records carried a `mixed` value that the mixer does not
395    /// produce from the record's own channel values. Zero unless a host set a
396    /// channel mask or gain (the trace records raw channel outputs, and the
397    /// mix is then the masked or scaled one).
398    #[must_use]
399    pub const fn trace_mismatches(&self) -> u64 {
400        self.trace_mismatches
401    }
402
403    /// The largest `|mix - Σ tracks|` seen so far, over every sample.
404    #[must_use]
405    pub const fn max_sum_error(&self) -> f32 {
406        self.max_sum_error
407    }
408
409    /// Output samples captured so far (per track).
410    #[must_use]
411    pub const fn samples(&self) -> u64 {
412        self.samples
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use alloc::vec;
420    use rustynes_apu::CHANNEL_MASK_ALL;
421
422    /// A one-bank NROM that programs every 2A03 channel at once and loops: the
423    /// two pulses at different volumes and pitches, the triangle, the noise,
424    /// and the DMC's direct load (`$4011`), so every group of the mixer has
425    /// two or more channels sounding together and the interaction term is
426    /// non-zero.
427    fn all_channels_rom() -> Vec<u8> {
428        let mut prg = vec![0xEAu8; 0x4000];
429        let code: &[u8] = &[
430            0x78, // SEI
431            0xA9, 0x0F, 0x8D, 0x15, 0x40, // LDA #$0F ; STA $4015
432            0xA9, 0xBF, 0x8D, 0x00, 0x40, // pulse 1: duty 2, const vol 15
433            0xA9, 0xFD, 0x8D, 0x02, 0x40, 0xA9, 0x00, 0x8D, 0x03, 0x40, // period $0FD
434            0xA9, 0x77, 0x8D, 0x04, 0x40, // pulse 2: duty 1, const vol 7
435            0xA9, 0x52, 0x8D, 0x06, 0x40, 0xA9, 0x01, 0x8D, 0x07, 0x40, // period $152
436            0xA9, 0xFF, 0x8D, 0x08, 0x40, // triangle linear counter
437            0xA9, 0x80, 0x8D, 0x0A, 0x40, 0xA9, 0x00, 0x8D, 0x0B, 0x40, // period $080
438            0xA9, 0x3A, 0x8D, 0x0C, 0x40, // noise const vol 10
439            0xA9, 0x05, 0x8D, 0x0E, 0x40, 0xA9, 0x00, 0x8D, 0x0F, 0x40, // noise period 5
440            // loop: alternate the DMC level between $10 and $50 forever.
441            0xA9, 0x10, 0x8D, 0x11, 0x40, // LDA #$10 ; STA $4011
442            0xA2, 0x00, 0xCA, 0xD0, 0xFD, // LDX #0 ; DEX ; BNE -3
443            0xA9, 0x50, 0x8D, 0x11, 0x40, // LDA #$50 ; STA $4011
444            0xA2, 0x00, 0xCA, 0xD0, 0xFD, // delay again
445            0x4C, 0x00, 0x00, // JMP loop (patched below)
446        ];
447        prg[..code.len()].copy_from_slice(code);
448        let loop_at = 0xC000u16 + 66;
449        let jmp = code.len() - 2;
450        prg[jmp] = (loop_at & 0xFF) as u8;
451        prg[jmp + 1] = (loop_at >> 8) as u8;
452        prg[0x3FFC] = 0x00;
453        prg[0x3FFD] = 0xC0;
454        let mut rom = vec![b'N', b'E', b'S', 0x1A, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
455        rom.extend_from_slice(&prg);
456        rom.extend(core::iter::repeat_n(0u8, 0x2000));
457        rom
458    }
459
460    fn capture(frames: usize) -> (StemCapture, Vec<Vec<f32>>) {
461        capture_rom(&all_channels_rom(), frames, 48_000, None)
462    }
463
464    /// Run `rom` for `frames` frames under a capture; returns the capture and
465    /// the streams, the console mix first and then the tracks in
466    /// [`Stem::ALL`] order.
467    fn capture_rom(
468        rom: &[u8],
469        frames: usize,
470        rate: u32,
471        filter: Option<FilterModel>,
472    ) -> (StemCapture, Vec<Vec<f32>>) {
473        let mut nes = Nes::from_rom_with_sample_rate(rom, rate).expect("rom loads");
474        if let Some(f) = filter {
475            nes.set_apu_filter_model(f);
476        }
477        let mut cap = StemCapture::start(&mut nes, rate).expect("starts");
478        let mut tracks = vec![Vec::new(); STEM_COUNT + 1];
479        for _ in 0..frames {
480            nes.run_frame();
481            let f = cap.after_frame(&mut nes).expect("frame captures");
482            tracks[0].extend_from_slice(f.mix);
483            for (i, t) in f.tracks.iter().enumerate() {
484                tracks[i + 1].extend_from_slice(t);
485            }
486        }
487        (cap, tracks)
488    }
489
490    #[test]
491    fn the_rerendered_mix_is_the_consoles_bit_for_bit() {
492        let (cap, tracks) = capture(60);
493        assert!(
494            cap.samples() > 40_000,
495            "a second of audio: {}",
496            cap.samples()
497        );
498        assert_eq!(cap.mix_mismatches(), 0, "the private pipeline is the APU's");
499        assert_eq!(cap.trace_mismatches(), 0, "each record describes its mix");
500        for t in &tracks {
501            assert_eq!(t.len(), tracks[0].len(), "every stream is the same length");
502        }
503    }
504
505    #[test]
506    fn the_seven_tracks_sum_to_the_mix() {
507        let (cap, tracks) = capture(60);
508        let peak = tracks[0].iter().fold(0.0f32, |m, &v| m.max(v.abs()));
509        assert!(peak > 0.05, "the ROM is audible: peak {peak}");
510        assert!(
511            cap.max_sum_error() < 1e-5,
512            "mix - Σ tracks = {} (f32 rounding only)",
513            cap.max_sum_error()
514        );
515    }
516
517    #[test]
518    fn the_sources_alone_do_not_sum_to_the_mix() {
519        // The non-linear mixer is real: without the interaction track the
520        // sources overshoot. If this ever passed with a tiny difference, the
521        // stems would be rendered through a linear mixer, not the console's.
522        let (_cap, tracks) = capture(60);
523        let interaction = &tracks[1 + Stem::Interaction.index()];
524        let peak = interaction.iter().fold(0.0f32, |m, &v| m.max(v.abs()));
525        assert!(peak > 0.01, "interaction peak {peak}");
526    }
527
528    #[test]
529    fn each_source_stem_carries_its_channel() {
530        let (_cap, tracks) = capture(60);
531        for stem in [
532            Stem::Pulse1,
533            Stem::Pulse2,
534            Stem::Triangle,
535            Stem::Noise,
536            Stem::Dmc,
537        ] {
538            let t = &tracks[1 + stem.index()];
539            let peak = t.iter().fold(0.0f32, |m, &v| m.max(v.abs()));
540            assert!(peak > 0.005, "{} is audible: peak {peak}", stem.name());
541        }
542        let ext = &tracks[1 + Stem::Expansion.index()];
543        assert!(ext.iter().all(|&v| v == 0.0), "no expansion chip on NROM");
544    }
545
546    #[test]
547    fn a_stem_value_is_the_mixer_with_one_channel() {
548        let m = Mixer::new();
549        let r = MixRecord {
550            mixed: m.mix(15, 15, 15, 15, 127) + 0.25,
551            external: 0.25,
552            pulse1: 15,
553            pulse2: 15,
554            triangle: 15,
555            noise: 15,
556            dmc: 127,
557        };
558        let v = stem_values(&m, &r);
559        assert_eq!(v[0], m.mix(15, 0, 0, 0, 0));
560        assert_eq!(v[1], m.mix(0, 15, 0, 0, 0));
561        assert_eq!(v[2], m.mix(0, 0, 15, 0, 0));
562        assert_eq!(v[3], m.mix(0, 0, 0, 15, 0));
563        assert_eq!(v[4], m.mix(0, 0, 0, 0, 127));
564        assert_eq!(v[5], 0.25);
565        // Concave tables: the interaction term is negative at full scale.
566        assert!(v[6] < 0.0, "interaction {}", v[6]);
567        let sum: f32 = v.iter().sum();
568        assert!((sum - r.mixed).abs() < 1e-6);
569    }
570
571    #[test]
572    fn a_capture_started_late_is_refused() {
573        let rom = all_channels_rom();
574        let mut nes = Nes::from_rom_with_sample_rate(&rom, 48_000).expect("rom loads");
575        // The first `run_frame` after power-on returns at once (the frame
576        // flag the reset left set); the second runs a real frame.
577        nes.run_frame();
578        nes.run_frame();
579        assert_eq!(
580            StemCapture::start(&mut nes, 48_000).err(),
581            Some(StemError::StartedLate)
582        );
583    }
584
585    #[test]
586    fn an_uncaptured_frame_is_a_gap() {
587        let rom = all_channels_rom();
588        let mut nes = Nes::from_rom_with_sample_rate(&rom, 48_000).expect("rom loads");
589        let mut cap = StemCapture::start(&mut nes, 48_000).expect("starts");
590        nes.run_frame();
591        cap.after_frame(&mut nes).expect("first frame");
592        nes.run_frame();
593        nes.run_frame();
594        assert!(matches!(
595            cap.after_frame(&mut nes),
596            Err(StemError::Gap { .. })
597        ));
598    }
599
600    fn peak(t: &[f32]) -> f32 {
601        t.iter().fold(0.0f32, |m, &v| m.max(v.abs()))
602    }
603
604    #[test]
605    fn a_pal_console_and_another_filter_model_still_match() {
606        // An NES 2.0 header (byte 7 = $08) with byte 12 = 1 marks the image
607        // PAL, which changes the pipeline's CPU clock; the Famicom filter
608        // model changes its coefficients. Both are read from the console, so
609        // the private pipeline follows.
610        let mut rom = all_channels_rom();
611        rom[7] = 0x08;
612        rom[12] = 0x01;
613        assert_eq!(Nes::from_rom(&rom).expect("loads").region(), Region::Pal);
614        let (cap, tracks) = capture_rom(&rom, 50, 44_100, Some(FilterModel::Famicom));
615        assert!(cap.samples() > 40_000);
616        assert_eq!(cap.mix_mismatches(), 0, "PAL + Famicom filter");
617        assert!(cap.max_sum_error() < 1e-5, "{}", cap.max_sum_error());
618        assert!(peak(&tracks[0]) > 0.05);
619    }
620
621    /// The bbbradsmith expansion-audio ROMs vendored under
622    /// `tests/roms/audio-tests/` play a 2A03 reference square and then the
623    /// expansion chip's (see `rustynes-test-harness/tests/audio_expansion.rs`,
624    /// whose frame windows these reuse: the chip sounds in frames 560-650).
625    fn expansion_rom(name: &str) -> Vec<u8> {
626        let path = std::format!(
627            "{}/../../tests/roms/audio-tests/{name}.nes",
628            env!("CARGO_MANIFEST_DIR")
629        );
630        std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"))
631    }
632
633    fn check_expansion(name: &str, chip: &str) {
634        let rom = expansion_rom(name);
635        let nes = Nes::from_rom(&rom).expect("loads");
636        assert_eq!(nes.expansion_audio_chip(), Some(chip), "{name}");
637        let (cap, tracks) = capture_rom(&rom, 650, 44_100, None);
638        assert_eq!(cap.mix_mismatches(), 0, "{name}: mix re-render");
639        assert_eq!(cap.trace_mismatches(), 0, "{name}: trace");
640        assert!(
641            cap.max_sum_error() < 1e-5,
642            "{name}: mix - Σ tracks = {}",
643            cap.max_sum_error()
644        );
645        // 735 samples a frame at 44.1 kHz; the chip's segment.
646        let per_frame = 44_100 / 60;
647        let ext = &tracks[1 + Stem::Expansion.index()];
648        let seg = &ext[560 * per_frame..640 * per_frame];
649        assert!(
650            peak(seg) > 0.02,
651            "{name}: the {chip} stem carries the chip: {}",
652            peak(seg)
653        );
654        // And the reference segment is the 2A03's, not the chip's.
655        let p1 = &tracks[1 + Stem::Pulse1.index()];
656        assert!(
657            peak(&p1[400 * per_frame..470 * per_frame]) > 0.05,
658            "{name}: reference square"
659        );
660    }
661
662    #[test]
663    fn a_vrc6_cartridge_gets_its_own_stem() {
664        check_expansion("db_vrc6a", "VRC6");
665    }
666
667    #[test]
668    fn a_namco_163_cartridge_gets_its_own_stem() {
669        check_expansion("db_n163", "Namco 163");
670    }
671
672    #[test]
673    fn an_mmc5_cartridge_gets_its_own_stem() {
674        check_expansion("db_mmc5", "MMC5");
675    }
676
677    #[test]
678    fn a_sunsoft_5b_cartridge_gets_its_own_stem() {
679        check_expansion("db_5b", "Sunsoft 5B");
680    }
681
682    #[test]
683    fn a_vrc7_cartridge_gets_its_own_stem() {
684        check_expansion("db_vrc7", "VRC7 (OPLL)");
685    }
686
687    /// Run `rom` from a cold boot with the channel mask `mask`, returning its
688    /// audio; and, when `capture` is set, a stem capture of the same run.
689    ///
690    /// The mask is set and THEN the console power-cycled, so the reset
691    /// sequence's own few cycles run under the mask too: a mask set after
692    /// construction leaves those cycles mixed with every channel, which the
693    /// band-limited buffer carries into the first frame or so.
694    fn cold(rom: &[u8], frames: usize, rate: u32, mask: u8) -> (Vec<f32>, Option<Vec<Vec<f32>>>) {
695        let mut nes = Nes::from_rom_with_sample_rate(rom, rate).expect("rom loads");
696        nes.set_apu_channel_mask(mask);
697        nes.power_cycle();
698        let mut cap = (mask == CHANNEL_MASK_ALL)
699            .then(|| StemCapture::start(&mut nes, rate).expect("starts after a power cycle"));
700        let mut audio = Vec::new();
701        let mut tracks = vec![Vec::new(); STEM_COUNT];
702        for _ in 0..frames {
703            nes.run_frame();
704            if let Some(c) = cap.as_mut() {
705                let f = c.after_frame(&mut nes).expect("frame captures");
706                audio.extend_from_slice(f.mix);
707                for (t, v) in tracks.iter_mut().zip(f.tracks) {
708                    t.extend_from_slice(v);
709                }
710            } else {
711                audio.extend(nes.drain_audio());
712            }
713        }
714        if let Some(c) = &cap {
715            assert_eq!(c.mix_mismatches(), 0, "the capture after a power cycle");
716        }
717        (audio, cap.map(|_| tracks))
718    }
719
720    /// The strong per-stem check. The sum gate cannot catch a wrong stem
721    /// (the interaction track is defined as the remainder, so the seven
722    /// always add up); this one can. The APU's own channel mask zeroes every
723    /// other channel before its mixer, so a console with one mask bit set
724    /// plays exactly "that channel alone through the same mixer", and each
725    /// stem must equal it sample for sample.
726    // Exact equality is the claim: the same values through the same
727    // pipeline, so not one sample may differ, by any margin.
728    #[allow(clippy::float_cmp)]
729    fn check_against_mask(rom: &[u8], frames: usize, rate: u32, stems: &[Stem]) {
730        let (_, tracks) = cold(rom, frames, rate, CHANNEL_MASK_ALL);
731        let tracks = tracks.expect("captured");
732        for &stem in stems {
733            let bit = u8::try_from(stem.index()).expect("a channel bit");
734            let (alone, _) = cold(rom, frames, rate, 1 << bit);
735            let ours = &tracks[stem.index()];
736            assert_eq!(ours.len(), alone.len(), "{}", stem.name());
737            let differ = ours.iter().zip(&alone).filter(|(a, b)| a != b).count();
738            assert_eq!(
739                differ,
740                0,
741                "{}: {differ} samples differ from the masked console",
742                stem.name()
743            );
744            assert!(peak(ours) > 0.0, "{} is not silent", stem.name());
745        }
746    }
747
748    #[test]
749    fn each_2a03_stem_is_the_console_with_only_that_channel() {
750        check_against_mask(
751            &all_channels_rom(),
752            60,
753            48_000,
754            &[
755                Stem::Pulse1,
756                Stem::Pulse2,
757                Stem::Triangle,
758                Stem::Noise,
759                Stem::Dmc,
760            ],
761        );
762    }
763
764    #[test]
765    fn the_expansion_stem_is_the_console_with_only_the_chip() {
766        check_against_mask(&expansion_rom("db_vrc6a"), 650, 44_100, &[Stem::Expansion]);
767    }
768
769    /// A synthetic FDS: a one-side disk with only its info-block signature,
770    /// and an 8 KiB "BIOS" written for this test (not Nintendo's, which is
771    /// never committed) that turns the sound I/O on, fills the wavetable with
772    /// a sawtooth, sets a direct volume and a pitch, and spins.
773    fn fds_disk_and_bios() -> (Vec<u8>, Vec<u8>) {
774        let mut disk = vec![0u8; 16 + 65_500];
775        disk[0..4].copy_from_slice(b"FDS\x1A");
776        disk[4] = 1;
777        disk[16] = 0x01;
778        disk[17..31].copy_from_slice(b"*NINTENDO-HVC*");
779        let code: &[u8] = &[
780            0x78, // E000 SEI
781            0xA9, 0x03, 0x8D, 0x23, 0x40, // LDA #$03 ; STA $4023 (disk + sound I/O)
782            0xA9, 0x80, 0x8D, 0x89, 0x40, // LDA #$80 ; STA $4089 (wavetable writable)
783            0xA2, 0x00, // LDX #0
784            0x8A, // E00D TXA
785            0x9D, 0x40, 0x40, // STA $4040,X (a sawtooth: the index)
786            0xE8, // INX
787            0xE0, 0x40, // CPX #$40
788            0xD0, 0xF7, // BNE $E00D
789            0xA9, 0x00, 0x8D, 0x89, 0x40, // LDA #0 ; STA $4089 (locked, full volume)
790            0xA9, 0xA0, 0x8D, 0x80, 0x40, // LDA #$A0 ; STA $4080 (direct gain 32)
791            0xA9, 0x80, 0x8D, 0x87, 0x40, // LDA #$80 ; STA $4087 (modulator halted)
792            0xA9, 0x00, 0x8D, 0x82, 0x40, // LDA #0 ; STA $4082
793            0xA9, 0x02, 0x8D, 0x83, 0x40, // LDA #2 ; STA $4083 (pitch $200, running)
794            0x4C, 0x34, 0xE0, // E034 JMP $E034
795        ];
796        let mut bios = vec![0u8; 0x2000];
797        bios[..code.len()].copy_from_slice(code);
798        bios[0x40] = 0x40; // $E040: RTI
799        bios[0x1FFA..0x1FFC].copy_from_slice(&0xE040u16.to_le_bytes());
800        bios[0x1FFC..0x1FFE].copy_from_slice(&0xE000u16.to_le_bytes());
801        bios[0x1FFE..0x2000].copy_from_slice(&0xE040u16.to_le_bytes());
802        (disk, bios)
803    }
804
805    #[test]
806    #[allow(clippy::float_cmp)] // exact equality is the claim, as above
807    fn an_fds_gets_its_own_stem() {
808        let (disk, bios) = fds_disk_and_bios();
809        let run = |mask: Option<u8>| {
810            let mut nes = Nes::from_disk_with_sample_rate(&disk, &bios, 48_000).expect("loads");
811            assert_eq!(nes.expansion_audio_chip(), Some("FDS"));
812            // Mask first, then the cold boot, as in `cold` above.
813            if let Some(m) = mask {
814                nes.set_apu_channel_mask(m);
815            }
816            nes.power_cycle();
817            let mut cap = mask
818                .is_none()
819                .then(|| StemCapture::start(&mut nes, 48_000).expect("starts"));
820            let (mut mix, mut ext) = (Vec::new(), Vec::new());
821            for _ in 0..30 {
822                nes.run_frame();
823                if let Some(c) = cap.as_mut() {
824                    let f = c.after_frame(&mut nes).expect("captures");
825                    mix.extend_from_slice(f.mix);
826                    ext.extend_from_slice(f.tracks[Stem::Expansion.index()]);
827                } else {
828                    mix.extend(nes.drain_audio());
829                }
830            }
831            if let Some(c) = &cap {
832                assert_eq!(c.mix_mismatches(), 0);
833                assert!(c.max_sum_error() < 1e-5, "{}", c.max_sum_error());
834            }
835            (mix, ext)
836        };
837        let (_, ext) = run(None);
838        assert!(
839            peak(&ext) > 0.02,
840            "the FDS wave is in its stem: {}",
841            peak(&ext)
842        );
843        let (alone, _) = run(Some(1 << Stem::Expansion.index()));
844        assert_eq!(ext.len(), alone.len());
845        assert!(
846            ext.iter().zip(&alone).all(|(a, b)| a == b),
847            "the masked console"
848        );
849    }
850}