From 0e0496e04ce4737c013b1a715b37cfe35c4aca31 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 22:44:04 -0800 Subject: [PATCH] feat(engine): add linear HDR OpenEXR (f16/f32 + Z/Normal) Saver export and float readback --- crates/engine/src/bin/render_check.rs | 182 ++++++- crates/engine/src/eval/dispatch.rs | 295 ++++++++-- crates/engine/src/export.rs | 113 +++- crates/engine/src/export/exr.rs | 742 ++++++++++++++++++++++++++ crates/engine/src/export/png.rs | 56 +- crates/engine/src/export/tests.rs | 506 ++++++++++++++++++ 6 files changed, 1802 insertions(+), 92 deletions(-) create mode 100644 crates/engine/src/export/exr.rs diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index 562529ef4d712f1b85cb98b762c585d2acace020..53b1d596b94179b52270ad371a6eb23a6d1e9540 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -1,12 +1,13 @@ //! Headless verification, parity+perf suite runner, and batch PNG sequence renderer for `engine`. use engine::export::{ - VideoCodec, VideoExportOptions, export_node_png_sequence_with_progress, - export_node_video_ffmpeg, write_png_fast_buffered, + ExrCompression, ExrDepth, VideoCodec, VideoExportOptions, export_node_exr_sequence_with_progress, + export_node_frame_exr, export_node_png_sequence_with_progress, export_node_video_ffmpeg, + write_png_fast_buffered, }; use engine::media::default_media_cache_budget_mb; use engine::{CacheMode, Engine, ExportOptions, export_saver_png_sequence}; -use model::Comp; +use model::{Comp, NodeId, SaverSpec}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Instant; @@ -349,6 +350,128 @@ fn run_video_export( Ok(()) } +fn run_exr_export( + comp_path: &Path, + out_path: PathBuf, + node_name: Option<&str>, + range_str: Option<&str>, + depth: ExrDepth, + proxy_scale: u32, + hiq: bool, +) -> Result<(), Box> { + let comp = Comp::from_fusion_file(comp_path)?; + let target = match node_name { + Some(n) => comp.find_node(n).ok_or_else(|| format!("no such node {n}"))?, + None => comp.default_output_node().ok_or("comp has no nodes")?, + }; + let is_exr_file = out_path + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("exr")); + + let mut engine = Engine::new_headless()?; + engine.set_media_budget_mb(default_media_cache_budget_mb()); + engine.proxy_scale = proxy_scale; + engine.hiq = hiq; + + let parsed_range: Option<([i64; 2], bool)> = match range_str { + Some(r) if !r.is_empty() => { + if let Some((a, b)) = r.split_once("..") { + Some(([a.parse::()?, b.parse::()?], false)) + } else { + let single = r.parse::()?; + Some(([single, single], true)) + } + } + _ => None, + }; + + let t_start = Instant::now(); + let depth_label = match depth { + ExrDepth::Float16 => "f16", + ExrDepth::Float32 => "f32", + }; + + if is_exr_file && parsed_range.is_none_or(|(_, single)| single) { + let frame = parsed_range.map_or(comp.current_time, |(r, _)| r[0] as f64); + let saved = export_node_frame_exr( + &mut engine, + &comp, + target, + frame, + &out_path, + depth, + ExrCompression::Zip16, + ) + .map_err(|e| format!("EXR export failed: {e}"))?; + eprintln!( + "Exported EXR ({depth_label}) frame {frame} in {:.2}s -> {}", + t_start.elapsed().as_secs_f64(), + saved.display() + ); + return Ok(()); + } + + let range = parsed_range.map_or(comp.render_range, |(r, _)| r); + let label = comp.node(target).name.clone(); + let template_saver = is_exr_file.then(|| SaverSpec { + node_id: NodeId(0), + name: label.clone(), + upstream: None, + filename: out_path.to_string_lossy().into_owned(), + range, + sequence_start: None, + }); + let summary = export_node_exr_sequence_with_progress( + &mut engine, + &comp, + target, + range, + |frame| { + if let Some(s) = &template_saver { + Ok(s.frame_path(frame)) + } else { + Ok(out_path.join(format!("{frame:04}.exr"))) + } + }, + label, + hiq, + proxy_scale, + 0, + depth, + ExrCompression::Zip16, + None, + |p| { + if p.index == 0 || (p.index + 1) % 10 == 0 || p.index + 1 == p.total { + let elapsed = t_start.elapsed().as_secs_f64().max(1e-6); + let fps = (p.index + 1) as f64 / elapsed; + eprintln!( + " [{:>4}/{}] {} f{:04} | eval={:.1}ms | avg={fps:.1} fps -> {}", + p.index + 1, + p.total, + p.saver_name, + p.frame, + p.eval_ms, + p.out_path.display() + ); + } + }, + ) + .map_err(|e| format!("EXR sequence export failed: {e}"))?; + let secs = (summary.total_ms / 1000.0).max(1e-6); + eprintln!( + "Exported {} EXR ({depth_label}) frames via {} in {:.2}s ({:.1} fps)", + summary.frames_written, + summary.saver_name, + secs, + summary.frames_written as f64 / secs + ); + if let (Some(first), Some(last)) = (summary.first_path, summary.last_path) { + eprintln!(" range: {} .. {}", first.display(), last.display()); + } + Ok(()) +} + fn main() -> Result<(), Box> { let args: Vec = std::env::args().collect(); if args.len() >= 3 && args[1] == "--suite" { @@ -357,12 +480,63 @@ fn main() -> Result<(), Box> { } if args.len() < 3 { eprintln!( - "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast] [--bench] [--profile]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --export [--saver ] [--range ..] [--out-dir ] [--proxy <1|2|4>] [--fast]\n render-check --export-mp4 [--node ] [--range ..] [--crf ] [--max-height ] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --export-prores [--prores-4444] [--node ] [--range ..] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --roundtrip \n render-check --suite [--fast]" + "usage:\n render-check [--out ] [--ref ] [--node ] [--proxy <1|2|4>] [--fast] [--bench] [--profile]\n render-check --render .. --out-dir [--node ] [--proxy <1|2|4>]\n render-check --export [--saver ] [--range ..] [--out-dir ] [--proxy <1|2|4>] [--fast]\n render-check --export-exr [--exr-f32] [--node ] [--range ..] [--proxy <1|2|4>] [--fast]\n render-check --export-mp4 [--node ] [--range ..] [--crf ] [--max-height ] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --export-prores [--prores-4444] [--node ] [--range ..] [--no-audio] [--proxy <1|2|4>] [--fast]\n render-check --roundtrip \n render-check --suite [--fast]" ); std::process::exit(2); } let comp_path = PathBuf::from(&args[1]); + if args[2..].iter().any(|a| a == "--export-exr") { + let mut out_path: Option = None; + let mut depth = ExrDepth::Float16; + let mut node_name: Option = None; + let mut range_str: Option = None; + let mut proxy_scale = 1u32; + let mut hiq = true; + let mut i = 2; + while i < args.len() { + match args[i].as_str() { + "--export-exr" if i + 1 < args.len() => { + out_path = Some(PathBuf::from(&args[i + 1])); + i += 2; + } + "--exr-f32" => { + depth = ExrDepth::Float32; + i += 1; + } + "--node" if i + 1 < args.len() => { + node_name = Some(args[i + 1].clone()); + i += 2; + } + "--range" if i + 1 < args.len() => { + range_str = Some(args[i + 1].clone()); + i += 2; + } + "--proxy" if i + 1 < args.len() => { + proxy_scale = args[i + 1].parse().unwrap_or(1).max(1); + i += 2; + } + "--fast" => { + hiq = false; + i += 1; + } + other => { + eprintln!("unexpected argument '{other}'"); + std::process::exit(2); + } + } + } + let out_path = out_path.ok_or("--export-exr requires an output path or directory")?; + return run_exr_export( + &comp_path, + out_path, + node_name.as_deref(), + range_str.as_deref(), + depth, + proxy_scale, + hiq, + ); + } if args[2..].iter().any(|a| a == "--export-mp4" || a == "--export-prores") { let mut out_path: Option = None; let mut codec = VideoCodec::H264Share; diff --git a/crates/engine/src/eval/dispatch.rs b/crates/engine/src/eval/dispatch.rs index 0658242405cbf07683bf76499fcb126c8493bae7..05e72851092189c122f1e5e95b1427ab0a9cd818 100644 --- a/crates/engine/src/eval/dispatch.rs +++ b/crates/engine/src/eval/dispatch.rs @@ -9,7 +9,7 @@ use web_time::Instant; use bytemuck::{Pod, Zeroable}; use model::BitDepth; -use crate::cache::{CachedTexture, EvalStats}; +use crate::cache::{AuxChannelTex, CachedTexture, EvalStats}; use super::registry::{ShaderOp, ShaderRegistry}; use super::{DisplaySettings, Engine}; @@ -40,8 +40,6 @@ pub struct PendingReadback { #[cfg(not(target_arch = "wasm32"))] rx: std::sync::mpsc::Receiver>, #[cfg(not(target_arch = "wasm32"))] - width: u32, - #[cfg(not(target_arch = "wasm32"))] height: u32, #[cfg(not(target_arch = "wasm32"))] unpadded_bpr: u32, @@ -83,9 +81,8 @@ impl PendingReadback { map_res?; let slice = self.buf.slice(..self.required_bytes); let data = slice.get_mapped_range()?; - let total_bytes = (self.width as usize) + let total_bytes = (self.unpadded_bpr as usize) .checked_mul(self.height as usize) - .and_then(|n| n.checked_mul(4)) .ok_or("readback buffer size overflow")?; dst.clear(); dst.reserve(total_bytes); @@ -311,6 +308,76 @@ impl Engine { } } + #[cfg(not(target_arch = "wasm32"))] + fn encode_and_submit_readback( + &self, + mut enc: wgpu::CommandEncoder, + texture: &wgpu::Texture, + size: [u32; 2], + bpp: u32, + ) -> Result> { + let [w, h] = size; + let unpadded_bpr = w.checked_mul(bpp).ok_or("readback row size overflow")?; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr + .div_ceil(align) + .checked_mul(align) + .ok_or("readback padded row size overflow")?; + let required_bytes = u64::from(padded_bpr) + .checked_mul(u64::from(h)) + .ok_or("readback buffer size overflow")?; + let buf = self + .pipelines + .borrow_mut() + .readback_pool + .acquire_buffer(&self.device, required_bytes); + + enc.copy_texture_to_buffer( + texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_bpr), + rows_per_image: Some(h), + }, + }, + wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + ); + let submission_index = self.queue.submit(Some(enc.finish())); + self.reset_uniform_cursors(); + + let slice = buf.slice(..required_bytes); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |res| { + let _ = tx.send(res); + }); + Ok(PendingReadback { + buf, + submission_index, + rx, + height: h, + unpadded_bpr, + padded_bpr, + required_bytes, + }) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn begin_readback_raw( + &self, + texture: &wgpu::Texture, + size: [u32; 2], + bpp: u32, + ) -> Result> { + let enc = self.device.create_command_encoder(&Default::default()); + self.encode_and_submit_readback(enc, texture, size, bpp) + } + /// Starts an asynchronous GPU-to-CPU RGBA8 readback by encoding any Float16/Float32 -> /// `Rgba8Unorm` conversion plus `copy_texture_to_buffer` into a pooled staging buffer, /// submitting to the queue, and starting `map_async` without polling. @@ -333,18 +400,6 @@ impl Engine { None }; let src_tex = converted.as_ref().unwrap_or(tex); - let [w, h] = src_tex.size; - let bpp = 4u32; - let unpadded_bpr = w * bpp; - let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; - let padded_bpr = unpadded_bpr.div_ceil(align) * align; - let required_bytes = u64::from(padded_bpr) * u64::from(h); - let buf = self - .pipelines - .borrow_mut() - .readback_pool - .acquire_buffer(&self.device, required_bytes); - let mut enc = self.device.create_command_encoder(&Default::default()); if let Some(conv) = converted.as_ref() { let mut params = UniformParams::default(); @@ -360,36 +415,7 @@ impl Engine { ¶ms, ); } - enc.copy_texture_to_buffer( - src_tex.texture.as_image_copy(), - wgpu::TexelCopyBufferInfo { - buffer: &buf, - layout: wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(padded_bpr), - rows_per_image: Some(h), - }, - }, - wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - ); - let submission_index = self.queue.submit(Some(enc.finish())); - self.reset_uniform_cursors(); - - let slice = buf.slice(..required_bytes); - let (tx, rx) = std::sync::mpsc::channel(); - slice.map_async(wgpu::MapMode::Read, move |res| { - let _ = tx.send(res); - }); - Ok(PendingReadback { - buf, - submission_index, - rx, - width: w, - height: h, - unpadded_bpr, - padded_bpr, - required_bytes, - }) + self.encode_and_submit_readback(enc, &src_tex.texture, src_tex.size, 4) } } @@ -400,6 +426,181 @@ impl Engine { self.begin_readback_rgba(tex)?.finish(self) } + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn rgba_f32_bpp(format: wgpu::TextureFormat) -> Result> { + match format { + wgpu::TextureFormat::Rgba32Float => Ok(16), + wgpu::TextureFormat::Rgba16Float => Ok(8), + wgpu::TextureFormat::Rgba8Unorm => Ok(4), + other => Err(format!("unsupported texture format for linear f32 readback: {other:?}").into()), + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn decode_rgba_bytes_into_f32( + format: wgpu::TextureFormat, + size: [u32; 2], + raw: &[u8], + out: &mut Vec, + ) -> Result<(), Box> { + let px_count = (size[0] as usize) + .checked_mul(size[1] as usize) + .ok_or("readback pixel count overflow")?; + let float_count = px_count + .checked_mul(4) + .ok_or("readback float count overflow")?; + out.clear(); + out.reserve(float_count); + match format { + wgpu::TextureFormat::Rgba32Float => { + let expected = float_count + .checked_mul(4) + .ok_or("readback byte count overflow")?; + if raw.len() != expected { + return Err(format!( + "Rgba32Float readback size mismatch: expected {expected} bytes, got {}", + raw.len() + ) + .into()); + } + for c in raw.chunks_exact(4) { + out.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]])); + } + } + wgpu::TextureFormat::Rgba16Float => { + let expected = float_count + .checked_mul(2) + .ok_or("readback byte count overflow")?; + if raw.len() != expected { + return Err(format!( + "Rgba16Float readback size mismatch: expected {expected} bytes, got {}", + raw.len() + ) + .into()); + } + for c in raw.chunks_exact(2) { + let bits = u16::from_le_bytes([c[0], c[1]]); + out.push(::exr::prelude::f16::from_bits(bits).to_f32()); + } + } + wgpu::TextureFormat::Rgba8Unorm => { + if raw.len() != float_count { + return Err(format!( + "Rgba8Unorm readback size mismatch: expected {float_count} bytes, got {}", + raw.len() + ) + .into()); + } + for &b in raw { + out.push(f32::from(b) / 255.0); + } + } + other => { + return Err( + format!("unsupported texture format for linear f32 readback: {other:?}").into(), + ); + } + } + Ok(()) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn decode_z_bytes_into_f32( + size: [u32; 2], + raw: &[u8], + out: &mut Vec, + ) -> Result<(), Box> { + let px_count = (size[0] as usize) + .checked_mul(size[1] as usize) + .ok_or("Z readback pixel count overflow")?; + let expected = px_count + .checked_mul(4) + .ok_or("Z readback byte count overflow")?; + if raw.len() != expected { + return Err(format!( + "R32Float Z readback size mismatch: expected {expected} bytes, got {}", + raw.len() + ) + .into()); + } + out.clear(); + out.reserve(px_count); + for c in raw.chunks_exact(4) { + out.push(f32::from_le_bytes([c[0], c[1], c[2], c[3]])); + } + Ok(()) + } + + /// Reads back a `CachedTexture` to CPU linear HDR `f32` RGBA samples (`4 floats/px`), + /// preserving full float precision (`> 1.0` and negatives) for `Rgba32Float` and `Rgba16Float`. + /// Always `Err` on wasm32: a blocking map would trap the browser main thread. + pub fn readback_rgba_f32(&self, tex: &CachedTexture) -> Result, Box> { + #[cfg(target_arch = "wasm32")] + { + let _ = tex; + Err("synchronous GPU readback is unavailable on wasm32".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let bpp = Self::rgba_f32_bpp(tex.format)?; + let raw = self.begin_readback_raw(&tex.texture, tex.size, bpp)?.finish(self)?; + let mut out = Vec::new(); + Self::decode_rgba_bytes_into_f32(tex.format, tex.size, &raw, &mut out)?; + Ok(out) + } + } + + /// Reads back an `R32Float` auxiliary `Z` texture (`4 bytes/px`) into linear `Vec`, + /// preserving exact `-1e30` empty-sky sentinel and negative eye-space depths. + /// Always `Err` on wasm32. + pub fn readback_aux_z_f32( + &self, + z_tex: &AuxChannelTex, + ) -> Result, Box> { + #[cfg(target_arch = "wasm32")] + { + let _ = z_tex; + Err("synchronous GPU readback is unavailable on wasm32".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + if z_tex.format != wgpu::TextureFormat::R32Float { + return Err(format!( + "expected R32Float for Z aux channel, got {:?}", + z_tex.format + ) + .into()); + } + let raw = self.begin_readback_raw(&z_tex.texture, z_tex.size, 4)?.finish(self)?; + let mut out = Vec::new(); + Self::decode_z_bytes_into_f32(z_tex.size, &raw, &mut out)?; + Ok(out) + } + } + + /// Reads back an RGBA auxiliary channel texture (e.g. `Normal` / `Vector` `Rgba16Float`) + /// into linear `Vec` (`4 floats/px`). Always `Err` on wasm32. + pub fn readback_aux_rgba_f32( + &self, + aux_tex: &AuxChannelTex, + ) -> Result, Box> { + #[cfg(target_arch = "wasm32")] + { + let _ = aux_tex; + Err("synchronous GPU readback is unavailable on wasm32".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let bpp = Self::rgba_f32_bpp(aux_tex.format)?; + let raw = self + .begin_readback_raw(&aux_tex.texture, aux_tex.size, bpp)? + .finish(self)?; + let mut out = Vec::new(); + Self::decode_rgba_bytes_into_f32(aux_tex.format, aux_tex.size, &raw, &mut out)?; + Ok(out) + } + } + #[allow(clippy::too_many_arguments)] fn dispatch_with_registry( &self, diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index db1607d2c0042ae02af4b68e9ad010ebd63d34b3..cdffd9ea59f364da08b348c35d3a6a1e61080e40 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1,13 +1,18 @@ -//! Saver-driven pipelined PNG sequence export and ffmpeg video export for `Engine`. +//! Saver-driven pipelined PNG / OpenEXR sequence export and ffmpeg video export for `Engine`. //! -//! Evaluates frames on the GPU while encoding lossless RGBA8 PNG files concurrently -//! across a bounded background worker pool, or piping raw RGBA8 frames into `ffmpeg`. +//! Evaluates frames on the GPU while encoding lossless RGBA8 PNG or linear HDR OpenEXR files +//! concurrently across a bounded background worker pool, or piping raw RGBA8 frames into `ffmpeg`. +mod exr; mod png; #[cfg(test)] mod tests; mod video; +pub use exr::{ + ExrCompression, ExrDepth, export_node_exr_sequence_with_progress, export_node_frame_exr, + export_saver_exr_sequence, export_saver_exr_sequence_with_progress, write_exr_rgba_with_aux, +}; pub use png::{ encode_png_rgba8_into, export_node_frame_png, export_node_png_sequence_with_progress, export_saver_png_sequence, export_saver_png_sequence_with_progress, write_png_fast_buffered, @@ -15,8 +20,9 @@ pub use png::{ pub use video::{export_node_video_ffmpeg, export_node_video_ffmpeg_with_progress}; use crate::cache::EvalStats; +use crate::eval::Engine; use model::{Comp, NodeId, SaverSpec}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Instant; @@ -177,6 +183,105 @@ pub fn select_saver(comp: &Comp, saver_name: Option<&str>) -> Result, + default_ext: &str, +) -> Result { + if saver.filename.is_empty() { + let dir = out_dir_override.ok_or_else(|| { + format!( + "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)", + saver.name + ) + })?; + return Ok(dir.join(format!("{frame:04}.{default_ext}"))); + } + let frame_path = saver.frame_path(frame); + if let Some(dir) = out_dir_override { + let fname = frame_path + .file_name() + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.{default_ext}"))); + Ok(dir.join(fname)) + } else { + Ok(frame_path) + } +} + +pub(super) fn ensure_parent_dir( + path: &Path, + last_parent: &mut Option, +) -> Result<(), String> { + if let Some(parent) = path.parent() + && !parent.as_os_str().is_empty() + && last_parent.as_deref() != Some(parent) + { + std::fs::create_dir_all(parent) + .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; + *last_parent = Some(parent.to_path_buf()); + } + Ok(()) +} + +fn saver_targets_exr(comp: &Comp, saver: &SaverSpec, out_dir_override: Option<&Path>) -> bool { + let node = comp.node(saver.node_id); + if node + .static_str("OutputFormat") + .is_some_and(|s| s.eq_ignore_ascii_case("OpenEXRFormat")) + { + return true; + } + if node + .raw + .get_table("Inputs") + .and_then(|i| i.get_table("Clip")) + .and_then(|c| c.get_table("Value")) + .and_then(|v| v.get_str("FormatID")) + .is_some_and(|s| s.eq_ignore_ascii_case("OpenEXRFormat")) + { + return true; + } + resolve_output_path_with_ext(saver, saver.range[0], out_dir_override, "png").is_ok_and(|p| { + p.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("exr")) + }) +} + +/// Renders and writes an image sequence driven by a Fusion `Saver` node, dispatching +/// automatically to linear HDR OpenEXR (`OpenEXRFormat` / `.exr`) or lossless PNG. +pub fn export_saver_sequence( + engine: &mut Engine, + comp: &Comp, + opts: &ExportOptions, + on_progress: impl FnMut(&ExportProgress), +) -> Result { + export_saver_sequence_with_progress(engine, comp, opts, None, on_progress) +} + +/// Renders and writes an image sequence driven by a Fusion `Saver` node with cooperative +/// cancellation and live progress reporting, dispatching automatically to linear HDR OpenEXR +/// (`OpenEXRFormat` / `.exr`) or lossless PNG. +pub fn export_saver_sequence_with_progress( + engine: &mut Engine, + comp: &Comp, + opts: &ExportOptions, + control: Option<&ExportControl>, + on_progress: impl FnMut(&ExportProgress), +) -> Result { + if control.is_some_and(ExportControl::is_cancelled) { + return Err("Cancelled".to_owned()); + } + let saver = select_saver(comp, opts.saver_name.as_deref())?; + if saver_targets_exr(comp, &saver, opts.out_dir_override.as_deref()) { + exr::export_saver_exr_sequence_with_progress(engine, comp, opts, control, on_progress) + } else { + png::export_saver_png_only_sequence_with_progress(engine, comp, opts, control, on_progress) + } +} + /// Output video codec profile for direct viewer / node ffmpeg export. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum VideoCodec { diff --git a/crates/engine/src/export/exr.rs b/crates/engine/src/export/exr.rs new file mode 100644 index 0000000000000000000000000000000000000000..aff41d024ba9bb254f3959a2af79765862d2289a --- /dev/null +++ b/crates/engine/src/export/exr.rs @@ -0,0 +1,742 @@ +//! Linear HDR OpenEXR (`f16` / `f32` + `Z` / `Normal` auxiliary channels) encoding +//! and pipelined multi-threaded sequence export. + +use super::{ + ExportControl, ExportOptions, ExportProgress, ExportSummary, ensure_parent_dir, make_progress, + resolve_output_path_with_ext, select_saver, +}; +use crate::cache::EvalStats; +use crate::eval::{Engine, PendingReadback}; +use ::exr::prelude::{ + AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Image, Layer, + LayerAttributes, LineOrder, SmallVec, Vec2, WritableImage, f16, +}; +use model::{Comp, NodeId}; +use std::io::Cursor; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::Instant; + +/// Sample bit depth for OpenEXR RGBA (and `Normal`) channels, matching Fusion's +/// `OpenEXRFormat.Depth` (`0` = Float16 default, `1` = Float32). +/// +/// Note: auxiliary `Z` depth is always written as `f32` so `-1e30` sky sentinels +/// and negative eye-space depths never overflow `f16`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ExrDepth { + #[default] + Float16, + Float32, +} + +impl ExrDepth { + pub fn from_fusion_code(code: i32) -> Self { + match code { + 1 => Self::Float32, + _ => Self::Float16, + } + } +} + +/// OpenEXR scanline compression mode matching Fusion's `OpenEXRFormat.Compression` (`0..=5`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ExrCompression { + Uncompressed, + Rle, + Zip1, + #[default] + Zip16, + Piz, + Pxr24, +} + +impl ExrCompression { + pub fn from_fusion_code(code: i32) -> Self { + match code { + 0 => Self::Uncompressed, + 1 => Self::Rle, + 2 => Self::Zip1, + 3 => Self::Zip16, + 4 => Self::Piz, + 5 => Self::Pxr24, + _ => Self::Zip16, + } + } + + fn to_exr(self) -> Compression { + match self { + Self::Uncompressed => Compression::Uncompressed, + Self::Rle => Compression::RLE, + Self::Zip1 => Compression::ZIP1, + Self::Zip16 => Compression::ZIP16, + Self::Piz => Compression::PIZ, + Self::Pxr24 => Compression::PXR24, + } + } +} + +fn push_strided_channel( + channels: &mut SmallVec<[AnyChannel; 4]>, + name: &'static str, + src: &[f32], + stride: usize, + offset: usize, + px_count: usize, + depth: ExrDepth, +) { + let iter = (0..px_count).map(|i| src[i * stride + offset]); + let samples = match depth { + ExrDepth::Float16 => FlatSamples::F16(iter.map(f16::from_f32).collect()), + ExrDepth::Float32 => FlatSamples::F32(iter.collect()), + }; + channels.push(AnyChannel::new(name, samples)); +} + +#[allow(clippy::too_many_arguments)] +fn encode_exr_rgba_with_aux_into( + size: [u32; 2], + rgba_f32: &[f32], + z_f32: Option<&[f32]>, + normal_f32: Option<&[f32]>, + depth: ExrDepth, + compression: ExrCompression, + out: &mut Vec, + parallel: bool, +) -> Result<(), String> { + let [w, h] = size; + if w == 0 || h == 0 { + return Err(format!("invalid EXR dimensions {w}x{h}")); + } + let px_count = (w as usize) + .checked_mul(h as usize) + .ok_or_else(|| format!("EXR dimensions {w}x{h} overflow"))?; + let rgba_len = px_count + .checked_mul(4) + .ok_or_else(|| format!("EXR RGBA size overflow for {w}x{h}"))?; + if rgba_f32.len() != rgba_len { + return Err(format!( + "EXR RGBA slice length mismatch: expected {rgba_len}, got {}", + rgba_f32.len() + )); + } + if let Some(z) = z_f32 + && z.len() != px_count + { + return Err(format!( + "EXR Z slice length mismatch: expected {px_count}, got {}", + z.len() + )); + } + if let Some(n) = normal_f32 + && n.len() != rgba_len + { + return Err(format!( + "EXR Normal slice length mismatch: expected {rgba_len}, got {}", + n.len() + )); + } + + let mut channels = SmallVec::<[AnyChannel; 4]>::new(); + for (offset, name) in [(0, "R"), (1, "G"), (2, "B"), (3, "A")] { + push_strided_channel(&mut channels, name, rgba_f32, 4, offset, px_count, depth); + } + if let Some(z) = z_f32 { + channels.push(AnyChannel::new("Z", FlatSamples::F32(z.to_vec()))); + } + if let Some(n) = normal_f32 { + for (offset, name) in [(0, "NX"), (1, "NY"), (2, "NZ")] { + push_strided_channel(&mut channels, name, n, 4, offset, px_count, depth); + } + } + + let encoding = Encoding { + compression: compression.to_exr(), + blocks: Blocks::ScanLines, + line_order: LineOrder::Increasing, + }; + let image = Image::from_layer(Layer::new( + Vec2(w as usize, h as usize), + LayerAttributes::default(), + encoding, + AnyChannels::sort(channels), + )); + + out.clear(); + let mut cursor = Cursor::new(&mut *out); + let writer = image.write(); + let res = if parallel { + writer.to_buffered(&mut cursor) + } else { + writer.non_parallel().to_buffered(&mut cursor) + }; + res.map_err(|e| format!("failed to encode OpenEXR: {e}")) +} + +#[allow(clippy::too_many_arguments)] +fn write_exr_rgba_with_aux_buffered( + path: &Path, + size: [u32; 2], + rgba_f32: &[f32], + z_f32: Option<&[f32]>, + normal_f32: Option<&[f32]>, + depth: ExrDepth, + compression: ExrCompression, + staging: &mut Vec, + last_parent: &mut Option, + parallel: bool, + cancel: Option<&AtomicBool>, +) -> Result<(), String> { + encode_exr_rgba_with_aux_into( + size, + rgba_f32, + z_f32, + normal_f32, + depth, + compression, + staging, + parallel, + ) + .map_err(|e| format!("{e} ('{}')", path.display()))?; + if cancel.is_some_and(|c| c.load(Ordering::Acquire)) { + return Ok(()); + } + ensure_parent_dir(path, last_parent)?; + std::fs::write(path, staging.as_slice()) + .map_err(|e| format!("failed to write '{}': {e}", path.display())) +} + +/// Writes a linear HDR OpenEXR image containing `"R"`, `"G"`, `"B"`, `"A"` (at `depth`), +/// optional `"Z"` (`f32`), and optional `"NX"`, `"NY"`, `"NZ"` (at `depth`). +pub fn write_exr_rgba_with_aux( + path: &Path, + size: [u32; 2], + rgba_f32: &[f32], + z_f32: Option<&[f32]>, + normal_f32: Option<&[f32]>, + depth: ExrDepth, + compression: ExrCompression, +) -> Result<(), String> { + let mut staging = Vec::new(); + let mut last_parent = None; + write_exr_rgba_with_aux_buffered( + path, + size, + rgba_f32, + z_f32, + normal_f32, + depth, + compression, + &mut staging, + &mut last_parent, + true, + None, + ) +} + +/// Evaluates `target` at `frame` on GPU and saves a single linear HDR OpenEXR to `out_path`, +/// automatically attaching `aux.z` (`"Z"`) and `aux.normal` (`"NX"`, `"NY"`, `"NZ"`) when present. +pub fn export_node_frame_exr( + engine: &mut Engine, + comp: &Comp, + target: NodeId, + frame: f64, + out_path: &Path, + depth: ExrDepth, + compression: ExrCompression, +) -> Result { + if target.0 >= comp.nodes.len() { + return Err(format!("invalid target node id {}", target.0)); + } + let (tex, _) = engine.evaluate(comp, target, frame); + let rgba_f32 = engine + .readback_rgba_f32(&tex) + .map_err(|e| format!("GPU RGBA float readback failed at frame {frame}: {e}"))?; + let z_f32 = match tex.aux.as_ref().and_then(|a| a.z.as_ref()) { + Some(z_tex) if z_tex.size == tex.size => Some( + engine + .readback_aux_z_f32(z_tex) + .map_err(|e| format!("GPU Z aux readback failed at frame {frame}: {e}"))?, + ), + _ => None, + }; + let normal_f32 = match tex.aux.as_ref().and_then(|a| a.normal.as_ref()) { + Some(n_tex) if n_tex.size == tex.size => Some( + engine + .readback_aux_rgba_f32(n_tex) + .map_err(|e| format!("GPU Normal aux readback failed at frame {frame}: {e}"))?, + ), + _ => None, + }; + write_exr_rgba_with_aux( + out_path, + tex.size, + &rgba_f32, + z_f32.as_deref(), + normal_f32.as_deref(), + depth, + compression, + )?; + Ok(out_path.to_path_buf()) +} + +#[derive(Default)] +struct RawByteBuffers { + rgba: Vec, + z: Vec, + normal: Vec, +} + +struct ExrEncodeJob { + path: PathBuf, + size: [u32; 2], + rgba_fmt: wgpu::TextureFormat, + normal_fmt: Option, + has_z: bool, + bufs: RawByteBuffers, +} + +struct PendingExrFrame { + rgba_rb: PendingReadback, + rgba_fmt: wgpu::TextureFormat, + z_rb: Option, + normal_rb: Option<(PendingReadback, wgpu::TextureFormat)>, + frame: i64, + idx: usize, + path: PathBuf, + size: [u32; 2], + stats: EvalStats, +} + +fn start_pending_exr_frame( + engine: &Engine, + tex: &crate::cache::CachedTexture, + frame: i64, + idx: usize, + path: PathBuf, + stats: EvalStats, +) -> Result { + let rgba_bpp = Engine::rgba_f32_bpp(tex.format) + .map_err(|e| format!("GPU RGBA readback setup failed at frame {frame}: {e}"))?; + let rgba_rb = engine + .begin_readback_raw(&tex.texture, tex.size, rgba_bpp) + .map_err(|e| format!("GPU RGBA readback failed at frame {frame}: {e}"))?; + let z_rb = match tex.aux.as_ref().and_then(|a| a.z.as_ref()) { + Some(z_tex) if z_tex.size == tex.size => { + if z_tex.format != wgpu::TextureFormat::R32Float { + return Err(format!( + "expected R32Float for Z aux channel at frame {frame}, got {:?}", + z_tex.format + )); + } + Some( + engine + .begin_readback_raw(&z_tex.texture, z_tex.size, 4) + .map_err(|e| format!("GPU Z aux readback failed at frame {frame}: {e}"))?, + ) + } + _ => None, + }; + let normal_rb = match tex.aux.as_ref().and_then(|a| a.normal.as_ref()) { + Some(n_tex) if n_tex.size == tex.size => { + let n_bpp = Engine::rgba_f32_bpp(n_tex.format) + .map_err(|e| format!("GPU Normal aux format error at frame {frame}: {e}"))?; + let rb = engine + .begin_readback_raw(&n_tex.texture, n_tex.size, n_bpp) + .map_err(|e| format!("GPU Normal aux readback failed at frame {frame}: {e}"))?; + Some((rb, n_tex.format)) + } + _ => None, + }; + Ok(PendingExrFrame { + rgba_rb, + rgba_fmt: tex.format, + z_rb, + normal_rb, + frame, + idx, + path, + size: tex.size, + stats, + }) +} + +fn finish_pending_exr_frame( + engine: &Engine, + pending: PendingExrFrame, + mut bufs: RawByteBuffers, +) -> Result { + pending + .rgba_rb + .finish_into(engine, &mut bufs.rgba) + .map_err(|e| format!("GPU RGBA readback failed at frame {}: {e}", pending.frame))?; + let has_z = if let Some(z_rb) = pending.z_rb { + z_rb.finish_into(engine, &mut bufs.z) + .map_err(|e| format!("GPU Z aux readback failed at frame {}: {e}", pending.frame))?; + true + } else { + bufs.z.clear(); + false + }; + let normal_fmt = if let Some((n_rb, n_fmt)) = pending.normal_rb { + n_rb.finish_into(engine, &mut bufs.normal) + .map_err(|e| format!("GPU Normal aux readback failed at frame {}: {e}", pending.frame))?; + Some(n_fmt) + } else { + bufs.normal.clear(); + None + }; + Ok(ExrEncodeJob { + path: pending.path, + size: pending.size, + rgba_fmt: pending.rgba_fmt, + normal_fmt, + has_z, + bufs, + }) +} + +/// Renders and writes a linear HDR OpenEXR sequence for an arbitrary `target` node across +/// `range` (`[start, end]` inclusive) using double-buffered async GPU readback, recycled raw +/// staging buffers, 12-frame media prefetch, and a bounded background EXR encoder pool. +#[allow(clippy::too_many_arguments)] +pub fn export_node_exr_sequence_with_progress( + engine: &mut Engine, + comp: &Comp, + target: NodeId, + range: [i64; 2], + path_for_frame: impl Fn(i64) -> Result, + label: String, + hiq: bool, + proxy_scale: u32, + exr_workers: usize, + depth: ExrDepth, + compression: ExrCompression, + control: Option<&ExportControl>, + mut on_progress: impl FnMut(&ExportProgress), +) -> Result { + if control.is_some_and(ExportControl::is_cancelled) { + return Err("Cancelled".to_owned()); + } + if target.0 >= comp.nodes.len() { + return Err(format!("invalid target node id {}", target.0)); + } + let [start, end] = range; + let total_i128 = i128::from(end) - i128::from(start) + 1; + if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { + return Err(format!("invalid export frame range {start}..={end}")); + } + + let prev_hiq = engine.hiq; + let prev_proxy = engine.proxy_scale; + engine.hiq = hiq; + engine.proxy_scale = proxy_scale.max(1); + + let total = total_i128 as usize; + let workers = if exr_workers > 0 { + exr_workers.clamp(1, 24) + } else { + std::thread::available_parallelism() + .map(|n| n.get().clamp(2, 24)) + .unwrap_or(4) + } + .min(total.max(1)); + + let t0 = Instant::now(); + let mut first_path: Option = None; + let mut last_path: Option = None; + let mut frames_written: usize = 0; + + let first_err: Arc>> = Arc::new(Mutex::new(None)); + let failed = Arc::new(AtomicBool::new(false)); + let cancelled = Arc::new(AtomicBool::new(false)); + + let eval_result: Result<(), String> = std::thread::scope(|scope| { + let queue_cap = (workers * 2).clamp(16, 48); + let (tx, rx) = mpsc::sync_channel::(queue_cap); + let (recycle_tx, recycle_rx) = mpsc::sync_channel::(queue_cap + workers); + let shared_rx = Arc::new(Mutex::new(rx)); + + let mut handles = Vec::with_capacity(workers); + for _ in 0..workers { + let rx_c = Arc::clone(&shared_rx); + let recycle_c = recycle_tx.clone(); + let err_c = Arc::clone(&first_err); + let fail_c = Arc::clone(&failed); + let cancel_c = Arc::clone(&cancelled); + handles.push(scope.spawn(move || { + let mut rgba_f32 = Vec::new(); + let mut z_f32 = Vec::new(); + let mut normal_f32 = Vec::new(); + let mut staging = Vec::new(); + let mut last_parent: Option = None; + loop { + let job = { + let Ok(guard) = rx_c.lock() else { break }; + guard.recv() + }; + let Ok(job) = job else { break }; + if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) { + continue; + } + let decode_res = (|| -> Result<(), String> { + Engine::decode_rgba_bytes_into_f32( + job.rgba_fmt, + job.size, + &job.bufs.rgba, + &mut rgba_f32, + ) + .map_err(|e| format!("RGBA float decode failed: {e}"))?; + if job.has_z { + Engine::decode_z_bytes_into_f32(job.size, &job.bufs.z, &mut z_f32) + .map_err(|e| format!("Z aux decode failed: {e}"))?; + } + if let Some(n_fmt) = job.normal_fmt { + Engine::decode_rgba_bytes_into_f32( + n_fmt, + job.size, + &job.bufs.normal, + &mut normal_f32, + ) + .map_err(|e| format!("Normal aux decode failed: {e}"))?; + } + write_exr_rgba_with_aux_buffered( + &job.path, + job.size, + &rgba_f32, + job.has_z.then_some(z_f32.as_slice()), + job.normal_fmt.map(|_| normal_f32.as_slice()), + depth, + compression, + &mut staging, + &mut last_parent, + false, + Some(&cancel_c), + ) + })(); + if let Err(e) = decode_res { + if let Ok(mut g) = err_c.lock() + && g.is_none() + { + *g = Some(e); + } + fail_c.store(true, Ordering::Release); + } + let _ = recycle_c.try_send(job.bufs); + } + })); + } + drop(recycle_tx); + + let mut loop_err: Option = None; + const PREFETCH_LOOKAHEAD: usize = 12; + engine.prewarm_for_depth(comp.depth_full); + let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); + if start < end { + let seed_start = start.saturating_add(1); + let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end); + for (k, f) in (seed_start..=seed_end).enumerate() { + prefetch.enqueue_frame( + comp, + target, + k + 1, + f as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } + } + + let mut flush_pending = |engine: &Engine, pend: PendingExrFrame| -> Result { + let prev_frame = pend.frame; + let prev_idx = pend.idx; + let prev_path = pend.path.clone(); + let prev_stats = pend.stats.clone(); + let bufs = recycle_rx.try_recv().unwrap_or_default(); + let job = finish_pending_exr_frame(engine, pend, bufs)?; + if control.is_some_and(ExportControl::is_cancelled) { + cancelled.store(true, Ordering::Release); + return Ok(false); + } + if first_path.is_none() { + first_path = Some(prev_path.clone()); + } + last_path = Some(prev_path.clone()); + let prog = make_progress( + prev_frame, + prev_idx, + total, + prev_stats, + prev_path, + label.clone(), + t0, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); + } + on_progress(&prog); + if control.is_some_and(ExportControl::is_cancelled) { + cancelled.store(true, Ordering::Release); + return Ok(false); + } + if tx.send(job).is_err() { + return Ok(false); + } + frames_written += 1; + Ok(true) + }; + + let mut pending: Option = None; + for (idx, frame) in (start..=end).enumerate() { + if failed.load(Ordering::Acquire) { + break; + } + if control.is_some_and(ExportControl::is_cancelled) { + cancelled.store(true, Ordering::Release); + break; + } + prefetch.set_current_seq(idx); + if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) + && ahead_frame <= end + { + prefetch.enqueue_frame( + comp, + target, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, + &engine.expr, + engine.use_proxy_clips, + ); + } + let out_path = match path_for_frame(frame) { + Ok(p) => p, + Err(e) => { + loop_err = Some(e); + break; + } + }; + let (tex, stats) = engine.evaluate(comp, target, frame as f64); + let next_pend = match start_pending_exr_frame(engine, &tex, frame, idx, out_path, stats) { + Ok(p) => p, + Err(e) => { + loop_err = Some(e); + break; + } + }; + if let Some(prev_pend) = pending.replace(next_pend) { + match flush_pending(engine, prev_pend) { + Ok(true) => {} + Ok(false) => break, + Err(e) => { + loop_err = Some(e); + break; + } + } + } + } + if loop_err.is_none() + && !failed.load(Ordering::Acquire) + && !cancelled.load(Ordering::Acquire) + && let Some(prev_pend) = pending.take() + && let Err(e) = flush_pending(engine, prev_pend) + { + loop_err = Some(e); + } + + drop(prefetch); + drop(tx); + for h in handles { + let _ = h.join(); + } + + if let Some(e) = loop_err { + return Err(e); + } + if let Ok(mut g) = first_err.lock() + && let Some(e) = g.take() + { + return Err(e); + } + if cancelled.load(Ordering::Acquire) { + return Err("Cancelled".to_owned()); + } + Ok(()) + }); + + engine.hiq = prev_hiq; + engine.proxy_scale = prev_proxy; + + eval_result?; + + Ok(ExportSummary { + saver_name: label, + frames_written, + total_ms: t0.elapsed().as_secs_f64() * 1000.0, + first_path, + last_path, + }) +} + +/// Renders and writes a linear HDR OpenEXR sequence driven by a Fusion `Saver` node. +pub fn export_saver_exr_sequence( + engine: &mut Engine, + comp: &Comp, + opts: &ExportOptions, + on_progress: impl FnMut(&ExportProgress), +) -> Result { + export_saver_exr_sequence_with_progress(engine, comp, opts, None, on_progress) +} + +/// Renders and writes a linear HDR OpenEXR sequence driven by a Fusion `Saver` node with +/// cooperative cancellation and live progress reporting via `ExportControl`. +pub fn export_saver_exr_sequence_with_progress( + engine: &mut Engine, + comp: &Comp, + opts: &ExportOptions, + control: Option<&ExportControl>, + on_progress: impl FnMut(&ExportProgress), +) -> Result { + if control.is_some_and(ExportControl::is_cancelled) { + return Err("Cancelled".to_owned()); + } + let saver = select_saver(comp, opts.saver_name.as_deref())?; + let target: NodeId = saver.upstream.unwrap_or(saver.node_id); + let range = opts.range_override.unwrap_or(saver.range); + let saver_node = comp.node(saver.node_id); + let depth = ExrDepth::from_fusion_code( + comp.eval_number( + saver_node, + "OpenEXRFormat.Depth", + range[0] as f64, + 0.0, + &engine.expr, + ) + .round() as i32, + ); + let compression = ExrCompression::from_fusion_code( + comp.eval_number( + saver_node, + "OpenEXRFormat.Compression", + range[0] as f64, + 3.0, + &engine.expr, + ) + .round() as i32, + ); + let out_dir_override = opts.out_dir_override.as_deref(); + export_node_exr_sequence_with_progress( + engine, + comp, + target, + range, + |frame| resolve_output_path_with_ext(&saver, frame, out_dir_override, "exr"), + saver.name.clone(), + opts.hiq, + opts.proxy_scale, + opts.png_workers, + depth, + compression, + control, + on_progress, + ) +} diff --git a/crates/engine/src/export/png.rs b/crates/engine/src/export/png.rs index 625051f9717d7e0144e9d22ea29d28f2da8ce650..0c6ab880c028b5121d1c923a06249d1b985a70a2 100644 --- a/crates/engine/src/export/png.rs +++ b/crates/engine/src/export/png.rs @@ -1,42 +1,17 @@ //! Lossless RGBA8 PNG encoding and pipelined multi-threaded PNG sequence export. use super::{ - ExportControl, ExportOptions, ExportProgress, ExportSummary, make_progress, select_saver, + ExportControl, ExportOptions, ExportProgress, ExportSummary, ensure_parent_dir, make_progress, + resolve_output_path_with_ext, select_saver, }; use crate::cache::EvalStats; use crate::eval::Engine; -use model::{Comp, NodeId, SaverSpec}; +use model::{Comp, NodeId}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, mpsc}; use std::time::Instant; -fn resolve_output_path( - saver: &SaverSpec, - frame: i64, - out_dir_override: Option<&Path>, -) -> Result { - if saver.filename.is_empty() { - let dir = out_dir_override.ok_or_else(|| { - format!( - "Saver '{}' has no Clip.Filename set (pass an output directory override or configure Clip.Filename)", - saver.name - ) - })?; - return Ok(dir.join(format!("{frame:04}.png"))); - } - let frame_path = saver.frame_path(frame); - if let Some(dir) = out_dir_override { - let fname = frame_path - .file_name() - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(format!("{frame:04}.png"))); - Ok(dir.join(fname)) - } else { - Ok(frame_path) - } -} - /// Encodes an RGBA8 image into `out` as a lossless PNG matching Fusion's default /// libpng compression (`Compression::Balanced` = zlib level 6 + `Filter::Adaptive`). pub fn encode_png_rgba8_into(size: [u32; 2], pixels: &[u8], out: &mut Vec) -> Result<(), String> { @@ -66,13 +41,7 @@ pub fn write_png_fast_buffered( staging: &mut Vec, last_parent: &mut Option, ) -> Result<(), String> { - if let Some(parent) = path.parent() { - if !parent.as_os_str().is_empty() && last_parent.as_deref() != Some(parent) { - std::fs::create_dir_all(parent) - .map_err(|e| format!("failed to create '{}': {e}", parent.display()))?; - *last_parent = Some(parent.to_path_buf()); - } - } + ensure_parent_dir(path, last_parent)?; encode_png_rgba8_into(size, pixels, staging) .map_err(|e| format!("{e} ('{}')", path.display()))?; std::fs::write(path, staging.as_slice()) @@ -410,14 +379,27 @@ pub fn export_saver_png_sequence( export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress) } -/// Renders and writes a PNG sequence driven by a Fusion `Saver` node with cooperative +/// Renders and writes an image sequence driven by a Fusion `Saver` node with cooperative /// cancellation and live progress reporting via `ExportControl`. +/// +/// Automatically dispatches to OpenEXR export when the Saver specifies `OutputFormat == "OpenEXRFormat"` +/// or resolves to a `.exr` output path. pub fn export_saver_png_sequence_with_progress( engine: &mut Engine, comp: &Comp, opts: &ExportOptions, control: Option<&ExportControl>, on_progress: impl FnMut(&ExportProgress), +) -> Result { + super::export_saver_sequence_with_progress(engine, comp, opts, control, on_progress) +} + +pub(super) fn export_saver_png_only_sequence_with_progress( + engine: &mut Engine, + comp: &Comp, + opts: &ExportOptions, + control: Option<&ExportControl>, + on_progress: impl FnMut(&ExportProgress), ) -> Result { if control.is_some_and(ExportControl::is_cancelled) { return Err("Cancelled".to_owned()); @@ -431,7 +413,7 @@ pub fn export_saver_png_sequence_with_progress( comp, target, range, - |frame| resolve_output_path(&saver, frame, out_dir_override), + |frame| resolve_output_path_with_ext(&saver, frame, out_dir_override, "png"), saver.name.clone(), opts.hiq, opts.proxy_scale, diff --git a/crates/engine/src/export/tests.rs b/crates/engine/src/export/tests.rs index ec0d5abf8864fc921a9925219438756b4a9fa54e..e2dd7e89308009c01656c49c62f6862f3b8f5dca 100644 --- a/crates/engine/src/export/tests.rs +++ b/crates/engine/src/export/tests.rs @@ -1284,3 +1284,509 @@ fn video_export_cancel_on_final_frame_progress_cancels_cleanly() { let _ = std::fs::remove_dir_all(&tmp_dir); } + +#[test] +fn readback_rgba_f32_preserves_hdr_and_strips_row_padding() { + let Ok(engine) = Engine::new_headless() else { + return; + }; + // Unaligned width 19 forces row padding on Rgba8Unorm (76->256), Rgba16Float (152->256), and Rgba32Float (304->512). + let [w, h] = [19u32, 11u32]; + let px_count = (w * h) as usize; + + let upload_and_check = |format: wgpu::TextureFormat, bytes: &[u8], expected: &[f32]| { + let texture = engine.device().create_texture(&wgpu::TextureDescriptor { + label: Some("test-readback-f32"), + size: wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let bpp = match format { + wgpu::TextureFormat::Rgba32Float => 16u32, + wgpu::TextureFormat::Rgba16Float => 8u32, + wgpu::TextureFormat::Rgba8Unorm => 4u32, + _ => unreachable!(), + }; + engine.queue().write_texture( + texture.as_image_copy(), + bytes, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(w * bpp), + rows_per_image: Some(h), + }, + wgpu::Extent3d { + width: w, + height: h, + depth_or_array_layers: 1, + }, + ); + let cached = crate::cache::CachedTexture::from_texture(texture, [w, h], 0); + let got = engine + .readback_rgba_f32(&cached) + .expect("readback_rgba_f32 should succeed"); + assert_eq!(got.len(), px_count * 4); + for (i, (&g, &e)) in got.iter().zip(expected.iter()).enumerate() { + assert!( + (g - e).abs() <= 2e-3, + "{format:?} sample {i}: expected {e}, got {g}" + ); + } + }; + + let mut f32_vals = Vec::with_capacity(px_count * 4); + let mut f16_bits = Vec::with_capacity(px_count * 4); + let mut u8_vals = Vec::with_capacity(px_count * 4); + let mut u8_expected = Vec::with_capacity(px_count * 4); + for i in 0..px_count { + let r = 2.5 + (i % 5) as f32 * 0.25; + let g = -0.75 + (i % 3) as f32 * 0.5; + let b = 0.125 * (i % 7) as f32; + let a = 1.0; + f32_vals.extend_from_slice(&[r, g, b, a]); + f16_bits.extend_from_slice(&[ + ::exr::prelude::f16::from_f32(r).to_bits(), + ::exr::prelude::f16::from_f32(g).to_bits(), + ::exr::prelude::f16::from_f32(b).to_bits(), + ::exr::prelude::f16::from_f32(a).to_bits(), + ]); + let r8 = ((i * 17) % 256) as u8; + let g8 = ((i * 31) % 256) as u8; + let b8 = ((i * 53) % 256) as u8; + let a8 = 255u8; + u8_vals.extend_from_slice(&[r8, g8, b8, a8]); + u8_expected.extend_from_slice(&[ + f32::from(r8) / 255.0, + f32::from(g8) / 255.0, + f32::from(b8) / 255.0, + 1.0, + ]); + } + + upload_and_check( + wgpu::TextureFormat::Rgba32Float, + bytemuck::cast_slice(&f32_vals), + &f32_vals, + ); + upload_and_check( + wgpu::TextureFormat::Rgba16Float, + bytemuck::cast_slice(&f16_bits), + &f32_vals, + ); + upload_and_check(wgpu::TextureFormat::Rgba8Unorm, &u8_vals, &u8_expected); +} + +#[test] +fn exports_exr_hdr_and_aux_roundtrips_through_loader() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-exr-roundtrip-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); + + let Ok(mut engine) = Engine::new_headless() else { + let _ = std::fs::remove_dir_all(&tmp_dir); + return; + }; + + for (depth_code, expected_sample_type, tag) in [ + (0, ::exr::meta::attribute::SampleType::F16, "f16"), + (1, ::exr::meta::attribute::SampleType::F32, "f32"), + ] { + let saver_path = tmp_dir.join(tag).join("render_0000.exr"); + let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); + // Plane at Z = 0, Camera at Z = 2 => eye-space Z = -2.0; R3D Z + Normal aux channels + // flow through ChangeDepth (Depth=4 Float32) + BrightnessContrast (Gain=2.5 => R=2.5 HDR). + let comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 0 }}, + GlobalRange = {{ 0, 10 }}, + Tools = ordered() {{ + Flat = MtlBlinn {{ + Inputs = {{ + ["Diffuse.Color.Red"] = Input {{ Value = 1.0, }}, + ["Diffuse.Color.Green"] = Input {{ Value = 0.2, }}, + ["Diffuse.Color.Blue"] = Input {{ Value = 0.1, }}, + ["Specular.Intensity"] = Input {{ Value = 0, }}, + }}, + }}, + P = Shape3D {{ + Inputs = {{ + ["SurfacePlaneInputs.Width"] = Input {{ Value = 0.5, }}, + ["SurfacePlaneInputs.Height"] = Input {{ Value = 0.5, }}, + ["Transform3DOp.Translate.Z"] = Input {{ Value = 0.0, }}, + MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, + }}, + }}, + Cam = Camera3D {{ + Inputs = {{ + ProjectionType = Input {{ Value = FuID {{ "Perspective" }}, }}, + ["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, + ApertureW = Input {{ Value = 1.0, }}, + ApertureH = Input {{ Value = 1.0, }}, + }}, + }}, + M = Merge3D {{ + Inputs = {{ + SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, + SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, + }}, + }}, + R = Renderer3D {{ + Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 64, }}, + Depth = Input {{ Value = 4, }}, + ["RendererSoftware.Channels.Z"] = Input {{ Value = 1, }}, + ["RendererSoftware.Channels.Normal"] = Input {{ Value = 1, }}, + SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, + }}, + }}, + CD = ChangeDepth {{ + Inputs = {{ + Depth = Input {{ Value = 4, }}, + Input = Input {{ SourceOp = "R", Source = "Output", }}, + }}, + }}, + BC = BrightnessContrast {{ + Inputs = {{ + Gain = Input {{ Value = 2.5, }}, + Input = Input {{ SourceOp = "CD", Source = "Output", }}, + }}, + }}, + Saver1 = Saver {{ + Inputs = {{ + OutputFormat = Input {{ Value = FuID {{ "OpenEXRFormat" }}, }}, + ["OpenEXRFormat.Depth"] = Input {{ Value = {depth_code}, }}, + ["OpenEXRFormat.Compression"] = Input {{ Value = 3, }}, + Clip = Input {{ + Value = Clip {{ + Filename = "{saver_path_escaped}", + FormatID = "OpenEXRFormat", + Saving = true, + }}, + }}, + Input = Input {{ SourceOp = "BC", Source = "Output", }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 64, Rate = 24, DepthFull = 4 }} }} }}, +}}"# + ); + + let comp = Comp::from_fusion_str(&comp_src).expect("parse EXR Saver comp"); + let summary = export_saver_sequence_with_progress( + &mut engine, + &comp, + &ExportOptions::default(), + None, + |_| {}, + ) + .expect("export EXR via Saver"); + assert_eq!(summary.frames_written, 1); + + let out_exr = tmp_dir.join(tag).join("render_0000.exr"); + assert!(out_exr.exists(), "missing exported EXR {}", out_exr.display()); + + // Inspect channel metadata & Normal channel values directly in the EXR file. + let meta = ::exr::meta::MetaData::read_from_file(&out_exr, false).expect("read EXR meta"); + let ch_list = &meta.headers[0].channels.list; + let find_ch = |name: &str| { + ch_list + .iter() + .find(|c| c.name.to_string() == name) + .unwrap_or_else(|| panic!("{tag}: missing EXR channel '{name}'")) + }; + for c in ["R", "G", "B", "A", "NX", "NY", "NZ"] { + assert_eq!( + find_ch(c).sample_type, + expected_sample_type, + "{tag}: channel {c} sample type mismatch" + ); + } + assert_eq!( + find_ch("Z").sample_type, + ::exr::meta::attribute::SampleType::F32, + "{tag}: Z channel must always be Float32" + ); + // Verify NX, NY, NZ normal values directly in the exported EXR layer. + let flat_img = ::exr::prelude::read_all_flat_layers_from_file(&out_exr) + .expect("read EXR flat layers"); + let channels = &flat_img.layer_data[0].channel_data.list; + let read_ch_f32 = |name: &str, idx: usize| -> f32 { + let ch = channels + .iter() + .find(|c| c.name.to_string() == name) + .unwrap_or_else(|| panic!("{tag}: missing flat channel '{name}'")); + match &ch.sample_data { + ::exr::prelude::FlatSamples::F16(v) => v[idx].to_f32(), + ::exr::prelude::FlatSamples::F32(v) => v[idx], + ::exr::prelude::FlatSamples::U32(v) => v[idx] as f32, + } + }; + let center_idx = 32 * 64 + 32; + let (nx, ny, nz) = ( + read_ch_f32("NX", center_idx), + read_ch_f32("NY", center_idx), + read_ch_f32("NZ", center_idx), + ); + assert!( + nx.abs() <= 1e-2 && ny.abs() <= 1e-2 && (nz - 1.0).abs() <= 1e-2, + "{tag}: center normal expected ~(0,0,1), got ({nx}, {ny}, {nz})" + ); + assert_eq!( + (read_ch_f32("NX", 0), read_ch_f32("NY", 0), read_ch_f32("NZ", 0)), + (0.0, 0.0, 0.0), + "{tag}: corner normal expected (0,0,0)" + ); + + // Reload via Fusion Loader node (media/exr.rs) and verify linear HDR + aux.z! + let out_exr_escaped = out_exr.to_string_lossy().replace('\\', "\\\\"); + let loader_comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 0 }}, + GlobalRange = {{ 0, 0 }}, + Tools = ordered() {{ + L = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{out_exr_escaped}", + FormatID = "OpenEXRFormat", + StartFrame = 0, + Length = 1, + GlobalStart = 0, + GlobalEnd = 0, + }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 64, Rate = 24, DepthFull = 4 }} }} }}, +}}"# + ); + let loader_comp = Comp::from_fusion_str(&loader_comp_src).expect("parse Loader comp"); + let l_id = loader_comp.find_node("L").expect("find Loader"); + let (loaded_tex, _) = engine.evaluate(&loader_comp, l_id, 0.0); + + let rgba = engine + .readback_rgba_f32(&loaded_tex) + .expect("readback reloaded EXR RGBA"); + let center_off = (32 * 64 + 32) * 4; + assert!( + rgba[center_off] > 2.0, + "{tag}: HDR linear R must be preserved (> 2.0), got {}", + rgba[center_off] + ); + assert!( + (rgba[center_off] - 2.5).abs() <= 0.03, + "{tag}: expected R ~ 2.5, got {}", + rgba[center_off] + ); + assert!( + (rgba[center_off + 1] - 0.5).abs() <= 0.03, + "{tag}: expected G ~ 0.5, got {}", + rgba[center_off + 1] + ); + assert!( + (rgba[center_off + 2] - 0.25).abs() <= 0.03, + "{tag}: expected B ~ 0.25, got {}", + rgba[center_off + 2] + ); + assert!((rgba[center_off + 3] - 1.0).abs() <= 0.01); + + let aux = loaded_tex + .aux + .as_ref() + .expect("reloaded EXR must carry aux channels"); + let z_tex = aux.z.as_ref().expect("reloaded EXR must carry aux.z"); + let z_vals = engine + .readback_aux_z_f32(z_tex) + .expect("readback reloaded EXR aux.z"); + let center_z = z_vals[32 * 64 + 32]; + let corner_z = z_vals[0]; + assert!( + (center_z - (-2.0)).abs() <= 1e-3, + "{tag}: reloaded center Z expected -2.0, got {center_z}" + ); + assert_eq!( + corner_z, + crate::cache::EMPTY_Z_SENTINEL, + "{tag}: reloaded empty corner Z expected -1e30, got {corner_z}" + ); + } + + // Also verify write_exr_rgba_with_aux across all 6 Fusion compression modes. + let rgba_sample = vec![2.5, 0.5, 0.25, 1.0, 0.0, 0.0, 0.0, 0.0]; + let z_sample = vec![-2.0, crate::cache::EMPTY_Z_SENTINEL]; + let n_sample = vec![0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + for comp_mode in [ + ExrCompression::Uncompressed, + ExrCompression::Rle, + ExrCompression::Zip1, + ExrCompression::Zip16, + ExrCompression::Piz, + ExrCompression::Pxr24, + ] { + let p = tmp_dir.join(format!("comp_{comp_mode:?}.exr")); + write_exr_rgba_with_aux( + &p, + [2, 1], + &rgba_sample, + Some(&z_sample), + Some(&n_sample), + ExrDepth::Float16, + comp_mode, + ) + .unwrap_or_else(|e| panic!("write EXR {comp_mode:?} failed: {e}")); + assert!(p.exists()); + } + + let _ = std::fs::remove_dir_all(&tmp_dir); +} + +#[test] +fn exports_exr_saver_sequence_and_stops_cleanly_on_cancel() { + let tmp_dir = std::env::temp_dir().join(format!( + "fission-exr-seq-cancel-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + + let full_dir = tmp_dir.join("full"); + let cancel_dir = tmp_dir.join("cancel"); + + let make_comp = |dir: &Path| { + let saver_path = dir.join("shot_0000.exr"); + let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); + let comp_src = format!( + r#"Composition {{ + CurrentTime = 10, + RenderRange = {{ 10, 15 }}, + GlobalRange = {{ 0, 100 }}, + Tools = ordered() {{ + BG = Background {{ + Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 32, }}, + Depth = Input {{ Value = 4, }}, + TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, + TopLeftGreen = Input {{ Value = 0.25, }}, + TopLeftBlue = Input {{ Value = 0.5, }}, + TopLeftAlpha = Input {{ Value = 1, }}, + }}, + }}, + BGRed = BezierSpline {{ + KeyFrames = {{ + [10] = {{ 0.5, Flags = {{ Linear = true }} }}, + [15] = {{ 3.0, Flags = {{ Linear = true }} }}, + }}, + }}, + Saver1 = Saver {{ + Inputs = {{ + OutputFormat = Input {{ Value = FuID {{ "OpenEXRFormat" }}, }}, + ["OpenEXRFormat.Depth"] = Input {{ Value = 0, }}, + ["OpenEXRFormat.Compression"] = Input {{ Value = 3, }}, + Clip = Input {{ + Value = Clip {{ + Filename = "{saver_path_escaped}", + FormatID = "OpenEXRFormat", + Saving = true, + }}, + }}, + Input = Input {{ SourceOp = "BG", Source = "Output", }}, + }}, + }}, + }}, + Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 4 }} }} }}, +}}"# + ); + Comp::from_fusion_str(&comp_src).expect("parse EXR sequence comp") + }; + + let Ok(mut engine) = Engine::new_headless() else { + return; + }; + + // 1. Verify export_saver_png_sequence_with_progress automatically dispatches to OpenEXR! + let full_comp = make_comp(&full_dir); + let mut seen_frames = Vec::new(); + let summary = export_saver_png_sequence_with_progress( + &mut engine, + &full_comp, + &ExportOptions::default(), + None, + |p| seen_frames.push(p.frame), + ) + .expect("export EXR sequence via Saver dispatcher"); + assert_eq!(summary.frames_written, 6); + assert_eq!(seen_frames, vec![10, 11, 12, 13, 14, 15]); + for f in 10..=15 { + let p = full_dir.join(format!("shot_{f:04}.exr")); + assert!(p.exists(), "missing EXR frame {}", p.display()); + } + let last_exr = full_dir.join("shot_0015.exr"); + let last_exr_escaped = last_exr.to_string_lossy().replace('\\', "\\\\"); + let loader_comp = Comp::from_fusion_str(&format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ + L = Loader {{ Clips = {{ Clip {{ ID = "Clip1", Filename = "{last_exr_escaped}", StartFrame = 0, Length = 1, GlobalStart = 0, GlobalEnd = 0, }} }}, }}, + }}, Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, DepthFull = 4 }} }} }} }}"# + )) + .unwrap(); + let (ltex, _) = engine.evaluate(&loader_comp, loader_comp.find_node("L").unwrap(), 0.0); + let lrgba = engine.readback_rgba_f32(<ex).unwrap(); + assert!( + (lrgba[0] - 3.0).abs() <= 0.02, + "frame 15 HDR red expected ~3.0, got {}", + lrgba[0] + ); + + // 2. Verify cooperative cancellation stops cleanly and leaves zero leaked temp files. + let cancel_comp = make_comp(&cancel_dir); + let control = ExportControl::new(); + let ctrl_cb = control.clone(); + let mut reported = Vec::new(); + let err = export_saver_exr_sequence_with_progress( + &mut engine, + &cancel_comp, + &ExportOptions::default(), + Some(&control), + |p| { + reported.push(p.completed_frames); + if p.completed_frames >= 2 { + ctrl_cb.cancel(); + } + }, + ) + .expect_err("EXR sequence export should cancel early"); + assert_eq!(err, "Cancelled"); + assert_eq!(reported, vec![1, 2]); + assert!(!cancel_dir.join("shot_0015.exr").exists()); + + if cancel_dir.exists() { + for entry in std::fs::read_dir(&cancel_dir).expect("read cancel_dir") { + let entry = entry.expect("dir entry"); + let path = entry.path(); + assert_eq!( + path.extension().and_then(|e| e.to_str()), + Some("exr"), + "unexpected leaked temp/partial file: {}", + path.display() + ); + ::exr::meta::MetaData::read_from_file(&path, false) + .unwrap_or_else(|e| panic!("corrupt EXR file {}: {e}", path.display())); + } + } + + let _ = std::fs::remove_dir_all(&tmp_dir); +} -- 2.54.1