//! Replay an input movie from power-on, check it reproduces the recorded //! board, and optionally render it to a video with sound through ffmpeg. //! Usage: //! galaga-movie MOVIE.json [--rom DIR] [--video OUT.mp4] [--from F] [--to F] [--scale N] [--paths] //! //! --sprites FILE replaces the sprite ROM pair (8 KB) for the picture, as a //! replacement sprite EPROM would: new art, the same game. //! //! --paths draws the flight paths over the picture: a thin line tracing //! every enemy's current flight (states 0x03, 0x07, 0x09) and every rocket //! and bomb (0x06), in the neon look's colours (`web/neon.js`). //! //! The picture is the unmodified board's (`Video`), the sound its WSG and //! 54xx model (`Sound`), at the board's 60.606 Hz frame rate. use std::io::Write; use std::path::PathBuf; use std::process::{Command, Stdio}; use emu_galaga::galaga::movie::{ram_crc32, Movie}; use emu_galaga::galaga::objects::objects; use emu_galaga::galaga::roms::load_directory; use emu_galaga::galaga::sound::Sound; use emu_galaga::galaga::video::{Video, SCREEN_HEIGHT, SCREEN_WIDTH}; use emu_galaga::galaga::Machine; /// 18.432 MHz / 3 / 384 / 264: the board's frame rate. const FPS: &str = "60.606060"; fn main() { let mut args = std::env::args().skip(1); let mut movie_path: Option = None; let mut rom_dir = PathBuf::from("rom/galaga"); let mut video_out: Option = None; let mut from: u64 = 0; let mut to: Option = None; let mut scale: u32 = 3; let mut draw_paths = false; let mut sprites: Option = None; while let Some(arg) = args.next() { let mut value = || args.next().unwrap_or_else(|| panic!("{arg} needs a value")); match arg.as_str() { "--rom" => rom_dir = PathBuf::from(value()), "--video" => video_out = Some(PathBuf::from(value())), "--from" => from = value().parse().expect("--from F"), "--to" => to = Some(value().parse().expect("--to F")), "--scale" => scale = value().parse().expect("--scale N"), "--paths" => draw_paths = true, "--sprites" => sprites = Some(PathBuf::from(value())), _ if movie_path.is_none() => movie_path = Some(PathBuf::from(arg)), _ => panic!("unknown argument {arg}"), } } let movie_path = movie_path.expect("usage: galaga-movie MOVIE.json [--video OUT.mp4]"); let movie = Movie::from_json(&std::fs::read_to_string(&movie_path).unwrap()).unwrap(); let mut roms = load_directory(&rom_dir).unwrap_or_else(|e| { eprintln!("{}: {e}", rom_dir.display()); std::process::exit(2) }); if let Some(path) = &sprites { let art = std::fs::read(path).expect("--sprites FILE"); assert_eq!(art.len(), roms.sprites.len(), "a sprite ROM pair is 8 KB"); roms.sprites = art; } let to = to.unwrap_or(movie.frames).min(movie.frames); let mut machine = Machine::new(&roms); movie.setup(&mut machine).unwrap(); let mut video = Video::new(&roms); // The movie's path mod may carry new sprite art for the picture. if let Some(m) = movie.path_mod().unwrap() { m.apply_video(&mut video); } let mut sound = Sound::new(&roms); let mut rgba = vec![0u8; SCREEN_WIDTH * SCREEN_HEIGHT * 4]; let s = scale as usize; let (out_w, out_h) = (SCREEN_WIDTH * s, SCREEN_HEIGHT * s); let mut rgb = vec![0u8; out_w * out_h * 3]; let mut paths: Vec> = vec![Vec::new(); 64]; let mut samples: Vec = Vec::new(); let mut pcm: Vec = Vec::new(); let silent = video_out.as_ref().map(|p| p.with_extension("silent.mp4")); let mut ffmpeg = silent.as_ref().map(|path| { Command::new("ffmpeg") .args([ "-loglevel", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", ]) .args(["-s", &format!("{out_w}x{out_h}"), "-r", FPS, "-i", "-"]) .args(["-c:v", "libx264", "-crf", "16", "-pix_fmt", "yuv420p"]) .arg(path) .stdin(Stdio::piped()) .spawn() .expect("ffmpeg") }); for (frame, controls) in movie.inputs().into_iter().enumerate() { let frame = frame as u64; machine.set_controls(controls); machine.run_frame(); if draw_paths { track_paths(&machine, &mut paths); } let Some(ffmpeg) = ffmpeg.as_mut() else { continue; }; let (wsg_writes, n54_writes) = { let mut s = machine.shared.borrow_mut(); ( std::mem::take(&mut s.wsg_writes), std::mem::take(&mut s.n54_writes), ) }; samples.clear(); sound.render_frame(frame, &wsg_writes, &n54_writes, &mut samples); video.render(&machine.shared.borrow(), machine.videolatch_at_vblank_end); if frame < from || frame >= to { continue; } pcm.extend(samples.chunks(2).map(|p| { ((p.iter().sum::() / p.len() as f32) * 32767.0) .round() .clamp(-32768.0, 32767.0) as i16 })); video.screen_rgba(&mut rgba); for y in 0..out_h { for x in 0..out_w { let src = ((y / s) * SCREEN_WIDTH + x / s) * 4; let dst = (y * out_w + x) * 3; rgb[dst..dst + 3].copy_from_slice(&rgba[src..src + 3]); } } if draw_paths { for (n, path) in paths.iter().enumerate() { let color = slot_color(n); for w in path.windows(2) { line(&mut rgb, out_w, out_h, w[0], w[1], scale as f32, color); } } } ffmpeg.stdin.as_mut().unwrap().write_all(&rgb).unwrap(); } let crc = ram_crc32(&machine); if crc != movie.final_ram_crc32 { eprintln!( "replay DIFFERS: RAM CRC-32 {crc:08x}, the movie recorded {:08x}", movie.final_ram_crc32 ); std::process::exit(1); } println!( "{}: {} frames replayed, RAM identical to the recording ({crc:08x})", movie_path.display(), movie.frames ); if let (Some(mut ffmpeg), Some(silent), Some(out)) = (ffmpeg, silent, video_out) { drop(ffmpeg.stdin.take()); assert!(ffmpeg.wait().unwrap().success(), "ffmpeg (video) failed"); let wav = out.with_extension("wav"); write_wav(&wav, &pcm); let status = Command::new("ffmpeg") .args(["-loglevel", "error", "-y", "-i"]) .arg(&silent) .arg("-i") .arg(&wav) .args(["-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-shortest"]) .arg(&out) .status() .expect("ffmpeg"); assert!(status.success(), "ffmpeg (mux) failed"); let _ = std::fs::remove_file(&silent); let _ = std::fs::remove_file(&wav); println!("video: frames {from}..{to} -> {}", out.display()); } } /// Each slot's current flight, in screen pixels (centres), as `web/neon.js` /// keeps it: enemies while flying, rockets and bombs while live; a jump of /// more than 40 px starts a new path. fn track_paths(machine: &Machine, paths: &mut [Vec<(f32, f32)>]) { let objs = objects(&machine.shared.borrow()); for o in objs.iter() { let n = usize::from(o.slot); let flying = n < 0x30 && matches!(o.state, 0x03 | 0x07 | 0x09); let shot = (0x32..=0x3b).contains(&n) && o.state == 0x06; let (cx, cy) = o.center(); let (cx, cy) = (cx as f32, cy as f32); let path = &mut paths[n]; if (flying || shot) && o.on_screen() { if let Some(&(lx, ly)) = path.last() { if (lx - cx).hypot(ly - cy) > 40.0 { path.clear(); } } path.push((cx, cy)); if path.len() > 900 { path.remove(0); } } else { path.clear(); } } } /// The neon look's colour per slot role. fn slot_color(slot: usize) -> [u8; 3] { match slot { 0x00..=0x03 => [255, 64, 77], 0x04..=0x17 => [64, 190, 255], 0x18..=0x1b => [77, 255, 128], 0x1c..=0x1f => [255, 90, 255], 0x20..=0x2f => [255, 77, 90], 0x30..=0x31 => [217, 242, 255], 0x32..=0x33 => [100, 255, 255], _ => [255, 140, 50], } } /// A thin line between two screen points, blended half over the picture. fn line( rgb: &mut [u8], w: usize, h: usize, a: (f32, f32), b: (f32, f32), scale: f32, color: [u8; 3], ) { let (x0, y0, x1, y1) = (a.0 * scale, a.1 * scale, b.0 * scale, b.1 * scale); let steps = (x1 - x0).abs().max((y1 - y0).abs()).ceil().max(1.0) as usize; for i in 0..=steps { let t = i as f32 / steps as f32; let (x, y) = ((x0 + (x1 - x0) * t) as isize, (y0 + (y1 - y0) * t) as isize); if x < 0 || y < 0 || x as usize >= w || y as usize >= h { continue; } let o = (y as usize * w + x as usize) * 3; for c in 0..3 { rgb[o + c] = ((u16::from(rgb[o + c]) + u16::from(color[c])) / 2) .max(u16::from(rgb[o + c])) as u8; } } } /// 16-bit mono at 48 kHz. fn write_wav(path: &std::path::Path, pcm: &[i16]) { let mut out = Vec::with_capacity(44 + pcm.len() * 2); let data_len = (pcm.len() * 2) as u32; out.extend_from_slice(b"RIFF"); out.extend_from_slice(&(36 + data_len).to_le_bytes()); out.extend_from_slice(b"WAVEfmt "); out.extend_from_slice(&16u32.to_le_bytes()); out.extend_from_slice(&1u16.to_le_bytes()); out.extend_from_slice(&1u16.to_le_bytes()); out.extend_from_slice(&48_000u32.to_le_bytes()); out.extend_from_slice(&96_000u32.to_le_bytes()); out.extend_from_slice(&2u16.to_le_bytes()); out.extend_from_slice(&16u16.to_le_bytes()); out.extend_from_slice(b"data"); out.extend_from_slice(&data_len.to_le_bytes()); for s in pcm { out.extend_from_slice(&s.to_le_bytes()); } std::fs::write(path, out).unwrap(); }