Files
prometeu-runtime/crates/tools/pbxgen-stress/tests/music_cartridge.rs
T
bquarkz e9fcf35580
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
test(stress): isolate music cartridge fixture directories
Reserve temporary directories exclusively, cover equal timestamps and include host logs in boot failures.

Work: WRK-0027 (DEC-0002). Validation: make -C tooling verify, run 20261127T004152Z-e028bb55, PASSED.
2026-11-27 00:51:37 +00:00

234 lines
9.8 KiB
Rust

use prometeu_drivers::bank_format::{decode_audio_bank, DecodedAudioBank};
use prometeu_host_headless::{AdvanceFrameOutcome, HeadlessHost};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
struct Cartridge(PathBuf);
impl Cartridge {
fn new() -> Self {
let unique =
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
Self::with_timestamp(unique)
}
fn with_timestamp(timestamp: u128) -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let path = loop {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let candidate = std::env::temp_dir()
.join(format!("stress-console-music-{}-{timestamp}-{id}", std::process::id()));
match std::fs::create_dir(&candidate) {
Ok(()) => break candidate,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("create cartridge directory {candidate:?}: {error}"),
}
};
let cartridge = Self(path);
std::fs::write(cartridge.0.join("program.pbx"), pbxgen_stress::build_program()).unwrap();
std::fs::write(cartridge.0.join("manifest.json"), pbxgen_stress::manifest_json()).unwrap();
std::fs::write(cartridge.0.join("assets.pa"), pbxgen_stress::build_assets_pack().unwrap())
.unwrap();
cartridge
}
fn boot(&self) -> HeadlessHost {
let mut host = HeadlessHost::new();
if let Err(error) = host.boot(self.0.to_string_lossy()) {
panic!(
"boot cartridge {:?}: {error:?}; logs: {:?}",
self.0,
host.log_snapshot(None, 128)
);
}
assert!(matches!(
host.advance_frame().unwrap(),
AdvanceFrameOutcome::FrameCompleted { .. }
));
host.resume().unwrap();
host
}
}
impl Drop for Cartridge {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn equal_timestamps_keep_cartridge_lifetimes_independent() {
let (first, second) = std::thread::scope(|scope| {
let first = scope.spawn(|| Cartridge::with_timestamp(0));
let second = scope.spawn(|| Cartridge::with_timestamp(0));
(first.join().unwrap(), second.join().unwrap())
});
assert_ne!(first.0, second.0);
drop(first);
drop(second.boot());
drop(second.boot());
}
#[test]
fn bank_preserves_transcription_and_mixed_samples() {
let bytes = include_bytes!("../music/storm-eagle.mbnk");
let decoded =
decode_audio_bank(bytes, true).expect("packer bank must load in the real decoder");
let metrics: serde_json::Value =
serde_json::from_str(include_str!("../music/bank-metrics.json")).unwrap();
assert_eq!(decoded.decoded_size() as u64, metrics["decoded_size"].as_u64().unwrap());
let DecodedAudioBank::Music(bank) = decoded else { panic!("expected music") };
assert_eq!(bank.samples.len(), 8);
assert_eq!(bank.instruments.len(), 8);
let manifest: serde_json::Value =
serde_json::from_str(include_str!("../music/song.json")).unwrap();
let lead: Vec<_> = manifest["events"]
.as_array()
.unwrap()
.iter()
.filter(|e| e["kind"] == 1 && e["track"] == 0)
.collect();
assert_eq!(lead.len(), 90);
let first_pitches: Vec<_> = lead.iter().take(8).map(|e| e["c"].as_u64().unwrap()).collect();
assert_eq!(first_pitches, [71, 70, 71, 73, 74, 73, 71, 78]);
assert_eq!(lead[4]["tick"], 3840);
assert_eq!(lead[5]["tick"], 4160);
assert_eq!(lead[6]["tick"], 4480);
assert_eq!(manifest["duration_ticks"], 69120);
let mapping: serde_json::Value =
serde_json::from_str(include_str!("../music/instrument-mapping.json")).unwrap();
assert_eq!(mapping["voicings"].as_array().unwrap().len(), 20);
assert_eq!(mapping["voicings"][4]["target_tones"], serde_json::json!([58, 61, 66]));
let samples_at = 48 + u32::from_le_bytes(bytes[40..44].try_into().unwrap()) as usize;
let codecs: Vec<_> = (0..8).map(|i| bytes[samples_at + i * 40]).collect();
assert!(codecs.contains(&0) && codecs.contains(&1));
}
#[test]
fn tracked_cartridge_is_the_exact_generator_output() {
let root =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../test-cartridges/stress-console");
assert_eq!(std::fs::read(root.join("program.pbx")).unwrap(), pbxgen_stress::build_program());
assert_eq!(std::fs::read(root.join("manifest.json")).unwrap(), pbxgen_stress::manifest_json());
assert_eq!(
std::fs::read(root.join("assets.pa")).unwrap(),
pbxgen_stress::build_assets_pack().unwrap()
);
}
#[test]
fn guest_preloads_music_and_renders_audio() {
let cartridge = Cartridge::new();
let mut host = cartridge.boot();
let mut output = [0.0; 9600];
host.render_audio(&mut output);
assert!(output.iter().any(|x| x.abs() > 0.001));
assert!(host.audio_diagnostics().maximum_voices > 0);
assert_eq!(host.audio_diagnostics().frames, 4800);
}
fn render_sequence(
mut host: HeadlessHost,
frames: usize,
graphics_and_pause: bool,
) -> (Vec<f32>, prometeu_drivers::engine::AudioDiagnostics, usize) {
let mut output = vec![0.0; frames * 2];
let mut graphics_frames = 0;
for (index, buffer) in output.chunks_mut(1600).enumerate() {
if graphics_and_pause {
// Exercise the heavy workload at bounded checkpoints across both loops.
// This is a sequencing regression test, not a 60 FPS performance run.
if index < 6 || index % 120 == 0 || [60, 1543, 3086].contains(&index) {
assert!(matches!(
host.advance_frame().unwrap(),
AdvanceFrameOutcome::FrameCompleted { .. }
));
graphics_frames += 1;
host.resume().unwrap();
}
if index == 60 {
let before = host.audio_diagnostics().frames;
host.pause().unwrap();
let mut silence = [1.0; 2048];
host.render_audio(&mut silence);
assert_eq!(silence, [0.0; 2048]);
assert_eq!(host.audio_diagnostics().frames, before);
host.resume().unwrap();
}
}
host.render_audio(buffer);
}
let diagnostics = host.audio_diagnostics();
assert_eq!(diagnostics.frames, frames as u64);
(output, diagnostics, graphics_frames)
}
fn write_wav(path: &std::path::Path, pcm: &[f32]) {
use std::io::Write;
let mut file = std::fs::File::create(path).unwrap();
let byte_count = u32::try_from(pcm.len() * 2).unwrap();
file.write_all(b"RIFF").unwrap();
file.write_all(&(36 + byte_count).to_le_bytes()).unwrap();
file.write_all(b"WAVEfmt \x10\0\0\0\x01\0\x02\0").unwrap();
file.write_all(&48_000_u32.to_le_bytes()).unwrap();
file.write_all(&192_000_u32.to_le_bytes()).unwrap();
file.write_all(&4_u16.to_le_bytes()).unwrap();
file.write_all(&16_u16.to_le_bytes()).unwrap();
file.write_all(b"data").unwrap();
file.write_all(&byte_count.to_le_bytes()).unwrap();
let mut bytes = Vec::with_capacity(pcm.len() * 2);
for value in pcm {
bytes.extend_from_slice(&((value.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes());
}
file.write_all(&bytes).unwrap();
}
#[test]
fn full_sequence_loops_and_frame_controls_preserve_audio() {
let cartridge = Cartridge::new();
let one_loop_numerator = 48_000_u64 * 72 * 357_143;
let first_loop = one_loop_numerator.div_ceil(1_000_000) as usize;
let frames = (one_loop_numerator * 2).div_ceil(1_000_000) as usize + 48_000;
let (reference, diagnostics, _) = render_sequence(cartridge.boot(), frames, false);
let (with_frames, _, graphics_frames) = render_sequence(cartridge.boot(), frames, true);
assert!(graphics_frames >= 30);
assert_eq!(
reference, with_frames,
"graphics and explicit pause/resume must not change a single PCM sample"
);
assert!((6..=12).contains(&diagnostics.maximum_voices));
let peak = reference.iter().map(|x| x.abs()).fold(0.0_f32, f32::max);
let energy: f64 = reference.iter().map(|x| f64::from(*x).powi(2)).sum();
let rms = (energy / reference.len() as f64).sqrt();
let clipped = reference.iter().filter(|x| x.abs() >= 1.0).count();
let stereo_difference: f64 =
reference.as_chunks::<2>().0.iter().map(|lr| f64::from(lr[0] - lr[1]).powi(2)).sum();
// Loop onset should reproduce the opening. A subframe remainder and the shared
// echo tail may differ, so compare relative signal energy rather than bit identity.
let mut loop_error = 0.0;
let mut opening_energy = 0.0;
for i in 400..4000 {
loop_error += f64::from(reference[i] - reference[first_loop * 2 + i]).powi(2);
opening_energy += f64::from(reference[i]).powi(2);
}
let loop_error_ratio = loop_error / opening_energy;
let report = serde_json::json!({
"sample_rate": 48000, "channels": 2, "audio_frames": frames,
"seconds": frames as f64 / 48000.0, "first_loop_frame": first_loop,
"maximum_voices": diagnostics.maximum_voices, "peak": peak,
"rms": rms, "clipped_samples": clipped,
"loop_onset_relative_error": loop_error_ratio,
"graphics_pause_pcm_identical": true,
"interleaved_graphics_frames": graphics_frames,
});
println!("stress_music={report}");
if let Some(path) = std::env::var_os("PROMETEU_STRESS_WAV") {
write_wav(std::path::Path::new(&path), &reference);
}
assert!(reference.iter().all(|x| x.is_finite()));
assert!(rms > 0.005 && stereo_difference > 0.01);
assert_eq!(clipped, 0, "adjust arrangement gain rather than delivering clipped audio");
assert!(
loop_error_ratio < 0.04,
"loop did not reproduce the musical opening: {loop_error_ratio}"
);
}