| 1 | use super::video::{ |
| 2 | VideoEncoder, VideoToolboxSupport, export_node_video_ffmpeg_with_encoder, fit_frame_rgba, |
| 3 | h264_scale_filter_and_dims, parse_videotoolbox_encoders, push_video_encoder_args, |
| 4 | select_video_encoder, vt_quality_from_crf, |
| 5 | }; |
| 6 | use super::*; |
| 7 | use crate::eval::Engine; |
| 8 | use model::Comp; |
| 9 | use std::path::Path; |
| 10 | use std::process::Command; |
| 11 | use std::time::Instant; |
| 12 | |
| 13 | #[test] |
| 14 | fn exports_saver_png_sequence_animated() { |
| 15 | let tmp_dir = std::env::temp_dir().join(format!( |
| 16 | "fission-saver-export-test-{}", |
| 17 | std::process::id() |
| 18 | )); |
| 19 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 20 | let saver_path = tmp_dir.join("nested").join("shot_0000.png"); |
| 21 | let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); |
| 22 | |
| 23 | let comp_src = format!( |
| 24 | r#"Composition {{ |
| 25 | 	CurrentTime = 10, |
| 26 | 	RenderRange = {{ 10, 12 }}, |
| 27 | 	GlobalRange = {{ 0, 100 }}, |
| 28 | 	Tools = ordered() {{ |
| 29 | 		BG = Background {{ |
| 30 | 			Inputs = {{ |
| 31 | 				Width = Input {{ Value = 64, }}, |
| 32 | 				Height = Input {{ Value = 32, }}, |
| 33 | 				TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, |
| 34 | 				TopLeftGreen = Input {{ Value = 0.25, }}, |
| 35 | 				TopLeftBlue = Input {{ Value = 0.5, }}, |
| 36 | 				TopLeftAlpha = Input {{ Value = 1, }}, |
| 37 | 			}}, |
| 38 | 		}}, |
| 39 | 		BGRed = BezierSpline {{ |
| 40 | 			KeyFrames = {{ |
| 41 | 				[10] = {{ 0.0, Flags = {{ Linear = true }} }}, |
| 42 | 				[12] = {{ 1.0, Flags = {{ Linear = true }} }}, |
| 43 | 			}}, |
| 44 | 		}}, |
| 45 | 		Saver1 = Saver {{ |
| 46 | 			Inputs = {{ |
| 47 | 				Clip = Input {{ |
| 48 | 					Value = Clip {{ |
| 49 | 						Filename = "{saver_path_escaped}", |
| 50 | 						FormatID = "PNGFormat", |
| 51 | 						Saving = true, |
| 52 | 					}}, |
| 53 | 				}}, |
| 54 | 				Input = Input {{ |
| 55 | 					SourceOp = "BG", |
| 56 | 					Source = "Output", |
| 57 | 				}}, |
| 58 | 			}}, |
| 59 | 		}}, |
| 60 | 	}}, |
| 61 | 	Prefs = {{ |
| 62 | 		Comp = {{ |
| 63 | 			FrameFormat = {{ |
| 64 | 				Width = 64, |
| 65 | 				Height = 32, |
| 66 | 				Rate = 30, |
| 67 | 				DepthFull = 1, |
| 68 | 			}}, |
| 69 | 		}}, |
| 70 | 	}}, |
| 71 | }}"# |
| 72 | ); |
| 73 | |
| 74 | let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp"); |
| 75 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 76 | |
| 77 | let mut seen_frames = Vec::new(); |
| 78 | let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |p| { |
| 79 | seen_frames.push(p.frame); |
| 80 | }) |
| 81 | .expect("export png sequence"); |
| 82 | |
| 83 | assert_eq!(summary.saver_name, "Saver1"); |
| 84 | assert_eq!(summary.frames_written, 3); |
| 85 | assert_eq!(seen_frames, vec![10, 11, 12]); |
| 86 | |
| 87 | let expected_reds = [0u8, 128u8, 255u8]; |
| 88 | for (frame, exp_r) in [10i64, 11, 12].into_iter().zip(expected_reds) { |
| 89 | let p = tmp_dir.join("nested").join(format!("shot_{frame:04}.png")); |
| 90 | assert!(p.exists(), "missing exported frame {}", p.display()); |
| 91 | let img = image::open(&p).expect("decode exported PNG").to_rgba8(); |
| 92 | assert_eq!(img.dimensions(), (64, 32)); |
| 93 | let px = img.get_pixel(32, 16); |
| 94 | assert!( |
| 95 | (px[0] as i32 - exp_r as i32).abs() <= 2, |
| 96 | "frame {frame}: expected R~{exp_r}, got {:?}", |
| 97 | px.0 |
| 98 | ); |
| 99 | assert!((px[1] as i32 - 64).abs() <= 2); |
| 100 | assert!((px[2] as i32 - 128).abs() <= 2); |
| 101 | assert_eq!(px[3], 255); |
| 102 | } |
| 103 | |
| 104 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 105 | } |
| 106 | |
| 107 | #[test] |
| 108 | fn exports_node_png_sequence_directly_with_eval_stats() { |
| 109 | let tmp_dir = std::env::temp_dir().join(format!( |
| 110 | "fission-node-png-seq-test-{}", |
| 111 | std::process::id() |
| 112 | )); |
| 113 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 114 | |
| 115 | let comp_src = r#"Composition { |
| 116 | 	CurrentTime = 5, |
| 117 | 	RenderRange = { 5, 7 }, |
| 118 | 	GlobalRange = { 0, 100 }, |
| 119 | 	Tools = ordered() { |
| 120 | 		BG = Background { |
| 121 | 			Inputs = { |
| 122 | 				Width = Input { Value = 64, }, |
| 123 | 				Height = Input { Value = 32, }, |
| 124 | 				TopLeftRed = Input { Value = 0.5, }, |
| 125 | 				TopLeftGreen = Input { Value = 0.25, }, |
| 126 | 				TopLeftBlue = Input { Value = 0.75, }, |
| 127 | 				TopLeftAlpha = Input { Value = 1, }, |
| 128 | 			}, |
| 129 | 		}, |
| 130 | 	}, |
| 131 | 	Prefs = { Comp = { FrameFormat = { Width = 64, Height = 32, Rate = 24, DepthFull = 1 } } }, |
| 132 | }"#; |
| 133 | |
| 134 | let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic comp"); |
| 135 | let target = comp.find_node("BG").expect("find BG"); |
| 136 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 137 | |
| 138 | let mut seen = Vec::new(); |
| 139 | let summary = export_node_png_sequence_with_progress( |
| 140 | &mut engine, |
| 141 | &comp, |
| 142 | target, |
| 143 | [5, 7], |
| 144 | |f| Ok(tmp_dir.join(format!("{f:04}.png"))), |
| 145 | "BG".to_owned(), |
| 146 | true, |
| 147 | 1, |
| 148 | 0, |
| 149 | None, |
| 150 | |p| { |
| 151 | assert!(p.cached_vram_mb >= 0.0); |
| 152 | assert!(p.unsupported_nodes.is_empty()); |
| 153 | seen.push(p.frame); |
| 154 | }, |
| 155 | ) |
| 156 | .expect("export node png sequence"); |
| 157 | |
| 158 | assert_eq!(summary.saver_name, "BG"); |
| 159 | assert_eq!(summary.frames_written, 3); |
| 160 | assert_eq!(seen, vec![5, 6, 7]); |
| 161 | assert_eq!(summary.first_path, Some(tmp_dir.join("0005.png"))); |
| 162 | assert_eq!(summary.last_path, Some(tmp_dir.join("0007.png"))); |
| 163 | for f in 5..=7 { |
| 164 | let p = tmp_dir.join(format!("{f:04}.png")); |
| 165 | assert!(p.exists(), "missing {}", p.display()); |
| 166 | } |
| 167 | |
| 168 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 169 | } |
| 170 | |
| 171 | fn write_test_wav(path: &Path, sample_rate: u32, duration_secs: f64) { |
| 172 | let num_channels: u16 = 2; |
| 173 | let bits_per_sample: u16 = 16; |
| 174 | let num_samples = (sample_rate as f64 * duration_secs) as u32; |
| 175 | let byte_rate = sample_rate * u32::from(num_channels) * u32::from(bits_per_sample) / 8; |
| 176 | let block_align = num_channels * bits_per_sample / 8; |
| 177 | let data_bytes = num_samples * u32::from(block_align); |
| 178 | let riff_chunk_size = 36 + data_bytes; |
| 179 | |
| 180 | let mut buf = Vec::with_capacity((44 + data_bytes) as usize); |
| 181 | buf.extend_from_slice(b"RIFF"); |
| 182 | buf.extend_from_slice(&riff_chunk_size.to_le_bytes()); |
| 183 | buf.extend_from_slice(b"WAVE"); |
| 184 | buf.extend_from_slice(b"fmt "); |
| 185 | buf.extend_from_slice(&16u32.to_le_bytes()); |
| 186 | buf.extend_from_slice(&1u16.to_le_bytes()); // PCM |
| 187 | buf.extend_from_slice(&num_channels.to_le_bytes()); |
| 188 | buf.extend_from_slice(&sample_rate.to_le_bytes()); |
| 189 | buf.extend_from_slice(&byte_rate.to_le_bytes()); |
| 190 | buf.extend_from_slice(&block_align.to_le_bytes()); |
| 191 | buf.extend_from_slice(&bits_per_sample.to_le_bytes()); |
| 192 | buf.extend_from_slice(b"data"); |
| 193 | buf.extend_from_slice(&data_bytes.to_le_bytes()); |
| 194 | for i in 0..num_samples { |
| 195 | let t = i as f64 / sample_rate as f64; |
| 196 | let sample = ((t * 440.0 * std::f64::consts::TAU).sin() * 12000.0) as i16; |
| 197 | buf.extend_from_slice(&sample.to_le_bytes()); |
| 198 | buf.extend_from_slice(&sample.to_le_bytes()); |
| 199 | } |
| 200 | std::fs::write(path, buf).expect("write synthetic wav"); |
| 201 | } |
| 202 | |
| 203 | #[test] |
| 204 | fn exports_snippet_mp4_with_synced_audio() { |
| 205 | let tmp_dir = std::env::temp_dir().join(format!( |
| 206 | "fission-video-export-test-{}", |
| 207 | std::process::id() |
| 208 | )); |
| 209 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 210 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 211 | |
| 212 | let wav_path = tmp_dir.join("tone.wav"); |
| 213 | write_test_wav(&wav_path, 44100, 2.0); |
| 214 | let wav_escaped = wav_path.to_string_lossy().replace('\\', "\\\\"); |
| 215 | |
| 216 | let comp_src = format!( |
| 217 | r#"Composition {{ |
| 218 | 	CurrentTime = 10, |
| 219 | 	RenderRange = {{ 10, 21 }}, |
| 220 | 	GlobalRange = {{ 0, 100 }}, |
| 221 | 	AudioFilename = "{wav_escaped}", |
| 222 | 	AudioOffset = 10, |
| 223 | 	Tools = ordered() {{ |
| 224 | 		BG = Background {{ |
| 225 | 			Inputs = {{ |
| 226 | 				Width = Input {{ Value = 128, }}, |
| 227 | 				Height = Input {{ Value = 72, }}, |
| 228 | 				TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, |
| 229 | 				TopLeftGreen = Input {{ Value = 0.25, }}, |
| 230 | 				TopLeftBlue = Input {{ Value = 0.75, }}, |
| 231 | 				TopLeftAlpha = Input {{ Value = 1, }}, |
| 232 | 			}}, |
| 233 | 		}}, |
| 234 | 		BGRed = BezierSpline {{ |
| 235 | 			KeyFrames = {{ |
| 236 | 				[10] = {{ 0.0, Flags = {{ Linear = true }} }}, |
| 237 | 				[21] = {{ 1.0, Flags = {{ Linear = true }} }}, |
| 238 | 			}}, |
| 239 | 		}}, |
| 240 | 	}}, |
| 241 | 	Prefs = {{ |
| 242 | 		Comp = {{ |
| 243 | 			FrameFormat = {{ |
| 244 | 				Width = 128, |
| 245 | 				Height = 72, |
| 246 | 				Rate = 30, |
| 247 | 				DepthFull = 1, |
| 248 | 			}}, |
| 249 | 		}}, |
| 250 | 	}}, |
| 251 | }}"# |
| 252 | ); |
| 253 | |
| 254 | let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic audio comp"); |
| 255 | let target = comp.find_node("BG").expect("find BG node"); |
| 256 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 257 | |
| 258 | let mp4_path = tmp_dir.join("snippet.mp4"); |
| 259 | let mut seen_frames = Vec::new(); |
| 260 | let summary = export_node_video_ffmpeg( |
| 261 | &mut engine, |
| 262 | &comp, |
| 263 | &VideoExportOptions { |
| 264 | target, |
| 265 | out_path: mp4_path.clone(), |
| 266 | range: [10, 21], |
| 267 | codec: VideoCodec::H264Share, |
| 268 | crf: 26, |
| 269 | max_height: None, |
| 270 | include_audio: true, |
| 271 | hiq: true, |
| 272 | proxy_scale: 1, |
| 273 | }, |
| 274 | |p| seen_frames.push(p.frame), |
| 275 | ) |
| 276 | .expect("export snippet mp4"); |
| 277 | |
| 278 | assert_eq!(summary.frames_written, 12); |
| 279 | assert_eq!(summary.width, 128); |
| 280 | assert_eq!(summary.height, 72); |
| 281 | assert!(summary.has_audio); |
| 282 | assert!(summary.file_bytes > 0); |
| 283 | assert_eq!(seen_frames.len(), 12); |
| 284 | assert!(mp4_path.exists()); |
| 285 | |
| 286 | // Verify streams and exact video frame count via ffprobe |
| 287 | let probe = Command::new("ffprobe") |
| 288 | .args([ |
| 289 | "-v", |
| 290 | "error", |
| 291 | "-count_frames", |
| 292 | "-show_entries", |
| 293 | "stream=codec_type,codec_name,nb_read_frames", |
| 294 | "-of", |
| 295 | "csv=p=0", |
| 296 | ]) |
| 297 | .arg(&mp4_path) |
| 298 | .output() |
| 299 | .expect("run ffprobe"); |
| 300 | assert!( |
| 301 | probe.status.success(), |
| 302 | "ffprobe failed: {}", |
| 303 | String::from_utf8_lossy(&probe.stderr) |
| 304 | ); |
| 305 | let stdout = String::from_utf8_lossy(&probe.stdout); |
| 306 | let mut saw_h264_12 = false; |
| 307 | let mut saw_aac = false; |
| 308 | for line in stdout.lines() { |
| 309 | let cols: Vec<&str> = line.split(',').map(str::trim).collect(); |
| 310 | if cols.len() >= 3 && cols[1] == "video" && cols[0] == "h264" && cols[2] == "12" { |
| 311 | saw_h264_12 = true; |
| 312 | } |
| 313 | if cols.len() >= 2 && cols[1] == "audio" && cols[0] == "aac" { |
| 314 | saw_aac = true; |
| 315 | } |
| 316 | } |
| 317 | assert!( |
| 318 | saw_h264_12, |
| 319 | "expected h264 video stream with 12 frames, ffprobe output:\n{stdout}" |
| 320 | ); |
| 321 | assert!( |
| 322 | saw_aac, |
| 323 | "expected aac audio stream, ffprobe output:\n{stdout}" |
| 324 | ); |
| 325 | |
| 326 | // Also verify negative audio_start_secs (range starts before AudioOffset = 10) |
| 327 | let pre_mp4_path = tmp_dir.join("snippet_pre_offset.mp4"); |
| 328 | let pre_summary = export_node_video_ffmpeg( |
| 329 | &mut engine, |
| 330 | &comp, |
| 331 | &VideoExportOptions { |
| 332 | target, |
| 333 | out_path: pre_mp4_path.clone(), |
| 334 | range: [6, 17], |
| 335 | codec: VideoCodec::H264Share, |
| 336 | crf: 26, |
| 337 | max_height: Some(64), |
| 338 | include_audio: true, |
| 339 | hiq: true, |
| 340 | proxy_scale: 1, |
| 341 | }, |
| 342 | |_| {}, |
| 343 | ) |
| 344 | .expect("export snippet mp4 with negative audio_start_secs"); |
| 345 | assert_eq!(pre_summary.frames_written, 12); |
| 346 | assert!(pre_summary.has_audio); |
| 347 | assert!(pre_summary.file_bytes > 0); |
| 348 | assert!(pre_mp4_path.exists()); |
| 349 | |
| 350 | // Verify single-frame PNG helper |
| 351 | let png_path = tmp_dir.join("frame_10.png"); |
| 352 | let saved = export_node_frame_png(&mut engine, &comp, target, 10.0, &png_path) |
| 353 | .expect("export single frame png"); |
| 354 | assert_eq!(saved, png_path); |
| 355 | let img = image::open(&png_path) |
| 356 | .expect("decode exported frame png") |
| 357 | .to_rgba8(); |
| 358 | assert_eq!(img.dimensions(), (128, 72)); |
| 359 | |
| 360 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 361 | } |
| 362 | |
| 363 | #[test] |
| 364 | fn saver_export_reports_progress_and_stops_on_cancel() { |
| 365 | let tmp_dir = std::env::temp_dir().join(format!( |
| 366 | "fission-saver-cancel-test-{}", |
| 367 | std::process::id() |
| 368 | )); |
| 369 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 370 | let saver_path = tmp_dir.join("shot_0000.png"); |
| 371 | let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); |
| 372 | |
| 373 | let comp_src = format!( |
| 374 | r#"Composition {{ |
| 375 | 	CurrentTime = 10, |
| 376 | 	RenderRange = {{ 10, 15 }}, |
| 377 | 	GlobalRange = {{ 0, 100 }}, |
| 378 | 	Tools = ordered() {{ |
| 379 | 		BG = Background {{ |
| 380 | 			Inputs = {{ |
| 381 | 				Width = Input {{ Value = 64, }}, |
| 382 | 				Height = Input {{ Value = 32, }}, |
| 383 | 				TopLeftRed = Input {{ Value = 0.7, }}, |
| 384 | 				TopLeftAlpha = Input {{ Value = 1, }}, |
| 385 | 			}}, |
| 386 | 		}}, |
| 387 | 		Saver1 = Saver {{ |
| 388 | 			Inputs = {{ |
| 389 | 				Clip = Input {{ |
| 390 | 					Value = Clip {{ |
| 391 | 						Filename = "{saver_path_escaped}", |
| 392 | 						FormatID = "PNGFormat", |
| 393 | 						Saving = true, |
| 394 | 					}}, |
| 395 | 				}}, |
| 396 | 				Input = Input {{ |
| 397 | 					SourceOp = "BG", |
| 398 | 					Source = "Output", |
| 399 | 				}}, |
| 400 | 			}}, |
| 401 | 		}}, |
| 402 | 	}}, |
| 403 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 1 }} }} }}, |
| 404 | }}"# |
| 405 | ); |
| 406 | |
| 407 | let comp = Comp::from_fusion_str(&comp_src).expect("parse synthetic Saver comp"); |
| 408 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 409 | let control = ExportControl::new(); |
| 410 | let ctrl_cb = control.clone(); |
| 411 | let mut reported = Vec::new(); |
| 412 | |
| 413 | let err = export_saver_png_sequence_with_progress( |
| 414 | &mut engine, |
| 415 | &comp, |
| 416 | &ExportOptions::default(), |
| 417 | Some(&control), |
| 418 | |p| { |
| 419 | reported.push(( |
| 420 | p.current_frame, |
| 421 | p.completed_frames, |
| 422 | p.total_frames, |
| 423 | p.label.clone(), |
| 424 | )); |
| 425 | if p.completed_frames >= 2 { |
| 426 | ctrl_cb.cancel(); |
| 427 | } |
| 428 | }, |
| 429 | ) |
| 430 | .expect_err("saver export should cancel early"); |
| 431 | |
| 432 | assert_eq!(err, "Cancelled"); |
| 433 | assert_eq!(reported.len(), 2); |
| 434 | assert_eq!(reported[0].0, 10); |
| 435 | assert_eq!(reported[0].1, 1); |
| 436 | assert_eq!(reported[0].2, 6); |
| 437 | assert_eq!(reported[0].3, "Saver1"); |
| 438 | assert_eq!(reported[1].0, 11); |
| 439 | assert_eq!(reported[1].1, 2); |
| 440 | |
| 441 | let snap = control.snapshot_progress(); |
| 442 | assert_eq!(snap.completed_frames, 2); |
| 443 | assert_eq!(snap.total_frames, 6); |
| 444 | assert!(snap.elapsed_secs >= 0.0); |
| 445 | assert!(!tmp_dir.join("shot_0015.png").exists()); |
| 446 | |
| 447 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 448 | } |
| 449 | |
| 450 | #[test] |
| 451 | fn video_export_reports_progress_and_cleans_up_on_cancel() { |
| 452 | let tmp_dir = std::env::temp_dir().join(format!( |
| 453 | "fission-video-cancel-test-{}", |
| 454 | std::process::id() |
| 455 | )); |
| 456 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 457 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 458 | |
| 459 | let comp_src = r#"Composition { |
| 460 | 	CurrentTime = 1, |
| 461 | 	RenderRange = { 1, 12 }, |
| 462 | 	GlobalRange = { 0, 100 }, |
| 463 | 	Tools = ordered() { |
| 464 | 		BG = Background { |
| 465 | 			Inputs = { |
| 466 | 				Width = Input { Value = 128, }, |
| 467 | 				Height = Input { Value = 72, }, |
| 468 | 				TopLeftRed = Input { Value = 0.2, }, |
| 469 | 				TopLeftGreen = Input { Value = 0.6, }, |
| 470 | 				TopLeftBlue = Input { Value = 0.9, }, |
| 471 | 				TopLeftAlpha = Input { Value = 1, }, |
| 472 | 			}, |
| 473 | 		}, |
| 474 | 	}, |
| 475 | 	Prefs = { Comp = { FrameFormat = { Width = 128, Height = 72, Rate = 24, DepthFull = 1 } } }, |
| 476 | }"#; |
| 477 | |
| 478 | let comp = Comp::from_fusion_str(comp_src).expect("parse synthetic video comp"); |
| 479 | let target = comp.find_node("BG").expect("find BG node"); |
| 480 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 481 | let out_mp4 = tmp_dir.join("cancelled.mp4"); |
| 482 | let control = ExportControl::new(); |
| 483 | let ctrl_cb = control.clone(); |
| 484 | let mut seen = Vec::new(); |
| 485 | |
| 486 | let err = export_node_video_ffmpeg_with_progress( |
| 487 | &mut engine, |
| 488 | &comp, |
| 489 | &VideoExportOptions { |
| 490 | target, |
| 491 | out_path: out_mp4.clone(), |
| 492 | range: [1, 12], |
| 493 | codec: VideoCodec::H264Share, |
| 494 | crf: 26, |
| 495 | max_height: None, |
| 496 | include_audio: false, |
| 497 | hiq: true, |
| 498 | proxy_scale: 1, |
| 499 | }, |
| 500 | Some(&control), |
| 501 | |p| { |
| 502 | seen.push(( |
| 503 | p.current_frame, |
| 504 | p.completed_frames, |
| 505 | p.total_frames, |
| 506 | p.label.clone(), |
| 507 | )); |
| 508 | if p.completed_frames >= 3 { |
| 509 | ctrl_cb.cancel(); |
| 510 | } |
| 511 | }, |
| 512 | ) |
| 513 | .expect_err("video export should cancel early"); |
| 514 | |
| 515 | assert_eq!(err, "Cancelled"); |
| 516 | assert_eq!(seen.len(), 3); |
| 517 | assert_eq!(seen[0].0, 1); |
| 518 | assert_eq!(seen[0].1, 1); |
| 519 | assert_eq!(seen[0].2, 12); |
| 520 | assert_eq!(seen[0].3, "BG"); |
| 521 | assert_eq!(seen[2].0, 3); |
| 522 | assert_eq!(seen[2].1, 3); |
| 523 | |
| 524 | let snap = control.snapshot_progress(); |
| 525 | assert_eq!(snap.completed_frames, 3); |
| 526 | assert_eq!(snap.total_frames, 12); |
| 527 | assert!( |
| 528 | !out_mp4.exists(), |
| 529 | "partial mp4 should be removed after cancellation" |
| 530 | ); |
| 531 | |
| 532 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 533 | } |
| 534 | |
| 535 | #[test] |
| 536 | fn video_export_handles_short_audio_past_eof_odd_dims_and_1x1_dummy() { |
| 537 | let tmp_dir = std::env::temp_dir().join(format!( |
| 538 | "fission-video-edge-cases-{}", |
| 539 | std::process::id() |
| 540 | )); |
| 541 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 542 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 543 | |
| 544 | let short_wav = tmp_dir.join("short.wav"); |
| 545 | write_test_wav(&short_wav, 44100, 0.15); |
| 546 | let wav_escaped = short_wav.to_string_lossy().replace('\\', "\\\\"); |
| 547 | |
| 548 | // 1. Short audio (0.15s) with 1.0s (24 frames @ 24fps) odd-dimension (127x71) video. |
| 549 | let comp_src = format!( |
| 550 | r#"Composition {{ |
| 551 | 	CurrentTime = 0, |
| 552 | 	RenderRange = {{ 0, 23 }}, |
| 553 | 	GlobalRange = {{ 0, 23 }}, |
| 554 | 	AudioFilename = "{wav_escaped}", |
| 555 | 	AudioOffset = 0, |
| 556 | 	Tools = ordered() {{ |
| 557 | 		BG = Background {{ |
| 558 | 			Inputs = {{ |
| 559 | 				Width = Input {{ Value = 127, }}, |
| 560 | 				Height = Input {{ Value = 71, }}, |
| 561 | 				TopLeftRed = Input {{ Value = 0.4, }}, |
| 562 | 				TopLeftGreen = Input {{ Value = 0.5, }}, |
| 563 | 				TopLeftBlue = Input {{ Value = 0.6, }}, |
| 564 | 				TopLeftAlpha = Input {{ Value = 1, }}, |
| 565 | 			}}, |
| 566 | 		}}, |
| 567 | 	}}, |
| 568 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 127, Height = 71, Rate = 24, DepthFull = 1 }} }} }}, |
| 569 | }}"# |
| 570 | ); |
| 571 | let comp = Comp::from_fusion_str(&comp_src).expect("parse odd+short-audio comp"); |
| 572 | let target = comp.find_node("BG").unwrap(); |
| 573 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 574 | |
| 575 | let short_mp4 = tmp_dir.join("short_audio_odd.mp4"); |
| 576 | let summary = export_node_video_ffmpeg( |
| 577 | &mut engine, |
| 578 | &comp, |
| 579 | &VideoExportOptions { |
| 580 | target, |
| 581 | out_path: short_mp4.clone(), |
| 582 | range: [0, 23], |
| 583 | codec: VideoCodec::H264Share, |
| 584 | crf: 26, |
| 585 | max_height: None, |
| 586 | include_audio: true, |
| 587 | hiq: true, |
| 588 | proxy_scale: 1, |
| 589 | }, |
| 590 | |_| {}, |
| 591 | ) |
| 592 | .expect("export with short audio and odd dimensions should succeed without Broken pipe"); |
| 593 | assert_eq!(summary.frames_written, 24); |
| 594 | assert_eq!(summary.width, 126); |
| 595 | assert_eq!(summary.height, 70); |
| 596 | assert!(summary.has_audio); |
| 597 | |
| 598 | // 2. Audio start past EOF -> skips audio cleanly (`has_audio == false`). |
| 599 | let mut past_eof_comp = comp.clone(); |
| 600 | past_eof_comp.audio_offset = -100.0; // start=0 -> audio_start_secs = +4.17s > 0.15s |
| 601 | let past_mp4 = tmp_dir.join("past_eof.mp4"); |
| 602 | let past_summary = export_node_video_ffmpeg( |
| 603 | &mut engine, |
| 604 | &past_eof_comp, |
| 605 | &VideoExportOptions { |
| 606 | target, |
| 607 | out_path: past_mp4.clone(), |
| 608 | range: [0, 5], |
| 609 | codec: VideoCodec::H264Share, |
| 610 | crf: 26, |
| 611 | max_height: None, |
| 612 | include_audio: true, |
| 613 | hiq: true, |
| 614 | proxy_scale: 1, |
| 615 | }, |
| 616 | |_| {}, |
| 617 | ) |
| 618 | .expect("export with audio past EOF should skip audio and succeed"); |
| 619 | assert_eq!(past_summary.frames_written, 6); |
| 620 | assert!(!past_summary.has_audio); |
| 621 | |
| 622 | // 3. First frame 1x1 dummy (Loader with missing frame 0, MissingFrames = 0) -> falls back to comp canvas. |
| 623 | let seq1 = tmp_dir.join("seq_0001.png"); |
| 624 | image::RgbaImage::from_pixel(64, 36, image::Rgba([20, 200, 40, 255])) |
| 625 | .save(&seq1) |
| 626 | .unwrap(); |
| 627 | let seq0 = tmp_dir.join("seq_0000.png"); // intentionally absent |
| 628 | let seq0_esc = seq0.to_string_lossy().replace('\\', "\\\\"); |
| 629 | let dummy_comp_src = format!( |
| 630 | r#"Composition {{ |
| 631 | 	CurrentTime = 0, |
| 632 | 	RenderRange = {{ 0, 1 }}, |
| 633 | 	GlobalRange = {{ 0, 1 }}, |
| 634 | 	Tools = ordered() {{ |
| 635 | 		LD = Loader {{ |
| 636 | 			Clips = {{ |
| 637 | 				Clip {{ |
| 638 | 					ID = "Clip1", |
| 639 | 					Filename = "{seq0_esc}", |
| 640 | 					FormatID = "PNGFormat", |
| 641 | 					StartFrame = 0, |
| 642 | 					Length = 2, |
| 643 | 					GlobalStart = 0, |
| 644 | 					GlobalEnd = 1, |
| 645 | 				}}, |
| 646 | 			}}, |
| 647 | 		}}, |
| 648 | 	}}, |
| 649 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 36, Rate = 24, DepthFull = 1 }} }} }}, |
| 650 | }}"# |
| 651 | ); |
| 652 | let dummy_comp = Comp::from_fusion_str(&dummy_comp_src).expect("parse dummy loader comp"); |
| 653 | let ld = dummy_comp.find_node("LD").unwrap(); |
| 654 | engine.bust_all_caches(); |
| 655 | let dummy_mp4 = tmp_dir.join("dummy_first.mp4"); |
| 656 | let dummy_summary = export_node_video_ffmpeg( |
| 657 | &mut engine, |
| 658 | &dummy_comp, |
| 659 | &VideoExportOptions { |
| 660 | target: ld, |
| 661 | out_path: dummy_mp4.clone(), |
| 662 | range: [0, 1], |
| 663 | codec: VideoCodec::H264Share, |
| 664 | crf: 26, |
| 665 | max_height: None, |
| 666 | include_audio: false, |
| 667 | hiq: true, |
| 668 | proxy_scale: 1, |
| 669 | }, |
| 670 | |_| {}, |
| 671 | ) |
| 672 | .expect("export with 1x1 first frame should fall back to comp dimensions"); |
| 673 | assert_eq!(dummy_summary.frames_written, 2); |
| 674 | assert_eq!(dummy_summary.width, 64); |
| 675 | assert_eq!(dummy_summary.height, 36); |
| 676 | |
| 677 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 678 | } |
| 679 | |
| 680 | #[test] |
| 681 | fn video_export_cancel_preserves_existing_output_and_removes_temp_file() { |
| 682 | let tmp_dir = std::env::temp_dir().join(format!( |
| 683 | "fission-video-atomic-cancel-{}", |
| 684 | std::process::id() |
| 685 | )); |
| 686 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 687 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 688 | |
| 689 | let out_mp4 = tmp_dir.join("existing.mp4"); |
| 690 | let sentinel_bytes = b"ORIGINAL_VALUABLE_EXPORT_BYTES_DO_NOT_TRUNCATE"; |
| 691 | std::fs::write(&out_mp4, sentinel_bytes).expect("write sentinel existing file"); |
| 692 | |
| 693 | let comp_src = r#"Composition { |
| 694 | 	CurrentTime = 0, |
| 695 | 	RenderRange = { 0, 9 }, |
| 696 | 	GlobalRange = { 0, 9 }, |
| 697 | 	Tools = ordered() { |
| 698 | 		BG = Background { |
| 699 | 			Inputs = { |
| 700 | 				Width = Input { Value = 64, }, |
| 701 | 				Height = Input { Value = 64, }, |
| 702 | 				TopLeftRed = Input { Value = 0.8, }, |
| 703 | 				TopLeftAlpha = Input { Value = 1, }, |
| 704 | 			}, |
| 705 | 		}, |
| 706 | 	}, |
| 707 | 	Prefs = { Comp = { FrameFormat = { Width = 64, Height = 64, Rate = 24, DepthFull = 1 } } }, |
| 708 | }"#; |
| 709 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); |
| 710 | let target = comp.find_node("BG").expect("find BG"); |
| 711 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 712 | let control = ExportControl::new(); |
| 713 | let ctrl_cb = control.clone(); |
| 714 | |
| 715 | let err = export_node_video_ffmpeg_with_progress( |
| 716 | &mut engine, |
| 717 | &comp, |
| 718 | &VideoExportOptions { |
| 719 | target, |
| 720 | out_path: out_mp4.clone(), |
| 721 | range: [0, 9], |
| 722 | codec: VideoCodec::H264Share, |
| 723 | crf: 26, |
| 724 | max_height: None, |
| 725 | include_audio: false, |
| 726 | hiq: true, |
| 727 | proxy_scale: 1, |
| 728 | }, |
| 729 | Some(&control), |
| 730 | |p| { |
| 731 | if p.completed_frames >= 2 { |
| 732 | ctrl_cb.cancel(); |
| 733 | } |
| 734 | }, |
| 735 | ) |
| 736 | .expect_err("cancelled export should return Err"); |
| 737 | assert_eq!(err, "Cancelled"); |
| 738 | |
| 739 | let after_bytes = std::fs::read(&out_mp4).expect("existing output must still exist"); |
| 740 | assert_eq!( |
| 741 | after_bytes.as_slice(), |
| 742 | sentinel_bytes, |
| 743 | "existing file must stay untouched" |
| 744 | ); |
| 745 | |
| 746 | let entries: Vec<_> = std::fs::read_dir(&tmp_dir) |
| 747 | .expect("read tmp_dir") |
| 748 | .filter_map(|e| e.ok()) |
| 749 | .map(|e| e.file_name().to_string_lossy().into_owned()) |
| 750 | .collect(); |
| 751 | assert_eq!( |
| 752 | entries, |
| 753 | vec!["existing.mp4".to_owned()], |
| 754 | "no temp files should remain" |
| 755 | ); |
| 756 | |
| 757 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 758 | } |
| 759 | |
| 760 | #[test] |
| 761 | fn pipelined_png_export_is_pixel_exact_and_propagates_write_errors() { |
| 762 | let tmp_dir = std::env::temp_dir().join(format!( |
| 763 | "fission-png-pipeline-exact-{}", |
| 764 | std::process::id() |
| 765 | )); |
| 766 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 767 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 768 | |
| 769 | let saver_path = tmp_dir.join("out").join("frame_0000.png"); |
| 770 | let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); |
| 771 | let comp_src = format!( |
| 772 | r#"Composition {{ |
| 773 | 	CurrentTime = 0, |
| 774 | 	RenderRange = {{ 0, 5 }}, |
| 775 | 	GlobalRange = {{ 0, 5 }}, |
| 776 | 	Tools = ordered() {{ |
| 777 | 		BG = Background {{ |
| 778 | 			Inputs = {{ |
| 779 | 				Width = Input {{ Value = 96, }}, |
| 780 | 				Height = Input {{ Value = 48, }}, |
| 781 | 				TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, |
| 782 | 				TopLeftGreen = Input {{ Value = 0.5, }}, |
| 783 | 				TopLeftBlue = Input {{ Value = 0.25, }}, |
| 784 | 				TopLeftAlpha = Input {{ Value = 1.0, }}, |
| 785 | 			}}, |
| 786 | 		}}, |
| 787 | 		BGRed = BezierSpline {{ |
| 788 | 			KeyFrames = {{ |
| 789 | 				[0] = {{ 0.1, Flags = {{ Linear = true }} }}, |
| 790 | 				[5] = {{ 0.9, Flags = {{ Linear = true }} }}, |
| 791 | 			}}, |
| 792 | 		}}, |
| 793 | 		Saver1 = Saver {{ |
| 794 | 			Inputs = {{ |
| 795 | 				Clip = Input {{ |
| 796 | 					Value = Clip {{ |
| 797 | 						Filename = "{saver_path_escaped}", |
| 798 | 						FormatID = "PNGFormat", |
| 799 | 						Saving = true, |
| 800 | 					}}, |
| 801 | 				}}, |
| 802 | 				Input = Input {{ SourceOp = "BG", Source = "Output", }}, |
| 803 | 			}}, |
| 804 | 		}}, |
| 805 | 	}}, |
| 806 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 96, Height = 48, Rate = 24, DepthFull = 1 }} }} }}, |
| 807 | }}"# |
| 808 | ); |
| 809 | |
| 810 | let comp = Comp::from_fusion_str(&comp_src).expect("parse comp"); |
| 811 | let target = comp.find_node("BG").unwrap(); |
| 812 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 813 | |
| 814 | let summary = export_saver_png_sequence(&mut engine, &comp, &ExportOptions::default(), |_| {}) |
| 815 | .expect("export png sequence"); |
| 816 | assert_eq!(summary.frames_written, 6); |
| 817 | |
| 818 | // Verify fast-compressed PNGs decode byte-identically to direct GPU readback. |
| 819 | for f in 0..=5 { |
| 820 | let (tex, _) = engine.evaluate(&comp, target, f as f64); |
| 821 | let expected = engine.readback_rgba(&tex).expect("readback"); |
| 822 | let png_path = tmp_dir.join("out").join(format!("frame_{f:04}.png")); |
| 823 | let decoded = image::open(&png_path).expect("decode png").to_rgba8(); |
| 824 | assert_eq!(decoded.dimensions(), (tex.size[0], tex.size[1])); |
| 825 | assert_eq!( |
| 826 | decoded.into_raw(), |
| 827 | expected, |
| 828 | "fast PNG encode must be 100% lossless at frame {f}" |
| 829 | ); |
| 830 | } |
| 831 | |
| 832 | // Verify worker write error propagates cleanly: point out_dir_override inside a regular file. |
| 833 | let blocking_file = tmp_dir.join("not_a_dir"); |
| 834 | std::fs::write(&blocking_file, b"file").expect("write blocking file"); |
| 835 | let err = export_saver_png_sequence( |
| 836 | &mut engine, |
| 837 | &comp, |
| 838 | &ExportOptions { |
| 839 | out_dir_override: Some(blocking_file), |
| 840 | ..ExportOptions::default() |
| 841 | }, |
| 842 | |_| {}, |
| 843 | ) |
| 844 | .expect_err("writing into a regular file path must return Err"); |
| 845 | assert!(!err.is_empty()); |
| 846 | |
| 847 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 848 | } |
| 849 | |
| 850 | #[test] |
| 851 | fn videotoolbox_probe_selection_and_fallback() { |
| 852 | let sample_both = "\ |
| 853 | Encoders: |
| 854 | V..... = Video |
| 855 | ------ |
| 856 | V....D libx264 libx264 H.264 / AVC |
| 857 | V....D h264_videotoolbox VideoToolbox H.264 Encoder (codec h264) |
| 858 | VFS... prores_ks Apple ProRes (iCodec Pro) (codec prores) |
| 859 | V....D prores_videotoolbox VideoToolbox ProRes Encoder (codec prores) |
| 860 | A....D aac AAC (Advanced Audio Coding) |
| 861 | "; |
| 862 | let vt_both = parse_videotoolbox_encoders(sample_both); |
| 863 | assert_eq!( |
| 864 | vt_both, |
| 865 | VideoToolboxSupport { |
| 866 | h264: true, |
| 867 | prores: true |
| 868 | } |
| 869 | ); |
| 870 | |
| 871 | let sample_h264_only = " V....D h264_videotoolbox VideoToolbox H.264 Encoder\n"; |
| 872 | assert_eq!( |
| 873 | parse_videotoolbox_encoders(sample_h264_only), |
| 874 | VideoToolboxSupport { |
| 875 | h264: true, |
| 876 | prores: false |
| 877 | } |
| 878 | ); |
| 879 | assert_eq!( |
| 880 | parse_videotoolbox_encoders(" V....D libx264 H.264\n"), |
| 881 | VideoToolboxSupport::default() |
| 882 | ); |
| 883 | |
| 884 | // Hardware selection when supported and allowed |
| 885 | assert_eq!( |
| 886 | select_video_encoder(VideoCodec::H264Share, vt_both, true), |
| 887 | VideoEncoder::H264VideoToolbox |
| 888 | ); |
| 889 | assert_eq!( |
| 890 | select_video_encoder(VideoCodec::ProRes422, vt_both, true), |
| 891 | VideoEncoder::ProResVideoToolbox422 |
| 892 | ); |
| 893 | assert_eq!( |
| 894 | select_video_encoder(VideoCodec::ProRes4444, vt_both, true), |
| 895 | VideoEncoder::ProResVideoToolbox4444 |
| 896 | ); |
| 897 | |
| 898 | // Fallback when VideoToolbox is unavailable or disabled after failure |
| 899 | assert_eq!( |
| 900 | select_video_encoder(VideoCodec::H264Share, vt_both, false), |
| 901 | VideoEncoder::Libx264 |
| 902 | ); |
| 903 | assert_eq!( |
| 904 | select_video_encoder(VideoCodec::ProRes422, vt_both, false), |
| 905 | VideoEncoder::ProResKs422 |
| 906 | ); |
| 907 | assert_eq!( |
| 908 | select_video_encoder(VideoCodec::ProRes4444, vt_both, false), |
| 909 | VideoEncoder::ProResKs4444 |
| 910 | ); |
| 911 | assert_eq!( |
| 912 | select_video_encoder(VideoCodec::H264Share, VideoToolboxSupport::default(), true), |
| 913 | VideoEncoder::Libx264 |
| 914 | ); |
| 915 | |
| 916 | assert_eq!(vt_quality_from_crf(0), 95); |
| 917 | assert_eq!(vt_quality_from_crf(26), 52); |
| 918 | assert_eq!(vt_quality_from_crf(51), 15); |
| 919 | |
| 920 | let mut args = Vec::new(); |
| 921 | push_video_encoder_args( |
| 922 | &mut args, |
| 923 | VideoEncoder::H264VideoToolbox, |
| 924 | 26, |
| 925 | Some("scale=trunc(iw/2)*2:trunc(ih/2)*2"), |
| 926 | ); |
| 927 | assert!(args.windows(2).any(|w| w == ["-c:v", "h264_videotoolbox"])); |
| 928 | assert!(args.windows(2).any(|w| w == ["-q:v", "52"])); |
| 929 | assert!(args.windows(2).any(|w| w == ["-tag:v", "avc1"])); |
| 930 | assert!(args.windows(2).any(|w| w == ["-pix_fmt", "yuv420p"])); |
| 931 | |
| 932 | args.clear(); |
| 933 | push_video_encoder_args( |
| 934 | &mut args, |
| 935 | VideoEncoder::Libx264, |
| 936 | 26, |
| 937 | Some("scale=trunc(iw/2)*2:trunc(ih/2)*2"), |
| 938 | ); |
| 939 | assert!(args.windows(2).any(|w| w == ["-c:v", "libx264"])); |
| 940 | assert!(args.windows(2).any(|w| w == ["-crf", "26"])); |
| 941 | |
| 942 | args.clear(); |
| 943 | push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox422, 26, None); |
| 944 | assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"])); |
| 945 | assert!(args.windows(2).any(|w| w == ["-profile:v", "2"])); |
| 946 | assert!(args.windows(2).any(|w| w == ["-pix_fmt", "p210le"])); |
| 947 | |
| 948 | args.clear(); |
| 949 | push_video_encoder_args(&mut args, VideoEncoder::ProResVideoToolbox4444, 26, None); |
| 950 | assert!(args.windows(2).any(|w| w == ["-c:v", "prores_videotoolbox"])); |
| 951 | assert!(args.windows(2).any(|w| w == ["-profile:v", "4"])); |
| 952 | assert!(args.windows(2).any(|w| w == ["-pix_fmt", "ayuv64le"])); |
| 953 | } |
| 954 | |
| 955 | #[test] |
| 956 | fn fit_frame_rgba_zero_copy_fast_path_and_resize() { |
| 957 | let pixels = vec![128u8; 8 * 4 * 4]; |
| 958 | let orig_ptr = pixels.as_ptr(); |
| 959 | let moved = fit_frame_rgba(pixels, [8, 4], [8, 4], 0).expect("matching size fast path"); |
| 960 | assert_eq!( |
| 961 | moved.as_ptr(), |
| 962 | orig_ptr, |
| 963 | "matching size must move Vec without copying" |
| 964 | ); |
| 965 | |
| 966 | let resized = fit_frame_rgba(moved, [8, 4], [4, 2], 1).expect("resize path"); |
| 967 | assert_eq!(resized.len(), 4 * 2 * 4); |
| 968 | |
| 969 | let err = fit_frame_rgba(vec![0u8; 10], [8, 4], [8, 4], 2) |
| 970 | .expect_err("mismatched RGBA byte length must fail"); |
| 971 | assert!(err.contains("invalid RGBA buffer size")); |
| 972 | } |
| 973 | |
| 974 | #[test] |
| 975 | fn prores_4444_preserves_alpha_channel() { |
| 976 | let tmp_dir = std::env::temp_dir().join(format!( |
| 977 | "fission-prores4444-alpha-{}", |
| 978 | std::process::id() |
| 979 | )); |
| 980 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 981 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 982 | |
| 983 | let comp_src = r#"Composition { |
| 984 | 	CurrentTime = 0, |
| 985 | 	RenderRange = { 0, 1 }, |
| 986 | 	GlobalRange = { 0, 1 }, |
| 987 | 	Tools = ordered() { |
| 988 | 		BG = Background { |
| 989 | 			Inputs = { |
| 990 | 				Width = Input { Value = 64, }, |
| 991 | 				Height = Input { Value = 36, }, |
| 992 | 				TopLeftRed = Input { Value = 0.8, }, |
| 993 | 				TopLeftGreen = Input { Value = 0.4, }, |
| 994 | 				TopLeftBlue = Input { Value = 0.2, }, |
| 995 | 				TopLeftAlpha = Input { SourceOp = "BGAlpha", Source = "Value", }, |
| 996 | 			}, |
| 997 | 		}, |
| 998 | 		BGAlpha = BezierSpline { |
| 999 | 			KeyFrames = { |
| 1000 | 				[0] = { 0.25, Flags = { Linear = true } }, |
| 1001 | 				[1] = { 0.75, Flags = { Linear = true } }, |
| 1002 | 			}, |
| 1003 | 		}, |
| 1004 | 	}, |
| 1005 | 	Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, |
| 1006 | }"#; |
| 1007 | let comp = Comp::from_fusion_str(comp_src).expect("parse alpha ProRes comp"); |
| 1008 | let target = comp.find_node("BG").expect("find BG"); |
| 1009 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 1010 | |
| 1011 | let out_mov = tmp_dir.join("alpha_4444.mov"); |
| 1012 | let summary = export_node_video_ffmpeg( |
| 1013 | &mut engine, |
| 1014 | &comp, |
| 1015 | &VideoExportOptions { |
| 1016 | target, |
| 1017 | out_path: out_mov.clone(), |
| 1018 | range: [0, 1], |
| 1019 | codec: VideoCodec::ProRes4444, |
| 1020 | crf: 26, |
| 1021 | max_height: None, |
| 1022 | include_audio: false, |
| 1023 | hiq: true, |
| 1024 | proxy_scale: 1, |
| 1025 | }, |
| 1026 | |_| {}, |
| 1027 | ) |
| 1028 | .expect("export ProRes 4444"); |
| 1029 | assert_eq!(summary.frames_written, 2); |
| 1030 | assert_eq!(summary.width, 64); |
| 1031 | assert_eq!(summary.height, 36); |
| 1032 | |
| 1033 | let probe = Command::new("ffprobe") |
| 1034 | .args([ |
| 1035 | "-v", |
| 1036 | "error", |
| 1037 | "-show_entries", |
| 1038 | "stream=codec_name,profile,pix_fmt", |
| 1039 | "-of", |
| 1040 | "csv=p=0", |
| 1041 | ]) |
| 1042 | .arg(&out_mov) |
| 1043 | .output() |
| 1044 | .expect("run ffprobe"); |
| 1045 | assert!(probe.status.success()); |
| 1046 | let probe_out = String::from_utf8_lossy(&probe.stdout); |
| 1047 | assert!( |
| 1048 | probe_out.contains("prores") && probe_out.contains("4444") && probe_out.contains("yuva"), |
| 1049 | "expected ProRes 4444 with alpha pixel format, got: {probe_out}" |
| 1050 | ); |
| 1051 | |
| 1052 | let dec = Command::new("ffmpeg") |
| 1053 | .args(["-v", "error", "-i"]) |
| 1054 | .arg(&out_mov) |
| 1055 | .args(["-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1"]) |
| 1056 | .output() |
| 1057 | .expect("decode ProRes 4444 to rgba"); |
| 1058 | assert!(dec.status.success()); |
| 1059 | let frame_bytes = 64 * 36 * 4; |
| 1060 | assert_eq!(dec.stdout.len(), frame_bytes * 2); |
| 1061 | |
| 1062 | let a0 = dec.stdout[3]; |
| 1063 | let a1 = dec.stdout[frame_bytes + 3]; |
| 1064 | assert!( |
| 1065 | (i32::from(a0) - 64).abs() <= 2, |
| 1066 | "frame 0 alpha should be ~64 (0.25), got {a0}" |
| 1067 | ); |
| 1068 | assert!( |
| 1069 | (i32::from(a1) - 191).abs() <= 2, |
| 1070 | "frame 1 alpha should be ~191 (0.75), got {a1}" |
| 1071 | ); |
| 1072 | |
| 1073 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1074 | } |
| 1075 | |
| 1076 | #[test] |
| 1077 | fn prores_422_and_software_fallback_encoders_produce_valid_streams() { |
| 1078 | let tmp_dir = std::env::temp_dir().join(format!( |
| 1079 | "fission-prores422-fallback-{}", |
| 1080 | std::process::id() |
| 1081 | )); |
| 1082 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1083 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 1084 | |
| 1085 | let comp_src = r#"Composition { |
| 1086 | 	CurrentTime = 0, |
| 1087 | 	RenderRange = { 0, 2 }, |
| 1088 | 	GlobalRange = { 0, 2 }, |
| 1089 | 	Tools = ordered() { |
| 1090 | 		BG = Background { |
| 1091 | 			Inputs = { |
| 1092 | 				Width = Input { Value = 64, }, |
| 1093 | 				Height = Input { Value = 36, }, |
| 1094 | 				TopLeftRed = Input { Value = 0.2, }, |
| 1095 | 				TopLeftGreen = Input { Value = 0.7, }, |
| 1096 | 				TopLeftBlue = Input { Value = 0.3, }, |
| 1097 | 				TopLeftAlpha = Input { Value = 1.0, }, |
| 1098 | 			}, |
| 1099 | 		}, |
| 1100 | 	}, |
| 1101 | 	Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, |
| 1102 | }"#; |
| 1103 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); |
| 1104 | let target = comp.find_node("BG").expect("find BG"); |
| 1105 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 1106 | |
| 1107 | let prores422_mov = tmp_dir.join("prores422.mov"); |
| 1108 | let summary_422 = export_node_video_ffmpeg( |
| 1109 | &mut engine, |
| 1110 | &comp, |
| 1111 | &VideoExportOptions { |
| 1112 | target, |
| 1113 | out_path: prores422_mov.clone(), |
| 1114 | range: [0, 2], |
| 1115 | codec: VideoCodec::ProRes422, |
| 1116 | crf: 26, |
| 1117 | max_height: None, |
| 1118 | include_audio: false, |
| 1119 | hiq: true, |
| 1120 | proxy_scale: 1, |
| 1121 | }, |
| 1122 | |_| {}, |
| 1123 | ) |
| 1124 | .expect("export ProRes 422"); |
| 1125 | assert_eq!(summary_422.frames_written, 3); |
| 1126 | |
| 1127 | let probe_422 = Command::new("ffprobe") |
| 1128 | .args([ |
| 1129 | "-v", |
| 1130 | "error", |
| 1131 | "-count_frames", |
| 1132 | "-show_entries", |
| 1133 | "stream=codec_name,profile,nb_read_frames", |
| 1134 | "-of", |
| 1135 | "csv=p=0", |
| 1136 | ]) |
| 1137 | .arg(&prores422_mov) |
| 1138 | .output() |
| 1139 | .expect("ffprobe prores 422"); |
| 1140 | assert!(probe_422.status.success()); |
| 1141 | let out_422 = String::from_utf8_lossy(&probe_422.stdout); |
| 1142 | assert!( |
| 1143 | out_422.contains("prores") && out_422.contains("Standard") && out_422.contains(",3"), |
| 1144 | "expected ProRes 422 Standard with 3 frames, got: {out_422}" |
| 1145 | ); |
| 1146 | |
| 1147 | // Directly verify software fallback encoders (Libx264 and ProResKs422) |
| 1148 | let sw_mp4 = tmp_dir.join("sw_libx264.mp4"); |
| 1149 | let mut noop = |_| {}; |
| 1150 | let sw_summary = export_node_video_ffmpeg_with_encoder( |
| 1151 | &mut engine, |
| 1152 | &comp, |
| 1153 | &VideoExportOptions { |
| 1154 | target, |
| 1155 | out_path: sw_mp4.clone(), |
| 1156 | range: [0, 2], |
| 1157 | codec: VideoCodec::H264Share, |
| 1158 | crf: 26, |
| 1159 | max_height: None, |
| 1160 | include_audio: false, |
| 1161 | hiq: true, |
| 1162 | proxy_scale: 1, |
| 1163 | }, |
| 1164 | None, |
| 1165 | &mut noop, |
| 1166 | VideoEncoder::Libx264, |
| 1167 | Instant::now(), |
| 1168 | ) |
| 1169 | .expect("software libx264 fallback export"); |
| 1170 | assert_eq!(sw_summary.frames_written, 3); |
| 1171 | assert!(sw_mp4.exists()); |
| 1172 | |
| 1173 | let sw_mov = tmp_dir.join("sw_prores_ks.mov"); |
| 1174 | let sw_prores = export_node_video_ffmpeg_with_encoder( |
| 1175 | &mut engine, |
| 1176 | &comp, |
| 1177 | &VideoExportOptions { |
| 1178 | target, |
| 1179 | out_path: sw_mov.clone(), |
| 1180 | range: [0, 2], |
| 1181 | codec: VideoCodec::ProRes422, |
| 1182 | crf: 26, |
| 1183 | max_height: None, |
| 1184 | include_audio: false, |
| 1185 | hiq: true, |
| 1186 | proxy_scale: 1, |
| 1187 | }, |
| 1188 | None, |
| 1189 | &mut noop, |
| 1190 | VideoEncoder::ProResKs422, |
| 1191 | Instant::now(), |
| 1192 | ) |
| 1193 | .expect("software prores_ks fallback export"); |
| 1194 | assert_eq!(sw_prores.frames_written, 3); |
| 1195 | assert!(sw_mov.exists()); |
| 1196 | |
| 1197 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1198 | } |
| 1199 | |
| 1200 | #[test] |
| 1201 | fn h264_max_height_out_width_matches_ffmpeg_scale_neg2_rounding() { |
| 1202 | // 101x100 with max_height >= 100: scale=-2 rounds 101.0/2 = 50.5 -> 51 * 2 = 102 |
| 1203 | let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(100)); |
| 1204 | assert_eq!((w, h), (102, 100)); |
| 1205 | let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(200)); |
| 1206 | assert_eq!((w, h), (102, 100)); |
| 1207 | let (_, w, h) = h264_scale_filter_and_dims(101, 100, Some(50)); |
| 1208 | assert_eq!((w, h), (50, 50)); |
| 1209 | |
| 1210 | // 1000x750 downscaled: 1000*700/750 = 933.33 -> nearest even 934; 1000*400/750 = 533.33 -> 534; 1000*500/750 = 666.67 -> 666 |
| 1211 | let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(700)); |
| 1212 | assert_eq!((w, h), (934, 700)); |
| 1213 | let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(400)); |
| 1214 | assert_eq!((w, h), (534, 400)); |
| 1215 | let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(500)); |
| 1216 | assert_eq!((w, h), (666, 500)); |
| 1217 | let (_, w, h) = h264_scale_filter_and_dims(1000, 750, Some(750)); |
| 1218 | assert_eq!((w, h), (1000, 750)); |
| 1219 | |
| 1220 | // Without max_height, trunc(iw/2)*2:trunc(ih/2)*2 truncates odd dimensions downward |
| 1221 | let (_, w, h) = h264_scale_filter_and_dims(101, 100, None); |
| 1222 | assert_eq!((w, h), (100, 100)); |
| 1223 | } |
| 1224 | |
| 1225 | #[test] |
| 1226 | fn video_export_cancel_on_final_frame_progress_cancels_cleanly() { |
| 1227 | let tmp_dir = std::env::temp_dir().join(format!( |
| 1228 | "fission-video-cancel-final-{}", |
| 1229 | std::process::id() |
| 1230 | )); |
| 1231 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1232 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 1233 | |
| 1234 | let comp_src = r#"Composition { |
| 1235 | 	CurrentTime = 0, |
| 1236 | 	RenderRange = { 0, 2 }, |
| 1237 | 	GlobalRange = { 0, 2 }, |
| 1238 | 	Tools = ordered() { |
| 1239 | 		BG = Background { |
| 1240 | 			Inputs = { |
| 1241 | 				Width = Input { Value = 64, }, |
| 1242 | 				Height = Input { Value = 36, }, |
| 1243 | 				TopLeftRed = Input { Value = 0.5, }, |
| 1244 | 				TopLeftAlpha = Input { Value = 1, }, |
| 1245 | 			}, |
| 1246 | 		}, |
| 1247 | 	}, |
| 1248 | 	Prefs = { Comp = { FrameFormat = { Width = 64, Height = 36, Rate = 24, DepthFull = 1 } } }, |
| 1249 | }"#; |
| 1250 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); |
| 1251 | let target = comp.find_node("BG").expect("find BG"); |
| 1252 | let mut engine = Engine::new_headless().expect("headless wgpu engine"); |
| 1253 | let out_mp4 = tmp_dir.join("final_cancel.mp4"); |
| 1254 | let control = ExportControl::new(); |
| 1255 | let ctrl_cb = control.clone(); |
| 1256 | |
| 1257 | let err = export_node_video_ffmpeg_with_progress( |
| 1258 | &mut engine, |
| 1259 | &comp, |
| 1260 | &VideoExportOptions { |
| 1261 | target, |
| 1262 | out_path: out_mp4.clone(), |
| 1263 | range: [0, 2], |
| 1264 | codec: VideoCodec::H264Share, |
| 1265 | crf: 26, |
| 1266 | max_height: None, |
| 1267 | include_audio: false, |
| 1268 | hiq: true, |
| 1269 | proxy_scale: 1, |
| 1270 | }, |
| 1271 | Some(&control), |
| 1272 | |p| { |
| 1273 | if p.completed_frames == p.total_frames { |
| 1274 | ctrl_cb.cancel(); |
| 1275 | } |
| 1276 | }, |
| 1277 | ) |
| 1278 | .expect_err("cancelling on final frame callback must return Cancelled"); |
| 1279 | assert_eq!(err, "Cancelled"); |
| 1280 | assert!( |
| 1281 | !out_mp4.exists(), |
| 1282 | "cancelled export must not publish output file" |
| 1283 | ); |
| 1284 | |
| 1285 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1286 | } |
| 1287 | |
| 1288 | #[test] |
| 1289 | fn readback_rgba_f32_preserves_hdr_and_strips_row_padding() { |
| 1290 | let Ok(engine) = Engine::new_headless() else { |
| 1291 | return; |
| 1292 | }; |
| 1293 | // Unaligned width 19 forces row padding on Rgba8Unorm (76->256), Rgba16Float (152->256), and Rgba32Float (304->512). |
| 1294 | let [w, h] = [19u32, 11u32]; |
| 1295 | let px_count = (w * h) as usize; |
| 1296 | |
| 1297 | let upload_and_check = |format: wgpu::TextureFormat, bytes: &[u8], expected: &[f32]| { |
| 1298 | let texture = engine.device().create_texture(&wgpu::TextureDescriptor { |
| 1299 | label: Some("test-readback-f32"), |
| 1300 | size: wgpu::Extent3d { |
| 1301 | width: w, |
| 1302 | height: h, |
| 1303 | depth_or_array_layers: 1, |
| 1304 | }, |
| 1305 | mip_level_count: 1, |
| 1306 | sample_count: 1, |
| 1307 | dimension: wgpu::TextureDimension::D2, |
| 1308 | format, |
| 1309 | usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, |
| 1310 | view_formats: &[], |
| 1311 | }); |
| 1312 | let bpp = match format { |
| 1313 | wgpu::TextureFormat::Rgba32Float => 16u32, |
| 1314 | wgpu::TextureFormat::Rgba16Float => 8u32, |
| 1315 | wgpu::TextureFormat::Rgba8Unorm => 4u32, |
| 1316 | _ => unreachable!(), |
| 1317 | }; |
| 1318 | engine.queue().write_texture( |
| 1319 | texture.as_image_copy(), |
| 1320 | bytes, |
| 1321 | wgpu::TexelCopyBufferLayout { |
| 1322 | offset: 0, |
| 1323 | bytes_per_row: Some(w * bpp), |
| 1324 | rows_per_image: Some(h), |
| 1325 | }, |
| 1326 | wgpu::Extent3d { |
| 1327 | width: w, |
| 1328 | height: h, |
| 1329 | depth_or_array_layers: 1, |
| 1330 | }, |
| 1331 | ); |
| 1332 | let cached = crate::cache::CachedTexture::from_texture(texture, [w, h], 0); |
| 1333 | let got = engine |
| 1334 | .readback_rgba_f32(&cached) |
| 1335 | .expect("readback_rgba_f32 should succeed"); |
| 1336 | assert_eq!(got.len(), px_count * 4); |
| 1337 | for (i, (&g, &e)) in got.iter().zip(expected.iter()).enumerate() { |
| 1338 | assert!( |
| 1339 | (g - e).abs() <= 2e-3, |
| 1340 | "{format:?} sample {i}: expected {e}, got {g}" |
| 1341 | ); |
| 1342 | } |
| 1343 | }; |
| 1344 | |
| 1345 | let mut f32_vals = Vec::with_capacity(px_count * 4); |
| 1346 | let mut f16_bits = Vec::with_capacity(px_count * 4); |
| 1347 | let mut u8_vals = Vec::with_capacity(px_count * 4); |
| 1348 | let mut u8_expected = Vec::with_capacity(px_count * 4); |
| 1349 | for i in 0..px_count { |
| 1350 | let r = 2.5 + (i % 5) as f32 * 0.25; |
| 1351 | let g = -0.75 + (i % 3) as f32 * 0.5; |
| 1352 | let b = 0.125 * (i % 7) as f32; |
| 1353 | let a = 1.0; |
| 1354 | f32_vals.extend_from_slice(&[r, g, b, a]); |
| 1355 | f16_bits.extend_from_slice(&[ |
| 1356 | ::exr::prelude::f16::from_f32(r).to_bits(), |
| 1357 | ::exr::prelude::f16::from_f32(g).to_bits(), |
| 1358 | ::exr::prelude::f16::from_f32(b).to_bits(), |
| 1359 | ::exr::prelude::f16::from_f32(a).to_bits(), |
| 1360 | ]); |
| 1361 | let r8 = ((i * 17) % 256) as u8; |
| 1362 | let g8 = ((i * 31) % 256) as u8; |
| 1363 | let b8 = ((i * 53) % 256) as u8; |
| 1364 | let a8 = 255u8; |
| 1365 | u8_vals.extend_from_slice(&[r8, g8, b8, a8]); |
| 1366 | u8_expected.extend_from_slice(&[ |
| 1367 | f32::from(r8) / 255.0, |
| 1368 | f32::from(g8) / 255.0, |
| 1369 | f32::from(b8) / 255.0, |
| 1370 | 1.0, |
| 1371 | ]); |
| 1372 | } |
| 1373 | |
| 1374 | upload_and_check( |
| 1375 | wgpu::TextureFormat::Rgba32Float, |
| 1376 | bytemuck::cast_slice(&f32_vals), |
| 1377 | &f32_vals, |
| 1378 | ); |
| 1379 | upload_and_check( |
| 1380 | wgpu::TextureFormat::Rgba16Float, |
| 1381 | bytemuck::cast_slice(&f16_bits), |
| 1382 | &f32_vals, |
| 1383 | ); |
| 1384 | upload_and_check(wgpu::TextureFormat::Rgba8Unorm, &u8_vals, &u8_expected); |
| 1385 | } |
| 1386 | |
| 1387 | #[test] |
| 1388 | fn exports_exr_hdr_and_aux_roundtrips_through_loader() { |
| 1389 | let tmp_dir = std::env::temp_dir().join(format!( |
| 1390 | "fission-exr-roundtrip-test-{}", |
| 1391 | std::process::id() |
| 1392 | )); |
| 1393 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1394 | std::fs::create_dir_all(&tmp_dir).expect("create temp dir"); |
| 1395 | |
| 1396 | let Ok(mut engine) = Engine::new_headless() else { |
| 1397 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1398 | return; |
| 1399 | }; |
| 1400 | |
| 1401 | for (depth_code, expected_sample_type, tag) in [ |
| 1402 | (0, ::exr::meta::attribute::SampleType::F16, "f16"), |
| 1403 | (1, ::exr::meta::attribute::SampleType::F32, "f32"), |
| 1404 | ] { |
| 1405 | let saver_path = tmp_dir.join(tag).join("render_0000.exr"); |
| 1406 | let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); |
| 1407 | // Plane at Z = 0, Camera at Z = 2 => eye-space Z = -2.0; R3D Z + Normal aux channels |
| 1408 | // flow through ChangeDepth (Depth=4 Float32) + BrightnessContrast (Gain=2.5 => R=2.5 HDR). |
| 1409 | let comp_src = format!( |
| 1410 | r#"Composition {{ |
| 1411 | 	CurrentTime = 0, |
| 1412 | 	RenderRange = {{ 0, 0 }}, |
| 1413 | 	GlobalRange = {{ 0, 10 }}, |
| 1414 | 	Tools = ordered() {{ |
| 1415 | 		Flat = MtlBlinn {{ |
| 1416 | 			Inputs = {{ |
| 1417 | 				["Diffuse.Color.Red"] = Input {{ Value = 1.0, }}, |
| 1418 | 				["Diffuse.Color.Green"] = Input {{ Value = 0.2, }}, |
| 1419 | 				["Diffuse.Color.Blue"] = Input {{ Value = 0.1, }}, |
| 1420 | 				["Specular.Intensity"] = Input {{ Value = 0, }}, |
| 1421 | 			}}, |
| 1422 | 		}}, |
| 1423 | 		P = Shape3D {{ |
| 1424 | 			Inputs = {{ |
| 1425 | 				["SurfacePlaneInputs.Width"] = Input {{ Value = 0.5, }}, |
| 1426 | 				["SurfacePlaneInputs.Height"] = Input {{ Value = 0.5, }}, |
| 1427 | 				["Transform3DOp.Translate.Z"] = Input {{ Value = 0.0, }}, |
| 1428 | 				MaterialInput = Input {{ SourceOp = "Flat", Source = "MaterialOutput", }}, |
| 1429 | 			}}, |
| 1430 | 		}}, |
| 1431 | 		Cam = Camera3D {{ |
| 1432 | 			Inputs = {{ |
| 1433 | 				ProjectionType = Input {{ Value = FuID {{ "Perspective" }}, }}, |
| 1434 | 				["Transform3DOp.Translate.Z"] = Input {{ Value = 2.0, }}, |
| 1435 | 				ApertureW = Input {{ Value = 1.0, }}, |
| 1436 | 				ApertureH = Input {{ Value = 1.0, }}, |
| 1437 | 			}}, |
| 1438 | 		}}, |
| 1439 | 		M = Merge3D {{ |
| 1440 | 			Inputs = {{ |
| 1441 | 				SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, |
| 1442 | 				SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, |
| 1443 | 			}}, |
| 1444 | 		}}, |
| 1445 | 		R = Renderer3D {{ |
| 1446 | 			Inputs = {{ |
| 1447 | 				Width = Input {{ Value = 64, }}, |
| 1448 | 				Height = Input {{ Value = 64, }}, |
| 1449 | 				Depth = Input {{ Value = 4, }}, |
| 1450 | 				["RendererSoftware.Channels.Z"] = Input {{ Value = 1, }}, |
| 1451 | 				["RendererSoftware.Channels.Normal"] = Input {{ Value = 1, }}, |
| 1452 | 				SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, |
| 1453 | 			}}, |
| 1454 | 		}}, |
| 1455 | 		CD = ChangeDepth {{ |
| 1456 | 			Inputs = {{ |
| 1457 | 				Depth = Input {{ Value = 4, }}, |
| 1458 | 				Input = Input {{ SourceOp = "R", Source = "Output", }}, |
| 1459 | 			}}, |
| 1460 | 		}}, |
| 1461 | 		BC = BrightnessContrast {{ |
| 1462 | 			Inputs = {{ |
| 1463 | 				Gain = Input {{ Value = 2.5, }}, |
| 1464 | 				Input = Input {{ SourceOp = "CD", Source = "Output", }}, |
| 1465 | 			}}, |
| 1466 | 		}}, |
| 1467 | 		Saver1 = Saver {{ |
| 1468 | 			Inputs = {{ |
| 1469 | 				OutputFormat = Input {{ Value = FuID {{ "OpenEXRFormat" }}, }}, |
| 1470 | 				["OpenEXRFormat.Depth"] = Input {{ Value = {depth_code}, }}, |
| 1471 | 				["OpenEXRFormat.Compression"] = Input {{ Value = 3, }}, |
| 1472 | 				Clip = Input {{ |
| 1473 | 					Value = Clip {{ |
| 1474 | 						Filename = "{saver_path_escaped}", |
| 1475 | 						FormatID = "OpenEXRFormat", |
| 1476 | 						Saving = true, |
| 1477 | 					}}, |
| 1478 | 				}}, |
| 1479 | 				Input = Input {{ SourceOp = "BC", Source = "Output", }}, |
| 1480 | 			}}, |
| 1481 | 		}}, |
| 1482 | 	}}, |
| 1483 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 64, Rate = 24, DepthFull = 4 }} }} }}, |
| 1484 | }}"# |
| 1485 | ); |
| 1486 | |
| 1487 | let comp = Comp::from_fusion_str(&comp_src).expect("parse EXR Saver comp"); |
| 1488 | let summary = export_saver_sequence_with_progress( |
| 1489 | &mut engine, |
| 1490 | &comp, |
| 1491 | &ExportOptions::default(), |
| 1492 | None, |
| 1493 | |_| {}, |
| 1494 | ) |
| 1495 | .expect("export EXR via Saver"); |
| 1496 | assert_eq!(summary.frames_written, 1); |
| 1497 | |
| 1498 | let out_exr = tmp_dir.join(tag).join("render_0000.exr"); |
| 1499 | assert!(out_exr.exists(), "missing exported EXR {}", out_exr.display()); |
| 1500 | |
| 1501 | // Inspect channel metadata & Normal channel values directly in the EXR file. |
| 1502 | let meta = ::exr::meta::MetaData::read_from_file(&out_exr, false).expect("read EXR meta"); |
| 1503 | let ch_list = &meta.headers[0].channels.list; |
| 1504 | let find_ch = |name: &str| { |
| 1505 | ch_list |
| 1506 | .iter() |
| 1507 | .find(|c| c.name.to_string() == name) |
| 1508 | .unwrap_or_else(|| panic!("{tag}: missing EXR channel '{name}'")) |
| 1509 | }; |
| 1510 | for c in ["R", "G", "B", "A", "NX", "NY", "NZ"] { |
| 1511 | assert_eq!( |
| 1512 | find_ch(c).sample_type, |
| 1513 | expected_sample_type, |
| 1514 | "{tag}: channel {c} sample type mismatch" |
| 1515 | ); |
| 1516 | } |
| 1517 | assert_eq!( |
| 1518 | find_ch("Z").sample_type, |
| 1519 | ::exr::meta::attribute::SampleType::F32, |
| 1520 | "{tag}: Z channel must always be Float32" |
| 1521 | ); |
| 1522 | // Verify NX, NY, NZ normal values directly in the exported EXR layer. |
| 1523 | let flat_img = ::exr::prelude::read_all_flat_layers_from_file(&out_exr) |
| 1524 | .expect("read EXR flat layers"); |
| 1525 | let channels = &flat_img.layer_data[0].channel_data.list; |
| 1526 | let read_ch_f32 = |name: &str, idx: usize| -> f32 { |
| 1527 | let ch = channels |
| 1528 | .iter() |
| 1529 | .find(|c| c.name.to_string() == name) |
| 1530 | .unwrap_or_else(|| panic!("{tag}: missing flat channel '{name}'")); |
| 1531 | match &ch.sample_data { |
| 1532 | ::exr::prelude::FlatSamples::F16(v) => v[idx].to_f32(), |
| 1533 | ::exr::prelude::FlatSamples::F32(v) => v[idx], |
| 1534 | ::exr::prelude::FlatSamples::U32(v) => v[idx] as f32, |
| 1535 | } |
| 1536 | }; |
| 1537 | let center_idx = 32 * 64 + 32; |
| 1538 | let (nx, ny, nz) = ( |
| 1539 | read_ch_f32("NX", center_idx), |
| 1540 | read_ch_f32("NY", center_idx), |
| 1541 | read_ch_f32("NZ", center_idx), |
| 1542 | ); |
| 1543 | assert!( |
| 1544 | nx.abs() <= 1e-2 && ny.abs() <= 1e-2 && (nz - 1.0).abs() <= 1e-2, |
| 1545 | "{tag}: center normal expected ~(0,0,1), got ({nx}, {ny}, {nz})" |
| 1546 | ); |
| 1547 | assert_eq!( |
| 1548 | (read_ch_f32("NX", 0), read_ch_f32("NY", 0), read_ch_f32("NZ", 0)), |
| 1549 | (0.0, 0.0, 0.0), |
| 1550 | "{tag}: corner normal expected (0,0,0)" |
| 1551 | ); |
| 1552 | |
| 1553 | // Reload via Fusion Loader node (media/exr.rs) and verify linear HDR + aux.z! |
| 1554 | let out_exr_escaped = out_exr.to_string_lossy().replace('\\', "\\\\"); |
| 1555 | let loader_comp_src = format!( |
| 1556 | r#"Composition {{ |
| 1557 | 	CurrentTime = 0, |
| 1558 | 	RenderRange = {{ 0, 0 }}, |
| 1559 | 	GlobalRange = {{ 0, 0 }}, |
| 1560 | 	Tools = ordered() {{ |
| 1561 | 		L = Loader {{ |
| 1562 | 			Clips = {{ |
| 1563 | 				Clip {{ |
| 1564 | 					ID = "Clip1", |
| 1565 | 					Filename = "{out_exr_escaped}", |
| 1566 | 					FormatID = "OpenEXRFormat", |
| 1567 | 					StartFrame = 0, |
| 1568 | 					Length = 1, |
| 1569 | 					GlobalStart = 0, |
| 1570 | 					GlobalEnd = 0, |
| 1571 | 				}}, |
| 1572 | 			}}, |
| 1573 | 		}}, |
| 1574 | 	}}, |
| 1575 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 64, Rate = 24, DepthFull = 4 }} }} }}, |
| 1576 | }}"# |
| 1577 | ); |
| 1578 | let loader_comp = Comp::from_fusion_str(&loader_comp_src).expect("parse Loader comp"); |
| 1579 | let l_id = loader_comp.find_node("L").expect("find Loader"); |
| 1580 | let (loaded_tex, _) = engine.evaluate(&loader_comp, l_id, 0.0); |
| 1581 | |
| 1582 | let rgba = engine |
| 1583 | .readback_rgba_f32(&loaded_tex) |
| 1584 | .expect("readback reloaded EXR RGBA"); |
| 1585 | let center_off = (32 * 64 + 32) * 4; |
| 1586 | assert!( |
| 1587 | rgba[center_off] > 2.0, |
| 1588 | "{tag}: HDR linear R must be preserved (> 2.0), got {}", |
| 1589 | rgba[center_off] |
| 1590 | ); |
| 1591 | assert!( |
| 1592 | (rgba[center_off] - 2.5).abs() <= 0.03, |
| 1593 | "{tag}: expected R ~ 2.5, got {}", |
| 1594 | rgba[center_off] |
| 1595 | ); |
| 1596 | assert!( |
| 1597 | (rgba[center_off + 1] - 0.5).abs() <= 0.03, |
| 1598 | "{tag}: expected G ~ 0.5, got {}", |
| 1599 | rgba[center_off + 1] |
| 1600 | ); |
| 1601 | assert!( |
| 1602 | (rgba[center_off + 2] - 0.25).abs() <= 0.03, |
| 1603 | "{tag}: expected B ~ 0.25, got {}", |
| 1604 | rgba[center_off + 2] |
| 1605 | ); |
| 1606 | assert!((rgba[center_off + 3] - 1.0).abs() <= 0.01); |
| 1607 | |
| 1608 | let aux = loaded_tex |
| 1609 | .aux |
| 1610 | .as_ref() |
| 1611 | .expect("reloaded EXR must carry aux channels"); |
| 1612 | let z_tex = aux.z.as_ref().expect("reloaded EXR must carry aux.z"); |
| 1613 | let z_vals = engine |
| 1614 | .readback_aux_z_f32(z_tex) |
| 1615 | .expect("readback reloaded EXR aux.z"); |
| 1616 | let center_z = z_vals[32 * 64 + 32]; |
| 1617 | let corner_z = z_vals[0]; |
| 1618 | assert!( |
| 1619 | (center_z - (-2.0)).abs() <= 1e-3, |
| 1620 | "{tag}: reloaded center Z expected -2.0, got {center_z}" |
| 1621 | ); |
| 1622 | assert_eq!( |
| 1623 | corner_z, |
| 1624 | crate::cache::EMPTY_Z_SENTINEL, |
| 1625 | "{tag}: reloaded empty corner Z expected -1e30, got {corner_z}" |
| 1626 | ); |
| 1627 | } |
| 1628 | |
| 1629 | // Also verify write_exr_rgba_with_aux across all 6 Fusion compression modes. |
| 1630 | let rgba_sample = vec![2.5, 0.5, 0.25, 1.0, 0.0, 0.0, 0.0, 0.0]; |
| 1631 | let z_sample = vec![-2.0, crate::cache::EMPTY_Z_SENTINEL]; |
| 1632 | let n_sample = vec![0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]; |
| 1633 | for comp_mode in [ |
| 1634 | ExrCompression::Uncompressed, |
| 1635 | ExrCompression::Rle, |
| 1636 | ExrCompression::Zip1, |
| 1637 | ExrCompression::Zip16, |
| 1638 | ExrCompression::Piz, |
| 1639 | ExrCompression::Pxr24, |
| 1640 | ] { |
| 1641 | let p = tmp_dir.join(format!("comp_{comp_mode:?}.exr")); |
| 1642 | write_exr_rgba_with_aux( |
| 1643 | &p, |
| 1644 | [2, 1], |
| 1645 | &rgba_sample, |
| 1646 | Some(&z_sample), |
| 1647 | Some(&n_sample), |
| 1648 | ExrDepth::Float16, |
| 1649 | comp_mode, |
| 1650 | ) |
| 1651 | .unwrap_or_else(|e| panic!("write EXR {comp_mode:?} failed: {e}")); |
| 1652 | assert!(p.exists()); |
| 1653 | } |
| 1654 | |
| 1655 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1656 | } |
| 1657 | |
| 1658 | #[test] |
| 1659 | fn exports_exr_saver_sequence_and_stops_cleanly_on_cancel() { |
| 1660 | let tmp_dir = std::env::temp_dir().join(format!( |
| 1661 | "fission-exr-seq-cancel-test-{}", |
| 1662 | std::process::id() |
| 1663 | )); |
| 1664 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1665 | |
| 1666 | let full_dir = tmp_dir.join("full"); |
| 1667 | let cancel_dir = tmp_dir.join("cancel"); |
| 1668 | |
| 1669 | let make_comp = |dir: &Path| { |
| 1670 | let saver_path = dir.join("shot_0000.exr"); |
| 1671 | let saver_path_escaped = saver_path.to_string_lossy().replace('\\', "\\\\"); |
| 1672 | let comp_src = format!( |
| 1673 | r#"Composition {{ |
| 1674 | 	CurrentTime = 10, |
| 1675 | 	RenderRange = {{ 10, 15 }}, |
| 1676 | 	GlobalRange = {{ 0, 100 }}, |
| 1677 | 	Tools = ordered() {{ |
| 1678 | 		BG = Background {{ |
| 1679 | 			Inputs = {{ |
| 1680 | 				Width = Input {{ Value = 64, }}, |
| 1681 | 				Height = Input {{ Value = 32, }}, |
| 1682 | 				Depth = Input {{ Value = 4, }}, |
| 1683 | 				TopLeftRed = Input {{ SourceOp = "BGRed", Source = "Value", }}, |
| 1684 | 				TopLeftGreen = Input {{ Value = 0.25, }}, |
| 1685 | 				TopLeftBlue = Input {{ Value = 0.5, }}, |
| 1686 | 				TopLeftAlpha = Input {{ Value = 1, }}, |
| 1687 | 			}}, |
| 1688 | 		}}, |
| 1689 | 		BGRed = BezierSpline {{ |
| 1690 | 			KeyFrames = {{ |
| 1691 | 				[10] = {{ 0.5, Flags = {{ Linear = true }} }}, |
| 1692 | 				[15] = {{ 3.0, Flags = {{ Linear = true }} }}, |
| 1693 | 			}}, |
| 1694 | 		}}, |
| 1695 | 		Saver1 = Saver {{ |
| 1696 | 			Inputs = {{ |
| 1697 | 				OutputFormat = Input {{ Value = FuID {{ "OpenEXRFormat" }}, }}, |
| 1698 | 				["OpenEXRFormat.Depth"] = Input {{ Value = 0, }}, |
| 1699 | 				["OpenEXRFormat.Compression"] = Input {{ Value = 3, }}, |
| 1700 | 				Clip = Input {{ |
| 1701 | 					Value = Clip {{ |
| 1702 | 						Filename = "{saver_path_escaped}", |
| 1703 | 						FormatID = "OpenEXRFormat", |
| 1704 | 						Saving = true, |
| 1705 | 					}}, |
| 1706 | 				}}, |
| 1707 | 				Input = Input {{ SourceOp = "BG", Source = "Output", }}, |
| 1708 | 			}}, |
| 1709 | 		}}, |
| 1710 | 	}}, |
| 1711 | 	Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, Rate = 24, DepthFull = 4 }} }} }}, |
| 1712 | }}"# |
| 1713 | ); |
| 1714 | Comp::from_fusion_str(&comp_src).expect("parse EXR sequence comp") |
| 1715 | }; |
| 1716 | |
| 1717 | let Ok(mut engine) = Engine::new_headless() else { |
| 1718 | return; |
| 1719 | }; |
| 1720 | |
| 1721 | // 1. Verify export_saver_png_sequence_with_progress automatically dispatches to OpenEXR! |
| 1722 | let full_comp = make_comp(&full_dir); |
| 1723 | let mut seen_frames = Vec::new(); |
| 1724 | let summary = export_saver_png_sequence_with_progress( |
| 1725 | &mut engine, |
| 1726 | &full_comp, |
| 1727 | &ExportOptions::default(), |
| 1728 | None, |
| 1729 | |p| seen_frames.push(p.frame), |
| 1730 | ) |
| 1731 | .expect("export EXR sequence via Saver dispatcher"); |
| 1732 | assert_eq!(summary.frames_written, 6); |
| 1733 | assert_eq!(seen_frames, vec![10, 11, 12, 13, 14, 15]); |
| 1734 | for f in 10..=15 { |
| 1735 | let p = full_dir.join(format!("shot_{f:04}.exr")); |
| 1736 | assert!(p.exists(), "missing EXR frame {}", p.display()); |
| 1737 | } |
| 1738 | let last_exr = full_dir.join("shot_0015.exr"); |
| 1739 | let last_exr_escaped = last_exr.to_string_lossy().replace('\\', "\\\\"); |
| 1740 | let loader_comp = Comp::from_fusion_str(&format!( |
| 1741 | r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ |
| 1742 | L = Loader {{ Clips = {{ Clip {{ ID = "Clip1", Filename = "{last_exr_escaped}", StartFrame = 0, Length = 1, GlobalStart = 0, GlobalEnd = 0, }} }}, }}, |
| 1743 | }}, Prefs = {{ Comp = {{ FrameFormat = {{ Width = 64, Height = 32, DepthFull = 4 }} }} }} }}"# |
| 1744 | )) |
| 1745 | .unwrap(); |
| 1746 | let (ltex, _) = engine.evaluate(&loader_comp, loader_comp.find_node("L").unwrap(), 0.0); |
| 1747 | let lrgba = engine.readback_rgba_f32(&ltex).unwrap(); |
| 1748 | assert!( |
| 1749 | (lrgba[0] - 3.0).abs() <= 0.02, |
| 1750 | "frame 15 HDR red expected ~3.0, got {}", |
| 1751 | lrgba[0] |
| 1752 | ); |
| 1753 | |
| 1754 | // 2. Verify cooperative cancellation stops cleanly and leaves zero leaked temp files. |
| 1755 | let cancel_comp = make_comp(&cancel_dir); |
| 1756 | let control = ExportControl::new(); |
| 1757 | let ctrl_cb = control.clone(); |
| 1758 | let mut reported = Vec::new(); |
| 1759 | let err = export_saver_exr_sequence_with_progress( |
| 1760 | &mut engine, |
| 1761 | &cancel_comp, |
| 1762 | &ExportOptions::default(), |
| 1763 | Some(&control), |
| 1764 | |p| { |
| 1765 | reported.push(p.completed_frames); |
| 1766 | if p.completed_frames >= 2 { |
| 1767 | ctrl_cb.cancel(); |
| 1768 | } |
| 1769 | }, |
| 1770 | ) |
| 1771 | .expect_err("EXR sequence export should cancel early"); |
| 1772 | assert_eq!(err, "Cancelled"); |
| 1773 | assert_eq!(reported, vec![1, 2]); |
| 1774 | assert!(!cancel_dir.join("shot_0015.exr").exists()); |
| 1775 | |
| 1776 | if cancel_dir.exists() { |
| 1777 | for entry in std::fs::read_dir(&cancel_dir).expect("read cancel_dir") { |
| 1778 | let entry = entry.expect("dir entry"); |
| 1779 | let path = entry.path(); |
| 1780 | assert_eq!( |
| 1781 | path.extension().and_then(|e| e.to_str()), |
| 1782 | Some("exr"), |
| 1783 | "unexpected leaked temp/partial file: {}", |
| 1784 | path.display() |
| 1785 | ); |
| 1786 | ::exr::meta::MetaData::read_from_file(&path, false) |
| 1787 | .unwrap_or_else(|e| panic!("corrupt EXR file {}: {e}", path.display())); |
| 1788 | } |
| 1789 | } |
| 1790 | |
| 1791 | let _ = std::fs::remove_dir_all(&tmp_dir); |
| 1792 | } |
| 1793 | |
| 1794 | #[test] |
| 1795 | fn saver_output_format_takes_precedence_over_exr_extension() { |
| 1796 | let check = |output_format: Option<&str>, format_id: Option<&str>, filename: &str| -> bool { |
| 1797 | let of_line = output_format |
| 1798 | .map(|f| format!(r#"OutputFormat = Input {{ Value = FuID {{ "{f}" }}, }},"#)) |
| 1799 | .unwrap_or_default(); |
| 1800 | let fid_line = format_id |
| 1801 | .map(|f| format!(r#"FormatID = "{f}","#)) |
| 1802 | .unwrap_or_default(); |
| 1803 | let src = format!( |
| 1804 | r#"Composition {{ |
| 1805 | CurrentTime = 0, |
| 1806 | RenderRange = {{ 0, 0 }}, |
| 1807 | GlobalRange = {{ 0, 0 }}, |
| 1808 | Tools = ordered() {{ |
| 1809 | Saver1 = Saver {{ |
| 1810 | Inputs = {{ |
| 1811 | {of_line} |
| 1812 | Clip = Input {{ |
| 1813 | Value = Clip {{ |
| 1814 | Filename = "{filename}", |
| 1815 | {fid_line} |
| 1816 | Saving = true, |
| 1817 | }}, |
| 1818 | }}, |
| 1819 | }}, |
| 1820 | }}, |
| 1821 | }}, |
| 1822 | }}"# |
| 1823 | ); |
| 1824 | let comp = Comp::from_fusion_str(&src).expect("parse saver comp"); |
| 1825 | let saver = select_saver(&comp, None).expect("select saver"); |
| 1826 | saver_targets_exr(&comp, &saver, None) |
| 1827 | }; |
| 1828 | |
| 1829 | // Explicit non-EXR OutputFormat overrides .exr filename and even Clip.Value.FormatID. |
| 1830 | assert!(!check(Some("PNGFormat"), None, "/tmp/out_0000.exr")); |
| 1831 | assert!(!check(Some("PNGFormat"), Some("OpenEXRFormat"), "/tmp/out_0000.exr")); |
| 1832 | // Explicit OpenEXRFormat overrides .png filename. |
| 1833 | assert!(check(Some("OpenEXRFormat"), None, "/tmp/out_0000.png")); |
| 1834 | // Unset OutputFormat with explicit non-EXR FormatID overrides .exr extension. |
| 1835 | assert!(!check(None, Some("PNGFormat"), "/tmp/out_0000.exr")); |
| 1836 | // Empty OutputFormat and empty/unset FormatID fall back to .exr extension. |
| 1837 | assert!(check(None, None, "/tmp/out_0000.exr")); |
| 1838 | assert!(check(Some(""), Some(""), "/tmp/out_0000.exr")); |
| 1839 | assert!(!check(None, None, "/tmp/out_0000.png")); |
| 1840 | } |