| ... | ... | @@ -5,10 +5,12 @@ |
| 5 | 5 | |
| 6 | 6 | use crate::eval::Engine; |
| 7 | 7 | use model::{Comp, NodeId, SaverSpec}; |
| 8 | | use std::io::{BufWriter, Read, Write}; |
| 8 | use std::io::{Read, Write}; |
| 9 | 9 | use std::path::{Path, PathBuf}; |
| 10 | 10 | use std::process::{Command, Stdio}; |
| 11 | 11 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 12 | #[cfg(target_os = "macos")] |
| 13 | use std::sync::OnceLock; |
| 12 | 14 | use std::sync::{Arc, Mutex, mpsc}; |
| 13 | 15 | use std::time::Instant; |
| 14 | 16 | |
| ... | ... | @@ -515,11 +517,11 @@ pub fn export_saver_png_sequence_with_progress( |
| 515 | 517 | /// Output video codec profile for direct viewer / node ffmpeg export. |
| 516 | 518 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 517 | 519 | pub enum VideoCodec { |
| 518 | | /// H.264 (`libx264`, `yuv420p`, `-movflags +faststart`) for compact shareable MP4 snippets. |
| 520 | /// H.264 (`h264_videotoolbox` on macOS when available, `libx264` fallback, `yuv420p`, `-movflags +faststart`) for compact shareable MP4 snippets. |
| 519 | 521 | H264Share, |
| 520 | | /// Apple ProRes 422 (`prores_ks -profile:v 2 -pix_fmt yuv422p10le`). |
| 522 | /// Apple ProRes 422 (`prores_videotoolbox` on macOS when available, `prores_ks` fallback, `-profile:v 2`). |
| 521 | 523 | ProRes422, |
| 522 | | /// Apple ProRes 4444 with alpha (`prores_ks -profile:v 4 -pix_fmt yuva444p10le`). |
| 524 | /// Apple ProRes 4444 with alpha (`prores_videotoolbox` on macOS when available, `prores_ks` fallback, `-profile:v 4`). |
| 523 | 525 | ProRes4444, |
| 524 | 526 | } |
| 525 | 527 | |
| ... | ... | @@ -652,12 +654,207 @@ fn probe_audio_duration_secs(path: &Path) -> Option<f64> { |
| 652 | 654 | stream_dur.or(format_dur) |
| 653 | 655 | } |
| 654 | 656 | |
| 657 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 658 | struct VideoToolboxSupport { |
| 659 | h264: bool, |
| 660 | prores: bool, |
| 661 | } |
| 662 | |
| 663 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 664 | enum VideoEncoder { |
| 665 | Libx264, |
| 666 | H264VideoToolbox, |
| 667 | ProResKs422, |
| 668 | ProResVideoToolbox422, |
| 669 | ProResKs4444, |
| 670 | ProResVideoToolbox4444, |
| 671 | } |
| 672 | |
| 673 | impl VideoEncoder { |
| 674 | fn is_hardware_accelerated(self) -> bool { |
| 675 | matches!( |
| 676 | self, |
| 677 | Self::H264VideoToolbox | Self::ProResVideoToolbox422 | Self::ProResVideoToolbox4444 |
| 678 | ) |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | #[cfg_attr(not(target_os = "macos"), allow(dead_code))] |
| 683 | fn parse_videotoolbox_encoders(encoders_stdout: &str) -> VideoToolboxSupport { |
| 684 | let mut support = VideoToolboxSupport::default(); |
| 685 | for line in encoders_stdout.lines() { |
| 686 | let mut parts = line.split_whitespace(); |
| 687 | let Some(flags) = parts.next() else { |
| 688 | continue; |
| 689 | }; |
| 690 | if !flags.starts_with('V') { |
| 691 | continue; |
| 692 | } |
| 693 | let Some(name) = parts.next() else { |
| 694 | continue; |
| 695 | }; |
| 696 | match name { |
| 697 | "h264_videotoolbox" => support.h264 = true, |
| 698 | "prores_videotoolbox" => support.prores = true, |
| 699 | _ => {} |
| 700 | } |
| 701 | } |
| 702 | support |
| 703 | } |
| 704 | |
| 705 | #[cfg(target_os = "macos")] |
| 706 | fn probe_videotoolbox_support() -> VideoToolboxSupport { |
| 707 | static VT_SUPPORT: OnceLock<VideoToolboxSupport> = OnceLock::new(); |
| 708 | *VT_SUPPORT.get_or_init(|| { |
| 709 | let Ok(out) = Command::new("ffmpeg") |
| 710 | .args(["-hide_banner", "-encoders"]) |
| 711 | .output() |
| 712 | else { |
| 713 | return VideoToolboxSupport::default(); |
| 714 | }; |
| 715 | if !out.status.success() { |
| 716 | return VideoToolboxSupport::default(); |
| 717 | } |
| 718 | let text = String::from_utf8_lossy(&out.stdout); |
| 719 | parse_videotoolbox_encoders(&text) |
| 720 | }) |
| 721 | } |
| 722 | |
| 723 | #[cfg(not(target_os = "macos"))] |
| 724 | fn probe_videotoolbox_support() -> VideoToolboxSupport { |
| 725 | VideoToolboxSupport::default() |
| 726 | } |
| 727 | |
| 728 | fn select_video_encoder( |
| 729 | codec: VideoCodec, |
| 730 | vt: VideoToolboxSupport, |
| 731 | allow_videotoolbox: bool, |
| 732 | ) -> VideoEncoder { |
| 733 | match codec { |
| 734 | VideoCodec::H264Share => { |
| 735 | if allow_videotoolbox && vt.h264 { |
| 736 | VideoEncoder::H264VideoToolbox |
| 737 | } else { |
| 738 | VideoEncoder::Libx264 |
| 739 | } |
| 740 | } |
| 741 | VideoCodec::ProRes422 => { |
| 742 | if allow_videotoolbox && vt.prores { |
| 743 | VideoEncoder::ProResVideoToolbox422 |
| 744 | } else { |
| 745 | VideoEncoder::ProResKs422 |
| 746 | } |
| 747 | } |
| 748 | VideoCodec::ProRes4444 => { |
| 749 | if allow_videotoolbox && vt.prores { |
| 750 | VideoEncoder::ProResVideoToolbox4444 |
| 751 | } else { |
| 752 | VideoEncoder::ProResKs4444 |
| 753 | } |
| 754 | } |
| 755 | } |
| 756 | } |
| 757 | |
| 758 | /// Maps x264-style CRF (`0..=51`, lower = higher quality) to VideoToolbox `-q:v` (`15..=95`, higher = higher quality). |
| 759 | fn vt_quality_from_crf(crf: u8) -> u8 { |
| 760 | (104 - i32::from(crf) * 2).clamp(15, 95) as u8 |
| 761 | } |
| 762 | |
| 763 | fn push_video_encoder_args(args: &mut Vec<String>, encoder: VideoEncoder, crf: u8, vf: Option<&str>) { |
| 764 | match encoder { |
| 765 | VideoEncoder::H264VideoToolbox => { |
| 766 | if let Some(vf) = vf { |
| 767 | args.extend(["-vf".to_owned(), vf.to_owned()]); |
| 768 | } |
| 769 | args.extend([ |
| 770 | "-c:v".to_owned(), |
| 771 | "h264_videotoolbox".to_owned(), |
| 772 | "-q:v".to_owned(), |
| 773 | vt_quality_from_crf(crf).to_string(), |
| 774 | "-pix_fmt".to_owned(), |
| 775 | "yuv420p".to_owned(), |
| 776 | "-tag:v".to_owned(), |
| 777 | "avc1".to_owned(), |
| 778 | "-movflags".to_owned(), |
| 779 | "+faststart".to_owned(), |
| 780 | ]); |
| 781 | } |
| 782 | VideoEncoder::Libx264 => { |
| 783 | if let Some(vf) = vf { |
| 784 | args.extend(["-vf".to_owned(), vf.to_owned()]); |
| 785 | } |
| 786 | args.extend([ |
| 787 | "-c:v".to_owned(), |
| 788 | "libx264".to_owned(), |
| 789 | "-preset".to_owned(), |
| 790 | "medium".to_owned(), |
| 791 | "-crf".to_owned(), |
| 792 | crf.to_string(), |
| 793 | "-pix_fmt".to_owned(), |
| 794 | "yuv420p".to_owned(), |
| 795 | "-movflags".to_owned(), |
| 796 | "+faststart".to_owned(), |
| 797 | ]); |
| 798 | } |
| 799 | VideoEncoder::ProResVideoToolbox422 => { |
| 800 | args.extend([ |
| 801 | "-c:v".to_owned(), |
| 802 | "prores_videotoolbox".to_owned(), |
| 803 | "-profile:v".to_owned(), |
| 804 | "2".to_owned(), |
| 805 | "-pix_fmt".to_owned(), |
| 806 | "p210le".to_owned(), |
| 807 | ]); |
| 808 | } |
| 809 | VideoEncoder::ProResKs422 => { |
| 810 | args.extend([ |
| 811 | "-c:v".to_owned(), |
| 812 | "prores_ks".to_owned(), |
| 813 | "-profile:v".to_owned(), |
| 814 | "2".to_owned(), |
| 815 | "-pix_fmt".to_owned(), |
| 816 | "yuv422p10le".to_owned(), |
| 817 | ]); |
| 818 | } |
| 819 | VideoEncoder::ProResVideoToolbox4444 => { |
| 820 | args.extend([ |
| 821 | "-c:v".to_owned(), |
| 822 | "prores_videotoolbox".to_owned(), |
| 823 | "-profile:v".to_owned(), |
| 824 | "4".to_owned(), |
| 825 | "-pix_fmt".to_owned(), |
| 826 | "ayuv64le".to_owned(), |
| 827 | ]); |
| 828 | } |
| 829 | VideoEncoder::ProResKs4444 => { |
| 830 | args.extend([ |
| 831 | "-c:v".to_owned(), |
| 832 | "prores_ks".to_owned(), |
| 833 | "-profile:v".to_owned(), |
| 834 | "4".to_owned(), |
| 835 | "-pix_fmt".to_owned(), |
| 836 | "yuva444p10le".to_owned(), |
| 837 | ]); |
| 838 | } |
| 839 | } |
| 840 | } |
| 841 | |
| 655 | 842 | fn fit_frame_rgba( |
| 656 | 843 | pixels: Vec<u8>, |
| 657 | 844 | src_size: [u32; 2], |
| 658 | 845 | dst_size: [u32; 2], |
| 659 | 846 | frame: i64, |
| 660 | 847 | ) -> Result<Vec<u8>, String> { |
| 848 | let expected_len = (src_size[0] as usize) |
| 849 | .checked_mul(src_size[1] as usize) |
| 850 | .and_then(|px| px.checked_mul(4)) |
| 851 | .ok_or_else(|| format!("frame {frame} dimensions overflow buffer size"))?; |
| 852 | if pixels.len() != expected_len { |
| 853 | return Err(format!( |
| 854 | "invalid RGBA buffer size at frame {frame}: expected {expected_len}, got {}", |
| 855 | pixels.len() |
| 856 | )); |
| 857 | } |
| 661 | 858 | if src_size == dst_size { |
| 662 | 859 | return Ok(pixels); |
| 663 | 860 | } |
| ... | ... | @@ -712,6 +909,22 @@ impl Drop for TempExportGuard { |
| 712 | 909 | } |
| 713 | 910 | } |
| 714 | 911 | |
| 912 | #[derive(Debug)] |
| 913 | enum VideoExportError { |
| 914 | Cancelled, |
| 915 | Fatal(String), |
| 916 | EncoderFailed(String), |
| 917 | } |
| 918 | |
| 919 | impl VideoExportError { |
| 920 | fn into_string(self) -> String { |
| 921 | match self { |
| 922 | Self::Cancelled => "Cancelled".to_owned(), |
| 923 | Self::Fatal(s) | Self::EncoderFailed(s) => s, |
| 924 | } |
| 925 | } |
| 926 | } |
| 927 | |
| 715 | 928 | /// Evaluates `opts.target` over `opts.range[0]..=opts.range[1]`, pipes raw RGBA8 frames |
| 716 | 929 | /// directly into `ffmpeg` with cooperative cancellation and live progress via `ExportControl`. |
| 717 | 930 | pub fn export_node_video_ffmpeg_with_progress( |
| ... | ... | @@ -746,422 +959,441 @@ pub fn export_node_video_ffmpeg_with_progress( |
| 746 | 959 | engine.hiq = opts.hiq; |
| 747 | 960 | engine.proxy_scale = opts.proxy_scale.max(1); |
| 748 | 961 | |
| 749 | | let res = (|| -> Result<VideoExportSummary, String> { |
| 750 | | let t0 = Instant::now(); |
| 751 | | let total = (end - start + 1) as usize; |
| 752 | | let fps = comp.fps.max(1.0); |
| 753 | | let node_name = comp.node(opts.target).name.clone(); |
| 754 | | |
| 755 | | // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output. |
| 756 | | engine.prewarm_for_depth(comp.depth_full); |
| 757 | | let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64); |
| 758 | | if first_tex.size[0] == 0 || first_tex.size[1] == 0 { |
| 759 | | return Err(format!( |
| 760 | | "target '{}' produced empty frame {}x{}", |
| 761 | | node_name, first_tex.size[0], first_tex.size[1] |
| 762 | | )); |
| 962 | let vt = probe_videotoolbox_support(); |
| 963 | let encoder = select_video_encoder(opts.codec, vt, true); |
| 964 | let res = match export_node_video_ffmpeg_with_encoder( |
| 965 | engine, |
| 966 | comp, |
| 967 | opts, |
| 968 | control, |
| 969 | &mut on_progress, |
| 970 | encoder, |
| 971 | ) { |
| 972 | Ok(summary) => Ok(summary), |
| 973 | Err(VideoExportError::EncoderFailed(_)) if encoder.is_hardware_accelerated() => { |
| 974 | let fallback = select_video_encoder(opts.codec, VideoToolboxSupport::default(), false); |
| 975 | export_node_video_ffmpeg_with_encoder( |
| 976 | engine, |
| 977 | comp, |
| 978 | opts, |
| 979 | control, |
| 980 | &mut on_progress, |
| 981 | fallback, |
| 982 | ) |
| 983 | .map_err(VideoExportError::into_string) |
| 763 | 984 | } |
| 764 | | // If the first frame is a 1x1 dummy (e.g., missing Loader frame), fall back to comp |
| 765 | | // canvas dimensions so ffmpeg never receives -s 1x1 and crashes scale=trunc(iw/2)*2. |
| 766 | | let (width, height) = if first_tex.size[0] < 2 || first_tex.size[1] < 2 { |
| 767 | | let ps = engine.proxy_scale.max(1); |
| 768 | | let fw = (comp.width / ps).max(2); |
| 769 | | let fh = (comp.height / ps).max(2); |
| 770 | | if opts.codec == VideoCodec::H264Share { |
| 771 | | (((fw + 1) & !1).max(2), ((fh + 1) & !1).max(2)) |
| 772 | | } else { |
| 773 | | (fw, fh) |
| 774 | | } |
| 985 | Err(err) => Err(err.into_string()), |
| 986 | }; |
| 987 | |
| 988 | engine.hiq = prev_hiq; |
| 989 | engine.proxy_scale = prev_proxy; |
| 990 | res |
| 991 | } |
| 992 | |
| 993 | fn export_node_video_ffmpeg_with_encoder( |
| 994 | engine: &mut Engine, |
| 995 | comp: &Comp, |
| 996 | opts: &VideoExportOptions, |
| 997 | control: Option<&ExportControl>, |
| 998 | on_progress: &mut impl FnMut(ExportProgress), |
| 999 | encoder: VideoEncoder, |
| 1000 | ) -> Result<VideoExportSummary, VideoExportError> { |
| 1001 | let [start, end] = opts.range; |
| 1002 | let t0 = Instant::now(); |
| 1003 | let total = (end - start + 1) as usize; |
| 1004 | let fps = comp.fps.max(1.0); |
| 1005 | let node_name = comp.node(opts.target).name.clone(); |
| 1006 | |
| 1007 | // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output. |
| 1008 | engine.prewarm_for_depth(comp.depth_full); |
| 1009 | let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64); |
| 1010 | if first_tex.size[0] == 0 || first_tex.size[1] == 0 { |
| 1011 | return Err(VideoExportError::Fatal(format!( |
| 1012 | "target '{}' produced empty frame {}x{}", |
| 1013 | node_name, first_tex.size[0], first_tex.size[1] |
| 1014 | ))); |
| 1015 | } |
| 1016 | // If the first frame is a 1x1 dummy (e.g., missing Loader frame), fall back to comp |
| 1017 | // canvas dimensions so ffmpeg never receives -s 1x1 and crashes scale=trunc(iw/2)*2. |
| 1018 | let (width, height) = if first_tex.size[0] < 2 || first_tex.size[1] < 2 { |
| 1019 | let ps = engine.proxy_scale.max(1); |
| 1020 | let fw = (comp.width / ps).max(2); |
| 1021 | let fh = (comp.height / ps).max(2); |
| 1022 | if opts.codec == VideoCodec::H264Share { |
| 1023 | (((fw + 1) & !1).max(2), ((fh + 1) & !1).max(2)) |
| 775 | 1024 | } else { |
| 776 | | (first_tex.size[0], first_tex.size[1]) |
| 777 | | }; |
| 778 | | let raw_first = engine |
| 779 | | .readback_rgba(&first_tex) |
| 780 | | .map_err(|e| format!("GPU readback failed at frame {start}: {e}"))?; |
| 781 | | let first_pixels = fit_frame_rgba(raw_first, first_tex.size, [width, height], start)?; |
| 782 | | if control.is_some_and(ExportControl::is_cancelled) { |
| 783 | | return Err("Cancelled".to_owned()); |
| 1025 | (fw, fh) |
| 784 | 1026 | } |
| 1027 | } else { |
| 1028 | (first_tex.size[0], first_tex.size[1]) |
| 1029 | }; |
| 1030 | let raw_first = engine |
| 1031 | .readback_rgba(&first_tex) |
| 1032 | .map_err(|e| VideoExportError::Fatal(format!("GPU readback failed at frame {start}: {e}")))?; |
| 1033 | let first_pixels = fit_frame_rgba(raw_first, first_tex.size, [width, height], start) |
| 1034 | .map_err(VideoExportError::Fatal)?; |
| 1035 | if control.is_some_and(ExportControl::is_cancelled) { |
| 1036 | return Err(VideoExportError::Cancelled); |
| 1037 | } |
| 785 | 1038 | |
| 786 | | let duration_secs = total as f64 / fps; |
| 787 | | let audio_start_secs = (start as f64 - comp.audio_offset) / fps; |
| 788 | | let audio_path = if opts.include_audio { |
| 789 | | comp.audio_filename |
| 790 | | .as_deref() |
| 791 | | .map(PathBuf::from) |
| 792 | | .filter(|p| { |
| 793 | | if p.as_os_str().is_empty() || !p.exists() || -audio_start_secs >= duration_secs { |
| 1039 | let duration_secs = total as f64 / fps; |
| 1040 | let audio_start_secs = (start as f64 - comp.audio_offset) / fps; |
| 1041 | let audio_path = if opts.include_audio { |
| 1042 | comp.audio_filename |
| 1043 | .as_deref() |
| 1044 | .map(PathBuf::from) |
| 1045 | .filter(|p| { |
| 1046 | if p.as_os_str().is_empty() || !p.exists() || -audio_start_secs >= duration_secs { |
| 1047 | return false; |
| 1048 | } |
| 1049 | if let Some(audio_dur) = probe_audio_duration_secs(p) { |
| 1050 | if audio_dur <= 0.0 || audio_start_secs >= audio_dur { |
| 794 | 1051 | return false; |
| 795 | 1052 | } |
| 796 | | if let Some(audio_dur) = probe_audio_duration_secs(p) { |
| 797 | | if audio_dur <= 0.0 || audio_start_secs >= audio_dur { |
| 798 | | return false; |
| 799 | | } |
| 800 | | } |
| 801 | | true |
| 802 | | }) |
| 803 | | } else { |
| 804 | | None |
| 805 | | }; |
| 806 | | let has_audio = audio_path.is_some(); |
| 807 | | |
| 808 | | let mut cmd = Command::new("ffmpeg"); |
| 809 | | cmd.args(["-y", "-hide_banner", "-loglevel", "error"]); |
| 810 | | cmd.args([ |
| 811 | | "-f", |
| 812 | | "rawvideo", |
| 813 | | "-pix_fmt", |
| 814 | | "rgba", |
| 815 | | "-s", |
| 816 | | &format!("{width}x{height}"), |
| 817 | | "-r", |
| 818 | | &format!("{fps:.6}"), |
| 819 | | "-i", |
| 820 | | "pipe:0", |
| 821 | | ]); |
| 822 | | |
| 823 | | let audio_filter = if let Some(ap) = &audio_path { |
| 824 | | if audio_start_secs >= 0.0 { |
| 825 | | if audio_start_secs > 0.0 { |
| 826 | | cmd.args(["-ss", &format!("{audio_start_secs:.6}")]); |
| 827 | 1053 | } |
| 828 | | cmd.arg("-i").arg(ap); |
| 829 | | Some(format!("asetpts=PTS-STARTPTS,apad,atrim=0:{duration_secs:.6}")) |
| 830 | | } else { |
| 831 | | let delay_ms = (-audio_start_secs * 1000.0).max(0.0); |
| 832 | | cmd.arg("-i").arg(ap); |
| 833 | | Some(format!( |
| 834 | | "adelay={delay_ms:.3}:all=1,apad,atrim=0:{duration_secs:.6},asetpts=PTS-STARTPTS" |
| 835 | | )) |
| 1054 | true |
| 1055 | }) |
| 1056 | } else { |
| 1057 | None |
| 1058 | }; |
| 1059 | let has_audio = audio_path.is_some(); |
| 1060 | |
| 1061 | let mut cmd = Command::new("ffmpeg"); |
| 1062 | cmd.args(["-y", "-hide_banner", "-loglevel", "error"]); |
| 1063 | cmd.args([ |
| 1064 | "-f", |
| 1065 | "rawvideo", |
| 1066 | "-pix_fmt", |
| 1067 | "rgba", |
| 1068 | "-s", |
| 1069 | &format!("{width}x{height}"), |
| 1070 | "-r", |
| 1071 | &format!("{fps:.6}"), |
| 1072 | "-i", |
| 1073 | "pipe:0", |
| 1074 | ]); |
| 1075 | |
| 1076 | let audio_filter = if let Some(ap) = &audio_path { |
| 1077 | if audio_start_secs >= 0.0 { |
| 1078 | if audio_start_secs > 0.0 { |
| 1079 | cmd.args(["-ss", &format!("{audio_start_secs:.6}")]); |
| 836 | 1080 | } |
| 1081 | cmd.arg("-i").arg(ap); |
| 1082 | Some(format!("asetpts=PTS-STARTPTS,apad,atrim=0:{duration_secs:.6}")) |
| 837 | 1083 | } else { |
| 838 | | None |
| 839 | | }; |
| 1084 | let delay_ms = (-audio_start_secs * 1000.0).max(0.0); |
| 1085 | cmd.arg("-i").arg(ap); |
| 1086 | Some(format!( |
| 1087 | "adelay={delay_ms:.3}:all=1,apad,atrim=0:{duration_secs:.6},asetpts=PTS-STARTPTS" |
| 1088 | )) |
| 1089 | } |
| 1090 | } else { |
| 1091 | None |
| 1092 | }; |
| 840 | 1093 | |
| 841 | | let (out_width, out_height) = match opts.codec { |
| 842 | | VideoCodec::H264Share => { |
| 843 | | let (vf, ow, oh) = if let Some(max_h) = opts.max_height.filter(|&h| h >= 2) { |
| 844 | | let oh = (height.min(max_h) & !1).max(2); |
| 845 | | let ow = if height > max_h { |
| 846 | | let scaled = ((width as f64) * (oh as f64) / (height as f64)).round() as u32; |
| 847 | | (scaled & !1).max(2) |
| 848 | | } else { |
| 849 | | (width & !1).max(2) |
| 850 | | }; |
| 851 | | (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh) |
| 1094 | let (out_width, out_height) = match opts.codec { |
| 1095 | VideoCodec::H264Share => { |
| 1096 | let (vf, ow, oh) = if let Some(max_h) = opts.max_height.filter(|&h| h >= 2) { |
| 1097 | let oh = (height.min(max_h) & !1).max(2); |
| 1098 | let ow = if height > max_h { |
| 1099 | let scaled = ((width as f64) * (oh as f64) / (height as f64)).round() as u32; |
| 1100 | (scaled & !1).max(2) |
| 852 | 1101 | } else { |
| 853 | | let ow = (width & !1).max(2); |
| 854 | | let oh = (height & !1).max(2); |
| 855 | | ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh) |
| 1102 | (width & !1).max(2) |
| 856 | 1103 | }; |
| 857 | | cmd.args([ |
| 858 | | "-vf", |
| 859 | | &vf, |
| 860 | | "-c:v", |
| 861 | | "libx264", |
| 862 | | "-preset", |
| 863 | | "medium", |
| 864 | | "-crf", |
| 865 | | &opts.crf.to_string(), |
| 866 | | "-pix_fmt", |
| 867 | | "yuv420p", |
| 868 | | "-movflags", |
| 869 | | "+faststart", |
| 870 | | ]); |
| 871 | | (ow, oh) |
| 872 | | } |
| 873 | | VideoCodec::ProRes422 => { |
| 874 | | cmd.args([ |
| 875 | | "-c:v", |
| 876 | | "prores_ks", |
| 877 | | "-profile:v", |
| 878 | | "2", |
| 879 | | "-pix_fmt", |
| 880 | | "yuv422p10le", |
| 881 | | ]); |
| 882 | | (width, height) |
| 1104 | (format!("scale=-2:trunc(min(ih\\,{max_h})/2)*2"), ow, oh) |
| 1105 | } else { |
| 1106 | let ow = (width & !1).max(2); |
| 1107 | let oh = (height & !1).max(2); |
| 1108 | ("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_owned(), ow, oh) |
| 1109 | }; |
| 1110 | let mut encoder_args = Vec::new(); |
| 1111 | push_video_encoder_args(&mut encoder_args, encoder, opts.crf, Some(&vf)); |
| 1112 | cmd.args(&encoder_args); |
| 1113 | (ow, oh) |
| 1114 | } |
| 1115 | VideoCodec::ProRes422 | VideoCodec::ProRes4444 => { |
| 1116 | let mut encoder_args = Vec::new(); |
| 1117 | push_video_encoder_args(&mut encoder_args, encoder, opts.crf, None); |
| 1118 | cmd.args(&encoder_args); |
| 1119 | (width, height) |
| 1120 | } |
| 1121 | }; |
| 1122 | |
| 1123 | if let Some(af) = audio_filter { |
| 1124 | cmd.args(["-map", "0:v:0", "-map", "1:a:0", "-af", &af]); |
| 1125 | match opts.codec { |
| 1126 | VideoCodec::H264Share => { |
| 1127 | cmd.args(["-c:a", "aac", "-b:a", "128k"]); |
| 883 | 1128 | } |
| 884 | | VideoCodec::ProRes4444 => { |
| 885 | | cmd.args([ |
| 886 | | "-c:v", |
| 887 | | "prores_ks", |
| 888 | | "-profile:v", |
| 889 | | "4", |
| 890 | | "-pix_fmt", |
| 891 | | "yuva444p10le", |
| 892 | | ]); |
| 893 | | (width, height) |
| 1129 | VideoCodec::ProRes422 | VideoCodec::ProRes4444 => { |
| 1130 | cmd.args(["-c:a", "pcm_s16le"]); |
| 894 | 1131 | } |
| 895 | | }; |
| 1132 | } |
| 1133 | } else { |
| 1134 | cmd.arg("-an"); |
| 1135 | } |
| 896 | 1136 | |
| 897 | | if let Some(af) = audio_filter { |
| 898 | | cmd.args(["-map", "0:v:0", "-map", "1:a:0", "-af", &af]); |
| 899 | | match opts.codec { |
| 900 | | VideoCodec::H264Share => { |
| 901 | | cmd.args(["-c:a", "aac", "-b:a", "128k"]); |
| 902 | | } |
| 903 | | VideoCodec::ProRes422 | VideoCodec::ProRes4444 => { |
| 904 | | cmd.args(["-c:a", "pcm_s16le"]); |
| 905 | | } |
| 906 | | } |
| 907 | | } else { |
| 908 | | cmd.arg("-an"); |
| 1137 | let tmp_path = sibling_temp_export_path(&opts.out_path); |
| 1138 | let mut tmp_guard = TempExportGuard::new(tmp_path.clone()); |
| 1139 | cmd.arg(&tmp_path); |
| 1140 | cmd.stdin(Stdio::piped()) |
| 1141 | .stdout(Stdio::null()) |
| 1142 | .stderr(Stdio::piped()); |
| 1143 | |
| 1144 | let mut child = cmd.spawn().map_err(|e| { |
| 1145 | VideoExportError::EncoderFailed(format!( |
| 1146 | "failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}" |
| 1147 | )) |
| 1148 | })?; |
| 1149 | |
| 1150 | let mut stderr_pipe = child.stderr.take(); |
| 1151 | let stderr_thread = std::thread::spawn(move || { |
| 1152 | let mut buf = String::new(); |
| 1153 | if let Some(ref mut pipe) = stderr_pipe { |
| 1154 | let _ = pipe.read_to_string(&mut buf); |
| 909 | 1155 | } |
| 1156 | buf |
| 1157 | }); |
| 910 | 1158 | |
| 911 | | let tmp_path = sibling_temp_export_path(&opts.out_path); |
| 912 | | let mut tmp_guard = TempExportGuard::new(tmp_path.clone()); |
| 913 | | cmd.arg(&tmp_path); |
| 914 | | cmd.stdin(Stdio::piped()) |
| 915 | | .stdout(Stdio::null()) |
| 916 | | .stderr(Stdio::piped()); |
| 917 | | |
| 918 | | let mut child = cmd |
| 919 | | .spawn() |
| 920 | | .map_err(|e| format!("failed to launch ffmpeg (is ffmpeg installed on PATH?): {e}"))?; |
| 921 | | |
| 922 | | let mut stderr_pipe = child.stderr.take(); |
| 923 | | let stderr_thread = std::thread::spawn(move || { |
| 924 | | let mut buf = String::new(); |
| 925 | | if let Some(ref mut pipe) = stderr_pipe { |
| 926 | | let _ = pipe.read_to_string(&mut buf); |
| 927 | | } |
| 928 | | buf |
| 929 | | }); |
| 930 | | |
| 931 | | let mut pipe_err: Option<String> = None; |
| 932 | | let mut cancelled = false; |
| 933 | | let writer_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); |
| 934 | | let writer_failed = Arc::new(AtomicBool::new(false)); |
| 935 | | let stdin = child |
| 936 | | .stdin |
| 937 | | .take() |
| 938 | | .ok_or_else(|| "failed to open ffmpeg stdin".to_owned())?; |
| 939 | | |
| 940 | | let frame_bytes_len = (width as usize) |
| 941 | | .saturating_mul(height as usize) |
| 942 | | .saturating_mul(4) |
| 943 | | .max(1); |
| 944 | | let queue_cap = (128 * 1024 * 1024 / frame_bytes_len).clamp(4, 16); |
| 945 | | let (tx, rx) = mpsc::sync_channel::<(i64, [u32; 2], Vec<u8>)>(queue_cap); |
| 946 | | let writer_err_c = Arc::clone(&writer_err); |
| 947 | | let writer_failed_c = Arc::clone(&writer_failed); |
| 948 | | let dst_size = [width, height]; |
| 949 | | let writer_thread = std::thread::spawn(move || { |
| 950 | | let mut stdin = BufWriter::with_capacity(4 * 1024 * 1024, stdin); |
| 951 | | while let Ok((frame, src_size, pixels)) = rx.recv() { |
| 952 | | let frame_bytes = match fit_frame_rgba(pixels, src_size, dst_size, frame) { |
| 953 | | Ok(bytes) => bytes, |
| 954 | | Err(e) => { |
| 955 | | if let Ok(mut g) = writer_err_c.lock() { |
| 956 | | if g.is_none() { |
| 957 | | *g = Some(e); |
| 958 | | } |
| 959 | | } |
| 960 | | writer_failed_c.store(true, Ordering::Release); |
| 961 | | break; |
| 962 | | } |
| 963 | | }; |
| 964 | | if let Err(e) = stdin.write_all(&frame_bytes) { |
| 1159 | let mut readback_err: Option<String> = None; |
| 1160 | let mut pipe_err: Option<String> = None; |
| 1161 | let mut cancelled = false; |
| 1162 | let writer_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); |
| 1163 | let writer_failed = Arc::new(AtomicBool::new(false)); |
| 1164 | let stdin = child |
| 1165 | .stdin |
| 1166 | .take() |
| 1167 | .ok_or_else(|| VideoExportError::EncoderFailed("failed to open ffmpeg stdin".to_owned()))?; |
| 1168 | |
| 1169 | let frame_bytes_len = (width as usize) |
| 1170 | .saturating_mul(height as usize) |
| 1171 | .saturating_mul(4) |
| 1172 | .max(1); |
| 1173 | let queue_cap = (128 * 1024 * 1024 / frame_bytes_len).clamp(4, 16); |
| 1174 | let (tx, rx) = mpsc::sync_channel::<(i64, [u32; 2], Vec<u8>)>(queue_cap); |
| 1175 | let writer_err_c = Arc::clone(&writer_err); |
| 1176 | let writer_failed_c = Arc::clone(&writer_failed); |
| 1177 | let dst_size = [width, height]; |
| 1178 | let writer_thread = std::thread::spawn(move || { |
| 1179 | let mut stdin = stdin; |
| 1180 | while let Ok((frame, src_size, pixels)) = rx.recv() { |
| 1181 | let frame_bytes = match fit_frame_rgba(pixels, src_size, dst_size, frame) { |
| 1182 | Ok(bytes) => bytes, |
| 1183 | Err(e) => { |
| 965 | 1184 | if let Ok(mut g) = writer_err_c.lock() { |
| 966 | 1185 | if g.is_none() { |
| 967 | | *g = Some(format!("failed writing frame {frame} to ffmpeg: {e}")); |
| 1186 | *g = Some(e); |
| 968 | 1187 | } |
| 969 | 1188 | } |
| 970 | 1189 | writer_failed_c.store(true, Ordering::Release); |
| 971 | 1190 | break; |
| 972 | 1191 | } |
| 1192 | }; |
| 1193 | // Each frame is already a contiguous RGBA buffer; write directly without an extra copy. |
| 1194 | if let Err(e) = stdin.write_all(&frame_bytes) { |
| 1195 | if let Ok(mut g) = writer_err_c.lock() { |
| 1196 | if g.is_none() { |
| 1197 | *g = Some(format!("failed writing frame {frame} to ffmpeg: {e}")); |
| 1198 | } |
| 1199 | } |
| 1200 | writer_failed_c.store(true, Ordering::Release); |
| 1201 | break; |
| 973 | 1202 | } |
| 974 | | let _ = stdin.flush(); |
| 975 | | }); |
| 976 | | |
| 977 | | if tx.send((start, [width, height], first_pixels)).is_err() { |
| 978 | | pipe_err = writer_err |
| 979 | | .lock() |
| 980 | | .ok() |
| 981 | | .and_then(|mut g| g.take()) |
| 982 | | .or_else(|| Some(format!("failed writing frame {start} to ffmpeg"))); |
| 983 | | } else { |
| 984 | | let first_prog = make_progress( |
| 985 | | start, |
| 986 | | 0, |
| 987 | | total, |
| 988 | | first_stats.eval_ms, |
| 989 | | opts.out_path.clone(), |
| 990 | | node_name.clone(), |
| 991 | | t0, |
| 992 | | ); |
| 993 | | if let Some(ctrl) = control { |
| 994 | | ctrl.update_progress(&first_prog); |
| 1203 | } |
| 1204 | let _ = stdin.flush(); |
| 1205 | }); |
| 1206 | |
| 1207 | if tx.send((start, [width, height], first_pixels)).is_err() { |
| 1208 | pipe_err = writer_err |
| 1209 | .lock() |
| 1210 | .ok() |
| 1211 | .and_then(|mut g| g.take()) |
| 1212 | .or_else(|| Some(format!("failed writing frame {start} to ffmpeg"))); |
| 1213 | } else { |
| 1214 | let first_prog = make_progress( |
| 1215 | start, |
| 1216 | 0, |
| 1217 | total, |
| 1218 | first_stats.eval_ms, |
| 1219 | opts.out_path.clone(), |
| 1220 | node_name.clone(), |
| 1221 | t0, |
| 1222 | ); |
| 1223 | if let Some(ctrl) = control { |
| 1224 | ctrl.update_progress(&first_prog); |
| 1225 | } |
| 1226 | on_progress(first_prog); |
| 1227 | if control.is_some_and(ExportControl::is_cancelled) { |
| 1228 | cancelled = true; |
| 1229 | } else if start < end { |
| 1230 | const PREFETCH_LOOKAHEAD: usize = 12; |
| 1231 | let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); |
| 1232 | let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end); |
| 1233 | for (k, f) in ((start + 1)..=seed_end).enumerate() { |
| 1234 | prefetch.enqueue_frame( |
| 1235 | comp, |
| 1236 | opts.target, |
| 1237 | k, |
| 1238 | f as f64, |
| 1239 | &engine.expr, |
| 1240 | engine.use_proxy_clips, |
| 1241 | ); |
| 995 | 1242 | } |
| 996 | | on_progress(first_prog); |
| 997 | | if control.is_some_and(ExportControl::is_cancelled) { |
| 998 | | cancelled = true; |
| 999 | | } else if start < end { |
| 1000 | | const PREFETCH_LOOKAHEAD: usize = 12; |
| 1001 | | let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); |
| 1002 | | let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end); |
| 1003 | | for (k, f) in ((start + 1)..=seed_end).enumerate() { |
| 1243 | let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None; |
| 1244 | for (idx, frame) in ((start + 1)..=end).enumerate() { |
| 1245 | if writer_failed.load(Ordering::Acquire) { |
| 1246 | break; |
| 1247 | } |
| 1248 | if control.is_some_and(ExportControl::is_cancelled) { |
| 1249 | cancelled = true; |
| 1250 | break; |
| 1251 | } |
| 1252 | prefetch.set_current_seq(idx); |
| 1253 | let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; |
| 1254 | if ahead_frame <= end { |
| 1004 | 1255 | prefetch.enqueue_frame( |
| 1005 | 1256 | comp, |
| 1006 | 1257 | opts.target, |
| 1007 | | k, |
| 1008 | | f as f64, |
| 1258 | idx + PREFETCH_LOOKAHEAD, |
| 1259 | ahead_frame as f64, |
| 1009 | 1260 | &engine.expr, |
| 1010 | 1261 | engine.use_proxy_clips, |
| 1011 | 1262 | ); |
| 1012 | 1263 | } |
| 1013 | | let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None; |
| 1014 | | for (idx, frame) in ((start + 1)..=end).enumerate() { |
| 1015 | | if writer_failed.load(Ordering::Acquire) { |
| 1264 | let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); |
| 1265 | let next_rb = match engine.begin_readback_rgba(&tex) { |
| 1266 | Ok(rb) => rb, |
| 1267 | Err(e) => { |
| 1268 | readback_err = Some(format!("GPU readback failed at frame {frame}: {e}")); |
| 1016 | 1269 | break; |
| 1017 | 1270 | } |
| 1271 | }; |
| 1272 | if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = |
| 1273 | pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms)) |
| 1274 | { |
| 1275 | let pixels = match prev_rb.finish(engine) { |
| 1276 | Ok(px) => px, |
| 1277 | Err(e) => { |
| 1278 | readback_err = |
| 1279 | Some(format!("GPU readback failed at frame {prev_frame}: {e}")); |
| 1280 | break; |
| 1281 | } |
| 1282 | }; |
| 1018 | 1283 | if control.is_some_and(ExportControl::is_cancelled) { |
| 1019 | 1284 | cancelled = true; |
| 1020 | 1285 | break; |
| 1021 | 1286 | } |
| 1022 | | prefetch.set_current_seq(idx); |
| 1023 | | let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; |
| 1024 | | if ahead_frame <= end { |
| 1025 | | prefetch.enqueue_frame( |
| 1026 | | comp, |
| 1027 | | opts.target, |
| 1028 | | idx + PREFETCH_LOOKAHEAD, |
| 1029 | | ahead_frame as f64, |
| 1030 | | &engine.expr, |
| 1031 | | engine.use_proxy_clips, |
| 1032 | | ); |
| 1287 | if tx.send((prev_frame, prev_size, pixels)).is_err() { |
| 1288 | break; |
| 1033 | 1289 | } |
| 1034 | | let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); |
| 1035 | | let next_rb = match engine.begin_readback_rgba(&tex) { |
| 1036 | | Ok(rb) => rb, |
| 1037 | | Err(e) => { |
| 1038 | | pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}")); |
| 1039 | | break; |
| 1040 | | } |
| 1041 | | }; |
| 1042 | | if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = |
| 1043 | | pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms)) |
| 1044 | | { |
| 1045 | | let pixels = match prev_rb.finish(engine) { |
| 1046 | | Ok(px) => px, |
| 1047 | | Err(e) => { |
| 1048 | | pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); |
| 1049 | | break; |
| 1050 | | } |
| 1051 | | }; |
| 1052 | | if control.is_some_and(ExportControl::is_cancelled) { |
| 1053 | | cancelled = true; |
| 1054 | | break; |
| 1055 | | } |
| 1056 | | if tx.send((prev_frame, prev_size, pixels)).is_err() { |
| 1057 | | break; |
| 1058 | | } |
| 1059 | | let prog = make_progress( |
| 1060 | | prev_frame, |
| 1061 | | prev_idx + 1, |
| 1062 | | total, |
| 1063 | | prev_ms, |
| 1064 | | opts.out_path.clone(), |
| 1065 | | node_name.clone(), |
| 1066 | | t0, |
| 1067 | | ); |
| 1068 | | if let Some(ctrl) = control { |
| 1069 | | ctrl.update_progress(&prog); |
| 1070 | | } |
| 1071 | | on_progress(prog); |
| 1290 | let prog = make_progress( |
| 1291 | prev_frame, |
| 1292 | prev_idx + 1, |
| 1293 | total, |
| 1294 | prev_ms, |
| 1295 | opts.out_path.clone(), |
| 1296 | node_name.clone(), |
| 1297 | t0, |
| 1298 | ); |
| 1299 | if let Some(ctrl) = control { |
| 1300 | ctrl.update_progress(&prog); |
| 1072 | 1301 | } |
| 1302 | on_progress(prog); |
| 1073 | 1303 | } |
| 1074 | | if pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) { |
| 1075 | | if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() { |
| 1076 | | match prev_rb.finish(engine) { |
| 1077 | | Ok(pixels) => { |
| 1078 | | if control.is_some_and(ExportControl::is_cancelled) { |
| 1079 | | cancelled = true; |
| 1080 | | } else if tx.send((prev_frame, prev_size, pixels)).is_ok() { |
| 1081 | | let prog = make_progress( |
| 1082 | | prev_frame, |
| 1083 | | prev_idx + 1, |
| 1084 | | total, |
| 1085 | | prev_ms, |
| 1086 | | opts.out_path.clone(), |
| 1087 | | node_name.clone(), |
| 1088 | | t0, |
| 1089 | | ); |
| 1090 | | if let Some(ctrl) = control { |
| 1091 | | ctrl.update_progress(&prog); |
| 1092 | | } |
| 1093 | | on_progress(prog); |
| 1304 | } |
| 1305 | if readback_err.is_none() && pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) { |
| 1306 | if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() { |
| 1307 | match prev_rb.finish(engine) { |
| 1308 | Ok(pixels) => { |
| 1309 | if control.is_some_and(ExportControl::is_cancelled) { |
| 1310 | cancelled = true; |
| 1311 | } else if tx.send((prev_frame, prev_size, pixels)).is_ok() { |
| 1312 | let prog = make_progress( |
| 1313 | prev_frame, |
| 1314 | prev_idx + 1, |
| 1315 | total, |
| 1316 | prev_ms, |
| 1317 | opts.out_path.clone(), |
| 1318 | node_name.clone(), |
| 1319 | t0, |
| 1320 | ); |
| 1321 | if let Some(ctrl) = control { |
| 1322 | ctrl.update_progress(&prog); |
| 1094 | 1323 | } |
| 1324 | on_progress(prog); |
| 1095 | 1325 | } |
| 1096 | | Err(e) => { |
| 1097 | | pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); |
| 1098 | | } |
| 1326 | } |
| 1327 | Err(e) => { |
| 1328 | readback_err = |
| 1329 | Some(format!("GPU readback failed at frame {prev_frame}: {e}")); |
| 1099 | 1330 | } |
| 1100 | 1331 | } |
| 1101 | 1332 | } |
| 1102 | | drop(prefetch); |
| 1103 | | } |
| 1104 | | } |
| 1105 | | drop(tx); |
| 1106 | | |
| 1107 | | if cancelled || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) { |
| 1108 | | // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately. |
| 1109 | | let _ = child.kill(); |
| 1110 | | } |
| 1111 | | let _ = writer_thread.join(); |
| 1112 | | if pipe_err.is_none() && !cancelled { |
| 1113 | | if let Ok(mut g) = writer_err.lock() { |
| 1114 | | pipe_err = g.take(); |
| 1115 | 1333 | } |
| 1334 | drop(prefetch); |
| 1116 | 1335 | } |
| 1117 | | if pipe_err.is_some() && !cancelled { |
| 1118 | | let _ = child.kill(); |
| 1119 | | } |
| 1120 | | let status = child |
| 1121 | | .wait() |
| 1122 | | .map_err(|e| format!("failed waiting on ffmpeg: {e}"))?; |
| 1123 | | let stderr_text = stderr_thread.join().unwrap_or_default(); |
| 1124 | | let stderr_trim = stderr_text.trim(); |
| 1336 | } |
| 1337 | drop(tx); |
| 1125 | 1338 | |
| 1126 | | if cancelled { |
| 1127 | | return Err("Cancelled".to_owned()); |
| 1128 | | } |
| 1129 | | if let Some(err) = pipe_err { |
| 1130 | | if !stderr_trim.is_empty() { |
| 1131 | | return Err(format!("{err} (ffmpeg: {stderr_trim})")); |
| 1132 | | } |
| 1133 | | return Err(err); |
| 1134 | | } |
| 1135 | | if !status.success() { |
| 1136 | | return Err(if stderr_trim.is_empty() { |
| 1137 | | format!("ffmpeg exited with {status}") |
| 1138 | | } else { |
| 1139 | | format!("ffmpeg exited with {status}: {stderr_trim}") |
| 1140 | | }); |
| 1339 | if cancelled || readback_err.is_some() || pipe_err.is_some() || writer_failed.load(Ordering::Acquire) { |
| 1340 | // Kill ffmpeg before joining writer_thread so a blocked pipe write unblocks immediately. |
| 1341 | let _ = child.kill(); |
| 1342 | } |
| 1343 | let _ = writer_thread.join(); |
| 1344 | if pipe_err.is_none() && !cancelled { |
| 1345 | if let Ok(mut g) = writer_err.lock() { |
| 1346 | pipe_err = g.take(); |
| 1141 | 1347 | } |
| 1348 | } |
| 1349 | if pipe_err.is_some() && !cancelled { |
| 1350 | let _ = child.kill(); |
| 1351 | } |
| 1352 | let status = child |
| 1353 | .wait() |
| 1354 | .map_err(|e| VideoExportError::EncoderFailed(format!("failed waiting on ffmpeg: {e}")))?; |
| 1355 | let stderr_text = stderr_thread.join().unwrap_or_default(); |
| 1356 | let stderr_trim = stderr_text.trim(); |
| 1357 | |
| 1358 | if cancelled { |
| 1359 | return Err(VideoExportError::Cancelled); |
| 1360 | } |
| 1361 | if let Some(err) = readback_err { |
| 1362 | return Err(VideoExportError::Fatal(err)); |
| 1363 | } |
| 1364 | if let Some(err) = pipe_err { |
| 1365 | return Err(VideoExportError::EncoderFailed(if !stderr_trim.is_empty() { |
| 1366 | format!("{err} (ffmpeg: {stderr_trim})") |
| 1367 | } else { |
| 1368 | err |
| 1369 | })); |
| 1370 | } |
| 1371 | if !status.success() { |
| 1372 | return Err(VideoExportError::EncoderFailed(if stderr_trim.is_empty() { |
| 1373 | format!("ffmpeg exited with {status}") |
| 1374 | } else { |
| 1375 | format!("ffmpeg exited with {status}: {stderr_trim}") |
| 1376 | })); |
| 1377 | } |
| 1142 | 1378 | |
| 1143 | | std::fs::rename(&tmp_path, &opts.out_path) |
| 1144 | | .map_err(|e| format!("failed to finalize '{}': {e}", opts.out_path.display()))?; |
| 1145 | | tmp_guard.disarm(); |
| 1146 | | |
| 1147 | | let file_bytes = std::fs::metadata(&opts.out_path) |
| 1148 | | .map(|m| m.len()) |
| 1149 | | .unwrap_or(0); |
| 1150 | | |
| 1151 | | Ok(VideoExportSummary { |
| 1152 | | out_path: opts.out_path.clone(), |
| 1153 | | frames_written: total, |
| 1154 | | width: out_width, |
| 1155 | | height: out_height, |
| 1156 | | has_audio, |
| 1157 | | total_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| 1158 | | file_bytes, |
| 1159 | | }) |
| 1160 | | })(); |
| 1161 | | |
| 1162 | | engine.hiq = prev_hiq; |
| 1163 | | engine.proxy_scale = prev_proxy; |
| 1164 | | res |
| 1379 | std::fs::rename(&tmp_path, &opts.out_path).map_err(|e| { |
| 1380 | VideoExportError::Fatal(format!("failed to finalize '{}': {e}", opts.out_path.display())) |
| 1381 | })?; |
| 1382 | tmp_guard.disarm(); |
| 1383 | |
| 1384 | let file_bytes = std::fs::metadata(&opts.out_path) |
| 1385 | .map(|m| m.len()) |
| 1386 | .unwrap_or(0); |
| 1387 | |
| 1388 | Ok(VideoExportSummary { |
| 1389 | out_path: opts.out_path.clone(), |
| 1390 | frames_written: total, |
| 1391 | width: out_width, |
| 1392 | height: out_height, |
| 1393 | has_audio, |
| 1394 | total_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| 1395 | file_bytes, |
| 1396 | }) |
| 1165 | 1397 | } |
| 1166 | 1398 | |
| 1167 | 1399 | #[cfg(test)] |
| ... | ... | @@ -1917,4 +2149,321 @@ mod tests { |
| 1917 | 2149 | |
| 1918 | 2150 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1919 | 2151 | } |
| 2152 | |
| 2153 | #[test] |
| 2154 | fn videotoolbox_probe_selection_and_fallback() { |
| 2155 | let sample_both = "\ |
| 2156 | Encoders: |
| 2157 | V..... = Video |
| 2158 | ------ |
| 2159 | V....D libx264 libx264 H.264 / AVC |
| 2160 | V....D h264_videotoolbox VideoToolbox H.264 Encoder (codec h264) |
| 2161 | VFS... prores_ks Apple ProRes (iCodec Pro) (codec prores) |
| 2162 | V....D prores_videotoolbox VideoToolbox ProRes Encoder (codec prores) |
| 2163 | A....D aac AAC (Advanced Audio Coding) |
| 2164 | "; |
| 2165 | let vt_both = parse_videotoolbox_encoders(sample_both); |
| 2166 | assert_eq!(vt_both, VideoToolboxSupport { h264: true, prores: true }); |
| 2167 | |
| 2168 | let sample_h264_only = " V....D h264_videotoolbox VideoToolbox H.264 Encoder\n"; |
| 2169 | assert_eq!( |
| 2170 | parse_videotoolbox_encoders(sample_h264_only), |
| 2171 | VideoToolboxSupport { h264: true, prores: false } |
| 2172 | ); |
| 2173 | assert_eq!( |
| 2174 | parse_videotoolbox_encoders(" V....D libx264 H.264\n"), |
| 2175 | VideoToolboxSupport::default() |
| 2176 | ); |
| 2177 | |
| 2178 | // Hardware selection when supported and allowed |
| 2179 | assert_eq!( |
| 2180 | select_video_encoder(VideoCodec::H264Share, vt_both, true), |
| 2181 | VideoEncoder::H264VideoToolbox |
| 2182 | ); |
| 2183 | assert_eq!( |
| 2184 | select_video_encoder(VideoCodec::ProRes422, vt_both, true), |
| 2185 | VideoEncoder::ProResVideoToolbox422 |
| 2186 | ); |
| 2187 | assert_eq!( |
| 2188 | select_video_encoder(VideoCodec::ProRes4444, vt_both, true), |
| 2189 | VideoEncoder::ProResVideoToolbox4444 |
| 2190 | ); |
| 2191 | |
| 2192 | // Fallback when VideoToolbox is unavailable or disabled after failure |
| 2193 | assert_eq!( |
| 2194 | select_video_encoder(VideoCodec::H264Share, vt_both, false), |
| 2195 | VideoEncoder::Libx264 |
| 2196 | ); |
| 2197 | assert_eq!( |
| 2198 | select_video_encoder(VideoCodec::ProRes422, vt_both, false), |
| 2199 | VideoEncoder::ProResKs422 |
| 2200 | ); |
| 2201 | assert_eq!( |
| 2202 | select_video_encoder(VideoCodec::ProRes4444, vt_both, false), |
| 2203 | VideoEncoder::ProResKs4444 |
| 2204 | ); |
| 2205 | assert_eq!( |
| 2206 | select_video_encoder(VideoCodec::H264Share, VideoToolboxSupport::default(), true), |
| 2207 | VideoEncoder::Libx264 |
| 2208 | ); |
| 2209 | |
| 2210 | assert_eq!(vt_quality_from_crf(0), 95); |
| 2211 | assert_eq!(vt_quality_from_crf(26), 52); |
| 2212 | assert_eq!(vt_quality_from_crf(51), 15); |
| 2213 | |
| 2214 | let mut args = Vec::new(); |
| 2215 | push_video_encoder_args(&mut args, VideoEncoder::H264VideoToolbox, 26, Some("scale=trunc(iw/2)*2:trunc(ih/2)*2")); |
| 2216 | assert!(args.windows(2).any(|w| w == ["-c:v", "h264_videotoolbox"])); |
| 2217 | assert!(args.windows(2).any(|w| w == ["-q:v", "52"])); |
| 2218 | assert!(args.windows(2).any(|w| w == ["-tag:v", "avc1"])); |
| 2219 | assert!(args.windows(2).any(|w| w == ["-pix_fmt", "yuv420p"])); |
| 2220 | |
| 2221 | args.clear(); |
| 2222 | push_video_encoder_args(&mut args, VideoEncoder::Libx264, 26, Some("scale=trunc(iw/2)*2:trunc(ih/2)*2")); |
| 2223 | assert!(args.windows(2).any(|w| w == ["-c:v", "libx264"])); |
| 2224 | assert!(args.windows(2).any(|w| w == ["-crf", "26"])); |
| 2225 | |
| 2226 | args.clear(); |
| 2227 | push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox422, 26, None); |
| 2228 | assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"])); |
| 2229 | assert!(args.windows(2).any(|w| w == ["-profile:v", "2"])); |
| 2230 | assert!(args.windows(2).any(|w| w == ["-pix_fmt", "p210le"])); |
| 2231 | |
| 2232 | args.clear(); |
| 2233 | push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox4444, 26, None); |
| 2234 | assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"])); |
| 2235 | assert!(args.windows(2).any(|w| w == ["-profile:v", "4"])); |
| 2236 | assert!(args.windows(2).any(|w| w == ["-pix_fmt", "ayuv64le"])); |
| 2237 | } |
| 2238 | |
| 2239 | #[test] |
| 2240 | fn fit_frame_rgba_zero_copy_fast_path_and_resize() { |
| 2241 | let pixels = vec![128u8; 8 * 4 * 4]; |
| 2242 | let orig_ptr = pixels.as_ptr(); |
| 2243 | let moved = fit_frame_rgba(pixels, [8, 4], [8, 4], 0).expect("matching size fast path"); |
| 2244 | assert_eq!(moved.as_ptr(), orig_ptr, "matching size must move Vec without copying"); |
| 2245 | |
| 2246 | let resized = fit_frame_rgba(moved, [8, 4], [4, 2], 1).expect("resize path"); |
| 2247 | assert_eq!(resized.len(), 4 * 2 * 4); |
| 2248 | |
| 2249 | let err = fit_frame_rgba(vec![0u8; 10], [8, 4], [8, 4], 2) |
| 2250 | .expect_err("mismatched RGBA byte length must fail"); |
| 2251 | assert!(err.contains("invalid RGBA buffer size")); |
| 2252 | } |
| 2253 | |
| 2254 | #[test] |
| 2255 | fn prores_4444_preserves_alpha_channel() { |
| 2256 | let tmp_dir = std::env::temp_dir().join(format!( |
| 2257 | "fission-prores4444-alpha-{}", |
| 2258 | std::process::id() |
| 2259 | )); |
| 2260 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 2261 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 2262 | |
| 2263 | let comp_src = r#"Composition { |
| 2264 | 	CurrentTime = 0, |
| 2265 | 	RenderRange = { 0, 1 }, |
| 2266 | 	GlobalRange = { 0, 1 }, |
| 2267 | 	Tools = ordered() { |
| 2268 | 		BG = Background { |
| 2269 | 			Inputs = { |
| 2270 | 				Width = Input { Value = 64, }, |
| 2271 | 				Height = Input { Value = 36, }, |
| 2272 | 				TopLeftRed = Input { Value = 0.8, }, |
| 2273 | 				TopLeftGreen = Input { Value = 0.4, }, |
| 2274 | 				TopLeftBlue = Input { Value = 0.2, }, |
| 2275 | 				TopLeftAlpha = Input { SourceOp = "BGAlpha", Source = "Value", }, |
| 2276 | 			}, |
| 2277 | 		}, |
| 2278 | 		BGAlpha = BezierSpline { |
| 2279 | 			KeyFrames = { |
| 2280 | 				[0] = { 0.25, Flags = { Linear = true } }, |
| 2281 | 				[1] = { 0.75, Flags = { Linear = true } }, |
| 2282 | 			}, |
| 2283 | 		}, |
| 2284 | 	}, |
| 2285 | 	Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, |
| 2286 | }"#; |
| 2287 | let comp = Comp::from_fusion_str(comp_src).expect("parse alpha ProRes comp"); |
| 2288 | let target = comp.find_node("BG").expect("find BG"); |
| 2289 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 2290 | |
| 2291 | let out_mov = tmp_dir.join("alpha_4444.mov"); |
| 2292 | let summary = export_node_video_ffmpeg( |
| 2293 | &mut engine, |
| 2294 | &comp, |
| 2295 | &VideoExportOptions { |
| 2296 | target, |
| 2297 | out_path: out_mov.clone(), |
| 2298 | range: [0, 1], |
| 2299 | codec: VideoCodec::ProRes4444, |
| 2300 | crf: 26, |
| 2301 | max_height: None, |
| 2302 | include_audio: false, |
| 2303 | hiq: true, |
| 2304 | proxy_scale: 1, |
| 2305 | }, |
| 2306 | |_| {}, |
| 2307 | ) |
| 2308 | .expect("export ProRes 4444"); |
| 2309 | assert_eq!(summary.frames_written, 2); |
| 2310 | assert_eq!(summary.width, 64); |
| 2311 | assert_eq!(summary.height, 36); |
| 2312 | |
| 2313 | let probe = Command::new("ffprobe") |
| 2314 | .args([ |
| 2315 | "-v", |
| 2316 | "error", |
| 2317 | "-show_entries", |
| 2318 | "stream=codec_name,profile,pix_fmt", |
| 2319 | "-of", |
| 2320 | "csv=p=0", |
| 2321 | ]) |
| 2322 | .arg(&out_mov) |
| 2323 | .output() |
| 2324 | .expect("run ffprobe"); |
| 2325 | assert!(probe.status.success()); |
| 2326 | let probe_out = String::from_utf8_lossy(&probe.stdout); |
| 2327 | assert!( |
| 2328 | probe_out.contains("prores") && probe_out.contains("4444") && probe_out.contains("yuva"), |
| 2329 | "expected ProRes 4444 with alpha pixel format, got: {probe_out}" |
| 2330 | ); |
| 2331 | |
| 2332 | let dec = Command::new("ffmpeg") |
| 2333 | .args(["-v", "error", "-i"]) |
| 2334 | .arg(&out_mov) |
| 2335 | .args(["-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1"]) |
| 2336 | .output() |
| 2337 | .expect("decode ProRes 4444 to rgba"); |
| 2338 | assert!(dec.status.success()); |
| 2339 | let frame_bytes = 64 * 36 * 4; |
| 2340 | assert_eq!(dec.stdout.len(), frame_bytes * 2); |
| 2341 | |
| 2342 | let a0 = dec.stdout[3]; |
| 2343 | let a1 = dec.stdout[frame_bytes + 3]; |
| 2344 | assert!( |
| 2345 | (i32::from(a0) - 64).abs() <= 2, |
| 2346 | "frame 0 alpha should be ~64 (0.25), got {a0}" |
| 2347 | ); |
| 2348 | assert!( |
| 2349 | (i32::from(a1) - 191).abs() <= 2, |
| 2350 | "frame 1 alpha should be ~191 (0.75), got {a1}" |
| 2351 | ); |
| 2352 | |
| 2353 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 2354 | } |
| 2355 | |
| 2356 | #[test] |
| 2357 | fn prores_422_and_software_fallback_encoders_produce_valid_streams() { |
| 2358 | let tmp_dir = std::env::temp_dir().join(format!( |
| 2359 | "fission-prores422-fallback-{}", |
| 2360 | std::process::id() |
| 2361 | )); |
| 2362 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 2363 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 2364 | |
| 2365 | let comp_src = r#"Composition { |
| 2366 | 	CurrentTime = 0, |
| 2367 | 	RenderRange = { 0, 2 }, |
| 2368 | 	GlobalRange = { 0, 2 }, |
| 2369 | 	Tools = ordered() { |
| 2370 | 		BG = Background { |
| 2371 | 			Inputs = { |
| 2372 | 				Width = Input { Value = 64, }, |
| 2373 | 				Height = Input { Value = 36, }, |
| 2374 | 				TopLeftRed = Input { Value = 0.2, }, |
| 2375 | 				TopLeftGreen = Input { Value = 0.7, }, |
| 2376 | 				TopLeftBlue = Input { Value = 0.3, }, |
| 2377 | 				TopLeftAlpha = Input { Value = 1.0, }, |
| 2378 | 			}, |
| 2379 | 		}, |
| 2380 | 	}, |
| 2381 | 	Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, |
| 2382 | }"#; |
| 2383 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); |
| 2384 | let target = comp.find_node("BG").expect("find BG"); |
| 2385 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 2386 | |
| 2387 | let prores422_mov = tmp_dir.join("prores422.mov"); |
| 2388 | let summary_422 = export_node_video_ffmpeg( |
| 2389 | &mut engine, |
| 2390 | &comp, |
| 2391 | &VideoExportOptions { |
| 2392 | target, |
| 2393 | out_path: prores422_mov.clone(), |
| 2394 | range: [0, 2], |
| 2395 | codec: VideoCodec::ProRes422, |
| 2396 | crf: 26, |
| 2397 | max_height: None, |
| 2398 | include_audio: false, |
| 2399 | hiq: true, |
| 2400 | proxy_scale: 1, |
| 2401 | }, |
| 2402 | |_| {}, |
| 2403 | ) |
| 2404 | .expect("export ProRes 422"); |
| 2405 | assert_eq!(summary_422.frames_written, 3); |
| 2406 | |
| 2407 | let probe_422 = Command::new("ffprobe") |
| 2408 | .args(["-v", "error", "-count_frames", "-show_entries", "stream=codec_name,profile,nb_read_frames", "-of", "csv=p=0"]) |
| 2409 | .arg(&prores422_mov) |
| 2410 | .output() |
| 2411 | .expect("ffprobe prores 422"); |
| 2412 | assert!(probe_422.status.success()); |
| 2413 | let out_422 = String::from_utf8_lossy(&probe_422.stdout); |
| 2414 | assert!( |
| 2415 | out_422.contains("prores") && out_422.contains("Standard") && out_422.contains(",3"), |
| 2416 | "expected ProRes 422 Standard with 3 frames, got: {out_422}" |
| 2417 | ); |
| 2418 | |
| 2419 | // Directly verify software fallback encoders (Libx264 and ProResKs422) |
| 2420 | let sw_mp4 = tmp_dir.join("sw_libx264.mp4"); |
| 2421 | let mut noop = |_| {}; |
| 2422 | let sw_summary = export_node_video_ffmpeg_with_encoder( |
| 2423 | &mut engine, |
| 2424 | &comp, |
| 2425 | &VideoExportOptions { |
| 2426 | target, |
| 2427 | out_path: sw_mp4.clone(), |
| 2428 | range: [0, 2], |
| 2429 | codec: VideoCodec::H264Share, |
| 2430 | crf: 26, |
| 2431 | max_height: None, |
| 2432 | include_audio: false, |
| 2433 | hiq: true, |
| 2434 | proxy_scale: 1, |
| 2435 | }, |
| 2436 | None, |
| 2437 | &mut noop, |
| 2438 | VideoEncoder::Libx264, |
| 2439 | ) |
| 2440 | .expect("software libx264 fallback export"); |
| 2441 | assert_eq!(sw_summary.frames_written, 3); |
| 2442 | assert!(sw_mp4.exists()); |
| 2443 | |
| 2444 | let sw_mov = tmp_dir.join("sw_prores_ks.mov"); |
| 2445 | let sw_prores = export_node_video_ffmpeg_with_encoder( |
| 2446 | &mut engine, |
| 2447 | &comp, |
| 2448 | &VideoExportOptions { |
| 2449 | target, |
| 2450 | out_path: sw_mov.clone(), |
| 2451 | range: [0, 2], |
| 2452 | codec: VideoCodec::ProRes422, |
| 2453 | crf: 26, |
| 2454 | max_height: None, |
| 2455 | include_audio: false, |
| 2456 | hiq: true, |
| 2457 | proxy_scale: 1, |
| 2458 | }, |
| 2459 | None, |
| 2460 | &mut noop, |
| 2461 | VideoEncoder::ProResKs422, |
| 2462 | ) |
| 2463 | .expect("software prores_ks fallback export"); |
| 2464 | assert_eq!(sw_prores.frames_written, 3); |
| 2465 | assert!(sw_mov.exists()); |
| 2466 | |
| 2467 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 2468 | } |
| 1920 | 2469 | } |