authoravatarclover caruso<git@paperclover.net>2026-12-01 22:01:25-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 22:07:29-08:00
log56052a3327a40509f74214405211941b01f80e37
tree71d2fe9058734bf9bbc4d784e4fafaa354aa6ae6
parentd030c95f46cc2ba3c53447e31f9b327fa8684e3e
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

refactor(engine): split export.rs into png/video/tests submodules and unify render-check PNG loop


5 files changed, 2679 insertions(+), 2567 deletions(-)

crates/engine/src/bin/render_check.rs+32-175
......@@ -1,13 +1,14 @@
11//! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`.
22
3use engine::export::{VideoCodec, VideoExportOptions, export_node_video_ffmpeg, write_png_fast_buffered};
3use engine::export::{
4 VideoCodec, VideoExportOptions, export_node_png_sequence_with_progress,
5 export_node_video_ffmpeg, write_png_fast_buffered,
6};
47use engine::media::default_media_cache_budget_mb;
58use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence};
69use model::Comp;
710use std::collections::HashMap;
811use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::{Arc, Mutex, mpsc};
1112use std::time::Instant;
1213
1314fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f64, f64, f64), Box<dyn std::error::Error>> {
......@@ -161,192 +162,48 @@ fn run_batch_render(
161162
162163 let total = (end - start + 1).max(0) as usize;
163164 let t_all = Instant::now();
165 let label = comp.node(target).name.clone();
164166 eprintln!(
165167 "Rendering {} ({}x{}, proxy 1:{}) node={} frames {}..{} ({total} frames) -> {}",
166168 comp.name,
167169 comp.width,
168170 comp.height,
169171 proxy_scale,
170 comp.node(target).name,
172 label,
171173 start,
172174 end,
173175 out_dir.display()
174176 );
175177
176178 if total > 0 {
177 struct RenderEncodeJob {
178 path: PathBuf,
179 size: [u32; 2],
180 pixels: Vec<u8>,
181 }
182 let workers = std::thread::available_parallelism()
183 .map(|n| n.get().clamp(2, 24))
184 .unwrap_or(4)
185 .min(total.max(1));
186 let queue_cap = (workers * 2).clamp(16, 48);
187 let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
188 let failed = Arc::new(AtomicBool::new(false));
189
190 std::thread::scope(|scope| -> Result<(), Box<dyn std::error::Error>> {
191 let (tx, rx) = mpsc::sync_channel::<RenderEncodeJob>(queue_cap);
192 let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + workers);
193 let shared_rx = Arc::new(Mutex::new(rx));
194 let mut handles = Vec::with_capacity(workers);
195 for _ in 0..workers {
196 let rx_c = Arc::clone(&shared_rx);
197 let recycle_c = recycle_tx.clone();
198 let err_c = Arc::clone(&first_err);
199 let fail_c = Arc::clone(&failed);
200 handles.push(scope.spawn(move || {
201 let mut staging = Vec::new();
202 let mut last_parent = Some(out_dir.to_path_buf());
203 loop {
204 let job = {
205 let Ok(guard) = rx_c.lock() else { break };
206 guard.recv()
207 };
208 let Ok(job) = job else { break };
209 if fail_c.load(Ordering::Acquire) {
210 continue;
211 }
212 if let Err(e) = write_png_fast_buffered(
213 &job.path,
214 job.size,
215 &job.pixels,
216 &mut staging,
217 &mut last_parent,
218 ) {
219 if let Ok(mut g) = err_c.lock() {
220 if g.is_none() {
221 *g = Some(e);
222 }
223 }
224 fail_c.store(true, Ordering::Release);
225 }
226 let _ = recycle_c.try_send(job.pixels);
227 }
228 }));
229 }
230 drop(recycle_tx);
231
232 let mut loop_err: Option<String> = None;
233 const PREFETCH_LOOKAHEAD: usize = 12;
234 engine.prewarm_for_depth(comp.depth_full);
235 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
236 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);
237 for (k, f) in ((start + 1)..=seed_end).enumerate() {
238 prefetch.enqueue_frame(
239 &comp,
240 target,
241 k + 1,
242 f as f64,
243 &engine.expr,
244 engine.use_proxy_clips,
245 );
246 }
247 let mut pending: Option<(engine::PendingReadback, i64, usize, [u32; 2], engine::EvalStats)> = None;
248 for (idx, f) in (start..=end).enumerate() {
249 if failed.load(Ordering::Acquire) {
250 break;
251 }
252 prefetch.set_current_seq(idx);
253 let ahead_frame = f + PREFETCH_LOOKAHEAD as i64;
254 if ahead_frame <= end {
255 prefetch.enqueue_frame(
256 &comp,
257 target,
258 idx + PREFETCH_LOOKAHEAD,
259 ahead_frame as f64,
260 &engine.expr,
261 engine.use_proxy_clips,
179 let hiq = engine.hiq;
180 export_node_png_sequence_with_progress(
181 &mut engine,
182 &comp,
183 target,
184 [start, end],
185 |f| Ok(out_dir.join(format!("{f:04}.png"))),
186 label,
187 hiq,
188 proxy_scale,
189 0,
190 None,
191 |p| {
192 if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total {
193 let elapsed = t_all.elapsed().as_secs_f64().max(1e-6);
194 let fps = (p.index + 1) as f64 / elapsed;
195 eprintln!(
196 " [{:>4}/{}] f{:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}",
197 p.index + 1,
198 p.total,
199 p.frame,
200 p.eval_ms,
201 p.cached_vram_mb,
202 p.unsupported_nodes,
262203 );
263204 }
264 let (tex, stats) = engine.evaluate(&comp, target, f as f64);
265 let next_rb = match engine.begin_readback_rgba(&tex) {
266 Ok(rb) => rb,
267 Err(e) => {
268 loop_err = Some(format!("GPU readback failed at frame {f}: {e}"));
269 break;
270 }
271 };
272 if let Some((prev_rb, prev_f, prev_idx, prev_size, prev_stats)) =
273 pending.replace((next_rb, f, idx, tex.size, stats))
274 {
275 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
276 if let Err(e) = prev_rb.finish_into(&engine, &mut pixels) {
277 loop_err = Some(format!("GPU readback failed at frame {prev_f}: {e}"));
278 break;
279 }
280 let out_file = out_dir.join(format!("{prev_f:04}.png"));
281 if tx
282 .send(RenderEncodeJob {
283 path: out_file,
284 size: prev_size,
285 pixels,
286 })
287 .is_err()
288 {
289 break;
290 }
291 if prev_idx == 0 || (prev_idx + 1) % 10 == 0 || prev_idx + 1 == total {
292 let elapsed = t_all.elapsed().as_secs_f64().max(1e-6);
293 let fps = (prev_idx + 1) as f64 / elapsed;
294 eprintln!(
295 " [{:>4}/{total}] f{prev_f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}",
296 prev_idx + 1,
297 prev_stats.eval_ms,
298 prev_stats.cached_vram_mb,
299 prev_stats.unsupported_nodes,
300 );
301 }
302 }
303 }
304 if loop_err.is_none() && !failed.load(Ordering::Acquire) {
305 if let Some((prev_rb, prev_f, prev_idx, prev_size, prev_stats)) = pending.take() {
306 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
307 match prev_rb.finish_into(&engine, &mut pixels) {
308 Ok(()) => {
309 let out_file = out_dir.join(format!("{prev_f:04}.png"));
310 let _ = tx.send(RenderEncodeJob {
311 path: out_file,
312 size: prev_size,
313 pixels,
314 });
315 if prev_idx == 0 || (prev_idx + 1) % 10 == 0 || prev_idx + 1 == total {
316 let elapsed = t_all.elapsed().as_secs_f64().max(1e-6);
317 let fps = (prev_idx + 1) as f64 / elapsed;
318 eprintln!(
319 " [{:>4}/{total}] f{prev_f:04} | eval={:.1}ms | avg={fps:.1} fps | vram={:.0}MB | unsupported={:?}",
320 prev_idx + 1,
321 prev_stats.eval_ms,
322 prev_stats.cached_vram_mb,
323 prev_stats.unsupported_nodes,
324 );
325 }
326 }
327 Err(e) => {
328 loop_err = Some(format!("GPU readback failed at frame {prev_f}: {e}"));
329 }
330 }
331 }
332 }
333
334 drop(prefetch);
335 drop(tx);
336 for h in handles {
337 let _ = h.join();
338 }
339
340 if let Some(e) = loop_err {
341 return Err(e.into());
342 }
343 if let Ok(mut g) = first_err.lock() {
344 if let Some(e) = g.take() {
345 return Err(e.into());
346 }
347 }
348 Ok(())
349 })?;
205 },
206 )?;
350207 }
351208 eprintln!(
352209 "Finished {total} frames in {:.2}s ({:.1} fps)",
crates/engine/src/export.rs+23-2392
......@@ -1,17 +1,24 @@
1//! Saver-driven pipelined PNG sequence export for `Engine`.
1//! Saver-driven pipelined PNG sequence export and ffmpeg video export for `Engine`.
22//!
33//! Evaluates frames on the GPU while encoding lossless RGBA8 PNG files concurrently
4//! across a bounded background worker pool, creating parent directories automatically.
4//! across a bounded background worker pool, or piping raw RGBA8 frames into `ffmpeg`.
55
6use crate::eval::Engine;
6mod png;
7#[cfg(test)]
8mod tests;
9mod video;
10
11pub use png::{
12 encode_png_rgba8_into, export_node_frame_png, export_node_png_sequence_with_progress,
13 export_saver_png_sequence, export_saver_png_sequence_with_progress, write_png_fast_buffered,
14};
15pub use video::{export_node_video_ffmpeg, export_node_video_ffmpeg_with_progress};
16
17use crate::cache::EvalStats;
718use model::{Comp, NodeId, SaverSpec};
8use std::io::{Read, Write};
9use std::path::{Path, PathBuf};
10use std::process::{Command, Stdio};
11use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
12#[cfg(target_os = "macos")]
13use std::sync::OnceLock;
14use std::sync::{Arc, Mutex, mpsc};
19use std::path::PathBuf;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::{Arc, Mutex};
1522use std::time::Instant;
1623
1724#[derive(Clone, Debug)]
......@@ -50,6 +57,8 @@ pub struct ExportProgress {
5057 pub index: usize,
5158 pub total: usize,
5259 pub eval_ms: f64,
60 pub cached_vram_mb: f64,
61 pub unsupported_nodes: Vec<String>,
5362 pub out_path: PathBuf,
5463 pub saver_name: String,
5564 pub current_frame: u32,
......@@ -113,7 +122,7 @@ fn make_progress(
113122 frame: i64,
114123 index: usize,
115124 total: usize,
116 eval_ms: f64,
125 stats: EvalStats,
117126 out_path: PathBuf,
118127 label: String,
119128 started_at: Instant,
......@@ -122,7 +131,9 @@ fn make_progress(
122131 frame,
123132 index,
124133 total,
125 eval_ms,
134 eval_ms: stats.eval_ms,
135 cached_vram_mb: stats.cached_vram_mb,
136 unsupported_nodes: stats.unsupported_nodes,
126137 out_path,
127138 saver_name: label.clone(),
128139 current_frame: frame.max(0) as u32,
......@@ -166,363 +177,6 @@ pub fn select_saver(comp: &Comp, saver_name: Option<&str>) -> Result<SaverSpec,
166177 Ok(savers[0].clone())
167178}
168179
169fn resolve_output_path(saver: &SaverSpec, frame: i64, out_dir_override: Option<&Path>) -> Result<PathBuf, String> {
170 if saver.filename.is_empty() {
171 let dir = out_dir_override.ok_or_else(|| {
172 format!(
173 "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)",
174 saver.name
175 )
176 })?;
177 return Ok(dir.join(format!("{frame:04}.png")));
178 }
179 let frame_path = saver.frame_path(frame);
180 if let Some(dir) = out_dir_override {
181 let fname = frame_path
182 .file_name()
183 .map(PathBuf::from)
184 .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.png")));
185 Ok(dir.join(fname))
186 } else {
187 Ok(frame_path)
188 }
189}
190
191/// Encodes an RGBA8 image into `out` as a lossless PNG matching Fusion's default
192/// libpng compression (`Compression::Balanced` = zlib level 6 + `Filter::Adaptive`).
193pub fn encode_png_rgba8_into(size: [u32; 2], pixels: &[u8], out: &mut Vec<u8>) -> Result<(), String> {
194 out.clear();
195 if out.capacity() == 0 {
196 out.reserve(pixels.len() / 2);
197 }
198 let mut enc = png::Encoder::new(&mut *out, size[0], size[1]);
199 enc.set_color(png::ColorType::Rgba);
200 enc.set_depth(png::BitDepth::Eight);
201 enc.set_compression(png::Compression::Balanced);
202 enc.set_filter(png::Filter::Adaptive);
203 let mut png_w = enc
204 .write_header()
205 .map_err(|e| format!("failed to write PNG header: {e}"))?;
206 png_w
207 .write_image_data(pixels)
208 .map_err(|e| format!("failed to write PNG data: {e}"))?;
209 Ok(())
210}
211
212/// Encodes and writes an RGBA8 PNG using a reusable staging buffer and cached parent directory.
213pub fn write_png_fast_buffered(
214 path: &Path,
215 size: [u32; 2],
216 pixels: &[u8],
217 staging: &mut Vec<u8>,
218 last_parent: &mut Option<PathBuf>,
219) -> Result<(), String> {
220 if let Some(parent) = path.parent() {
221 if !parent.as_os_str().is_empty() && last_parent.as_deref() != Some(parent) {
222 std::fs::create_dir_all(parent)
223 .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
224 *last_parent = Some(parent.to_path_buf());
225 }
226 }
227 encode_png_rgba8_into(size, pixels, staging)
228 .map_err(|e| format!("{e} ('{}')", path.display()))?;
229 std::fs::write(path, staging.as_slice())
230 .map_err(|e| format!("failed to write '{}': {e}", path.display()))?;
231 Ok(())
232}
233
234fn write_png_fast(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), String> {
235 let mut staging = Vec::with_capacity(pixels.len() / 2);
236 let mut last_parent = None;
237 write_png_fast_buffered(path, size, pixels, &mut staging, &mut last_parent)
238}
239
240struct EncodeJob {
241 path: PathBuf,
242 size: [u32; 2],
243 pixels: Vec<u8>,
244}
245
246/// Renders and writes a PNG sequence driven by a Fusion `Saver` node.
247///
248/// GPU evaluation runs on the caller's thread while PNG compression and disk I/O run
249/// concurrently on a bounded pool of background worker threads.
250pub fn export_saver_png_sequence(
251 engine: &mut Engine,
252 comp: &Comp,
253 opts: &ExportOptions,
254 on_progress: impl FnMut(&ExportProgress),
255) -> Result<ExportSummary, String> {
256 export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress)
257}
258
259/// Renders and writes a PNG sequence driven by a Fusion `Saver` node with cooperative
260/// cancellation and live progress reporting via `ExportControl`.
261pub fn export_saver_png_sequence_with_progress(
262 engine: &mut Engine,
263 comp: &Comp,
264 opts: &ExportOptions,
265 control: Option<&ExportControl>,
266 mut on_progress: impl FnMut(&ExportProgress),
267) -> Result<ExportSummary, String> {
268 if control.is_some_and(ExportControl::is_cancelled) {
269 return Err("Cancelled".to_owned());
270 }
271 let saver = select_saver(comp, opts.saver_name.as_deref())?;
272 let target: NodeId = saver.upstream.unwrap_or(saver.node_id);
273 let [start, end] = opts.range_override.unwrap_or(saver.range);
274 let total_i128 = i128::from(end) - i128::from(start) + 1;
275 if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) {
276 return Err(format!("invalid export frame range {start}..={end}"));
277 }
278
279 let prev_hiq = engine.hiq;
280 let prev_proxy = engine.proxy_scale;
281 engine.hiq = opts.hiq;
282 engine.proxy_scale = opts.proxy_scale.max(1);
283
284 let total = total_i128 as usize;
285 let workers = if opts.png_workers > 0 {
286 opts.png_workers.clamp(1, 24)
287 } else {
288 std::thread::available_parallelism()
289 .map(|n| n.get().clamp(2, 24))
290 .unwrap_or(4)
291 }
292 .min(total.max(1));
293
294 let t0 = Instant::now();
295 let mut first_path: Option<PathBuf> = None;
296 let mut last_path: Option<PathBuf> = None;
297 let mut frames_written: usize = 0;
298
299 let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
300 let failed = Arc::new(AtomicBool::new(false));
301 let cancelled = Arc::new(AtomicBool::new(false));
302
303 let eval_result: Result<(), String> = std::thread::scope(|scope| {
304 let queue_cap = (workers * 2).clamp(16, 48);
305 let (tx, rx) = mpsc::sync_channel::<EncodeJob>(queue_cap);
306 let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + workers);
307 let shared_rx = Arc::new(Mutex::new(rx));
308
309 let mut handles = Vec::with_capacity(workers);
310 for _ in 0..workers {
311 let rx_c = Arc::clone(&shared_rx);
312 let recycle_c = recycle_tx.clone();
313 let err_c = Arc::clone(&first_err);
314 let fail_c = Arc::clone(&failed);
315 let cancel_c = Arc::clone(&cancelled);
316 handles.push(scope.spawn(move || {
317 let mut staging = Vec::new();
318 let mut last_parent: Option<PathBuf> = None;
319 loop {
320 let job = {
321 let Ok(guard) = rx_c.lock() else { break };
322 guard.recv()
323 };
324 let Ok(job) = job else { break };
325 if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) {
326 continue;
327 }
328 if let Err(e) = write_png_fast_buffered(
329 &job.path,
330 job.size,
331 &job.pixels,
332 &mut staging,
333 &mut last_parent,
334 ) {
335 if let Ok(mut g) = err_c.lock() {
336 if g.is_none() {
337 *g = Some(e);
338 }
339 }
340 fail_c.store(true, Ordering::Release);
341 }
342 let _ = recycle_c.try_send(job.pixels);
343 }
344 }));
345 }
346 drop(recycle_tx);
347
348 let mut loop_err: Option<String> = None;
349 const PREFETCH_LOOKAHEAD: usize = 12;
350 engine.prewarm_for_depth(comp.depth_full);
351 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
352 if start < end {
353 let seed_start = start.saturating_add(1);
354 let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end);
355 for (k, f) in (seed_start..=seed_end).enumerate() {
356 prefetch.enqueue_frame(
357 comp,
358 target,
359 k + 1,
360 f as f64,
361 &engine.expr,
362 engine.use_proxy_clips,
363 );
364 }
365 }
366 // Double-buffered async GPU readback: frame N+1 evaluates/submits on GPU while
367 // frame N finishes its copy/map and hands off to the background PNG writer pool.
368 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, PathBuf, [u32; 2], f64)> = None;
369 for (idx, frame) in (start..=end).enumerate() {
370 if failed.load(Ordering::Acquire) {
371 break;
372 }
373 if control.is_some_and(ExportControl::is_cancelled) {
374 cancelled.store(true, Ordering::Release);
375 break;
376 }
377 prefetch.set_current_seq(idx);
378 if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) {
379 if ahead_frame <= end {
380 prefetch.enqueue_frame(
381 comp,
382 target,
383 idx + PREFETCH_LOOKAHEAD,
384 ahead_frame as f64,
385 &engine.expr,
386 engine.use_proxy_clips,
387 );
388 }
389 }
390 let out_path = match resolve_output_path(&saver, frame, opts.out_dir_override.as_deref()) {
391 Ok(p) => p,
392 Err(e) => {
393 loop_err = Some(e);
394 break;
395 }
396 };
397
398 let (tex, stats) = engine.evaluate(comp, target, frame as f64);
399 let next_rb = match engine.begin_readback_rgba(&tex) {
400 Ok(rb) => rb,
401 Err(e) => {
402 loop_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
403 break;
404 }
405 };
406 if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_ms)) =
407 pending.replace((next_rb, frame, idx, out_path, tex.size, stats.eval_ms))
408 {
409 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
410 if let Err(e) = prev_rb.finish_into(engine, &mut pixels) {
411 loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
412 break;
413 }
414 if control.is_some_and(ExportControl::is_cancelled) {
415 cancelled.store(true, Ordering::Release);
416 break;
417 }
418 if first_path.is_none() {
419 first_path = Some(prev_path.clone());
420 }
421 last_path = Some(prev_path.clone());
422 let prog = make_progress(
423 prev_frame,
424 prev_idx,
425 total,
426 prev_ms,
427 prev_path.clone(),
428 saver.name.clone(),
429 t0,
430 );
431 if let Some(ctrl) = control {
432 ctrl.update_progress(&prog);
433 }
434 on_progress(&prog);
435 if tx
436 .send(EncodeJob {
437 path: prev_path,
438 size: prev_size,
439 pixels,
440 })
441 .is_err()
442 {
443 break;
444 }
445 frames_written += 1;
446 }
447 }
448 if loop_err.is_none() && !failed.load(Ordering::Acquire) && !cancelled.load(Ordering::Acquire) {
449 if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_ms)) = pending.take() {
450 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
451 match prev_rb.finish_into(engine, &mut pixels) {
452 Ok(()) => {
453 if control.is_some_and(ExportControl::is_cancelled) {
454 cancelled.store(true, Ordering::Release);
455 } else {
456 if first_path.is_none() {
457 first_path = Some(prev_path.clone());
458 }
459 last_path = Some(prev_path.clone());
460 let prog = make_progress(
461 prev_frame,
462 prev_idx,
463 total,
464 prev_ms,
465 prev_path.clone(),
466 saver.name.clone(),
467 t0,
468 );
469 if let Some(ctrl) = control {
470 ctrl.update_progress(&prog);
471 }
472 on_progress(&prog);
473 if tx
474 .send(EncodeJob {
475 path: prev_path,
476 size: prev_size,
477 pixels,
478 })
479 .is_ok()
480 {
481 frames_written += 1;
482 }
483 }
484 }
485 Err(e) => {
486 loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
487 }
488 }
489 }
490 }
491
492 drop(prefetch);
493 drop(tx);
494 for h in handles {
495 let _ = h.join();
496 }
497
498 if let Some(e) = loop_err {
499 return Err(e);
500 }
501 if let Ok(mut g) = first_err.lock() {
502 if let Some(e) = g.take() {
503 return Err(e);
504 }
505 }
506 if cancelled.load(Ordering::Acquire) {
507 return Err("Cancelled".to_owned());
508 }
509 Ok(())
510 });
511
512 engine.hiq = prev_hiq;
513 engine.proxy_scale = prev_proxy;
514
515 eval_result?;
516
517 Ok(ExportSummary {
518 saver_name: saver.name,
519 frames_written,
520 total_ms: t0.elapsed().as_secs_f64() * 1000.0,
521 first_path,
522 last_path,
523 })
524}
525
526180/// Output video codec profile for direct viewer / node ffmpeg export.
527181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
528182pub enum VideoCodec {
......@@ -573,2026 +227,3 @@ pub struct VideoExportSummary {
573227 pub total_ms: f64,
574228 pub file_bytes: u64,
575229}
576
577/// Evaluates `target` at `frame` on GPU and saves a single RGBA8 PNG to `out_path`.
578pub fn export_node_frame_png(
579 engine: &mut Engine,
580 comp: &Comp,
581 target: NodeId,
582 frame: f64,
583 out_path: &Path,
584) -> Result<PathBuf, String> {
585 if target.0 >= comp.nodes.len() {
586 return Err(format!("invalid target node id {}", target.0));
587 }
588 let (tex, _) = engine.evaluate(comp, target, frame);
589 let pixels = engine
590 .readback_rgba(&tex)
591 .map_err(|e| format!("GPU readback failed at frame {frame}: {e}"))?;
592 write_png_fast(out_path, tex.size, &pixels)?;
593 Ok(out_path.to_path_buf())
594}
595
596/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames
597/// directly into `ffmpeg`, and muxes synced comp audio when `opts.include_audio` is enabled.
598pub fn export_node_video_ffmpeg(
599 engine: &mut Engine,
600 comp: &Comp,
601 opts: &VideoExportOptions,
602 on_progress: impl FnMut(ExportProgress),
603) -> Result<VideoExportSummary, String> {
604 export_node_video_ffmpeg_with_progress(engine, comp, opts, None, on_progress)
605}
606
607fn probe_audio_duration_secs(path: &Path) -> Option<f64> {
608 let out = Command::new("ffprobe")
609 .args([
610 "-v",
611 "error",
612 "-select_streams",
613 "a:0",
614 "-show_entries",
615 "stream=codec_type,duration",
616 "-show_entries",
617 "format=duration",
618 "-of",
619 "default=noprint_wrappers=1",
620 ])
621 .arg(path)
622 .output()
623 .ok()?;
624 if !out.status.success() {
625 return None;
626 }
627 let text = String::from_utf8_lossy(&out.stdout);
628 let mut has_audio_stream = false;
629 let mut stream_dur: Option<f64> = None;
630 let mut format_dur: Option<f64> = None;
631 let mut in_stream = false;
632 for line in text.lines() {
633 let Some((k, v)) = line.split_once('=') else {
634 continue;
635 };
636 let key = k.trim();
637 let val = v.trim();
638 match key {
639 "codec_type" => {
640 in_stream = true;
641 if val == "audio" {
642 has_audio_stream = true;
643 }
644 }
645 "duration" => {
646 if let Ok(d) = val.parse::<f64>() {
647 if d.is_finite() && d >= 0.0 {
648 if in_stream && stream_dur.is_none() {
649 stream_dur = Some(d);
650 } else if !in_stream && format_dur.is_none() {
651 format_dur = Some(d);
652 }
653 }
654 }
655 in_stream = false;
656 }
657 _ => {}
658 }
659 }
660 if !has_audio_stream {
661 return Some(0.0);
662 }
663 stream_dur.or(format_dur)
664}
665
666#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
667struct VideoToolboxSupport {
668 h264: bool,
669 prores: bool,
670}
671
672#[derive(Clone, Copy, Debug, PartialEq, Eq)]
673enum VideoEncoder {
674 Libx264,
675 H264VideoToolbox,
676 ProResKs422,
677 ProResVideoToolbox422,
678 ProResKs4444,
679 ProResVideoToolbox4444,
680}
681
682impl VideoEncoder {
683 fn is_hardware_accelerated(self) -> bool {
684 matches!(
685 self,
686 Self::H264VideoToolbox | Self::ProResVideoToolbox422 | Self::ProResVideoToolbox4444
687 )
688 }
689}
690
691#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
692fn parse_videotoolbox_encoders(encoders_stdout: &str) -> VideoToolboxSupport {
693 let mut support = VideoToolboxSupport::default();
694 for line in encoders_stdout.lines() {
695 let mut parts = line.split_whitespace();
696 let Some(flags) = parts.next() else {
697 continue;
698 };
699 if !flags.starts_with('V') {
700 continue;
701 }
702 let Some(name) = parts.next() else {
703 continue;
704 };
705 match name {
706 "h264_videotoolbox" => support.h264 = true,
707 "prores_videotoolbox" => support.prores = true,
708 _ => {}
709 }
710 }
711 support
712}
713
714#[cfg(target_os = "macos")]
715fn probe_videotoolbox_support() -> VideoToolboxSupport {
716 static VT_SUPPORT: OnceLock<VideoToolboxSupport> = OnceLock::new();
717 *VT_SUPPORT.get_or_init(|| {
718 let Ok(out) = Command::new("ffmpeg")
719 .args(["-hide_banner", "-encoders"])
720 .output()
721 else {
722 return VideoToolboxSupport::default();
723 };
724 if !out.status.success() {
725 return VideoToolboxSupport::default();
726 }
727 let text = String::from_utf8_lossy(&out.stdout);
728 parse_videotoolbox_encoders(&text)
729 })
730}
731
732#[cfg(not(target_os = "macos"))]
733fn probe_videotoolbox_support() -> VideoToolboxSupport {
734 VideoToolboxSupport::default()
735}
736
737fn select_video_encoder(
738 codec: VideoCodec,
739 vt: VideoToolboxSupport,
740 allow_videotoolbox: bool,
741) -> VideoEncoder {
742 match codec {
743 VideoCodec::H264Share => {
744 if allow_videotoolbox && vt.h264 {
745 VideoEncoder::H264VideoToolbox
746 } else {
747 VideoEncoder::Libx264
748 }
749 }
750 VideoCodec::ProRes422 => {
751 if allow_videotoolbox && vt.prores {
752 VideoEncoder::ProResVideoToolbox422
753 } else {
754 VideoEncoder::ProResKs422
755 }
756 }
757 VideoCodec::ProRes4444 => {
758 if allow_videotoolbox && vt.prores {
759 VideoEncoder::ProResVideoToolbox4444
760 } else {
761 VideoEncoder::ProResKs4444
762 }
763 }
764 }
765}
766
767/// Maps x264-style CRF (`0..=51`, lower = higher quality) to VideoToolbox `-q:v` (`15..=95`, higher = higher quality).
768fn vt_quality_from_crf(crf: u8) -> u8 {
769 (104 - i32::from(crf) * 2).clamp(15, 95) as u8
770}
771
772fn push_video_encoder_args(args: &mut Vec<String>, encoder: VideoEncoder, crf: u8, vf: Option<&str>) {
773 match encoder {
774 VideoEncoder::H264VideoToolbox => {
775 if let Some(vf) = vf {
776 args.extend(["-vf".to_owned(), vf.to_owned()]);
777 }
778 args.extend([
779 "-c:v".to_owned(),
780 "h264_videotoolbox".to_owned(),
781 "-q:v".to_owned(),
782 vt_quality_from_crf(crf).to_string(),
783 "-pix_fmt".to_owned(),
784 "yuv420p".to_owned(),
785 "-tag:v".to_owned(),
786 "avc1".to_owned(),
787 "-movflags".to_owned(),
788 "+faststart".to_owned(),
789 ]);
790 }
791 VideoEncoder::Libx264 => {
792 if let Some(vf) = vf {
793 args.extend(["-vf".to_owned(), vf.to_owned()]);
794 }
795 args.extend([
796 "-c:v".to_owned(),
797 "libx264".to_owned(),
798 "-preset".to_owned(),
799 "medium".to_owned(),
800 "-crf".to_owned(),
801 crf.to_string(),
802 "-pix_fmt".to_owned(),
803 "yuv420p".to_owned(),
804 "-movflags".to_owned(),
805 "+faststart".to_owned(),
806 ]);
807 }
808 VideoEncoder::ProResVideoToolbox422 => {
809 args.extend([
810 "-c:v".to_owned(),
811 "prores_videotoolbox".to_owned(),
812 "-profile:v".to_owned(),
813 "2".to_owned(),
814 "-pix_fmt".to_owned(),
815 "p210le".to_owned(),
816 ]);
817 }
818 VideoEncoder::ProResKs422 => {
819 args.extend([
820 "-c:v".to_owned(),
821 "prores_ks".to_owned(),
822 "-profile:v".to_owned(),
823 "2".to_owned(),
824 "-pix_fmt".to_owned(),
825 "yuv422p10le".to_owned(),
826 ]);
827 }
828 VideoEncoder::ProResVideoToolbox4444 => {
829 args.extend([
830 "-c:v".to_owned(),
831 "prores_videotoolbox".to_owned(),
832 "-profile:v".to_owned(),
833 "4".to_owned(),
834 "-pix_fmt".to_owned(),
835 "ayuv64le".to_owned(),
836 ]);
837 }
838 VideoEncoder::ProResKs4444 => {
839 args.extend([
840 "-c:v".to_owned(),
841 "prores_ks".to_owned(),
842 "-profile:v".to_owned(),
843 "4".to_owned(),
844 "-pix_fmt".to_owned(),
845 "yuva444p10le".to_owned(),
846 ]);
847 }
848 }
849}
850
851fn fit_frame_rgba(
852 pixels: Vec<u8>,
853 src_size: [u32; 2],
854 dst_size: [u32; 2],
855 frame: i64,
856) -> Result<Vec<u8>, String> {
857 let expected_len = (src_size[0] as usize)
858 .checked_mul(src_size[1] as usize)
859 .and_then(|px| px.checked_mul(4))
860 .ok_or_else(|| format!("frame {frame} dimensions overflow buffer size"))?;
861 if pixels.len() != expected_len {
862 return Err(format!(
863 "invalid RGBA buffer size at frame {frame}: expected {expected_len}, got {}",
864 pixels.len()
865 ));
866 }
867 if src_size == dst_size {
868 return Ok(pixels);
869 }
870 let img = image::RgbaImage::from_raw(src_size[0], src_size[1], pixels)
871 .ok_or_else(|| format!("invalid RGBA buffer size at frame {frame}"))?;
872 Ok(image::imageops::resize(
873 &img,
874 dst_size[0],
875 dst_size[1],
876 image::imageops::FilterType::Triangle,
877 )
878 .into_raw())
879}
880
881static EXPORT_TMP_SEQ: AtomicU64 = AtomicU64::new(0);
882
883fn sibling_temp_export_path(out_path: &Path) -> PathBuf {
884 let seq = EXPORT_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
885 let pid = std::process::id();
886 let stem = out_path
887 .file_stem()
888 .and_then(|s| s.to_str())
889 .filter(|s| !s.is_empty())
890 .unwrap_or("export");
891 let file_name = match out_path.extension().and_then(|e| e.to_str()).filter(|e| !e.is_empty()) {
892 Some(ext) => format!("{stem}.fission_tmp_{pid}_{seq}.{ext}"),
893 None => format!("{stem}.fission_tmp_{pid}_{seq}"),
894 };
895 out_path.with_file_name(file_name)
896}
897
898struct TempExportGuard {
899 path: PathBuf,
900 active: bool,
901}
902
903impl TempExportGuard {
904 fn new(path: PathBuf) -> Self {
905 Self { path, active: true }
906 }
907
908 fn disarm(&mut self) {
909 self.active = false;
910 }
911}
912
913impl Drop for TempExportGuard {
914 fn drop(&mut self) {
915 if self.active {
916 let _ = std::fs::remove_file(&self.path);
917 }
918 }
919}
920
921#[derive(Debug)]
922enum VideoExportError {
923 Cancelled,
924 Fatal(String),
925 EncoderFailed(String),
926}
927
928impl VideoExportError {
929 fn into_string(self) -> String {
930 match self {
931 Self::Cancelled => "Cancelled".to_owned(),
932 Self::Fatal(s) | Self::EncoderFailed(s) => s,
933 }
934 }
935}
936
937fn h264_scale_filter_and_dims(width: u32, height: u32, max_height: Option<u32>) -> (String, u32, u32) {
938 if let Some(max_h) = max_height.filter(|&h| h >= 2) {
939 let oh = (height.min(max_h) & !1).max(2);
940 let ow = ((((width as f64) * (oh as f64) / (height as f64)) / 2.0).round() as u32 * 2).max(2);
941 (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh)
942 } else {
943 let ow = (width & !1).max(2);
944 let oh = (height & !1).max(2);
945 ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh)
946 }
947}
948
949/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames
950/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`.
951pub fn export_node_video_ffmpeg_with_progress(
952 engine: &mut Engine,
953 comp: &Comp,
954 opts: &VideoExportOptions,
955 control: Option<&ExportControl>,
956 mut on_progress: impl FnMut(ExportProgress),
957) -> Result<VideoExportSummary, String> {
958 if control.is_some_and(ExportControl::is_cancelled) {
959 return Err("Cancelled".to_owned());
960 }
961 let [start, end] = opts.range;
962 let total_i128 = i128::from(end) - i128::from(start) + 1;
963 if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) {
964 return Err(format!("invalid export frame range {start}..={end}"));
965 }
966 if opts.target.0 >= comp.nodes.len() {
967 return Err(format!("invalid target node id {}", opts.target.0));
968 }
969 if opts.out_path.as_os_str().is_empty() {
970 return Err("video export output path is empty".to_owned());
971 }
972 if let Some(parent) = opts.out_path.parent() {
973 if !parent.as_os_str().is_empty() {
974 std::fs::create_dir_all(parent)
975 .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
976 }
977 }
978
979 let prev_hiq = engine.hiq;
980 let prev_proxy = engine.proxy_scale;
981 engine.hiq = opts.hiq;
982 engine.proxy_scale = opts.proxy_scale.max(1);
983
984 let started_at = Instant::now();
985 let vt = probe_videotoolbox_support();
986 let encoder = select_video_encoder(opts.codec, vt, true);
987 let res = match export_node_video_ffmpeg_with_encoder(
988 engine,
989 comp,
990 opts,
991 control,
992 &mut on_progress,
993 encoder,
994 started_at,
995 ) {
996 Ok(summary) => Ok(summary),
997 Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => {
998 if control.is_some_and(ExportControl::is_cancelled) {
999 Err("Cancelled".to_owned())
1000 } else {
1001 let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false);
1002 export_node_video_ffmpeg_with_encoder(
1003 engine,
1004 comp,
1005 opts,
1006 control,
1007 &mut on_progress,
1008 fallback,
1009 started_at,
1010 )
1011 .map_err(VideoExportError::into_string)
1012 }
1013 }
1014 Err(err) => Err(err.into_string()),
1015 };
1016
1017 engine.hiq = prev_hiq;
1018 engine.proxy_scale = prev_proxy;
1019 res
1020}
1021
1022fn export_node_video_ffmpeg_with_encoder(
1023 engine: &mut Engine,
1024 comp: &Comp,
1025 opts: &VideoExportOptions,
1026 control: Option<&ExportControl>,
1027 on_progress: &mut impl FnMut(ExportProgress),
1028 encoder: VideoEncoder,
1029 started_at: Instant,
1030) -> Result<VideoExportSummary, VideoExportError> {
1031 let [start, end] = opts.range;
1032 let total = (end - start + 1) as usize;
1033 let fps = comp.fps.max(1.0);
1034 let node_name = comp.node(opts.target).name.clone();
1035
1036 // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output.
1037 engine.prewarm_for_depth(comp.depth_full);
1038 let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64);
1039 if first_tex.size[0] == 0 || first_tex.size[1] == 0 {
1040 return Err(VideoExportError::Fatal(format!(
1041 "target '{}' produced empty frame {}x{}",
1042 node_name, first_tex.size[0], first_tex.size[1]
1043 )));
1044 }
1045 // If the first frame is a 1x1 dummy (e.g., missing Loader frame), fall back to comp
1046 // canvas dimensions so ffmpeg never receives -s 1x1 and crashes scale=trunc(iw/2)*2.
1047 let (width, height) = if first_tex.size[0] < 2 || first_tex.size[1] < 2 {
1048 let ps = engine.proxy_scale.max(1);
1049 let fw = (comp.width / ps).max(2);
1050 let fh = (comp.height / ps).max(2);
1051 if opts.codec == VideoCodec::H264Share {
1052 (((fw + 1) & !1).max(2), ((fh + 1) & !1).max(2))
1053 } else {
1054 (fw, fh)
1055 }
1056 } else {
1057 (first_tex.size[0], first_tex.size[1])
1058 };
1059 let raw_first = engine
1060 .readback_rgba(&first_tex)
1061 .map_err(|e| VideoExportError::Fatal(format!("GPU readback failed at frame {start}: {e}")))?;
1062 let first_pixels = fit_frame_rgba(raw_first, first_tex.size, [width, height], start)
1063 .map_err(VideoExportError::Fatal)?;
1064 if control.is_some_and(ExportControl::is_cancelled) {
1065 return Err(VideoExportError::Cancelled);
1066 }
1067
1068 let duration_secs = total as f64 / fps;
1069 let audio_start_secs = (start as f64 - comp.audio_offset) / fps;
1070 let audio_path = if opts.include_audio {
1071 comp.audio_filename
1072 .as_deref()
1073 .map(PathBuf::from)
1074 .filter(|p| {
1075 if p.as_os_str().is_empty() || !p.exists() || -audio_start_secs >= duration_secs {
1076 return false;
1077 }
1078 if let Some(audio_dur) = probe_audio_duration_secs(p) {
1079 if audio_dur <= 0.0 || audio_start_secs >= audio_dur {
1080 return false;
1081 }
1082 }
1083 true
1084 })
1085 } else {
1086 None
1087 };
1088 let has_audio = audio_path.is_some();
1089
1090 let mut cmd = Command::new("ffmpeg");
1091 cmd.args(["-y", "-hide_banner", "-loglevel", "error"]);
1092 cmd.args([
1093 "-f",
1094 "rawvideo",
1095 "-pix_fmt",
1096 "rgba",
1097 "-s",
1098 &format!("{width}x{height}"),
1099 "-r",
1100 &format!("{fps:.6}"),
1101 "-i",
1102 "pipe:0",
1103 ]);
1104
1105 let audio_filter = if let Some(ap) = &audio_path {
1106 if audio_start_secs >= 0.0 {
1107 if audio_start_secs > 0.0 {
1108 cmd.args(["-ss", &format!("{audio_start_secs:.6}")]);
1109 }
1110 cmd.arg("-i").arg(ap);
1111 Some(format!("asetpts=PTS-STARTPTS,apad,atrim=0:{duration_secs:.6}"))
1112 } else {
1113 let delay_ms = (-audio_start_secs * 1000.0).max(0.0);
1114 cmd.arg("-i").arg(ap);
1115 Some(format!(
1116 "adelay={delay_ms:.3}:all=1,apad,atrim=0:{duration_secs:.6},asetpts=PTS-STARTPTS"
1117 ))
1118 }
1119 } else {
1120 None
1121 };
1122
1123 let (out_width, out_height) = match opts.codec {
1124 VideoCodec::H264Share => {
1125 let (vf, ow, oh) = h264_scale_filter_and_dims(width, height, opts.max_height);
1126 let mut encoder_args = Vec::new();
1127 push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf));
1128 cmd.args(&encoder_args);
1129 (ow, oh)
1130 }
1131 VideoCodec::ProRes422 | VideoCodec::ProRes4444 => {
1132 let mut encoder_args = Vec::new();
1133 push_video_encoder_args(&mut encoder_args, encoder, opts.crf, None);
1134 cmd.args(&encoder_args);
1135 (width, height)
1136 }
1137 };
1138
1139 if let Some(af) = audio_filter {
1140 cmd.args(["-map", "0:v:0", "-map", "1:a:0", "-af", &af]);
1141 match opts.codec {
1142 VideoCodec::H264Share => {
1143 cmd.args(["-c:a", "aac", "-b:a", "128k"]);
1144 }
1145 VideoCodec::ProRes422 | VideoCodec::ProRes4444 => {
1146 cmd.args(["-c:a", "pcm_s16le"]);
1147 }
1148 }
1149 } else {
1150 cmd.arg("-an");
1151 }
1152
1153 let tmp_path = sibling_temp_export_path(&opts.out_path);
1154 let mut tmp_guard = TempExportGuard::new(tmp_path.clone());
1155 cmd.arg(&tmp_path);
1156 cmd.stdin(Stdio::piped())
1157 .stdout(Stdio::null())
1158 .stderr(Stdio::piped());
1159
1160 let mut child = cmd.spawn().map_err(|e| {
1161 VideoExportError::Fatal(format!(
1162 "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}"
1163 ))
1164 })?;
1165
1166 let mut stderr_pipe = child.stderr.take();
1167 let stderr_thread = std::thread::spawn(move || {
1168 let mut buf = String::new();
1169 if let Some(ref mut pipe) = stderr_pipe {
1170 let _ = pipe.read_to_string(&mut buf);
1171 }
1172 buf
1173 });
1174
1175 let mut readback_err: Option<String> = None;
1176 let mut pipe_err: Option<String> = None;
1177 let mut cancelled = false;
1178 let writer_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
1179 let writer_failed = Arc::new(AtomicBool::new(false));
1180 let writer_fatal = Arc::new(AtomicBool::new(false));
1181 let Some(stdin) = child.stdin.take() else {
1182 let _ = child.kill();
1183 let _ = child.wait();
1184 let _ = stderr_thread.join();
1185 return Err(VideoExportError::Fatal(
1186 "failed to open ffmpeg stdin".to_owned(),
1187 ));
1188 };
1189
1190 let frame_bytes_len = (width as usize)
1191 .saturating_mul(height as usize)
1192 .saturating_mul(4)
1193 .max(1);
1194 let queue_cap = (128 * 1024 * 1024 / frame_bytes_len).clamp(4, 16);
1195 let (tx, rx) = mpsc::sync_channel::<(i64, [u32; 2], Vec<u8>)>(queue_cap);
1196 let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + 2);
1197 let writer_err_c = Arc::clone(&writer_err);
1198 let writer_failed_c = Arc::clone(&writer_failed);
1199 let writer_fatal_c = Arc::clone(&writer_fatal);
1200 let dst_size = [width, height];
1201 let writer_thread = std::thread::spawn(move || {
1202 let mut stdin = stdin;
1203 while let Ok((frame, src_size, pixels)) = rx.recv() {
1204 let frame_bytes = match fit_frame_rgba(pixels, src_size, dst_size, frame) {
1205 Ok(bytes) => bytes,
1206 Err(e) => {
1207 if let Ok(mut g) = writer_err_c.lock() {
1208 if g.is_none() {
1209 *g = Some(e);
1210 }
1211 }
1212 writer_fatal_c.store(true, Ordering::Release);
1213 writer_failed_c.store(true, Ordering::Release);
1214 break;
1215 }
1216 };
1217 // Each frame is already a contiguous RGBA buffer; write directly without an extra copy.
1218 if let Err(e) = stdin.write_all(&frame_bytes) {
1219 if let Ok(mut g) = writer_err_c.lock() {
1220 if g.is_none() {
1221 *g = Some(format!("failed writing frame {frame} to ffmpeg: {e}"));
1222 }
1223 }
1224 writer_failed_c.store(true, Ordering::Release);
1225 break;
1226 }
1227 let _ = recycle_tx.try_send(frame_bytes);
1228 }
1229 let _ = stdin.flush();
1230 });
1231
1232 if tx.send((start, [width, height], first_pixels)).is_err() {
1233 pipe_err = writer_err
1234 .lock()
1235 .ok()
1236 .and_then(|mut g| g.take())
1237 .or_else(|| Some(format!("failed writing frame {start} to ffmpeg")));
1238 } else {
1239 let first_prog = make_progress(
1240 start,
1241 0,
1242 total,
1243 first_stats.eval_ms,
1244 opts.out_path.clone(),
1245 node_name.clone(),
1246 started_at,
1247 );
1248 if let Some(ctrl) = control {
1249 ctrl.update_progress(&first_prog);
1250 }
1251 on_progress(first_prog);
1252 if control.is_some_and(ExportControl::is_cancelled) {
1253 cancelled = true;
1254 } else if start < end {
1255 const PREFETCH_LOOKAHEAD: usize = 12;
1256 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
1257 let seed_start = start.saturating_add(1);
1258 let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64).min(end);
1259 for (k, f) in (seed_start..=seed_end).enumerate() {
1260 prefetch.enqueue_frame(
1261 comp,
1262 opts.target,
1263 k,
1264 f as f64,
1265 &engine.expr,
1266 engine.use_proxy_clips,
1267 );
1268 }
1269 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;
1270 for (idx, frame) in (seed_start..=end).enumerate() {
1271 if control.is_some_and(ExportControl::is_cancelled) {
1272 cancelled = true;
1273 break;
1274 }
1275 if writer_failed.load(Ordering::Acquire) {
1276 break;
1277 }
1278 prefetch.set_current_seq(idx);
1279 if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) {
1280 if ahead_frame <= end {
1281 prefetch.enqueue_frame(
1282 comp,
1283 opts.target,
1284 idx + PREFETCH_LOOKAHEAD,
1285 ahead_frame as f64,
1286 &engine.expr,
1287 engine.use_proxy_clips,
1288 );
1289 }
1290 }
1291 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
1292 let next_rb = match engine.begin_readback_rgba(&tex) {
1293 Ok(rb) => rb,
1294 Err(e) => {
1295 readback_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
1296 break;
1297 }
1298 };
1299 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) =
1300 pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms))
1301 {
1302 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
1303 if let Err(e) = prev_rb.finish_into(engine, &mut pixels) {
1304 readback_err =
1305 Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
1306 break;
1307 }
1308 if control.is_some_and(ExportControl::is_cancelled) {
1309 cancelled = true;
1310 break;
1311 }
1312 if tx.send((prev_frame, prev_size, pixels)).is_err() {
1313 break;
1314 }
1315 let prog = make_progress(
1316 prev_frame,
1317 prev_idx + 1,
1318 total,
1319 prev_ms,
1320 opts.out_path.clone(),
1321 node_name.clone(),
1322 started_at,
1323 );
1324 if let Some(ctrl) = control {
1325 ctrl.update_progress(&prog);
1326 }
1327 on_progress(prog);
1328 }
1329 }
1330 if control.is_some_and(ExportControl::is_cancelled) {
1331 cancelled = true;
1332 }
1333 if readback_err.is_none() && pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) {
1334 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() {
1335 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
1336 match prev_rb.finish_into(engine, &mut pixels) {
1337 Ok(()) => {
1338 if control.is_some_and(ExportControl::is_cancelled) {
1339 cancelled = true;
1340 } else if tx.send((prev_frame, prev_size, pixels)).is_ok() {
1341 let prog = make_progress(
1342 prev_frame,
1343 prev_idx + 1,
1344 total,
1345 prev_ms,
1346 opts.out_path.clone(),
1347 node_name.clone(),
1348 started_at,
1349 );
1350 if let Some(ctrl) = control {
1351 ctrl.update_progress(&prog);
1352 }
1353 on_progress(prog);
1354 if control.is_some_and(ExportControl::is_cancelled) {
1355 cancelled = true;
1356 }
1357 }
1358 }
1359 Err(e) => {
1360 readback_err =
1361 Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
1362 }
1363 }
1364 }
1365 }
1366 drop(prefetch);
1367 }
1368 }
1369 drop(tx);
1370
1371 if control.is_some_and(ExportControl::is_cancelled) {
1372 cancelled = true;
1373 }
1374 if cancelled || readback_err.is_some() || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) {
1375 // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately.
1376 let _ = child.kill();
1377 }
1378 let _ = writer_thread.join();
1379 if pipe_err.is_none() && !cancelled {
1380 if let Ok(mut g) = writer_err.lock() {
1381 pipe_err = g.take();
1382 }
1383 }
1384 if pipe_err.is_some() && !cancelled {
1385 let _ = child.kill();
1386 }
1387 let wait_res = child.wait();
1388 let stderr_text = stderr_thread.join().unwrap_or_default();
1389 let stderr_trim = stderr_text.trim();
1390
1391 if cancelled || control.is_some_and(ExportControl::is_cancelled) {
1392 return Err(VideoExportError::Cancelled);
1393 }
1394 if let Some(err) = readback_err {
1395 return Err(VideoExportError::Fatal(err));
1396 }
1397 if let Some(err) = pipe_err {
1398 if writer_fatal.load(Ordering::Acquire) {
1399 return Err(VideoExportError::Fatal(err));
1400 }
1401 return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() {
1402 format!("{err} (ffmpeg: {stderr_trim})")
1403 } else {
1404 err
1405 }));
1406 }
1407 let status = wait_res.map_err(|e| {
1408 VideoExportError::Fatal(format!("failed waiting on ffmpeg: {e}"))
1409 })?;
1410 if !status.success() {
1411 if control.is_some_and(ExportControl::is_cancelled) {
1412 return Err(VideoExportError::Cancelled);
1413 }
1414 return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() {
1415 format!("ffmpeg exited with {status}")
1416 } else {
1417 format!("ffmpeg exited with {status}: {stderr_trim}")
1418 }));
1419 }
1420
1421 std::fs::rename(&tmp_path, &opts.out_path).map_err(|e| {
1422 VideoExportError::Fatal(format!("failed to finalize '{}': {e}", opts.out_path.display()))
1423 })?;
1424 tmp_guard.disarm();
1425
1426 let file_bytes = std::fs::metadata(&opts.out_path)
1427 .map(|m| m.len())
1428 .unwrap_or(0);
1429
1430 Ok(VideoExportSummary {
1431 out_path: opts.out_path.clone(),
1432 frames_written: total,
1433 width: out_width,
1434 height: out_height,
1435 has_audio,
1436 total_ms: started_at.elapsed().as_secs_f64() * 1000.0,
1437 file_bytes,
1438 })
1439}
1440
1441#[cfg(test)]
1442mod tests {
1443 use super::*;
1444
1445 #[test]
1446 fn exports_saver_png_sequence_animated() {
1447 let tmp_dir = std::env::temp_dir().join(format!(
1448 "fission-saver-export-test-{}",
1449 std::process::id()
1450 ));
1451 let _ = std::fs::remove_dir_all(&tmp_dir);
1452 let saver_path = tmp_dir.join("nested").join("shot_0000.png");
1453 let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\");
1454
1455 let comp_src = format!(
1456 r#"Composition {{
1457 CurrentTime = 10,
1458 RenderRange = {{ 10, 12 }},
1459 GlobalRange = {{ 0, 100 }},
1460 Tools = ordered() {{
1461 BG = Background {{
1462 Inputs = {{
1463 Width = Input {{ Value = 64, }},
1464 Height = Input {{ Value = 32, }},
1465 TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }},
1466 TopLeftGreen = Input {{ Value = 0.25, }},
1467 TopLeftBlue = Input {{ Value = 0.5, }},
1468 TopLeftAlpha = Input {{ Value = 1, }},
1469 }},
1470 }},
1471 BGRed = BezierSpline {{
1472 KeyFrames = {{
1473 [10] = {{ 0.0, Flags = {{ Linear = true }} }},
1474 [12] = {{ 1.0, Flags = {{ Linear = true }} }},
1475 }},
1476 }},
1477 Saver1 = Saver {{
1478 Inputs = {{
1479 Clip = Input {{
1480 Value = Clip {{
1481 Filename = "{saver_path_escaped}",
1482 FormatID = "PNGFormat",
1483 Saving = true,
1484 }},
1485 }},
1486 Input = Input {{
1487 SourceOp = "BG",
1488 Source = "Output",
1489 }},
1490 }},
1491 }},
1492 }},
1493 Prefs = {{
1494 Comp = {{
1495 FrameFormat = {{
1496 Width = 64,
1497 Height = 32,
1498 Rate = 30,
1499 DepthFull = 1,
1500 }},
1501 }},
1502 }},
1503}}"#
1504 );
1505
1506 let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp");
1507 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1508
1509 let mut seen_frames = Vec::new();
1510 let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |p| {
1511 seen_frames.push(p.frame);
1512 })
1513 .expect("export png sequence");
1514
1515 assert_eq!(summary.saver_name, "Saver1");
1516 assert_eq!(summary.frames_written, 3);
1517 assert_eq!(seen_frames, vec![10, 11, 12]);
1518
1519 let expected_reds = [0u8, 128u8, 255u8];
1520 for (frame, exp_r) in [10i64, 11, 12].into_iter().zip(expected_reds) {
1521 let p = tmp_dir.join("nested").join(format!("shot_{frame:04}.png"));
1522 assert!(p.exists(), "missing exported frame {}", p.display());
1523 let img = image::open(&p).expect("decode exported PNG").to_rgba8();
1524 assert_eq!(img.dimensions(), (64, 32));
1525 let px = img.get_pixel(32, 16);
1526 assert!(
1527 (px[0] as i32 - exp_r as i32).abs() <= 2,
1528 "frame {frame}: expected R~{exp_r}, got {:?}",
1529 px.0
1530 );
1531 assert!((px[1] as i32 - 64).abs() <= 2);
1532 assert!((px[2] as i32 - 128).abs() <= 2);
1533 assert_eq!(px[3], 255);
1534 }
1535
1536 let _ = std::fs::remove_dir_all(&tmp_dir);
1537 }
1538
1539 fn write_test_wav(path: &Path, sample_rate: u32, duration_secs: f64) {
1540 let num_channels: u16 = 2;
1541 let bits_per_sample: u16 = 16;
1542 let num_samples = (sample_rate as f64 * duration_secs) as u32;
1543 let byte_rate = sample_rate * u32::from(num_channels) * u32::from(bits_per_sample) / 8;
1544 let block_align = num_channels * bits_per_sample / 8;
1545 let data_bytes = num_samples * u32::from(block_align);
1546 let riff_chunk_size = 36 + data_bytes;
1547
1548 let mut buf = Vec::with_capacity((44 + data_bytes) as usize);
1549 buf.extend_from_slice(b"RIFF");
1550 buf.extend_from_slice(&riff_chunk_size.to_le_bytes());
1551 buf.extend_from_slice(b"WAVE");
1552 buf.extend_from_slice(b"fmt ");
1553 buf.extend_from_slice(&16u32.to_le_bytes());
1554 buf.extend_from_slice(&1u16.to_le_bytes()); // PCM
1555 buf.extend_from_slice(&num_channels.to_le_bytes());
1556 buf.extend_from_slice(&sample_rate.to_le_bytes());
1557 buf.extend_from_slice(&byte_rate.to_le_bytes());
1558 buf.extend_from_slice(&block_align.to_le_bytes());
1559 buf.extend_from_slice(&bits_per_sample.to_le_bytes());
1560 buf.extend_from_slice(b"data");
1561 buf.extend_from_slice(&data_bytes.to_le_bytes());
1562 for i in 0..num_samples {
1563 let t = i as f64 / sample_rate as f64;
1564 let sample = ((t * 440.0 * std::f64::consts::TAU).sin() * 12000.0) as i16;
1565 buf.extend_from_slice(&sample.to_le_bytes());
1566 buf.extend_from_slice(&sample.to_le_bytes());
1567 }
1568 std::fs::write(path, buf).expect("write synthetic wav");
1569 }
1570
1571 #[test]
1572 fn exports_snippet_mp4_with_synced_audio() {
1573 let tmp_dir = std::env::temp_dir().join(format!(
1574 "fission-video-export-test-{}",
1575 std::process::id()
1576 ));
1577 let _ = std::fs::remove_dir_all(&tmp_dir);
1578 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
1579
1580 let wav_path = tmp_dir.join("tone.wav");
1581 write_test_wav(&wav_path, 44100, 2.0);
1582 let wav_escaped = wav_path.to_string_lossy().replace('\\', "\\\\");
1583
1584 let comp_src = format!(
1585 r#"Composition {{
1586 CurrentTime = 10,
1587 RenderRange = {{ 10, 21 }},
1588 GlobalRange = {{ 0, 100 }},
1589 AudioFilename = "{wav_escaped}",
1590 AudioOffset = 10,
1591 Tools = ordered() {{
1592 BG = Background {{
1593 Inputs = {{
1594 Width = Input {{ Value = 128, }},
1595 Height = Input {{ Value = 72, }},
1596 TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }},
1597 TopLeftGreen = Input {{ Value = 0.25, }},
1598 TopLeftBlue = Input {{ Value = 0.75, }},
1599 TopLeftAlpha = Input {{ Value = 1, }},
1600 }},
1601 }},
1602 BGRed = BezierSpline {{
1603 KeyFrames = {{
1604 [10] = {{ 0.0, Flags = {{ Linear = true }} }},
1605 [21] = {{ 1.0, Flags = {{ Linear = true }} }},
1606 }},
1607 }},
1608 }},
1609 Prefs = {{
1610 Comp = {{
1611 FrameFormat = {{
1612 Width = 128,
1613 Height = 72,
1614 Rate = 30,
1615 DepthFull = 1,
1616 }},
1617 }},
1618 }},
1619}}"#
1620 );
1621
1622 let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic audio comp");
1623 let target = comp.find_node("BG").expect("find BG node");
1624 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1625
1626 let mp4_path = tmp_dir.join("snippet.mp4");
1627 let mut seen_frames = Vec::new();
1628 let summary = export_node_video_ffmpeg(
1629 &mut engine,
1630 &comp,
1631 &VideoExportOptions {
1632 target,
1633 out_path: mp4_path.clone(),
1634 range: [10, 21],
1635 codec: VideoCodec::H264Share,
1636 crf: 26,
1637 max_height: None,
1638 include_audio: true,
1639 hiq: true,
1640 proxy_scale: 1,
1641 },
1642 |p| seen_frames.push(p.frame),
1643 )
1644 .expect("export snippet mp4");
1645
1646 assert_eq!(summary.frames_written, 12);
1647 assert_eq!(summary.width, 128);
1648 assert_eq!(summary.height, 72);
1649 assert!(summary.has_audio);
1650 assert!(summary.file_bytes > 0);
1651 assert_eq!(seen_frames.len(), 12);
1652 assert!(mp4_path.exists());
1653
1654 // Verify streams and exact video frame count via ffprobe
1655 let probe = Command::new("ffprobe")
1656 .args([
1657 "-v",
1658 "error",
1659 "-count_frames",
1660 "-show_entries",
1661 "stream=codec_type,codec_name,nb_read_frames",
1662 "-of",
1663 "csv=p=0",
1664 ])
1665 .arg(&mp4_path)
1666 .output()
1667 .expect("run ffprobe");
1668 assert!(
1669 probe.status.success(),
1670 "ffprobe failed: {}",
1671 String::from_utf8_lossy(&probe.stderr)
1672 );
1673 let stdout = String::from_utf8_lossy(&probe.stdout);
1674 let mut saw_h264_12 = false;
1675 let mut saw_aac = false;
1676 for line in stdout.lines() {
1677 let cols: Vec<&str> = line.split(',').map(str::trim).collect();
1678 if cols.len() >= 3 && cols[1] == "video" && cols[0] == "h264" && cols[2] == "12" {
1679 saw_h264_12 = true;
1680 }
1681 if cols.len() >= 2 && cols[1] == "audio" && cols[0] == "aac" {
1682 saw_aac = true;
1683 }
1684 }
1685 assert!(
1686 saw_h264_12,
1687 "expected h264 video stream with 12 frames, ffprobe output:\n{stdout}"
1688 );
1689 assert!(
1690 saw_aac,
1691 "expected aac audio stream, ffprobe output:\n{stdout}"
1692 );
1693
1694 // Also verify negative audio_start_secs (range starts before AudioOffset = 10)
1695 let pre_mp4_path = tmp_dir.join("snippet_pre_offset.mp4");
1696 let pre_summary = export_node_video_ffmpeg(
1697 &mut engine,
1698 &comp,
1699 &VideoExportOptions {
1700 target,
1701 out_path: pre_mp4_path.clone(),
1702 range: [6, 17],
1703 codec: VideoCodec::H264Share,
1704 crf: 26,
1705 max_height: Some(64),
1706 include_audio: true,
1707 hiq: true,
1708 proxy_scale: 1,
1709 },
1710 |_| {},
1711 )
1712 .expect("export snippet mp4 with negative audio_start_secs");
1713 assert_eq!(pre_summary.frames_written, 12);
1714 assert!(pre_summary.has_audio);
1715 assert!(pre_summary.file_bytes > 0);
1716 assert!(pre_mp4_path.exists());
1717
1718 // Verify single-frame PNG helper
1719 let png_path = tmp_dir.join("frame_10.png");
1720 let saved = export_node_frame_png(&mut engine, &comp, target, 10.0, &png_path)
1721 .expect("export single frame png");
1722 assert_eq!(saved, png_path);
1723 let img = image::open(&png_path).expect("decode exported frame png").to_rgba8();
1724 assert_eq!(img.dimensions(), (128, 72));
1725
1726 let _ = std::fs::remove_dir_all(&tmp_dir);
1727 }
1728
1729 #[test]
1730 fn saver_export_reports_progress_and_stops_on_cancel() {
1731 let tmp_dir = std::env::temp_dir().join(format!(
1732 "fission-saver-cancel-test-{}",
1733 std::process::id()
1734 ));
1735 let _ = std::fs::remove_dir_all(&tmp_dir);
1736 let saver_path = tmp_dir.join("shot_0000.png");
1737 let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\");
1738
1739 let comp_src = format!(
1740 r#"Composition {{
1741 CurrentTime = 10,
1742 RenderRange = {{ 10, 15 }},
1743 GlobalRange = {{ 0, 100 }},
1744 Tools = ordered() {{
1745 BG = Background {{
1746 Inputs = {{
1747 Width = Input {{ Value = 64, }},
1748 Height = Input {{ Value = 32, }},
1749 TopLeftRed = Input {{ Value = 0.7, }},
1750 TopLeftAlpha = Input {{ Value = 1, }},
1751 }},
1752 }},
1753 Saver1 = Saver {{
1754 Inputs = {{
1755 Clip = Input {{
1756 Value = Clip {{
1757 Filename = "{saver_path_escaped}",
1758 FormatID = "PNGFormat",
1759 Saving = true,
1760 }},
1761 }},
1762 Input = Input {{
1763 SourceOp = "BG",
1764 Source = "Output",
1765 }},
1766 }},
1767 }},
1768 }},
1769 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 1 }} }} }},
1770}}"#
1771 );
1772
1773 let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp");
1774 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1775 let control = ExportControl::new();
1776 let ctrl_cb = control.clone();
1777 let mut reported = Vec::new();
1778
1779 let err = export_saver_png_sequence_with_progress(
1780 &mut engine,
1781 &comp,
1782 &ExportOptions::default(),
1783 Some(&control),
1784 |p| {
1785 reported.push((p.current_frame, p.completed_frames, p.total_frames, p.label.clone()));
1786 if p.completed_frames >= 2 {
1787 ctrl_cb.cancel();
1788 }
1789 },
1790 )
1791 .expect_err("saver export should cancel early");
1792
1793 assert_eq!(err, "Cancelled");
1794 assert_eq!(reported.len(), 2);
1795 assert_eq!(reported[0].0, 10);
1796 assert_eq!(reported[0].1, 1);
1797 assert_eq!(reported[0].2, 6);
1798 assert_eq!(reported[0].3, "Saver1");
1799 assert_eq!(reported[1].0, 11);
1800 assert_eq!(reported[1].1, 2);
1801
1802 let snap = control.snapshot_progress();
1803 assert_eq!(snap.completed_frames, 2);
1804 assert_eq!(snap.total_frames, 6);
1805 assert!(snap.elapsed_secs >= 0.0);
1806 assert!(!tmp_dir.join("shot_0015.png").exists());
1807
1808 let _ = std::fs::remove_dir_all(&tmp_dir);
1809 }
1810
1811 #[test]
1812 fn video_export_reports_progress_and_cleans_up_on_cancel() {
1813 let tmp_dir = std::env::temp_dir().join(format!(
1814 "fission-video-cancel-test-{}",
1815 std::process::id()
1816 ));
1817 let _ = std::fs::remove_dir_all(&tmp_dir);
1818 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
1819
1820 let comp_src = r#"Composition {
1821 CurrentTime = 1,
1822 RenderRange = { 1, 12 },
1823 GlobalRange = { 0, 100 },
1824 Tools = ordered() {
1825 BG = Background {
1826 Inputs = {
1827 Width = Input { Value = 128, },
1828 Height = Input { Value = 72, },
1829 TopLeftRed = Input { Value = 0.2, },
1830 TopLeftGreen = Input { Value = 0.6, },
1831 TopLeftBlue = Input { Value = 0.9, },
1832 TopLeftAlpha = Input { Value = 1, },
1833 },
1834 },
1835 },
1836 Prefs = { Comp = { FrameFormat = { Width = 128, Height = 72, Rate = 24, DepthFull = 1 } } },
1837}"#;
1838
1839 let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic video comp");
1840 let target = comp.find_node("BG").expect("find BG node");
1841 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1842 let out_mp4 = tmp_dir.join("cancelled.mp4");
1843 let control = ExportControl::new();
1844 let ctrl_cb = control.clone();
1845 let mut seen = Vec::new();
1846
1847 let err = export_node_video_ffmpeg_with_progress(
1848 &mut engine,
1849 &comp,
1850 &VideoExportOptions {
1851 target,
1852 out_path: out_mp4.clone(),
1853 range: [1, 12],
1854 codec: VideoCodec::H264Share,
1855 crf: 26,
1856 max_height: None,
1857 include_audio: false,
1858 hiq: true,
1859 proxy_scale: 1,
1860 },
1861 Some(&control),
1862 |p| {
1863 seen.push((p.current_frame, p.completed_frames, p.total_frames, p.label.clone()));
1864 if p.completed_frames >= 3 {
1865 ctrl_cb.cancel();
1866 }
1867 },
1868 )
1869 .expect_err("video export should cancel early");
1870
1871 assert_eq!(err, "Cancelled");
1872 assert_eq!(seen.len(), 3);
1873 assert_eq!(seen[0].0, 1);
1874 assert_eq!(seen[0].1, 1);
1875 assert_eq!(seen[0].2, 12);
1876 assert_eq!(seen[0].3, "BG");
1877 assert_eq!(seen[2].0, 3);
1878 assert_eq!(seen[2].1, 3);
1879
1880 let snap = control.snapshot_progress();
1881 assert_eq!(snap.completed_frames, 3);
1882 assert_eq!(snap.total_frames, 12);
1883 assert!(!out_mp4.exists(), "partial mp4 should be removed after cancellation");
1884
1885 let _ = std::fs::remove_dir_all(&tmp_dir);
1886 }
1887
1888 #[test]
1889 fn video_export_handles_short_audio_past_eof_odd_dims_and_1x1_dummy() {
1890 let tmp_dir = std::env::temp_dir().join(format!(
1891 "fission-video-edge-cases-{}",
1892 std::process::id()
1893 ));
1894 let _ = std::fs::remove_dir_all(&tmp_dir);
1895 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
1896
1897 let short_wav = tmp_dir.join("short.wav");
1898 write_test_wav(&short_wav, 44100, 0.15);
1899 let wav_escaped = short_wav.to_string_lossy().replace('\\', "\\\\");
1900
1901 // 1. Short audio (0.15s) with 1.0s (24 frames @ 24fps) odd-dimension (127x71) video.
1902 let comp_src = format!(
1903 r#"Composition {{
1904 CurrentTime = 0,
1905 RenderRange = {{ 0, 23 }},
1906 GlobalRange = {{ 0, 23 }},
1907 AudioFilename = "{wav_escaped}",
1908 AudioOffset = 0,
1909 Tools = ordered() {{
1910 BG = Background {{
1911 Inputs = {{
1912 Width = Input {{ Value = 127, }},
1913 Height = Input {{ Value = 71, }},
1914 TopLeftRed = Input {{ Value = 0.4, }},
1915 TopLeftGreen = Input {{ Value = 0.5, }},
1916 TopLeftBlue = Input {{ Value = 0.6, }},
1917 TopLeftAlpha = Input {{ Value = 1, }},
1918 }},
1919 }},
1920 }},
1921 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 127, Height = 71, Rate = 24, DepthFull = 1 }} }} }},
1922}}"#
1923 );
1924 let comp = Comp::from_fusion_str(&comp_src).expect("parse odd+short-audio comp");
1925 let target = comp.find_node("BG").unwrap();
1926 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1927
1928 let short_mp4 = tmp_dir.join("short_audio_odd.mp4");
1929 let summary = export_node_video_ffmpeg(
1930 &mut engine,
1931 &comp,
1932 &VideoExportOptions {
1933 target,
1934 out_path: short_mp4.clone(),
1935 range: [0, 23],
1936 codec: VideoCodec::H264Share,
1937 crf: 26,
1938 max_height: None,
1939 include_audio: true,
1940 hiq: true,
1941 proxy_scale: 1,
1942 },
1943 |_| {},
1944 )
1945 .expect("export with short audio and odd dimensions should succeed without Broken pipe");
1946 assert_eq!(summary.frames_written, 24);
1947 assert_eq!(summary.width, 126);
1948 assert_eq!(summary.height, 70);
1949 assert!(summary.has_audio);
1950
1951 // 2. Audio start past EOF -> skips audio cleanly (`has_audio == false`).
1952 let mut past_eof_comp = comp.clone();
1953 past_eof_comp.audio_offset = -100.0; // start=0 -> audio_start_secs = +4.17s > 0.15s
1954 let past_mp4 = tmp_dir.join("past_eof.mp4");
1955 let past_summary = export_node_video_ffmpeg(
1956 &mut engine,
1957 &past_eof_comp,
1958 &VideoExportOptions {
1959 target,
1960 out_path: past_mp4.clone(),
1961 range: [0, 5],
1962 codec: VideoCodec::H264Share,
1963 crf: 26,
1964 max_height: None,
1965 include_audio: true,
1966 hiq: true,
1967 proxy_scale: 1,
1968 },
1969 |_| {},
1970 )
1971 .expect("export with audio past EOF should skip audio and succeed");
1972 assert_eq!(past_summary.frames_written, 6);
1973 assert!(!past_summary.has_audio);
1974
1975 // 3. First frame 1x1 dummy (Loader with missing frame 0, MissingFrames = 0) -> falls back to comp canvas.
1976 let seq1 = tmp_dir.join("seq_0001.png");
1977 image::RgbaImage::from_pixel(64, 36, image::Rgba([20, 200, 40, 255]))
1978 .save(&seq1)
1979 .unwrap();
1980 let seq0 = tmp_dir.join("seq_0000.png"); // intentionally absent
1981 let seq0_esc = seq0.to_string_lossy().replace('\\', "\\\\");
1982 let dummy_comp_src = format!(
1983 r#"Composition {{
1984 CurrentTime = 0,
1985 RenderRange = {{ 0, 1 }},
1986 GlobalRange = {{ 0, 1 }},
1987 Tools = ordered() {{
1988 LD = Loader {{
1989 Clips = {{
1990 Clip {{
1991 ID = "Clip1",
1992 Filename = "{seq0_esc}",
1993 FormatID = "PNGFormat",
1994 StartFrame = 0,
1995 Length = 2,
1996 GlobalStart = 0,
1997 GlobalEnd = 1,
1998 }},
1999 }},
2000 }},
2001 }},
2002 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 36, Rate = 24, DepthFull = 1 }} }} }},
2003}}"#
2004 );
2005 let dummy_comp = Comp::from_fusion_str(&dummy_comp_src).expect("parse dummy loader comp");
2006 let ld = dummy_comp.find_node("LD").unwrap();
2007 engine.bust_all_caches();
2008 let dummy_mp4 = tmp_dir.join("dummy_first.mp4");
2009 let dummy_summary = export_node_video_ffmpeg(
2010 &mut engine,
2011 &dummy_comp,
2012 &VideoExportOptions {
2013 target: ld,
2014 out_path: dummy_mp4.clone(),
2015 range: [0, 1],
2016 codec: VideoCodec::H264Share,
2017 crf: 26,
2018 max_height: None,
2019 include_audio: false,
2020 hiq: true,
2021 proxy_scale: 1,
2022 },
2023 |_| {},
2024 )
2025 .expect("export with 1x1 first frame should fall back to comp dimensions");
2026 assert_eq!(dummy_summary.frames_written, 2);
2027 assert_eq!(dummy_summary.width, 64);
2028 assert_eq!(dummy_summary.height, 36);
2029
2030 let _ = std::fs::remove_dir_all(&tmp_dir);
2031 }
2032
2033 #[test]
2034 fn video_export_cancel_preserves_existing_output_and_removes_temp_file() {
2035 let tmp_dir = std::env::temp_dir().join(format!(
2036 "fission-video-atomic-cancel-{}",
2037 std::process::id()
2038 ));
2039 let _ = std::fs::remove_dir_all(&tmp_dir);
2040 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
2041
2042 let out_mp4 = tmp_dir.join("existing.mp4");
2043 let sentinel_bytes = b"ORIGINAL_VALUABLE_EXPORT_BYTES_DO_NOT_TRUNCATE";
2044 std::fs::write(&out_mp4, sentinel_bytes).expect("write sentinel existing file");
2045
2046 let comp_src = r#"Composition {
2047 CurrentTime = 0,
2048 RenderRange = { 0, 9 },
2049 GlobalRange = { 0, 9 },
2050 Tools = ordered() {
2051 BG = Background {
2052 Inputs = {
2053 Width = Input { Value = 64, },
2054 Height = Input { Value = 64, },
2055 TopLeftRed = Input { Value = 0.8, },
2056 TopLeftAlpha = Input { Value = 1, },
2057 },
2058 },
2059 },
2060 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 64, Rate = 24, DepthFull = 1 } } },
2061}"#;
2062 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
2063 let target = comp.find_node("BG").expect("find BG");
2064 let mut engine = Engine::new_headless().expect("headless wgpu engine");
2065 let control = ExportControl::new();
2066 let ctrl_cb = control.clone();
2067
2068 let err = export_node_video_ffmpeg_with_progress(
2069 &mut engine,
2070 &comp,
2071 &VideoExportOptions {
2072 target,
2073 out_path: out_mp4.clone(),
2074 range: [0, 9],
2075 codec: VideoCodec::H264Share,
2076 crf: 26,
2077 max_height: None,
2078 include_audio: false,
2079 hiq: true,
2080 proxy_scale: 1,
2081 },
2082 Some(&control),
2083 |p| {
2084 if p.completed_frames >= 2 {
2085 ctrl_cb.cancel();
2086 }
2087 },
2088 )
2089 .expect_err("cancelled export should return Err");
2090 assert_eq!(err, "Cancelled");
2091
2092 let after_bytes = std::fs::read(&out_mp4).expect("existing output must still exist");
2093 assert_eq!(after_bytes.as_slice(), sentinel_bytes, "existing file must stay untouched");
2094
2095 let entries: Vec<_> = std::fs::read_dir(&tmp_dir)
2096 .expect("read tmp_dir")
2097 .filter_map(|e| e.ok())
2098 .map(|e| e.file_name().to_string_lossy().into_owned())
2099 .collect();
2100 assert_eq!(entries, vec!["existing.mp4".to_owned()], "no temp files should remain");
2101
2102 let _ = std::fs::remove_dir_all(&tmp_dir);
2103 }
2104
2105 #[test]
2106 fn pipelined_png_export_is_pixel_exact_and_propagates_write_errors() {
2107 let tmp_dir = std::env::temp_dir().join(format!(
2108 "fission-png-pipeline-exact-{}",
2109 std::process::id()
2110 ));
2111 let _ = std::fs::remove_dir_all(&tmp_dir);
2112 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
2113
2114 let saver_path = tmp_dir.join("out").join("frame_0000.png");
2115 let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\");
2116 let comp_src = format!(
2117 r#"Composition {{
2118 CurrentTime = 0,
2119 RenderRange = {{ 0, 5 }},
2120 GlobalRange = {{ 0, 5 }},
2121 Tools = ordered() {{
2122 BG = Background {{
2123 Inputs = {{
2124 Width = Input {{ Value = 96, }},
2125 Height = Input {{ Value = 48, }},
2126 TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }},
2127 TopLeftGreen = Input {{ Value = 0.5, }},
2128 TopLeftBlue = Input {{ Value = 0.25, }},
2129 TopLeftAlpha = Input {{ Value = 1.0, }},
2130 }},
2131 }},
2132 BGRed = BezierSpline {{
2133 KeyFrames = {{
2134 [0] = {{ 0.1, Flags = {{ Linear = true }} }},
2135 [5] = {{ 0.9, Flags = {{ Linear = true }} }},
2136 }},
2137 }},
2138 Saver1 = Saver {{
2139 Inputs = {{
2140 Clip = Input {{
2141 Value = Clip {{
2142 Filename = "{saver_path_escaped}",
2143 FormatID = "PNGFormat",
2144 Saving = true,
2145 }},
2146 }},
2147 Input = Input {{ SourceOp = "BG", Source = "Output", }},
2148 }},
2149 }},
2150 }},
2151 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 96, Height = 48, Rate = 24, DepthFull = 1 }} }} }},
2152}}"#
2153 );
2154
2155 let comp = Comp::from_fusion_str(&comp_src).expect("parse comp");
2156 let target = comp.find_node("BG").unwrap();
2157 let mut engine = Engine::new_headless().expect("headless wgpu engine");
2158
2159 let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |_| {})
2160 .expect("export png sequence");
2161 assert_eq!(summary.frames_written, 6);
2162
2163 // Verify fast-compressed PNGs decode byte-identically to direct GPU readback.
2164 for f in 0..=5 {
2165 let (tex, _) = engine.evaluate(&comp, target, f as f64);
2166 let expected = engine.readback_rgba(&tex).expect("readback");
2167 let png_path = tmp_dir.join("out").join(format!("frame_{f:04}.png"));
2168 let decoded = image::open(&png_path).expect("decode png").to_rgba8();
2169 assert_eq!(decoded.dimensions(), (tex.size[0], tex.size[1]));
2170 assert_eq!(
2171 decoded.into_raw(),
2172 expected,
2173 "fast PNG encode must be 100% lossless at frame {f}"
2174 );
2175 }
2176
2177 // Verify worker write error propagates cleanly: point out_dir_override inside a regular file.
2178 let blocking_file = tmp_dir.join("not_a_dir");
2179 std::fs::write(&blocking_file, b"file").expect("write blocking file");
2180 let err = export_saver_png_sequence(
2181 &mut engine,
2182 &comp,
2183 &ExportOptions {
2184 out_dir_override: Some(blocking_file),
2185 ..ExportOptions::default()
2186 },
2187 |_| {},
2188 )
2189 .expect_err("writing into a regular file path must return Err");
2190 assert!(!err.is_empty());
2191
2192 let _ = std::fs::remove_dir_all(&tmp_dir);
2193 }
2194
2195 #[test]
2196 fn videotoolbox_probe_selection_and_fallback() {
2197 let sample_both = "\
2198Encoders:
2199 V..... = Video
2200 ------
2201 V....D libx264 libx264 H.264 / AVC
2202 V....D h264_videotoolbox VideoToolbox H.264 Encoder (codec h264)
2203 VFS... prores_ks Apple ProRes (iCodec Pro) (codec prores)
2204 V....D prores_videotoolbox VideoToolbox ProRes Encoder (codec prores)
2205 A....D aac AAC (Advanced Audio Coding)
2206";
2207 let vt_both = parse_videotoolbox_encoders(sample_both);
2208 assert_eq!(vt_both, VideoToolboxSupport { h264: true, prores: true });
2209
2210 let sample_h264_only = " V....D h264_videotoolbox VideoToolbox H.264 Encoder\n";
2211 assert_eq!(
2212 parse_videotoolbox_encoders(sample_h264_only),
2213 VideoToolboxSupport { h264: true, prores: false }
2214 );
2215 assert_eq!(
2216 parse_videotoolbox_encoders(" V....D libx264 H.264\n"),
2217 VideoToolboxSupport::default()
2218 );
2219
2220 // Hardware selection when supported and allowed
2221 assert_eq!(
2222 select_video_encoder(VideoCodec::H264Share, vt_both, true),
2223 VideoEncoder::H264VideoToolbox
2224 );
2225 assert_eq!(
2226 select_video_encoder(VideoCodec::ProRes422, vt_both, true),
2227 VideoEncoder::ProResVideoToolbox422
2228 );
2229 assert_eq!(
2230 select_video_encoder(VideoCodec::ProRes4444, vt_both, true),
2231 VideoEncoder::ProResVideoToolbox4444
2232 );
2233
2234 // Fallback when VideoToolbox is unavailable or disabled after failure
2235 assert_eq!(
2236 select_video_encoder(VideoCodec::H264Share, vt_both, false),
2237 VideoEncoder::Libx264
2238 );
2239 assert_eq!(
2240 select_video_encoder(VideoCodec::ProRes422, vt_both, false),
2241 VideoEncoder::ProResKs422
2242 );
2243 assert_eq!(
2244 select_video_encoder(VideoCodec::ProRes4444, vt_both, false),
2245 VideoEncoder::ProResKs4444
2246 );
2247 assert_eq!(
2248 select_video_encoder(VideoCodec::H264Share, VideoToolboxSupport::default(), true),
2249 VideoEncoder::Libx264
2250 );
2251
2252 assert_eq!(vt_quality_from_crf(0), 95);
2253 assert_eq!(vt_quality_from_crf(26), 52);
2254 assert_eq!(vt_quality_from_crf(51), 15);
2255
2256 let mut args = Vec::new();
2257 push_video_encoder_args(&mut args, VideoEncoder::H264VideoToolbox, 26, Some("scale=trunc(iw/2)*2:trunc(ih/2)*2"));
2258 assert!(args.windows(2).any(|w| w == ["-c:v", "h264_videotoolbox"]));
2259 assert!(args.windows(2).any(|w| w == ["-q:v", "52"]));
2260 assert!(args.windows(2).any(|w| w == ["-tag:v", "avc1"]));
2261 assert!(args.windows(2).any(|w| w == ["-pix_fmt", "yuv420p"]));
2262
2263 args.clear();
2264 push_video_encoder_args(&mut args, VideoEncoder::Libx264, 26, Some("scale=trunc(iw/2)*2:trunc(ih/2)*2"));
2265 assert!(args.windows(2).any(|w| w == ["-c:v", "libx264"]));
2266 assert!(args.windows(2).any(|w| w == ["-crf", "26"]));
2267
2268 args.clear();
2269 push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox422, 26, None);
2270 assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"]));
2271 assert!(args.windows(2).any(|w| w == ["-profile:v", "2"]));
2272 assert!(args.windows(2).any(|w| w == ["-pix_fmt", "p210le"]));
2273
2274 args.clear();
2275 push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox4444, 26, None);
2276 assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"]));
2277 assert!(args.windows(2).any(|w| w == ["-profile:v", "4"]));
2278 assert!(args.windows(2).any(|w| w == ["-pix_fmt", "ayuv64le"]));
2279 }
2280
2281 #[test]
2282 fn fit_frame_rgba_zero_copy_fast_path_and_resize() {
2283 let pixels = vec![128u8; 8 * 4 * 4];
2284 let orig_ptr = pixels.as_ptr();
2285 let moved = fit_frame_rgba(pixels, [8, 4], [8, 4], 0).expect("matching size fast path");
2286 assert_eq!(moved.as_ptr(), orig_ptr, "matching size must move Vec without copying");
2287
2288 let resized = fit_frame_rgba(moved, [8, 4], [4, 2], 1).expect("resize path");
2289 assert_eq!(resized.len(), 4 * 2 * 4);
2290
2291 let err = fit_frame_rgba(vec![0u8; 10], [8, 4], [8, 4], 2)
2292 .expect_err("mismatched RGBA byte length must fail");
2293 assert!(err.contains("invalid RGBA buffer size"));
2294 }
2295
2296 #[test]
2297 fn prores_4444_preserves_alpha_channel() {
2298 let tmp_dir = std::env::temp_dir().join(format!(
2299 "fission-prores4444-alpha-{}",
2300 std::process::id()
2301 ));
2302 let _ = std::fs::remove_dir_all(&tmp_dir);
2303 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
2304
2305 let comp_src = r#"Composition {
2306 CurrentTime = 0,
2307 RenderRange = { 0, 1 },
2308 GlobalRange = { 0, 1 },
2309 Tools = ordered() {
2310 BG = Background {
2311 Inputs = {
2312 Width = Input { Value = 64, },
2313 Height = Input { Value = 36, },
2314 TopLeftRed = Input { Value = 0.8, },
2315 TopLeftGreen = Input { Value = 0.4, },
2316 TopLeftBlue = Input { Value = 0.2, },
2317 TopLeftAlpha = Input { SourceOp = "BGAlpha", Source = "Value", },
2318 },
2319 },
2320 BGAlpha = BezierSpline {
2321 KeyFrames = {
2322 [0] = { 0.25, Flags = { Linear = true } },
2323 [1] = { 0.75, Flags = { Linear = true } },
2324 },
2325 },
2326 },
2327 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } },
2328}"#;
2329 let comp = Comp::from_fusion_str(comp_src).expect("parse alpha ProRes comp");
2330 let target = comp.find_node("BG").expect("find BG");
2331 let mut engine = Engine::new_headless().expect("headless wgpu engine");
2332
2333 let out_mov = tmp_dir.join("alpha_4444.mov");
2334 let summary = export_node_video_ffmpeg(
2335 &mut engine,
2336 &comp,
2337 &VideoExportOptions {
2338 target,
2339 out_path: out_mov.clone(),
2340 range: [0, 1],
2341 codec: VideoCodec::ProRes4444,
2342 crf: 26,
2343 max_height: None,
2344 include_audio: false,
2345 hiq: true,
2346 proxy_scale: 1,
2347 },
2348 |_| {},
2349 )
2350 .expect("export ProRes 4444");
2351 assert_eq!(summary.frames_written, 2);
2352 assert_eq!(summary.width, 64);
2353 assert_eq!(summary.height, 36);
2354
2355 let probe = Command::new("ffprobe")
2356 .args([
2357 "-v",
2358 "error",
2359 "-show_entries",
2360 "stream=codec_name,profile,pix_fmt",
2361 "-of",
2362 "csv=p=0",
2363 ])
2364 .arg(&out_mov)
2365 .output()
2366 .expect("run ffprobe");
2367 assert!(probe.status.success());
2368 let probe_out = String::from_utf8_lossy(&probe.stdout);
2369 assert!(
2370 probe_out.contains("prores") && probe_out.contains("4444") && probe_out.contains("yuva"),
2371 "expected ProRes 4444 with alpha pixel format, got: {probe_out}"
2372 );
2373
2374 let dec = Command::new("ffmpeg")
2375 .args(["-v", "error", "-i"])
2376 .arg(&out_mov)
2377 .args(["-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1"])
2378 .output()
2379 .expect("decode ProRes 4444 to rgba");
2380 assert!(dec.status.success());
2381 let frame_bytes = 64 * 36 * 4;
2382 assert_eq!(dec.stdout.len(), frame_bytes * 2);
2383
2384 let a0 = dec.stdout[3];
2385 let a1 = dec.stdout[frame_bytes + 3];
2386 assert!(
2387 (i32::from(a0) - 64).abs() <= 2,
2388 "frame 0 alpha should be ~64 (0.25), got {a0}"
2389 );
2390 assert!(
2391 (i32::from(a1) - 191).abs() <= 2,
2392 "frame 1 alpha should be ~191 (0.75), got {a1}"
2393 );
2394
2395 let _ = std::fs::remove_dir_all(&tmp_dir);
2396 }
2397
2398 #[test]
2399 fn prores_422_and_software_fallback_encoders_produce_valid_streams() {
2400 let tmp_dir = std::env::temp_dir().join(format!(
2401 "fission-prores422-fallback-{}",
2402 std::process::id()
2403 ));
2404 let _ = std::fs::remove_dir_all(&tmp_dir);
2405 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
2406
2407 let comp_src = r#"Composition {
2408 CurrentTime = 0,
2409 RenderRange = { 0, 2 },
2410 GlobalRange = { 0, 2 },
2411 Tools = ordered() {
2412 BG = Background {
2413 Inputs = {
2414 Width = Input { Value = 64, },
2415 Height = Input { Value = 36, },
2416 TopLeftRed = Input { Value = 0.2, },
2417 TopLeftGreen = Input { Value = 0.7, },
2418 TopLeftBlue = Input { Value = 0.3, },
2419 TopLeftAlpha = Input { Value = 1.0, },
2420 },
2421 },
2422 },
2423 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } },
2424}"#;
2425 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
2426 let target = comp.find_node("BG").expect("find BG");
2427 let mut engine = Engine::new_headless().expect("headless wgpu engine");
2428
2429 let prores422_mov = tmp_dir.join("prores422.mov");
2430 let summary_422 = export_node_video_ffmpeg(
2431 &mut engine,
2432 &comp,
2433 &VideoExportOptions {
2434 target,
2435 out_path: prores422_mov.clone(),
2436 range: [0, 2],
2437 codec: VideoCodec::ProRes422,
2438 crf: 26,
2439 max_height: None,
2440 include_audio: false,
2441 hiq: true,
2442 proxy_scale: 1,
2443 },
2444 |_| {},
2445 )
2446 .expect("export ProRes 422");
2447 assert_eq!(summary_422.frames_written, 3);
2448
2449 let probe_422 = Command::new("ffprobe")
2450 .args(["-v", "error", "-count_frames", "-show_entries", "stream=codec_name,profile,nb_read_frames", "-of", "csv=p=0"])
2451 .arg(&prores422_mov)
2452 .output()
2453 .expect("ffprobe prores 422");
2454 assert!(probe_422.status.success());
2455 let out_422 = String::from_utf8_lossy(&probe_422.stdout);
2456 assert!(
2457 out_422.contains("prores") && out_422.contains("Standard") && out_422.contains(",3"),
2458 "expected ProRes 422 Standard with 3 frames, got: {out_422}"
2459 );
2460
2461 // Directly verify software fallback encoders (Libx264 and ProResKs422)
2462 let sw_mp4 = tmp_dir.join("sw_libx264.mp4");
2463 let mut noop = |_| {};
2464 let sw_summary = export_node_video_ffmpeg_with_encoder(
2465 &mut engine,
2466 &comp,
2467 &VideoExportOptions {
2468 target,
2469 out_path: sw_mp4.clone(),
2470 range: [0, 2],
2471 codec: VideoCodec::H264Share,
2472 crf: 26,
2473 max_height: None,
2474 include_audio: false,
2475 hiq: true,
2476 proxy_scale: 1,
2477 },
2478 None,
2479 &mut noop,
2480 VideoEncoder::Libx264,
2481 Instant::now(),
2482 )
2483 .expect("software libx264 fallback export");
2484 assert_eq!(sw_summary.frames_written, 3);
2485 assert!(sw_mp4.exists());
2486
2487 let sw_mov = tmp_dir.join("sw_prores_ks.mov");
2488 let sw_prores = export_node_video_ffmpeg_with_encoder(
2489 &mut engine,
2490 &comp,
2491 &VideoExportOptions {
2492 target,
2493 out_path: sw_mov.clone(),
2494 range: [0, 2],
2495 codec: VideoCodec::ProRes422,
2496 crf: 26,
2497 max_height: None,
2498 include_audio: false,
2499 hiq: true,
2500 proxy_scale: 1,
2501 },
2502 None,
2503 &mut noop,
2504 VideoEncoder::ProResKs422,
2505 Instant::now(),
2506 )
2507 .expect("software prores_ks fallback export");
2508 assert_eq!(sw_prores.frames_written, 3);
2509 assert!(sw_mov.exists());
2510
2511 let _ = std::fs::remove_dir_all(&tmp_dir);
2512 }
2513
2514 #[test]
2515 fn h264_max_height_out_width_matches_ffmpeg_scale_neg2_rounding() {
2516 // 101x100 with max_height >= 100: scale=-2 rounds 101.0/2 = 50.5 -> 51 * 2 = 102
2517 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(100));
2518 assert_eq!((w, h), (102, 100));
2519 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(200));
2520 assert_eq!((w, h), (102, 100));
2521 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(50));
2522 assert_eq!((w, h), (50, 50));
2523
2524 // 1000x750 downscaled: 1000*700/750 = 933.33 -> nearest even 934; 1000*400/750 = 533.33 -> 534; 1000*500/750 = 666.67 -> 666
2525 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(700));
2526 assert_eq!((w, h), (934, 700));
2527 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(400));
2528 assert_eq!((w, h), (534, 400));
2529 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(500));
2530 assert_eq!((w, h), (666, 500));
2531 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(750));
2532 assert_eq!((w, h), (1000, 750));
2533
2534 // Without max_height, trunc(iw/2)*2:trunc(ih/2)*2 truncates odd dimensions downward
2535 let (_, w, h) = h264_scale_filter_and_dims(101, 100, None);
2536 assert_eq!((w, h), (100, 100));
2537 }
2538
2539 #[test]
2540 fn video_export_cancel_on_final_frame_progress_cancels_cleanly() {
2541 let tmp_dir = std::env::temp_dir().join(format!(
2542 "fission-video-cancel-final-{}",
2543 std::process::id()
2544 ));
2545 let _ = std::fs::remove_dir_all(&tmp_dir);
2546 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
2547
2548 let comp_src = r#"Composition {
2549 CurrentTime = 0,
2550 RenderRange = { 0, 2 },
2551 GlobalRange = { 0, 2 },
2552 Tools = ordered() {
2553 BG = Background {
2554 Inputs = {
2555 Width = Input { Value = 64, },
2556 Height = Input { Value = 36, },
2557 TopLeftRed = Input { Value = 0.5, },
2558 TopLeftAlpha = Input { Value = 1, },
2559 },
2560 },
2561 },
2562 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } },
2563}"#;
2564 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
2565 let target = comp.find_node("BG").expect("find BG");
2566 let mut engine = Engine::new_headless().expect("headless wgpu engine");
2567 let out_mp4 = tmp_dir.join("final_cancel.mp4");
2568 let control = ExportControl::new();
2569 let ctrl_cb = control.clone();
2570
2571 let err = export_node_video_ffmpeg_with_progress(
2572 &mut engine,
2573 &comp,
2574 &VideoExportOptions {
2575 target,
2576 out_path: out_mp4.clone(),
2577 range: [0, 2],
2578 codec: VideoCodec::H264Share,
2579 crf: 26,
2580 max_height: None,
2581 include_audio: false,
2582 hiq: true,
2583 proxy_scale: 1,
2584 },
2585 Some(&control),
2586 |p| {
2587 if p.completed_frames == p.total_frames {
2588 ctrl_cb.cancel();
2589 }
2590 },
2591 )
2592 .expect_err("cancelling on final frame callback must return Cancelled");
2593 assert_eq!(err, "Cancelled");
2594 assert!(!out_mp4.exists(), "cancelled export must not publish output file");
2595
2596 let _ = std::fs::remove_dir_all(&tmp_dir);
2597 }
2598}
crates/engine/src/export/png.rs created+442
......@@ -0,0 +1,442 @@
1//! Lossless RGBA8 PNG encoding and pipelined multi-threaded PNG sequence export.
2
3use super::{
4 ExportControl, ExportOptions, ExportProgress, ExportSummary, make_progress, select_saver,
5};
6use crate::cache::EvalStats;
7use crate::eval::Engine;
8use model::{Comp, NodeId, SaverSpec};
9use std::path::{Path, PathBuf};
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{Arc, Mutex, mpsc};
12use std::time::Instant;
13
14fn resolve_output_path(
15 saver: &SaverSpec,
16 frame: i64,
17 out_dir_override: Option<&Path>,
18) -> Result<PathBuf, String> {
19 if saver.filename.is_empty() {
20 let dir = out_dir_override.ok_or_else(|| {
21 format!(
22 "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)",
23 saver.name
24 )
25 })?;
26 return Ok(dir.join(format!("{frame:04}.png")));
27 }
28 let frame_path = saver.frame_path(frame);
29 if let Some(dir) = out_dir_override {
30 let fname = frame_path
31 .file_name()
32 .map(PathBuf::from)
33 .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.png")));
34 Ok(dir.join(fname))
35 } else {
36 Ok(frame_path)
37 }
38}
39
40/// Encodes an RGBA8 image into `out` as a lossless PNG matching Fusion's default
41/// libpng compression (`Compression::Balanced` = zlib level 6 + `Filter::Adaptive`).
42pub fn encode_png_rgba8_into(size: [u32; 2], pixels: &[u8], out: &mut Vec<u8>) -> Result<(), String> {
43 out.clear();
44 if out.capacity() == 0 {
45 out.reserve(pixels.len() / 2);
46 }
47 let mut enc = ::png::Encoder::new(&mut *out, size[0], size[1]);
48 enc.set_color(::png::ColorType::Rgba);
49 enc.set_depth(::png::BitDepth::Eight);
50 enc.set_compression(::png::Compression::Balanced);
51 enc.set_filter(::png::Filter::Adaptive);
52 let mut png_w = enc
53 .write_header()
54 .map_err(|e| format!("failed to write PNG header: {e}"))?;
55 png_w
56 .write_image_data(pixels)
57 .map_err(|e| format!("failed to write PNG data: {e}"))?;
58 Ok(())
59}
60
61/// Encodes and writes an RGBA8 PNG using a reusable staging buffer and cached parent directory.
62pub fn write_png_fast_buffered(
63 path: &Path,
64 size: [u32; 2],
65 pixels: &[u8],
66 staging: &mut Vec<u8>,
67 last_parent: &mut Option<PathBuf>,
68) -> Result<(), String> {
69 if let Some(parent) = path.parent() {
70 if !parent.as_os_str().is_empty() && last_parent.as_deref() != Some(parent) {
71 std::fs::create_dir_all(parent)
72 .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
73 *last_parent = Some(parent.to_path_buf());
74 }
75 }
76 encode_png_rgba8_into(size, pixels, staging)
77 .map_err(|e| format!("{e} ('{}')", path.display()))?;
78 std::fs::write(path, staging.as_slice())
79 .map_err(|e| format!("failed to write '{}': {e}", path.display()))?;
80 Ok(())
81}
82
83fn write_png_fast(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), String> {
84 let mut staging = Vec::with_capacity(pixels.len() / 2);
85 let mut last_parent = None;
86 write_png_fast_buffered(path, size, pixels, &mut staging, &mut last_parent)
87}
88
89struct EncodeJob {
90 path: PathBuf,
91 size: [u32; 2],
92 pixels: Vec<u8>,
93}
94
95/// Evaluates `target` at `frame` on GPU and saves a single RGBA8 PNG to `out_path`.
96pub fn export_node_frame_png(
97 engine: &mut Engine,
98 comp: &Comp,
99 target: NodeId,
100 frame: f64,
101 out_path: &Path,
102) -> Result<PathBuf, String> {
103 if target.0 >= comp.nodes.len() {
104 return Err(format!("invalid target node id {}", target.0));
105 }
106 let (tex, _) = engine.evaluate(comp, target, frame);
107 let pixels = engine
108 .readback_rgba(&tex)
109 .map_err(|e| format!("GPU readback failed at frame {frame}: {e}"))?;
110 write_png_fast(out_path, tex.size, &pixels)?;
111 Ok(out_path.to_path_buf())
112}
113
114/// Renders and writes a PNG sequence for an arbitrary `target` node across `range`
115/// (`[start, end]` inclusive) using double-buffered async GPU readback, recycled RGBA
116/// pixel buffers, 12-frame media prefetch, and a bounded background PNG encoder pool.
117#[allow(clippy::too_many_arguments)]
118pub fn export_node_png_sequence_with_progress(
119 engine: &mut Engine,
120 comp: &Comp,
121 target: NodeId,
122 range: [i64; 2],
123 path_for_frame: impl Fn(i64) -> Result<PathBuf, String>,
124 label: String,
125 hiq: bool,
126 proxy_scale: u32,
127 png_workers: usize,
128 control: Option<&ExportControl>,
129 mut on_progress: impl FnMut(&ExportProgress),
130) -> Result<ExportSummary, String> {
131 if control.is_some_and(ExportControl::is_cancelled) {
132 return Err("Cancelled".to_owned());
133 }
134 if target.0 >= comp.nodes.len() {
135 return Err(format!("invalid target node id {}", target.0));
136 }
137 let [start, end] = range;
138 let total_i128 = i128::from(end) - i128::from(start) + 1;
139 if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) {
140 return Err(format!("invalid export frame range {start}..={end}"));
141 }
142
143 let prev_hiq = engine.hiq;
144 let prev_proxy = engine.proxy_scale;
145 engine.hiq = hiq;
146 engine.proxy_scale = proxy_scale.max(1);
147
148 let total = total_i128 as usize;
149 let workers = if png_workers > 0 {
150 png_workers.clamp(1, 24)
151 } else {
152 std::thread::available_parallelism()
153 .map(|n| n.get().clamp(2, 24))
154 .unwrap_or(4)
155 }
156 .min(total.max(1));
157
158 let t0 = Instant::now();
159 let mut first_path: Option<PathBuf> = None;
160 let mut last_path: Option<PathBuf> = None;
161 let mut frames_written: usize = 0;
162
163 let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
164 let failed = Arc::new(AtomicBool::new(false));
165 let cancelled = Arc::new(AtomicBool::new(false));
166
167 let eval_result: Result<(), String> = std::thread::scope(|scope| {
168 let queue_cap = (workers * 2).clamp(16, 48);
169 let (tx, rx) = mpsc::sync_channel::<EncodeJob>(queue_cap);
170 let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + workers);
171 let shared_rx = Arc::new(Mutex::new(rx));
172
173 let mut handles = Vec::with_capacity(workers);
174 for _ in 0..workers {
175 let rx_c = Arc::clone(&shared_rx);
176 let recycle_c = recycle_tx.clone();
177 let err_c = Arc::clone(&first_err);
178 let fail_c = Arc::clone(&failed);
179 let cancel_c = Arc::clone(&cancelled);
180 handles.push(scope.spawn(move || {
181 let mut staging = Vec::new();
182 let mut last_parent: Option<PathBuf> = None;
183 loop {
184 let job = {
185 let Ok(guard) = rx_c.lock() else { break };
186 guard.recv()
187 };
188 let Ok(job) = job else { break };
189 if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) {
190 continue;
191 }
192 if let Err(e) = write_png_fast_buffered(
193 &job.path,
194 job.size,
195 &job.pixels,
196 &mut staging,
197 &mut last_parent,
198 ) {
199 if let Ok(mut g) = err_c.lock() {
200 if g.is_none() {
201 *g = Some(e);
202 }
203 }
204 fail_c.store(true, Ordering::Release);
205 }
206 let _ = recycle_c.try_send(job.pixels);
207 }
208 }));
209 }
210 drop(recycle_tx);
211
212 let mut loop_err: Option<String> = None;
213 const PREFETCH_LOOKAHEAD: usize = 12;
214 engine.prewarm_for_depth(comp.depth_full);
215 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
216 if start < end {
217 let seed_start = start.saturating_add(1);
218 let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end);
219 for (k, f) in (seed_start..=seed_end).enumerate() {
220 prefetch.enqueue_frame(
221 comp,
222 target,
223 k + 1,
224 f as f64,
225 &engine.expr,
226 engine.use_proxy_clips,
227 );
228 }
229 }
230 // Double-buffered async GPU readback: frame N+1 evaluates/submits on GPU while
231 // frame N finishes its copy/map and hands off to the background PNG writer pool.
232 let mut pending: Option<(
233 crate::eval::PendingReadback,
234 i64,
235 usize,
236 PathBuf,
237 [u32; 2],
238 EvalStats,
239 )> = None;
240 for (idx, frame) in (start..=end).enumerate() {
241 if failed.load(Ordering::Acquire) {
242 break;
243 }
244 if control.is_some_and(ExportControl::is_cancelled) {
245 cancelled.store(true, Ordering::Release);
246 break;
247 }
248 prefetch.set_current_seq(idx);
249 if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) {
250 if ahead_frame <= end {
251 prefetch.enqueue_frame(
252 comp,
253 target,
254 idx + PREFETCH_LOOKAHEAD,
255 ahead_frame as f64,
256 &engine.expr,
257 engine.use_proxy_clips,
258 );
259 }
260 }
261 let out_path = match path_for_frame(frame) {
262 Ok(p) => p,
263 Err(e) => {
264 loop_err = Some(e);
265 break;
266 }
267 };
268
269 let (tex, stats) = engine.evaluate(comp, target, frame as f64);
270 let next_rb = match engine.begin_readback_rgba(&tex) {
271 Ok(rb) => rb,
272 Err(e) => {
273 loop_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
274 break;
275 }
276 };
277 if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_stats)) =
278 pending.replace((next_rb, frame, idx, out_path, tex.size, stats))
279 {
280 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
281 if let Err(e) = prev_rb.finish_into(engine, &mut pixels) {
282 loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
283 break;
284 }
285 if control.is_some_and(ExportControl::is_cancelled) {
286 cancelled.store(true, Ordering::Release);
287 break;
288 }
289 if first_path.is_none() {
290 first_path = Some(prev_path.clone());
291 }
292 last_path = Some(prev_path.clone());
293 let prog = make_progress(
294 prev_frame,
295 prev_idx,
296 total,
297 prev_stats,
298 prev_path.clone(),
299 label.clone(),
300 t0,
301 );
302 if let Some(ctrl) = control {
303 ctrl.update_progress(&prog);
304 }
305 on_progress(&prog);
306 if tx
307 .send(EncodeJob {
308 path: prev_path,
309 size: prev_size,
310 pixels,
311 })
312 .is_err()
313 {
314 break;
315 }
316 frames_written += 1;
317 }
318 }
319 if loop_err.is_none() && !failed.load(Ordering::Acquire) && !cancelled.load(Ordering::Acquire)
320 {
321 if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_stats)) =
322 pending.take()
323 {
324 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
325 match prev_rb.finish_into(engine, &mut pixels) {
326 Ok(()) => {
327 if control.is_some_and(ExportControl::is_cancelled) {
328 cancelled.store(true, Ordering::Release);
329 } else {
330 if first_path.is_none() {
331 first_path = Some(prev_path.clone());
332 }
333 last_path = Some(prev_path.clone());
334 let prog = make_progress(
335 prev_frame,
336 prev_idx,
337 total,
338 prev_stats,
339 prev_path.clone(),
340 label.clone(),
341 t0,
342 );
343 if let Some(ctrl) = control {
344 ctrl.update_progress(&prog);
345 }
346 on_progress(&prog);
347 if tx
348 .send(EncodeJob {
349 path: prev_path,
350 size: prev_size,
351 pixels,
352 })
353 .is_ok()
354 {
355 frames_written += 1;
356 }
357 }
358 }
359 Err(e) => {
360 loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
361 }
362 }
363 }
364 }
365
366 drop(prefetch);
367 drop(tx);
368 for h in handles {
369 let _ = h.join();
370 }
371
372 if let Some(e) = loop_err {
373 return Err(e);
374 }
375 if let Ok(mut g) = first_err.lock() {
376 if let Some(e) = g.take() {
377 return Err(e);
378 }
379 }
380 if cancelled.load(Ordering::Acquire) {
381 return Err("Cancelled".to_owned());
382 }
383 Ok(())
384 });
385
386 engine.hiq = prev_hiq;
387 engine.proxy_scale = prev_proxy;
388
389 eval_result?;
390
391 Ok(ExportSummary {
392 saver_name: label,
393 frames_written,
394 total_ms: t0.elapsed().as_secs_f64() * 1000.0,
395 first_path,
396 last_path,
397 })
398}
399
400/// Renders and writes a PNG sequence driven by a Fusion `Saver` node.
401///
402/// GPU evaluation runs on the caller's thread while PNG compression and disk I/O run
403/// concurrently on a bounded pool of background worker threads.
404pub fn export_saver_png_sequence(
405 engine: &mut Engine,
406 comp: &Comp,
407 opts: &ExportOptions,
408 on_progress: impl FnMut(&ExportProgress),
409) -> Result<ExportSummary, String> {
410 export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress)
411}
412
413/// Renders and writes a PNG sequence driven by a Fusion `Saver` node with cooperative
414/// cancellation and live progress reporting via `ExportControl`.
415pub fn export_saver_png_sequence_with_progress(
416 engine: &mut Engine,
417 comp: &Comp,
418 opts: &ExportOptions,
419 control: Option<&ExportControl>,
420 on_progress: impl FnMut(&ExportProgress),
421) -> Result<ExportSummary, String> {
422 if control.is_some_and(ExportControl::is_cancelled) {
423 return Err("Cancelled".to_owned());
424 }
425 let saver = select_saver(comp, opts.saver_name.as_deref())?;
426 let target: NodeId = saver.upstream.unwrap_or(saver.node_id);
427 let range = opts.range_override.unwrap_or(saver.range);
428 let out_dir_override = opts.out_dir_override.as_deref();
429 export_node_png_sequence_with_progress(
430 engine,
431 comp,
432 target,
433 range,
434 |frame| resolve_output_path(&saver, frame, out_dir_override),
435 saver.name.clone(),
436 opts.hiq,
437 opts.proxy_scale,
438 opts.png_workers,
439 control,
440 on_progress,
441 )
442}
crates/engine/src/export/tests.rs created+1286
......@@ -0,0 +1,1286 @@
1use super::video::{
2 VideoEncoder, VideoToolboxSupport, export_node_video_ffmpeg_with_encoder, fit_frame_rgba,
3 h264_scale_filter_and_dims, parse_videotoolbox_encoders, push_video_encoder_args,
4 select_video_encoder, vt_quality_from_crf,
5};
6use super::*;
7use crate::eval::Engine;
8use model::Comp;
9use std::path::Path;
10use std::process::Command;
11use std::time::Instant;
12
13#[test]
14fn exports_saver_png_sequence_animated() {
15 let tmp_dir = std::env::temp_dir().join(format!(
16 "fission-saver-export-test-{}",
17 std::process::id()
18 ));
19 let _ = std::fs::remove_dir_all(&tmp_dir);
20 let saver_path = tmp_dir.join("nested").join("shot_0000.png");
21 let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\");
22
23 let comp_src = format!(
24 r#"Composition {{
25 CurrentTime = 10,
26 RenderRange = {{ 10, 12 }},
27 GlobalRange = {{ 0, 100 }},
28 Tools = ordered() {{
29 BG = Background {{
30 Inputs = {{
31 Width = Input {{ Value = 64, }},
32 Height = Input {{ Value = 32, }},
33 TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }},
34 TopLeftGreen = Input {{ Value = 0.25, }},
35 TopLeftBlue = Input {{ Value = 0.5, }},
36 TopLeftAlpha = Input {{ Value = 1, }},
37 }},
38 }},
39 BGRed = BezierSpline {{
40 KeyFrames = {{
41 [10] = {{ 0.0, Flags = {{ Linear = true }} }},
42 [12] = {{ 1.0, Flags = {{ Linear = true }} }},
43 }},
44 }},
45 Saver1 = Saver {{
46 Inputs = {{
47 Clip = Input {{
48 Value = Clip {{
49 Filename = "{saver_path_escaped}",
50 FormatID = "PNGFormat",
51 Saving = true,
52 }},
53 }},
54 Input = Input {{
55 SourceOp = "BG",
56 Source = "Output",
57 }},
58 }},
59 }},
60 }},
61 Prefs = {{
62 Comp = {{
63 FrameFormat = {{
64 Width = 64,
65 Height = 32,
66 Rate = 30,
67 DepthFull = 1,
68 }},
69 }},
70 }},
71}}"#
72 );
73
74 let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp");
75 let mut engine = Engine::new_headless().expect("headless wgpu engine");
76
77 let mut seen_frames = Vec::new();
78 let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |p| {
79 seen_frames.push(p.frame);
80 })
81 .expect("export png sequence");
82
83 assert_eq!(summary.saver_name, "Saver1");
84 assert_eq!(summary.frames_written, 3);
85 assert_eq!(seen_frames, vec![10, 11, 12]);
86
87 let expected_reds = [0u8, 128u8, 255u8];
88 for (frame, exp_r) in [10i64, 11, 12].into_iter().zip(expected_reds) {
89 let p = tmp_dir.join("nested").join(format!("shot_{frame:04}.png"));
90 assert!(p.exists(), "missing exported frame {}", p.display());
91 let img = image::open(&p).expect("decode exported PNG").to_rgba8();
92 assert_eq!(img.dimensions(), (64, 32));
93 let px = img.get_pixel(32, 16);
94 assert!(
95 (px[0] as i32 - exp_r as i32).abs() <= 2,
96 "frame {frame}: expected R~{exp_r}, got {:?}",
97 px.0
98 );
99 assert!((px[1] as i32 - 64).abs() <= 2);
100 assert!((px[2] as i32 - 128).abs() <= 2);
101 assert_eq!(px[3], 255);
102 }
103
104 let _ = std::fs::remove_dir_all(&tmp_dir);
105}
106
107#[test]
108fn exports_node_png_sequence_directly_with_eval_stats() {
109 let tmp_dir = std::env::temp_dir().join(format!(
110 "fission-node-png-seq-test-{}",
111 std::process::id()
112 ));
113 let _ = std::fs::remove_dir_all(&tmp_dir);
114
115 let comp_src = r#"Composition {
116 CurrentTime = 5,
117 RenderRange = { 5, 7 },
118 GlobalRange = { 0, 100 },
119 Tools = ordered() {
120 BG = Background {
121 Inputs = {
122 Width = Input { Value = 64, },
123 Height = Input { Value = 32, },
124 TopLeftRed = Input { Value = 0.5, },
125 TopLeftGreen = Input { Value = 0.25, },
126 TopLeftBlue = Input { Value = 0.75, },
127 TopLeftAlpha = Input { Value = 1, },
128 },
129 },
130 },
131 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 32, Rate = 24, DepthFull = 1 } } },
132}"#;
133
134 let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic comp");
135 let target = comp.find_node("BG").expect("find BG");
136 let mut engine = Engine::new_headless().expect("headless wgpu engine");
137
138 let mut seen = Vec::new();
139 let summary = export_node_png_sequence_with_progress(
140 &mut engine,
141 &comp,
142 target,
143 [5, 7],
144 |f| Ok(tmp_dir.join(format!("{f:04}.png"))),
145 "BG".to_owned(),
146 true,
147 1,
148 0,
149 None,
150 |p| {
151 assert!(p.cached_vram_mb >= 0.0);
152 assert!(p.unsupported_nodes.is_empty());
153 seen.push(p.frame);
154 },
155 )
156 .expect("export node png sequence");
157
158 assert_eq!(summary.saver_name, "BG");
159 assert_eq!(summary.frames_written, 3);
160 assert_eq!(seen, vec![5, 6, 7]);
161 assert_eq!(summary.first_path, Some(tmp_dir.join("0005.png")));
162 assert_eq!(summary.last_path, Some(tmp_dir.join("0007.png")));
163 for f in 5..=7 {
164 let p = tmp_dir.join(format!("{f:04}.png"));
165 assert!(p.exists(), "missing {}", p.display());
166 }
167
168 let _ = std::fs::remove_dir_all(&tmp_dir);
169}
170
171fn write_test_wav(path: &Path, sample_rate: u32, duration_secs: f64) {
172 let num_channels: u16 = 2;
173 let bits_per_sample: u16 = 16;
174 let num_samples = (sample_rate as f64 * duration_secs) as u32;
175 let byte_rate = sample_rate * u32::from(num_channels) * u32::from(bits_per_sample) / 8;
176 let block_align = num_channels * bits_per_sample / 8;
177 let data_bytes = num_samples * u32::from(block_align);
178 let riff_chunk_size = 36 + data_bytes;
179
180 let mut buf = Vec::with_capacity((44 + data_bytes) as usize);
181 buf.extend_from_slice(b"RIFF");
182 buf.extend_from_slice(&riff_chunk_size.to_le_bytes());
183 buf.extend_from_slice(b"WAVE");
184 buf.extend_from_slice(b"fmt ");
185 buf.extend_from_slice(&16u32.to_le_bytes());
186 buf.extend_from_slice(&1u16.to_le_bytes()); // PCM
187 buf.extend_from_slice(&num_channels.to_le_bytes());
188 buf.extend_from_slice(&sample_rate.to_le_bytes());
189 buf.extend_from_slice(&byte_rate.to_le_bytes());
190 buf.extend_from_slice(&block_align.to_le_bytes());
191 buf.extend_from_slice(&bits_per_sample.to_le_bytes());
192 buf.extend_from_slice(b"data");
193 buf.extend_from_slice(&data_bytes.to_le_bytes());
194 for i in 0..num_samples {
195 let t = i as f64 / sample_rate as f64;
196 let sample = ((t * 440.0 * std::f64::consts::TAU).sin() * 12000.0) as i16;
197 buf.extend_from_slice(&sample.to_le_bytes());
198 buf.extend_from_slice(&sample.to_le_bytes());
199 }
200 std::fs::write(path, buf).expect("write synthetic wav");
201}
202
203#[test]
204fn exports_snippet_mp4_with_synced_audio() {
205 let tmp_dir = std::env::temp_dir().join(format!(
206 "fission-video-export-test-{}",
207 std::process::id()
208 ));
209 let _ = std::fs::remove_dir_all(&tmp_dir);
210 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
211
212 let wav_path = tmp_dir.join("tone.wav");
213 write_test_wav(&wav_path, 44100, 2.0);
214 let wav_escaped = wav_path.to_string_lossy().replace('\\', "\\\\");
215
216 let comp_src = format!(
217 r#"Composition {{
218 CurrentTime = 10,
219 RenderRange = {{ 10, 21 }},
220 GlobalRange = {{ 0, 100 }},
221 AudioFilename = "{wav_escaped}",
222 AudioOffset = 10,
223 Tools = ordered() {{
224 BG = Background {{
225 Inputs = {{
226 Width = Input {{ Value = 128, }},
227 Height = Input {{ Value = 72, }},
228 TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }},
229 TopLeftGreen = Input {{ Value = 0.25, }},
230 TopLeftBlue = Input {{ Value = 0.75, }},
231 TopLeftAlpha = Input {{ Value = 1, }},
232 }},
233 }},
234 BGRed = BezierSpline {{
235 KeyFrames = {{
236 [10] = {{ 0.0, Flags = {{ Linear = true }} }},
237 [21] = {{ 1.0, Flags = {{ Linear = true }} }},
238 }},
239 }},
240 }},
241 Prefs = {{
242 Comp = {{
243 FrameFormat = {{
244 Width = 128,
245 Height = 72,
246 Rate = 30,
247 DepthFull = 1,
248 }},
249 }},
250 }},
251}}"#
252 );
253
254 let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic audio comp");
255 let target = comp.find_node("BG").expect("find BG node");
256 let mut engine = Engine::new_headless().expect("headless wgpu engine");
257
258 let mp4_path = tmp_dir.join("snippet.mp4");
259 let mut seen_frames = Vec::new();
260 let summary = export_node_video_ffmpeg(
261 &mut engine,
262 &comp,
263 &VideoExportOptions {
264 target,
265 out_path: mp4_path.clone(),
266 range: [10, 21],
267 codec: VideoCodec::H264Share,
268 crf: 26,
269 max_height: None,
270 include_audio: true,
271 hiq: true,
272 proxy_scale: 1,
273 },
274 |p| seen_frames.push(p.frame),
275 )
276 .expect("export snippet mp4");
277
278 assert_eq!(summary.frames_written, 12);
279 assert_eq!(summary.width, 128);
280 assert_eq!(summary.height, 72);
281 assert!(summary.has_audio);
282 assert!(summary.file_bytes > 0);
283 assert_eq!(seen_frames.len(), 12);
284 assert!(mp4_path.exists());
285
286 // Verify streams and exact video frame count via ffprobe
287 let probe = Command::new("ffprobe")
288 .args([
289 "-v",
290 "error",
291 "-count_frames",
292 "-show_entries",
293 "stream=codec_type,codec_name,nb_read_frames",
294 "-of",
295 "csv=p=0",
296 ])
297 .arg(&mp4_path)
298 .output()
299 .expect("run ffprobe");
300 assert!(
301 probe.status.success(),
302 "ffprobe failed: {}",
303 String::from_utf8_lossy(&probe.stderr)
304 );
305 let stdout = String::from_utf8_lossy(&probe.stdout);
306 let mut saw_h264_12 = false;
307 let mut saw_aac = false;
308 for line in stdout.lines() {
309 let cols: Vec<&str> = line.split(',').map(str::trim).collect();
310 if cols.len() >= 3 && cols[1] == "video" && cols[0] == "h264" && cols[2] == "12" {
311 saw_h264_12 = true;
312 }
313 if cols.len() >= 2 && cols[1] == "audio" && cols[0] == "aac" {
314 saw_aac = true;
315 }
316 }
317 assert!(
318 saw_h264_12,
319 "expected h264 video stream with 12 frames, ffprobe output:\n{stdout}"
320 );
321 assert!(
322 saw_aac,
323 "expected aac audio stream, ffprobe output:\n{stdout}"
324 );
325
326 // Also verify negative audio_start_secs (range starts before AudioOffset = 10)
327 let pre_mp4_path = tmp_dir.join("snippet_pre_offset.mp4");
328 let pre_summary = export_node_video_ffmpeg(
329 &mut engine,
330 &comp,
331 &VideoExportOptions {
332 target,
333 out_path: pre_mp4_path.clone(),
334 range: [6, 17],
335 codec: VideoCodec::H264Share,
336 crf: 26,
337 max_height: Some(64),
338 include_audio: true,
339 hiq: true,
340 proxy_scale: 1,
341 },
342 |_| {},
343 )
344 .expect("export snippet mp4 with negative audio_start_secs");
345 assert_eq!(pre_summary.frames_written, 12);
346 assert!(pre_summary.has_audio);
347 assert!(pre_summary.file_bytes > 0);
348 assert!(pre_mp4_path.exists());
349
350 // Verify single-frame PNG helper
351 let png_path = tmp_dir.join("frame_10.png");
352 let saved = export_node_frame_png(&mut engine, &comp, target, 10.0, &png_path)
353 .expect("export single frame png");
354 assert_eq!(saved, png_path);
355 let img = image::open(&png_path)
356 .expect("decode exported frame png")
357 .to_rgba8();
358 assert_eq!(img.dimensions(), (128, 72));
359
360 let _ = std::fs::remove_dir_all(&tmp_dir);
361}
362
363#[test]
364fn saver_export_reports_progress_and_stops_on_cancel() {
365 let tmp_dir = std::env::temp_dir().join(format!(
366 "fission-saver-cancel-test-{}",
367 std::process::id()
368 ));
369 let _ = std::fs::remove_dir_all(&tmp_dir);
370 let saver_path = tmp_dir.join("shot_0000.png");
371 let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\");
372
373 let comp_src = format!(
374 r#"Composition {{
375 CurrentTime = 10,
376 RenderRange = {{ 10, 15 }},
377 GlobalRange = {{ 0, 100 }},
378 Tools = ordered() {{
379 BG = Background {{
380 Inputs = {{
381 Width = Input {{ Value = 64, }},
382 Height = Input {{ Value = 32, }},
383 TopLeftRed = Input {{ Value = 0.7, }},
384 TopLeftAlpha = Input {{ Value = 1, }},
385 }},
386 }},
387 Saver1 = Saver {{
388 Inputs = {{
389 Clip = Input {{
390 Value = Clip {{
391 Filename = "{saver_path_escaped}",
392 FormatID = "PNGFormat",
393 Saving = true,
394 }},
395 }},
396 Input = Input {{
397 SourceOp = "BG",
398 Source = "Output",
399 }},
400 }},
401 }},
402 }},
403 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 1 }} }} }},
404}}"#
405 );
406
407 let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp");
408 let mut engine = Engine::new_headless().expect("headless wgpu engine");
409 let control = ExportControl::new();
410 let ctrl_cb = control.clone();
411 let mut reported = Vec::new();
412
413 let err = export_saver_png_sequence_with_progress(
414 &mut engine,
415 &comp,
416 &ExportOptions::default(),
417 Some(&control),
418 |p| {
419 reported.push((
420 p.current_frame,
421 p.completed_frames,
422 p.total_frames,
423 p.label.clone(),
424 ));
425 if p.completed_frames >= 2 {
426 ctrl_cb.cancel();
427 }
428 },
429 )
430 .expect_err("saver export should cancel early");
431
432 assert_eq!(err, "Cancelled");
433 assert_eq!(reported.len(), 2);
434 assert_eq!(reported[0].0, 10);
435 assert_eq!(reported[0].1, 1);
436 assert_eq!(reported[0].2, 6);
437 assert_eq!(reported[0].3, "Saver1");
438 assert_eq!(reported[1].0, 11);
439 assert_eq!(reported[1].1, 2);
440
441 let snap = control.snapshot_progress();
442 assert_eq!(snap.completed_frames, 2);
443 assert_eq!(snap.total_frames, 6);
444 assert!(snap.elapsed_secs >= 0.0);
445 assert!(!tmp_dir.join("shot_0015.png").exists());
446
447 let _ = std::fs::remove_dir_all(&tmp_dir);
448}
449
450#[test]
451fn video_export_reports_progress_and_cleans_up_on_cancel() {
452 let tmp_dir = std::env::temp_dir().join(format!(
453 "fission-video-cancel-test-{}",
454 std::process::id()
455 ));
456 let _ = std::fs::remove_dir_all(&tmp_dir);
457 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
458
459 let comp_src = r#"Composition {
460 CurrentTime = 1,
461 RenderRange = { 1, 12 },
462 GlobalRange = { 0, 100 },
463 Tools = ordered() {
464 BG = Background {
465 Inputs = {
466 Width = Input { Value = 128, },
467 Height = Input { Value = 72, },
468 TopLeftRed = Input { Value = 0.2, },
469 TopLeftGreen = Input { Value = 0.6, },
470 TopLeftBlue = Input { Value = 0.9, },
471 TopLeftAlpha = Input { Value = 1, },
472 },
473 },
474 },
475 Prefs = { Comp = { FrameFormat = { Width = 128, Height = 72, Rate = 24, DepthFull = 1 } } },
476}"#;
477
478 let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic video comp");
479 let target = comp.find_node("BG").expect("find BG node");
480 let mut engine = Engine::new_headless().expect("headless wgpu engine");
481 let out_mp4 = tmp_dir.join("cancelled.mp4");
482 let control = ExportControl::new();
483 let ctrl_cb = control.clone();
484 let mut seen = Vec::new();
485
486 let err = export_node_video_ffmpeg_with_progress(
487 &mut engine,
488 &comp,
489 &VideoExportOptions {
490 target,
491 out_path: out_mp4.clone(),
492 range: [1, 12],
493 codec: VideoCodec::H264Share,
494 crf: 26,
495 max_height: None,
496 include_audio: false,
497 hiq: true,
498 proxy_scale: 1,
499 },
500 Some(&control),
501 |p| {
502 seen.push((
503 p.current_frame,
504 p.completed_frames,
505 p.total_frames,
506 p.label.clone(),
507 ));
508 if p.completed_frames >= 3 {
509 ctrl_cb.cancel();
510 }
511 },
512 )
513 .expect_err("video export should cancel early");
514
515 assert_eq!(err, "Cancelled");
516 assert_eq!(seen.len(), 3);
517 assert_eq!(seen[0].0, 1);
518 assert_eq!(seen[0].1, 1);
519 assert_eq!(seen[0].2, 12);
520 assert_eq!(seen[0].3, "BG");
521 assert_eq!(seen[2].0, 3);
522 assert_eq!(seen[2].1, 3);
523
524 let snap = control.snapshot_progress();
525 assert_eq!(snap.completed_frames, 3);
526 assert_eq!(snap.total_frames, 12);
527 assert!(
528 !out_mp4.exists(),
529 "partial mp4 should be removed after cancellation"
530 );
531
532 let _ = std::fs::remove_dir_all(&tmp_dir);
533}
534
535#[test]
536fn video_export_handles_short_audio_past_eof_odd_dims_and_1x1_dummy() {
537 let tmp_dir = std::env::temp_dir().join(format!(
538 "fission-video-edge-cases-{}",
539 std::process::id()
540 ));
541 let _ = std::fs::remove_dir_all(&tmp_dir);
542 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
543
544 let short_wav = tmp_dir.join("short.wav");
545 write_test_wav(&short_wav, 44100, 0.15);
546 let wav_escaped = short_wav.to_string_lossy().replace('\\', "\\\\");
547
548 // 1. Short audio (0.15s) with 1.0s (24 frames @ 24fps) odd-dimension (127x71) video.
549 let comp_src = format!(
550 r#"Composition {{
551 CurrentTime = 0,
552 RenderRange = {{ 0, 23 }},
553 GlobalRange = {{ 0, 23 }},
554 AudioFilename = "{wav_escaped}",
555 AudioOffset = 0,
556 Tools = ordered() {{
557 BG = Background {{
558 Inputs = {{
559 Width = Input {{ Value = 127, }},
560 Height = Input {{ Value = 71, }},
561 TopLeftRed = Input {{ Value = 0.4, }},
562 TopLeftGreen = Input {{ Value = 0.5, }},
563 TopLeftBlue = Input {{ Value = 0.6, }},
564 TopLeftAlpha = Input {{ Value = 1, }},
565 }},
566 }},
567 }},
568 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 127, Height = 71, Rate = 24, DepthFull = 1 }} }} }},
569}}"#
570 );
571 let comp = Comp::from_fusion_str(&comp_src).expect("parse odd+short-audio comp");
572 let target = comp.find_node("BG").unwrap();
573 let mut engine = Engine::new_headless().expect("headless wgpu engine");
574
575 let short_mp4 = tmp_dir.join("short_audio_odd.mp4");
576 let summary = export_node_video_ffmpeg(
577 &mut engine,
578 &comp,
579 &VideoExportOptions {
580 target,
581 out_path: short_mp4.clone(),
582 range: [0, 23],
583 codec: VideoCodec::H264Share,
584 crf: 26,
585 max_height: None,
586 include_audio: true,
587 hiq: true,
588 proxy_scale: 1,
589 },
590 |_| {},
591 )
592 .expect("export with short audio and odd dimensions should succeed without Broken pipe");
593 assert_eq!(summary.frames_written, 24);
594 assert_eq!(summary.width, 126);
595 assert_eq!(summary.height, 70);
596 assert!(summary.has_audio);
597
598 // 2. Audio start past EOF -> skips audio cleanly (`has_audio == false`).
599 let mut past_eof_comp = comp.clone();
600 past_eof_comp.audio_offset = -100.0; // start=0 -> audio_start_secs = +4.17s > 0.15s
601 let past_mp4 = tmp_dir.join("past_eof.mp4");
602 let past_summary = export_node_video_ffmpeg(
603 &mut engine,
604 &past_eof_comp,
605 &VideoExportOptions {
606 target,
607 out_path: past_mp4.clone(),
608 range: [0, 5],
609 codec: VideoCodec::H264Share,
610 crf: 26,
611 max_height: None,
612 include_audio: true,
613 hiq: true,
614 proxy_scale: 1,
615 },
616 |_| {},
617 )
618 .expect("export with audio past EOF should skip audio and succeed");
619 assert_eq!(past_summary.frames_written, 6);
620 assert!(!past_summary.has_audio);
621
622 // 3. First frame 1x1 dummy (Loader with missing frame 0, MissingFrames = 0) -> falls back to comp canvas.
623 let seq1 = tmp_dir.join("seq_0001.png");
624 image::RgbaImage::from_pixel(64, 36, image::Rgba([20, 200, 40, 255]))
625 .save(&seq1)
626 .unwrap();
627 let seq0 = tmp_dir.join("seq_0000.png"); // intentionally absent
628 let seq0_esc = seq0.to_string_lossy().replace('\\', "\\\\");
629 let dummy_comp_src = format!(
630 r#"Composition {{
631 CurrentTime = 0,
632 RenderRange = {{ 0, 1 }},
633 GlobalRange = {{ 0, 1 }},
634 Tools = ordered() {{
635 LD = Loader {{
636 Clips = {{
637 Clip {{
638 ID = "Clip1",
639 Filename = "{seq0_esc}",
640 FormatID = "PNGFormat",
641 StartFrame = 0,
642 Length = 2,
643 GlobalStart = 0,
644 GlobalEnd = 1,
645 }},
646 }},
647 }},
648 }},
649 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 36, Rate = 24, DepthFull = 1 }} }} }},
650}}"#
651 );
652 let dummy_comp = Comp::from_fusion_str(&dummy_comp_src).expect("parse dummy loader comp");
653 let ld = dummy_comp.find_node("LD").unwrap();
654 engine.bust_all_caches();
655 let dummy_mp4 = tmp_dir.join("dummy_first.mp4");
656 let dummy_summary = export_node_video_ffmpeg(
657 &mut engine,
658 &dummy_comp,
659 &VideoExportOptions {
660 target: ld,
661 out_path: dummy_mp4.clone(),
662 range: [0, 1],
663 codec: VideoCodec::H264Share,
664 crf: 26,
665 max_height: None,
666 include_audio: false,
667 hiq: true,
668 proxy_scale: 1,
669 },
670 |_| {},
671 )
672 .expect("export with 1x1 first frame should fall back to comp dimensions");
673 assert_eq!(dummy_summary.frames_written, 2);
674 assert_eq!(dummy_summary.width, 64);
675 assert_eq!(dummy_summary.height, 36);
676
677 let _ = std::fs::remove_dir_all(&tmp_dir);
678}
679
680#[test]
681fn video_export_cancel_preserves_existing_output_and_removes_temp_file() {
682 let tmp_dir = std::env::temp_dir().join(format!(
683 "fission-video-atomic-cancel-{}",
684 std::process::id()
685 ));
686 let _ = std::fs::remove_dir_all(&tmp_dir);
687 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
688
689 let out_mp4 = tmp_dir.join("existing.mp4");
690 let sentinel_bytes = b"ORIGINAL_VALUABLE_EXPORT_BYTES_DO_NOT_TRUNCATE";
691 std::fs::write(&out_mp4, sentinel_bytes).expect("write sentinel existing file");
692
693 let comp_src = r#"Composition {
694 CurrentTime = 0,
695 RenderRange = { 0, 9 },
696 GlobalRange = { 0, 9 },
697 Tools = ordered() {
698 BG = Background {
699 Inputs = {
700 Width = Input { Value = 64, },
701 Height = Input { Value = 64, },
702 TopLeftRed = Input { Value = 0.8, },
703 TopLeftAlpha = Input { Value = 1, },
704 },
705 },
706 },
707 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 64, Rate = 24, DepthFull = 1 } } },
708}"#;
709 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
710 let target = comp.find_node("BG").expect("find BG");
711 let mut engine = Engine::new_headless().expect("headless wgpu engine");
712 let control = ExportControl::new();
713 let ctrl_cb = control.clone();
714
715 let err = export_node_video_ffmpeg_with_progress(
716 &mut engine,
717 &comp,
718 &VideoExportOptions {
719 target,
720 out_path: out_mp4.clone(),
721 range: [0, 9],
722 codec: VideoCodec::H264Share,
723 crf: 26,
724 max_height: None,
725 include_audio: false,
726 hiq: true,
727 proxy_scale: 1,
728 },
729 Some(&control),
730 |p| {
731 if p.completed_frames >= 2 {
732 ctrl_cb.cancel();
733 }
734 },
735 )
736 .expect_err("cancelled export should return Err");
737 assert_eq!(err, "Cancelled");
738
739 let after_bytes = std::fs::read(&out_mp4).expect("existing output must still exist");
740 assert_eq!(
741 after_bytes.as_slice(),
742 sentinel_bytes,
743 "existing file must stay untouched"
744 );
745
746 let entries: Vec<_> = std::fs::read_dir(&tmp_dir)
747 .expect("read tmp_dir")
748 .filter_map(|e| e.ok())
749 .map(|e| e.file_name().to_string_lossy().into_owned())
750 .collect();
751 assert_eq!(
752 entries,
753 vec!["existing.mp4".to_owned()],
754 "no temp files should remain"
755 );
756
757 let _ = std::fs::remove_dir_all(&tmp_dir);
758}
759
760#[test]
761fn pipelined_png_export_is_pixel_exact_and_propagates_write_errors() {
762 let tmp_dir = std::env::temp_dir().join(format!(
763 "fission-png-pipeline-exact-{}",
764 std::process::id()
765 ));
766 let _ = std::fs::remove_dir_all(&tmp_dir);
767 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
768
769 let saver_path = tmp_dir.join("out").join("frame_0000.png");
770 let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\");
771 let comp_src = format!(
772 r#"Composition {{
773 CurrentTime = 0,
774 RenderRange = {{ 0, 5 }},
775 GlobalRange = {{ 0, 5 }},
776 Tools = ordered() {{
777 BG = Background {{
778 Inputs = {{
779 Width = Input {{ Value = 96, }},
780 Height = Input {{ Value = 48, }},
781 TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }},
782 TopLeftGreen = Input {{ Value = 0.5, }},
783 TopLeftBlue = Input {{ Value = 0.25, }},
784 TopLeftAlpha = Input {{ Value = 1.0, }},
785 }},
786 }},
787 BGRed = BezierSpline {{
788 KeyFrames = {{
789 [0] = {{ 0.1, Flags = {{ Linear = true }} }},
790 [5] = {{ 0.9, Flags = {{ Linear = true }} }},
791 }},
792 }},
793 Saver1 = Saver {{
794 Inputs = {{
795 Clip = Input {{
796 Value = Clip {{
797 Filename = "{saver_path_escaped}",
798 FormatID = "PNGFormat",
799 Saving = true,
800 }},
801 }},
802 Input = Input {{ SourceOp = "BG", Source = "Output", }},
803 }},
804 }},
805 }},
806 Prefs = {{ Comp = {{ FrameFormat = {{ Width = 96, Height = 48, Rate = 24, DepthFull = 1 }} }} }},
807}}"#
808 );
809
810 let comp = Comp::from_fusion_str(&comp_src).expect("parse comp");
811 let target = comp.find_node("BG").unwrap();
812 let mut engine = Engine::new_headless().expect("headless wgpu engine");
813
814 let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |_| {})
815 .expect("export png sequence");
816 assert_eq!(summary.frames_written, 6);
817
818 // Verify fast-compressed PNGs decode byte-identically to direct GPU readback.
819 for f in 0..=5 {
820 let (tex, _) = engine.evaluate(&comp, target, f as f64);
821 let expected = engine.readback_rgba(&tex).expect("readback");
822 let png_path = tmp_dir.join("out").join(format!("frame_{f:04}.png"));
823 let decoded = image::open(&png_path).expect("decode png").to_rgba8();
824 assert_eq!(decoded.dimensions(), (tex.size[0], tex.size[1]));
825 assert_eq!(
826 decoded.into_raw(),
827 expected,
828 "fast PNG encode must be 100% lossless at frame {f}"
829 );
830 }
831
832 // Verify worker write error propagates cleanly: point out_dir_override inside a regular file.
833 let blocking_file = tmp_dir.join("not_a_dir");
834 std::fs::write(&blocking_file, b"file").expect("write blocking file");
835 let err = export_saver_png_sequence(
836 &mut engine,
837 &comp,
838 &ExportOptions {
839 out_dir_override: Some(blocking_file),
840 ..ExportOptions::default()
841 },
842 |_| {},
843 )
844 .expect_err("writing into a regular file path must return Err");
845 assert!(!err.is_empty());
846
847 let _ = std::fs::remove_dir_all(&tmp_dir);
848}
849
850#[test]
851fn videotoolbox_probe_selection_and_fallback() {
852 let sample_both = "\
853Encoders:
854 V..... = Video
855 ------
856 V....D libx264 libx264 H.264 / AVC
857 V....D h264_videotoolbox VideoToolbox H.264 Encoder (codec h264)
858 VFS... prores_ks Apple ProRes (iCodec Pro) (codec prores)
859 V....D prores_videotoolbox VideoToolbox ProRes Encoder (codec prores)
860 A....D aac AAC (Advanced Audio Coding)
861";
862 let vt_both = parse_videotoolbox_encoders(sample_both);
863 assert_eq!(
864 vt_both,
865 VideoToolboxSupport {
866 h264: true,
867 prores: true
868 }
869 );
870
871 let sample_h264_only = " V....D h264_videotoolbox VideoToolbox H.264 Encoder\n";
872 assert_eq!(
873 parse_videotoolbox_encoders(sample_h264_only),
874 VideoToolboxSupport {
875 h264: true,
876 prores: false
877 }
878 );
879 assert_eq!(
880 parse_videotoolbox_encoders(" V....D libx264 H.264\n"),
881 VideoToolboxSupport::default()
882 );
883
884 // Hardware selection when supported and allowed
885 assert_eq!(
886 select_video_encoder(VideoCodec::H264Share, vt_both, true),
887 VideoEncoder::H264VideoToolbox
888 );
889 assert_eq!(
890 select_video_encoder(VideoCodec::ProRes422, vt_both, true),
891 VideoEncoder::ProResVideoToolbox422
892 );
893 assert_eq!(
894 select_video_encoder(VideoCodec::ProRes4444, vt_both, true),
895 VideoEncoder::ProResVideoToolbox4444
896 );
897
898 // Fallback when VideoToolbox is unavailable or disabled after failure
899 assert_eq!(
900 select_video_encoder(VideoCodec::H264Share, vt_both, false),
901 VideoEncoder::Libx264
902 );
903 assert_eq!(
904 select_video_encoder(VideoCodec::ProRes422, vt_both, false),
905 VideoEncoder::ProResKs422
906 );
907 assert_eq!(
908 select_video_encoder(VideoCodec::ProRes4444, vt_both, false),
909 VideoEncoder::ProResKs4444
910 );
911 assert_eq!(
912 select_video_encoder(VideoCodec::H264Share, VideoToolboxSupport::default(), true),
913 VideoEncoder::Libx264
914 );
915
916 assert_eq!(vt_quality_from_crf(0), 95);
917 assert_eq!(vt_quality_from_crf(26), 52);
918 assert_eq!(vt_quality_from_crf(51), 15);
919
920 let mut args = Vec::new();
921 push_video_encoder_args(
922 &mut args,
923 VideoEncoder::H264VideoToolbox,
924 26,
925 Some("scale=trunc(iw/2)*2:trunc(ih/2)*2"),
926 );
927 assert!(args.windows(2).any(|w| w == ["-c:v", "h264_videotoolbox"]));
928 assert!(args.windows(2).any(|w| w == ["-q:v", "52"]));
929 assert!(args.windows(2).any(|w| w == ["-tag:v", "avc1"]));
930 assert!(args.windows(2).any(|w| w == ["-pix_fmt", "yuv420p"]));
931
932 args.clear();
933 push_video_encoder_args(
934 &mut args,
935 VideoEncoder::Libx264,
936 26,
937 Some("scale=trunc(iw/2)*2:trunc(ih/2)*2"),
938 );
939 assert!(args.windows(2).any(|w| w == ["-c:v", "libx264"]));
940 assert!(args.windows(2).any(|w| w == ["-crf", "26"]));
941
942 args.clear();
943 push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox422, 26, None);
944 assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"]));
945 assert!(args.windows(2).any(|w| w == ["-profile:v", "2"]));
946 assert!(args.windows(2).any(|w| w == ["-pix_fmt", "p210le"]));
947
948 args.clear();
949 push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox4444, 26, None);
950 assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"]));
951 assert!(args.windows(2).any(|w| w == ["-profile:v", "4"]));
952 assert!(args.windows(2).any(|w| w == ["-pix_fmt", "ayuv64le"]));
953}
954
955#[test]
956fn fit_frame_rgba_zero_copy_fast_path_and_resize() {
957 let pixels = vec![128u8; 8 * 4 * 4];
958 let orig_ptr = pixels.as_ptr();
959 let moved = fit_frame_rgba(pixels, [8, 4], [8, 4], 0).expect("matching size fast path");
960 assert_eq!(
961 moved.as_ptr(),
962 orig_ptr,
963 "matching size must move Vec without copying"
964 );
965
966 let resized = fit_frame_rgba(moved, [8, 4], [4, 2], 1).expect("resize path");
967 assert_eq!(resized.len(), 4 * 2 * 4);
968
969 let err = fit_frame_rgba(vec![0u8; 10], [8, 4], [8, 4], 2)
970 .expect_err("mismatched RGBA byte length must fail");
971 assert!(err.contains("invalid RGBA buffer size"));
972}
973
974#[test]
975fn prores_4444_preserves_alpha_channel() {
976 let tmp_dir = std::env::temp_dir().join(format!(
977 "fission-prores4444-alpha-{}",
978 std::process::id()
979 ));
980 let _ = std::fs::remove_dir_all(&tmp_dir);
981 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
982
983 let comp_src = r#"Composition {
984 CurrentTime = 0,
985 RenderRange = { 0, 1 },
986 GlobalRange = { 0, 1 },
987 Tools = ordered() {
988 BG = Background {
989 Inputs = {
990 Width = Input { Value = 64, },
991 Height = Input { Value = 36, },
992 TopLeftRed = Input { Value = 0.8, },
993 TopLeftGreen = Input { Value = 0.4, },
994 TopLeftBlue = Input { Value = 0.2, },
995 TopLeftAlpha = Input { SourceOp = "BGAlpha", Source = "Value", },
996 },
997 },
998 BGAlpha = BezierSpline {
999 KeyFrames = {
1000 [0] = { 0.25, Flags = { Linear = true } },
1001 [1] = { 0.75, Flags = { Linear = true } },
1002 },
1003 },
1004 },
1005 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } },
1006}"#;
1007 let comp = Comp::from_fusion_str(comp_src).expect("parse alpha ProRes comp");
1008 let target = comp.find_node("BG").expect("find BG");
1009 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1010
1011 let out_mov = tmp_dir.join("alpha_4444.mov");
1012 let summary = export_node_video_ffmpeg(
1013 &mut engine,
1014 &comp,
1015 &VideoExportOptions {
1016 target,
1017 out_path: out_mov.clone(),
1018 range: [0, 1],
1019 codec: VideoCodec::ProRes4444,
1020 crf: 26,
1021 max_height: None,
1022 include_audio: false,
1023 hiq: true,
1024 proxy_scale: 1,
1025 },
1026 |_| {},
1027 )
1028 .expect("export ProRes 4444");
1029 assert_eq!(summary.frames_written, 2);
1030 assert_eq!(summary.width, 64);
1031 assert_eq!(summary.height, 36);
1032
1033 let probe = Command::new("ffprobe")
1034 .args([
1035 "-v",
1036 "error",
1037 "-show_entries",
1038 "stream=codec_name,profile,pix_fmt",
1039 "-of",
1040 "csv=p=0",
1041 ])
1042 .arg(&out_mov)
1043 .output()
1044 .expect("run ffprobe");
1045 assert!(probe.status.success());
1046 let probe_out = String::from_utf8_lossy(&probe.stdout);
1047 assert!(
1048 probe_out.contains("prores") && probe_out.contains("4444") && probe_out.contains("yuva"),
1049 "expected ProRes 4444 with alpha pixel format, got: {probe_out}"
1050 );
1051
1052 let dec = Command::new("ffmpeg")
1053 .args(["-v", "error", "-i"])
1054 .arg(&out_mov)
1055 .args(["-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1"])
1056 .output()
1057 .expect("decode ProRes 4444 to rgba");
1058 assert!(dec.status.success());
1059 let frame_bytes = 64 * 36 * 4;
1060 assert_eq!(dec.stdout.len(), frame_bytes * 2);
1061
1062 let a0 = dec.stdout[3];
1063 let a1 = dec.stdout[frame_bytes + 3];
1064 assert!(
1065 (i32::from(a0) - 64).abs() <= 2,
1066 "frame 0 alpha should be ~64 (0.25), got {a0}"
1067 );
1068 assert!(
1069 (i32::from(a1) - 191).abs() <= 2,
1070 "frame 1 alpha should be ~191 (0.75), got {a1}"
1071 );
1072
1073 let _ = std::fs::remove_dir_all(&tmp_dir);
1074}
1075
1076#[test]
1077fn prores_422_and_software_fallback_encoders_produce_valid_streams() {
1078 let tmp_dir = std::env::temp_dir().join(format!(
1079 "fission-prores422-fallback-{}",
1080 std::process::id()
1081 ));
1082 let _ = std::fs::remove_dir_all(&tmp_dir);
1083 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
1084
1085 let comp_src = r#"Composition {
1086 CurrentTime = 0,
1087 RenderRange = { 0, 2 },
1088 GlobalRange = { 0, 2 },
1089 Tools = ordered() {
1090 BG = Background {
1091 Inputs = {
1092 Width = Input { Value = 64, },
1093 Height = Input { Value = 36, },
1094 TopLeftRed = Input { Value = 0.2, },
1095 TopLeftGreen = Input { Value = 0.7, },
1096 TopLeftBlue = Input { Value = 0.3, },
1097 TopLeftAlpha = Input { Value = 1.0, },
1098 },
1099 },
1100 },
1101 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } },
1102}"#;
1103 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
1104 let target = comp.find_node("BG").expect("find BG");
1105 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1106
1107 let prores422_mov = tmp_dir.join("prores422.mov");
1108 let summary_422 = export_node_video_ffmpeg(
1109 &mut engine,
1110 &comp,
1111 &VideoExportOptions {
1112 target,
1113 out_path: prores422_mov.clone(),
1114 range: [0, 2],
1115 codec: VideoCodec::ProRes422,
1116 crf: 26,
1117 max_height: None,
1118 include_audio: false,
1119 hiq: true,
1120 proxy_scale: 1,
1121 },
1122 |_| {},
1123 )
1124 .expect("export ProRes 422");
1125 assert_eq!(summary_422.frames_written, 3);
1126
1127 let probe_422 = Command::new("ffprobe")
1128 .args([
1129 "-v",
1130 "error",
1131 "-count_frames",
1132 "-show_entries",
1133 "stream=codec_name,profile,nb_read_frames",
1134 "-of",
1135 "csv=p=0",
1136 ])
1137 .arg(&prores422_mov)
1138 .output()
1139 .expect("ffprobe prores 422");
1140 assert!(probe_422.status.success());
1141 let out_422 = String::from_utf8_lossy(&probe_422.stdout);
1142 assert!(
1143 out_422.contains("prores") && out_422.contains("Standard") && out_422.contains(",3"),
1144 "expected ProRes 422 Standard with 3 frames, got: {out_422}"
1145 );
1146
1147 // Directly verify software fallback encoders (Libx264 and ProResKs422)
1148 let sw_mp4 = tmp_dir.join("sw_libx264.mp4");
1149 let mut noop = |_| {};
1150 let sw_summary = export_node_video_ffmpeg_with_encoder(
1151 &mut engine,
1152 &comp,
1153 &VideoExportOptions {
1154 target,
1155 out_path: sw_mp4.clone(),
1156 range: [0, 2],
1157 codec: VideoCodec::H264Share,
1158 crf: 26,
1159 max_height: None,
1160 include_audio: false,
1161 hiq: true,
1162 proxy_scale: 1,
1163 },
1164 None,
1165 &mut noop,
1166 VideoEncoder::Libx264,
1167 Instant::now(),
1168 )
1169 .expect("software libx264 fallback export");
1170 assert_eq!(sw_summary.frames_written, 3);
1171 assert!(sw_mp4.exists());
1172
1173 let sw_mov = tmp_dir.join("sw_prores_ks.mov");
1174 let sw_prores = export_node_video_ffmpeg_with_encoder(
1175 &mut engine,
1176 &comp,
1177 &VideoExportOptions {
1178 target,
1179 out_path: sw_mov.clone(),
1180 range: [0, 2],
1181 codec: VideoCodec::ProRes422,
1182 crf: 26,
1183 max_height: None,
1184 include_audio: false,
1185 hiq: true,
1186 proxy_scale: 1,
1187 },
1188 None,
1189 &mut noop,
1190 VideoEncoder::ProResKs422,
1191 Instant::now(),
1192 )
1193 .expect("software prores_ks fallback export");
1194 assert_eq!(sw_prores.frames_written, 3);
1195 assert!(sw_mov.exists());
1196
1197 let _ = std::fs::remove_dir_all(&tmp_dir);
1198}
1199
1200#[test]
1201fn h264_max_height_out_width_matches_ffmpeg_scale_neg2_rounding() {
1202 // 101x100 with max_height >= 100: scale=-2 rounds 101.0/2 = 50.5 -> 51 * 2 = 102
1203 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(100));
1204 assert_eq!((w, h), (102, 100));
1205 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(200));
1206 assert_eq!((w, h), (102, 100));
1207 let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(50));
1208 assert_eq!((w, h), (50, 50));
1209
1210 // 1000x750 downscaled: 1000*700/750 = 933.33 -> nearest even 934; 1000*400/750 = 533.33 -> 534; 1000*500/750 = 666.67 -> 666
1211 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(700));
1212 assert_eq!((w, h), (934, 700));
1213 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(400));
1214 assert_eq!((w, h), (534, 400));
1215 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(500));
1216 assert_eq!((w, h), (666, 500));
1217 let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(750));
1218 assert_eq!((w, h), (1000, 750));
1219
1220 // Without max_height, trunc(iw/2)*2:trunc(ih/2)*2 truncates odd dimensions downward
1221 let (_, w, h) = h264_scale_filter_and_dims(101, 100, None);
1222 assert_eq!((w, h), (100, 100));
1223}
1224
1225#[test]
1226fn video_export_cancel_on_final_frame_progress_cancels_cleanly() {
1227 let tmp_dir = std::env::temp_dir().join(format!(
1228 "fission-video-cancel-final-{}",
1229 std::process::id()
1230 ));
1231 let _ = std::fs::remove_dir_all(&tmp_dir);
1232 std::fs::create_dir_all(&tmp_dir).expect("create temp dir");
1233
1234 let comp_src = r#"Composition {
1235 CurrentTime = 0,
1236 RenderRange = { 0, 2 },
1237 GlobalRange = { 0, 2 },
1238 Tools = ordered() {
1239 BG = Background {
1240 Inputs = {
1241 Width = Input { Value = 64, },
1242 Height = Input { Value = 36, },
1243 TopLeftRed = Input { Value = 0.5, },
1244 TopLeftAlpha = Input { Value = 1, },
1245 },
1246 },
1247 },
1248 Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } },
1249}"#;
1250 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
1251 let target = comp.find_node("BG").expect("find BG");
1252 let mut engine = Engine::new_headless().expect("headless wgpu engine");
1253 let out_mp4 = tmp_dir.join("final_cancel.mp4");
1254 let control = ExportControl::new();
1255 let ctrl_cb = control.clone();
1256
1257 let err = export_node_video_ffmpeg_with_progress(
1258 &mut engine,
1259 &comp,
1260 &VideoExportOptions {
1261 target,
1262 out_path: out_mp4.clone(),
1263 range: [0, 2],
1264 codec: VideoCodec::H264Share,
1265 crf: 26,
1266 max_height: None,
1267 include_audio: false,
1268 hiq: true,
1269 proxy_scale: 1,
1270 },
1271 Some(&control),
1272 |p| {
1273 if p.completed_frames == p.total_frames {
1274 ctrl_cb.cancel();
1275 }
1276 },
1277 )
1278 .expect_err("cancelling on final frame callback must return Cancelled");
1279 assert_eq!(err, "Cancelled");
1280 assert!(
1281 !out_mp4.exists(),
1282 "cancelled export must not publish output file"
1283 );
1284
1285 let _ = std::fs::remove_dir_all(&tmp_dir);
1286}
crates/engine/src/export/video.rs created+896
......@@ -0,0 +1,896 @@
1//! Piped `ffmpeg` video export with VideoToolbox hardware acceleration, automatic
2//! software fallback, synced audio muxing, and atomic temp-file finalization.
3
4use super::{
5 ExportControl, ExportProgress, VideoCodec, VideoExportOptions, VideoExportSummary,
6 make_progress,
7};
8use crate::cache::EvalStats;
9use crate::eval::Engine;
10use model::Comp;
11use std::io::{Read, Write};
12use std::path::{Path, PathBuf};
13use std::process::{Command, Stdio};
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15#[cfg(target_os = "macos")]
16use std::sync::OnceLock;
17use std::sync::{Arc, Mutex, mpsc};
18use std::time::Instant;
19
20/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames
21/// directly into `ffmpeg`, and muxes synced comp audio when `opts.include_audio` is enabled.
22pub fn export_node_video_ffmpeg(
23 engine: &mut Engine,
24 comp: &Comp,
25 opts: &VideoExportOptions,
26 on_progress: impl FnMut(ExportProgress),
27) -> Result<VideoExportSummary, String> {
28 export_node_video_ffmpeg_with_progress(engine, comp, opts, None, on_progress)
29}
30
31fn probe_audio_duration_secs(path: &Path) -> Option<f64> {
32 let out = Command::new("ffprobe")
33 .args([
34 "-v",
35 "error",
36 "-select_streams",
37 "a:0",
38 "-show_entries",
39 "stream=codec_type,duration",
40 "-show_entries",
41 "format=duration",
42 "-of",
43 "default=noprint_wrappers=1",
44 ])
45 .arg(path)
46 .output()
47 .ok()?;
48 if !out.status.success() {
49 return None;
50 }
51 let text = String::from_utf8_lossy(&out.stdout);
52 let mut has_audio_stream = false;
53 let mut stream_dur: Option<f64> = None;
54 let mut format_dur: Option<f64> = None;
55 let mut in_stream = false;
56 for line in text.lines() {
57 let Some((k, v)) = line.split_once('=') else {
58 continue;
59 };
60 let key = k.trim();
61 let val = v.trim();
62 match key {
63 "codec_type" => {
64 in_stream = true;
65 if val == "audio" {
66 has_audio_stream = true;
67 }
68 }
69 "duration" => {
70 if let Ok(d) = val.parse::<f64>() {
71 if d.is_finite() && d >= 0.0 {
72 if in_stream && stream_dur.is_none() {
73 stream_dur = Some(d);
74 } else if !in_stream && format_dur.is_none() {
75 format_dur = Some(d);
76 }
77 }
78 }
79 in_stream = false;
80 }
81 _ => {}
82 }
83 }
84 if !has_audio_stream {
85 return Some(0.0);
86 }
87 stream_dur.or(format_dur)
88}
89
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
91pub(super) struct VideoToolboxSupport {
92 pub(super) h264: bool,
93 pub(super) prores: bool,
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub(super) enum VideoEncoder {
98 Libx264,
99 H264VideoToolbox,
100 ProResKs422,
101 ProResVideoToolbox422,
102 ProResKs4444,
103 ProResVideoToolbox4444,
104}
105
106impl VideoEncoder {
107 fn is_hardware_accelerated(self) -> bool {
108 matches!(
109 self,
110 Self::H264VideoToolbox | Self::ProResVideoToolbox422 | Self::ProResVideoToolbox4444
111 )
112 }
113}
114
115#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
116pub(super) fn parse_videotoolbox_encoders(encoders_stdout: &str) -> VideoToolboxSupport {
117 let mut support = VideoToolboxSupport::default();
118 for line in encoders_stdout.lines() {
119 let mut parts = line.split_whitespace();
120 let Some(flags) = parts.next() else {
121 continue;
122 };
123 if !flags.starts_with('V') {
124 continue;
125 }
126 let Some(name) = parts.next() else {
127 continue;
128 };
129 match name {
130 "h264_videotoolbox" => support.h264 = true,
131 "prores_videotoolbox" => support.prores = true,
132 _ => {}
133 }
134 }
135 support
136}
137
138#[cfg(target_os = "macos")]
139fn probe_videotoolbox_support() -> VideoToolboxSupport {
140 static VT_SUPPORT: OnceLock<VideoToolboxSupport> = OnceLock::new();
141 *VT_SUPPORT.get_or_init(|| {
142 let Ok(out) = Command::new("ffmpeg")
143 .args(["-hide_banner", "-encoders"])
144 .output()
145 else {
146 return VideoToolboxSupport::default();
147 };
148 if !out.status.success() {
149 return VideoToolboxSupport::default();
150 }
151 let text = String::from_utf8_lossy(&out.stdout);
152 parse_videotoolbox_encoders(&text)
153 })
154}
155
156#[cfg(not(target_os = "macos"))]
157fn probe_videotoolbox_support() -> VideoToolboxSupport {
158 VideoToolboxSupport::default()
159}
160
161pub(super) fn select_video_encoder(
162 codec: VideoCodec,
163 vt: VideoToolboxSupport,
164 allow_videotoolbox: bool,
165) -> VideoEncoder {
166 match codec {
167 VideoCodec::H264Share => {
168 if allow_videotoolbox && vt.h264 {
169 VideoEncoder::H264VideoToolbox
170 } else {
171 VideoEncoder::Libx264
172 }
173 }
174 VideoCodec::ProRes422 => {
175 if allow_videotoolbox && vt.prores {
176 VideoEncoder::ProResVideoToolbox422
177 } else {
178 VideoEncoder::ProResKs422
179 }
180 }
181 VideoCodec::ProRes4444 => {
182 if allow_videotoolbox && vt.prores {
183 VideoEncoder::ProResVideoToolbox4444
184 } else {
185 VideoEncoder::ProResKs4444
186 }
187 }
188 }
189}
190
191/// Maps x264-style CRF (`0..=51`, lower = higher quality) to VideoToolbox `-q:v` (`15..=95`, higher = higher quality).
192pub(super) fn vt_quality_from_crf(crf: u8) -> u8 {
193 (104 - i32::from(crf) * 2).clamp(15, 95) as u8
194}
195
196pub(super) fn push_video_encoder_args(
197 args: &mut Vec<String>,
198 encoder: VideoEncoder,
199 crf: u8,
200 vf: Option<&str>,
201) {
202 match encoder {
203 VideoEncoder::H264VideoToolbox => {
204 if let Some(vf) = vf {
205 args.extend(["-vf".to_owned(), vf.to_owned()]);
206 }
207 args.extend([
208 "-c:v".to_owned(),
209 "h264_videotoolbox".to_owned(),
210 "-q:v".to_owned(),
211 vt_quality_from_crf(crf).to_string(),
212 "-pix_fmt".to_owned(),
213 "yuv420p".to_owned(),
214 "-tag:v".to_owned(),
215 "avc1".to_owned(),
216 "-movflags".to_owned(),
217 "+faststart".to_owned(),
218 ]);
219 }
220 VideoEncoder::Libx264 => {
221 if let Some(vf) = vf {
222 args.extend(["-vf".to_owned(), vf.to_owned()]);
223 }
224 args.extend([
225 "-c:v".to_owned(),
226 "libx264".to_owned(),
227 "-preset".to_owned(),
228 "medium".to_owned(),
229 "-crf".to_owned(),
230 crf.to_string(),
231 "-pix_fmt".to_owned(),
232 "yuv420p".to_owned(),
233 "-movflags".to_owned(),
234 "+faststart".to_owned(),
235 ]);
236 }
237 VideoEncoder::ProResVideoToolbox422 => {
238 args.extend([
239 "-c:v".to_owned(),
240 "prores_videotoolbox".to_owned(),
241 "-profile:v".to_owned(),
242 "2".to_owned(),
243 "-pix_fmt".to_owned(),
244 "p210le".to_owned(),
245 ]);
246 }
247 VideoEncoder::ProResKs422 => {
248 args.extend([
249 "-c:v".to_owned(),
250 "prores_ks".to_owned(),
251 "-profile:v".to_owned(),
252 "2".to_owned(),
253 "-pix_fmt".to_owned(),
254 "yuv422p10le".to_owned(),
255 ]);
256 }
257 VideoEncoder::ProResVideoToolbox4444 => {
258 args.extend([
259 "-c:v".to_owned(),
260 "prores_videotoolbox".to_owned(),
261 "-profile:v".to_owned(),
262 "4".to_owned(),
263 "-pix_fmt".to_owned(),
264 "ayuv64le".to_owned(),
265 ]);
266 }
267 VideoEncoder::ProResKs4444 => {
268 args.extend([
269 "-c:v".to_owned(),
270 "prores_ks".to_owned(),
271 "-profile:v".to_owned(),
272 "4".to_owned(),
273 "-pix_fmt".to_owned(),
274 "yuva444p10le".to_owned(),
275 ]);
276 }
277 }
278}
279
280pub(super) fn fit_frame_rgba(
281 pixels: Vec<u8>,
282 src_size: [u32; 2],
283 dst_size: [u32; 2],
284 frame: i64,
285) -> Result<Vec<u8>, String> {
286 let expected_len = (src_size[0] as usize)
287 .checked_mul(src_size[1] as usize)
288 .and_then(|px| px.checked_mul(4))
289 .ok_or_else(|| format!("frame {frame} dimensions overflow buffer size"))?;
290 if pixels.len() != expected_len {
291 return Err(format!(
292 "invalid RGBA buffer size at frame {frame}: expected {expected_len}, got {}",
293 pixels.len()
294 ));
295 }
296 if src_size == dst_size {
297 return Ok(pixels);
298 }
299 let img = image::RgbaImage::from_raw(src_size[0], src_size[1], pixels)
300 .ok_or_else(|| format!("invalid RGBA buffer size at frame {frame}"))?;
301 Ok(image::imageops::resize(
302 &img,
303 dst_size[0],
304 dst_size[1],
305 image::imageops::FilterType::Triangle,
306 )
307 .into_raw())
308}
309
310static EXPORT_TMP_SEQ: AtomicU64 = AtomicU64::new(0);
311
312fn sibling_temp_export_path(out_path: &Path) -> PathBuf {
313 let seq = EXPORT_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
314 let pid = std::process::id();
315 let stem = out_path
316 .file_stem()
317 .and_then(|s| s.to_str())
318 .filter(|s| !s.is_empty())
319 .unwrap_or("export");
320 let file_name = match out_path
321 .extension()
322 .and_then(|e| e.to_str())
323 .filter(|e| !e.is_empty())
324 {
325 Some(ext) => format!("{stem}.fission_tmp_{pid}_{seq}.{ext}"),
326 None => format!("{stem}.fission_tmp_{pid}_{seq}"),
327 };
328 out_path.with_file_name(file_name)
329}
330
331struct TempExportGuard {
332 path: PathBuf,
333 active: bool,
334}
335
336impl TempExportGuard {
337 fn new(path: PathBuf) -> Self {
338 Self { path, active: true }
339 }
340
341 fn disarm(&mut self) {
342 self.active = false;
343 }
344}
345
346impl Drop for TempExportGuard {
347 fn drop(&mut self) {
348 if self.active {
349 let _ = std::fs::remove_file(&self.path);
350 }
351 }
352}
353
354#[derive(Debug)]
355pub(super) enum VideoExportError {
356 Cancelled,
357 Fatal(String),
358 EncoderFailed(String),
359}
360
361impl VideoExportError {
362 fn into_string(self) -> String {
363 match self {
364 Self::Cancelled => "Cancelled".to_owned(),
365 Self::Fatal(s) | Self::EncoderFailed(s) => s,
366 }
367 }
368}
369
370pub(super) fn h264_scale_filter_and_dims(
371 width: u32,
372 height: u32,
373 max_height: Option<u32>,
374) -> (String, u32, u32) {
375 if let Some(max_h) = max_height.filter(|&h| h >= 2) {
376 let oh = (height.min(max_h) & !1).max(2);
377 let ow =
378 ((((width as f64) * (oh as f64) / (height as f64)) / 2.0).round() as u32 * 2).max(2);
379 (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh)
380 } else {
381 let ow = (width & !1).max(2);
382 let oh = (height & !1).max(2);
383 ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh)
384 }
385}
386
387/// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames
388/// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`.
389pub fn export_node_video_ffmpeg_with_progress(
390 engine: &mut Engine,
391 comp: &Comp,
392 opts: &VideoExportOptions,
393 control: Option<&ExportControl>,
394 mut on_progress: impl FnMut(ExportProgress),
395) -> Result<VideoExportSummary, String> {
396 if control.is_some_and(ExportControl::is_cancelled) {
397 return Err("Cancelled".to_owned());
398 }
399 let [start, end] = opts.range;
400 let total_i128 = i128::from(end) - i128::from(start) + 1;
401 if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) {
402 return Err(format!("invalid export frame range {start}..={end}"));
403 }
404 if opts.target.0 >= comp.nodes.len() {
405 return Err(format!("invalid target node id {}", opts.target.0));
406 }
407 if opts.out_path.as_os_str().is_empty() {
408 return Err("video export output path is empty".to_owned());
409 }
410 if let Some(parent) = opts.out_path.parent() {
411 if !parent.as_os_str().is_empty() {
412 std::fs::create_dir_all(parent)
413 .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
414 }
415 }
416
417 let prev_hiq = engine.hiq;
418 let prev_proxy = engine.proxy_scale;
419 engine.hiq = opts.hiq;
420 engine.proxy_scale = opts.proxy_scale.max(1);
421
422 let started_at = Instant::now();
423 let vt = probe_videotoolbox_support();
424 let encoder = select_video_encoder(opts.codec, vt, true);
425 let res = match export_node_video_ffmpeg_with_encoder(
426 engine,
427 comp,
428 opts,
429 control,
430 &mut on_progress,
431 encoder,
432 started_at,
433 ) {
434 Ok(summary) => Ok(summary),
435 Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => {
436 if control.is_some_and(ExportControl::is_cancelled) {
437 Err("Cancelled".to_owned())
438 } else {
439 let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false);
440 export_node_video_ffmpeg_with_encoder(
441 engine,
442 comp,
443 opts,
444 control,
445 &mut on_progress,
446 fallback,
447 started_at,
448 )
449 .map_err(VideoExportError::into_string)
450 }
451 }
452 Err(err) => Err(err.into_string()),
453 };
454
455 engine.hiq = prev_hiq;
456 engine.proxy_scale = prev_proxy;
457 res
458}
459
460pub(super) fn export_node_video_ffmpeg_with_encoder(
461 engine: &mut Engine,
462 comp: &Comp,
463 opts: &VideoExportOptions,
464 control: Option<&ExportControl>,
465 on_progress: &mut impl FnMut(ExportProgress),
466 encoder: VideoEncoder,
467 started_at: Instant,
468) -> Result<VideoExportSummary, VideoExportError> {
469 let [start, end] = opts.range;
470 let total = (end - start + 1) as usize;
471 let fps = comp.fps.max(1.0);
472 let node_name = comp.node(opts.target).name.clone();
473
474 // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output.
475 engine.prewarm_for_depth(comp.depth_full);
476 let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64);
477 if first_tex.size[0] == 0 || first_tex.size[1] == 0 {
478 return Err(VideoExportError::Fatal(format!(
479 "target '{}' produced empty frame {}x{}",
480 node_name, first_tex.size[0], first_tex.size[1]
481 )));
482 }
483 // If the first frame is a 1x1 dummy (e.g., missing Loader frame), fall back to comp
484 // canvas dimensions so ffmpeg never receives -s 1x1 and crashes scale=trunc(iw/2)*2.
485 let (width, height) = if first_tex.size[0] < 2 || first_tex.size[1] < 2 {
486 let ps = engine.proxy_scale.max(1);
487 let fw = (comp.width / ps).max(2);
488 let fh = (comp.height / ps).max(2);
489 if opts.codec == VideoCodec::H264Share {
490 (((fw + 1) & !1).max(2), ((fh + 1) & !1).max(2))
491 } else {
492 (fw, fh)
493 }
494 } else {
495 (first_tex.size[0], first_tex.size[1])
496 };
497 let raw_first = engine
498 .readback_rgba(&first_tex)
499 .map_err(|e| VideoExportError::Fatal(format!("GPU readback failed at frame {start}: {e}")))?;
500 let first_pixels = fit_frame_rgba(raw_first, first_tex.size, [width, height], start)
501 .map_err(VideoExportError::Fatal)?;
502 if control.is_some_and(ExportControl::is_cancelled) {
503 return Err(VideoExportError::Cancelled);
504 }
505
506 let duration_secs = total as f64 / fps;
507 let audio_start_secs = (start as f64 - comp.audio_offset) / fps;
508 let audio_path = if opts.include_audio {
509 comp.audio_filename
510 .as_deref()
511 .map(PathBuf::from)
512 .filter(|p| {
513 if p.as_os_str().is_empty() || !p.exists() || -audio_start_secs >= duration_secs {
514 return false;
515 }
516 if let Some(audio_dur) = probe_audio_duration_secs(p) {
517 if audio_dur <= 0.0 || audio_start_secs >= audio_dur {
518 return false;
519 }
520 }
521 true
522 })
523 } else {
524 None
525 };
526 let has_audio = audio_path.is_some();
527
528 let mut cmd = Command::new("ffmpeg");
529 cmd.args(["-y", "-hide_banner", "-loglevel", "error"]);
530 cmd.args([
531 "-f",
532 "rawvideo",
533 "-pix_fmt",
534 "rgba",
535 "-s",
536 &format!("{width}x{height}"),
537 "-r",
538 &format!("{fps:.6}"),
539 "-i",
540 "pipe:0",
541 ]);
542
543 let audio_filter = if let Some(ap) = &audio_path {
544 if audio_start_secs >= 0.0 {
545 if audio_start_secs > 0.0 {
546 cmd.args(["-ss", &format!("{audio_start_secs:.6}")]);
547 }
548 cmd.arg("-i").arg(ap);
549 Some(format!(
550 "asetpts=PTS-STARTPTS,apad,atrim=0:{duration_secs:.6}"
551 ))
552 } else {
553 let delay_ms = (-audio_start_secs * 1000.0).max(0.0);
554 cmd.arg("-i").arg(ap);
555 Some(format!(
556 "adelay={delay_ms:.3}:all=1,apad,atrim=0:{duration_secs:.6},asetpts=PTS-STARTPTS"
557 ))
558 }
559 } else {
560 None
561 };
562
563 let (out_width, out_height) = match opts.codec {
564 VideoCodec::H264Share => {
565 let (vf, ow, oh) = h264_scale_filter_and_dims(width, height, opts.max_height);
566 let mut encoder_args = Vec::new();
567 push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf));
568 cmd.args(&encoder_args);
569 (ow, oh)
570 }
571 VideoCodec::ProRes422 | VideoCodec::ProRes4444 => {
572 let mut encoder_args = Vec::new();
573 push_video_encoder_args(&mut encoder_args, encoder, opts.crf, None);
574 cmd.args(&encoder_args);
575 (width, height)
576 }
577 };
578
579 if let Some(af) = audio_filter {
580 cmd.args(["-map", "0:v:0", "-map", "1:a:0", "-af", &af]);
581 match opts.codec {
582 VideoCodec::H264Share => {
583 cmd.args(["-c:a", "aac", "-b:a", "128k"]);
584 }
585 VideoCodec::ProRes422 | VideoCodec::ProRes4444 => {
586 cmd.args(["-c:a", "pcm_s16le"]);
587 }
588 }
589 } else {
590 cmd.arg("-an");
591 }
592
593 let tmp_path = sibling_temp_export_path(&opts.out_path);
594 let mut tmp_guard = TempExportGuard::new(tmp_path.clone());
595 cmd.arg(&tmp_path);
596 cmd.stdin(Stdio::piped())
597 .stdout(Stdio::null())
598 .stderr(Stdio::piped());
599
600 let mut child = cmd.spawn().map_err(|e| {
601 VideoExportError::Fatal(format!(
602 "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}"
603 ))
604 })?;
605
606 let mut stderr_pipe = child.stderr.take();
607 let stderr_thread = std::thread::spawn(move || {
608 let mut buf = String::new();
609 if let Some(ref mut pipe) = stderr_pipe {
610 let _ = pipe.read_to_string(&mut buf);
611 }
612 buf
613 });
614
615 let mut readback_err: Option<String> = None;
616 let mut pipe_err: Option<String> = None;
617 let mut cancelled = false;
618 let writer_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
619 let writer_failed = Arc::new(AtomicBool::new(false));
620 let writer_fatal = Arc::new(AtomicBool::new(false));
621 let Some(stdin) = child.stdin.take() else {
622 let _ = child.kill();
623 let _ = child.wait();
624 let _ = stderr_thread.join();
625 return Err(VideoExportError::Fatal(
626 "failed to open ffmpeg stdin".to_owned(),
627 ));
628 };
629
630 let frame_bytes_len = (width as usize)
631 .saturating_mul(height as usize)
632 .saturating_mul(4)
633 .max(1);
634 let queue_cap = (128 * 1024 * 1024 / frame_bytes_len).clamp(4, 16);
635 let (tx, rx) = mpsc::sync_channel::<(i64, [u32; 2], Vec<u8>)>(queue_cap);
636 let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + 2);
637 let writer_err_c = Arc::clone(&writer_err);
638 let writer_failed_c = Arc::clone(&writer_failed);
639 let writer_fatal_c = Arc::clone(&writer_fatal);
640 let dst_size = [width, height];
641 let writer_thread = std::thread::spawn(move || {
642 let mut stdin = stdin;
643 while let Ok((frame, src_size, pixels)) = rx.recv() {
644 let frame_bytes = match fit_frame_rgba(pixels, src_size, dst_size, frame) {
645 Ok(bytes) => bytes,
646 Err(e) => {
647 if let Ok(mut g) = writer_err_c.lock() {
648 if g.is_none() {
649 *g = Some(e);
650 }
651 }
652 writer_fatal_c.store(true, Ordering::Release);
653 writer_failed_c.store(true, Ordering::Release);
654 break;
655 }
656 };
657 // Each frame is already a contiguous RGBA buffer; write directly without an extra copy.
658 if let Err(e) = stdin.write_all(&frame_bytes) {
659 if let Ok(mut g) = writer_err_c.lock() {
660 if g.is_none() {
661 *g = Some(format!("failed writing frame {frame} to ffmpeg: {e}"));
662 }
663 }
664 writer_failed_c.store(true, Ordering::Release);
665 break;
666 }
667 let _ = recycle_tx.try_send(frame_bytes);
668 }
669 let _ = stdin.flush();
670 });
671
672 if tx.send((start, [width, height], first_pixels)).is_err() {
673 pipe_err = writer_err
674 .lock()
675 .ok()
676 .and_then(|mut g| g.take())
677 .or_else(|| Some(format!("failed writing frame {start} to ffmpeg")));
678 } else {
679 let first_prog = make_progress(
680 start,
681 0,
682 total,
683 first_stats,
684 opts.out_path.clone(),
685 node_name.clone(),
686 started_at,
687 );
688 if let Some(ctrl) = control {
689 ctrl.update_progress(&first_prog);
690 }
691 on_progress(first_prog);
692 if control.is_some_and(ExportControl::is_cancelled) {
693 cancelled = true;
694 } else if start < end {
695 const PREFETCH_LOOKAHEAD: usize = 12;
696 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
697 let seed_start = start.saturating_add(1);
698 let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64).min(end);
699 for (k, f) in (seed_start..=seed_end).enumerate() {
700 prefetch.enqueue_frame(
701 comp,
702 opts.target,
703 k,
704 f as f64,
705 &engine.expr,
706 engine.use_proxy_clips,
707 );
708 }
709 let mut pending: Option<(
710 crate::eval::PendingReadback,
711 i64,
712 usize,
713 [u32; 2],
714 EvalStats,
715 )> = None;
716 for (idx, frame) in (seed_start..=end).enumerate() {
717 if control.is_some_and(ExportControl::is_cancelled) {
718 cancelled = true;
719 break;
720 }
721 if writer_failed.load(Ordering::Acquire) {
722 break;
723 }
724 prefetch.set_current_seq(idx);
725 if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) {
726 if ahead_frame <= end {
727 prefetch.enqueue_frame(
728 comp,
729 opts.target,
730 idx + PREFETCH_LOOKAHEAD,
731 ahead_frame as f64,
732 &engine.expr,
733 engine.use_proxy_clips,
734 );
735 }
736 }
737 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
738 let next_rb = match engine.begin_readback_rgba(&tex) {
739 Ok(rb) => rb,
740 Err(e) => {
741 readback_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
742 break;
743 }
744 };
745 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_stats)) =
746 pending.replace((next_rb, frame, idx, tex.size, stats))
747 {
748 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
749 if let Err(e) = prev_rb.finish_into(engine, &mut pixels) {
750 readback_err =
751 Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
752 break;
753 }
754 if control.is_some_and(ExportControl::is_cancelled) {
755 cancelled = true;
756 break;
757 }
758 if tx.send((prev_frame, prev_size, pixels)).is_err() {
759 break;
760 }
761 let prog = make_progress(
762 prev_frame,
763 prev_idx + 1,
764 total,
765 prev_stats,
766 opts.out_path.clone(),
767 node_name.clone(),
768 started_at,
769 );
770 if let Some(ctrl) = control {
771 ctrl.update_progress(&prog);
772 }
773 on_progress(prog);
774 }
775 }
776 if control.is_some_and(ExportControl::is_cancelled) {
777 cancelled = true;
778 }
779 if readback_err.is_none()
780 && pipe_err.is_none()
781 && !cancelled
782 && !writer_failed.load(Ordering::Acquire)
783 {
784 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_stats)) = pending.take()
785 {
786 let mut pixels = recycle_rx.try_recv().unwrap_or_default();
787 match prev_rb.finish_into(engine, &mut pixels) {
788 Ok(()) => {
789 if control.is_some_and(ExportControl::is_cancelled) {
790 cancelled = true;
791 } else if tx.send((prev_frame, prev_size, pixels)).is_ok() {
792 let prog = make_progress(
793 prev_frame,
794 prev_idx + 1,
795 total,
796 prev_stats,
797 opts.out_path.clone(),
798 node_name.clone(),
799 started_at,
800 );
801 if let Some(ctrl) = control {
802 ctrl.update_progress(&prog);
803 }
804 on_progress(prog);
805 if control.is_some_and(ExportControl::is_cancelled) {
806 cancelled = true;
807 }
808 }
809 }
810 Err(e) => {
811 readback_err =
812 Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
813 }
814 }
815 }
816 }
817 drop(prefetch);
818 }
819 }
820 drop(tx);
821
822 if control.is_some_and(ExportControl::is_cancelled) {
823 cancelled = true;
824 }
825 if cancelled
826 || readback_err.is_some()
827 || pipe_err.is_some()
828 || writer_failed.load(Ordering::Acquire)
829 {
830 // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately.
831 let _ = child.kill();
832 }
833 let _ = writer_thread.join();
834 if pipe_err.is_none() && !cancelled {
835 if let Ok(mut g) = writer_err.lock() {
836 pipe_err = g.take();
837 }
838 }
839 if pipe_err.is_some() && !cancelled {
840 let _ = child.kill();
841 }
842 let wait_res = child.wait();
843 let stderr_text = stderr_thread.join().unwrap_or_default();
844 let stderr_trim = stderr_text.trim();
845
846 if cancelled || control.is_some_and(ExportControl::is_cancelled) {
847 return Err(VideoExportError::Cancelled);
848 }
849 if let Some(err) = readback_err {
850 return Err(VideoExportError::Fatal(err));
851 }
852 if let Some(err) = pipe_err {
853 if writer_fatal.load(Ordering::Acquire) {
854 return Err(VideoExportError::Fatal(err));
855 }
856 return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() {
857 format!("{err} (ffmpeg: {stderr_trim})")
858 } else {
859 err
860 }));
861 }
862 let status = wait_res
863 .map_err(|e| VideoExportError::Fatal(format!("failed waiting on ffmpeg: {e}")))?;
864 if !status.success() {
865 if control.is_some_and(ExportControl::is_cancelled) {
866 return Err(VideoExportError::Cancelled);
867 }
868 return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() {
869 format!("ffmpeg exited with {status}")
870 } else {
871 format!("ffmpeg exited with {status}: {stderr_trim}")
872 }));
873 }
874
875 std::fs::rename(&tmp_path, &opts.out_path).map_err(|e| {
876 VideoExportError::Fatal(format!(
877 "failed to finalize '{}': {e}",
878 opts.out_path.display()
879 ))
880 })?;
881 tmp_guard.disarm();
882
883 let file_bytes = std::fs::metadata(&opts.out_path)
884 .map(|m| m.len())
885 .unwrap_or(0);
886
887 Ok(VideoExportSummary {
888 out_path: opts.out_path.clone(),
889 frames_written: total,
890 width: out_width,
891 height: out_height,
892 has_audio,
893 total_ms: started_at.elapsed().as_secs_f64() * 1000.0,
894 file_bytes,
895 })
896}