#![forbid(unsafe_code)] use std::collections::HashMap; use std::io::Write; use std::process::{Command, Stdio}; const SR: usize = 44100; const FPS: f32 = 30.0; fn decode(path: &str) -> Vec { let out = Command::new("ffmpeg").args(["-v", "error", "-i", path, "-f", "f32le", "-ac", "2", "-ar", "44100", "-"]).output().expect("ffmpeg"); out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() } fn main() { let args: Vec = std::env::args().collect(); let (video, root, out) = (&args[1], &args[2], &args[3]); let cues = std::fs::read_to_string(format!("{video}.cues")).expect("cues"); let mut layers: Vec = Vec::new(); let mut vols: Vec<(f32, Vec)> = Vec::new(); let mut shots: Vec<(f32, String, f32)> = Vec::new(); for line in cues.lines() { let p: Vec<&str> = line.split(' ').collect(); match p[0] { "H" => layers = p[1..].iter().map(|s| s.to_string()).collect(), "L" => vols.push((p[1].parse().unwrap(), p[2..].iter().map(|v| v.parse().unwrap()).collect())), "S" => shots.push((p[1].parse().unwrap(), p[2].to_string(), p[3].parse().unwrap())), _ => {} } } let t0 = 5.0 / FPS; let dur = vols.last().map(|v| v.0).unwrap_or(0.0) - t0; let n = (dur.max(0.0) * SR as f32) as usize; let mut buf = vec![0.0f32; n * 2]; let mut cache: HashMap> = HashMap::new(); let mut load = |p: &str| -> Vec { cache.entry(p.to_string()).or_insert_with(|| decode(&format!("{root}/{p}"))).clone() }; for (li, path) in layers.iter().enumerate() { let data = load(path); if data.len() < 2 { continue; } let frames = data.len() / 2; for k in 0..n { let t = t0 + k as f32 / SR as f32; let fi = t * FPS; let i = (fi as usize).min(vols.len() - 1); let j = (i + 1).min(vols.len() - 1); let f = fi.fract(); let v = vols[i].1[li] * (1.0 - f) + vols[j].1[li] * f; if v <= 0.0005 { continue; } let s = k % frames; buf[k * 2] += data[s * 2] * v; buf[k * 2 + 1] += data[s * 2 + 1] * v; } } for (t, path, vol) in &shots { let data = load(path); let start = ((t - t0).max(0.0) * SR as f32) as usize; for (i, x) in data.iter().enumerate() { let k = start * 2 + i; if k >= buf.len() { break; } buf[k] += x * vol; } } let bytes: Vec = buf.iter().flat_map(|x| (x * 0.9).tanh().to_le_bytes()).collect(); let mut child = Command::new("ffmpeg") .args(["-y", "-v", "error", "-i", video, "-f", "f32le", "-ar", "44100", "-ac", "2", "-i", "-", "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-shortest", out]) .stdin(Stdio::piped()) .spawn() .expect("ffmpeg"); child.stdin.take().unwrap().write_all(&bytes).unwrap(); child.wait().unwrap(); }