diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index 07e7a704a60b6da94244eb42eea0a7f45714d874..28814c3867deb80bc4b021bb05e02702581abf87 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -497,7 +497,7 @@ fn main() -> Result<(), Box> { } if args.len() < 3 { eprintln!( - "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast] [--bench] [--profile]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --export [--saver ] [--range ..] [--out-dir ] [--proxy <1|2|4>] [--fast]\n render-check --export-mp4 [--node ] [--range ..] [--crf ] [--max-height ] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --export-prores [--node ] [--range ..] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --roundtrip \n render-check --suite [--fast]" + "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast] [--bench] [--profile]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --export [--saver ] [--range ..] [--out-dir ] [--proxy <1|2|4>] [--fast]\n render-check --export-mp4 [--node ] [--range ..] [--crf ] [--max-height ] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --export-prores [--prores-4444] [--node ] [--range ..] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --roundtrip \n render-check --suite [--fast]" ); std::process::exit(2); } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index b321d2c5193e808b23efe94f11f1665283115173..d2c72c9e9a10e3c1e7977f64e4a70dccbfbe7e81 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -5,10 +5,12 @@ use crate::eval::Engine; use model::{Comp, NodeId, SaverSpec}; -use std::io::{BufWriter, Read, Write}; +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; @@ -515,11 +517,11 @@ pub fn export_saver_png_sequence_with_progress( /// Output video codec profile for direct viewer / node ffmpeg export. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum VideoCodec { - /// H.264 (`libx264`, `yuv420p`, `-movflags +faststart`) for compact shareable MP4 snippets. + /// H.264 (`h264_videotoolbox` on macOS when available, `libx264` fallback, `yuv420p`, `-movflags +faststart`) for compact shareable MP4 snippets. H264Share, - /// Apple ProRes 422 (`prores_ks -profile:v 2 -pix_fmt yuv422p10le`). + /// Apple ProRes 422 (`prores_videotoolbox` on macOS when available, `prores_ks` fallback, `-profile:v 2`). ProRes422, - /// Apple ProRes 4444 with alpha (`prores_ks -profile:v 4 -pix_fmt yuva444p10le`). + /// Apple ProRes 4444 with alpha (`prores_videotoolbox` on macOS when available, `prores_ks` fallback, `-profile:v 4`). ProRes4444, } @@ -652,12 +654,207 @@ fn probe_audio_duration_secs(path: &Path) -> Option { 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); } @@ -712,6 +909,22 @@ impl Drop for TempExportGuard { } } +#[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, + } + } +} + /// 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( @@ -746,422 +959,441 @@ pub fn export_node_video_ffmpeg_with_progress( engine.hiq = opts.hiq; engine.proxy_scale = opts.proxy_scale.max(1); - let res = (|| -> Result { - let t0 = Instant::now(); - 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(format!( - "target '{}' produced empty frame {}x{}", - node_name, first_tex.size[0], first_tex.size[1] - )); + 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, + ) { + Ok(summary) => Ok(summary), + Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => { + let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false); + export_node_video_ffmpeg_with_encoder( + engine, + comp, + opts, + control, + &mut on_progress, + fallback, + ) + .map_err(VideoExportError::into_string) } - // 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) - } + 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, +) -> Result { + let [start, end] = opts.range; + let t0 = Instant::now(); + 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 { - (first_tex.size[0], first_tex.size[1]) - }; - let raw_first = engine - .readback_rgba(&first_tex) - .map_err(|e| format!("GPU readback failed at frame {start}: {e}"))?; - let first_pixels = fit_frame_rgba(raw_first, first_tex.size, [width, height], start)?; - if control.is_some_and(ExportControl::is_cancelled) { - return Err("Cancelled".to_owned()); + (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 { + 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; } - 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" - )) + 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 { - None - }; + 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) = if let Some(max_h) = opts.max_height.filter(|&h| h >= 2) { - let oh = (height.min(max_h) & !1).max(2); - let ow = if height > max_h { - let scaled = ((width as f64) * (oh as f64) / (height as f64)).round() as u32; - (scaled & !1).max(2) - } else { - (width & !1).max(2) - }; - (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh) + let (out_width, out_height) = match opts.codec { + VideoCodec::H264Share => { + let (vf, ow, oh) = if let Some(max_h) = opts.max_height.filter(|&h| h >= 2) { + let oh = (height.min(max_h) & !1).max(2); + let ow = if height > max_h { + let scaled = ((width as f64) * (oh as f64) / (height as f64)).round() as u32; + (scaled & !1).max(2) } 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) + (width & !1).max(2) }; - cmd.args([ - "-vf", - &vf, - "-c:v", - "libx264", - "-preset", - "medium", - "-crf", - &opts.crf.to_string(), - "-pix_fmt", - "yuv420p", - "-movflags", - "+faststart", - ]); - (ow, oh) - } - VideoCodec::ProRes422 => { - cmd.args([ - "-c:v", - "prores_ks", - "-profile:v", - "2", - "-pix_fmt", - "yuv422p10le", - ]); - (width, height) - } - VideoCodec::ProRes4444 => { - cmd.args([ - "-c:v", - "prores_ks", - "-profile:v", - "4", - "-pix_fmt", - "yuva444p10le", - ]); - (width, height) - } - }; + (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) + }; + 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"]); - } + 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"); } + } 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 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| format!("failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}"))?; + let mut child = cmd.spawn().map_err(|e| { + VideoExportError::EncoderFailed(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 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 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 stdin = child - .stdin - .take() - .ok_or_else(|| "failed to open ffmpeg stdin".to_owned())?; + 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 stdin = child + .stdin + .take() + .ok_or_else(|| VideoExportError::EncoderFailed("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 writer_err_c = Arc::clone(&writer_err); - let writer_failed_c = Arc::clone(&writer_failed); - let dst_size = [width, height]; - let writer_thread = std::thread::spawn(move || { - let mut stdin = BufWriter::with_capacity(4 * 1024 * 1024, 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_failed_c.store(true, Ordering::Release); - break; - } - }; - if let Err(e) = stdin.write_all(&frame_bytes) { + 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 writer_err_c = Arc::clone(&writer_err); + let writer_failed_c = Arc::clone(&writer_failed); + 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(format!("failed writing frame {frame} to ffmpeg: {e}")); + *g = Some(e); } } 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 _ = stdin.flush(); - }); + } + 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(), - t0, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&first_prog); + 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(), + t0, + ); + 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_end = (start + PREFETCH_LOOKAHEAD as i64).min(end); + for (k, f) in ((start + 1)..=seed_end).enumerate() { + prefetch.enqueue_frame( + comp, + opts.target, + k, + f as f64, + &engine.expr, + engine.use_proxy_clips, + ); } - 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_end = (start + PREFETCH_LOOKAHEAD as i64).min(end); - for (k, f) in ((start + 1)..=seed_end).enumerate() { + let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None; + for (idx, frame) in ((start + 1)..=end).enumerate() { + if writer_failed.load(Ordering::Acquire) { + break; + } + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + break; + } + prefetch.set_current_seq(idx); + let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; + if ahead_frame <= end { prefetch.enqueue_frame( comp, opts.target, - k, - f as f64, + idx + PREFETCH_LOOKAHEAD, + ahead_frame 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 ((start + 1)..=end).enumerate() { - if writer_failed.load(Ordering::Acquire) { + 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 pixels = match prev_rb.finish(engine) { + Ok(px) => px, + Err(e) => { + readback_err = + Some(format!("GPU readback failed at frame {prev_frame}: {e}")); + break; + } + }; if control.is_some_and(ExportControl::is_cancelled) { cancelled = true; break; } - prefetch.set_current_seq(idx); - let ahead_frame = frame + 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, - ); + if tx.send((prev_frame, prev_size, pixels)).is_err() { + break; } - 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) => { - pipe_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 pixels = match prev_rb.finish(engine) { - Ok(px) => px, - Err(e) => { - pipe_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(), - t0, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); - } - on_progress(prog); + let prog = make_progress( + prev_frame, + prev_idx + 1, + total, + prev_ms, + opts.out_path.clone(), + node_name.clone(), + t0, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); } + on_progress(prog); } - if 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() { - match prev_rb.finish(engine) { - Ok(pixels) => { - 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(), - t0, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); - } - on_progress(prog); + } + 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() { + match prev_rb.finish(engine) { + Ok(pixels) => { + 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(), + t0, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); } + on_progress(prog); } - Err(e) => { - pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); - } + } + Err(e) => { + readback_err = + Some(format!("GPU readback failed at frame {prev_frame}: {e}")); } } } - drop(prefetch); } + drop(prefetch); } - drop(tx); + } + drop(tx); - if cancelled || 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 status = child - .wait() - .map_err(|e| format!("failed waiting on ffmpeg: {e}"))?; - let stderr_text = stderr_thread.join().unwrap_or_default(); - let stderr_trim = stderr_text.trim(); - - if cancelled { - return Err("Cancelled".to_owned()); - } - if let Some(err) = pipe_err { - if !stderr_trim.is_empty() { - return Err(format!("{err} (ffmpeg: {stderr_trim})")); - } - return Err(err); - } - if !status.success() { - return Err(if stderr_trim.is_empty() { - format!("ffmpeg exited with {status}") - } else { - format!("ffmpeg exited with {status}: {stderr_trim}") - }); + 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 status = child + .wait() + .map_err(|e| VideoExportError::EncoderFailed(format!("failed waiting on ffmpeg: {e}")))?; + let stderr_text = stderr_thread.join().unwrap_or_default(); + let stderr_trim = stderr_text.trim(); - std::fs::rename(&tmp_path, &opts.out_path) - .map_err(|e| format!("failed to finalize '{}': {e}", opts.out_path.display()))?; - tmp_guard.disarm(); + if cancelled { + return Err(VideoExportError::Cancelled); + } + if let Some(err) = readback_err { + return Err(VideoExportError::Fatal(err)); + } + if let Some(err) = pipe_err { + return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() { + format!("{err} (ffmpeg: {stderr_trim})") + } else { + err + })); + } + if !status.success() { + return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() { + format!("ffmpeg exited with {status}") + } else { + format!("ffmpeg exited with {status}: {stderr_trim}") + })); + } - let file_bytes = std::fs::metadata(&opts.out_path) - .map(|m| m.len()) - .unwrap_or(0); + 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(); - Ok(VideoExportSummary { - out_path: opts.out_path.clone(), - frames_written: total, - width: out_width, - height: out_height, - has_audio, - total_ms: t0.elapsed().as_secs_f64() * 1000.0, - file_bytes, - }) - })(); + let file_bytes = std::fs::metadata(&opts.out_path) + .map(|m| m.len()) + .unwrap_or(0); - engine.hiq = prev_hiq; - engine.proxy_scale = prev_proxy; - res + Ok(VideoExportSummary { + out_path: opts.out_path.clone(), + frames_written: total, + width: out_width, + height: out_height, + has_audio, + total_ms: t0.elapsed().as_secs_f64() * 1000.0, + file_bytes, + }) } #[cfg(test)] @@ -1917,4 +2149,321 @@ mod tests { 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, + ) + .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, + ) + .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); + } }