From 56052a3327a40509f74214405211941b01f80e37 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 22:01:25 -0800 Subject: [PATCH] refactor(engine): split export.rs into png/video/tests submodules and unify render-check PNG loop --- crates/engine/src/bin/render_check.rs | 207 +-- crates/engine/src/export.rs | 2415 +------------------------ crates/engine/src/export/png.rs | 442 +++++ crates/engine/src/export/tests.rs | 1286 +++++++++++++ crates/engine/src/export/video.rs | 896 +++++++++ 5 files changed, 2679 insertions(+), 2567 deletions(-) create mode 100644 crates/engine/src/export/png.rs create mode 100644 crates/engine/src/export/tests.rs create mode 100644 crates/engine/src/export/video.rs diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index ed32e5307dd91a5c6c122fbb4fee15908111d819..562529ef4d712f1b85cb98b762c585d2acace020 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -1,13 +1,14 @@ //! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`. -use engine::export::{VideoCodec, VideoExportOptions, export_node_video_ffmpeg, write_png_fast_buffered}; +use engine::export::{ + VideoCodec, VideoExportOptions, export_node_png_sequence_with_progress, + export_node_video_ffmpeg, write_png_fast_buffered, +}; use engine::media::default_media_cache_budget_mb; use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence}; use model::Comp; use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex, mpsc}; use std::time::Instant; fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f64, f64, f64), Box> { @@ -161,192 +162,48 @@ fn run_batch_render( let total = (end - start + 1).max(0) as usize; let t_all = Instant::now(); + let label = comp.node(target).name.clone(); eprintln!( "Rendering {} ({}x{}, proxy 1:{}) node={} frames {}..{} ({total} frames) -> {}", comp.name, comp.width, comp.height, proxy_scale, - comp.node(target).name, + label, start, end, out_dir.display() ); if total > 0 { - struct RenderEncodeJob { - path: PathBuf, - size: [u32; 2], - pixels: Vec, - } - let workers = std::thread::available_parallelism() - .map(|n| n.get().clamp(2, 24)) - .unwrap_or(4) - .min(total.max(1)); - let queue_cap = (workers * 2).clamp(16, 48); - let first_err: Arc>> = Arc::new(Mutex::new(None)); - let failed = Arc::new(AtomicBool::new(false)); - - std::thread::scope(|scope| -> Result<(), Box> { - let (tx, rx) = mpsc::sync_channel::(queue_cap); - let (recycle_tx, recycle_rx) = mpsc::sync_channel::>(queue_cap + workers); - let shared_rx = Arc::new(Mutex::new(rx)); - let mut handles = Vec::with_capacity(workers); - for _ in 0..workers { - let rx_c = Arc::clone(&shared_rx); - let recycle_c = recycle_tx.clone(); - let err_c = Arc::clone(&first_err); - let fail_c = Arc::clone(&failed); - handles.push(scope.spawn(move || { - let mut staging = Vec::new(); - let mut last_parent = Some(out_dir.to_path_buf()); - loop { - let job = { - let Ok(guard) = rx_c.lock() else { break }; - guard.recv() - }; - let Ok(job) = job else { break }; - if fail_c.load(Ordering::Acquire) { - continue; - } - if let Err(e) = write_png_fast_buffered( - &job.path, - job.size, - &job.pixels, - &mut staging, - &mut last_parent, - ) { - if let Ok(mut g) = err_c.lock() { - if g.is_none() { - *g = Some(e); - } - } - fail_c.store(true, Ordering::Release); - } - let _ = recycle_c.try_send(job.pixels); - } - })); - } - drop(recycle_tx); - - let mut loop_err: Option = None; - const PREFETCH_LOOKAHEAD: usize = 12; - engine.prewarm_for_depth(comp.depth_full); - let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); - let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end); - for (k, f) in ((start + 1)..=seed_end).enumerate() { - prefetch.enqueue_frame( - &comp, - target, - k + 1, - f as f64, - &engine.expr, - engine.use_proxy_clips, - ); - } - let mut pending: Option<(engine::PendingReadback, i64, usize, [u32; 2], engine::EvalStats)> = None; - for (idx, f) in (start..=end).enumerate() { - if failed.load(Ordering::Acquire) { - break; - } - prefetch.set_current_seq(idx); - let ahead_frame = f + PREFETCH_LOOKAHEAD as i64; - if ahead_frame <= end { - prefetch.enqueue_frame( - &comp, - target, - idx + PREFETCH_LOOKAHEAD, - ahead_frame as f64, - &engine.expr, - engine.use_proxy_clips, + let hiq = engine.hiq; + export_node_png_sequence_with_progress( + &mut engine, + &comp, + target, + [start, end], + |f| Ok(out_dir.join(format!("{f:04}.png"))), + label, + hiq, + proxy_scale, + 0, + None, + |p| { + if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { + let elapsed = t_all.elapsed().as_secs_f64().max(1e-6); + let fps = (p.index + 1) as f64 / elapsed; + eprintln!( + " [{:>4}/{}] f{:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}", + p.index + 1, + p.total, + p.frame, + p.eval_ms, + p.cached_vram_mb, + p.unsupported_nodes, ); } - let (tex, stats) = engine.evaluate(&comp, target, f as f64); - let next_rb = match engine.begin_readback_rgba(&tex) { - Ok(rb) => rb, - Err(e) => { - loop_err = Some(format!("GPU readback failed at frame {f}: {e}")); - break; - } - }; - if let Some((prev_rb, prev_f, prev_idx, prev_size, prev_stats)) = - pending.replace((next_rb, f, idx, tex.size, stats)) - { - let mut pixels = recycle_rx.try_recv().unwrap_or_default(); - if let Err(e) = prev_rb.finish_into(&engine, &mut pixels) { - loop_err = Some(format!("GPU readback failed at frame {prev_f}: {e}")); - break; - } - let out_file = out_dir.join(format!("{prev_f:04}.png")); - if tx - .send(RenderEncodeJob { - path: out_file, - size: prev_size, - pixels, - }) - .is_err() - { - break; - } - if prev_idx == 0 || (prev_idx + 1) % 10 == 0 || prev_idx + 1 == total { - let elapsed = t_all.elapsed().as_secs_f64().max(1e-6); - let fps = (prev_idx + 1) as f64 / elapsed; - eprintln!( - " [{:>4}/{total}] f{prev_f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}", - prev_idx + 1, - prev_stats.eval_ms, - prev_stats.cached_vram_mb, - prev_stats.unsupported_nodes, - ); - } - } - } - if loop_err.is_none() && !failed.load(Ordering::Acquire) { - if let Some((prev_rb, prev_f, prev_idx, prev_size, prev_stats)) = pending.take() { - let mut pixels = recycle_rx.try_recv().unwrap_or_default(); - match prev_rb.finish_into(&engine, &mut pixels) { - Ok(()) => { - let out_file = out_dir.join(format!("{prev_f:04}.png")); - let _ = tx.send(RenderEncodeJob { - path: out_file, - size: prev_size, - pixels, - }); - if prev_idx == 0 || (prev_idx + 1) % 10 == 0 || prev_idx + 1 == total { - let elapsed = t_all.elapsed().as_secs_f64().max(1e-6); - let fps = (prev_idx + 1) as f64 / elapsed; - eprintln!( - " [{:>4}/{total}] f{prev_f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}", - prev_idx + 1, - prev_stats.eval_ms, - prev_stats.cached_vram_mb, - prev_stats.unsupported_nodes, - ); - } - } - Err(e) => { - loop_err = Some(format!("GPU readback failed at frame {prev_f}: {e}")); - } - } - } - } - - drop(prefetch); - drop(tx); - for h in handles { - let _ = h.join(); - } - - if let Some(e) = loop_err { - return Err(e.into()); - } - if let Ok(mut g) = first_err.lock() { - if let Some(e) = g.take() { - return Err(e.into()); - } - } - Ok(()) - })?; + }, + )?; } eprintln!( "Finished {total} frames in {:.2}s ({:.1} fps)", diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 17515a0c55e42ee89a4b50c400b0c8750548d7bd..db1607d2c0042ae02af4b68e9ad010ebd63d34b3 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1,17 +1,24 @@ -//! Saver-driven pipelined PNG sequence export for `Engine`. +//! Saver-driven pipelined PNG sequence export and ffmpeg video export for `Engine`. //! //! Evaluates frames on the GPU while encoding lossless RGBA8 PNG files concurrently -//! across a bounded background worker pool, creating parent directories automatically. +//! across a bounded background worker pool, or piping raw RGBA8 frames into `ffmpeg`. -use crate::eval::Engine; +mod png; +#[cfg(test)] +mod tests; +mod video; + +pub use png::{ + encode_png_rgba8_into, export_node_frame_png, export_node_png_sequence_with_progress, + export_saver_png_sequence, export_saver_png_sequence_with_progress, write_png_fast_buffered, +}; +pub use video::{export_node_video_ffmpeg, export_node_video_ffmpeg_with_progress}; + +use crate::cache::EvalStats; use model::{Comp, NodeId, SaverSpec}; -use std::io::{Read, Write}; -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -#[cfg(target_os = "macos")] -use std::sync::OnceLock; -use std::sync::{Arc, Mutex, mpsc}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Instant; #[derive(Clone, Debug)] @@ -50,6 +57,8 @@ pub struct ExportProgress { pub index: usize, pub total: usize, pub eval_ms: f64, + pub cached_vram_mb: f64, + pub unsupported_nodes: Vec, pub out_path: PathBuf, pub saver_name: String, pub current_frame: u32, @@ -113,7 +122,7 @@ fn make_progress( frame: i64, index: usize, total: usize, - eval_ms: f64, + stats: EvalStats, out_path: PathBuf, label: String, started_at: Instant, @@ -122,7 +131,9 @@ fn make_progress( frame, index, total, - eval_ms, + eval_ms: stats.eval_ms, + cached_vram_mb: stats.cached_vram_mb, + unsupported_nodes: stats.unsupported_nodes, out_path, saver_name: label.clone(), current_frame: frame.max(0) as u32, @@ -166,363 +177,6 @@ pub fn select_saver(comp: &Comp, saver_name: Option<&str>) -> Result) -> Result { - if saver.filename.is_empty() { - let dir = out_dir_override.ok_or_else(|| { - format!( - "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)", - saver.name - ) - })?; - return Ok(dir.join(format!("{frame:04}.png"))); - } - let frame_path = saver.frame_path(frame); - if let Some(dir) = out_dir_override { - let fname = frame_path - .file_name() - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.png"))); - Ok(dir.join(fname)) - } else { - Ok(frame_path) - } -} - -/// Encodes an RGBA8 image into `out` as a lossless PNG matching Fusion's default -/// libpng compression (`Compression::Balanced` = zlib level 6 + `Filter::Adaptive`). -pub fn encode_png_rgba8_into(size: [u32; 2], pixels: &[u8], out: &mut Vec) -> Result<(), String> { - out.clear(); - if out.capacity() == 0 { - out.reserve(pixels.len() / 2); - } - let mut enc = png::Encoder::new(&mut *out, size[0], size[1]); - enc.set_color(png::ColorType::Rgba); - enc.set_depth(png::BitDepth::Eight); - enc.set_compression(png::Compression::Balanced); - enc.set_filter(png::Filter::Adaptive); - let mut png_w = enc - .write_header() - .map_err(|e| format!("failed to write PNG header: {e}"))?; - png_w - .write_image_data(pixels) - .map_err(|e| format!("failed to write PNG data: {e}"))?; - Ok(()) -} - -/// Encodes and writes an RGBA8 PNG using a reusable staging buffer and cached parent directory. -pub fn write_png_fast_buffered( - path: &Path, - size: [u32; 2], - pixels: &[u8], - staging: &mut Vec, - last_parent: &mut Option, -) -> Result<(), String> { - if let Some(parent) = path.parent() { - if !parent.as_os_str().is_empty() && last_parent.as_deref() != Some(parent) { - std::fs::create_dir_all(parent) - .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; - *last_parent = Some(parent.to_path_buf()); - } - } - encode_png_rgba8_into(size, pixels, staging) - .map_err(|e| format!("{e} ('{}')", path.display()))?; - std::fs::write(path, staging.as_slice()) - .map_err(|e| format!("failed to write '{}': {e}", path.display()))?; - Ok(()) -} - -fn write_png_fast(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), String> { - let mut staging = Vec::with_capacity(pixels.len() / 2); - let mut last_parent = None; - write_png_fast_buffered(path, size, pixels, &mut staging, &mut last_parent) -} - -struct EncodeJob { - path: PathBuf, - size: [u32; 2], - pixels: Vec, -} - -/// Renders and writes a PNG sequence driven by a Fusion `Saver` node. -/// -/// GPU evaluation runs on the caller's thread while PNG compression and disk I/O run -/// concurrently on a bounded pool of background worker threads. -pub fn export_saver_png_sequence( - engine: &mut Engine, - comp: &Comp, - opts: &ExportOptions, - on_progress: impl FnMut(&ExportProgress), -) -> Result { - export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress) -} - -/// Renders and writes a PNG sequence driven by a Fusion `Saver` node with cooperative -/// cancellation and live progress reporting via `ExportControl`. -pub fn export_saver_png_sequence_with_progress( - engine: &mut Engine, - comp: &Comp, - opts: &ExportOptions, - control: Option<&ExportControl>, - mut on_progress: impl FnMut(&ExportProgress), -) -> Result { - if control.is_some_and(ExportControl::is_cancelled) { - return Err("Cancelled".to_owned()); - } - let saver = select_saver(comp, opts.saver_name.as_deref())?; - let target: NodeId = saver.upstream.unwrap_or(saver.node_id); - let [start, end] = opts.range_override.unwrap_or(saver.range); - let total_i128 = i128::from(end) - i128::from(start) + 1; - if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { - return Err(format!("invalid export frame range {start}..={end}")); - } - - let prev_hiq = engine.hiq; - let prev_proxy = engine.proxy_scale; - engine.hiq = opts.hiq; - engine.proxy_scale = opts.proxy_scale.max(1); - - let total = total_i128 as usize; - let workers = if opts.png_workers > 0 { - opts.png_workers.clamp(1, 24) - } else { - std::thread::available_parallelism() - .map(|n| n.get().clamp(2, 24)) - .unwrap_or(4) - } - .min(total.max(1)); - - let t0 = Instant::now(); - let mut first_path: Option = None; - let mut last_path: Option = None; - let mut frames_written: usize = 0; - - let first_err: Arc>> = Arc::new(Mutex::new(None)); - let failed = Arc::new(AtomicBool::new(false)); - let cancelled = Arc::new(AtomicBool::new(false)); - - let eval_result: Result<(), String> = std::thread::scope(|scope| { - let queue_cap = (workers * 2).clamp(16, 48); - let (tx, rx) = mpsc::sync_channel::(queue_cap); - let (recycle_tx, recycle_rx) = mpsc::sync_channel::>(queue_cap + workers); - let shared_rx = Arc::new(Mutex::new(rx)); - - let mut handles = Vec::with_capacity(workers); - for _ in 0..workers { - let rx_c = Arc::clone(&shared_rx); - let recycle_c = recycle_tx.clone(); - let err_c = Arc::clone(&first_err); - let fail_c = Arc::clone(&failed); - let cancel_c = Arc::clone(&cancelled); - handles.push(scope.spawn(move || { - let mut staging = Vec::new(); - let mut last_parent: Option = None; - loop { - let job = { - let Ok(guard) = rx_c.lock() else { break }; - guard.recv() - }; - let Ok(job) = job else { break }; - if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) { - continue; - } - if let Err(e) = write_png_fast_buffered( - &job.path, - job.size, - &job.pixels, - &mut staging, - &mut last_parent, - ) { - if let Ok(mut g) = err_c.lock() { - if g.is_none() { - *g = Some(e); - } - } - fail_c.store(true, Ordering::Release); - } - let _ = recycle_c.try_send(job.pixels); - } - })); - } - drop(recycle_tx); - - let mut loop_err: Option = None; - const PREFETCH_LOOKAHEAD: usize = 12; - engine.prewarm_for_depth(comp.depth_full); - let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); - if start < end { - let seed_start = start.saturating_add(1); - let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end); - for (k, f) in (seed_start..=seed_end).enumerate() { - prefetch.enqueue_frame( - comp, - target, - k + 1, - f as f64, - &engine.expr, - engine.use_proxy_clips, - ); - } - } - // Double-buffered async GPU readback: frame N+1 evaluates/submits on GPU while - // frame N finishes its copy/map and hands off to the background PNG writer pool. - let mut pending: Option<(crate::eval::PendingReadback, i64, usize, PathBuf, [u32; 2], f64)> = None; - for (idx, frame) in (start..=end).enumerate() { - if failed.load(Ordering::Acquire) { - break; - } - if control.is_some_and(ExportControl::is_cancelled) { - cancelled.store(true, Ordering::Release); - break; - } - prefetch.set_current_seq(idx); - if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) { - if ahead_frame <= end { - prefetch.enqueue_frame( - comp, - target, - idx + PREFETCH_LOOKAHEAD, - ahead_frame as f64, - &engine.expr, - engine.use_proxy_clips, - ); - } - } - let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) { - Ok(p) => p, - Err(e) => { - loop_err = Some(e); - break; - } - }; - - let (tex, stats) = engine.evaluate(comp, target, frame as f64); - let next_rb = match engine.begin_readback_rgba(&tex) { - Ok(rb) => rb, - Err(e) => { - loop_err = Some(format!("GPU readback failed at frame {frame}: {e}")); - break; - } - }; - if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_ms)) = - pending.replace((next_rb, frame, idx, out_path, tex.size, stats.eval_ms)) - { - let mut pixels = recycle_rx.try_recv().unwrap_or_default(); - if let Err(e) = prev_rb.finish_into(engine, &mut pixels) { - loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); - break; - } - if control.is_some_and(ExportControl::is_cancelled) { - cancelled.store(true, Ordering::Release); - break; - } - if first_path.is_none() { - first_path = Some(prev_path.clone()); - } - last_path = Some(prev_path.clone()); - let prog = make_progress( - prev_frame, - prev_idx, - total, - prev_ms, - prev_path.clone(), - saver.name.clone(), - t0, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); - } - on_progress(&prog); - if tx - .send(EncodeJob { - path: prev_path, - size: prev_size, - pixels, - }) - .is_err() - { - break; - } - frames_written += 1; - } - } - if loop_err.is_none() && !failed.load(Ordering::Acquire) && !cancelled.load(Ordering::Acquire) { - if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_ms)) = pending.take() { - let mut pixels = recycle_rx.try_recv().unwrap_or_default(); - match prev_rb.finish_into(engine, &mut pixels) { - Ok(()) => { - if control.is_some_and(ExportControl::is_cancelled) { - cancelled.store(true, Ordering::Release); - } else { - if first_path.is_none() { - first_path = Some(prev_path.clone()); - } - last_path = Some(prev_path.clone()); - let prog = make_progress( - prev_frame, - prev_idx, - total, - prev_ms, - prev_path.clone(), - saver.name.clone(), - t0, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); - } - on_progress(&prog); - if tx - .send(EncodeJob { - path: prev_path, - size: prev_size, - pixels, - }) - .is_ok() - { - frames_written += 1; - } - } - } - Err(e) => { - loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); - } - } - } - } - - drop(prefetch); - drop(tx); - for h in handles { - let _ = h.join(); - } - - if let Some(e) = loop_err { - return Err(e); - } - if let Ok(mut g) = first_err.lock() { - if let Some(e) = g.take() { - return Err(e); - } - } - if cancelled.load(Ordering::Acquire) { - return Err("Cancelled".to_owned()); - } - Ok(()) - }); - - engine.hiq = prev_hiq; - engine.proxy_scale = prev_proxy; - - eval_result?; - - Ok(ExportSummary { - saver_name: saver.name, - frames_written, - total_ms: t0.elapsed().as_secs_f64() * 1000.0, - first_path, - last_path, - }) -} - /// Output video codec profile for direct viewer / node ffmpeg export. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum VideoCodec { @@ -573,2026 +227,3 @@ pub struct VideoExportSummary { pub total_ms: f64, pub file_bytes: u64, } - -/// Evaluates `target` at `frame` on GPU and saves a single RGBA8 PNG to `out_path`. -pub fn export_node_frame_png( - engine: &mut Engine, - comp: &Comp, - target: NodeId, - frame: f64, - out_path: &Path, -) -> Result { - if target.0 >= comp.nodes.len() { - return Err(format!("invalid target node id {}", target.0)); - } - let (tex, _) = engine.evaluate(comp, target, frame); - let pixels = engine - .readback_rgba(&tex) - .map_err(|e| format!("GPU readback failed at frame {frame}: {e}"))?; - write_png_fast(out_path, tex.size, &pixels)?; - Ok(out_path.to_path_buf()) -} - -/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames -/// directly into `ffmpeg`, and muxes synced comp audio when `opts.include_audio` is enabled. -pub fn export_node_video_ffmpeg( - engine: &mut Engine, - comp: &Comp, - opts: &VideoExportOptions, - on_progress: impl FnMut(ExportProgress), -) -> Result { - export_node_video_ffmpeg_with_progress(engine, comp, opts, None, on_progress) -} - -fn probe_audio_duration_secs(path: &Path) -> Option { - let out = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "a:0", - "-show_entries", - "stream=codec_type,duration", - "-show_entries", - "format=duration", - "-of", - "default=noprint_wrappers=1", - ]) - .arg(path) - .output() - .ok()?; - if !out.status.success() { - return None; - } - let text = String::from_utf8_lossy(&out.stdout); - let mut has_audio_stream = false; - let mut stream_dur: Option = None; - let mut format_dur: Option = None; - let mut in_stream = false; - for line in text.lines() { - let Some((k, v)) = line.split_once('=') else { - continue; - }; - let key = k.trim(); - let val = v.trim(); - match key { - "codec_type" => { - in_stream = true; - if val == "audio" { - has_audio_stream = true; - } - } - "duration" => { - if let Ok(d) = val.parse::() { - if d.is_finite() && d >= 0.0 { - if in_stream && stream_dur.is_none() { - stream_dur = Some(d); - } else if !in_stream && format_dur.is_none() { - format_dur = Some(d); - } - } - } - in_stream = false; - } - _ => {} - } - } - if !has_audio_stream { - return Some(0.0); - } - stream_dur.or(format_dur) -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -struct VideoToolboxSupport { - h264: bool, - prores: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum VideoEncoder { - Libx264, - H264VideoToolbox, - ProResKs422, - ProResVideoToolbox422, - ProResKs4444, - ProResVideoToolbox4444, -} - -impl VideoEncoder { - fn is_hardware_accelerated(self) -> bool { - matches!( - self, - Self::H264VideoToolbox | Self::ProResVideoToolbox422 | Self::ProResVideoToolbox4444 - ) - } -} - -#[cfg_attr(not(target_os = "macos"), allow(dead_code))] -fn parse_videotoolbox_encoders(encoders_stdout: &str) -> VideoToolboxSupport { - let mut support = VideoToolboxSupport::default(); - for line in encoders_stdout.lines() { - let mut parts = line.split_whitespace(); - let Some(flags) = parts.next() else { - continue; - }; - if !flags.starts_with('V') { - continue; - } - let Some(name) = parts.next() else { - continue; - }; - match name { - "h264_videotoolbox" => support.h264 = true, - "prores_videotoolbox" => support.prores = true, - _ => {} - } - } - support -} - -#[cfg(target_os = "macos")] -fn probe_videotoolbox_support() -> VideoToolboxSupport { - static VT_SUPPORT: OnceLock = OnceLock::new(); - *VT_SUPPORT.get_or_init(|| { - let Ok(out) = Command::new("ffmpeg") - .args(["-hide_banner", "-encoders"]) - .output() - else { - return VideoToolboxSupport::default(); - }; - if !out.status.success() { - return VideoToolboxSupport::default(); - } - let text = String::from_utf8_lossy(&out.stdout); - parse_videotoolbox_encoders(&text) - }) -} - -#[cfg(not(target_os = "macos"))] -fn probe_videotoolbox_support() -> VideoToolboxSupport { - VideoToolboxSupport::default() -} - -fn select_video_encoder( - codec: VideoCodec, - vt: VideoToolboxSupport, - allow_videotoolbox: bool, -) -> VideoEncoder { - match codec { - VideoCodec::H264Share => { - if allow_videotoolbox && vt.h264 { - VideoEncoder::H264VideoToolbox - } else { - VideoEncoder::Libx264 - } - } - VideoCodec::ProRes422 => { - if allow_videotoolbox && vt.prores { - VideoEncoder::ProResVideoToolbox422 - } else { - VideoEncoder::ProResKs422 - } - } - VideoCodec::ProRes4444 => { - if allow_videotoolbox && vt.prores { - VideoEncoder::ProResVideoToolbox4444 - } else { - VideoEncoder::ProResKs4444 - } - } - } -} - -/// Maps x264-style CRF (`0..=51`, lower = higher quality) to VideoToolbox `-q:v` (`15..=95`, higher = higher quality). -fn vt_quality_from_crf(crf: u8) -> u8 { - (104 - i32::from(crf) * 2).clamp(15, 95) as u8 -} - -fn push_video_encoder_args(args: &mut Vec, encoder: VideoEncoder, crf: u8, vf: Option<&str>) { - match encoder { - VideoEncoder::H264VideoToolbox => { - if let Some(vf) = vf { - args.extend(["-vf".to_owned(), vf.to_owned()]); - } - args.extend([ - "-c:v".to_owned(), - "h264_videotoolbox".to_owned(), - "-q:v".to_owned(), - vt_quality_from_crf(crf).to_string(), - "-pix_fmt".to_owned(), - "yuv420p".to_owned(), - "-tag:v".to_owned(), - "avc1".to_owned(), - "-movflags".to_owned(), - "+faststart".to_owned(), - ]); - } - VideoEncoder::Libx264 => { - if let Some(vf) = vf { - args.extend(["-vf".to_owned(), vf.to_owned()]); - } - args.extend([ - "-c:v".to_owned(), - "libx264".to_owned(), - "-preset".to_owned(), - "medium".to_owned(), - "-crf".to_owned(), - crf.to_string(), - "-pix_fmt".to_owned(), - "yuv420p".to_owned(), - "-movflags".to_owned(), - "+faststart".to_owned(), - ]); - } - VideoEncoder::ProResVideoToolbox422 => { - args.extend([ - "-c:v".to_owned(), - "prores_videotoolbox".to_owned(), - "-profile:v".to_owned(), - "2".to_owned(), - "-pix_fmt".to_owned(), - "p210le".to_owned(), - ]); - } - VideoEncoder::ProResKs422 => { - args.extend([ - "-c:v".to_owned(), - "prores_ks".to_owned(), - "-profile:v".to_owned(), - "2".to_owned(), - "-pix_fmt".to_owned(), - "yuv422p10le".to_owned(), - ]); - } - VideoEncoder::ProResVideoToolbox4444 => { - args.extend([ - "-c:v".to_owned(), - "prores_videotoolbox".to_owned(), - "-profile:v".to_owned(), - "4".to_owned(), - "-pix_fmt".to_owned(), - "ayuv64le".to_owned(), - ]); - } - VideoEncoder::ProResKs4444 => { - args.extend([ - "-c:v".to_owned(), - "prores_ks".to_owned(), - "-profile:v".to_owned(), - "4".to_owned(), - "-pix_fmt".to_owned(), - "yuva444p10le".to_owned(), - ]); - } - } -} - -fn fit_frame_rgba( - pixels: Vec, - src_size: [u32; 2], - dst_size: [u32; 2], - frame: i64, -) -> Result, String> { - let expected_len = (src_size[0] as usize) - .checked_mul(src_size[1] as usize) - .and_then(|px| px.checked_mul(4)) - .ok_or_else(|| format!("frame {frame} dimensions overflow buffer size"))?; - if pixels.len() != expected_len { - return Err(format!( - "invalid RGBA buffer size at frame {frame}: expected {expected_len}, got {}", - pixels.len() - )); - } - if src_size == dst_size { - return Ok(pixels); - } - let img = image::RgbaImage::from_raw(src_size[0], src_size[1], pixels) - .ok_or_else(|| format!("invalid RGBA buffer size at frame {frame}"))?; - Ok(image::imageops::resize( - &img, - dst_size[0], - dst_size[1], - image::imageops::FilterType::Triangle, - ) - .into_raw()) -} - -static EXPORT_TMP_SEQ: AtomicU64 = AtomicU64::new(0); - -fn sibling_temp_export_path(out_path: &Path) -> PathBuf { - let seq = EXPORT_TMP_SEQ.fetch_add(1, Ordering::Relaxed); - let pid = std::process::id(); - let stem = out_path - .file_stem() - .and_then(|s| s.to_str()) - .filter(|s| !s.is_empty()) - .unwrap_or("export"); - let file_name = match out_path.extension().and_then(|e| e.to_str()).filter(|e| !e.is_empty()) { - Some(ext) => format!("{stem}.fission_tmp_{pid}_{seq}.{ext}"), - None => format!("{stem}.fission_tmp_{pid}_{seq}"), - }; - out_path.with_file_name(file_name) -} - -struct TempExportGuard { - path: PathBuf, - active: bool, -} - -impl TempExportGuard { - fn new(path: PathBuf) -> Self { - Self { path, active: true } - } - - fn disarm(&mut self) { - self.active = false; - } -} - -impl Drop for TempExportGuard { - fn drop(&mut self) { - if self.active { - let _ = std::fs::remove_file(&self.path); - } - } -} - -#[derive(Debug)] -enum VideoExportError { - Cancelled, - Fatal(String), - EncoderFailed(String), -} - -impl VideoExportError { - fn into_string(self) -> String { - match self { - Self::Cancelled => "Cancelled".to_owned(), - Self::Fatal(s) | Self::EncoderFailed(s) => s, - } - } -} - -fn h264_scale_filter_and_dims(width: u32, height: u32, max_height: Option) -> (String, u32, u32) { - if let Some(max_h) = max_height.filter(|&h| h >= 2) { - let oh = (height.min(max_h) & !1).max(2); - let ow = ((((width as f64) * (oh as f64) / (height as f64)) / 2.0).round() as u32 * 2).max(2); - (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh) - } else { - let ow = (width & !1).max(2); - let oh = (height & !1).max(2); - ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh) - } -} - -/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames -/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`. -pub fn export_node_video_ffmpeg_with_progress( - engine: &mut Engine, - comp: &Comp, - opts: &VideoExportOptions, - control: Option<&ExportControl>, - mut on_progress: impl FnMut(ExportProgress), -) -> Result { - if control.is_some_and(ExportControl::is_cancelled) { - return Err("Cancelled".to_owned()); - } - let [start, end] = opts.range; - let total_i128 = i128::from(end) - i128::from(start) + 1; - if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { - return Err(format!("invalid export frame range {start}..={end}")); - } - if opts.target.0 >= comp.nodes.len() { - return Err(format!("invalid target node id {}", opts.target.0)); - } - if opts.out_path.as_os_str().is_empty() { - return Err("video export output path is empty".to_owned()); - } - if let Some(parent) = opts.out_path.parent() { - if !parent.as_os_str().is_empty() { - std::fs::create_dir_all(parent) - .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; - } - } - - let prev_hiq = engine.hiq; - let prev_proxy = engine.proxy_scale; - engine.hiq = opts.hiq; - engine.proxy_scale = opts.proxy_scale.max(1); - - let started_at = Instant::now(); - let vt = probe_videotoolbox_support(); - let encoder = select_video_encoder(opts.codec, vt, true); - let res = match export_node_video_ffmpeg_with_encoder( - engine, - comp, - opts, - control, - &mut on_progress, - encoder, - started_at, - ) { - Ok(summary) => Ok(summary), - Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => { - if control.is_some_and(ExportControl::is_cancelled) { - Err("Cancelled".to_owned()) - } else { - let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false); - export_node_video_ffmpeg_with_encoder( - engine, - comp, - opts, - control, - &mut on_progress, - fallback, - started_at, - ) - .map_err(VideoExportError::into_string) - } - } - Err(err) => Err(err.into_string()), - }; - - engine.hiq = prev_hiq; - engine.proxy_scale = prev_proxy; - res -} - -fn export_node_video_ffmpeg_with_encoder( - engine: &mut Engine, - comp: &Comp, - opts: &VideoExportOptions, - control: Option<&ExportControl>, - on_progress: &mut impl FnMut(ExportProgress), - encoder: VideoEncoder, - started_at: Instant, -) -> Result { - let [start, end] = opts.range; - let total = (end - start + 1) as usize; - let fps = comp.fps.max(1.0); - let node_name = comp.node(opts.target).name.clone(); - - // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output. - engine.prewarm_for_depth(comp.depth_full); - let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64); - if first_tex.size[0] == 0 || first_tex.size[1] == 0 { - return Err(VideoExportError::Fatal(format!( - "target '{}' produced empty frame {}x{}", - node_name, first_tex.size[0], first_tex.size[1] - ))); - } - // If the first frame is a 1x1 dummy (e.g., missing Loader frame), fall back to comp - // canvas dimensions so ffmpeg never receives -s 1x1 and crashes scale=trunc(iw/2)*2. - let (width, height) = if first_tex.size[0] < 2 || first_tex.size[1] < 2 { - let ps = engine.proxy_scale.max(1); - let fw = (comp.width / ps).max(2); - let fh = (comp.height / ps).max(2); - if opts.codec == VideoCodec::H264Share { - (((fw + 1) & !1).max(2), ((fh + 1) & !1).max(2)) - } else { - (fw, fh) - } - } else { - (first_tex.size[0], first_tex.size[1]) - }; - let raw_first = engine - .readback_rgba(&first_tex) - .map_err(|e| VideoExportError::Fatal(format!("GPU readback failed at frame {start}: {e}")))?; - let first_pixels = fit_frame_rgba(raw_first, first_tex.size, [width, height], start) - .map_err(VideoExportError::Fatal)?; - if control.is_some_and(ExportControl::is_cancelled) { - return Err(VideoExportError::Cancelled); - } - - let duration_secs = total as f64 / fps; - let audio_start_secs = (start as f64 - comp.audio_offset) / fps; - let audio_path = if opts.include_audio { - comp.audio_filename - .as_deref() - .map(PathBuf::from) - .filter(|p| { - if p.as_os_str().is_empty() || !p.exists() || -audio_start_secs >= duration_secs { - return false; - } - if let Some(audio_dur) = probe_audio_duration_secs(p) { - if audio_dur <= 0.0 || audio_start_secs >= audio_dur { - return false; - } - } - true - }) - } else { - None - }; - let has_audio = audio_path.is_some(); - - let mut cmd = Command::new("ffmpeg"); - cmd.args(["-y", "-hide_banner", "-loglevel", "error"]); - cmd.args([ - "-f", - "rawvideo", - "-pix_fmt", - "rgba", - "-s", - &format!("{width}x{height}"), - "-r", - &format!("{fps:.6}"), - "-i", - "pipe:0", - ]); - - let audio_filter = if let Some(ap) = &audio_path { - if audio_start_secs >= 0.0 { - if audio_start_secs > 0.0 { - cmd.args(["-ss", &format!("{audio_start_secs:.6}")]); - } - cmd.arg("-i").arg(ap); - Some(format!("asetpts=PTS-STARTPTS,apad,atrim=0:{duration_secs:.6}")) - } else { - let delay_ms = (-audio_start_secs * 1000.0).max(0.0); - cmd.arg("-i").arg(ap); - Some(format!( - "adelay={delay_ms:.3}:all=1,apad,atrim=0:{duration_secs:.6},asetpts=PTS-STARTPTS" - )) - } - } else { - None - }; - - let (out_width, out_height) = match opts.codec { - VideoCodec::H264Share => { - let (vf, ow, oh) = h264_scale_filter_and_dims(width, height, opts.max_height); - let mut encoder_args = Vec::new(); - push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf)); - cmd.args(&encoder_args); - (ow, oh) - } - VideoCodec::ProRes422 | VideoCodec::ProRes4444 => { - let mut encoder_args = Vec::new(); - push_video_encoder_args(&mut encoder_args, encoder, opts.crf, None); - cmd.args(&encoder_args); - (width, height) - } - }; - - if let Some(af) = audio_filter { - cmd.args(["-map", "0:v:0", "-map", "1:a:0", "-af", &af]); - match opts.codec { - VideoCodec::H264Share => { - cmd.args(["-c:a", "aac", "-b:a", "128k"]); - } - VideoCodec::ProRes422 | VideoCodec::ProRes4444 => { - cmd.args(["-c:a", "pcm_s16le"]); - } - } - } else { - cmd.arg("-an"); - } - - let tmp_path = sibling_temp_export_path(&opts.out_path); - let mut tmp_guard = TempExportGuard::new(tmp_path.clone()); - cmd.arg(&tmp_path); - cmd.stdin(Stdio::piped()) - .stdout(Stdio::null()) - .stderr(Stdio::piped()); - - let mut child = cmd.spawn().map_err(|e| { - VideoExportError::Fatal(format!( - "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}" - )) - })?; - - let mut stderr_pipe = child.stderr.take(); - let stderr_thread = std::thread::spawn(move || { - let mut buf = String::new(); - if let Some(ref mut pipe) = stderr_pipe { - let _ = pipe.read_to_string(&mut buf); - } - buf - }); - - let mut readback_err: Option = None; - let mut pipe_err: Option = None; - let mut cancelled = false; - let writer_err: Arc>> = Arc::new(Mutex::new(None)); - let writer_failed = Arc::new(AtomicBool::new(false)); - let writer_fatal = Arc::new(AtomicBool::new(false)); - let Some(stdin) = child.stdin.take() else { - let _ = child.kill(); - let _ = child.wait(); - let _ = stderr_thread.join(); - return Err(VideoExportError::Fatal( - "failed to open ffmpeg stdin".to_owned(), - )); - }; - - let frame_bytes_len = (width as usize) - .saturating_mul(height as usize) - .saturating_mul(4) - .max(1); - let queue_cap = (128 * 1024 * 1024 / frame_bytes_len).clamp(4, 16); - let (tx, rx) = mpsc::sync_channel::<(i64, [u32; 2], Vec)>(queue_cap); - let (recycle_tx, recycle_rx) = mpsc::sync_channel::>(queue_cap + 2); - let writer_err_c = Arc::clone(&writer_err); - let writer_failed_c = Arc::clone(&writer_failed); - let writer_fatal_c = Arc::clone(&writer_fatal); - let dst_size = [width, height]; - let writer_thread = std::thread::spawn(move || { - let mut stdin = stdin; - while let Ok((frame, src_size, pixels)) = rx.recv() { - let frame_bytes = match fit_frame_rgba(pixels, src_size, dst_size, frame) { - Ok(bytes) => bytes, - Err(e) => { - if let Ok(mut g) = writer_err_c.lock() { - if g.is_none() { - *g = Some(e); - } - } - writer_fatal_c.store(true, Ordering::Release); - writer_failed_c.store(true, Ordering::Release); - break; - } - }; - // Each frame is already a contiguous RGBA buffer; write directly without an extra copy. - if let Err(e) = stdin.write_all(&frame_bytes) { - if let Ok(mut g) = writer_err_c.lock() { - if g.is_none() { - *g = Some(format!("failed writing frame {frame} to ffmpeg: {e}")); - } - } - writer_failed_c.store(true, Ordering::Release); - break; - } - let _ = recycle_tx.try_send(frame_bytes); - } - let _ = stdin.flush(); - }); - - if tx.send((start, [width, height], first_pixels)).is_err() { - pipe_err = writer_err - .lock() - .ok() - .and_then(|mut g| g.take()) - .or_else(|| Some(format!("failed writing frame {start} to ffmpeg"))); - } else { - let first_prog = make_progress( - start, - 0, - total, - first_stats.eval_ms, - opts.out_path.clone(), - node_name.clone(), - started_at, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&first_prog); - } - on_progress(first_prog); - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - } else if start < end { - const PREFETCH_LOOKAHEAD: usize = 12; - let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); - let seed_start = start.saturating_add(1); - let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64).min(end); - for (k, f) in (seed_start..=seed_end).enumerate() { - prefetch.enqueue_frame( - comp, - opts.target, - k, - f as f64, - &engine.expr, - engine.use_proxy_clips, - ); - } - let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None; - for (idx, frame) in (seed_start..=end).enumerate() { - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - break; - } - if writer_failed.load(Ordering::Acquire) { - break; - } - prefetch.set_current_seq(idx); - if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) { - if ahead_frame <= end { - prefetch.enqueue_frame( - comp, - opts.target, - idx + PREFETCH_LOOKAHEAD, - ahead_frame as f64, - &engine.expr, - engine.use_proxy_clips, - ); - } - } - let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); - let next_rb = match engine.begin_readback_rgba(&tex) { - Ok(rb) => rb, - Err(e) => { - readback_err = Some(format!("GPU readback failed at frame {frame}: {e}")); - break; - } - }; - if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = - pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms)) - { - let mut pixels = recycle_rx.try_recv().unwrap_or_default(); - if let Err(e) = prev_rb.finish_into(engine, &mut pixels) { - readback_err = - Some(format!("GPU readback failed at frame {prev_frame}: {e}")); - break; - } - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - break; - } - if tx.send((prev_frame, prev_size, pixels)).is_err() { - break; - } - let prog = make_progress( - prev_frame, - prev_idx + 1, - total, - prev_ms, - opts.out_path.clone(), - node_name.clone(), - started_at, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); - } - on_progress(prog); - } - } - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - } - if readback_err.is_none() && pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) { - if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() { - let mut pixels = recycle_rx.try_recv().unwrap_or_default(); - match prev_rb.finish_into(engine, &mut pixels) { - Ok(()) => { - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - } else if tx.send((prev_frame, prev_size, pixels)).is_ok() { - let prog = make_progress( - prev_frame, - prev_idx + 1, - total, - prev_ms, - opts.out_path.clone(), - node_name.clone(), - started_at, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); - } - on_progress(prog); - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - } - } - } - Err(e) => { - readback_err = - Some(format!("GPU readback failed at frame {prev_frame}: {e}")); - } - } - } - } - drop(prefetch); - } - } - drop(tx); - - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - } - if cancelled || readback_err.is_some() || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) { - // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately. - let _ = child.kill(); - } - let _ = writer_thread.join(); - if pipe_err.is_none() && !cancelled { - if let Ok(mut g) = writer_err.lock() { - pipe_err = g.take(); - } - } - if pipe_err.is_some() && !cancelled { - let _ = child.kill(); - } - let wait_res = child.wait(); - let stderr_text = stderr_thread.join().unwrap_or_default(); - let stderr_trim = stderr_text.trim(); - - if cancelled || control.is_some_and(ExportControl::is_cancelled) { - return Err(VideoExportError::Cancelled); - } - if let Some(err) = readback_err { - return Err(VideoExportError::Fatal(err)); - } - if let Some(err) = pipe_err { - if writer_fatal.load(Ordering::Acquire) { - return Err(VideoExportError::Fatal(err)); - } - return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() { - format!("{err} (ffmpeg: {stderr_trim})") - } else { - err - })); - } - let status = wait_res.map_err(|e| { - VideoExportError::Fatal(format!("failed waiting on ffmpeg: {e}")) - })?; - if !status.success() { - if control.is_some_and(ExportControl::is_cancelled) { - return Err(VideoExportError::Cancelled); - } - return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() { - format!("ffmpeg exited with {status}") - } else { - format!("ffmpeg exited with {status}: {stderr_trim}") - })); - } - - std::fs::rename(&tmp_path, &opts.out_path).map_err(|e| { - VideoExportError::Fatal(format!("failed to finalize '{}': {e}", opts.out_path.display())) - })?; - tmp_guard.disarm(); - - let file_bytes = std::fs::metadata(&opts.out_path) - .map(|m| m.len()) - .unwrap_or(0); - - Ok(VideoExportSummary { - out_path: opts.out_path.clone(), - frames_written: total, - width: out_width, - height: out_height, - has_audio, - total_ms: started_at.elapsed().as_secs_f64() * 1000.0, - file_bytes, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn exports_saver_png_sequence_animated() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-saver-export-test-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - let saver_path = tmp_dir.join("nested").join("shot_0000.png"); - let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); - - let comp_src = format!( - r#"Composition {{ - CurrentTime = 10, - RenderRange = {{ 10, 12 }}, - GlobalRange = {{ 0, 100 }}, - Tools = ordered() {{ - BG = Background {{ - Inputs = {{ - Width = Input {{ Value = 64, }}, - Height = Input {{ Value = 32, }}, - TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, - TopLeftGreen = Input {{ Value = 0.25, }}, - TopLeftBlue = Input {{ Value = 0.5, }}, - TopLeftAlpha = Input {{ Value = 1, }}, - }}, - }}, - BGRed = BezierSpline {{ - KeyFrames = {{ - [10] = {{ 0.0, Flags = {{ Linear = true }} }}, - [12] = {{ 1.0, Flags = {{ Linear = true }} }}, - }}, - }}, - Saver1 = Saver {{ - Inputs = {{ - Clip = Input {{ - Value = Clip {{ - Filename = "{saver_path_escaped}", - FormatID = "PNGFormat", - Saving = true, - }}, - }}, - Input = Input {{ - SourceOp = "BG", - Source = "Output", - }}, - }}, - }}, - }}, - Prefs = {{ - Comp = {{ - FrameFormat = {{ - Width = 64, - Height = 32, - Rate = 30, - DepthFull = 1, - }}, - }}, - }}, -}}"# - ); - - let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp"); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - - let mut seen_frames = Vec::new(); - let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |p| { - seen_frames.push(p.frame); - }) - .expect("export png sequence"); - - assert_eq!(summary.saver_name, "Saver1"); - assert_eq!(summary.frames_written, 3); - assert_eq!(seen_frames, vec![10, 11, 12]); - - let expected_reds = [0u8, 128u8, 255u8]; - for (frame, exp_r) in [10i64, 11, 12].into_iter().zip(expected_reds) { - let p = tmp_dir.join("nested").join(format!("shot_{frame:04}.png")); - assert!(p.exists(), "missing exported frame {}", p.display()); - let img = image::open(&p).expect("decode exported PNG").to_rgba8(); - assert_eq!(img.dimensions(), (64, 32)); - let px = img.get_pixel(32, 16); - assert!( - (px[0] as i32 - exp_r as i32).abs() <= 2, - "frame {frame}: expected R~{exp_r}, got {:?}", - px.0 - ); - assert!((px[1] as i32 - 64).abs() <= 2); - assert!((px[2] as i32 - 128).abs() <= 2); - assert_eq!(px[3], 255); - } - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - fn write_test_wav(path: &Path, sample_rate: u32, duration_secs: f64) { - let num_channels: u16 = 2; - let bits_per_sample: u16 = 16; - let num_samples = (sample_rate as f64 * duration_secs) as u32; - let byte_rate = sample_rate * u32::from(num_channels) * u32::from(bits_per_sample) / 8; - let block_align = num_channels * bits_per_sample / 8; - let data_bytes = num_samples * u32::from(block_align); - let riff_chunk_size = 36 + data_bytes; - - let mut buf = Vec::with_capacity((44 + data_bytes) as usize); - buf.extend_from_slice(b"RIFF"); - buf.extend_from_slice(&riff_chunk_size.to_le_bytes()); - buf.extend_from_slice(b"WAVE"); - buf.extend_from_slice(b"fmt "); - buf.extend_from_slice(&16u32.to_le_bytes()); - buf.extend_from_slice(&1u16.to_le_bytes()); // PCM - buf.extend_from_slice(&num_channels.to_le_bytes()); - buf.extend_from_slice(&sample_rate.to_le_bytes()); - buf.extend_from_slice(&byte_rate.to_le_bytes()); - buf.extend_from_slice(&block_align.to_le_bytes()); - buf.extend_from_slice(&bits_per_sample.to_le_bytes()); - buf.extend_from_slice(b"data"); - buf.extend_from_slice(&data_bytes.to_le_bytes()); - for i in 0..num_samples { - let t = i as f64 / sample_rate as f64; - let sample = ((t * 440.0 * std::f64::consts::TAU).sin() * 12000.0) as i16; - buf.extend_from_slice(&sample.to_le_bytes()); - buf.extend_from_slice(&sample.to_le_bytes()); - } - std::fs::write(path, buf).expect("write synthetic wav"); - } - - #[test] - fn exports_snippet_mp4_with_synced_audio() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-video-export-test-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); - - let wav_path = tmp_dir.join("tone.wav"); - write_test_wav(&wav_path, 44100, 2.0); - let wav_escaped = wav_path.to_string_lossy().replace('\\', "\\\\"); - - let comp_src = format!( - r#"Composition {{ - CurrentTime = 10, - RenderRange = {{ 10, 21 }}, - GlobalRange = {{ 0, 100 }}, - AudioFilename = "{wav_escaped}", - AudioOffset = 10, - Tools = ordered() {{ - BG = Background {{ - Inputs = {{ - Width = Input {{ Value = 128, }}, - Height = Input {{ Value = 72, }}, - TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, - TopLeftGreen = Input {{ Value = 0.25, }}, - TopLeftBlue = Input {{ Value = 0.75, }}, - TopLeftAlpha = Input {{ Value = 1, }}, - }}, - }}, - BGRed = BezierSpline {{ - KeyFrames = {{ - [10] = {{ 0.0, Flags = {{ Linear = true }} }}, - [21] = {{ 1.0, Flags = {{ Linear = true }} }}, - }}, - }}, - }}, - Prefs = {{ - Comp = {{ - FrameFormat = {{ - Width = 128, - Height = 72, - Rate = 30, - DepthFull = 1, - }}, - }}, - }}, -}}"# - ); - - let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic audio comp"); - let target = comp.find_node("BG").expect("find BG node"); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - - let mp4_path = tmp_dir.join("snippet.mp4"); - let mut seen_frames = Vec::new(); - let summary = export_node_video_ffmpeg( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: mp4_path.clone(), - range: [10, 21], - codec: VideoCodec::H264Share, - crf: 26, - max_height: None, - include_audio: true, - hiq: true, - proxy_scale: 1, - }, - |p| seen_frames.push(p.frame), - ) - .expect("export snippet mp4"); - - assert_eq!(summary.frames_written, 12); - assert_eq!(summary.width, 128); - assert_eq!(summary.height, 72); - assert!(summary.has_audio); - assert!(summary.file_bytes > 0); - assert_eq!(seen_frames.len(), 12); - assert!(mp4_path.exists()); - - // Verify streams and exact video frame count via ffprobe - let probe = Command::new("ffprobe") - .args([ - "-v", - "error", - "-count_frames", - "-show_entries", - "stream=codec_type,codec_name,nb_read_frames", - "-of", - "csv=p=0", - ]) - .arg(&mp4_path) - .output() - .expect("run ffprobe"); - assert!( - probe.status.success(), - "ffprobe failed: {}", - String::from_utf8_lossy(&probe.stderr) - ); - let stdout = String::from_utf8_lossy(&probe.stdout); - let mut saw_h264_12 = false; - let mut saw_aac = false; - for line in stdout.lines() { - let cols: Vec<&str> = line.split(',').map(str::trim).collect(); - if cols.len() >= 3 && cols[1] == "video" && cols[0] == "h264" && cols[2] == "12" { - saw_h264_12 = true; - } - if cols.len() >= 2 && cols[1] == "audio" && cols[0] == "aac" { - saw_aac = true; - } - } - assert!( - saw_h264_12, - "expected h264 video stream with 12 frames, ffprobe output:\n{stdout}" - ); - assert!( - saw_aac, - "expected aac audio stream, ffprobe output:\n{stdout}" - ); - - // Also verify negative audio_start_secs (range starts before AudioOffset = 10) - let pre_mp4_path = tmp_dir.join("snippet_pre_offset.mp4"); - let pre_summary = export_node_video_ffmpeg( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: pre_mp4_path.clone(), - range: [6, 17], - codec: VideoCodec::H264Share, - crf: 26, - max_height: Some(64), - include_audio: true, - hiq: true, - proxy_scale: 1, - }, - |_| {}, - ) - .expect("export snippet mp4 with negative audio_start_secs"); - assert_eq!(pre_summary.frames_written, 12); - assert!(pre_summary.has_audio); - assert!(pre_summary.file_bytes > 0); - assert!(pre_mp4_path.exists()); - - // Verify single-frame PNG helper - let png_path = tmp_dir.join("frame_10.png"); - let saved = export_node_frame_png(&mut engine, &comp, target, 10.0, &png_path) - .expect("export single frame png"); - assert_eq!(saved, png_path); - let img = image::open(&png_path).expect("decode exported frame png").to_rgba8(); - assert_eq!(img.dimensions(), (128, 72)); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - #[test] - fn saver_export_reports_progress_and_stops_on_cancel() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-saver-cancel-test-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - let saver_path = tmp_dir.join("shot_0000.png"); - let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); - - let comp_src = format!( - r#"Composition {{ - CurrentTime = 10, - RenderRange = {{ 10, 15 }}, - GlobalRange = {{ 0, 100 }}, - Tools = ordered() {{ - BG = Background {{ - Inputs = {{ - Width = Input {{ Value = 64, }}, - Height = Input {{ Value = 32, }}, - TopLeftRed = Input {{ Value = 0.7, }}, - TopLeftAlpha = Input {{ Value = 1, }}, - }}, - }}, - Saver1 = Saver {{ - Inputs = {{ - Clip = Input {{ - Value = Clip {{ - Filename = "{saver_path_escaped}", - FormatID = "PNGFormat", - Saving = true, - }}, - }}, - Input = Input {{ - SourceOp = "BG", - Source = "Output", - }}, - }}, - }}, - }}, - Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 1 }} }} }}, -}}"# - ); - - let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp"); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - let control = ExportControl::new(); - let ctrl_cb = control.clone(); - let mut reported = Vec::new(); - - let err = export_saver_png_sequence_with_progress( - &mut engine, - &comp, - &ExportOptions::default(), - Some(&control), - |p| { - reported.push((p.current_frame, p.completed_frames, p.total_frames, p.label.clone())); - if p.completed_frames >= 2 { - ctrl_cb.cancel(); - } - }, - ) - .expect_err("saver export should cancel early"); - - assert_eq!(err, "Cancelled"); - assert_eq!(reported.len(), 2); - assert_eq!(reported[0].0, 10); - assert_eq!(reported[0].1, 1); - assert_eq!(reported[0].2, 6); - assert_eq!(reported[0].3, "Saver1"); - assert_eq!(reported[1].0, 11); - assert_eq!(reported[1].1, 2); - - let snap = control.snapshot_progress(); - assert_eq!(snap.completed_frames, 2); - assert_eq!(snap.total_frames, 6); - assert!(snap.elapsed_secs >= 0.0); - assert!(!tmp_dir.join("shot_0015.png").exists()); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - #[test] - fn video_export_reports_progress_and_cleans_up_on_cancel() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-video-cancel-test-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); - - let comp_src = r#"Composition { - CurrentTime = 1, - RenderRange = { 1, 12 }, - GlobalRange = { 0, 100 }, - Tools = ordered() { - BG = Background { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 72, }, - TopLeftRed = Input { Value = 0.2, }, - TopLeftGreen = Input { Value = 0.6, }, - TopLeftBlue = Input { Value = 0.9, }, - TopLeftAlpha = Input { Value = 1, }, - }, - }, - }, - Prefs = { Comp = { FrameFormat = { Width = 128, Height = 72, Rate = 24, DepthFull = 1 } } }, -}"#; - - let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic video comp"); - let target = comp.find_node("BG").expect("find BG node"); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - let out_mp4 = tmp_dir.join("cancelled.mp4"); - let control = ExportControl::new(); - let ctrl_cb = control.clone(); - let mut seen = Vec::new(); - - let err = export_node_video_ffmpeg_with_progress( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: out_mp4.clone(), - range: [1, 12], - codec: VideoCodec::H264Share, - crf: 26, - max_height: None, - include_audio: false, - hiq: true, - proxy_scale: 1, - }, - Some(&control), - |p| { - seen.push((p.current_frame, p.completed_frames, p.total_frames, p.label.clone())); - if p.completed_frames >= 3 { - ctrl_cb.cancel(); - } - }, - ) - .expect_err("video export should cancel early"); - - assert_eq!(err, "Cancelled"); - assert_eq!(seen.len(), 3); - assert_eq!(seen[0].0, 1); - assert_eq!(seen[0].1, 1); - assert_eq!(seen[0].2, 12); - assert_eq!(seen[0].3, "BG"); - assert_eq!(seen[2].0, 3); - assert_eq!(seen[2].1, 3); - - let snap = control.snapshot_progress(); - assert_eq!(snap.completed_frames, 3); - assert_eq!(snap.total_frames, 12); - assert!(!out_mp4.exists(), "partial mp4 should be removed after cancellation"); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - #[test] - fn video_export_handles_short_audio_past_eof_odd_dims_and_1x1_dummy() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-video-edge-cases-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); - - let short_wav = tmp_dir.join("short.wav"); - write_test_wav(&short_wav, 44100, 0.15); - let wav_escaped = short_wav.to_string_lossy().replace('\\', "\\\\"); - - // 1. Short audio (0.15s) with 1.0s (24 frames @ 24fps) odd-dimension (127x71) video. - let comp_src = format!( - r#"Composition {{ - CurrentTime = 0, - RenderRange = {{ 0, 23 }}, - GlobalRange = {{ 0, 23 }}, - AudioFilename = "{wav_escaped}", - AudioOffset = 0, - Tools = ordered() {{ - BG = Background {{ - Inputs = {{ - Width = Input {{ Value = 127, }}, - Height = Input {{ Value = 71, }}, - TopLeftRed = Input {{ Value = 0.4, }}, - TopLeftGreen = Input {{ Value = 0.5, }}, - TopLeftBlue = Input {{ Value = 0.6, }}, - TopLeftAlpha = Input {{ Value = 1, }}, - }}, - }}, - }}, - Prefs = {{ Comp = {{ FrameFormat = {{ Width = 127, Height = 71, Rate = 24, DepthFull = 1 }} }} }}, -}}"# - ); - let comp = Comp::from_fusion_str(&comp_src).expect("parse odd+short-audio comp"); - let target = comp.find_node("BG").unwrap(); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - - let short_mp4 = tmp_dir.join("short_audio_odd.mp4"); - let summary = export_node_video_ffmpeg( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: short_mp4.clone(), - range: [0, 23], - codec: VideoCodec::H264Share, - crf: 26, - max_height: None, - include_audio: true, - hiq: true, - proxy_scale: 1, - }, - |_| {}, - ) - .expect("export with short audio and odd dimensions should succeed without Broken pipe"); - assert_eq!(summary.frames_written, 24); - assert_eq!(summary.width, 126); - assert_eq!(summary.height, 70); - assert!(summary.has_audio); - - // 2. Audio start past EOF -> skips audio cleanly (`has_audio == false`). - let mut past_eof_comp = comp.clone(); - past_eof_comp.audio_offset = -100.0; // start=0 -> audio_start_secs = +4.17s > 0.15s - let past_mp4 = tmp_dir.join("past_eof.mp4"); - let past_summary = export_node_video_ffmpeg( - &mut engine, - &past_eof_comp, - &VideoExportOptions { - target, - out_path: past_mp4.clone(), - range: [0, 5], - codec: VideoCodec::H264Share, - crf: 26, - max_height: None, - include_audio: true, - hiq: true, - proxy_scale: 1, - }, - |_| {}, - ) - .expect("export with audio past EOF should skip audio and succeed"); - assert_eq!(past_summary.frames_written, 6); - assert!(!past_summary.has_audio); - - // 3. First frame 1x1 dummy (Loader with missing frame 0, MissingFrames = 0) -> falls back to comp canvas. - let seq1 = tmp_dir.join("seq_0001.png"); - image::RgbaImage::from_pixel(64, 36, image::Rgba([20, 200, 40, 255])) - .save(&seq1) - .unwrap(); - let seq0 = tmp_dir.join("seq_0000.png"); // intentionally absent - let seq0_esc = seq0.to_string_lossy().replace('\\', "\\\\"); - let dummy_comp_src = format!( - r#"Composition {{ - CurrentTime = 0, - RenderRange = {{ 0, 1 }}, - GlobalRange = {{ 0, 1 }}, - Tools = ordered() {{ - LD = Loader {{ - Clips = {{ - Clip {{ - ID = "Clip1", - Filename = "{seq0_esc}", - FormatID = "PNGFormat", - StartFrame = 0, - Length = 2, - GlobalStart = 0, - GlobalEnd = 1, - }}, - }}, - }}, - }}, - Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 36, Rate = 24, DepthFull = 1 }} }} }}, -}}"# - ); - let dummy_comp = Comp::from_fusion_str(&dummy_comp_src).expect("parse dummy loader comp"); - let ld = dummy_comp.find_node("LD").unwrap(); - engine.bust_all_caches(); - let dummy_mp4 = tmp_dir.join("dummy_first.mp4"); - let dummy_summary = export_node_video_ffmpeg( - &mut engine, - &dummy_comp, - &VideoExportOptions { - target: ld, - out_path: dummy_mp4.clone(), - range: [0, 1], - codec: VideoCodec::H264Share, - crf: 26, - max_height: None, - include_audio: false, - hiq: true, - proxy_scale: 1, - }, - |_| {}, - ) - .expect("export with 1x1 first frame should fall back to comp dimensions"); - assert_eq!(dummy_summary.frames_written, 2); - assert_eq!(dummy_summary.width, 64); - assert_eq!(dummy_summary.height, 36); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - #[test] - fn video_export_cancel_preserves_existing_output_and_removes_temp_file() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-video-atomic-cancel-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); - - let out_mp4 = tmp_dir.join("existing.mp4"); - let sentinel_bytes = b"ORIGINAL_VALUABLE_EXPORT_BYTES_DO_NOT_TRUNCATE"; - std::fs::write(&out_mp4, sentinel_bytes).expect("write sentinel existing file"); - - let comp_src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 9 }, - GlobalRange = { 0, 9 }, - Tools = ordered() { - BG = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - TopLeftRed = Input { Value = 0.8, }, - TopLeftAlpha = Input { Value = 1, }, - }, - }, - }, - Prefs = { Comp = { FrameFormat = { Width = 64, Height = 64, Rate = 24, DepthFull = 1 } } }, -}"#; - let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); - let target = comp.find_node("BG").expect("find BG"); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - let control = ExportControl::new(); - let ctrl_cb = control.clone(); - - let err = export_node_video_ffmpeg_with_progress( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: out_mp4.clone(), - range: [0, 9], - codec: VideoCodec::H264Share, - crf: 26, - max_height: None, - include_audio: false, - hiq: true, - proxy_scale: 1, - }, - Some(&control), - |p| { - if p.completed_frames >= 2 { - ctrl_cb.cancel(); - } - }, - ) - .expect_err("cancelled export should return Err"); - assert_eq!(err, "Cancelled"); - - let after_bytes = std::fs::read(&out_mp4).expect("existing output must still exist"); - assert_eq!(after_bytes.as_slice(), sentinel_bytes, "existing file must stay untouched"); - - let entries: Vec<_> = std::fs::read_dir(&tmp_dir) - .expect("read tmp_dir") - .filter_map(|e| e.ok()) - .map(|e| e.file_name().to_string_lossy().into_owned()) - .collect(); - assert_eq!(entries, vec!["existing.mp4".to_owned()], "no temp files should remain"); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - #[test] - fn pipelined_png_export_is_pixel_exact_and_propagates_write_errors() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-png-pipeline-exact-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); - - let saver_path = tmp_dir.join("out").join("frame_0000.png"); - let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); - let comp_src = format!( - r#"Composition {{ - CurrentTime = 0, - RenderRange = {{ 0, 5 }}, - GlobalRange = {{ 0, 5 }}, - Tools = ordered() {{ - BG = Background {{ - Inputs = {{ - Width = Input {{ Value = 96, }}, - Height = Input {{ Value = 48, }}, - TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, - TopLeftGreen = Input {{ Value = 0.5, }}, - TopLeftBlue = Input {{ Value = 0.25, }}, - TopLeftAlpha = Input {{ Value = 1.0, }}, - }}, - }}, - BGRed = BezierSpline {{ - KeyFrames = {{ - [0] = {{ 0.1, Flags = {{ Linear = true }} }}, - [5] = {{ 0.9, Flags = {{ Linear = true }} }}, - }}, - }}, - Saver1 = Saver {{ - Inputs = {{ - Clip = Input {{ - Value = Clip {{ - Filename = "{saver_path_escaped}", - FormatID = "PNGFormat", - Saving = true, - }}, - }}, - Input = Input {{ SourceOp = "BG", Source = "Output", }}, - }}, - }}, - }}, - Prefs = {{ Comp = {{ FrameFormat = {{ Width = 96, Height = 48, Rate = 24, DepthFull = 1 }} }} }}, -}}"# - ); - - let comp = Comp::from_fusion_str(&comp_src).expect("parse comp"); - let target = comp.find_node("BG").unwrap(); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - - let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |_| {}) - .expect("export png sequence"); - assert_eq!(summary.frames_written, 6); - - // Verify fast-compressed PNGs decode byte-identically to direct GPU readback. - for f in 0..=5 { - let (tex, _) = engine.evaluate(&comp, target, f as f64); - let expected = engine.readback_rgba(&tex).expect("readback"); - let png_path = tmp_dir.join("out").join(format!("frame_{f:04}.png")); - let decoded = image::open(&png_path).expect("decode png").to_rgba8(); - assert_eq!(decoded.dimensions(), (tex.size[0], tex.size[1])); - assert_eq!( - decoded.into_raw(), - expected, - "fast PNG encode must be 100% lossless at frame {f}" - ); - } - - // Verify worker write error propagates cleanly: point out_dir_override inside a regular file. - let blocking_file = tmp_dir.join("not_a_dir"); - std::fs::write(&blocking_file, b"file").expect("write blocking file"); - let err = export_saver_png_sequence( - &mut engine, - &comp, - &ExportOptions { - out_dir_override: Some(blocking_file), - ..ExportOptions::default() - }, - |_| {}, - ) - .expect_err("writing into a regular file path must return Err"); - assert!(!err.is_empty()); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - #[test] - fn videotoolbox_probe_selection_and_fallback() { - let sample_both = "\ -Encoders: - V..... = Video - ------ - V....D libx264 libx264 H.264 / AVC - V....D h264_videotoolbox VideoToolbox H.264 Encoder (codec h264) - VFS... prores_ks Apple ProRes (iCodec Pro) (codec prores) - V....D prores_videotoolbox VideoToolbox ProRes Encoder (codec prores) - A....D aac AAC (Advanced Audio Coding) -"; - let vt_both = parse_videotoolbox_encoders(sample_both); - assert_eq!(vt_both, VideoToolboxSupport { h264: true, prores: true }); - - let sample_h264_only = " V....D h264_videotoolbox VideoToolbox H.264 Encoder\n"; - assert_eq!( - parse_videotoolbox_encoders(sample_h264_only), - VideoToolboxSupport { h264: true, prores: false } - ); - assert_eq!( - parse_videotoolbox_encoders(" V....D libx264 H.264\n"), - VideoToolboxSupport::default() - ); - - // Hardware selection when supported and allowed - assert_eq!( - select_video_encoder(VideoCodec::H264Share, vt_both, true), - VideoEncoder::H264VideoToolbox - ); - assert_eq!( - select_video_encoder(VideoCodec::ProRes422, vt_both, true), - VideoEncoder::ProResVideoToolbox422 - ); - assert_eq!( - select_video_encoder(VideoCodec::ProRes4444, vt_both, true), - VideoEncoder::ProResVideoToolbox4444 - ); - - // Fallback when VideoToolbox is unavailable or disabled after failure - assert_eq!( - select_video_encoder(VideoCodec::H264Share, vt_both, false), - VideoEncoder::Libx264 - ); - assert_eq!( - select_video_encoder(VideoCodec::ProRes422, vt_both, false), - VideoEncoder::ProResKs422 - ); - assert_eq!( - select_video_encoder(VideoCodec::ProRes4444, vt_both, false), - VideoEncoder::ProResKs4444 - ); - assert_eq!( - select_video_encoder(VideoCodec::H264Share, VideoToolboxSupport::default(), true), - VideoEncoder::Libx264 - ); - - assert_eq!(vt_quality_from_crf(0), 95); - assert_eq!(vt_quality_from_crf(26), 52); - assert_eq!(vt_quality_from_crf(51), 15); - - let mut args = Vec::new(); - push_video_encoder_args(&mut args, VideoEncoder::H264VideoToolbox, 26, Some("scale=trunc(iw/2)*2:trunc(ih/2)*2")); - assert!(args.windows(2).any(|w| w == ["-c:v", "h264_videotoolbox"])); - assert!(args.windows(2).any(|w| w == ["-q:v", "52"])); - assert!(args.windows(2).any(|w| w == ["-tag:v", "avc1"])); - assert!(args.windows(2).any(|w| w == ["-pix_fmt", "yuv420p"])); - - args.clear(); - push_video_encoder_args(&mut args, VideoEncoder::Libx264, 26, Some("scale=trunc(iw/2)*2:trunc(ih/2)*2")); - assert!(args.windows(2).any(|w| w == ["-c:v", "libx264"])); - assert!(args.windows(2).any(|w| w == ["-crf", "26"])); - - args.clear(); - push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox422, 26, None); - assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"])); - assert!(args.windows(2).any(|w| w == ["-profile:v", "2"])); - assert!(args.windows(2).any(|w| w == ["-pix_fmt", "p210le"])); - - args.clear(); - push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox4444, 26, None); - assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"])); - assert!(args.windows(2).any(|w| w == ["-profile:v", "4"])); - assert!(args.windows(2).any(|w| w == ["-pix_fmt", "ayuv64le"])); - } - - #[test] - fn fit_frame_rgba_zero_copy_fast_path_and_resize() { - let pixels = vec![128u8; 8 * 4 * 4]; - let orig_ptr = pixels.as_ptr(); - let moved = fit_frame_rgba(pixels, [8, 4], [8, 4], 0).expect("matching size fast path"); - assert_eq!(moved.as_ptr(), orig_ptr, "matching size must move Vec without copying"); - - let resized = fit_frame_rgba(moved, [8, 4], [4, 2], 1).expect("resize path"); - assert_eq!(resized.len(), 4 * 2 * 4); - - let err = fit_frame_rgba(vec![0u8; 10], [8, 4], [8, 4], 2) - .expect_err("mismatched RGBA byte length must fail"); - assert!(err.contains("invalid RGBA buffer size")); - } - - #[test] - fn prores_4444_preserves_alpha_channel() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-prores4444-alpha-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); - - let comp_src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - BG = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 36, }, - TopLeftRed = Input { Value = 0.8, }, - TopLeftGreen = Input { Value = 0.4, }, - TopLeftBlue = Input { Value = 0.2, }, - TopLeftAlpha = Input { SourceOp = "BGAlpha", Source = "Value", }, - }, - }, - BGAlpha = BezierSpline { - KeyFrames = { - [0] = { 0.25, Flags = { Linear = true } }, - [1] = { 0.75, Flags = { Linear = true } }, - }, - }, - }, - Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, -}"#; - let comp = Comp::from_fusion_str(comp_src).expect("parse alpha ProRes comp"); - let target = comp.find_node("BG").expect("find BG"); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - - let out_mov = tmp_dir.join("alpha_4444.mov"); - let summary = export_node_video_ffmpeg( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: out_mov.clone(), - range: [0, 1], - codec: VideoCodec::ProRes4444, - crf: 26, - max_height: None, - include_audio: false, - hiq: true, - proxy_scale: 1, - }, - |_| {}, - ) - .expect("export ProRes 4444"); - assert_eq!(summary.frames_written, 2); - assert_eq!(summary.width, 64); - assert_eq!(summary.height, 36); - - let probe = Command::new("ffprobe") - .args([ - "-v", - "error", - "-show_entries", - "stream=codec_name,profile,pix_fmt", - "-of", - "csv=p=0", - ]) - .arg(&out_mov) - .output() - .expect("run ffprobe"); - assert!(probe.status.success()); - let probe_out = String::from_utf8_lossy(&probe.stdout); - assert!( - probe_out.contains("prores") && probe_out.contains("4444") && probe_out.contains("yuva"), - "expected ProRes 4444 with alpha pixel format, got: {probe_out}" - ); - - let dec = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(&out_mov) - .args(["-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1"]) - .output() - .expect("decode ProRes 4444 to rgba"); - assert!(dec.status.success()); - let frame_bytes = 64 * 36 * 4; - assert_eq!(dec.stdout.len(), frame_bytes * 2); - - let a0 = dec.stdout[3]; - let a1 = dec.stdout[frame_bytes + 3]; - assert!( - (i32::from(a0) - 64).abs() <= 2, - "frame 0 alpha should be ~64 (0.25), got {a0}" - ); - assert!( - (i32::from(a1) - 191).abs() <= 2, - "frame 1 alpha should be ~191 (0.75), got {a1}" - ); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - #[test] - fn prores_422_and_software_fallback_encoders_produce_valid_streams() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-prores422-fallback-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); - - let comp_src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 2 }, - GlobalRange = { 0, 2 }, - Tools = ordered() { - BG = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 36, }, - TopLeftRed = Input { Value = 0.2, }, - TopLeftGreen = Input { Value = 0.7, }, - TopLeftBlue = Input { Value = 0.3, }, - TopLeftAlpha = Input { Value = 1.0, }, - }, - }, - }, - Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, -}"#; - let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); - let target = comp.find_node("BG").expect("find BG"); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - - let prores422_mov = tmp_dir.join("prores422.mov"); - let summary_422 = export_node_video_ffmpeg( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: prores422_mov.clone(), - range: [0, 2], - codec: VideoCodec::ProRes422, - crf: 26, - max_height: None, - include_audio: false, - hiq: true, - proxy_scale: 1, - }, - |_| {}, - ) - .expect("export ProRes 422"); - assert_eq!(summary_422.frames_written, 3); - - let probe_422 = Command::new("ffprobe") - .args(["-v", "error", "-count_frames", "-show_entries", "stream=codec_name,profile,nb_read_frames", "-of", "csv=p=0"]) - .arg(&prores422_mov) - .output() - .expect("ffprobe prores 422"); - assert!(probe_422.status.success()); - let out_422 = String::from_utf8_lossy(&probe_422.stdout); - assert!( - out_422.contains("prores") && out_422.contains("Standard") && out_422.contains(",3"), - "expected ProRes 422 Standard with 3 frames, got: {out_422}" - ); - - // Directly verify software fallback encoders (Libx264 and ProResKs422) - let sw_mp4 = tmp_dir.join("sw_libx264.mp4"); - let mut noop = |_| {}; - let sw_summary = export_node_video_ffmpeg_with_encoder( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: sw_mp4.clone(), - range: [0, 2], - codec: VideoCodec::H264Share, - crf: 26, - max_height: None, - include_audio: false, - hiq: true, - proxy_scale: 1, - }, - None, - &mut noop, - VideoEncoder::Libx264, - Instant::now(), - ) - .expect("software libx264 fallback export"); - assert_eq!(sw_summary.frames_written, 3); - assert!(sw_mp4.exists()); - - let sw_mov = tmp_dir.join("sw_prores_ks.mov"); - let sw_prores = export_node_video_ffmpeg_with_encoder( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: sw_mov.clone(), - range: [0, 2], - codec: VideoCodec::ProRes422, - crf: 26, - max_height: None, - include_audio: false, - hiq: true, - proxy_scale: 1, - }, - None, - &mut noop, - VideoEncoder::ProResKs422, - Instant::now(), - ) - .expect("software prores_ks fallback export"); - assert_eq!(sw_prores.frames_written, 3); - assert!(sw_mov.exists()); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } - - #[test] - fn h264_max_height_out_width_matches_ffmpeg_scale_neg2_rounding() { - // 101x100 with max_height >= 100: scale=-2 rounds 101.0/2 = 50.5 -> 51 * 2 = 102 - let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(100)); - assert_eq!((w, h), (102, 100)); - let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(200)); - assert_eq!((w, h), (102, 100)); - let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(50)); - assert_eq!((w, h), (50, 50)); - - // 1000x750 downscaled: 1000*700/750 = 933.33 -> nearest even 934; 1000*400/750 = 533.33 -> 534; 1000*500/750 = 666.67 -> 666 - let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(700)); - assert_eq!((w, h), (934, 700)); - let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(400)); - assert_eq!((w, h), (534, 400)); - let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(500)); - assert_eq!((w, h), (666, 500)); - let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(750)); - assert_eq!((w, h), (1000, 750)); - - // Without max_height, trunc(iw/2)*2:trunc(ih/2)*2 truncates odd dimensions downward - let (_, w, h) = h264_scale_filter_and_dims(101, 100, None); - assert_eq!((w, h), (100, 100)); - } - - #[test] - fn video_export_cancel_on_final_frame_progress_cancels_cleanly() { - let tmp_dir = std::env::temp_dir().join(format!( - "fission-video-cancel-final-{}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); - - let comp_src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 2 }, - GlobalRange = { 0, 2 }, - Tools = ordered() { - BG = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 36, }, - TopLeftRed = Input { Value = 0.5, }, - TopLeftAlpha = Input { Value = 1, }, - }, - }, - }, - Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, -}"#; - let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); - let target = comp.find_node("BG").expect("find BG"); - let mut engine = Engine::new_headless().expect("headless wgpu engine"); - let out_mp4 = tmp_dir.join("final_cancel.mp4"); - let control = ExportControl::new(); - let ctrl_cb = control.clone(); - - let err = export_node_video_ffmpeg_with_progress( - &mut engine, - &comp, - &VideoExportOptions { - target, - out_path: out_mp4.clone(), - range: [0, 2], - codec: VideoCodec::H264Share, - crf: 26, - max_height: None, - include_audio: false, - hiq: true, - proxy_scale: 1, - }, - Some(&control), - |p| { - if p.completed_frames == p.total_frames { - ctrl_cb.cancel(); - } - }, - ) - .expect_err("cancelling on final frame callback must return Cancelled"); - assert_eq!(err, "Cancelled"); - assert!(!out_mp4.exists(), "cancelled export must not publish output file"); - - let _ = std::fs::remove_dir_all(&tmp_dir); - } -} diff --git a/crates/engine/src/export/png.rs b/crates/engine/src/export/png.rs new file mode 100644 index 0000000000000000000000000000000000000000..625051f9717d7e0144e9d22ea29d28f2da8ce650 --- /dev/null +++ b/crates/engine/src/export/png.rs @@ -0,0 +1,442 @@ +//! Lossless RGBA8 PNG encoding and pipelined multi-threaded PNG sequence export. + +use super::{ + ExportControl, ExportOptions, ExportProgress, ExportSummary, make_progress, select_saver, +}; +use crate::cache::EvalStats; +use crate::eval::Engine; +use model::{Comp, NodeId, SaverSpec}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::Instant; + +fn resolve_output_path( + saver: &SaverSpec, + frame: i64, + out_dir_override: Option<&Path>, +) -> Result { + if saver.filename.is_empty() { + let dir = out_dir_override.ok_or_else(|| { + format!( + "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)", + saver.name + ) + })?; + return Ok(dir.join(format!("{frame:04}.png"))); + } + let frame_path = saver.frame_path(frame); + if let Some(dir) = out_dir_override { + let fname = frame_path + .file_name() + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.png"))); + Ok(dir.join(fname)) + } else { + Ok(frame_path) + } +} + +/// Encodes an RGBA8 image into `out` as a lossless PNG matching Fusion's default +/// libpng compression (`Compression::Balanced` = zlib level 6 + `Filter::Adaptive`). +pub fn encode_png_rgba8_into(size: [u32; 2], pixels: &[u8], out: &mut Vec) -> Result<(), String> { + out.clear(); + if out.capacity() == 0 { + out.reserve(pixels.len() / 2); + } + let mut enc = ::png::Encoder::new(&mut *out, size[0], size[1]); + enc.set_color(::png::ColorType::Rgba); + enc.set_depth(::png::BitDepth::Eight); + enc.set_compression(::png::Compression::Balanced); + enc.set_filter(::png::Filter::Adaptive); + let mut png_w = enc + .write_header() + .map_err(|e| format!("failed to write PNG header: {e}"))?; + png_w + .write_image_data(pixels) + .map_err(|e| format!("failed to write PNG data: {e}"))?; + Ok(()) +} + +/// Encodes and writes an RGBA8 PNG using a reusable staging buffer and cached parent directory. +pub fn write_png_fast_buffered( + path: &Path, + size: [u32; 2], + pixels: &[u8], + staging: &mut Vec, + last_parent: &mut Option, +) -> Result<(), String> { + if let Some(parent) = path.parent() { + if !parent.as_os_str().is_empty() && last_parent.as_deref() != Some(parent) { + std::fs::create_dir_all(parent) + .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; + *last_parent = Some(parent.to_path_buf()); + } + } + encode_png_rgba8_into(size, pixels, staging) + .map_err(|e| format!("{e} ('{}')", path.display()))?; + std::fs::write(path, staging.as_slice()) + .map_err(|e| format!("failed to write '{}': {e}", path.display()))?; + Ok(()) +} + +fn write_png_fast(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), String> { + let mut staging = Vec::with_capacity(pixels.len() / 2); + let mut last_parent = None; + write_png_fast_buffered(path, size, pixels, &mut staging, &mut last_parent) +} + +struct EncodeJob { + path: PathBuf, + size: [u32; 2], + pixels: Vec, +} + +/// Evaluates `target` at `frame` on GPU and saves a single RGBA8 PNG to `out_path`. +pub fn export_node_frame_png( + engine: &mut Engine, + comp: &Comp, + target: NodeId, + frame: f64, + out_path: &Path, +) -> Result { + if target.0 >= comp.nodes.len() { + return Err(format!("invalid target node id {}", target.0)); + } + let (tex, _) = engine.evaluate(comp, target, frame); + let pixels = engine + .readback_rgba(&tex) + .map_err(|e| format!("GPU readback failed at frame {frame}: {e}"))?; + write_png_fast(out_path, tex.size, &pixels)?; + Ok(out_path.to_path_buf()) +} + +/// Renders and writes a PNG sequence for an arbitrary `target` node across `range` +/// (`[start, end]` inclusive) using double-buffered async GPU readback, recycled RGBA +/// pixel buffers, 12-frame media prefetch, and a bounded background PNG encoder pool. +#[allow(clippy::too_many_arguments)] +pub fn export_node_png_sequence_with_progress( + engine: &mut Engine, + comp: &Comp, + target: NodeId, + range: [i64; 2], + path_for_frame: impl Fn(i64) -> Result, + label: String, + hiq: bool, + proxy_scale: u32, + png_workers: usize, + control: Option<&ExportControl>, + mut on_progress: impl FnMut(&ExportProgress), +) -> Result { + if control.is_some_and(ExportControl::is_cancelled) { + return Err("Cancelled".to_owned()); + } + if target.0 >= comp.nodes.len() { + return Err(format!("invalid target node id {}", target.0)); + } + let [start, end] = range; + let total_i128 = i128::from(end) - i128::from(start) + 1; + if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { + return Err(format!("invalid export frame range {start}..={end}")); + } + + let prev_hiq = engine.hiq; + let prev_proxy = engine.proxy_scale; + engine.hiq = hiq; + engine.proxy_scale = proxy_scale.max(1); + + let total = total_i128 as usize; + let workers = if png_workers > 0 { + png_workers.clamp(1, 24) + } else { + std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 24)) + .unwrap_or(4) + } + .min(total.max(1)); + + let t0 = Instant::now(); + let mut first_path: Option = None; + let mut last_path: Option = None; + let mut frames_written: usize = 0; + + let first_err: Arc>> = Arc::new(Mutex::new(None)); + let failed = Arc::new(AtomicBool::new(false)); + let cancelled = Arc::new(AtomicBool::new(false)); + + let eval_result: Result<(), String> = std::thread::scope(|scope| { + let queue_cap = (workers * 2).clamp(16, 48); + let (tx, rx) = mpsc::sync_channel::(queue_cap); + let (recycle_tx, recycle_rx) = mpsc::sync_channel::>(queue_cap + workers); + let shared_rx = Arc::new(Mutex::new(rx)); + + let mut handles = Vec::with_capacity(workers); + for _ in 0..workers { + let rx_c = Arc::clone(&shared_rx); + let recycle_c = recycle_tx.clone(); + let err_c = Arc::clone(&first_err); + let fail_c = Arc::clone(&failed); + let cancel_c = Arc::clone(&cancelled); + handles.push(scope.spawn(move || { + let mut staging = Vec::new(); + let mut last_parent: Option = None; + loop { + let job = { + let Ok(guard) = rx_c.lock() else { break }; + guard.recv() + }; + let Ok(job) = job else { break }; + if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) { + continue; + } + if let Err(e) = write_png_fast_buffered( + &job.path, + job.size, + &job.pixels, + &mut staging, + &mut last_parent, + ) { + if let Ok(mut g) = err_c.lock() { + if g.is_none() { + *g = Some(e); + } + } + fail_c.store(true, Ordering::Release); + } + let _ = recycle_c.try_send(job.pixels); + } + })); + } + drop(recycle_tx); + + let mut loop_err: Option = None; + const PREFETCH_LOOKAHEAD: usize = 12; + engine.prewarm_for_depth(comp.depth_full); + let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); + if start < end { + let seed_start = start.saturating_add(1); + let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end); + for (k, f) in (seed_start..=seed_end).enumerate() { + prefetch.enqueue_frame( + comp, + target, + k + 1, + f as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } + } + // Double-buffered async GPU readback: frame N+1 evaluates/submits on GPU while + // frame N finishes its copy/map and hands off to the background PNG writer pool. + let mut pending: Option<( + crate::eval::PendingReadback, + i64, + usize, + PathBuf, + [u32; 2], + EvalStats, + )> = None; + for (idx, frame) in (start..=end).enumerate() { + if failed.load(Ordering::Acquire) { + break; + } + if control.is_some_and(ExportControl::is_cancelled) { + cancelled.store(true, Ordering::Release); + break; + } + prefetch.set_current_seq(idx); + if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) { + if ahead_frame <= end { + prefetch.enqueue_frame( + comp, + target, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } + } + let out_path = match path_for_frame(frame) { + Ok(p) => p, + Err(e) => { + loop_err = Some(e); + break; + } + }; + + let (tex, stats) = engine.evaluate(comp, target, frame as f64); + let next_rb = match engine.begin_readback_rgba(&tex) { + Ok(rb) => rb, + Err(e) => { + loop_err = Some(format!("GPU readback failed at frame {frame}: {e}")); + break; + } + }; + if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_stats)) = + pending.replace((next_rb, frame, idx, out_path, tex.size, stats)) + { + let mut pixels = recycle_rx.try_recv().unwrap_or_default(); + if let Err(e) = prev_rb.finish_into(engine, &mut pixels) { + loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); + break; + } + if control.is_some_and(ExportControl::is_cancelled) { + cancelled.store(true, Ordering::Release); + break; + } + if first_path.is_none() { + first_path = Some(prev_path.clone()); + } + last_path = Some(prev_path.clone()); + let prog = make_progress( + prev_frame, + prev_idx, + total, + prev_stats, + prev_path.clone(), + label.clone(), + t0, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); + } + on_progress(&prog); + if tx + .send(EncodeJob { + path: prev_path, + size: prev_size, + pixels, + }) + .is_err() + { + break; + } + frames_written += 1; + } + } + if loop_err.is_none() && !failed.load(Ordering::Acquire) && !cancelled.load(Ordering::Acquire) + { + if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_stats)) = + pending.take() + { + let mut pixels = recycle_rx.try_recv().unwrap_or_default(); + match prev_rb.finish_into(engine, &mut pixels) { + Ok(()) => { + if control.is_some_and(ExportControl::is_cancelled) { + cancelled.store(true, Ordering::Release); + } else { + if first_path.is_none() { + first_path = Some(prev_path.clone()); + } + last_path = Some(prev_path.clone()); + let prog = make_progress( + prev_frame, + prev_idx, + total, + prev_stats, + prev_path.clone(), + label.clone(), + t0, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); + } + on_progress(&prog); + if tx + .send(EncodeJob { + path: prev_path, + size: prev_size, + pixels, + }) + .is_ok() + { + frames_written += 1; + } + } + } + Err(e) => { + loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); + } + } + } + } + + drop(prefetch); + drop(tx); + for h in handles { + let _ = h.join(); + } + + if let Some(e) = loop_err { + return Err(e); + } + if let Ok(mut g) = first_err.lock() { + if let Some(e) = g.take() { + return Err(e); + } + } + if cancelled.load(Ordering::Acquire) { + return Err("Cancelled".to_owned()); + } + Ok(()) + }); + + engine.hiq = prev_hiq; + engine.proxy_scale = prev_proxy; + + eval_result?; + + Ok(ExportSummary { + saver_name: label, + frames_written, + total_ms: t0.elapsed().as_secs_f64() * 1000.0, + first_path, + last_path, + }) +} + +/// Renders and writes a PNG sequence driven by a Fusion `Saver` node. +/// +/// GPU evaluation runs on the caller's thread while PNG compression and disk I/O run +/// concurrently on a bounded pool of background worker threads. +pub fn export_saver_png_sequence( + engine: &mut Engine, + comp: &Comp, + opts: &ExportOptions, + on_progress: impl FnMut(&ExportProgress), +) -> Result { + export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress) +} + +/// Renders and writes a PNG sequence driven by a Fusion `Saver` node with cooperative +/// cancellation and live progress reporting via `ExportControl`. +pub fn export_saver_png_sequence_with_progress( + engine: &mut Engine, + comp: &Comp, + opts: &ExportOptions, + control: Option<&ExportControl>, + on_progress: impl FnMut(&ExportProgress), +) -> Result { + if control.is_some_and(ExportControl::is_cancelled) { + return Err("Cancelled".to_owned()); + } + let saver = select_saver(comp, opts.saver_name.as_deref())?; + let target: NodeId = saver.upstream.unwrap_or(saver.node_id); + let range = opts.range_override.unwrap_or(saver.range); + let out_dir_override = opts.out_dir_override.as_deref(); + export_node_png_sequence_with_progress( + engine, + comp, + target, + range, + |frame| resolve_output_path(&saver, frame, out_dir_override), + saver.name.clone(), + opts.hiq, + opts.proxy_scale, + opts.png_workers, + control, + on_progress, + ) +} diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..ec0d5abf8864fc921a9925219438756b4a9fa54e --- /dev/null +++ b/crates/engine/src/export/tests.rs @@ -0,0 +1,1286 @@ +use super::video::{ + VideoEncoder, VideoToolboxSupport, export_node_video_ffmpeg_with_encoder, fit_frame_rgba, + h264_scale_filter_and_dims, parse_videotoolbox_encoders, push_video_encoder_args, + select_video_encoder, vt_quality_from_crf, +}; +use super::*; +use crate::eval::Engine; +use model::Comp; +use std::path::Path; +use std::process::Command; +use std::time::Instant; + +#[test] +fn exports_saver_png_sequence_animated() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-saver-export-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + let saver_path = tmp_dir.join("nested").join("shot_0000.png"); + let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); + + let comp_src = format!( + r#"Composition {{ + CurrentTime = 10, + RenderRange = {{ 10, 12 }}, + GlobalRange = {{ 0, 100 }}, + Tools = ordered() {{ + BG = Background {{ + Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 32, }}, + TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, + TopLeftGreen = Input {{ Value = 0.25, }}, + TopLeftBlue = Input {{ Value = 0.5, }}, + TopLeftAlpha = Input {{ Value = 1, }}, + }}, + }}, + BGRed = BezierSpline {{ + KeyFrames = {{ + [10] = {{ 0.0, Flags = {{ Linear = true }} }}, + [12] = {{ 1.0, Flags = {{ Linear = true }} }}, + }}, + }}, + Saver1 = Saver {{ + Inputs = {{ + Clip = Input {{ + Value = Clip {{ + Filename = "{saver_path_escaped}", + FormatID = "PNGFormat", + Saving = true, + }}, + }}, + Input = Input {{ + SourceOp = "BG", + Source = "Output", + }}, + }}, + }}, + }}, + Prefs = {{ + Comp = {{ + FrameFormat = {{ + Width = 64, + Height = 32, + Rate = 30, + DepthFull = 1, + }}, + }}, + }}, +}}"# + ); + + let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let mut seen_frames = Vec::new(); + let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |p| { + seen_frames.push(p.frame); + }) + .expect("export png sequence"); + + assert_eq!(summary.saver_name, "Saver1"); + assert_eq!(summary.frames_written, 3); + assert_eq!(seen_frames, vec![10, 11, 12]); + + let expected_reds = [0u8, 128u8, 255u8]; + for (frame, exp_r) in [10i64, 11, 12].into_iter().zip(expected_reds) { + let p = tmp_dir.join("nested").join(format!("shot_{frame:04}.png")); + assert!(p.exists(), "missing exported frame {}", p.display()); + let img = image::open(&p).expect("decode exported PNG").to_rgba8(); + assert_eq!(img.dimensions(), (64, 32)); + let px = img.get_pixel(32, 16); + assert!( + (px[0] as i32 - exp_r as i32).abs() <= 2, + "frame {frame}: expected R~{exp_r}, got {:?}", + px.0 + ); + assert!((px[1] as i32 - 64).abs() <= 2); + assert!((px[2] as i32 - 128).abs() <= 2); + assert_eq!(px[3], 255); + } + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn exports_node_png_sequence_directly_with_eval_stats() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-node-png-seq-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + + let comp_src = r#"Composition { + CurrentTime = 5, + RenderRange = { 5, 7 }, + GlobalRange = { 0, 100 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 32, }, + TopLeftRed = Input { Value = 0.5, }, + TopLeftGreen = Input { Value = 0.25, }, + TopLeftBlue = Input { Value = 0.75, }, + TopLeftAlpha = Input { Value = 1, }, + }, + }, + }, + Prefs = { Comp = { FrameFormat = { Width = 64, Height = 32, Rate = 24, DepthFull = 1 } } }, +}"#; + + let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic comp"); + let target = comp.find_node("BG").expect("find BG"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let mut seen = Vec::new(); + let summary = export_node_png_sequence_with_progress( + &mut engine, + &comp, + target, + [5, 7], + |f| Ok(tmp_dir.join(format!("{f:04}.png"))), + "BG".to_owned(), + true, + 1, + 0, + None, + |p| { + assert!(p.cached_vram_mb >= 0.0); + assert!(p.unsupported_nodes.is_empty()); + seen.push(p.frame); + }, + ) + .expect("export node png sequence"); + + assert_eq!(summary.saver_name, "BG"); + assert_eq!(summary.frames_written, 3); + assert_eq!(seen, vec![5, 6, 7]); + assert_eq!(summary.first_path, Some(tmp_dir.join("0005.png"))); + assert_eq!(summary.last_path, Some(tmp_dir.join("0007.png"))); + for f in 5..=7 { + let p = tmp_dir.join(format!("{f:04}.png")); + assert!(p.exists(), "missing {}", p.display()); + } + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +fn write_test_wav(path: &Path, sample_rate: u32, duration_secs: f64) { + let num_channels: u16 = 2; + let bits_per_sample: u16 = 16; + let num_samples = (sample_rate as f64 * duration_secs) as u32; + let byte_rate = sample_rate * u32::from(num_channels) * u32::from(bits_per_sample) / 8; + let block_align = num_channels * bits_per_sample / 8; + let data_bytes = num_samples * u32::from(block_align); + let riff_chunk_size = 36 + data_bytes; + + let mut buf = Vec::with_capacity((44 + data_bytes) as usize); + buf.extend_from_slice(b"RIFF"); + buf.extend_from_slice(&riff_chunk_size.to_le_bytes()); + buf.extend_from_slice(b"WAVE"); + buf.extend_from_slice(b"fmt "); + buf.extend_from_slice(&16u32.to_le_bytes()); + buf.extend_from_slice(&1u16.to_le_bytes()); // PCM + buf.extend_from_slice(&num_channels.to_le_bytes()); + buf.extend_from_slice(&sample_rate.to_le_bytes()); + buf.extend_from_slice(&byte_rate.to_le_bytes()); + buf.extend_from_slice(&block_align.to_le_bytes()); + buf.extend_from_slice(&bits_per_sample.to_le_bytes()); + buf.extend_from_slice(b"data"); + buf.extend_from_slice(&data_bytes.to_le_bytes()); + for i in 0..num_samples { + let t = i as f64 / sample_rate as f64; + let sample = ((t * 440.0 * std::f64::consts::TAU).sin() * 12000.0) as i16; + buf.extend_from_slice(&sample.to_le_bytes()); + buf.extend_from_slice(&sample.to_le_bytes()); + } + std::fs::write(path, buf).expect("write synthetic wav"); +} + +#[test] +fn exports_snippet_mp4_with_synced_audio() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-video-export-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let wav_path = tmp_dir.join("tone.wav"); + write_test_wav(&wav_path, 44100, 2.0); + let wav_escaped = wav_path.to_string_lossy().replace('\\', "\\\\"); + + let comp_src = format!( + r#"Composition {{ + CurrentTime = 10, + RenderRange = {{ 10, 21 }}, + GlobalRange = {{ 0, 100 }}, + AudioFilename = "{wav_escaped}", + AudioOffset = 10, + Tools = ordered() {{ + BG = Background {{ + Inputs = {{ + Width = Input {{ Value = 128, }}, + Height = Input {{ Value = 72, }}, + TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, + TopLeftGreen = Input {{ Value = 0.25, }}, + TopLeftBlue = Input {{ Value = 0.75, }}, + TopLeftAlpha = Input {{ Value = 1, }}, + }}, + }}, + BGRed = BezierSpline {{ + KeyFrames = {{ + [10] = {{ 0.0, Flags = {{ Linear = true }} }}, + [21] = {{ 1.0, Flags = {{ Linear = true }} }}, + }}, + }}, + }}, + Prefs = {{ + Comp = {{ + FrameFormat = {{ + Width = 128, + Height = 72, + Rate = 30, + DepthFull = 1, + }}, + }}, + }}, +}}"# + ); + + let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic audio comp"); + let target = comp.find_node("BG").expect("find BG node"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let mp4_path = tmp_dir.join("snippet.mp4"); + let mut seen_frames = Vec::new(); + let summary = export_node_video_ffmpeg( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: mp4_path.clone(), + range: [10, 21], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: true, + hiq: true, + proxy_scale: 1, + }, + |p| seen_frames.push(p.frame), + ) + .expect("export snippet mp4"); + + assert_eq!(summary.frames_written, 12); + assert_eq!(summary.width, 128); + assert_eq!(summary.height, 72); + assert!(summary.has_audio); + assert!(summary.file_bytes > 0); + assert_eq!(seen_frames.len(), 12); + assert!(mp4_path.exists()); + + // Verify streams and exact video frame count via ffprobe + let probe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-count_frames", + "-show_entries", + "stream=codec_type,codec_name,nb_read_frames", + "-of", + "csv=p=0", + ]) + .arg(&mp4_path) + .output() + .expect("run ffprobe"); + assert!( + probe.status.success(), + "ffprobe failed: {}", + String::from_utf8_lossy(&probe.stderr) + ); + let stdout = String::from_utf8_lossy(&probe.stdout); + let mut saw_h264_12 = false; + let mut saw_aac = false; + for line in stdout.lines() { + let cols: Vec<&str> = line.split(',').map(str::trim).collect(); + if cols.len() >= 3 && cols[1] == "video" && cols[0] == "h264" && cols[2] == "12" { + saw_h264_12 = true; + } + if cols.len() >= 2 && cols[1] == "audio" && cols[0] == "aac" { + saw_aac = true; + } + } + assert!( + saw_h264_12, + "expected h264 video stream with 12 frames, ffprobe output:\n{stdout}" + ); + assert!( + saw_aac, + "expected aac audio stream, ffprobe output:\n{stdout}" + ); + + // Also verify negative audio_start_secs (range starts before AudioOffset = 10) + let pre_mp4_path = tmp_dir.join("snippet_pre_offset.mp4"); + let pre_summary = export_node_video_ffmpeg( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: pre_mp4_path.clone(), + range: [6, 17], + codec: VideoCodec::H264Share, + crf: 26, + max_height: Some(64), + include_audio: true, + hiq: true, + proxy_scale: 1, + }, + |_| {}, + ) + .expect("export snippet mp4 with negative audio_start_secs"); + assert_eq!(pre_summary.frames_written, 12); + assert!(pre_summary.has_audio); + assert!(pre_summary.file_bytes > 0); + assert!(pre_mp4_path.exists()); + + // Verify single-frame PNG helper + let png_path = tmp_dir.join("frame_10.png"); + let saved = export_node_frame_png(&mut engine, &comp, target, 10.0, &png_path) + .expect("export single frame png"); + assert_eq!(saved, png_path); + let img = image::open(&png_path) + .expect("decode exported frame png") + .to_rgba8(); + assert_eq!(img.dimensions(), (128, 72)); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn saver_export_reports_progress_and_stops_on_cancel() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-saver-cancel-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + let saver_path = tmp_dir.join("shot_0000.png"); + let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); + + let comp_src = format!( + r#"Composition {{ + CurrentTime = 10, + RenderRange = {{ 10, 15 }}, + GlobalRange = {{ 0, 100 }}, + Tools = ordered() {{ + BG = Background {{ + Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 32, }}, + TopLeftRed = Input {{ Value = 0.7, }}, + TopLeftAlpha = Input {{ Value = 1, }}, + }}, + }}, + Saver1 = Saver {{ + Inputs = {{ + Clip = Input {{ + Value = Clip {{ + Filename = "{saver_path_escaped}", + FormatID = "PNGFormat", + Saving = true, + }}, + }}, + Input = Input {{ + SourceOp = "BG", + Source = "Output", + }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 1 }} }} }}, +}}"# + ); + + let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + let control = ExportControl::new(); + let ctrl_cb = control.clone(); + let mut reported = Vec::new(); + + let err = export_saver_png_sequence_with_progress( + &mut engine, + &comp, + &ExportOptions::default(), + Some(&control), + |p| { + reported.push(( + p.current_frame, + p.completed_frames, + p.total_frames, + p.label.clone(), + )); + if p.completed_frames >= 2 { + ctrl_cb.cancel(); + } + }, + ) + .expect_err("saver export should cancel early"); + + assert_eq!(err, "Cancelled"); + assert_eq!(reported.len(), 2); + assert_eq!(reported[0].0, 10); + assert_eq!(reported[0].1, 1); + assert_eq!(reported[0].2, 6); + assert_eq!(reported[0].3, "Saver1"); + assert_eq!(reported[1].0, 11); + assert_eq!(reported[1].1, 2); + + let snap = control.snapshot_progress(); + assert_eq!(snap.completed_frames, 2); + assert_eq!(snap.total_frames, 6); + assert!(snap.elapsed_secs >= 0.0); + assert!(!tmp_dir.join("shot_0015.png").exists()); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn video_export_reports_progress_and_cleans_up_on_cancel() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-video-cancel-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let comp_src = r#"Composition { + CurrentTime = 1, + RenderRange = { 1, 12 }, + GlobalRange = { 0, 100 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 72, }, + TopLeftRed = Input { Value = 0.2, }, + TopLeftGreen = Input { Value = 0.6, }, + TopLeftBlue = Input { Value = 0.9, }, + TopLeftAlpha = Input { Value = 1, }, + }, + }, + }, + Prefs = { Comp = { FrameFormat = { Width = 128, Height = 72, Rate = 24, DepthFull = 1 } } }, +}"#; + + let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic video comp"); + let target = comp.find_node("BG").expect("find BG node"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + let out_mp4 = tmp_dir.join("cancelled.mp4"); + let control = ExportControl::new(); + let ctrl_cb = control.clone(); + let mut seen = Vec::new(); + + let err = export_node_video_ffmpeg_with_progress( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: out_mp4.clone(), + range: [1, 12], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + Some(&control), + |p| { + seen.push(( + p.current_frame, + p.completed_frames, + p.total_frames, + p.label.clone(), + )); + if p.completed_frames >= 3 { + ctrl_cb.cancel(); + } + }, + ) + .expect_err("video export should cancel early"); + + assert_eq!(err, "Cancelled"); + assert_eq!(seen.len(), 3); + assert_eq!(seen[0].0, 1); + assert_eq!(seen[0].1, 1); + assert_eq!(seen[0].2, 12); + assert_eq!(seen[0].3, "BG"); + assert_eq!(seen[2].0, 3); + assert_eq!(seen[2].1, 3); + + let snap = control.snapshot_progress(); + assert_eq!(snap.completed_frames, 3); + assert_eq!(snap.total_frames, 12); + assert!( + !out_mp4.exists(), + "partial mp4 should be removed after cancellation" + ); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn video_export_handles_short_audio_past_eof_odd_dims_and_1x1_dummy() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-video-edge-cases-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let short_wav = tmp_dir.join("short.wav"); + write_test_wav(&short_wav, 44100, 0.15); + let wav_escaped = short_wav.to_string_lossy().replace('\\', "\\\\"); + + // 1. Short audio (0.15s) with 1.0s (24 frames @ 24fps) odd-dimension (127x71) video. + let comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 23 }}, + GlobalRange = {{ 0, 23 }}, + AudioFilename = "{wav_escaped}", + AudioOffset = 0, + Tools = ordered() {{ + BG = Background {{ + Inputs = {{ + Width = Input {{ Value = 127, }}, + Height = Input {{ Value = 71, }}, + TopLeftRed = Input {{ Value = 0.4, }}, + TopLeftGreen = Input {{ Value = 0.5, }}, + TopLeftBlue = Input {{ Value = 0.6, }}, + TopLeftAlpha = Input {{ Value = 1, }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = 127, Height = 71, Rate = 24, DepthFull = 1 }} }} }}, +}}"# + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse odd+short-audio comp"); + let target = comp.find_node("BG").unwrap(); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let short_mp4 = tmp_dir.join("short_audio_odd.mp4"); + let summary = export_node_video_ffmpeg( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: short_mp4.clone(), + range: [0, 23], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: true, + hiq: true, + proxy_scale: 1, + }, + |_| {}, + ) + .expect("export with short audio and odd dimensions should succeed without Broken pipe"); + assert_eq!(summary.frames_written, 24); + assert_eq!(summary.width, 126); + assert_eq!(summary.height, 70); + assert!(summary.has_audio); + + // 2. Audio start past EOF -> skips audio cleanly (`has_audio == false`). + let mut past_eof_comp = comp.clone(); + past_eof_comp.audio_offset = -100.0; // start=0 -> audio_start_secs = +4.17s > 0.15s + let past_mp4 = tmp_dir.join("past_eof.mp4"); + let past_summary = export_node_video_ffmpeg( + &mut engine, + &past_eof_comp, + &VideoExportOptions { + target, + out_path: past_mp4.clone(), + range: [0, 5], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: true, + hiq: true, + proxy_scale: 1, + }, + |_| {}, + ) + .expect("export with audio past EOF should skip audio and succeed"); + assert_eq!(past_summary.frames_written, 6); + assert!(!past_summary.has_audio); + + // 3. First frame 1x1 dummy (Loader with missing frame 0, MissingFrames = 0) -> falls back to comp canvas. + let seq1 = tmp_dir.join("seq_0001.png"); + image::RgbaImage::from_pixel(64, 36, image::Rgba([20, 200, 40, 255])) + .save(&seq1) + .unwrap(); + let seq0 = tmp_dir.join("seq_0000.png"); // intentionally absent + let seq0_esc = seq0.to_string_lossy().replace('\\', "\\\\"); + let dummy_comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 1 }}, + GlobalRange = {{ 0, 1 }}, + Tools = ordered() {{ + LD = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{seq0_esc}", + FormatID = "PNGFormat", + StartFrame = 0, + Length = 2, + GlobalStart = 0, + GlobalEnd = 1, + }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 36, Rate = 24, DepthFull = 1 }} }} }}, +}}"# + ); + let dummy_comp = Comp::from_fusion_str(&dummy_comp_src).expect("parse dummy loader comp"); + let ld = dummy_comp.find_node("LD").unwrap(); + engine.bust_all_caches(); + let dummy_mp4 = tmp_dir.join("dummy_first.mp4"); + let dummy_summary = export_node_video_ffmpeg( + &mut engine, + &dummy_comp, + &VideoExportOptions { + target: ld, + out_path: dummy_mp4.clone(), + range: [0, 1], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + |_| {}, + ) + .expect("export with 1x1 first frame should fall back to comp dimensions"); + assert_eq!(dummy_summary.frames_written, 2); + assert_eq!(dummy_summary.width, 64); + assert_eq!(dummy_summary.height, 36); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn video_export_cancel_preserves_existing_output_and_removes_temp_file() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-video-atomic-cancel-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let out_mp4 = tmp_dir.join("existing.mp4"); + let sentinel_bytes = b"ORIGINAL_VALUABLE_EXPORT_BYTES_DO_NOT_TRUNCATE"; + std::fs::write(&out_mp4, sentinel_bytes).expect("write sentinel existing file"); + + let comp_src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 9 }, + GlobalRange = { 0, 9 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.8, }, + TopLeftAlpha = Input { Value = 1, }, + }, + }, + }, + Prefs = { Comp = { FrameFormat = { Width = 64, Height = 64, Rate = 24, DepthFull = 1 } } }, +}"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let target = comp.find_node("BG").expect("find BG"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + let control = ExportControl::new(); + let ctrl_cb = control.clone(); + + let err = export_node_video_ffmpeg_with_progress( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: out_mp4.clone(), + range: [0, 9], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + Some(&control), + |p| { + if p.completed_frames >= 2 { + ctrl_cb.cancel(); + } + }, + ) + .expect_err("cancelled export should return Err"); + assert_eq!(err, "Cancelled"); + + let after_bytes = std::fs::read(&out_mp4).expect("existing output must still exist"); + assert_eq!( + after_bytes.as_slice(), + sentinel_bytes, + "existing file must stay untouched" + ); + + let entries: Vec<_> = std::fs::read_dir(&tmp_dir) + .expect("read tmp_dir") + .filter_map(|e| e.ok()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!( + entries, + vec!["existing.mp4".to_owned()], + "no temp files should remain" + ); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn pipelined_png_export_is_pixel_exact_and_propagates_write_errors() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-png-pipeline-exact-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let saver_path = tmp_dir.join("out").join("frame_0000.png"); + let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); + let comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 5 }}, + GlobalRange = {{ 0, 5 }}, + Tools = ordered() {{ + BG = Background {{ + Inputs = {{ + Width = Input {{ Value = 96, }}, + Height = Input {{ Value = 48, }}, + TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, + TopLeftGreen = Input {{ Value = 0.5, }}, + TopLeftBlue = Input {{ Value = 0.25, }}, + TopLeftAlpha = Input {{ Value = 1.0, }}, + }}, + }}, + BGRed = BezierSpline {{ + KeyFrames = {{ + [0] = {{ 0.1, Flags = {{ Linear = true }} }}, + [5] = {{ 0.9, Flags = {{ Linear = true }} }}, + }}, + }}, + Saver1 = Saver {{ + Inputs = {{ + Clip = Input {{ + Value = Clip {{ + Filename = "{saver_path_escaped}", + FormatID = "PNGFormat", + Saving = true, + }}, + }}, + Input = Input {{ SourceOp = "BG", Source = "Output", }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = 96, Height = 48, Rate = 24, DepthFull = 1 }} }} }}, +}}"# + ); + + let comp = Comp::from_fusion_str(&comp_src).expect("parse comp"); + let target = comp.find_node("BG").unwrap(); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |_| {}) + .expect("export png sequence"); + assert_eq!(summary.frames_written, 6); + + // Verify fast-compressed PNGs decode byte-identically to direct GPU readback. + for f in 0..=5 { + let (tex, _) = engine.evaluate(&comp, target, f as f64); + let expected = engine.readback_rgba(&tex).expect("readback"); + let png_path = tmp_dir.join("out").join(format!("frame_{f:04}.png")); + let decoded = image::open(&png_path).expect("decode png").to_rgba8(); + assert_eq!(decoded.dimensions(), (tex.size[0], tex.size[1])); + assert_eq!( + decoded.into_raw(), + expected, + "fast PNG encode must be 100% lossless at frame {f}" + ); + } + + // Verify worker write error propagates cleanly: point out_dir_override inside a regular file. + let blocking_file = tmp_dir.join("not_a_dir"); + std::fs::write(&blocking_file, b"file").expect("write blocking file"); + let err = export_saver_png_sequence( + &mut engine, + &comp, + &ExportOptions { + out_dir_override: Some(blocking_file), + ..ExportOptions::default() + }, + |_| {}, + ) + .expect_err("writing into a regular file path must return Err"); + assert!(!err.is_empty()); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn videotoolbox_probe_selection_and_fallback() { + let sample_both = "\ +Encoders: + V..... = Video + ------ + V....D libx264 libx264 H.264 / AVC + V....D h264_videotoolbox VideoToolbox H.264 Encoder (codec h264) + VFS... prores_ks Apple ProRes (iCodec Pro) (codec prores) + V....D prores_videotoolbox VideoToolbox ProRes Encoder (codec prores) + A....D aac AAC (Advanced Audio Coding) +"; + let vt_both = parse_videotoolbox_encoders(sample_both); + assert_eq!( + vt_both, + VideoToolboxSupport { + h264: true, + prores: true + } + ); + + let sample_h264_only = " V....D h264_videotoolbox VideoToolbox H.264 Encoder\n"; + assert_eq!( + parse_videotoolbox_encoders(sample_h264_only), + VideoToolboxSupport { + h264: true, + prores: false + } + ); + assert_eq!( + parse_videotoolbox_encoders(" V....D libx264 H.264\n"), + VideoToolboxSupport::default() + ); + + // Hardware selection when supported and allowed + assert_eq!( + select_video_encoder(VideoCodec::H264Share, vt_both, true), + VideoEncoder::H264VideoToolbox + ); + assert_eq!( + select_video_encoder(VideoCodec::ProRes422, vt_both, true), + VideoEncoder::ProResVideoToolbox422 + ); + assert_eq!( + select_video_encoder(VideoCodec::ProRes4444, vt_both, true), + VideoEncoder::ProResVideoToolbox4444 + ); + + // Fallback when VideoToolbox is unavailable or disabled after failure + assert_eq!( + select_video_encoder(VideoCodec::H264Share, vt_both, false), + VideoEncoder::Libx264 + ); + assert_eq!( + select_video_encoder(VideoCodec::ProRes422, vt_both, false), + VideoEncoder::ProResKs422 + ); + assert_eq!( + select_video_encoder(VideoCodec::ProRes4444, vt_both, false), + VideoEncoder::ProResKs4444 + ); + assert_eq!( + select_video_encoder(VideoCodec::H264Share, VideoToolboxSupport::default(), true), + VideoEncoder::Libx264 + ); + + assert_eq!(vt_quality_from_crf(0), 95); + assert_eq!(vt_quality_from_crf(26), 52); + assert_eq!(vt_quality_from_crf(51), 15); + + let mut args = Vec::new(); + push_video_encoder_args( + &mut args, + VideoEncoder::H264VideoToolbox, + 26, + Some("scale=trunc(iw/2)*2:trunc(ih/2)*2"), + ); + assert!(args.windows(2).any(|w| w == ["-c:v", "h264_videotoolbox"])); + assert!(args.windows(2).any(|w| w == ["-q:v", "52"])); + assert!(args.windows(2).any(|w| w == ["-tag:v", "avc1"])); + assert!(args.windows(2).any(|w| w == ["-pix_fmt", "yuv420p"])); + + args.clear(); + push_video_encoder_args( + &mut args, + VideoEncoder::Libx264, + 26, + Some("scale=trunc(iw/2)*2:trunc(ih/2)*2"), + ); + assert!(args.windows(2).any(|w| w == ["-c:v", "libx264"])); + assert!(args.windows(2).any(|w| w == ["-crf", "26"])); + + args.clear(); + push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox422, 26, None); + assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"])); + assert!(args.windows(2).any(|w| w == ["-profile:v", "2"])); + assert!(args.windows(2).any(|w| w == ["-pix_fmt", "p210le"])); + + args.clear(); + push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox4444, 26, None); + assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"])); + assert!(args.windows(2).any(|w| w == ["-profile:v", "4"])); + assert!(args.windows(2).any(|w| w == ["-pix_fmt", "ayuv64le"])); +} + +#[test] +fn fit_frame_rgba_zero_copy_fast_path_and_resize() { + let pixels = vec![128u8; 8 * 4 * 4]; + let orig_ptr = pixels.as_ptr(); + let moved = fit_frame_rgba(pixels, [8, 4], [8, 4], 0).expect("matching size fast path"); + assert_eq!( + moved.as_ptr(), + orig_ptr, + "matching size must move Vec without copying" + ); + + let resized = fit_frame_rgba(moved, [8, 4], [4, 2], 1).expect("resize path"); + assert_eq!(resized.len(), 4 * 2 * 4); + + let err = fit_frame_rgba(vec![0u8; 10], [8, 4], [8, 4], 2) + .expect_err("mismatched RGBA byte length must fail"); + assert!(err.contains("invalid RGBA buffer size")); +} + +#[test] +fn prores_4444_preserves_alpha_channel() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-prores4444-alpha-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let comp_src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 36, }, + TopLeftRed = Input { Value = 0.8, }, + TopLeftGreen = Input { Value = 0.4, }, + TopLeftBlue = Input { Value = 0.2, }, + TopLeftAlpha = Input { SourceOp = "BGAlpha", Source = "Value", }, + }, + }, + BGAlpha = BezierSpline { + KeyFrames = { + [0] = { 0.25, Flags = { Linear = true } }, + [1] = { 0.75, Flags = { Linear = true } }, + }, + }, + }, + Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, +}"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse alpha ProRes comp"); + let target = comp.find_node("BG").expect("find BG"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let out_mov = tmp_dir.join("alpha_4444.mov"); + let summary = export_node_video_ffmpeg( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: out_mov.clone(), + range: [0, 1], + codec: VideoCodec::ProRes4444, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + |_| {}, + ) + .expect("export ProRes 4444"); + assert_eq!(summary.frames_written, 2); + assert_eq!(summary.width, 64); + assert_eq!(summary.height, 36); + + let probe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "stream=codec_name,profile,pix_fmt", + "-of", + "csv=p=0", + ]) + .arg(&out_mov) + .output() + .expect("run ffprobe"); + assert!(probe.status.success()); + let probe_out = String::from_utf8_lossy(&probe.stdout); + assert!( + probe_out.contains("prores") && probe_out.contains("4444") && probe_out.contains("yuva"), + "expected ProRes 4444 with alpha pixel format, got: {probe_out}" + ); + + let dec = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(&out_mov) + .args(["-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1"]) + .output() + .expect("decode ProRes 4444 to rgba"); + assert!(dec.status.success()); + let frame_bytes = 64 * 36 * 4; + assert_eq!(dec.stdout.len(), frame_bytes * 2); + + let a0 = dec.stdout[3]; + let a1 = dec.stdout[frame_bytes + 3]; + assert!( + (i32::from(a0) - 64).abs() <= 2, + "frame 0 alpha should be ~64 (0.25), got {a0}" + ); + assert!( + (i32::from(a1) - 191).abs() <= 2, + "frame 1 alpha should be ~191 (0.75), got {a1}" + ); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn prores_422_and_software_fallback_encoders_produce_valid_streams() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-prores422-fallback-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let comp_src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 2 }, + GlobalRange = { 0, 2 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 36, }, + TopLeftRed = Input { Value = 0.2, }, + TopLeftGreen = Input { Value = 0.7, }, + TopLeftBlue = Input { Value = 0.3, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + }, + Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, +}"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let target = comp.find_node("BG").expect("find BG"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + + let prores422_mov = tmp_dir.join("prores422.mov"); + let summary_422 = export_node_video_ffmpeg( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: prores422_mov.clone(), + range: [0, 2], + codec: VideoCodec::ProRes422, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + |_| {}, + ) + .expect("export ProRes 422"); + assert_eq!(summary_422.frames_written, 3); + + let probe_422 = Command::new("ffprobe") + .args([ + "-v", + "error", + "-count_frames", + "-show_entries", + "stream=codec_name,profile,nb_read_frames", + "-of", + "csv=p=0", + ]) + .arg(&prores422_mov) + .output() + .expect("ffprobe prores 422"); + assert!(probe_422.status.success()); + let out_422 = String::from_utf8_lossy(&probe_422.stdout); + assert!( + out_422.contains("prores") && out_422.contains("Standard") && out_422.contains(",3"), + "expected ProRes 422 Standard with 3 frames, got: {out_422}" + ); + + // Directly verify software fallback encoders (Libx264 and ProResKs422) + let sw_mp4 = tmp_dir.join("sw_libx264.mp4"); + let mut noop = |_| {}; + let sw_summary = export_node_video_ffmpeg_with_encoder( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: sw_mp4.clone(), + range: [0, 2], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + None, + &mut noop, + VideoEncoder::Libx264, + Instant::now(), + ) + .expect("software libx264 fallback export"); + assert_eq!(sw_summary.frames_written, 3); + assert!(sw_mp4.exists()); + + let sw_mov = tmp_dir.join("sw_prores_ks.mov"); + let sw_prores = export_node_video_ffmpeg_with_encoder( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: sw_mov.clone(), + range: [0, 2], + codec: VideoCodec::ProRes422, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + None, + &mut noop, + VideoEncoder::ProResKs422, + Instant::now(), + ) + .expect("software prores_ks fallback export"); + assert_eq!(sw_prores.frames_written, 3); + assert!(sw_mov.exists()); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn h264_max_height_out_width_matches_ffmpeg_scale_neg2_rounding() { + // 101x100 with max_height >= 100: scale=-2 rounds 101.0/2 = 50.5 -> 51 * 2 = 102 + let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(100)); + assert_eq!((w, h), (102, 100)); + let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(200)); + assert_eq!((w, h), (102, 100)); + let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(50)); + assert_eq!((w, h), (50, 50)); + + // 1000x750 downscaled: 1000*700/750 = 933.33 -> nearest even 934; 1000*400/750 = 533.33 -> 534; 1000*500/750 = 666.67 -> 666 + let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(700)); + assert_eq!((w, h), (934, 700)); + let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(400)); + assert_eq!((w, h), (534, 400)); + let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(500)); + assert_eq!((w, h), (666, 500)); + let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(750)); + assert_eq!((w, h), (1000, 750)); + + // Without max_height, trunc(iw/2)*2:trunc(ih/2)*2 truncates odd dimensions downward + let (_, w, h) = h264_scale_filter_and_dims(101, 100, None); + assert_eq!((w, h), (100, 100)); +} + +#[test] +fn video_export_cancel_on_final_frame_progress_cancels_cleanly() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-video-cancel-final-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let comp_src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 2 }, + GlobalRange = { 0, 2 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 36, }, + TopLeftRed = Input { Value = 0.5, }, + TopLeftAlpha = Input { Value = 1, }, + }, + }, + }, + Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, +}"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let target = comp.find_node("BG").expect("find BG"); + let mut engine = Engine::new_headless().expect("headless wgpu engine"); + let out_mp4 = tmp_dir.join("final_cancel.mp4"); + let control = ExportControl::new(); + let ctrl_cb = control.clone(); + + let err = export_node_video_ffmpeg_with_progress( + &mut engine, + &comp, + &VideoExportOptions { + target, + out_path: out_mp4.clone(), + range: [0, 2], + codec: VideoCodec::H264Share, + crf: 26, + max_height: None, + include_audio: false, + hiq: true, + proxy_scale: 1, + }, + Some(&control), + |p| { + if p.completed_frames == p.total_frames { + ctrl_cb.cancel(); + } + }, + ) + .expect_err("cancelling on final frame callback must return Cancelled"); + assert_eq!(err, "Cancelled"); + assert!( + !out_mp4.exists(), + "cancelled export must not publish output file" + ); + + let _ = std::fs::remove_dir_all(&tmp_dir); +} diff --git a/crates/engine/src/export/video.rs b/crates/engine/src/export/video.rs new file mode 100644 index 0000000000000000000000000000000000000000..2a530b985359e4dca162d12f991467de21bf82da --- /dev/null +++ b/crates/engine/src/export/video.rs @@ -0,0 +1,896 @@ +//! Piped `ffmpeg` video export with VideoToolbox hardware acceleration, automatic +//! software fallback, synced audio muxing, and atomic temp-file finalization. + +use super::{ + ExportControl, ExportProgress, VideoCodec, VideoExportOptions, VideoExportSummary, + make_progress, +}; +use crate::cache::EvalStats; +use crate::eval::Engine; +use model::Comp; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +#[cfg(target_os = "macos")] +use std::sync::OnceLock; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::Instant; + +/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames +/// directly into `ffmpeg`, and muxes synced comp audio when `opts.include_audio` is enabled. +pub fn export_node_video_ffmpeg( + engine: &mut Engine, + comp: &Comp, + opts: &VideoExportOptions, + on_progress: impl FnMut(ExportProgress), +) -> Result { + export_node_video_ffmpeg_with_progress(engine, comp, opts, None, on_progress) +} + +fn probe_audio_duration_secs(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-show_entries", + "stream=codec_type,duration", + "-show_entries", + "format=duration", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(path) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let text = String::from_utf8_lossy(&out.stdout); + let mut has_audio_stream = false; + let mut stream_dur: Option = None; + let mut format_dur: Option = None; + let mut in_stream = false; + for line in text.lines() { + let Some((k, v)) = line.split_once('=') else { + continue; + }; + let key = k.trim(); + let val = v.trim(); + match key { + "codec_type" => { + in_stream = true; + if val == "audio" { + has_audio_stream = true; + } + } + "duration" => { + if let Ok(d) = val.parse::() { + if d.is_finite() && d >= 0.0 { + if in_stream && stream_dur.is_none() { + stream_dur = Some(d); + } else if !in_stream && format_dur.is_none() { + format_dur = Some(d); + } + } + } + in_stream = false; + } + _ => {} + } + } + if !has_audio_stream { + return Some(0.0); + } + stream_dur.or(format_dur) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct VideoToolboxSupport { + pub(super) h264: bool, + pub(super) prores: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum VideoEncoder { + Libx264, + H264VideoToolbox, + ProResKs422, + ProResVideoToolbox422, + ProResKs4444, + ProResVideoToolbox4444, +} + +impl VideoEncoder { + fn is_hardware_accelerated(self) -> bool { + matches!( + self, + Self::H264VideoToolbox | Self::ProResVideoToolbox422 | Self::ProResVideoToolbox4444 + ) + } +} + +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub(super) fn parse_videotoolbox_encoders(encoders_stdout: &str) -> VideoToolboxSupport { + let mut support = VideoToolboxSupport::default(); + for line in encoders_stdout.lines() { + let mut parts = line.split_whitespace(); + let Some(flags) = parts.next() else { + continue; + }; + if !flags.starts_with('V') { + continue; + } + let Some(name) = parts.next() else { + continue; + }; + match name { + "h264_videotoolbox" => support.h264 = true, + "prores_videotoolbox" => support.prores = true, + _ => {} + } + } + support +} + +#[cfg(target_os = "macos")] +fn probe_videotoolbox_support() -> VideoToolboxSupport { + static VT_SUPPORT: OnceLock = OnceLock::new(); + *VT_SUPPORT.get_or_init(|| { + let Ok(out) = Command::new("ffmpeg") + .args(["-hide_banner", "-encoders"]) + .output() + else { + return VideoToolboxSupport::default(); + }; + if !out.status.success() { + return VideoToolboxSupport::default(); + } + let text = String::from_utf8_lossy(&out.stdout); + parse_videotoolbox_encoders(&text) + }) +} + +#[cfg(not(target_os = "macos"))] +fn probe_videotoolbox_support() -> VideoToolboxSupport { + VideoToolboxSupport::default() +} + +pub(super) fn select_video_encoder( + codec: VideoCodec, + vt: VideoToolboxSupport, + allow_videotoolbox: bool, +) -> VideoEncoder { + match codec { + VideoCodec::H264Share => { + if allow_videotoolbox && vt.h264 { + VideoEncoder::H264VideoToolbox + } else { + VideoEncoder::Libx264 + } + } + VideoCodec::ProRes422 => { + if allow_videotoolbox && vt.prores { + VideoEncoder::ProResVideoToolbox422 + } else { + VideoEncoder::ProResKs422 + } + } + VideoCodec::ProRes4444 => { + if allow_videotoolbox && vt.prores { + VideoEncoder::ProResVideoToolbox4444 + } else { + VideoEncoder::ProResKs4444 + } + } + } +} + +/// Maps x264-style CRF (`0..=51`, lower = higher quality) to VideoToolbox `-q:v` (`15..=95`, higher = higher quality). +pub(super) fn vt_quality_from_crf(crf: u8) -> u8 { + (104 - i32::from(crf) * 2).clamp(15, 95) as u8 +} + +pub(super) fn push_video_encoder_args( + args: &mut Vec, + encoder: VideoEncoder, + crf: u8, + vf: Option<&str>, +) { + match encoder { + VideoEncoder::H264VideoToolbox => { + if let Some(vf) = vf { + args.extend(["-vf".to_owned(), vf.to_owned()]); + } + args.extend([ + "-c:v".to_owned(), + "h264_videotoolbox".to_owned(), + "-q:v".to_owned(), + vt_quality_from_crf(crf).to_string(), + "-pix_fmt".to_owned(), + "yuv420p".to_owned(), + "-tag:v".to_owned(), + "avc1".to_owned(), + "-movflags".to_owned(), + "+faststart".to_owned(), + ]); + } + VideoEncoder::Libx264 => { + if let Some(vf) = vf { + args.extend(["-vf".to_owned(), vf.to_owned()]); + } + args.extend([ + "-c:v".to_owned(), + "libx264".to_owned(), + "-preset".to_owned(), + "medium".to_owned(), + "-crf".to_owned(), + crf.to_string(), + "-pix_fmt".to_owned(), + "yuv420p".to_owned(), + "-movflags".to_owned(), + "+faststart".to_owned(), + ]); + } + VideoEncoder::ProResVideoToolbox422 => { + args.extend([ + "-c:v".to_owned(), + "prores_videotoolbox".to_owned(), + "-profile:v".to_owned(), + "2".to_owned(), + "-pix_fmt".to_owned(), + "p210le".to_owned(), + ]); + } + VideoEncoder::ProResKs422 => { + args.extend([ + "-c:v".to_owned(), + "prores_ks".to_owned(), + "-profile:v".to_owned(), + "2".to_owned(), + "-pix_fmt".to_owned(), + "yuv422p10le".to_owned(), + ]); + } + VideoEncoder::ProResVideoToolbox4444 => { + args.extend([ + "-c:v".to_owned(), + "prores_videotoolbox".to_owned(), + "-profile:v".to_owned(), + "4".to_owned(), + "-pix_fmt".to_owned(), + "ayuv64le".to_owned(), + ]); + } + VideoEncoder::ProResKs4444 => { + args.extend([ + "-c:v".to_owned(), + "prores_ks".to_owned(), + "-profile:v".to_owned(), + "4".to_owned(), + "-pix_fmt".to_owned(), + "yuva444p10le".to_owned(), + ]); + } + } +} + +pub(super) fn fit_frame_rgba( + pixels: Vec, + src_size: [u32; 2], + dst_size: [u32; 2], + frame: i64, +) -> Result, String> { + let expected_len = (src_size[0] as usize) + .checked_mul(src_size[1] as usize) + .and_then(|px| px.checked_mul(4)) + .ok_or_else(|| format!("frame {frame} dimensions overflow buffer size"))?; + if pixels.len() != expected_len { + return Err(format!( + "invalid RGBA buffer size at frame {frame}: expected {expected_len}, got {}", + pixels.len() + )); + } + if src_size == dst_size { + return Ok(pixels); + } + let img = image::RgbaImage::from_raw(src_size[0], src_size[1], pixels) + .ok_or_else(|| format!("invalid RGBA buffer size at frame {frame}"))?; + Ok(image::imageops::resize( + &img, + dst_size[0], + dst_size[1], + image::imageops::FilterType::Triangle, + ) + .into_raw()) +} + +static EXPORT_TMP_SEQ: AtomicU64 = AtomicU64::new(0); + +fn sibling_temp_export_path(out_path: &Path) -> PathBuf { + let seq = EXPORT_TMP_SEQ.fetch_add(1, Ordering::Relaxed); + let pid = std::process::id(); + let stem = out_path + .file_stem() + .and_then(|s| s.to_str()) + .filter(|s| !s.is_empty()) + .unwrap_or("export"); + let file_name = match out_path + .extension() + .and_then(|e| e.to_str()) + .filter(|e| !e.is_empty()) + { + Some(ext) => format!("{stem}.fission_tmp_{pid}_{seq}.{ext}"), + None => format!("{stem}.fission_tmp_{pid}_{seq}"), + }; + out_path.with_file_name(file_name) +} + +struct TempExportGuard { + path: PathBuf, + active: bool, +} + +impl TempExportGuard { + fn new(path: PathBuf) -> Self { + Self { path, active: true } + } + + fn disarm(&mut self) { + self.active = false; + } +} + +impl Drop for TempExportGuard { + fn drop(&mut self) { + if self.active { + let _ = std::fs::remove_file(&self.path); + } + } +} + +#[derive(Debug)] +pub(super) enum VideoExportError { + Cancelled, + Fatal(String), + EncoderFailed(String), +} + +impl VideoExportError { + fn into_string(self) -> String { + match self { + Self::Cancelled => "Cancelled".to_owned(), + Self::Fatal(s) | Self::EncoderFailed(s) => s, + } + } +} + +pub(super) fn h264_scale_filter_and_dims( + width: u32, + height: u32, + max_height: Option, +) -> (String, u32, u32) { + if let Some(max_h) = max_height.filter(|&h| h >= 2) { + let oh = (height.min(max_h) & !1).max(2); + let ow = + ((((width as f64) * (oh as f64) / (height as f64)) / 2.0).round() as u32 * 2).max(2); + (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh) + } else { + let ow = (width & !1).max(2); + let oh = (height & !1).max(2); + ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh) + } +} + +/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames +/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`. +pub fn export_node_video_ffmpeg_with_progress( + engine: &mut Engine, + comp: &Comp, + opts: &VideoExportOptions, + control: Option<&ExportControl>, + mut on_progress: impl FnMut(ExportProgress), +) -> Result { + if control.is_some_and(ExportControl::is_cancelled) { + return Err("Cancelled".to_owned()); + } + let [start, end] = opts.range; + let total_i128 = i128::from(end) - i128::from(start) + 1; + if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { + return Err(format!("invalid export frame range {start}..={end}")); + } + if opts.target.0 >= comp.nodes.len() { + return Err(format!("invalid target node id {}", opts.target.0)); + } + if opts.out_path.as_os_str().is_empty() { + return Err("video export output path is empty".to_owned()); + } + if let Some(parent) = opts.out_path.parent() { + if !parent.as_os_str().is_empty() { + std::fs::create_dir_all(parent) + .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; + } + } + + let prev_hiq = engine.hiq; + let prev_proxy = engine.proxy_scale; + engine.hiq = opts.hiq; + engine.proxy_scale = opts.proxy_scale.max(1); + + let started_at = Instant::now(); + let vt = probe_videotoolbox_support(); + let encoder = select_video_encoder(opts.codec, vt, true); + let res = match export_node_video_ffmpeg_with_encoder( + engine, + comp, + opts, + control, + &mut on_progress, + encoder, + started_at, + ) { + Ok(summary) => Ok(summary), + Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => { + if control.is_some_and(ExportControl::is_cancelled) { + Err("Cancelled".to_owned()) + } else { + let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false); + export_node_video_ffmpeg_with_encoder( + engine, + comp, + opts, + control, + &mut on_progress, + fallback, + started_at, + ) + .map_err(VideoExportError::into_string) + } + } + Err(err) => Err(err.into_string()), + }; + + engine.hiq = prev_hiq; + engine.proxy_scale = prev_proxy; + res +} + +pub(super) fn export_node_video_ffmpeg_with_encoder( + engine: &mut Engine, + comp: &Comp, + opts: &VideoExportOptions, + control: Option<&ExportControl>, + on_progress: &mut impl FnMut(ExportProgress), + encoder: VideoEncoder, + started_at: Instant, +) -> Result { + let [start, end] = opts.range; + let total = (end - start + 1) as usize; + let fps = comp.fps.max(1.0); + let node_name = comp.node(opts.target).name.clone(); + + // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output. + engine.prewarm_for_depth(comp.depth_full); + let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64); + if first_tex.size[0] == 0 || first_tex.size[1] == 0 { + return Err(VideoExportError::Fatal(format!( + "target '{}' produced empty frame {}x{}", + node_name, first_tex.size[0], first_tex.size[1] + ))); + } + // If the first frame is a 1x1 dummy (e.g., missing Loader frame), fall back to comp + // canvas dimensions so ffmpeg never receives -s 1x1 and crashes scale=trunc(iw/2)*2. + let (width, height) = if first_tex.size[0] < 2 || first_tex.size[1] < 2 { + let ps = engine.proxy_scale.max(1); + let fw = (comp.width / ps).max(2); + let fh = (comp.height / ps).max(2); + if opts.codec == VideoCodec::H264Share { + (((fw + 1) & !1).max(2), ((fh + 1) & !1).max(2)) + } else { + (fw, fh) + } + } else { + (first_tex.size[0], first_tex.size[1]) + }; + let raw_first = engine + .readback_rgba(&first_tex) + .map_err(|e| VideoExportError::Fatal(format!("GPU readback failed at frame {start}: {e}")))?; + let first_pixels = fit_frame_rgba(raw_first, first_tex.size, [width, height], start) + .map_err(VideoExportError::Fatal)?; + if control.is_some_and(ExportControl::is_cancelled) { + return Err(VideoExportError::Cancelled); + } + + let duration_secs = total as f64 / fps; + let audio_start_secs = (start as f64 - comp.audio_offset) / fps; + let audio_path = if opts.include_audio { + comp.audio_filename + .as_deref() + .map(PathBuf::from) + .filter(|p| { + if p.as_os_str().is_empty() || !p.exists() || -audio_start_secs >= duration_secs { + return false; + } + if let Some(audio_dur) = probe_audio_duration_secs(p) { + if audio_dur <= 0.0 || audio_start_secs >= audio_dur { + return false; + } + } + true + }) + } else { + None + }; + let has_audio = audio_path.is_some(); + + let mut cmd = Command::new("ffmpeg"); + cmd.args(["-y", "-hide_banner", "-loglevel", "error"]); + cmd.args([ + "-f", + "rawvideo", + "-pix_fmt", + "rgba", + "-s", + &format!("{width}x{height}"), + "-r", + &format!("{fps:.6}"), + "-i", + "pipe:0", + ]); + + let audio_filter = if let Some(ap) = &audio_path { + if audio_start_secs >= 0.0 { + if audio_start_secs > 0.0 { + cmd.args(["-ss", &format!("{audio_start_secs:.6}")]); + } + cmd.arg("-i").arg(ap); + Some(format!( + "asetpts=PTS-STARTPTS,apad,atrim=0:{duration_secs:.6}" + )) + } else { + let delay_ms = (-audio_start_secs * 1000.0).max(0.0); + cmd.arg("-i").arg(ap); + Some(format!( + "adelay={delay_ms:.3}:all=1,apad,atrim=0:{duration_secs:.6},asetpts=PTS-STARTPTS" + )) + } + } else { + None + }; + + let (out_width, out_height) = match opts.codec { + VideoCodec::H264Share => { + let (vf, ow, oh) = h264_scale_filter_and_dims(width, height, opts.max_height); + let mut encoder_args = Vec::new(); + push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf)); + cmd.args(&encoder_args); + (ow, oh) + } + VideoCodec::ProRes422 | VideoCodec::ProRes4444 => { + let mut encoder_args = Vec::new(); + push_video_encoder_args(&mut encoder_args, encoder, opts.crf, None); + cmd.args(&encoder_args); + (width, height) + } + }; + + if let Some(af) = audio_filter { + cmd.args(["-map", "0:v:0", "-map", "1:a:0", "-af", &af]); + match opts.codec { + VideoCodec::H264Share => { + cmd.args(["-c:a", "aac", "-b:a", "128k"]); + } + VideoCodec::ProRes422 | VideoCodec::ProRes4444 => { + cmd.args(["-c:a", "pcm_s16le"]); + } + } + } else { + cmd.arg("-an"); + } + + let tmp_path = sibling_temp_export_path(&opts.out_path); + let mut tmp_guard = TempExportGuard::new(tmp_path.clone()); + cmd.arg(&tmp_path); + cmd.stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()); + + let mut child = cmd.spawn().map_err(|e| { + VideoExportError::Fatal(format!( + "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}" + )) + })?; + + let mut stderr_pipe = child.stderr.take(); + let stderr_thread = std::thread::spawn(move || { + let mut buf = String::new(); + if let Some(ref mut pipe) = stderr_pipe { + let _ = pipe.read_to_string(&mut buf); + } + buf + }); + + let mut readback_err: Option = None; + let mut pipe_err: Option = None; + let mut cancelled = false; + let writer_err: Arc>> = Arc::new(Mutex::new(None)); + let writer_failed = Arc::new(AtomicBool::new(false)); + let writer_fatal = Arc::new(AtomicBool::new(false)); + let Some(stdin) = child.stdin.take() else { + let _ = child.kill(); + let _ = child.wait(); + let _ = stderr_thread.join(); + return Err(VideoExportError::Fatal( + "failed to open ffmpeg stdin".to_owned(), + )); + }; + + let frame_bytes_len = (width as usize) + .saturating_mul(height as usize) + .saturating_mul(4) + .max(1); + let queue_cap = (128 * 1024 * 1024 / frame_bytes_len).clamp(4, 16); + let (tx, rx) = mpsc::sync_channel::<(i64, [u32; 2], Vec)>(queue_cap); + let (recycle_tx, recycle_rx) = mpsc::sync_channel::>(queue_cap + 2); + let writer_err_c = Arc::clone(&writer_err); + let writer_failed_c = Arc::clone(&writer_failed); + let writer_fatal_c = Arc::clone(&writer_fatal); + let dst_size = [width, height]; + let writer_thread = std::thread::spawn(move || { + let mut stdin = stdin; + while let Ok((frame, src_size, pixels)) = rx.recv() { + let frame_bytes = match fit_frame_rgba(pixels, src_size, dst_size, frame) { + Ok(bytes) => bytes, + Err(e) => { + if let Ok(mut g) = writer_err_c.lock() { + if g.is_none() { + *g = Some(e); + } + } + writer_fatal_c.store(true, Ordering::Release); + writer_failed_c.store(true, Ordering::Release); + break; + } + }; + // Each frame is already a contiguous RGBA buffer; write directly without an extra copy. + if let Err(e) = stdin.write_all(&frame_bytes) { + if let Ok(mut g) = writer_err_c.lock() { + if g.is_none() { + *g = Some(format!("failed writing frame {frame} to ffmpeg: {e}")); + } + } + writer_failed_c.store(true, Ordering::Release); + break; + } + let _ = recycle_tx.try_send(frame_bytes); + } + let _ = stdin.flush(); + }); + + if tx.send((start, [width, height], first_pixels)).is_err() { + pipe_err = writer_err + .lock() + .ok() + .and_then(|mut g| g.take()) + .or_else(|| Some(format!("failed writing frame {start} to ffmpeg"))); + } else { + let first_prog = make_progress( + start, + 0, + total, + first_stats, + opts.out_path.clone(), + node_name.clone(), + started_at, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&first_prog); + } + on_progress(first_prog); + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } else if start < end { + const PREFETCH_LOOKAHEAD: usize = 12; + let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); + let seed_start = start.saturating_add(1); + let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64).min(end); + for (k, f) in (seed_start..=seed_end).enumerate() { + prefetch.enqueue_frame( + comp, + opts.target, + k, + f as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } + let mut pending: Option<( + crate::eval::PendingReadback, + i64, + usize, + [u32; 2], + EvalStats, + )> = None; + for (idx, frame) in (seed_start..=end).enumerate() { + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + break; + } + if writer_failed.load(Ordering::Acquire) { + break; + } + prefetch.set_current_seq(idx); + if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) { + if ahead_frame <= end { + prefetch.enqueue_frame( + comp, + opts.target, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } + } + let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); + let next_rb = match engine.begin_readback_rgba(&tex) { + Ok(rb) => rb, + Err(e) => { + readback_err = Some(format!("GPU readback failed at frame {frame}: {e}")); + break; + } + }; + if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_stats)) = + pending.replace((next_rb, frame, idx, tex.size, stats)) + { + let mut pixels = recycle_rx.try_recv().unwrap_or_default(); + if let Err(e) = prev_rb.finish_into(engine, &mut pixels) { + readback_err = + Some(format!("GPU readback failed at frame {prev_frame}: {e}")); + break; + } + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + break; + } + if tx.send((prev_frame, prev_size, pixels)).is_err() { + break; + } + let prog = make_progress( + prev_frame, + prev_idx + 1, + total, + prev_stats, + opts.out_path.clone(), + node_name.clone(), + started_at, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); + } + on_progress(prog); + } + } + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } + if readback_err.is_none() + && pipe_err.is_none() + && !cancelled + && !writer_failed.load(Ordering::Acquire) + { + if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_stats)) = pending.take() + { + let mut pixels = recycle_rx.try_recv().unwrap_or_default(); + match prev_rb.finish_into(engine, &mut pixels) { + Ok(()) => { + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } else if tx.send((prev_frame, prev_size, pixels)).is_ok() { + let prog = make_progress( + prev_frame, + prev_idx + 1, + total, + prev_stats, + opts.out_path.clone(), + node_name.clone(), + started_at, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); + } + on_progress(prog); + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } + } + } + Err(e) => { + readback_err = + Some(format!("GPU readback failed at frame {prev_frame}: {e}")); + } + } + } + } + drop(prefetch); + } + } + drop(tx); + + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } + if cancelled + || readback_err.is_some() + || pipe_err.is_some() + || writer_failed.load(Ordering::Acquire) + { + // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately. + let _ = child.kill(); + } + let _ = writer_thread.join(); + if pipe_err.is_none() && !cancelled { + if let Ok(mut g) = writer_err.lock() { + pipe_err = g.take(); + } + } + if pipe_err.is_some() && !cancelled { + let _ = child.kill(); + } + let wait_res = child.wait(); + let stderr_text = stderr_thread.join().unwrap_or_default(); + let stderr_trim = stderr_text.trim(); + + if cancelled || control.is_some_and(ExportControl::is_cancelled) { + return Err(VideoExportError::Cancelled); + } + if let Some(err) = readback_err { + return Err(VideoExportError::Fatal(err)); + } + if let Some(err) = pipe_err { + if writer_fatal.load(Ordering::Acquire) { + return Err(VideoExportError::Fatal(err)); + } + return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() { + format!("{err} (ffmpeg: {stderr_trim})") + } else { + err + })); + } + let status = wait_res + .map_err(|e| VideoExportError::Fatal(format!("failed waiting on ffmpeg: {e}")))?; + if !status.success() { + if control.is_some_and(ExportControl::is_cancelled) { + return Err(VideoExportError::Cancelled); + } + return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() { + format!("ffmpeg exited with {status}") + } else { + format!("ffmpeg exited with {status}: {stderr_trim}") + })); + } + + std::fs::rename(&tmp_path, &opts.out_path).map_err(|e| { + VideoExportError::Fatal(format!( + "failed to finalize '{}': {e}", + opts.out_path.display() + )) + })?; + tmp_guard.disarm(); + + let file_bytes = std::fs::metadata(&opts.out_path) + .map(|m| m.len()) + .unwrap_or(0); + + Ok(VideoExportSummary { + out_path: opts.out_path.clone(), + frames_written: total, + width: out_width, + height: out_height, + has_audio, + total_ms: started_at.elapsed().as_secs_f64() * 1000.0, + file_bytes, + }) +} -- 2.54.1