| ... | ... | @@ -10,15 +10,26 @@ pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; |
| 10 | 10 | #[cfg(target_os = "macos")] |
| 11 | 11 | pub use video::AvFoundationDecoder; |
| 12 | 12 | pub use video::{FfmpegDecoder, VideoDecoder, VideoInfo, open_video_decoder}; |
| 13 | | use exr::{apply_post_multiply_rgba8, decode_exr_rgba, is_exr_path, normalize_channel_opt}; |
| 13 | use exr::{ |
| 14 | apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path, |
| 15 | normalize_channel_opt, |
| 16 | }; |
| 14 | 17 | use video::is_video_path; |
| 15 | 18 | |
| 16 | 19 | use crate::text_engine; |
| 17 | | use model::{ClipSpec, ClsEntry, PolyPoint}; |
| 20 | #[cfg(not(target_arch = "wasm32"))] |
| 21 | use model::{Node, default_main_input_port}; |
| 22 | use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint}; |
| 23 | #[cfg(not(target_arch = "wasm32"))] |
| 24 | use std::collections::HashSet; |
| 18 | 25 | use std::collections::HashMap; |
| 19 | 26 | use std::path::{Path, PathBuf}; |
| 20 | 27 | use std::process::Command; |
| 28 | #[cfg(not(target_arch = "wasm32"))] |
| 29 | use std::sync::Mutex; |
| 21 | 30 | use std::sync::{Arc, RwLock}; |
| 31 | #[cfg(not(target_arch = "wasm32"))] |
| 32 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 22 | 33 | |
| 23 | 34 | #[derive(Clone)] |
| 24 | 35 | pub struct DecodedImage { |
| ... | ... | @@ -119,12 +130,58 @@ fn path_exists(path: &Path) -> bool { |
| 119 | 130 | } |
| 120 | 131 | |
| 121 | 132 | fn open_image(path: &Path) -> Option<image::DynamicImage> { |
| 122 | | match virtual_bytes(path) { |
| 123 | | Some(bytes) => image::load_from_memory(&bytes).ok(), |
| 124 | | None => image::open(path).ok(), |
| 133 | if let Some(bytes) = virtual_bytes(path) { |
| 134 | return image::load_from_memory(&bytes).ok(); |
| 135 | } |
| 136 | // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares. |
| 137 | if let Ok(bytes) = std::fs::read(path) { |
| 138 | if let Ok(img) = image::load_from_memory(&bytes) { |
| 139 | return Some(img); |
| 140 | } |
| 141 | } |
| 142 | image::open(path).ok() |
| 143 | } |
| 144 | |
| 145 | fn decode_raster_image( |
| 146 | path: &Path, |
| 147 | post_multiply: bool, |
| 148 | allow_parallel_premult: bool, |
| 149 | ) -> Option<DecodedImage> { |
| 150 | let dyn_img = open_image(path)?; |
| 151 | let has_alpha = dyn_img.color().has_alpha(); |
| 152 | let size = [dyn_img.width(), dyn_img.height()]; |
| 153 | let mut raw = dyn_img.into_rgba8().into_raw(); |
| 154 | if post_multiply && has_alpha { |
| 155 | apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult); |
| 156 | } |
| 157 | Some(DecodedImage { |
| 158 | size, |
| 159 | rgba: Arc::new(raw), |
| 160 | rgba_f16: None, |
| 161 | rgba_f32: None, |
| 162 | }) |
| 163 | } |
| 164 | |
| 165 | pub(crate) fn media_cache_budget_mb_for_total_bytes(total_bytes: u64) -> u64 { |
| 166 | let gib = total_bytes / (1024 * 1024 * 1024); |
| 167 | if gib >= 128 { |
| 168 | 8 * 1024 |
| 169 | } else if gib >= 64 { |
| 170 | 4 * 1024 |
| 171 | } else if gib >= 32 { |
| 172 | 2 * 1024 |
| 173 | } else if gib >= 16 { |
| 174 | 1024 |
| 175 | } else { |
| 176 | 512 |
| 125 | 177 | } |
| 126 | 178 | } |
| 127 | 179 | |
| 180 | /// Returns the default `MediaCache` budget in MiB scaled to host physical RAM. |
| 181 | pub fn default_media_cache_budget_mb() -> u64 { |
| 182 | media_cache_budget_mb_for_total_bytes(crate::ram_cache::system_memory_bytes()) |
| 183 | } |
| 184 | |
| 128 | 185 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 129 | 186 | struct ImageCacheKey { |
| 130 | 187 | path: PathBuf, |
| ... | ... | @@ -147,18 +204,28 @@ pub struct MediaCache { |
| 147 | 204 | tick: u64, |
| 148 | 205 | } |
| 149 | 206 | |
| 207 | impl Default for MediaCache { |
| 208 | fn default() -> Self { |
| 209 | Self::new(default_media_cache_budget_mb()) |
| 210 | } |
| 211 | } |
| 212 | |
| 150 | 213 | impl MediaCache { |
| 151 | 214 | pub fn new(budget_mb: u64) -> Self { |
| 152 | 215 | Self { |
| 153 | 216 | images: HashMap::new(), |
| 154 | 217 | video_decoders: HashMap::new(), |
| 155 | 218 | total_bytes: 0, |
| 156 | | budget_bytes: budget_mb * 1024 * 1024, |
| 219 | budget_bytes: budget_mb.saturating_mul(1024 * 1024), |
| 157 | 220 | lru: HashMap::new(), |
| 158 | 221 | tick: 0, |
| 159 | 222 | } |
| 160 | 223 | } |
| 161 | 224 | |
| 225 | pub fn with_budget_mb(budget_mb: u64) -> Self { |
| 226 | Self::new(budget_mb) |
| 227 | } |
| 228 | |
| 162 | 229 | /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false` |
| 163 | 230 | /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged. |
| 164 | 231 | pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) -> bool { |
| ... | ... | @@ -224,12 +291,13 @@ impl MediaCache { |
| 224 | 291 | } |
| 225 | 292 | } |
| 226 | 293 | |
| 227 | | fn get_or_open_video_decoder(&mut self, path: &Path) -> Option<VideoInfo> { |
| 294 | fn put_video_decoder(&mut self, path: PathBuf, decoder: Option<Box<dyn VideoDecoder>>) { |
| 228 | 295 | self.tick += 1; |
| 229 | 296 | let now_tick = self.tick; |
| 230 | | if let Some(entry) = self.video_decoders.get_mut(path) { |
| 297 | if let Some(entry) = self.video_decoders.get_mut(&path) { |
| 298 | entry.decoder = decoder; |
| 231 | 299 | entry.last_used = now_tick; |
| 232 | | return entry.decoder.as_ref().map(|d| d.info()); |
| 300 | return; |
| 233 | 301 | } |
| 234 | 302 | while self.video_decoders.len() >= MAX_VIDEO_DECODERS { |
| 235 | 303 | let Some(oldest_path) = self |
| ... | ... | @@ -242,15 +310,25 @@ impl MediaCache { |
| 242 | 310 | }; |
| 243 | 311 | self.video_decoders.remove(&oldest_path); |
| 244 | 312 | } |
| 245 | | let decoder = open_video_decoder(path); |
| 246 | | let info = decoder.as_ref().map(|d| d.info()); |
| 247 | 313 | self.video_decoders.insert( |
| 248 | | path.to_path_buf(), |
| 314 | path, |
| 249 | 315 | VideoDecoderEntry { |
| 250 | 316 | decoder, |
| 251 | 317 | last_used: now_tick, |
| 252 | 318 | }, |
| 253 | 319 | ); |
| 320 | } |
| 321 | |
| 322 | fn get_or_open_video_decoder(&mut self, path: &Path) -> Option<VideoInfo> { |
| 323 | self.tick += 1; |
| 324 | let now_tick = self.tick; |
| 325 | if let Some(entry) = self.video_decoders.get_mut(path) { |
| 326 | entry.last_used = now_tick; |
| 327 | return entry.decoder.as_ref().map(|d| d.info()); |
| 328 | } |
| 329 | let decoder = open_video_decoder(path); |
| 330 | let info = decoder.as_ref().map(|d| d.info()); |
| 331 | self.put_video_decoder(path.to_path_buf(), decoder); |
| 254 | 332 | info |
| 255 | 333 | } |
| 256 | 334 | |
| ... | ... | @@ -265,36 +343,12 @@ impl MediaCache { |
| 265 | 343 | ) -> Option<(PathBuf, i64, DecodedImage, bool)> { |
| 266 | 344 | let base = Path::new(&clip.filename); |
| 267 | 345 | if is_video_path(base) { |
| 268 | | if !base.exists() { |
| 346 | if !base.exists() || !video_frame_in_range(clip, frame) { |
| 269 | 347 | return None; |
| 270 | 348 | } |
| 271 | | // Enforce active timeline range [GlobalStart - ExtendFirst, GlobalEnd + ExtendLast]. |
| 272 | | if clip.global_end >= clip.global_start |
| 273 | | && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start) |
| 274 | | { |
| 275 | | let min_f = clip.global_start - clip.extend_first.max(0); |
| 276 | | let max_f = clip.global_end + clip.extend_last.max(0); |
| 277 | | if frame < min_f || (!clip.loop_clip && frame > max_f) { |
| 278 | | return None; |
| 279 | | } |
| 280 | | } |
| 281 | 349 | let base_buf = base.to_path_buf(); |
| 282 | 350 | let info = self.get_or_open_video_decoder(base)?; |
| 283 | | |
| 284 | | let len = clip.length.unwrap_or(info.nb_frames.max(1)).max(1); |
| 285 | | let trim_in = clip.trim_in.clamp(0, len - 1); |
| 286 | | let trim_out = if clip.trim_out > 0 { |
| 287 | | clip.trim_out.clamp(trim_in, len - 1) |
| 288 | | } else { |
| 289 | | len - 1 |
| 290 | | }; |
| 291 | | let span = (trim_out - trim_in + 1).max(1); |
| 292 | | let rel = if clip.loop_clip { |
| 293 | | (frame - clip.global_start).max(0).rem_euclid(span) |
| 294 | | } else { |
| 295 | | (frame - clip.global_start).clamp(0, span - 1) |
| 296 | | }; |
| 297 | | let idx = if clip.reverse { trim_out - rel } else { trim_in + rel }; |
| 351 | let idx = compute_video_frame_idx(clip, frame, info.nb_frames); |
| 298 | 352 | let cache_key = ImageCacheKey { |
| 299 | 353 | path: base_buf.clone(), |
| 300 | 354 | frame_idx: idx, |
| ... | ... | @@ -359,23 +413,759 @@ impl MediaCache { |
| 359 | 413 | false, |
| 360 | 414 | )? |
| 361 | 415 | } else { |
| 362 | | let dyn_img = open_image(&resolved)?; |
| 363 | | let rgba_img = dyn_img.to_rgba8(); |
| 364 | | let size = [rgba_img.width(), rgba_img.height()]; |
| 365 | | let mut raw = rgba_img.into_raw(); |
| 366 | | if post_multiply { |
| 367 | | apply_post_multiply_rgba8(&mut raw); |
| 368 | | } |
| 369 | | DecodedImage { |
| 370 | | size, |
| 371 | | rgba: Arc::new(raw), |
| 372 | | rgba_f16: None, |
| 373 | | rgba_f32: None, |
| 374 | | } |
| 416 | decode_raster_image(&resolved, post_multiply, true)? |
| 375 | 417 | }; |
| 376 | 418 | self.insert_cached(cache_key, decoded.clone()); |
| 377 | 419 | Some((resolved, -1, decoded, true)) |
| 378 | 420 | } |
| 421 | |
| 422 | /// Walks reachable `Loader` nodes upstream of `target` at `time` and decodes any missing |
| 423 | /// still/sequence/EXR frames into RAM in parallel when 2 or more distinct files are uncached. |
| 424 | pub fn preload_frame_loaders( |
| 425 | &mut self, |
| 426 | comp: &Comp, |
| 427 | target: NodeId, |
| 428 | time: f64, |
| 429 | expr: &model::ExprEngine, |
| 430 | ) { |
| 431 | self.preload_frame_loaders_with_proxy(comp, target, time, expr, false); |
| 432 | } |
| 433 | |
| 434 | /// Variant of [`Self::preload_frame_loaders`] honoring `use_proxy_clips`. |
| 435 | pub fn preload_frame_loaders_with_proxy( |
| 436 | &mut self, |
| 437 | comp: &Comp, |
| 438 | target: NodeId, |
| 439 | time: f64, |
| 440 | expr: &model::ExprEngine, |
| 441 | use_proxy_clips: bool, |
| 442 | ) { |
| 443 | #[cfg(target_arch = "wasm32")] |
| 444 | { |
| 445 | let _ = (comp, target, time, expr, use_proxy_clips); |
| 446 | } |
| 447 | #[cfg(not(target_arch = "wasm32"))] |
| 448 | { |
| 449 | let mut visited = HashSet::new(); |
| 450 | let mut jobs = MissingJobs::default(); |
| 451 | self.collect_missing_loader_jobs( |
| 452 | comp, |
| 453 | target, |
| 454 | time, |
| 455 | expr, |
| 456 | use_proxy_clips, |
| 457 | &mut visited, |
| 458 | &mut jobs, |
| 459 | ); |
| 460 | if jobs.total_units() < 2 { |
| 461 | return; |
| 462 | } |
| 463 | self.decode_jobs_parallel(jobs); |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | /// Pre-decodes reachable `Loader` files for upcoming `frames` in parallel into `MediaCache`. |
| 468 | pub fn prefetch_frames( |
| 469 | &mut self, |
| 470 | comp: &Comp, |
| 471 | target: NodeId, |
| 472 | frames: &[f64], |
| 473 | expr: &model::ExprEngine, |
| 474 | ) { |
| 475 | self.prefetch_frames_with_proxy(comp, target, frames, expr, false); |
| 476 | } |
| 477 | |
| 478 | /// Variant of [`Self::prefetch_frames`] honoring `use_proxy_clips`. |
| 479 | pub fn prefetch_frames_with_proxy( |
| 480 | &mut self, |
| 481 | comp: &Comp, |
| 482 | target: NodeId, |
| 483 | frames: &[f64], |
| 484 | expr: &model::ExprEngine, |
| 485 | use_proxy_clips: bool, |
| 486 | ) { |
| 487 | #[cfg(target_arch = "wasm32")] |
| 488 | { |
| 489 | let _ = (comp, target, frames, expr, use_proxy_clips); |
| 490 | } |
| 491 | #[cfg(not(target_arch = "wasm32"))] |
| 492 | { |
| 493 | if frames.is_empty() { |
| 494 | return; |
| 495 | } |
| 496 | let mut visited = HashSet::new(); |
| 497 | let mut jobs = MissingJobs::default(); |
| 498 | for &time in frames { |
| 499 | self.collect_missing_loader_jobs( |
| 500 | comp, |
| 501 | target, |
| 502 | time, |
| 503 | expr, |
| 504 | use_proxy_clips, |
| 505 | &mut visited, |
| 506 | &mut jobs, |
| 507 | ); |
| 508 | } |
| 509 | let total = jobs.total_units(); |
| 510 | if total == 0 { |
| 511 | return; |
| 512 | } |
| 513 | if total == 1 && jobs.raster.len() == 1 { |
| 514 | let job = jobs.raster.pop().expect("len == 1"); |
| 515 | if let Some(decoded) = decode_job(&job, true) { |
| 516 | self.insert_cached(job.cache_key, decoded); |
| 517 | } |
| 518 | return; |
| 519 | } |
| 520 | self.decode_jobs_parallel(jobs); |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | #[cfg(not(target_arch = "wasm32"))] |
| 525 | fn decode_jobs_parallel(&mut self, mut jobs: MissingJobs) { |
| 526 | let mut video_tasks: Vec<VideoDecodeTask> = jobs |
| 527 | .videos |
| 528 | .drain() |
| 529 | .map(|(path, requests)| { |
| 530 | let decoder = self |
| 531 | .video_decoders |
| 532 | .get_mut(&path) |
| 533 | .and_then(|entry| entry.decoder.take()); |
| 534 | VideoDecodeTask { |
| 535 | path, |
| 536 | decoder, |
| 537 | requests, |
| 538 | } |
| 539 | }) |
| 540 | .collect(); |
| 541 | let video_count = video_tasks.len(); |
| 542 | let raster_jobs = jobs.raster; |
| 543 | let total_units = video_count + raster_jobs.len(); |
| 544 | if total_units == 0 { |
| 545 | return; |
| 546 | } |
| 547 | let workers = std::thread::available_parallelism() |
| 548 | .map(|n| n.get().clamp(1, 8)) |
| 549 | .unwrap_or(4) |
| 550 | .min(total_units); |
| 551 | |
| 552 | let next_idx = AtomicUsize::new(0); |
| 553 | let video_slots: Vec< |
| 554 | Mutex<Option<(PathBuf, Option<Box<dyn VideoDecoder>>, Vec<(ImageCacheKey, DecodedImage)>)>>, |
| 555 | > = (0..video_count).map(|_| Mutex::new(None)).collect(); |
| 556 | let raster_slots: Vec<Mutex<Option<DecodedImage>>> = |
| 557 | (0..raster_jobs.len()).map(|_| Mutex::new(None)).collect(); |
| 558 | |
| 559 | let video_inputs: Vec<Mutex<Option<VideoDecodeTask>>> = |
| 560 | video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect(); |
| 561 | |
| 562 | std::thread::scope(|scope| { |
| 563 | for _ in 0..workers { |
| 564 | scope.spawn(|| loop { |
| 565 | let idx = next_idx.fetch_add(1, Ordering::Relaxed); |
| 566 | if idx >= total_units { |
| 567 | break; |
| 568 | } |
| 569 | if idx < video_count { |
| 570 | let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take()); |
| 571 | if let Some(mut task) = task { |
| 572 | let mut dec_opt = |
| 573 | task.decoder.take().or_else(|| open_video_decoder(&task.path)); |
| 574 | let mut decoded_frames = Vec::new(); |
| 575 | if let Some(ref mut dec) = dec_opt { |
| 576 | let info = dec.info(); |
| 577 | let mut seen_local = HashSet::new(); |
| 578 | for req in &task.requests { |
| 579 | let frame_idx = compute_video_frame_idx( |
| 580 | &req.clip, |
| 581 | req.frame_i, |
| 582 | info.nb_frames, |
| 583 | ); |
| 584 | if !seen_local.insert((frame_idx, req.post_multiply)) { |
| 585 | continue; |
| 586 | } |
| 587 | if let Some(mut raw) = dec.decode_frame(frame_idx) { |
| 588 | if req.post_multiply { |
| 589 | apply_post_multiply_rgba8_parallel(&mut raw, false); |
| 590 | } |
| 591 | let key = ImageCacheKey { |
| 592 | path: task.path.clone(), |
| 593 | frame_idx, |
| 594 | post_multiply: req.post_multiply, |
| 595 | exr_channels: [None, None, None, None], |
| 596 | }; |
| 597 | decoded_frames.push(( |
| 598 | key, |
| 599 | DecodedImage { |
| 600 | size: [info.width, info.height], |
| 601 | rgba: Arc::new(raw), |
| 602 | rgba_f16: None, |
| 603 | rgba_f32: None, |
| 604 | }, |
| 605 | )); |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | if let Ok(mut slot) = video_slots[idx].lock() { |
| 610 | *slot = Some((task.path, dec_opt, decoded_frames)); |
| 611 | } |
| 612 | } |
| 613 | } else { |
| 614 | let r_idx = idx - video_count; |
| 615 | let decoded = decode_job(&raster_jobs[r_idx], false); |
| 616 | if let Ok(mut slot) = raster_slots[r_idx].lock() { |
| 617 | *slot = decoded; |
| 618 | } |
| 619 | } |
| 620 | }); |
| 621 | } |
| 622 | }); |
| 623 | |
| 624 | for slot in video_slots { |
| 625 | if let Ok(mut guard) = slot.into_inner() { |
| 626 | if let Some((path, dec_opt, frames)) = guard.take() { |
| 627 | self.put_video_decoder(path, dec_opt); |
| 628 | for (key, img) in frames { |
| 629 | self.insert_cached(key, img); |
| 630 | } |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | for (job, slot) in raster_jobs.into_iter().zip(raster_slots) { |
| 635 | if let Ok(mut guard) = slot.into_inner() { |
| 636 | if let Some(decoded) = guard.take() { |
| 637 | self.insert_cached(job.cache_key, decoded); |
| 638 | } |
| 639 | } |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | #[cfg(not(target_arch = "wasm32"))] |
| 644 | #[allow(clippy::too_many_arguments)] |
| 645 | fn collect_missing_loader_jobs( |
| 646 | &self, |
| 647 | comp: &Comp, |
| 648 | node_id: NodeId, |
| 649 | time: f64, |
| 650 | expr: &model::ExprEngine, |
| 651 | use_proxy_clips: bool, |
| 652 | visited: &mut HashSet<(NodeId, i64)>, |
| 653 | jobs: &mut MissingJobs, |
| 654 | ) { |
| 655 | if node_id.0 >= comp.nodes.len() { |
| 656 | return; |
| 657 | } |
| 658 | let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64; |
| 659 | if !visited.insert((node_id, time_key)) { |
| 660 | return; |
| 661 | } |
| 662 | let node = comp.node(node_id); |
| 663 | |
| 664 | if node.bypassed |
| 665 | || matches!( |
| 666 | node.kind.as_str(), |
| 667 | "Saver" |
| 668 | | "PipeRouter" |
| 669 | | "Fuse.Wireless" |
| 670 | | "Tracker" |
| 671 | | "Dimension.OpticalFlow" |
| 672 | | "OpticalFlow" |
| 673 | | "Dimension.CopyAux" |
| 674 | ) |
| 675 | { |
| 676 | let port = default_main_input_port(&node.kind); |
| 677 | if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { |
| 678 | self.collect_missing_loader_jobs( |
| 679 | comp, |
| 680 | src_id, |
| 681 | time, |
| 682 | expr, |
| 683 | use_proxy_clips, |
| 684 | visited, |
| 685 | jobs, |
| 686 | ); |
| 687 | } |
| 688 | return; |
| 689 | } |
| 690 | |
| 691 | if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") { |
| 692 | let next_id = node.macro_output.or_else(|| { |
| 693 | node.connected_node("Input") |
| 694 | .or_else(|| node.connected_node("MainInput1")) |
| 695 | .and_then(|s| comp.find_node(s)) |
| 696 | }); |
| 697 | if let Some(src_id) = next_id { |
| 698 | self.collect_missing_loader_jobs( |
| 699 | comp, |
| 700 | src_id, |
| 701 | time, |
| 702 | expr, |
| 703 | use_proxy_clips, |
| 704 | visited, |
| 705 | jobs, |
| 706 | ); |
| 707 | } |
| 708 | return; |
| 709 | } |
| 710 | |
| 711 | if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") { |
| 712 | let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { |
| 713 | return; |
| 714 | }; |
| 715 | let remapped = match node.kind.as_str() { |
| 716 | "TimeStretcher" => comp.eval_number(node, "SourceTime", time, 0.0, expr), |
| 717 | "TimeSpeed" => { |
| 718 | let speed = comp.eval_number(node, "Speed", time, 1.0, expr); |
| 719 | let delay = comp.eval_number(node, "Delay", time, 0.0, expr); |
| 720 | let g_start = comp.global_range[0] as f64; |
| 721 | let g_end = comp.global_range[1] as f64; |
| 722 | if speed < 0.0 { |
| 723 | ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end) |
| 724 | } else { |
| 725 | g_start + (time - delay - g_start) * speed |
| 726 | } |
| 727 | } |
| 728 | _ => time, |
| 729 | }; |
| 730 | let interp = comp |
| 731 | .eval_number(node, "InterpolateBetweenFrames", time, 1.0, expr) |
| 732 | .round() as i32; |
| 733 | if interp <= 0 { |
| 734 | let snapped = (remapped + 0.5).floor(); |
| 735 | self.collect_missing_loader_jobs( |
| 736 | comp, |
| 737 | src_id, |
| 738 | snapped, |
| 739 | expr, |
| 740 | use_proxy_clips, |
| 741 | visited, |
| 742 | jobs, |
| 743 | ); |
| 744 | return; |
| 745 | } |
| 746 | let f0 = remapped.floor(); |
| 747 | let frac = (remapped - f0) as f32; |
| 748 | if frac > 1e-3 && frac < 1.0 - 1e-3 { |
| 749 | let src_node = comp.node(src_id); |
| 750 | let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow"); |
| 751 | let eval_src_id = if has_optflow { |
| 752 | src_node |
| 753 | .connected_node("Input") |
| 754 | .and_then(|s| comp.find_node(s)) |
| 755 | .unwrap_or(src_id) |
| 756 | } else { |
| 757 | src_id |
| 758 | }; |
| 759 | self.collect_missing_loader_jobs( |
| 760 | comp, |
| 761 | eval_src_id, |
| 762 | f0, |
| 763 | expr, |
| 764 | use_proxy_clips, |
| 765 | visited, |
| 766 | jobs, |
| 767 | ); |
| 768 | self.collect_missing_loader_jobs( |
| 769 | comp, |
| 770 | eval_src_id, |
| 771 | f0 + 1.0, |
| 772 | expr, |
| 773 | use_proxy_clips, |
| 774 | visited, |
| 775 | jobs, |
| 776 | ); |
| 777 | } else { |
| 778 | self.collect_missing_loader_jobs( |
| 779 | comp, |
| 780 | src_id, |
| 781 | remapped, |
| 782 | expr, |
| 783 | use_proxy_clips, |
| 784 | visited, |
| 785 | jobs, |
| 786 | ); |
| 787 | } |
| 788 | return; |
| 789 | } |
| 790 | |
| 791 | if node.kind == "Switch" || node.kind == "Fuse.Switch" { |
| 792 | let is_native_zero_indexed = node.kind == "Switch" |
| 793 | && (node.inputs.contains_key("Source") |
| 794 | || node.inputs.contains_key("Input0") |
| 795 | || !node.inputs.contains_key("Which")); |
| 796 | let src_name = if is_native_zero_indexed { |
| 797 | let source = comp |
| 798 | .eval_number(node, "Source", time, 0.0, expr) |
| 799 | .round() |
| 800 | .max(0.0) as usize; |
| 801 | let port = format!("Input{source}"); |
| 802 | node.connected_node(&port) |
| 803 | .or_else(|| node.connected_node("Input0")) |
| 804 | } else { |
| 805 | let which = comp |
| 806 | .eval_number(node, "Which", time, 1.0, expr) |
| 807 | .round() |
| 808 | .max(1.0) as usize; |
| 809 | let port = format!("Input{which}"); |
| 810 | node.connected_node(&port) |
| 811 | .or_else(|| node.connected_node("Input1")) |
| 812 | }; |
| 813 | if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) { |
| 814 | self.collect_missing_loader_jobs( |
| 815 | comp, |
| 816 | src_id, |
| 817 | time, |
| 818 | expr, |
| 819 | use_proxy_clips, |
| 820 | visited, |
| 821 | jobs, |
| 822 | ); |
| 823 | } |
| 824 | return; |
| 825 | } |
| 826 | |
| 827 | if node.kind == "Fuse.SwitchElse" { |
| 828 | let index = |name: &str, default: f64| { |
| 829 | comp.eval_number(node, name, time, default, expr) |
| 830 | .round() |
| 831 | .max(1.0) as usize |
| 832 | }; |
| 833 | let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| { |
| 834 | node.connected_node(&format!("Input{i}")) |
| 835 | .and_then(|s| comp.find_node(s)) |
| 836 | }); |
| 837 | if let Some(src_id) = picked { |
| 838 | self.collect_missing_loader_jobs( |
| 839 | comp, |
| 840 | src_id, |
| 841 | time, |
| 842 | expr, |
| 843 | use_proxy_clips, |
| 844 | visited, |
| 845 | jobs, |
| 846 | ); |
| 847 | } |
| 848 | return; |
| 849 | } |
| 850 | |
| 851 | if node.kind == "Merge" { |
| 852 | if let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) { |
| 853 | self.collect_missing_loader_jobs( |
| 854 | comp, |
| 855 | bg_id, |
| 856 | time, |
| 857 | expr, |
| 858 | use_proxy_clips, |
| 859 | visited, |
| 860 | jobs, |
| 861 | ); |
| 862 | } |
| 863 | let blend = comp.eval_number(node, "Blend", time, 1.0, expr) as f32; |
| 864 | let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, expr) > 0.5; |
| 865 | let mask_id = resolve_effect_mask_id_for_node(comp, node); |
| 866 | if !(blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some())) { |
| 867 | if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) { |
| 868 | self.collect_missing_loader_jobs( |
| 869 | comp, |
| 870 | fg_id, |
| 871 | time, |
| 872 | expr, |
| 873 | use_proxy_clips, |
| 874 | visited, |
| 875 | jobs, |
| 876 | ); |
| 877 | } |
| 878 | } |
| 879 | if let Some(mid) = mask_id { |
| 880 | self.collect_missing_loader_jobs( |
| 881 | comp, |
| 882 | mid, |
| 883 | time, |
| 884 | expr, |
| 885 | use_proxy_clips, |
| 886 | visited, |
| 887 | jobs, |
| 888 | ); |
| 889 | } |
| 890 | return; |
| 891 | } |
| 892 | |
| 893 | if node.kind == "Loader" { |
| 894 | if let Some(clip) = node.clips.first() { |
| 895 | let frame_i = time.round() as i64; |
| 896 | let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5; |
| 897 | let exr_channels = [ |
| 898 | node.static_str("Clip1.OpenEXRFormat.RedName"), |
| 899 | node.static_str("Clip1.OpenEXRFormat.GreenName"), |
| 900 | node.static_str("Clip1.OpenEXRFormat.BlueName"), |
| 901 | node.static_str("Clip1.OpenEXRFormat.AlphaName"), |
| 902 | ]; |
| 903 | let mut effective_clip = clip.clone(); |
| 904 | if node.inputs.contains_key("GlobalIn") { |
| 905 | effective_clip.global_start = comp |
| 906 | .eval_number(node, "GlobalIn", time, effective_clip.global_start as f64, expr) |
| 907 | .round() as i64; |
| 908 | } |
| 909 | if node.inputs.contains_key("GlobalOut") { |
| 910 | effective_clip.global_end = comp |
| 911 | .eval_number(node, "GlobalOut", time, effective_clip.global_end as f64, expr) |
| 912 | .round() as i64; |
| 913 | } |
| 914 | if node.inputs.contains_key("Loop") { |
| 915 | effective_clip.loop_clip = comp.eval_number( |
| 916 | node, |
| 917 | "Loop", |
| 918 | time, |
| 919 | if effective_clip.loop_clip { 1.0 } else { 0.0 }, |
| 920 | expr, |
| 921 | ) > 0.5; |
| 922 | } |
| 923 | if node.inputs.contains_key("Reverse") { |
| 924 | effective_clip.reverse = comp.eval_number( |
| 925 | node, |
| 926 | "Reverse", |
| 927 | time, |
| 928 | if effective_clip.reverse { 1.0 } else { 0.0 }, |
| 929 | expr, |
| 930 | ) > 0.5; |
| 931 | } |
| 932 | if use_proxy_clips { |
| 933 | let proxy_candidate = node |
| 934 | .static_str("ProxyFilename") |
| 935 | .filter(|s| !s.trim().is_empty()) |
| 936 | .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty())); |
| 937 | if let Some(proxy_name) = proxy_candidate { |
| 938 | let mut proxy_clip = effective_clip.clone(); |
| 939 | proxy_clip.filename = proxy_name.to_owned(); |
| 940 | if resolve_clip_path(&proxy_clip, frame_i).is_some_and(|p| path_exists(&p)) { |
| 941 | effective_clip = proxy_clip; |
| 942 | } |
| 943 | } |
| 944 | } |
| 945 | let out_of_range = effective_clip.global_end >= effective_clip.global_start |
| 946 | && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0) |
| 947 | || (!effective_clip.loop_clip |
| 948 | && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0))); |
| 949 | if !out_of_range { |
| 950 | let base = Path::new(&effective_clip.filename); |
| 951 | if is_video_path(base) { |
| 952 | if base.exists() && video_frame_in_range(&effective_clip, frame_i) { |
| 953 | let need_decode = match self.video_decoders.get(base) { |
| 954 | Some(entry) => entry.decoder.as_ref().is_some_and(|dec| { |
| 955 | let idx = compute_video_frame_idx( |
| 956 | &effective_clip, |
| 957 | frame_i, |
| 958 | dec.info().nb_frames, |
| 959 | ); |
| 960 | let cache_key = ImageCacheKey { |
| 961 | path: base.to_path_buf(), |
| 962 | frame_idx: idx, |
| 963 | post_multiply: post_mult, |
| 964 | exr_channels: [None, None, None, None], |
| 965 | }; |
| 966 | !self.images.contains_key(&cache_key) |
| 967 | }), |
| 968 | None => true, |
| 969 | }; |
| 970 | if need_decode { |
| 971 | jobs.videos |
| 972 | .entry(base.to_path_buf()) |
| 973 | .or_default() |
| 974 | .push(VideoFrameRequest { |
| 975 | clip: effective_clip, |
| 976 | frame_i, |
| 977 | post_multiply: post_mult, |
| 978 | }); |
| 979 | } |
| 980 | } |
| 981 | } else if let Some(resolved) = resolve_clip_path(&effective_clip, frame_i) { |
| 982 | let is_exr = is_exr_path(&resolved); |
| 983 | let key_channels = if is_exr { |
| 984 | [ |
| 985 | normalize_channel_opt(exr_channels[0]), |
| 986 | normalize_channel_opt(exr_channels[1]), |
| 987 | normalize_channel_opt(exr_channels[2]), |
| 988 | normalize_channel_opt(exr_channels[3]), |
| 989 | ] |
| 990 | } else { |
| 991 | [None, None, None, None] |
| 992 | }; |
| 993 | let cache_key = ImageCacheKey { |
| 994 | path: resolved, |
| 995 | frame_idx: -1, |
| 996 | post_multiply: post_mult && !is_exr, |
| 997 | exr_channels: key_channels, |
| 998 | }; |
| 999 | if !self.images.contains_key(&cache_key) |
| 1000 | && jobs.seen_raster.insert(cache_key.clone()) |
| 1001 | { |
| 1002 | jobs.raster.push(PreloadJob { cache_key, is_exr }); |
| 1003 | } |
| 1004 | } |
| 1005 | } |
| 1006 | } |
| 1007 | if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) { |
| 1008 | self.collect_missing_loader_jobs( |
| 1009 | comp, |
| 1010 | mid, |
| 1011 | time, |
| 1012 | expr, |
| 1013 | use_proxy_clips, |
| 1014 | visited, |
| 1015 | jobs, |
| 1016 | ); |
| 1017 | } |
| 1018 | return; |
| 1019 | } |
| 1020 | |
| 1021 | // General node: traverse all wired upstream node inputs and inherited EffectMask. |
| 1022 | let mut child_ids = Vec::new(); |
| 1023 | for binding in node.inputs.values() { |
| 1024 | if let Some(src) = binding.source_op.as_deref() { |
| 1025 | if let Some(cid) = comp.find_node(src) { |
| 1026 | if !child_ids.contains(&cid) { |
| 1027 | child_ids.push(cid); |
| 1028 | } |
| 1029 | } |
| 1030 | } |
| 1031 | } |
| 1032 | if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) { |
| 1033 | if !child_ids.contains(&mid) { |
| 1034 | child_ids.push(mid); |
| 1035 | } |
| 1036 | } |
| 1037 | for cid in child_ids { |
| 1038 | self.collect_missing_loader_jobs( |
| 1039 | comp, |
| 1040 | cid, |
| 1041 | time, |
| 1042 | expr, |
| 1043 | use_proxy_clips, |
| 1044 | visited, |
| 1045 | jobs, |
| 1046 | ); |
| 1047 | } |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool { |
| 1052 | if clip.global_end >= clip.global_start |
| 1053 | && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start) |
| 1054 | { |
| 1055 | let min_f = clip.global_start - clip.extend_first.max(0); |
| 1056 | let max_f = clip.global_end + clip.extend_last.max(0); |
| 1057 | if frame < min_f || (!clip.loop_clip && frame > max_f) { |
| 1058 | return false; |
| 1059 | } |
| 1060 | } |
| 1061 | true |
| 1062 | } |
| 1063 | |
| 1064 | fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 { |
| 1065 | let len = clip.length.unwrap_or(nb_frames.max(1)).max(1); |
| 1066 | let trim_in = clip.trim_in.clamp(0, len - 1); |
| 1067 | let trim_out = if clip.trim_out > 0 { |
| 1068 | clip.trim_out.clamp(trim_in, len - 1) |
| 1069 | } else { |
| 1070 | len - 1 |
| 1071 | }; |
| 1072 | let span = (trim_out - trim_in + 1).max(1); |
| 1073 | let rel = if clip.loop_clip { |
| 1074 | (frame - clip.global_start).max(0).rem_euclid(span) |
| 1075 | } else { |
| 1076 | (frame - clip.global_start).clamp(0, span - 1) |
| 1077 | }; |
| 1078 | if clip.reverse { trim_out - rel } else { trim_in + rel } |
| 1079 | } |
| 1080 | |
| 1081 | #[cfg(not(target_arch = "wasm32"))] |
| 1082 | #[derive(Default)] |
| 1083 | struct MissingJobs { |
| 1084 | raster: Vec<PreloadJob>, |
| 1085 | seen_raster: HashSet<ImageCacheKey>, |
| 1086 | videos: HashMap<PathBuf, Vec<VideoFrameRequest>>, |
| 1087 | } |
| 1088 | |
| 1089 | #[cfg(not(target_arch = "wasm32"))] |
| 1090 | impl MissingJobs { |
| 1091 | fn total_units(&self) -> usize { |
| 1092 | self.raster.len() + self.videos.len() |
| 1093 | } |
| 1094 | } |
| 1095 | |
| 1096 | #[cfg(not(target_arch = "wasm32"))] |
| 1097 | struct VideoFrameRequest { |
| 1098 | clip: ClipSpec, |
| 1099 | frame_i: i64, |
| 1100 | post_multiply: bool, |
| 1101 | } |
| 1102 | |
| 1103 | #[cfg(not(target_arch = "wasm32"))] |
| 1104 | struct VideoDecodeTask { |
| 1105 | path: PathBuf, |
| 1106 | decoder: Option<Box<dyn VideoDecoder>>, |
| 1107 | requests: Vec<VideoFrameRequest>, |
| 1108 | } |
| 1109 | |
| 1110 | #[cfg(not(target_arch = "wasm32"))] |
| 1111 | struct PreloadJob { |
| 1112 | cache_key: ImageCacheKey, |
| 1113 | is_exr: bool, |
| 1114 | } |
| 1115 | |
| 1116 | #[cfg(not(target_arch = "wasm32"))] |
| 1117 | fn decode_job(job: &PreloadJob, allow_parallel_premult: bool) -> Option<DecodedImage> { |
| 1118 | if job.is_exr { |
| 1119 | decode_exr_rgba( |
| 1120 | &job.cache_key.path, |
| 1121 | job.cache_key.exr_channels[0].as_deref(), |
| 1122 | job.cache_key.exr_channels[1].as_deref(), |
| 1123 | job.cache_key.exr_channels[2].as_deref(), |
| 1124 | job.cache_key.exr_channels[3].as_deref(), |
| 1125 | false, |
| 1126 | ) |
| 1127 | } else { |
| 1128 | decode_raster_image( |
| 1129 | &job.cache_key.path, |
| 1130 | job.cache_key.post_multiply, |
| 1131 | allow_parallel_premult, |
| 1132 | ) |
| 1133 | } |
| 1134 | } |
| 1135 | |
| 1136 | #[cfg(not(target_arch = "wasm32"))] |
| 1137 | fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option<NodeId> { |
| 1138 | if let Some(id) = node.connected_node("EffectMask").and_then(|s| comp.find_node(s)) { |
| 1139 | return Some(id); |
| 1140 | } |
| 1141 | let has_explicit_mask_entry = |n: &Node| -> bool { |
| 1142 | n.raw |
| 1143 | .get_table("Inputs") |
| 1144 | .and_then(|t| t.get("EffectMask")) |
| 1145 | .is_some() |
| 1146 | }; |
| 1147 | if has_explicit_mask_entry(node) { |
| 1148 | return None; |
| 1149 | } |
| 1150 | let mut visited = HashSet::new(); |
| 1151 | visited.insert(node.id); |
| 1152 | let mut cur = node; |
| 1153 | for _ in 0..8 { |
| 1154 | let master_name = cur.raw.get_str("SourceOp")?; |
| 1155 | let mid = comp.find_node(master_name)?; |
| 1156 | if !visited.insert(mid) { |
| 1157 | break; |
| 1158 | } |
| 1159 | let master = comp.node(mid); |
| 1160 | if let Some(mask_id) = master.connected_node("EffectMask").and_then(|s| comp.find_node(s)) { |
| 1161 | return Some(mask_id); |
| 1162 | } |
| 1163 | if has_explicit_mask_entry(master) { |
| 1164 | return None; |
| 1165 | } |
| 1166 | cur = master; |
| 1167 | } |
| 1168 | None |
| 379 | 1169 | } |
| 380 | 1170 | |
| 381 | 1171 | /// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`. |
| ... | ... | @@ -1022,4 +1812,253 @@ mod tests { |
| 1022 | 1812 | assert!(!put(&mut files, "a", 7)); |
| 1023 | 1813 | assert_eq!(files.iter().map(|f| f.bytes.len()).sum::<usize>(), 10); |
| 1024 | 1814 | } |
| 1815 | |
| 1816 | #[test] |
| 1817 | fn media_budget_scaling_matches_ram_tiers() { |
| 1818 | const GIB: u64 = 1024 * 1024 * 1024; |
| 1819 | assert_eq!(media_cache_budget_mb_for_total_bytes(8 * GIB), 512); |
| 1820 | assert_eq!(media_cache_budget_mb_for_total_bytes(16 * GIB), 1024); |
| 1821 | assert_eq!(media_cache_budget_mb_for_total_bytes(32 * GIB), 2048); |
| 1822 | assert_eq!(media_cache_budget_mb_for_total_bytes(64 * GIB), 4096); |
| 1823 | assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192); |
| 1824 | let default_cache = MediaCache::default(); |
| 1825 | assert_eq!( |
| 1826 | default_cache.budget_bytes, |
| 1827 | default_media_cache_budget_mb().saturating_mul(1024 * 1024) |
| 1828 | ); |
| 1829 | let explicit = MediaCache::with_budget_mb(32); |
| 1830 | assert_eq!(explicit.budget_bytes, 32 * 1024 * 1024); |
| 1831 | } |
| 1832 | |
| 1833 | #[test] |
| 1834 | fn parallel_post_multiply_matches_scalar_across_large_buffer() { |
| 1835 | let len = 4 * 1024 * 1024 * 4 + 64; // > 4 MP threshold |
| 1836 | let mut scalar = vec![0u8; len]; |
| 1837 | for (i, px) in scalar.chunks_exact_mut(4).enumerate() { |
| 1838 | px[0] = ((i * 7) % 256) as u8; |
| 1839 | px[1] = ((i * 13) % 256) as u8; |
| 1840 | px[2] = ((i * 29) % 256) as u8; |
| 1841 | px[3] = (i % 256) as u8; |
| 1842 | } |
| 1843 | let mut parallel = scalar.clone(); |
| 1844 | exr::apply_post_multiply_rgba8_parallel(&mut scalar, false); |
| 1845 | exr::apply_post_multiply_rgba8_parallel(&mut parallel, true); |
| 1846 | assert_eq!(scalar, parallel); |
| 1847 | } |
| 1848 | |
| 1849 | #[cfg(not(target_arch = "wasm32"))] |
| 1850 | #[test] |
| 1851 | fn preload_frame_loaders_and_prefetch_frames_populate_cache_in_parallel() { |
| 1852 | let dir = std::env::temp_dir().join(format!("fission_preload_test_{}", std::process::id())); |
| 1853 | let _ = std::fs::remove_dir_all(&dir); |
| 1854 | std::fs::create_dir_all(&dir).unwrap(); |
| 1855 | |
| 1856 | let p_bg = dir.join("bg.png"); |
| 1857 | let p_fg0 = dir.join("fg_0000.png"); |
| 1858 | let p_fg1 = dir.join("fg_0001.png"); |
| 1859 | let p_fg2 = dir.join("fg_0002.png"); |
| 1860 | let p_pruned = dir.join("pruned.png"); |
| 1861 | image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 40, 60, 255])).save(&p_bg).unwrap(); |
| 1862 | image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 100, 50, 128])).save(&p_fg0).unwrap(); |
| 1863 | image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 200, 50, 255])).save(&p_fg1).unwrap(); |
| 1864 | image::RgbaImage::from_pixel(4, 4, image::Rgba([50, 0, 200, 255])).save(&p_fg2).unwrap(); |
| 1865 | image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 9, 9, 255])).save(&p_pruned).unwrap(); |
| 1866 | |
| 1867 | let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); |
| 1868 | let comp_src = format!( |
| 1869 | r#"Composition {{ |
| 1870 | CurrentTime = 0, |
| 1871 | RenderRange = {{ 0, 2 }}, |
| 1872 | GlobalRange = {{ 0, 2 }}, |
| 1873 | Tools = ordered() {{ |
| 1874 | BgLoader = Loader {{ |
| 1875 | Clips = {{ |
| 1876 | Clip {{ |
| 1877 | ID = "Clip1", |
| 1878 | Filename = "{}", |
| 1879 | FormatID = "PNGFormat", |
| 1880 | Length = 1, |
| 1881 | GlobalStart = 0, |
| 1882 | GlobalEnd = 2, |
| 1883 | }}, |
| 1884 | }}, |
| 1885 | }}, |
| 1886 | FgLoader = Loader {{ |
| 1887 | Clips = {{ |
| 1888 | Clip {{ |
| 1889 | ID = "Clip1", |
| 1890 | Filename = "{}", |
| 1891 | FormatID = "PNGFormat", |
| 1892 | StartFrame = 0, |
| 1893 | Length = 3, |
| 1894 | GlobalStart = 0, |
| 1895 | GlobalEnd = 2, |
| 1896 | }}, |
| 1897 | }}, |
| 1898 | Inputs = {{ |
| 1899 | ["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = 1, }}, |
| 1900 | }}, |
| 1901 | }}, |
| 1902 | PrunedLoader = Loader {{ |
| 1903 | Clips = {{ |
| 1904 | Clip {{ |
| 1905 | ID = "Clip1", |
| 1906 | Filename = "{}", |
| 1907 | FormatID = "PNGFormat", |
| 1908 | Length = 1, |
| 1909 | GlobalStart = 0, |
| 1910 | GlobalEnd = 2, |
| 1911 | }}, |
| 1912 | }}, |
| 1913 | }}, |
| 1914 | PrunedMerge = Merge {{ |
| 1915 | Inputs = {{ |
| 1916 | Blend = Input {{ Value = 0, }}, |
| 1917 | Background = Input {{ SourceOp = "BgLoader", Source = "Output", }}, |
| 1918 | Foreground = Input {{ SourceOp = "PrunedLoader", Source = "Output", }}, |
| 1919 | }}, |
| 1920 | }}, |
| 1921 | MainMerge = Merge {{ |
| 1922 | Inputs = {{ |
| 1923 | Background = Input {{ SourceOp = "PrunedMerge", Source = "Output", }}, |
| 1924 | Foreground = Input {{ SourceOp = "FgLoader", Source = "Output", }}, |
| 1925 | }}, |
| 1926 | }}, |
| 1927 | }}, |
| 1928 | }}"#, |
| 1929 | esc(&p_bg), |
| 1930 | esc(&p_fg0), |
| 1931 | esc(&p_pruned), |
| 1932 | ); |
| 1933 | let comp = Comp::from_fusion_str(&comp_src).expect("parse preload comp"); |
| 1934 | let target = comp.find_node("MainMerge").expect("MainMerge"); |
| 1935 | let expr = model::ExprEngine::new(); |
| 1936 | let mut cache = MediaCache::new(64); |
| 1937 | |
| 1938 | cache.preload_frame_loaders(&comp, target, 0.0, &expr); |
| 1939 | // BgLoader + FgLoader(f0) are cached; PrunedLoader is skipped because PrunedMerge Blend == 0. |
| 1940 | assert_eq!(cache.entry_count(), 2); |
| 1941 | |
| 1942 | let bg_clip = comp.node(comp.find_node("BgLoader").unwrap()).clips[0].clone(); |
| 1943 | let fg_clip = comp.node(comp.find_node("FgLoader").unwrap()).clips[0].clone(); |
| 1944 | let (_, _, bg_img, bg_from_disk) = cache.load_clip(&bg_clip, 0, false, [None; 4]).unwrap(); |
| 1945 | let (_, _, fg0_img, fg0_from_disk) = cache.load_clip(&fg_clip, 0, true, [None; 4]).unwrap(); |
| 1946 | assert!(!bg_from_disk); |
| 1947 | assert!(!fg0_from_disk); |
| 1948 | assert_eq!(&bg_img.rgba[..4], &[20, 40, 60, 255]); |
| 1949 | assert_eq!(&fg0_img.rgba[..4], &[100, 50, 25, 128]); |
| 1950 | |
| 1951 | // Prefetch frames 1 and 2 ahead of playback. |
| 1952 | cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr); |
| 1953 | assert_eq!(cache.entry_count(), 4); |
| 1954 | let (_, _, fg1_img, fg1_from_disk) = cache.load_clip(&fg_clip, 1, true, [None; 4]).unwrap(); |
| 1955 | let (_, _, fg2_img, fg2_from_disk) = cache.load_clip(&fg_clip, 2, true, [None; 4]).unwrap(); |
| 1956 | assert!(!fg1_from_disk); |
| 1957 | assert!(!fg2_from_disk); |
| 1958 | assert_eq!(&fg1_img.rgba[..4], &[0, 200, 50, 255]); |
| 1959 | assert_eq!(&fg2_img.rgba[..4], &[50, 0, 200, 255]); |
| 1960 | |
| 1961 | let _ = std::fs::remove_dir_all(&dir); |
| 1962 | } |
| 1963 | |
| 1964 | #[cfg(not(target_arch = "wasm32"))] |
| 1965 | #[test] |
| 1966 | fn preload_frame_loaders_decodes_multiple_videos_in_parallel() { |
| 1967 | let dir = std::env::temp_dir().join(format!("fission_preload_vid_{}", std::process::id())); |
| 1968 | let _ = std::fs::remove_dir_all(&dir); |
| 1969 | std::fs::create_dir_all(&dir).unwrap(); |
| 1970 | |
| 1971 | let mk_mp4 = |name: &str, color: &str| { |
| 1972 | let p = dir.join(name); |
| 1973 | let ok = Command::new("ffmpeg") |
| 1974 | .args([ |
| 1975 | "-y", |
| 1976 | "-v", |
| 1977 | "error", |
| 1978 | "-f", |
| 1979 | "lavfi", |
| 1980 | "-i", |
| 1981 | &format!("color=c={color}:size=32x32:rate=24:duration=0.2"), |
| 1982 | "-c:v", |
| 1983 | "libx264", |
| 1984 | "-pix_fmt", |
| 1985 | "yuv420p", |
| 1986 | ]) |
| 1987 | .arg(&p) |
| 1988 | .status() |
| 1989 | .is_ok_and(|s| s.success()); |
| 1990 | (p, ok) |
| 1991 | }; |
| 1992 | let (v1, ok1) = mk_mp4("v1.mp4", "red"); |
| 1993 | let (v2, ok2) = mk_mp4("v2.mp4", "blue"); |
| 1994 | if !(ok1 && ok2) { |
| 1995 | let _ = std::fs::remove_dir_all(&dir); |
| 1996 | return; |
| 1997 | } |
| 1998 | |
| 1999 | let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); |
| 2000 | let comp_src = format!( |
| 2001 | r#"Composition {{ |
| 2002 | CurrentTime = 0, |
| 2003 | RenderRange = {{ 0, 3 }}, |
| 2004 | GlobalRange = {{ 0, 3 }}, |
| 2005 | Tools = ordered() {{ |
| 2006 | V1 = Loader {{ |
| 2007 | Clips = {{ |
| 2008 | Clip {{ |
| 2009 | ID = "Clip1", |
| 2010 | Filename = "{}", |
| 2011 | FormatID = "QuickTimeMovies", |
| 2012 | Length = 4, |
| 2013 | GlobalStart = 0, |
| 2014 | GlobalEnd = 3, |
| 2015 | }}, |
| 2016 | }}, |
| 2017 | }}, |
| 2018 | V2 = Loader {{ |
| 2019 | Clips = {{ |
| 2020 | Clip {{ |
| 2021 | ID = "Clip1", |
| 2022 | Filename = "{}", |
| 2023 | FormatID = "QuickTimeMovies", |
| 2024 | Length = 4, |
| 2025 | GlobalStart = 0, |
| 2026 | GlobalEnd = 3, |
| 2027 | }}, |
| 2028 | }}, |
| 2029 | }}, |
| 2030 | M = Merge {{ |
| 2031 | Inputs = {{ |
| 2032 | Background = Input {{ SourceOp = "V1", Source = "Output", }}, |
| 2033 | Foreground = Input {{ SourceOp = "V2", Source = "Output", }}, |
| 2034 | }}, |
| 2035 | }}, |
| 2036 | }}, |
| 2037 | }}"#, |
| 2038 | esc(&v1), |
| 2039 | esc(&v2), |
| 2040 | ); |
| 2041 | let comp = Comp::from_fusion_str(&comp_src).expect("parse video preload comp"); |
| 2042 | let target = comp.find_node("M").expect("M"); |
| 2043 | let expr = model::ExprEngine::new(); |
| 2044 | let mut cache = MediaCache::new(64); |
| 2045 | |
| 2046 | cache.preload_frame_loaders(&comp, target, 0.0, &expr); |
| 2047 | assert_eq!(cache.video_decoder_count(), 2); |
| 2048 | assert_eq!(cache.entry_count(), 2); |
| 2049 | |
| 2050 | let c1 = comp.node(comp.find_node("V1").unwrap()).clips[0].clone(); |
| 2051 | let c2 = comp.node(comp.find_node("V2").unwrap()).clips[0].clone(); |
| 2052 | let (_, _, img1, disk1) = cache.load_clip(&c1, 0, false, [None; 4]).unwrap(); |
| 2053 | let (_, _, img2, disk2) = cache.load_clip(&c2, 0, false, [None; 4]).unwrap(); |
| 2054 | assert!(!disk1); |
| 2055 | assert!(!disk2); |
| 2056 | assert!(img1.rgba[0] > 200 && img1.rgba[2] < 40); |
| 2057 | assert!(img2.rgba[2] > 200 && img2.rgba[0] < 40); |
| 2058 | |
| 2059 | cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr); |
| 2060 | assert_eq!(cache.entry_count(), 6); |
| 2061 | |
| 2062 | let _ = std::fs::remove_dir_all(&dir); |
| 2063 | } |
| 1025 | 2064 | } |