| 1 | //! Lossless RGBA8 PNG encoding and pipelined multi-threaded PNG sequence export. |
| 2 | |
| 3 | use super::{ |
| 4 | ExportControl, ExportOptions, ExportProgress, ExportSummary, ensure_parent_dir, make_progress, |
| 5 | resolve_output_path_with_ext, select_saver, |
| 6 | }; |
| 7 | use crate::cache::EvalStats; |
| 8 | use crate::eval::Engine; |
| 9 | use model::{Comp, NodeId}; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 12 | use std::sync::{Arc, Mutex, mpsc}; |
| 13 | use std::time::Instant; |
| 14 | |
| 15 | /// Encodes an RGBA8 image into `out` as a lossless PNG matching Fusion's default |
| 16 | /// libpng compression (`Compression::Balanced` = zlib level 6 + `Filter::Adaptive`). |
| 17 | pub fn encode_png_rgba8_into(size: [u32; 2], pixels: &[u8], out: &mut Vec<u8>) -> Result<(), String> { |
| 18 | out.clear(); |
| 19 | if out.capacity() == 0 { |
| 20 | out.reserve(pixels.len() / 2); |
| 21 | } |
| 22 | let mut enc = ::png::Encoder::new(&mut *out, size[0], size[1]); |
| 23 | enc.set_color(::png::ColorType::Rgba); |
| 24 | enc.set_depth(::png::BitDepth::Eight); |
| 25 | enc.set_compression(::png::Compression::Balanced); |
| 26 | enc.set_filter(::png::Filter::Adaptive); |
| 27 | let mut png_w = enc |
| 28 | .write_header() |
| 29 | .map_err(|e| format!("failed to write PNG header: {e}"))?; |
| 30 | png_w |
| 31 | .write_image_data(pixels) |
| 32 | .map_err(|e| format!("failed to write PNG data: {e}"))?; |
| 33 | Ok(()) |
| 34 | } |
| 35 | |
| 36 | /// Encodes and writes an RGBA8 PNG using a reusable staging buffer and cached parent directory. |
| 37 | pub fn write_png_fast_buffered( |
| 38 | path: &Path, |
| 39 | size: [u32; 2], |
| 40 | pixels: &[u8], |
| 41 | staging: &mut Vec<u8>, |
| 42 | last_parent: &mut Option<PathBuf>, |
| 43 | ) -> Result<(), String> { |
| 44 | ensure_parent_dir(path, last_parent)?; |
| 45 | encode_png_rgba8_into(size, pixels, staging) |
| 46 | .map_err(|e| format!("{e} ('{}')", path.display()))?; |
| 47 | std::fs::write(path, staging.as_slice()) |
| 48 | .map_err(|e| format!("failed to write '{}': {e}", path.display()))?; |
| 49 | Ok(()) |
| 50 | } |
| 51 | |
| 52 | fn write_png_fast(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), String> { |
| 53 | let mut staging = Vec::with_capacity(pixels.len() / 2); |
| 54 | let mut last_parent = None; |
| 55 | write_png_fast_buffered(path, size, pixels, &mut staging, &mut last_parent) |
| 56 | } |
| 57 | |
| 58 | struct EncodeJob { |
| 59 | path: PathBuf, |
| 60 | size: [u32; 2], |
| 61 | pixels: Vec<u8>, |
| 62 | } |
| 63 | |
| 64 | /// Evaluates `target` at `frame` on GPU and saves a single RGBA8 PNG to `out_path`. |
| 65 | pub fn export_node_frame_png( |
| 66 | engine: &mut Engine, |
| 67 | comp: &Comp, |
| 68 | target: NodeId, |
| 69 | frame: f64, |
| 70 | out_path: &Path, |
| 71 | ) -> Result<PathBuf, String> { |
| 72 | if target.0 >= comp.nodes.len() { |
| 73 | return Err(format!("invalid target node id {}", target.0)); |
| 74 | } |
| 75 | let (tex, _) = engine.evaluate(comp, target, frame); |
| 76 | let pixels = engine |
| 77 | .readback_rgba(&tex) |
| 78 | .map_err(|e| format!("GPU readback failed at frame {frame}: {e}"))?; |
| 79 | write_png_fast(out_path, tex.size, &pixels)?; |
| 80 | Ok(out_path.to_path_buf()) |
| 81 | } |
| 82 | |
| 83 | /// Renders and writes a PNG sequence for an arbitrary `target` node across `range` |
| 84 | /// (`[start, end]` inclusive) using double-buffered async GPU readback, recycled RGBA |
| 85 | /// pixel buffers, 12-frame media prefetch, and a bounded background PNG encoder pool. |
| 86 | #[allow(clippy::too_many_arguments)] |
| 87 | pub fn export_node_png_sequence_with_progress( |
| 88 | engine: &mut Engine, |
| 89 | comp: &Comp, |
| 90 | target: NodeId, |
| 91 | range: [i64; 2], |
| 92 | path_for_frame: impl Fn(i64) -> Result<PathBuf, String>, |
| 93 | label: String, |
| 94 | hiq: bool, |
| 95 | proxy_scale: u32, |
| 96 | png_workers: usize, |
| 97 | control: Option<&ExportControl>, |
| 98 | mut on_progress: impl FnMut(&ExportProgress), |
| 99 | ) -> Result<ExportSummary, String> { |
| 100 | if control.is_some_and(ExportControl::is_cancelled) { |
| 101 | return Err("Cancelled".to_owned()); |
| 102 | } |
| 103 | if target.0 >= comp.nodes.len() { |
| 104 | return Err(format!("invalid target node id {}", target.0)); |
| 105 | } |
| 106 | let [start, end] = range; |
| 107 | let total_i128 = i128::from(end) - i128::from(start) + 1; |
| 108 | if end < start || total_i128 <= 0 || total_i128 > i128::from(u32::MAX) { |
| 109 | return Err(format!("invalid export frame range {start}..={end}")); |
| 110 | } |
| 111 | |
| 112 | let prev_hiq = engine.hiq; |
| 113 | let prev_proxy = engine.proxy_scale; |
| 114 | engine.hiq = hiq; |
| 115 | engine.proxy_scale = proxy_scale.max(1); |
| 116 | |
| 117 | let total = total_i128 as usize; |
| 118 | let workers = if png_workers > 0 { |
| 119 | png_workers.clamp(1, 24) |
| 120 | } else { |
| 121 | std::thread::available_parallelism() |
| 122 | .map(|n| n.get().clamp(2, 24)) |
| 123 | .unwrap_or(4) |
| 124 | } |
| 125 | .min(total.max(1)); |
| 126 | |
| 127 | let t0 = Instant::now(); |
| 128 | let mut first_path: Option<PathBuf> = None; |
| 129 | let mut last_path: Option<PathBuf> = None; |
| 130 | let mut frames_written: usize = 0; |
| 131 | |
| 132 | let first_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); |
| 133 | let failed = Arc::new(AtomicBool::new(false)); |
| 134 | let cancelled = Arc::new(AtomicBool::new(false)); |
| 135 | |
| 136 | let eval_result: Result<(), String> = std::thread::scope(|scope| { |
| 137 | let queue_cap = (workers * 2).clamp(16, 48); |
| 138 | let (tx, rx) = mpsc::sync_channel::<EncodeJob>(queue_cap); |
| 139 | let (recycle_tx, recycle_rx) = mpsc::sync_channel::<Vec<u8>>(queue_cap + workers); |
| 140 | let shared_rx = Arc::new(Mutex::new(rx)); |
| 141 | |
| 142 | let mut handles = Vec::with_capacity(workers); |
| 143 | for _ in 0..workers { |
| 144 | let rx_c = Arc::clone(&shared_rx); |
| 145 | let recycle_c = recycle_tx.clone(); |
| 146 | let err_c = Arc::clone(&first_err); |
| 147 | let fail_c = Arc::clone(&failed); |
| 148 | let cancel_c = Arc::clone(&cancelled); |
| 149 | handles.push(scope.spawn(move || { |
| 150 | let mut staging = Vec::new(); |
| 151 | let mut last_parent: Option<PathBuf> = None; |
| 152 | loop { |
| 153 | let job = { |
| 154 | let Ok(guard) = rx_c.lock() else { break }; |
| 155 | guard.recv() |
| 156 | }; |
| 157 | let Ok(job) = job else { break }; |
| 158 | if fail_c.load(Ordering::Acquire) || cancel_c.load(Ordering::Acquire) { |
| 159 | continue; |
| 160 | } |
| 161 | if let Err(e) = write_png_fast_buffered( |
| 162 | &job.path, |
| 163 | job.size, |
| 164 | &job.pixels, |
| 165 | &mut staging, |
| 166 | &mut last_parent, |
| 167 | ) { |
| 168 | if let Ok(mut g) = err_c.lock() { |
| 169 | if g.is_none() { |
| 170 | *g = Some(e); |
| 171 | } |
| 172 | } |
| 173 | fail_c.store(true, Ordering::Release); |
| 174 | } |
| 175 | let _ = recycle_c.try_send(job.pixels); |
| 176 | } |
| 177 | })); |
| 178 | } |
| 179 | drop(recycle_tx); |
| 180 | |
| 181 | let mut loop_err: Option<String> = None; |
| 182 | const PREFETCH_LOOKAHEAD: usize = 12; |
| 183 | engine.prewarm_for_depth(comp.depth_full); |
| 184 | let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); |
| 185 | if start < end { |
| 186 | let seed_start = start.saturating_add(1); |
| 187 | let seed_end = start.saturating_add(PREFETCH_LOOKAHEAD as i64 - 1).min(end); |
| 188 | for (k, f) in (seed_start..=seed_end).enumerate() { |
| 189 | prefetch.enqueue_frame( |
| 190 | comp, |
| 191 | target, |
| 192 | k + 1, |
| 193 | f as f64, |
| 194 | &engine.expr, |
| 195 | engine.use_proxy_clips, |
| 196 | ); |
| 197 | } |
| 198 | } |
| 199 | // Double-buffered async GPU readback: frame N+1 evaluates/submits on GPU while |
| 200 | // frame N finishes its copy/map and hands off to the background PNG writer pool. |
| 201 | let mut pending: Option<( |
| 202 | crate::eval::PendingReadback, |
| 203 | i64, |
| 204 | usize, |
| 205 | PathBuf, |
| 206 | [u32; 2], |
| 207 | EvalStats, |
| 208 | )> = None; |
| 209 | for (idx, frame) in (start..=end).enumerate() { |
| 210 | if failed.load(Ordering::Acquire) { |
| 211 | break; |
| 212 | } |
| 213 | if control.is_some_and(ExportControl::is_cancelled) { |
| 214 | cancelled.store(true, Ordering::Release); |
| 215 | break; |
| 216 | } |
| 217 | prefetch.set_current_seq(idx); |
| 218 | if let Some(ahead_frame) = frame.checked_add(PREFETCH_LOOKAHEAD as i64) { |
| 219 | if ahead_frame <= end { |
| 220 | prefetch.enqueue_frame( |
| 221 | comp, |
| 222 | target, |
| 223 | idx + PREFETCH_LOOKAHEAD, |
| 224 | ahead_frame as f64, |
| 225 | &engine.expr, |
| 226 | engine.use_proxy_clips, |
| 227 | ); |
| 228 | } |
| 229 | } |
| 230 | let out_path = match path_for_frame(frame) { |
| 231 | Ok(p) => p, |
| 232 | Err(e) => { |
| 233 | loop_err = Some(e); |
| 234 | break; |
| 235 | } |
| 236 | }; |
| 237 | |
| 238 | let (tex, stats) = engine.evaluate(comp, target, frame as f64); |
| 239 | let next_rb = match engine.begin_readback_rgba(&tex) { |
| 240 | Ok(rb) => rb, |
| 241 | Err(e) => { |
| 242 | loop_err = Some(format!("GPU readback failed at frame {frame}: {e}")); |
| 243 | break; |
| 244 | } |
| 245 | }; |
| 246 | if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_stats)) = |
| 247 | pending.replace((next_rb, frame, idx, out_path, tex.size, stats)) |
| 248 | { |
| 249 | let mut pixels = recycle_rx.try_recv().unwrap_or_default(); |
| 250 | if let Err(e) = prev_rb.finish_into(engine, &mut pixels) { |
| 251 | loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); |
| 252 | break; |
| 253 | } |
| 254 | if control.is_some_and(ExportControl::is_cancelled) { |
| 255 | cancelled.store(true, Ordering::Release); |
| 256 | break; |
| 257 | } |
| 258 | if first_path.is_none() { |
| 259 | first_path = Some(prev_path.clone()); |
| 260 | } |
| 261 | last_path = Some(prev_path.clone()); |
| 262 | let prog = make_progress( |
| 263 | prev_frame, |
| 264 | prev_idx, |
| 265 | total, |
| 266 | prev_stats, |
| 267 | prev_path.clone(), |
| 268 | label.clone(), |
| 269 | t0, |
| 270 | ); |
| 271 | if let Some(ctrl) = control { |
| 272 | ctrl.update_progress(&prog); |
| 273 | } |
| 274 | on_progress(&prog); |
| 275 | if tx |
| 276 | .send(EncodeJob { |
| 277 | path: prev_path, |
| 278 | size: prev_size, |
| 279 | pixels, |
| 280 | }) |
| 281 | .is_err() |
| 282 | { |
| 283 | break; |
| 284 | } |
| 285 | frames_written += 1; |
| 286 | } |
| 287 | } |
| 288 | if loop_err.is_none() && !failed.load(Ordering::Acquire) && !cancelled.load(Ordering::Acquire) |
| 289 | { |
| 290 | if let Some((prev_rb, prev_frame, prev_idx, prev_path, prev_size, prev_stats)) = |
| 291 | pending.take() |
| 292 | { |
| 293 | let mut pixels = recycle_rx.try_recv().unwrap_or_default(); |
| 294 | match prev_rb.finish_into(engine, &mut pixels) { |
| 295 | Ok(()) => { |
| 296 | if control.is_some_and(ExportControl::is_cancelled) { |
| 297 | cancelled.store(true, Ordering::Release); |
| 298 | } else { |
| 299 | if first_path.is_none() { |
| 300 | first_path = Some(prev_path.clone()); |
| 301 | } |
| 302 | last_path = Some(prev_path.clone()); |
| 303 | let prog = make_progress( |
| 304 | prev_frame, |
| 305 | prev_idx, |
| 306 | total, |
| 307 | prev_stats, |
| 308 | prev_path.clone(), |
| 309 | label.clone(), |
| 310 | t0, |
| 311 | ); |
| 312 | if let Some(ctrl) = control { |
| 313 | ctrl.update_progress(&prog); |
| 314 | } |
| 315 | on_progress(&prog); |
| 316 | if tx |
| 317 | .send(EncodeJob { |
| 318 | path: prev_path, |
| 319 | size: prev_size, |
| 320 | pixels, |
| 321 | }) |
| 322 | .is_ok() |
| 323 | { |
| 324 | frames_written += 1; |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | Err(e) => { |
| 329 | loop_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | drop(prefetch); |
| 336 | drop(tx); |
| 337 | for h in handles { |
| 338 | let _ = h.join(); |
| 339 | } |
| 340 | |
| 341 | if let Some(e) = loop_err { |
| 342 | return Err(e); |
| 343 | } |
| 344 | if let Ok(mut g) = first_err.lock() { |
| 345 | if let Some(e) = g.take() { |
| 346 | return Err(e); |
| 347 | } |
| 348 | } |
| 349 | if cancelled.load(Ordering::Acquire) { |
| 350 | return Err("Cancelled".to_owned()); |
| 351 | } |
| 352 | Ok(()) |
| 353 | }); |
| 354 | |
| 355 | engine.hiq = prev_hiq; |
| 356 | engine.proxy_scale = prev_proxy; |
| 357 | |
| 358 | eval_result?; |
| 359 | |
| 360 | Ok(ExportSummary { |
| 361 | saver_name: label, |
| 362 | frames_written, |
| 363 | total_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| 364 | first_path, |
| 365 | last_path, |
| 366 | }) |
| 367 | } |
| 368 | |
| 369 | /// Renders and writes a PNG sequence driven by a Fusion `Saver` node. |
| 370 | /// |
| 371 | /// GPU evaluation runs on the caller's thread while PNG compression and disk I/O run |
| 372 | /// concurrently on a bounded pool of background worker threads. |
| 373 | pub fn export_saver_png_sequence( |
| 374 | engine: &mut Engine, |
| 375 | comp: &Comp, |
| 376 | opts: &ExportOptions, |
| 377 | on_progress: impl FnMut(&ExportProgress), |
| 378 | ) -> Result<ExportSummary, String> { |
| 379 | export_saver_png_sequence_with_progress(engine, comp, opts, None, on_progress) |
| 380 | } |
| 381 | |
| 382 | /// Renders and writes an image sequence driven by a Fusion `Saver` node with cooperative |
| 383 | /// cancellation and live progress reporting via `ExportControl`. |
| 384 | /// |
| 385 | /// Automatically dispatches to OpenEXR export when the Saver specifies `OutputFormat == "OpenEXRFormat"` |
| 386 | /// or resolves to a `.exr` output path. |
| 387 | pub fn export_saver_png_sequence_with_progress( |
| 388 | engine: &mut Engine, |
| 389 | comp: &Comp, |
| 390 | opts: &ExportOptions, |
| 391 | control: Option<&ExportControl>, |
| 392 | on_progress: impl FnMut(&ExportProgress), |
| 393 | ) -> Result<ExportSummary, String> { |
| 394 | super::export_saver_sequence_with_progress(engine, comp, opts, control, on_progress) |
| 395 | } |
| 396 | |
| 397 | pub(super) fn export_saver_png_only_sequence_with_progress( |
| 398 | engine: &mut Engine, |
| 399 | comp: &Comp, |
| 400 | opts: &ExportOptions, |
| 401 | control: Option<&ExportControl>, |
| 402 | on_progress: impl FnMut(&ExportProgress), |
| 403 | ) -> Result<ExportSummary, String> { |
| 404 | if control.is_some_and(ExportControl::is_cancelled) { |
| 405 | return Err("Cancelled".to_owned()); |
| 406 | } |
| 407 | let saver = select_saver(comp, opts.saver_name.as_deref())?; |
| 408 | let target: NodeId = saver.upstream.unwrap_or(saver.node_id); |
| 409 | let range = opts.range_override.unwrap_or(saver.range); |
| 410 | let out_dir_override = opts.out_dir_override.as_deref(); |
| 411 | export_node_png_sequence_with_progress( |
| 412 | engine, |
| 413 | comp, |
| 414 | target, |
| 415 | range, |
| 416 | |frame| resolve_output_path_with_ext(&saver, frame, out_dir_override, "png"), |
| 417 | saver.name.clone(), |
| 418 | opts.hiq, |
| 419 | opts.proxy_scale, |
| 420 | opts.png_workers, |
| 421 | control, |
| 422 | on_progress, |
| 423 | ) |
| 424 | } |