1//! Saver-driven pipelined PNG / OpenEXR sequence export and ffmpeg video export for `Engine`.
2//!
3//! Evaluates frames on the GPU while encoding lossless RGBA8 PNG or linear HDR OpenEXR files
4//! concurrently across a bounded background worker pool, or piping raw RGBA8 frames into `ffmpeg`.
5
6mod exr;
7mod png;
8#[cfg(test)]
9mod tests;
10mod video;
11
12pub use exr::{
13 ExrCompression, ExrDepth, export_node_exr_sequence_with_progress, export_node_frame_exr,
14 export_saver_exr_sequence, export_saver_exr_sequence_with_progress, write_exr_rgba_with_aux,
15};
16pub use png::{
17 encode_png_rgba8_into, export_node_frame_png, export_node_png_sequence_with_progress,
18 export_saver_png_sequence, export_saver_png_sequence_with_progress, write_png_fast_buffered,
19};
20pub use video::{export_node_video_ffmpeg, export_node_video_ffmpeg_with_progress};
21
22use crate::cache::EvalStats;
23use crate::eval::Engine;
24use model::{Comp, NodeId, SaverSpec};
25use std::path::{Path, PathBuf};
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::sync::{Arc, Mutex};
28use std::time::Instant;
29
30#[derive(Clone, Debug)]
31pub struct ExportOptions {
32 /// Optional explicit Saver node name. If `None`, selects the first non-bypassed Saver
33 /// with a configured filename (or falls back to the first Saver).
34 pub saver_name: Option<String>,
35 /// Optional output directory override (keeps each frame's filename from `SaverSpec::frame_path`).
36 pub out_dir_override: Option<PathBuf>,
37 /// Optional inclusive frame range override `[start, end]`. Defaults to `saver.range` (`comp.render_range`).
38 pub range_override: Option<[i64; 2]>,
39 /// Render quality mode (`true` = HiQ project depth, `false` = Fast).
40 pub hiq: bool,
41 /// Proxy downscale factor (`1` = full resolution).
42 pub proxy_scale: u32,
43 /// Number of background PNG encoder threads (`0` = automatic 2..=24, bounded by frame count).
44 pub png_workers: usize,
45}
46
47impl Default for ExportOptions {
48 fn default() -> Self {
49 Self {
50 saver_name: None,
51 out_dir_override: None,
52 range_override: None,
53 hiq: true,
54 proxy_scale: 1,
55 png_workers: 0,
56 }
57 }
58}
59
60#[derive(Clone, Debug, Default)]
61pub struct ExportProgress {
62 pub frame: i64,
63 pub index: usize,
64 pub total: usize,
65 pub eval_ms: f64,
66 pub cached_vram_mb: f64,
67 pub unsupported_nodes: Vec<String>,
68 pub out_path: PathBuf,
69 pub saver_name: String,
70 pub current_frame: u32,
71 pub total_frames: u32,
72 pub completed_frames: u32,
73 pub elapsed_secs: f32,
74 pub label: String,
75}
76
77/// Cooperative cancellation token and shared progress state for background exports.
78#[derive(Clone, Debug)]
79pub struct ExportControl {
80 pub cancel: Arc<AtomicBool>,
81 pub progress: Arc<Mutex<ExportProgress>>,
82}
83
84impl Default for ExportControl {
85 fn default() -> Self {
86 Self::new()
87 }
88}
89
90impl ExportControl {
91 pub fn new() -> Self {
92 Self {
93 cancel: Arc::new(AtomicBool::new(false)),
94 progress: Arc::new(Mutex::new(ExportProgress::default())),
95 }
96 }
97
98 pub fn with_cancel(cancel: Arc<AtomicBool>) -> Self {
99 Self {
100 cancel,
101 progress: Arc::new(Mutex::new(ExportProgress::default())),
102 }
103 }
104
105 pub fn cancel(&self) {
106 self.cancel.store(true, Ordering::Release);
107 }
108
109 pub fn is_cancelled(&self) -> bool {
110 self.cancel.load(Ordering::Acquire)
111 }
112
113 pub fn update_progress(&self, progress: &ExportProgress) {
114 if let Ok(mut guard) = self.progress.lock() {
115 *guard = progress.clone();
116 }
117 }
118
119 pub fn snapshot_progress(&self) -> ExportProgress {
120 self.progress
121 .lock()
122 .map(|guard| guard.clone())
123 .unwrap_or_default()
124 }
125}
126
127fn make_progress(
128 frame: i64,
129 index: usize,
130 total: usize,
131 stats: EvalStats,
132 out_path: PathBuf,
133 label: String,
134 started_at: Instant,
135) -> ExportProgress {
136 ExportProgress {
137 frame,
138 index,
139 total,
140 eval_ms: stats.eval_ms,
141 cached_vram_mb: stats.cached_vram_mb,
142 unsupported_nodes: stats.unsupported_nodes,
143 out_path,
144 saver_name: label.clone(),
145 current_frame: frame.max(0) as u32,
146 total_frames: total as u32,
147 completed_frames: (index + 1) as u32,
148 elapsed_secs: started_at.elapsed().as_secs_f32(),
149 label,
150 }
151}
152
153#[derive(Clone, Debug)]
154pub struct ExportSummary {
155 pub saver_name: String,
156 pub frames_written: usize,
157 pub total_ms: f64,
158 pub first_path: Option<PathBuf>,
159 pub last_path: Option<PathBuf>,
160}
161
162/// Selects the target `SaverSpec` from `comp` according to `saver_name`.
163pub fn select_saver(comp: &Comp, saver_name: Option<&str>) -> Result<SaverSpec, String> {
164 let savers = comp.savers();
165 if savers.is_empty() {
166 return Err(format!("comp '{}' has no Saver nodes", comp.name));
167 }
168 if let Some(name) = saver_name {
169 return savers
170 .into_iter()
171 .find(|s| s.name == name)
172 .ok_or_else(|| format!("comp '{}' has no Saver named '{name}'", comp.name));
173 }
174 // Prefer first non-bypassed Saver with an upstream connection and non-empty filename
175 if let Some(s) = savers.iter().find(|s| {
176 !comp.node(s.node_id).bypassed && s.upstream.is_some() && !s.filename.is_empty()
177 }) {
178 return Ok(s.clone());
179 }
180 if let Some(s) = savers.iter().find(|s| !comp.node(s.node_id).bypassed) {
181 return Ok(s.clone());
182 }
183 Ok(savers[0].clone())
184}
185
186pub(super) fn resolve_output_path_with_ext(
187 saver: &SaverSpec,
188 frame: i64,
189 out_dir_override: Option<&Path>,
190 default_ext: &str,
191) -> Result<PathBuf, String> {
192 if saver.filename.is_empty() {
193 let dir = out_dir_override.ok_or_else(|| {
194 format!(
195 "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)",
196 saver.name
197 )
198 })?;
199 return Ok(dir.join(format!("{frame:04}.{default_ext}")));
200 }
201 let frame_path = saver.frame_path(frame);
202 if let Some(dir) = out_dir_override {
203 let fname = frame_path
204 .file_name()
205 .map(PathBuf::from)
206 .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.{default_ext}")));
207 Ok(dir.join(fname))
208 } else {
209 Ok(frame_path)
210 }
211}
212
213pub(super) fn ensure_parent_dir(
214 path: &Path,
215 last_parent: &mut Option<PathBuf>,
216) -> Result<(), String> {
217 if let Some(parent) = path.parent()
218 && !parent.as_os_str().is_empty()
219 && last_parent.as_deref() != Some(parent)
220 {
221 std::fs::create_dir_all(parent)
222 .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
223 *last_parent = Some(parent.to_path_buf());
224 }
225 Ok(())
226}
227
228fn saver_targets_exr(comp: &Comp, saver: &SaverSpec, out_dir_override: Option<&Path>) -> bool {
229 let node = comp.node(saver.node_id);
230 if let Some(fmt) = node
231 .static_str("OutputFormat")
232 .map(str::trim)
233 .filter(|s| !s.is_empty())
234 {
235 return fmt.eq_ignore_ascii_case("OpenEXRFormat");
236 }
237 if let Some(fmt) = node
238 .raw
239 .get_table("Inputs")
240 .and_then(|i| i.get_table("Clip"))
241 .and_then(|c| c.get_table("Value"))
242 .and_then(|v| v.get_str("FormatID"))
243 .map(str::trim)
244 .filter(|s| !s.is_empty())
245 {
246 return fmt.eq_ignore_ascii_case("OpenEXRFormat");
247 }
248 resolve_output_path_with_ext(saver, saver.range[0], out_dir_override, "png").is_ok_and(|p| {
249 p.extension()
250 .and_then(|e| e.to_str())
251 .is_some_and(|e| e.eq_ignore_ascii_case("exr"))
252 })
253}
254
255/// Renders and writes an image sequence driven by a Fusion `Saver` node, dispatching
256/// automatically to linear HDR OpenEXR (`OpenEXRFormat` / `.exr`) or lossless PNG.
257pub fn export_saver_sequence(
258 engine: &mut Engine,
259 comp: &Comp,
260 opts: &ExportOptions,
261 on_progress: impl FnMut(&ExportProgress),
262) -> Result<ExportSummary, String> {
263 export_saver_sequence_with_progress(engine, comp, opts, None, on_progress)
264}
265
266/// Renders and writes an image sequence driven by a Fusion `Saver` node with cooperative
267/// cancellation and live progress reporting, dispatching automatically to linear HDR OpenEXR
268/// (`OpenEXRFormat` / `.exr`) or lossless PNG.
269pub fn export_saver_sequence_with_progress(
270 engine: &mut Engine,
271 comp: &Comp,
272 opts: &ExportOptions,
273 control: Option<&ExportControl>,
274 on_progress: impl FnMut(&ExportProgress),
275) -> Result<ExportSummary, String> {
276 if control.is_some_and(ExportControl::is_cancelled) {
277 return Err("Cancelled".to_owned());
278 }
279 let saver = select_saver(comp, opts.saver_name.as_deref())?;
280 if saver_targets_exr(comp, &saver, opts.out_dir_override.as_deref()) {
281 exr::export_saver_exr_sequence_with_progress(engine, comp, opts, control, on_progress)
282 } else {
283 png::export_saver_png_only_sequence_with_progress(engine, comp, opts, control, on_progress)
284 }
285}
286
287/// Output video codec profile for direct viewer / node ffmpeg export.
288#[derive(Clone, Copy, Debug, PartialEq, Eq)]
289pub enum VideoCodec {
290 /// H.264 (`h264_videotoolbox` on macOS when available, `libx264` fallback, `yuv420p`, `-movflags +faststart`) for compact shareable MP4 snippets.
291 H264Share,
292 /// Apple ProRes 422 (`prores_videotoolbox` on macOS when available, `prores_ks` fallback, `-profile:v 2`).
293 ProRes422,
294 /// Apple ProRes 4444 with alpha (`prores_videotoolbox` on macOS when available, `prores_ks` fallback, `-profile:v 4`).
295 ProRes4444,
296}
297
298#[derive(Clone, Debug)]
299pub struct VideoExportOptions {
300 pub target: NodeId,
301 pub out_path: PathBuf,
302 pub range: [i64; 2],
303 pub codec: VideoCodec,
304 pub crf: u8,
305 pub max_height: Option<u32>,
306 pub include_audio: bool,
307 pub hiq: bool,
308 pub proxy_scale: u32,
309}
310
311impl Default for VideoExportOptions {
312 fn default() -> Self {
313 Self {
314 target: NodeId(0),
315 out_path: PathBuf::new(),
316 range: [0, 0],
317 codec: VideoCodec::H264Share,
318 crf: 26,
319 max_height: None,
320 include_audio: true,
321 hiq: true,
322 proxy_scale: 1,
323 }
324 }
325}
326
327#[derive(Clone, Debug)]
328pub struct VideoExportSummary {
329 pub out_path: PathBuf,
330 pub frames_written: usize,
331 pub width: u32,
332 pub height: u32,
333 pub has_audio: bool,
334 pub total_ms: f64,
335 pub file_bytes: u64,
336}