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}