| 1 | //! Linear HDR OpenEXR (`f16` / `f32` + `Z` / `Normal` auxiliary channels) encoding |
| 2 | //! and pipelined multi-threaded sequence export. |
| 3 | |
| 4 | use super::{ |
| 5 | ExportControl, ExportOptions, ExportProgress, ExportSummary, ensure_parent_dir, make_progress, |
| 6 | resolve_output_path_with_ext, select_saver, |
| 7 | }; |
| 8 | use crate::cache::EvalStats; |
| 9 | use crate::eval::{Engine, PendingReadback}; |
| 10 | use ::exr::prelude::{ |
| 11 | AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, Image, Layer, |
| 12 | LayerAttributes, LineOrder, SmallVec, Vec2, WritableImage, f16, |
| 13 | }; |
| 14 | use model::{Comp, NodeId}; |
| 15 | use std::io::Cursor; |
| 16 | use std::path::{Path, PathBuf}; |
| 17 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 18 | use std::sync::{Arc, Mutex, mpsc}; |
| 19 | use std::time::Instant; |
| 20 | |
| 21 | /// Sample bit depth for OpenEXR RGBA (and `Normal`) channels, matching Fusion's |
| 22 | /// `OpenEXRFormat.Depth` (`0` = Float16 default, `1` = Float32). |
| 23 | /// |
| 24 | /// Note: auxiliary `Z` depth is always written as `f32` so `-1e30` sky sentinels |
| 25 | /// and negative eye-space depths never overflow `f16`. |
| 26 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] |
| 27 | pub enum ExrDepth { |
| 28 | #[default] |
| 29 | Float16, |
| 30 | Float32, |
| 31 | } |
| 32 | |
| 33 | impl ExrDepth { |
| 34 | pub fn from_fusion_code(code: i32) -> Self { |
| 35 | match code { |
| 36 | 1 => Self::Float32, |
| 37 | _ => Self::Float16, |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | /// OpenEXR scanline compression mode matching Fusion's `OpenEXRFormat.Compression` (`0..=5`). |
| 43 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] |
| 44 | pub enum ExrCompression { |
| 45 | Uncompressed, |
| 46 | Rle, |
| 47 | Zip1, |
| 48 | #[default] |
| 49 | Zip16, |
| 50 | Piz, |
| 51 | Pxr24, |
| 52 | } |
| 53 | |
| 54 | impl ExrCompression { |
| 55 | pub fn from_fusion_code(code: i32) -> Self { |
| 56 | match code { |
| 57 | 0 => Self::Uncompressed, |
| 58 | 1 => Self::Rle, |
| 59 | 2 => Self::Zip1, |
| 60 | 3 => Self::Zip16, |
| 61 | 4 => Self::Piz, |
| 62 | 5 => Self::Pxr24, |
| 63 | _ => Self::Zip16, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | fn to_exr(self) -> Compression { |
| 68 | match self { |
| 69 | Self::Uncompressed => Compression::Uncompressed, |
| 70 | Self::Rle => Compression::RLE, |
| 71 | Self::Zip1 => Compression::ZIP1, |
| 72 | Self::Zip16 => Compression::ZIP16, |
| 73 | Self::Piz => Compression::PIZ, |
| 74 | Self::Pxr24 => Compression::PXR24, |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | fn push_strided_channel( |
| 80 | channels: &mut SmallVec<[AnyChannel<FlatSamples>; 4]>, |
| 81 | name: &'static str, |
| 82 | src: &[f32], |
| 83 | stride: usize, |
| 84 | offset: usize, |
| 85 | px_count: usize, |
| 86 | depth: ExrDepth, |
| 87 | ) { |
| 88 | let iter = (0..px_count).map(|i| src[i * stride + offset]); |
| 89 | let samples = match depth { |
| 90 | ExrDepth::Float16 => FlatSamples::F16(iter.map(f16::from_f32).collect()), |
| 91 | ExrDepth::Float32 => FlatSamples::F32(iter.collect()), |
| 92 | }; |
| 93 | channels.push(AnyChannel::new(name, samples)); |
| 94 | } |
| 95 | |
| 96 | #[allow(clippy::too_many_arguments)] |
| 97 | fn encode_exr_rgba_with_aux_into( |
| 98 | size: [u32; 2], |
| 99 | rgba_f32: &[f32], |
| 100 | z_f32: Option<&[f32]>, |
| 101 | normal_f32: Option<&[f32]>, |
| 102 | depth: ExrDepth, |
| 103 | compression: ExrCompression, |
| 104 | out: &mut Vec<u8>, |
| 105 | parallel: bool, |
| 106 | ) -> Result<(), String> { |
| 107 | let [w, h] = size; |
| 108 | if w == 0 || h == 0 { |
| 109 | return Err(format!("invalid EXR dimensions {w}x{h}")); |
| 110 | } |
| 111 | let px_count = (w as usize) |
| 112 | .checked_mul(h as usize) |
| 113 | .ok_or_else(|| format!("EXR dimensions {w}x{h} overflow"))?; |
| 114 | let rgba_len = px_count |
| 115 | .checked_mul(4) |
| 116 | .ok_or_else(|| format!("EXR RGBA size overflow for {w}x{h}"))?; |
| 117 | if rgba_f32.len() != rgba_len { |
| 118 | return Err(format!( |
| 119 | "EXR RGBA slice length mismatch: expected {rgba_len}, got {}", |
| 120 | rgba_f32.len() |
| 121 | )); |
| 122 | } |
| 123 | if let Some(z) = z_f32 |
| 124 | && z.len() != px_count |
| 125 | { |
| 126 | return Err(format!( |
| 127 | "EXR Z slice length mismatch: expected {px_count}, got {}", |
| 128 | z.len() |
| 129 | )); |
| 130 | } |
| 131 | if let Some(n) = normal_f32 |
| 132 | && n.len() != rgba_len |
| 133 | { |
| 134 | return Err(format!( |
| 135 | "EXR Normal slice length mismatch: expected {rgba_len}, got {}", |
| 136 | n.len() |
| 137 | )); |
| 138 | } |
| 139 | |
| 140 | let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new(); |
| 141 | for (offset, name) in [(0, "R"), (1, "G"), (2, "B"), (3, "A")] { |
| 142 | push_strided_channel(&mut channels, name, rgba_f32, 4, offset, px_count, depth); |
| 143 | } |
| 144 | if let Some(z) = z_f32 { |
| 145 | channels.push(AnyChannel::new("Z", FlatSamples::F32(z.to_vec()))); |
| 146 | } |
| 147 | if let Some(n) = normal_f32 { |
| 148 | for (offset, name) in [(0, "NX"), (1, "NY"), (2, "NZ")] { |
| 149 | push_strided_channel(&mut channels, name, n, 4, offset, px_count, depth); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | let encoding = Encoding { |
| 154 | compression: compression.to_exr(), |
| 155 | blocks: Blocks::ScanLines, |
| 156 | line_order: LineOrder::Increasing, |
| 157 | }; |
| 158 | let image = Image::from_layer(Layer::new( |
| 159 | Vec2(w as usize, h as usize), |
| 160 | LayerAttributes::default(), |
| 161 | encoding, |
| 162 | AnyChannels::sort(channels), |
| 163 | )); |
| 164 | |
| 165 | out.clear(); |
| 166 | let mut cursor = Cursor::new(&mut *out); |
| 167 | let writer = image.write(); |
| 168 | let res = if parallel { |
| 169 | writer.to_buffered(&mut cursor) |
| 170 | } else { |
| 171 | writer.non_parallel().to_buffered(&mut cursor) |
| 172 | }; |
| 173 | res.map_err(|e| format!("failed to encode OpenEXR: {e}")) |
| 174 | } |
| 175 | |
| 176 | #[allow(clippy::too_many_arguments)] |
| 177 | fn write_exr_rgba_with_aux_buffered( |
| 178 | path: &Path, |
| 179 | size: [u32; 2], |
| 180 | rgba_f32: &[f32], |
| 181 | z_f32: Option<&[f32]>, |
| 182 | normal_f32: Option<&[f32]>, |
| 183 | depth: ExrDepth, |
| 184 | compression: ExrCompression, |
| 185 | staging: &mut Vec<u8>, |
| 186 | last_parent: &mut Option<PathBuf>, |
| 187 | parallel: bool, |
| 188 | cancel: Option<&AtomicBool>, |
| 189 | ) -> Result<(), String> { |
| 190 | encode_exr_rgba_with_aux_into( |
| 191 | size, |
| 192 | rgba_f32, |
| 193 | z_f32, |
| 194 | normal_f32, |
| 195 | depth, |
| 196 | compression, |
| 197 | staging, |
| 198 | parallel, |
| 199 | ) |
| 200 | .map_err(|e| format!("{e} ('{}')", path.display()))?; |
| 201 | if cancel.is_some_and(|c| c.load(Ordering::Acquire)) { |
| 202 | return Ok(()); |
| 203 | } |
| 204 | ensure_parent_dir(path, last_parent)?; |
| 205 | std::fs::write(path, staging.as_slice()) |
| 206 | .map_err(|e| format!("failed to write '{}': {e}", path.display())) |
| 207 | } |
| 208 | |
| 209 | /// Writes a linear HDR OpenEXR image containing `"R"`, `"G"`, `"B"`, `"A"` (at `depth`), |
| 210 | /// optional `"Z"` (`f32`), and optional `"NX"`, `"NY"`, `"NZ"` (at `depth`). |
| 211 | pub fn write_exr_rgba_with_aux( |
| 212 | path: &Path, |
| 213 | size: [u32; 2], |
| 214 | rgba_f32: &[f32], |
| 215 | z_f32: Option<&[f32]>, |
| 216 | normal_f32: Option<&[f32]>, |
| 217 | depth: ExrDepth, |
| 218 | compression: ExrCompression, |
| 219 | ) -> Result<(), String> { |
| 220 | let mut staging = Vec::new(); |
| 221 | let mut last_parent = None; |
| 222 | write_exr_rgba_with_aux_buffered( |
| 223 | path, |
| 224 | size, |
| 225 | rgba_f32, |
| 226 | z_f32, |
| 227 | normal_f32, |
| 228 | depth, |
| 229 | compression, |
| 230 | &mut staging, |
| 231 | &mut last_parent, |
| 232 | true, |
| 233 | None, |
| 234 | ) |
| 235 | } |
| 236 | |
| 237 | /// Evaluates `target` at `frame` on GPU and saves a single linear HDR OpenEXR to `out_path`, |
| 238 | /// automatically attaching `aux.z` (`"Z"`) and `aux.normal` (`"NX"`, `"NY"`, `"NZ"`) when present. |
| 239 | pub fn export_node_frame_exr( |
| 240 | engine: &mut Engine, |
| 241 | comp: &Comp, |
| 242 | target: NodeId, |
| 243 | frame: f64, |
| 244 | out_path: &Path, |
| 245 | depth: ExrDepth, |
| 246 | compression: ExrCompression, |
| 247 | ) -> Result<PathBuf, String> { |
| 248 | if target.0 >= comp.nodes.len() { |
| 249 | return Err(format!("invalid target node id {}", target.0)); |
| 250 | } |
| 251 | let (tex, _) = engine.evaluate(comp, target, frame); |
| 252 | let rgba_f32 = engine |
| 253 | .readback_rgba_f32(&tex) |
| 254 | .map_err(|e| format!("GPU RGBA float readback failed at frame {frame}: {e}"))?; |
| 255 | let z_f32 = match tex.aux.as_ref().and_then(|a| a.z.as_ref()) { |
| 256 | Some(z_tex) if z_tex.size == tex.size => Some( |
| 257 | engine |
| 258 | .readback_aux_z_f32(z_tex) |
| 259 | .map_err(|e| format!("GPU Z aux readback failed at frame {frame}: {e}"))?, |
| 260 | ), |
| 261 | _ => None, |
| 262 | }; |
| 263 | let normal_f32 = match tex.aux.as_ref().and_then(|a| a.normal.as_ref()) { |
| 264 | Some(n_tex) if n_tex.size == tex.size => Some( |
| 265 | engine |
| 266 | .readback_aux_rgba_f32(n_tex) |
| 267 | .map_err(|e| format!("GPU Normal aux readback failed at frame {frame}: {e}"))?, |
| 268 | ), |
| 269 | _ => None, |
| 270 | }; |
| 271 | write_exr_rgba_with_aux( |
| 272 | out_path, |
| 273 | tex.size, |
| 274 | &rgba_f32, |
| 275 | z_f32.as_deref(), |
| 276 | normal_f32.as_deref(), |
| 277 | depth, |
| 278 | compression, |
| 279 | )?; |
| 280 | Ok(out_path.to_path_buf()) |
| 281 | } |
| 282 | |
| 283 | #[derive(Default)] |
| 284 | struct RawByteBuffers { |
| 285 | rgba: Vec<u8>, |
| 286 | z: Vec<u8>, |
| 287 | normal: Vec<u8>, |
| 288 | } |
| 289 | |
| 290 | struct ExrEncodeJob { |
| 291 | path: PathBuf, |
| 292 | size: [u32; 2], |
| 293 | rgba_fmt: wgpu::TextureFormat, |
| 294 | normal_fmt: Option<wgpu::TextureFormat>, |
| 295 | has_z: bool, |
| 296 | bufs: RawByteBuffers, |
| 297 | } |
| 298 | |
| 299 | struct PendingExrFrame { |
| 300 | rgba_rb: PendingReadback, |
| 301 | rgba_fmt: wgpu::TextureFormat, |
| 302 | z_rb: Option<PendingReadback>, |
| 303 | normal_rb: Option<(PendingReadback, wgpu::TextureFormat)>, |
| 304 | frame: i64, |
| 305 | idx: usize, |
| 306 | path: PathBuf, |
| 307 | size: [u32; 2], |
| 308 | stats: EvalStats, |
| 309 | } |
| 310 | |
| 311 | fn start_pending_exr_frame( |
| 312 | engine: &Engine, |
| 313 | tex: &crate::cache::CachedTexture, |
| 314 | frame: i64, |
| 315 | idx: usize, |
| 316 | path: PathBuf, |
| 317 | stats: EvalStats, |
| 318 | ) -> Result<PendingExrFrame, String> { |
| 319 | let rgba_bpp = Engine::rgba_f32_bpp(tex.format) |
| 320 | .map_err(|e| format!("GPU RGBA readback setup failed at frame {frame}: {e}"))?; |
| 321 | let rgba_rb = engine |
| 322 | .begin_readback_raw(&tex.texture, tex.size, rgba_bpp) |
| 323 | .map_err(|e| format!("GPU RGBA readback failed at frame {frame}: {e}"))?; |
| 324 | let z_rb = match tex.aux.as_ref().and_then(|a| a.z.as_ref()) { |
| 325 | Some(z_tex) if z_tex.size == tex.size => { |
| 326 | if z_tex.format != wgpu::TextureFormat::R32Float { |
| 327 | return Err(format!( |
| 328 | "expected R32Float for Z aux channel at frame {frame}, got {:?}", |
| 329 | z_tex.format |
| 330 | )); |
| 331 | } |
| 332 | Some( |
| 333 | engine |
| 334 | .begin_readback_raw(&z_tex.texture, z_tex.size, 4) |
| 335 | .map_err(|e| format!("GPU Z aux readback failed at frame {frame}: {e}"))?, |
| 336 | ) |
| 337 | } |
| 338 | _ => None, |
| 339 | }; |
| 340 | let normal_rb = match tex.aux.as_ref().and_then(|a| a.normal.as_ref()) { |
| 341 | Some(n_tex) if n_tex.size == tex.size => { |
| 342 | let n_bpp = Engine::rgba_f32_bpp(n_tex.format) |
| 343 | .map_err(|e| format!("GPU Normal aux format error at frame {frame}: {e}"))?; |
| 344 | let rb = engine |
| 345 | .begin_readback_raw(&n_tex.texture, n_tex.size, n_bpp) |
| 346 | .map_err(|e| format!("GPU Normal aux readback failed at frame {frame}: {e}"))?; |
| 347 | Some((rb, n_tex.format)) |
| 348 | } |
| 349 | _ => None, |
| 350 | }; |
| 351 | Ok(PendingExrFrame { |
| 352 | rgba_rb, |
| 353 | rgba_fmt: tex.format, |
| 354 | z_rb, |
| 355 | normal_rb, |
| 356 | frame, |
| 357 | idx, |
| 358 | path, |
| 359 | size: tex.size, |
| 360 | stats, |
| 361 | }) |
| 362 | } |
| 363 | |
| 364 | fn finish_pending_exr_frame( |
| 365 | engine: &Engine, |
| 366 | pending: PendingExrFrame, |
| 367 | mut bufs: RawByteBuffers, |
| 368 | ) -> Result<ExrEncodeJob, String> { |
| 369 | pending |
| 370 | .rgba_rb |
| 371 | .finish_into(engine, &mut bufs.rgba) |
| 372 | .map_err(|e| format!("GPU RGBA readback failed at frame {}: {e}", pending.frame))?; |
| 373 | let has_z = if let Some(z_rb) = pending.z_rb { |
| 374 | z_rb.finish_into(engine, &mut bufs.z) |
| 375 | .map_err(|e| format!("GPU Z aux readback failed at frame {}: {e}", pending.frame))?; |
| 376 | true |
| 377 | } else { |
| 378 | bufs.z.clear(); |
| 379 | false |
| 380 | }; |
| 381 | let normal_fmt = if let Some((n_rb, n_fmt)) = pending.normal_rb { |
| 382 | n_rb.finish_into(engine, &mut bufs.normal) |
| 383 | .map_err(|e| format!("GPU Normal aux readback failed at frame {}: {e}", pending.frame))?; |
| 384 | Some(n_fmt) |
| 385 | } else { |
| 386 | bufs.normal.clear(); |
| 387 | None |
| 388 | }; |
| 389 | Ok(ExrEncodeJob { |
| 390 | path: pending.path, |
| 391 | size: pending.size, |
| 392 | rgba_fmt: pending.rgba_fmt, |
| 393 | normal_fmt, |
| 394 | has_z, |
| 395 | bufs, |
| 396 | }) |
| 397 | } |
| 398 | |
| 399 | /// Renders and writes a linear HDR OpenEXR sequence for an arbitrary `target` node across |
| 400 | /// `range` (`[start, end]` inclusive) using double-buffered async GPU readback, recycled raw |
| 401 | /// staging buffers, 12-frame media prefetch, and a bounded background EXR encoder pool. |
| 402 | #[allow(clippy::too_many_arguments)] |
| 403 | pub fn export_node_exr_sequence_with_progress( |
| 404 | engine: &mut Engine, |
| 405 | comp: &Comp, |
| 406 | target: NodeId, |
| 407 | range: [i64; 2], |
| 408 | path_for_frame: impl Fn(i64) -> Result<PathBuf, String>, |
| 409 | label: String, |
| 410 | hiq: bool, |
| 411 | proxy_scale: u32, |
| 412 | exr_workers: usize, |
| 413 | depth: ExrDepth, |
| 414 | compression: ExrCompression, |
| 415 | control: Option<&ExportControl>, |
| 416 | mut on_progress: impl FnMut(&ExportProgress), |
| 417 | ) -> Result<ExportSummary, String> { |
| 418 | if control.is_some_and(ExportControl::is_cancelled) { |
| 419 | return Err("Cancelled".to_owned()); |
| 420 | } |
| 421 | if target.0 >= comp.nodes.len() { |
| 422 | return Err(format!("invalid target node id {}", target.0)); |
| 423 | } |
| 424 | let [start, end] = range; |
| 425 | let total_i128 = i128::from(end) - i128::from(start) + 1; |
| 426 | if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { |
| 427 | return Err(format!("invalid export frame range {start}..={end}")); |
| 428 | } |
| 429 | |
| 430 | let prev_hiq = engine.hiq; |
| 431 | let prev_proxy = engine.proxy_scale; |
| 432 | engine.hiq = hiq; |
| 433 | engine.proxy_scale = proxy_scale.max(1); |
| 434 | |
| 435 | let total = total_i128 as usize; |
| 436 | let workers = if exr_workers > 0 { |
| 437 | exr_workers.clamp(1, 24) |
| 438 | } else { |
| 439 | std::thread::available_parallelism() |
| 440 | .map(|n| n.get().clamp(2, 24)) |
| 441 | .unwrap_or(4) |
| 442 | } |
| 443 | .min(total.max(1)); |
| 444 | |
| 445 | let t0 = Instant::now(); |
| 446 | let mut first_path: Option<PathBuf> = None; |
| 447 | let mut last_path: Option<PathBuf> = None; |
| 448 | let mut frames_written: usize = 0; |
| 449 | |
| 450 | let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); |
| 451 | let failed = Arc::new(AtomicBool::new(false)); |
| 452 | let cancelled = Arc::new(AtomicBool::new(false)); |
| 453 | |
| 454 | let eval_result: Result<(), String> = std::thread::scope(|scope| { |
| 455 | let queue_cap = (workers * 2).clamp(16, 48); |
| 456 | let (tx, rx) = mpsc::sync_channel::<ExrEncodeJob>(queue_cap); |
| 457 | let (recycle_tx, recycle_rx) = mpsc::sync_channel::<RawByteBuffers>(queue_cap + workers); |
| 458 | let shared_rx = Arc::new(Mutex::new(rx)); |
| 459 | |
| 460 | let mut handles = Vec::with_capacity(workers); |
| 461 | for _ in 0..workers { |
| 462 | let rx_c = Arc::clone(&shared_rx); |
| 463 | let recycle_c = recycle_tx.clone(); |
| 464 | let err_c = Arc::clone(&first_err); |
| 465 | let fail_c = Arc::clone(&failed); |
| 466 | let cancel_c = Arc::clone(&cancelled); |
| 467 | handles.push(scope.spawn(move || { |
| 468 | let mut rgba_f32 = Vec::new(); |
| 469 | let mut z_f32 = Vec::new(); |
| 470 | let mut normal_f32 = Vec::new(); |
| 471 | let mut staging = Vec::new(); |
| 472 | let mut last_parent: Option<PathBuf> = None; |
| 473 | loop { |
| 474 | let job = { |
| 475 | let Ok(guard) = rx_c.lock() else { break }; |
| 476 | guard.recv() |
| 477 | }; |
| 478 | let Ok(job) = job else { break }; |
| 479 | if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) { |
| 480 | continue; |
| 481 | } |
| 482 | let decode_res = (|| -> Result<(), String> { |
| 483 | Engine::decode_rgba_bytes_into_f32( |
| 484 | job.rgba_fmt, |
| 485 | job.size, |
| 486 | &job.bufs.rgba, |
| 487 | &mut rgba_f32, |
| 488 | ) |
| 489 | .map_err(|e| format!("RGBA float decode failed: {e}"))?; |
| 490 | if job.has_z { |
| 491 | Engine::decode_z_bytes_into_f32(job.size, &job.bufs.z, &mut z_f32) |
| 492 | .map_err(|e| format!("Z aux decode failed: {e}"))?; |
| 493 | } |
| 494 | if let Some(n_fmt) = job.normal_fmt { |
| 495 | Engine::decode_rgba_bytes_into_f32( |
| 496 | n_fmt, |
| 497 | job.size, |
| 498 | &job.bufs.normal, |
| 499 | &mut normal_f32, |
| 500 | ) |
| 501 | .map_err(|e| format!("Normal aux decode failed: {e}"))?; |
| 502 | } |
| 503 | write_exr_rgba_with_aux_buffered( |
| 504 | &job.path, |
| 505 | job.size, |
| 506 | &rgba_f32, |
| 507 | job.has_z.then_some(z_f32.as_slice()), |
| 508 | job.normal_fmt.map(|_| normal_f32.as_slice()), |
| 509 | depth, |
| 510 | compression, |
| 511 | &mut staging, |
| 512 | &mut last_parent, |
| 513 | false, |
| 514 | Some(&cancel_c), |
| 515 | ) |
| 516 | })(); |
| 517 | if let Err(e) = decode_res { |
| 518 | if let Ok(mut g) = err_c.lock() |
| 519 | && g.is_none() |
| 520 | { |
| 521 | *g = Some(e); |
| 522 | } |
| 523 | fail_c.store(true, Ordering::Release); |
| 524 | } |
| 525 | let _ = recycle_c.try_send(job.bufs); |
| 526 | } |
| 527 | })); |
| 528 | } |
| 529 | drop(recycle_tx); |
| 530 | |
| 531 | let mut loop_err: Option<String> = None; |
| 532 | const PREFETCH_LOOKAHEAD: usize = 12; |
| 533 | engine.prewarm_for_depth(comp.depth_full); |
| 534 | let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); |
| 535 | if start < end { |
| 536 | let seed_start = start.saturating_add(1); |
| 537 | let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end); |
| 538 | for (k, f) in (seed_start..=seed_end).enumerate() { |
| 539 | prefetch.enqueue_frame( |
| 540 | comp, |
| 541 | target, |
| 542 | k + 1, |
| 543 | f as f64, |
| 544 | &engine.expr, |
| 545 | engine.use_proxy_clips, |
| 546 | ); |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | let mut flush_pending = |engine: &Engine, pend: PendingExrFrame| -> Result<bool, String> { |
| 551 | let prev_frame = pend.frame; |
| 552 | let prev_idx = pend.idx; |
| 553 | let prev_path = pend.path.clone(); |
| 554 | let prev_stats = pend.stats.clone(); |
| 555 | let bufs = recycle_rx.try_recv().unwrap_or_default(); |
| 556 | let job = finish_pending_exr_frame(engine, pend, bufs)?; |
| 557 | if control.is_some_and(ExportControl::is_cancelled) { |
| 558 | cancelled.store(true, Ordering::Release); |
| 559 | return Ok(false); |
| 560 | } |
| 561 | if first_path.is_none() { |
| 562 | first_path = Some(prev_path.clone()); |
| 563 | } |
| 564 | last_path = Some(prev_path.clone()); |
| 565 | let prog = make_progress( |
| 566 | prev_frame, |
| 567 | prev_idx, |
| 568 | total, |
| 569 | prev_stats, |
| 570 | prev_path, |
| 571 | label.clone(), |
| 572 | t0, |
| 573 | ); |
| 574 | if let Some(ctrl) = control { |
| 575 | ctrl.update_progress(&prog); |
| 576 | } |
| 577 | on_progress(&prog); |
| 578 | if control.is_some_and(ExportControl::is_cancelled) { |
| 579 | cancelled.store(true, Ordering::Release); |
| 580 | return Ok(false); |
| 581 | } |
| 582 | if tx.send(job).is_err() { |
| 583 | return Ok(false); |
| 584 | } |
| 585 | frames_written += 1; |
| 586 | Ok(true) |
| 587 | }; |
| 588 | |
| 589 | let mut pending: Option<PendingExrFrame> = None; |
| 590 | for (idx, frame) in (start..=end).enumerate() { |
| 591 | if failed.load(Ordering::Acquire) { |
| 592 | break; |
| 593 | } |
| 594 | if control.is_some_and(ExportControl::is_cancelled) { |
| 595 | cancelled.store(true, Ordering::Release); |
| 596 | break; |
| 597 | } |
| 598 | prefetch.set_current_seq(idx); |
| 599 | if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) |
| 600 | && ahead_frame <= end |
| 601 | { |
| 602 | prefetch.enqueue_frame( |
| 603 | comp, |
| 604 | target, |
| 605 | idx + PREFETCH_LOOKAHEAD, |
| 606 | ahead_frame as f64, |
| 607 | &engine.expr, |
| 608 | engine.use_proxy_clips, |
| 609 | ); |
| 610 | } |
| 611 | let out_path = match path_for_frame(frame) { |
| 612 | Ok(p) => p, |
| 613 | Err(e) => { |
| 614 | loop_err = Some(e); |
| 615 | break; |
| 616 | } |
| 617 | }; |
| 618 | let (tex, stats) = engine.evaluate(comp, target, frame as f64); |
| 619 | let next_pend = match start_pending_exr_frame(engine, &tex, frame, idx, out_path, stats) { |
| 620 | Ok(p) => p, |
| 621 | Err(e) => { |
| 622 | loop_err = Some(e); |
| 623 | break; |
| 624 | } |
| 625 | }; |
| 626 | if let Some(prev_pend) = pending.replace(next_pend) { |
| 627 | match flush_pending(engine, prev_pend) { |
| 628 | Ok(true) => {} |
| 629 | Ok(false) => break, |
| 630 | Err(e) => { |
| 631 | loop_err = Some(e); |
| 632 | break; |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 | if loop_err.is_none() |
| 638 | && !failed.load(Ordering::Acquire) |
| 639 | && !cancelled.load(Ordering::Acquire) |
| 640 | && let Some(prev_pend) = pending.take() |
| 641 | && let Err(e) = flush_pending(engine, prev_pend) |
| 642 | { |
| 643 | loop_err = Some(e); |
| 644 | } |
| 645 | |
| 646 | drop(prefetch); |
| 647 | drop(tx); |
| 648 | for h in handles { |
| 649 | let _ = h.join(); |
| 650 | } |
| 651 | |
| 652 | if let Some(e) = loop_err { |
| 653 | return Err(e); |
| 654 | } |
| 655 | if let Ok(mut g) = first_err.lock() |
| 656 | && let Some(e) = g.take() |
| 657 | { |
| 658 | return Err(e); |
| 659 | } |
| 660 | if cancelled.load(Ordering::Acquire) { |
| 661 | return Err("Cancelled".to_owned()); |
| 662 | } |
| 663 | Ok(()) |
| 664 | }); |
| 665 | |
| 666 | engine.hiq = prev_hiq; |
| 667 | engine.proxy_scale = prev_proxy; |
| 668 | |
| 669 | eval_result?; |
| 670 | |
| 671 | Ok(ExportSummary { |
| 672 | saver_name: label, |
| 673 | frames_written, |
| 674 | total_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| 675 | first_path, |
| 676 | last_path, |
| 677 | }) |
| 678 | } |
| 679 | |
| 680 | /// Renders and writes a linear HDR OpenEXR sequence driven by a Fusion `Saver` node. |
| 681 | pub fn export_saver_exr_sequence( |
| 682 | engine: &mut Engine, |
| 683 | comp: &Comp, |
| 684 | opts: &ExportOptions, |
| 685 | on_progress: impl FnMut(&ExportProgress), |
| 686 | ) -> Result<ExportSummary, String> { |
| 687 | export_saver_exr_sequence_with_progress(engine, comp, opts, None, on_progress) |
| 688 | } |
| 689 | |
| 690 | /// Renders and writes a linear HDR OpenEXR sequence driven by a Fusion `Saver` node with |
| 691 | /// cooperative cancellation and live progress reporting via `ExportControl`. |
| 692 | pub fn export_saver_exr_sequence_with_progress( |
| 693 | engine: &mut Engine, |
| 694 | comp: &Comp, |
| 695 | opts: &ExportOptions, |
| 696 | control: Option<&ExportControl>, |
| 697 | on_progress: impl FnMut(&ExportProgress), |
| 698 | ) -> Result<ExportSummary, String> { |
| 699 | if control.is_some_and(ExportControl::is_cancelled) { |
| 700 | return Err("Cancelled".to_owned()); |
| 701 | } |
| 702 | let saver = select_saver(comp, opts.saver_name.as_deref())?; |
| 703 | let target: NodeId = saver.upstream.unwrap_or(saver.node_id); |
| 704 | let range = opts.range_override.unwrap_or(saver.range); |
| 705 | let saver_node = comp.node(saver.node_id); |
| 706 | let depth = ExrDepth::from_fusion_code( |
| 707 | comp.eval_number( |
| 708 | saver_node, |
| 709 | "OpenEXRFormat.Depth", |
| 710 | range[0] as f64, |
| 711 | 0.0, |
| 712 | &engine.expr, |
| 713 | ) |
| 714 | .round() as i32, |
| 715 | ); |
| 716 | let compression = ExrCompression::from_fusion_code( |
| 717 | comp.eval_number( |
| 718 | saver_node, |
| 719 | "OpenEXRFormat.Compression", |
| 720 | range[0] as f64, |
| 721 | 3.0, |
| 722 | &engine.expr, |
| 723 | ) |
| 724 | .round() as i32, |
| 725 | ); |
| 726 | let out_dir_override = opts.out_dir_override.as_deref(); |
| 727 | export_node_exr_sequence_with_progress( |
| 728 | engine, |
| 729 | comp, |
| 730 | target, |
| 731 | range, |
| 732 | |frame| resolve_output_path_with_ext(&saver, frame, out_dir_override, "exr"), |
| 733 | saver.name.clone(), |
| 734 | opts.hiq, |
| 735 | opts.proxy_scale, |
| 736 | opts.png_workers, |
| 737 | depth, |
| 738 | compression, |
| 739 | control, |
| 740 | on_progress, |
| 741 | ) |
| 742 | } |