1//! Media loading (PNG/JPG/EXR/TIFF stills & numbered image sequences) and
2//! CPU rasterizers (`TextPlus` via `text_engine`, `PolylineMask` via `zeno`).
3
4mod exr;
5mod png;
6mod prefetch;
7mod raster;
8#[cfg(test)]
9mod tests;
10mod video;
11
12pub use exr::f32_to_f16_bits;
13#[cfg(not(target_arch = "wasm32"))]
14pub use prefetch::MediaPrefetchHandle;
15pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus};
16#[cfg(target_os = "macos")]
17pub use video::AvFoundationDecoder;
18pub use video::{
19 DecodedVideoFrame, FfmpegDecoder, Nv12Frame, VideoDecoder, VideoInfo, YuvMatrix,
20 open_video_decoder,
21};
22use exr::{
23 apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path,
24 normalize_channel_opt,
25};
26use png::decode_raster_image;
27#[cfg(test)]
28use png::{PngDecodeOutcome, decode_png_bytes, decode_raster_bytes};
29#[cfg(not(target_arch = "wasm32"))]
30use prefetch::PrefetchQueue;
31use video::is_video_path;
32
33use crate::text_engine;
34#[cfg(not(target_arch = "wasm32"))]
35use model::{Node, default_main_input_port};
36use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint};
37#[cfg(not(target_arch = "wasm32"))]
38use std::collections::{HashSet, VecDeque};
39use std::collections::HashMap;
40use std::path::{Path, PathBuf};
41use std::process::Command;
42#[cfg(not(target_arch = "wasm32"))]
43use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
44#[cfg(not(target_arch = "wasm32"))]
45use std::sync::{Condvar, Weak, mpsc};
46use std::sync::{Arc, Mutex, RwLock};
47
48#[derive(Clone)]
49pub struct DecodedImage {
50 pub size: [u32; 2],
51 /// Premultiplied RGBA8 pixels, top-down.
52 pub rgba: Arc<Vec<u8>>,
53 /// Optional unclamped linear HDR RGBA16F bit-packed pixels (`[r, g, b, a, ...]`),
54 /// pre-converted once at EXR decode for zero-copy `Rgba16Float` GPU upload.
55 pub rgba_f16: Option<Arc<Vec<u16>>>,
56 /// Optional unclamped linear HDR RGBA32F pixels (`[r, g, b, a, ...]`, top-down),
57 /// populated for OpenEXR images to preserve HDR highlights `> 1.0` and negative values.
58 pub rgba_f32: Option<Arc<Vec<f32>>>,
59 /// Optional single-channel `f32` Z-depth buffer (`[w * h]`, top-down), populated when
60 /// an OpenEXR file contains a `Z` channel (`"Z"`, `"z"`, or `"*.Z"`).
61 pub z_f32: Option<Arc<Vec<f32>>>,
62}
63
64impl DecodedImage {
65 pub fn byte_size(&self) -> u64 {
66 let u8_bytes = self.rgba.len() as u64;
67 let f16_bytes = self
68 .rgba_f16
69 .as_ref()
70 .map_or(0, |v| (v.len() * std::mem::size_of::<u16>()) as u64);
71 let f32_bytes = self
72 .rgba_f32
73 .as_ref()
74 .map_or(0, |v| (v.len() * std::mem::size_of::<f32>()) as u64);
75 let z_bytes = self
76 .z_f32
77 .as_ref()
78 .map_or(0, |v| (v.len() * std::mem::size_of::<f32>()) as u64);
79 u8_bytes + f16_bytes + f32_bytes + z_bytes
80 }
81}
82
83/// Internal cached media payload: either decoded RGBA/HDR image buffers or a compact
84/// native NV12 video frame (`~2.67×` smaller than 4K RGBA) uploaded directly to GPU.
85#[derive(Clone)]
86pub(crate) enum CachedMedia {
87 Rgba(DecodedImage),
88 Nv12(Arc<Nv12Frame>),
89}
90
91impl CachedMedia {
92 pub(crate) fn size(&self) -> [u32; 2] {
93 match self {
94 Self::Rgba(img) => img.size,
95 Self::Nv12(frame) => frame.display_size,
96 }
97 }
98
99 pub(crate) fn byte_size(&self) -> u64 {
100 match self {
101 Self::Rgba(img) => img.byte_size(),
102 Self::Nv12(frame) => frame.byte_size(),
103 }
104 }
105
106 pub(crate) fn into_decoded_image(self) -> DecodedImage {
107 match self {
108 Self::Rgba(img) => img,
109 Self::Nv12(frame) => DecodedImage {
110 size: frame.display_size,
111 rgba: Arc::new(frame.to_rgba8()),
112 rgba_f16: None,
113 rgba_f32: None,
114 z_f32: None,
115 },
116 }
117 }
118}
119
120const MAX_VIDEO_DECODERS: usize = 12;
121
122struct VirtualFile {
123 parts: Vec<String>,
124 bytes: Arc<[u8]>,
125}
126
127/// In-memory files that shadow the filesystem for still and sequence loading, since `wasm32` has no `std::fs`.
128static VIRTUAL_FILES: RwLock<Vec<VirtualFile>> = RwLock::new(Vec::new());
129
130/// Total bytes registered virtual files may hold, so dropping a huge folder cannot exhaust the tab.
131const MAX_VIRTUAL_BYTES: usize = 512 * 1024 * 1024;
132
133/// `path`'s components with `.`, empty and resolved `..` segments removed.
134fn path_parts(path: &Path) -> Vec<String> {
135 let mut parts: Vec<String> = Vec::new();
136 for part in path.to_string_lossy().split(['/', '\\']) {
137 match part {
138 "" | "." => {}
139 ".." => {
140 parts.pop();
141 }
142 _ => parts.push(part.to_owned()),
143 }
144 }
145 parts
146}
147
148/// The registered file whose path shares the most trailing components with `want`, so a comp's
149/// absolute `Loader` path still finds a file dropped under a relative one. Exact case wins over
150/// case-insensitive; a tie (`/A/bg.png` vs `/B/bg.png` for `bg.png`) matches nothing.
151fn find_virtual<'a>(files: &'a [VirtualFile], want: &[String]) -> Option<&'a VirtualFile> {
152 let exact = |a: &String, b: &String| a == b;
153 let folded = |a: &String, b: &String| a.to_lowercase() == b.to_lowercase();
154 [&exact as &dyn Fn(&String, &String) -> bool, &folded].into_iter().find_map(|same| {
155 let shared = |f: &VirtualFile| f.parts.iter().rev().zip(want.iter().rev()).take_while(|(a, b)| same(a, b)).count();
156 let best = files.iter().map(shared).max().filter(|&n| n > 0)?;
157 let mut tied = files.iter().filter(|f| shared(f) == best);
158 match (tied.next(), tied.next()) {
159 (Some(file), None) => Some(Some(file)),
160 _ => Some(None),
161 }
162 })?
163}
164
165fn virtual_bytes(path: &Path) -> Option<Arc<[u8]>> {
166 let files = VIRTUAL_FILES.read().ok()?;
167 if files.is_empty() {
168 return None;
169 }
170 find_virtual(&files, &path_parts(path)).map(|f| Arc::clone(&f.bytes))
171}
172
173/// Adds or replaces `parts`, refusing when `files` would then hold more than `cap` bytes.
174fn insert_capped(files: &mut Vec<VirtualFile>, cap: usize, parts: Vec<String>, bytes: Arc<[u8]>) -> bool {
175 let held: usize = files.iter().filter(|f| f.parts != parts).map(|f| f.bytes.len()).sum();
176 if held.saturating_add(bytes.len()) > cap {
177 return false;
178 }
179 match files.iter_mut().find(|f| f.parts == parts) {
180 Some(existing) => existing.bytes = bytes,
181 None => files.push(VirtualFile { parts, bytes }),
182 }
183 true
184}
185
186fn path_exists(path: &Path) -> bool {
187 virtual_bytes(path).is_some() || path.exists()
188}
189
190pub(crate) fn media_cache_budget_mb_for_total_bytes(total_bytes: u64) -> u64 {
191 let gib = total_bytes / (1024 * 1024 * 1024);
192 if gib >= 128 {
193 8 * 1024
194 } else if gib >= 64 {
195 4 * 1024
196 } else if gib >= 32 {
197 2 * 1024
198 } else if gib >= 16 {
199 1024
200 } else {
201 512
202 }
203}
204
205/// Returns the default `MediaCache` budget in MiB scaled to host physical RAM.
206pub fn default_media_cache_budget_mb() -> u64 {
207 media_cache_budget_mb_for_total_bytes(crate::ram_cache::system_memory_bytes())
208}
209
210#[derive(Clone, Debug, PartialEq, Eq, Hash)]
211struct ImageCacheKey {
212 path: PathBuf,
213 frame_idx: i64,
214 post_multiply: bool,
215 exr_channels: [Option<String>; 4],
216}
217
218struct VideoDecoderSlot {
219 info: VideoInfo,
220 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,
221 last_used: u64,
222}
223
224struct MediaState {
225 images: HashMap<ImageCacheKey, CachedMedia>,
226 video_decoders: HashMap<PathBuf, VideoDecoderSlot>,
227 total_bytes: u64,
228 budget_bytes: u64,
229 lru: HashMap<ImageCacheKey, u64>,
230 tick: u64,
231 generation: u64,
232 #[cfg(not(target_arch = "wasm32"))]
233 in_flight: HashSet<ImageCacheKey>,
234 #[cfg(not(target_arch = "wasm32"))]
235 opening_videos: HashSet<PathBuf>,
236 #[cfg(not(target_arch = "wasm32"))]
237 known_existing_paths: HashSet<PathBuf>,
238 #[cfg(not(target_arch = "wasm32"))]
239 speculative_bytes_since_seq: u64,
240 #[cfg(not(target_arch = "wasm32"))]
241 speculative_count_since_seq: u64,
242 #[cfg(not(target_arch = "wasm32"))]
243 last_speculative_bytes: u64,
244 #[cfg(not(target_arch = "wasm32"))]
245 last_prefetch_seq: Option<usize>,
246}
247
248impl MediaState {
249 fn new(budget_bytes: u64) -> Self {
250 Self {
251 images: HashMap::new(),
252 video_decoders: HashMap::new(),
253 total_bytes: 0,
254 budget_bytes,
255 lru: HashMap::new(),
256 tick: 0,
257 generation: 0,
258 #[cfg(not(target_arch = "wasm32"))]
259 in_flight: HashSet::new(),
260 #[cfg(not(target_arch = "wasm32"))]
261 opening_videos: HashSet::new(),
262 #[cfg(not(target_arch = "wasm32"))]
263 known_existing_paths: HashSet::new(),
264 #[cfg(not(target_arch = "wasm32"))]
265 speculative_bytes_since_seq: 0,
266 #[cfg(not(target_arch = "wasm32"))]
267 speculative_count_since_seq: 0,
268 #[cfg(not(target_arch = "wasm32"))]
269 last_speculative_bytes: 0,
270 #[cfg(not(target_arch = "wasm32"))]
271 last_prefetch_seq: None,
272 }
273 }
274
275 fn record_existing_path(&mut self, path: &Path) {
276 #[cfg(not(target_arch = "wasm32"))]
277 {
278 if self.known_existing_paths.len() > 8192 {
279 self.known_existing_paths.clear();
280 }
281 self.known_existing_paths.insert(path.to_path_buf());
282 }
283 #[cfg(target_arch = "wasm32")]
284 let _ = path;
285 }
286
287 fn evict_existing_path(&mut self, path: &Path) {
288 #[cfg(not(target_arch = "wasm32"))]
289 self.known_existing_paths.remove(path);
290 #[cfg(target_arch = "wasm32")]
291 let _ = path;
292 }
293
294 #[cfg(not(target_arch = "wasm32"))]
295 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
296 self.insert_cached_media(cache_key, CachedMedia::Rgba(decoded));
297 }
298
299 fn insert_cached_media(&mut self, cache_key: ImageCacheKey, media: CachedMedia) {
300 let bytes = media.byte_size();
301 self.tick += 1;
302 if let Some(prev) = self.images.insert(cache_key.clone(), media) {
303 self.total_bytes = self.total_bytes.saturating_sub(prev.byte_size());
304 }
305 self.lru.insert(cache_key, self.tick);
306 self.total_bytes += bytes;
307
308 while self.total_bytes > self.budget_bytes && self.images.len() > 2 {
309 let Some(oldest) = self.lru.iter().min_by_key(|&(_, &t)| t).map(|(k, _)| k.clone()) else {
310 break;
311 };
312 self.lru.remove(&oldest);
313 if let Some(rem) = self.images.remove(&oldest) {
314 self.total_bytes = self.total_bytes.saturating_sub(rem.byte_size());
315 }
316 }
317 }
318
319 fn put_video_decoder(
320 &mut self,
321 path: PathBuf,
322 info: VideoInfo,
323 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,
324 ) -> Vec<VideoDecoderSlot> {
325 let mut evicted = Vec::new();
326 self.tick += 1;
327 let now_tick = self.tick;
328 let new_slot = VideoDecoderSlot {
329 info,
330 decoder,
331 last_used: now_tick,
332 };
333 if let Some(slot) = self.video_decoders.get_mut(&path) {
334 evicted.push(std::mem::replace(slot, new_slot));
335 return evicted;
336 }
337 while self.video_decoders.len() >= MAX_VIDEO_DECODERS {
338 let Some(oldest_path) = self
339 .video_decoders
340 .iter()
341 .min_by_key(|(_, e)| e.last_used)
342 .map(|(p, _)| p.clone())
343 else {
344 break;
345 };
346 if let Some(removed) = self.video_decoders.remove(&oldest_path) {
347 evicted.push(removed);
348 }
349 }
350 self.video_decoders.insert(path, new_slot);
351 evicted
352 }
353}
354
355struct MediaShared {
356 state: Mutex<MediaState>,
357 #[cfg(not(target_arch = "wasm32"))]
358 cv: Condvar,
359 #[cfg(not(target_arch = "wasm32"))]
360 lookahead_throttled: AtomicBool,
361 #[cfg(not(target_arch = "wasm32"))]
362 prefetch_queues: Mutex<Vec<Weak<PrefetchQueue>>>,
363}
364
365impl MediaShared {
366 fn new(budget_bytes: u64) -> Self {
367 let initial_state = MediaState::new(budget_bytes);
368 #[cfg(not(target_arch = "wasm32"))]
369 let initial_throttle = initial_state.should_throttle_lookahead();
370 Self {
371 state: Mutex::new(initial_state),
372 #[cfg(not(target_arch = "wasm32"))]
373 cv: Condvar::new(),
374 #[cfg(not(target_arch = "wasm32"))]
375 lookahead_throttled: AtomicBool::new(initial_throttle),
376 #[cfg(not(target_arch = "wasm32"))]
377 prefetch_queues: Mutex::new(Vec::new()),
378 }
379 }
380
381 #[cfg(not(target_arch = "wasm32"))]
382 fn insert_cached_locked(
383 &self,
384 state: &mut MediaState,
385 cache_key: ImageCacheKey,
386 decoded: DecodedImage,
387 ) -> bool {
388 state.insert_cached(cache_key, decoded);
389 self.sync_lookahead_throttle(state)
390 }
391
392 fn insert_cached_media_locked(
393 &self,
394 state: &mut MediaState,
395 cache_key: ImageCacheKey,
396 media: CachedMedia,
397 ) -> bool {
398 state.insert_cached_media(cache_key, media);
399 self.sync_lookahead_throttle(state)
400 }
401
402 fn path_exists_cached(&self, path: &Path) -> bool {
403 if virtual_bytes(path).is_some() {
404 return true;
405 }
406 #[cfg(not(target_arch = "wasm32"))]
407 {
408 if let Ok(state) = self.state.lock() {
409 if state.known_existing_paths.contains(path) || state.video_decoders.contains_key(path) {
410 return true;
411 }
412 }
413 if path.exists() {
414 if let Ok(mut state) = self.state.lock() {
415 state.record_existing_path(path);
416 }
417 true
418 } else {
419 false
420 }
421 }
422 #[cfg(target_arch = "wasm32")]
423 {
424 path.exists()
425 }
426 }
427
428 fn resolve_clip_path_cached(&self, clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
429 let candidate = resolve_clip_candidate_path(clip, frame)?;
430 self.path_exists_cached(&candidate).then_some(candidate)
431 }
432
433 fn get_or_open_video_decoder(
434 &self,
435 path: &Path,
436 ) -> Option<(VideoInfo, Arc<Mutex<Option<Box<dyn VideoDecoder>>>>)> {
437 let mut guard = self.state.lock().ok()?;
438 #[cfg(not(target_arch = "wasm32"))]
439 while guard.opening_videos.contains(path) {
440 guard = self.cv.wait(guard).ok()?;
441 }
442 guard.tick += 1;
443 let now_tick = guard.tick;
444 if let Some(slot) = guard.video_decoders.get_mut(path) {
445 slot.last_used = now_tick;
446 return Some((slot.info, Arc::clone(&slot.decoder)));
447 }
448
449 #[cfg(not(target_arch = "wasm32"))]
450 {
451 guard.opening_videos.insert(path.to_path_buf());
452 }
453 let cache_gen = guard.generation;
454 drop(guard);
455
456 struct OpenGuard<'a> {
457 shared: &'a MediaShared,
458 path: Option<PathBuf>,
459 }
460 impl Drop for OpenGuard<'_> {
461 fn drop(&mut self) {
462 #[cfg(not(target_arch = "wasm32"))]
463 if let Some(path) = self.path.take() {
464 if let Ok(mut state) = self.shared.state.lock() {
465 state.opening_videos.remove(&path);
466 self.shared.cv.notify_all();
467 }
468 }
469 #[cfg(target_arch = "wasm32")]
470 let _ = (&self.shared, &self.path);
471 }
472 }
473 let mut open_guard = OpenGuard {
474 shared: self,
475 path: Some(path.to_path_buf()),
476 };
477
478 let decoder = open_video_decoder(path);
479 let info = decoder.as_ref().map(|d| d.info());
480 let slot_arc = Arc::new(Mutex::new(decoder));
481
482 let mut evicted_decoders = Vec::new();
483 if let Ok(mut state) = self.state.lock() {
484 #[cfg(not(target_arch = "wasm32"))]
485 state.opening_videos.remove(path);
486 open_guard.path = None;
487 if let Some(dec_info) = info {
488 if state.generation == cache_gen {
489 state.record_existing_path(path);
490 evicted_decoders = state.put_video_decoder(
491 path.to_path_buf(),
492 dec_info,
493 Arc::clone(&slot_arc),
494 );
495 }
496 } else {
497 state.evict_existing_path(path);
498 }
499 #[cfg(not(target_arch = "wasm32"))]
500 self.cv.notify_all();
501 }
502 drop(evicted_decoders);
503 info.map(|i| (i, slot_arc))
504 }
505}
506
507#[cfg(not(target_arch = "wasm32"))]
508struct InFlightGuard<'a> {
509 shared: &'a MediaShared,
510 key: Option<ImageCacheKey>,
511}
512
513#[cfg(not(target_arch = "wasm32"))]
514impl Drop for InFlightGuard<'_> {
515 fn drop(&mut self) {
516 if let Some(key) = self.key.take() {
517 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
518 state.in_flight.remove(&key);
519 let unthrottled = self.shared.sync_lookahead_throttle(&state);
520 self.shared.cv.notify_all();
521 unthrottled
522 } else {
523 false
524 };
525 if unthrottled {
526 self.shared.notify_prefetch_waiters();
527 }
528 }
529 }
530}
531
532#[cfg(not(target_arch = "wasm32"))]
533struct StagingBufferEntry {
534 buffer: wgpu::Buffer,
535 capacity: u64,
536 rx: Option<mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>>,
537}
538
539#[cfg(not(target_arch = "wasm32"))]
540pub(crate) struct UploadStagingPool {
541 ready: Vec<StagingBufferEntry>,
542 pending_submit: Vec<StagingBufferEntry>,
543 mapping: Vec<StagingBufferEntry>,
544 total_bytes: u64,
545 max_bytes: u64,
546 needs_begin_frame: bool,
547}
548
549#[cfg(not(target_arch = "wasm32"))]
550impl UploadStagingPool {
551 fn new(max_bytes: u64) -> Self {
552 Self {
553 ready: Vec::new(),
554 pending_submit: Vec::new(),
555 mapping: Vec::new(),
556 total_bytes: 0,
557 max_bytes,
558 needs_begin_frame: false,
559 }
560 }
561
562 fn mark_frame_start(&mut self) {
563 self.needs_begin_frame = true;
564 }
565
566 fn clear(&mut self) {
567 self.ready.clear();
568 self.pending_submit.clear();
569 self.mapping.clear();
570 self.total_bytes = 0;
571 self.needs_begin_frame = false;
572 }
573
574 fn flush_pending_if_needed(&mut self, device: &wgpu::Device) {
575 if !self.needs_begin_frame {
576 return;
577 }
578 self.needs_begin_frame = false;
579 if !self.pending_submit.is_empty() {
580 for mut entry in self.pending_submit.drain(..) {
581 let (tx, rx) = mpsc::channel();
582 entry.buffer.slice(..).map_async(wgpu::MapMode::Write, move |res| {
583 let _ = tx.send(res);
584 });
585 entry.rx = Some(rx);
586 self.mapping.push(entry);
587 }
588 }
589 self.harvest_ready(device, false);
590 }
591
592 fn harvest_ready(&mut self, device: &wgpu::Device, wait: bool) {
593 if self.mapping.is_empty() {
594 return;
595 }
596 let poll_mode = if wait {
597 wgpu::PollType::Wait {
598 submission_index: None,
599 timeout: Some(std::time::Duration::from_secs(5)),
600 }
601 } else {
602 wgpu::PollType::Poll
603 };
604 let _ = device.poll(poll_mode);
605 let mut i = 0;
606 while i < self.mapping.len() {
607 let status = match self.mapping[i].rx.as_ref() {
608 Some(rx) => rx.try_recv(),
609 None => Ok(Ok(())),
610 };
611 match status {
612 Ok(Ok(())) => {
613 let mut entry = self.mapping.swap_remove(i);
614 entry.rx = None;
615 self.ready.push(entry);
616 }
617 Ok(Err(_)) | Err(mpsc::TryRecvError::Disconnected) => {
618 let entry = self.mapping.swap_remove(i);
619 self.total_bytes = self.total_bytes.saturating_sub(entry.capacity);
620 }
621 Err(mpsc::TryRecvError::Empty) => {
622 i += 1;
623 }
624 }
625 }
626 }
627
628 fn take_ready(&mut self, needed: u64) -> Option<wgpu::Buffer> {
629 let max_acceptable = needed.saturating_mul(2).max(needed.saturating_add(4 * 1024 * 1024));
630 let mut best_idx = None;
631 let mut best_cap = u64::MAX;
632 for (i, entry) in self.ready.iter().enumerate() {
633 if entry.capacity >= needed && entry.capacity <= max_acceptable && entry.capacity < best_cap {
634 best_cap = entry.capacity;
635 best_idx = Some(i);
636 }
637 }
638 best_idx.map(|idx| self.ready.swap_remove(idx).buffer)
639 }
640
641 pub(crate) fn acquire(&mut self, device: &wgpu::Device, needed: u64) -> Option<wgpu::Buffer> {
642 self.flush_pending_if_needed(device);
643 if let Some(buf) = self.take_ready(needed) {
644 return Some(buf);
645 }
646 self.harvest_ready(device, false);
647 if let Some(buf) = self.take_ready(needed) {
648 return Some(buf);
649 }
650 while self.total_bytes.saturating_add(needed) > self.max_bytes && !self.ready.is_empty() {
651 let evicted = self.ready.remove(0);
652 self.total_bytes = self.total_bytes.saturating_sub(evicted.capacity);
653 }
654 if self.total_bytes.saturating_add(needed) > self.max_bytes {
655 return None;
656 }
657 let alloc_size = needed.max(4096);
658 let buffer = device.create_buffer(&wgpu::BufferDescriptor {
659 label: Some("loader-upload-staging"),
660 size: alloc_size,
661 usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::MAP_WRITE,
662 mapped_at_creation: true,
663 });
664 self.total_bytes = self.total_bytes.saturating_add(alloc_size);
665 Some(buffer)
666 }
667
668 pub(crate) fn finish_upload(&mut self, buffer: wgpu::Buffer) {
669 let capacity = buffer.size();
670 self.pending_submit.push(StagingBufferEntry {
671 buffer,
672 capacity,
673 rx: None,
674 });
675 }
676
677 pub(crate) fn release_failed_upload(&mut self, capacity: u64) {
678 self.total_bytes = self.total_bytes.saturating_sub(capacity);
679 }
680}
681
682pub struct MediaCache {
683 shared: Arc<MediaShared>,
684 #[cfg(not(target_arch = "wasm32"))]
685 staging_pool: Mutex<UploadStagingPool>,
686 nv12_gpu_state: Mutex<Option<crate::eval::Nv12Pipelines>>,
687}
688
689impl Default for MediaCache {
690 fn default() -> Self {
691 Self::new(default_media_cache_budget_mb())
692 }
693}
694
695impl MediaCache {
696 pub fn new(budget_mb: u64) -> Self {
697 Self {
698 shared: Arc::new(MediaShared::new(budget_mb.saturating_mul(1024 * 1024))),
699 #[cfg(not(target_arch = "wasm32"))]
700 staging_pool: Mutex::new(UploadStagingPool::new(320 * 1024 * 1024)),
701 nv12_gpu_state: Mutex::new(None),
702 }
703 }
704
705 pub fn with_budget_mb(budget_mb: u64) -> Self {
706 Self::new(budget_mb)
707 }
708
709 /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false`
710 /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged.
711 pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) -> bool {
712 let Ok(mut files) = VIRTUAL_FILES.write() else { return false };
713 insert_capped(&mut files, MAX_VIRTUAL_BYTES, path_parts(path.as_ref()), bytes.into())
714 }
715
716 pub fn clear_virtual_bytes() {
717 if let Ok(mut files) = VIRTUAL_FILES.write() {
718 files.clear();
719 }
720 }
721
722 pub fn clear(&mut self) {
723 let mut cleared_decoders = Vec::new();
724 if let Ok(mut state) = self.shared.state.lock() {
725 state.images.clear();
726 state.lru.clear();
727 cleared_decoders.extend(state.video_decoders.drain().map(|(_, slot)| slot));
728 state.total_bytes = 0;
729 state.generation = state.generation.wrapping_add(1);
730 #[cfg(not(target_arch = "wasm32"))]
731 {
732 state.known_existing_paths.clear();
733 state.speculative_bytes_since_seq = 0;
734 state.speculative_count_since_seq = 0;
735 state.last_speculative_bytes = 0;
736 state.last_prefetch_seq = None;
737 }
738 self.shared.sync_lookahead_throttle(&state);
739 }
740 #[cfg(not(target_arch = "wasm32"))]
741 {
742 self.shared.cv.notify_all();
743 self.shared.notify_prefetch_waiters();
744 }
745 drop(cleared_decoders);
746 #[cfg(not(target_arch = "wasm32"))]
747 if let Ok(mut pool) = self.staging_pool.lock() {
748 pool.clear();
749 }
750 if let Ok(mut slot) = self.nv12_gpu_state.lock() {
751 *slot = None;
752 }
753 }
754
755 pub(crate) fn with_nv12_gpu_state<R>(
756 &self,
757 init: impl FnOnce() -> crate::eval::Nv12Pipelines,
758 f: impl FnOnce(&mut crate::eval::Nv12Pipelines) -> R,
759 ) -> R {
760 let mut slot = self.nv12_gpu_state.lock().unwrap_or_else(|e| e.into_inner());
761 let state = slot.get_or_insert_with(init);
762 f(state)
763 }
764
765 pub(crate) fn reset_nv12_uniform_cursor(&self) {
766 if let Ok(mut slot) = self.nv12_gpu_state.lock() {
767 if let Some(pipe) = slot.as_mut() {
768 pipe.reset_uniform_cursor();
769 }
770 }
771 }
772
773 pub(crate) fn trim_nv12_uniform_chunks(&self, max_chunks: usize) {
774 if let Ok(mut slot) = self.nv12_gpu_state.lock() {
775 if let Some(pipe) = slot.as_mut() {
776 pipe.trim_uniform_chunks(max_chunks);
777 }
778 }
779 }
780
781 pub(crate) fn nv12_vram_bytes(&self) -> u64 {
782 self.nv12_gpu_state
783 .lock()
784 .ok()
785 .and_then(|slot| slot.as_ref().map(|pipe| pipe.vram_bytes()))
786 .unwrap_or(0)
787 }
788
789 pub(crate) fn clear_nv12_gpu_state(&self) {
790 if let Ok(mut slot) = self.nv12_gpu_state.lock() {
791 if let Some(pipe) = slot.as_mut() {
792 pipe.clear_plane_pool();
793 pipe.trim_uniform_chunks(2);
794 }
795 }
796 }
797
798 #[cfg(not(target_arch = "wasm32"))]
799 pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option<wgpu::Buffer> {
800 self.staging_pool
801 .lock()
802 .ok()?
803 .acquire(device, needed)
804 }
805
806 #[cfg(not(target_arch = "wasm32"))]
807 pub(crate) fn recycle_upload_staging(&self, buffer: wgpu::Buffer) {
808 if let Ok(mut pool) = self.staging_pool.lock() {
809 pool.finish_upload(buffer);
810 }
811 }
812
813 #[cfg(not(target_arch = "wasm32"))]
814 pub(crate) fn release_failed_upload_staging(&self, capacity: u64) {
815 if let Ok(mut pool) = self.staging_pool.lock() {
816 pool.release_failed_upload(capacity);
817 }
818 }
819
820 /// Marks submitted upload staging buffers ready to begin asynchronous write-mapping
821 /// immediately after `queue.submit`, so they are already mapped by the next frame.
822 #[cfg(not(target_arch = "wasm32"))]
823 pub(crate) fn flush_upload_staging_after_submit(&self, device: &wgpu::Device) {
824 if let Ok(mut pool) = self.staging_pool.lock() {
825 pool.mark_frame_start();
826 pool.flush_pending_if_needed(device);
827 }
828 }
829
830 pub fn set_budget_mb(&mut self, budget_mb: u64) {
831 {
832 let Ok(mut state) = self.shared.state.lock() else { return };
833 state.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
834 while state.total_bytes > state.budget_bytes && state.images.len() > 1 {
835 let Some((oldest_key, _)) = state.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else {
836 break;
837 };
838 state.lru.remove(&oldest_key);
839 if let Some(removed) = state.images.remove(&oldest_key) {
840 state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size());
841 }
842 }
843 self.shared.sync_lookahead_throttle(&state);
844 }
845 #[cfg(not(target_arch = "wasm32"))]
846 {
847 self.shared.cv.notify_all();
848 self.shared.notify_prefetch_waiters();
849 }
850 }
851
852 pub fn entry_count(&self) -> usize {
853 self.shared.state.lock().map_or(0, |s| s.images.len())
854 }
855
856 pub fn video_decoder_count(&self) -> usize {
857 self.shared.state.lock().map_or(0, |s| s.video_decoders.len())
858 }
859
860 pub fn total_mb(&self) -> f64 {
861 self.shared
862 .state
863 .lock()
864 .map_or(0.0, |s| s.total_bytes as f64 / (1024.0 * 1024.0))
865 }
866
867 pub(crate) fn resolve_clip_path_cached(&self, clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
868 self.shared.resolve_clip_path_cached(clip, frame)
869 }
870
871 /// Loads a Fusion `ClipSpec` (still image, numbered sequence, OpenEXR, or `.mov`/`.mp4` video) at `frame`.
872 /// Returns `(resolved_path, local_frame_idx, decoded_image, loaded_from_disk)`.
873 pub fn load_clip(
874 &mut self,
875 clip: &ClipSpec,
876 frame: i64,
877 post_multiply: bool,
878 exr_channels: [Option<&str>; 4],
879 ) -> Option<(PathBuf, i64, DecodedImage, bool)> {
880 self.load_clip_media(clip, frame, post_multiply, exr_channels)
881 .map(|(resolved, idx, media, from_disk)| (resolved, idx, media.into_decoded_image(), from_disk))
882 }
883
884 /// Loads a Fusion `ClipSpec` keeping native `NV12` video frames unconverted for direct
885 /// single-pass GPU upload and YUV->RGBA+rotation conversion.
886 pub(crate) fn load_clip_media(
887 &mut self,
888 clip: &ClipSpec,
889 frame: i64,
890 post_multiply: bool,
891 exr_channels: [Option<&str>; 4],
892 ) -> Option<(PathBuf, i64, CachedMedia, bool)> {
893 let base = Path::new(&clip.filename);
894 if is_video_path(base) {
895 if !video_frame_in_range(clip, frame) || !self.shared.path_exists_cached(base) {
896 return None;
897 }
898 let base_buf = base.to_path_buf();
899 let (info, decoder_arc) = self.shared.get_or_open_video_decoder(base)?;
900 let idx = compute_video_frame_idx(clip, frame, info.nb_frames);
901 let cache_key = ImageCacheKey {
902 path: base_buf.clone(),
903 frame_idx: idx,
904 post_multiply,
905 exr_channels: [None, None, None, None],
906 };
907
908 let cache_gen = {
909 let mut state = self.shared.state.lock().ok()?;
910 loop {
911 if let Some(media) = state.images.get(&cache_key).cloned() {
912 state.tick += 1;
913 let t = state.tick;
914 state.lru.insert(cache_key, t);
915 return Some((base_buf, idx, media, false));
916 }
917 #[cfg(not(target_arch = "wasm32"))]
918 if state.in_flight.contains(&cache_key) {
919 state = self.shared.cv.wait(state).ok()?;
920 continue;
921 }
922 #[cfg(not(target_arch = "wasm32"))]
923 {
924 state.in_flight.insert(cache_key.clone());
925 self.shared.sync_lookahead_throttle(&state);
926 }
927 break state.generation;
928 }
929 };
930
931 #[cfg(not(target_arch = "wasm32"))]
932 let mut in_flight_guard = InFlightGuard {
933 shared: &self.shared,
934 key: Some(cache_key.clone()),
935 };
936
937 let decoded_frame = {
938 let mut dec_guard = decoder_arc.lock().ok()?;
939 dec_guard.as_mut()?.decode_frame_native(idx)?
940 };
941 let media = match decoded_frame {
942 DecodedVideoFrame::Nv12(nv12) => CachedMedia::Nv12(Arc::new(nv12)),
943 DecodedVideoFrame::Rgba(mut raw) => {
944 if post_multiply {
945 apply_post_multiply_rgba8(&mut raw);
946 }
947 CachedMedia::Rgba(DecodedImage {
948 size: [info.width, info.height],
949 rgba: Arc::new(raw),
950 rgba_f16: None,
951 rgba_f32: None,
952 z_f32: None,
953 })
954 }
955 };
956
957 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
958 #[cfg(not(target_arch = "wasm32"))]
959 {
960 state.in_flight.remove(&cache_key);
961 in_flight_guard.key = None;
962 }
963 let unthrottled = if state.generation == cache_gen {
964 self.shared
965 .insert_cached_media_locked(&mut state, cache_key, media.clone())
966 } else {
967 self.shared.sync_lookahead_throttle(&state)
968 };
969 #[cfg(not(target_arch = "wasm32"))]
970 self.shared.cv.notify_all();
971 unthrottled
972 } else {
973 false
974 };
975 #[cfg(not(target_arch = "wasm32"))]
976 if unthrottled {
977 self.shared.notify_prefetch_waiters();
978 }
979 #[cfg(target_arch = "wasm32")]
980 let _ = unthrottled;
981 return Some((base_buf, idx, media, true));
982 }
983
984 let resolved = resolve_clip_candidate_path(clip, frame)?;
985 let is_exr = is_exr_path(&resolved);
986 let key_channels = if is_exr {
987 [
988 normalize_channel_opt(exr_channels[0]),
989 normalize_channel_opt(exr_channels[1]),
990 normalize_channel_opt(exr_channels[2]),
991 normalize_channel_opt(exr_channels[3]),
992 ]
993 } else {
994 [None, None, None, None]
995 };
996 let cache_key = ImageCacheKey {
997 path: resolved.clone(),
998 frame_idx: -1,
999 post_multiply: post_multiply && !is_exr,
1000 exr_channels: key_channels,
1001 };
1002
1003 let cache_gen = {
1004 let mut state = self.shared.state.lock().ok()?;
1005 loop {
1006 if let Some(media) = state.images.get(&cache_key).cloned() {
1007 state.tick += 1;
1008 let t = state.tick;
1009 state.lru.insert(cache_key, t);
1010 return Some((resolved, -1, media, false));
1011 }
1012 #[cfg(not(target_arch = "wasm32"))]
1013 if state.in_flight.contains(&cache_key) {
1014 state = self.shared.cv.wait(state).ok()?;
1015 continue;
1016 }
1017 #[cfg(not(target_arch = "wasm32"))]
1018 {
1019 state.in_flight.insert(cache_key.clone());
1020 self.shared.sync_lookahead_throttle(&state);
1021 }
1022 break state.generation;
1023 }
1024 };
1025
1026 #[cfg(not(target_arch = "wasm32"))]
1027 let mut in_flight_guard = InFlightGuard {
1028 shared: &self.shared,
1029 key: Some(cache_key.clone()),
1030 };
1031
1032 let decoded = if is_exr {
1033 if !self.shared.path_exists_cached(&resolved) {
1034 return None;
1035 }
1036 // OpenEXR is already premultiplied in Blender/Fusion; never double-premultiply!
1037 decode_exr_rgba(
1038 &resolved,
1039 exr_channels[0],
1040 exr_channels[1],
1041 exr_channels[2],
1042 exr_channels[3],
1043 false,
1044 true,
1045 )
1046 } else {
1047 decode_raster_image(&resolved, post_multiply, true)
1048 };
1049 let Some(decoded) = decoded else {
1050 if let Ok(mut state) = self.shared.state.lock() {
1051 state.evict_existing_path(&resolved);
1052 }
1053 return None;
1054 };
1055 let media = CachedMedia::Rgba(decoded);
1056
1057 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
1058 #[cfg(not(target_arch = "wasm32"))]
1059 {
1060 state.in_flight.remove(&cache_key);
1061 in_flight_guard.key = None;
1062 }
1063 let unthrottled = if state.generation == cache_gen {
1064 state.record_existing_path(&resolved);
1065 self.shared
1066 .insert_cached_media_locked(&mut state, cache_key, media.clone())
1067 } else {
1068 self.shared.sync_lookahead_throttle(&state)
1069 };
1070 #[cfg(not(target_arch = "wasm32"))]
1071 self.shared.cv.notify_all();
1072 unthrottled
1073 } else {
1074 false
1075 };
1076 #[cfg(not(target_arch = "wasm32"))]
1077 if unthrottled {
1078 self.shared.notify_prefetch_waiters();
1079 }
1080 #[cfg(target_arch = "wasm32")]
1081 let _ = unthrottled;
1082 Some((resolved, -1, media, true))
1083 }
1084}
1085
1086fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool {
1087 if clip.global_end >= clip.global_start
1088 && (clip.length.unwrap_or(0) > 1 || clip.global_end > clip.global_start)
1089 {
1090 let min_f = clip.global_start.saturating_sub(clip.extend_first.max(0));
1091 let max_f = clip.global_end.saturating_add(clip.extend_last.max(0));
1092 if frame < min_f || (!clip.loop_clip && frame > max_f) {
1093 return false;
1094 }
1095 }
1096 true
1097}
1098
1099fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 {
1100 let len = clip.length.unwrap_or(nb_frames.max(1)).max(1);
1101 let trim_in = clip.trim_in.clamp(0, len - 1);
1102 let trim_out = if clip.trim_out > 0 {
1103 clip.trim_out.clamp(trim_in, len - 1)
1104 } else {
1105 len - 1
1106 };
1107 let span = trim_out.saturating_sub(trim_in).saturating_add(1).max(1);
1108 let delta = frame.saturating_sub(clip.global_start);
1109 let rel = if clip.loop_clip {
1110 delta.max(0).rem_euclid(span)
1111 } else {
1112 delta.clamp(0, span - 1)
1113 };
1114 if clip.reverse { trim_out.saturating_sub(rel) } else { trim_in.saturating_add(rel) }
1115}
1116
1117fn resolve_clip_candidate_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
1118 let base = Path::new(&clip.filename);
1119 let len = clip.length.unwrap_or(1);
1120 let stem = base.file_stem()?.to_str()?;
1121 let ext = base.extension().and_then(|e| e.to_str()).unwrap_or("");
1122 let digit_start = stem.rfind(|c: char| !c.is_ascii_digit()).map(|i| i + 1).unwrap_or(0);
1123 let prefix = &stem[..digit_start];
1124 let digits = &stem[digit_start..];
1125 let is_seq = len > 1 && (clip.start_frame >= 0 || !digits.is_empty());
1126 if !is_seq || digits.is_empty() {
1127 return Some(base.to_path_buf());
1128 }
1129
1130 let seq_start = if clip.start_frame >= 0 { clip.start_frame } else { 0 };
1131 let len = len.max(1);
1132 let trim_in = clip.trim_in.clamp(0, len - 1);
1133 let trim_out = if clip.trim_out > 0 { clip.trim_out.clamp(trim_in, len - 1) } else { len - 1 };
1134 let span = (trim_out - trim_in + 1).max(1);
1135
1136 let mut rel = frame - clip.global_start;
1137 if clip.loop_clip {
1138 rel = rel.rem_euclid(span);
1139 } else {
1140 rel = rel.clamp(0, span - 1);
1141 }
1142 let idx = if clip.reverse {
1143 seq_start + trim_out - rel
1144 } else {
1145 seq_start + trim_in + rel
1146 };
1147
1148 let width = digits.len();
1149 let new_name = if ext.is_empty() {
1150 format!("{prefix}{idx:0width$}")
1151 } else {
1152 format!("{prefix}{idx:0width$}.{ext}")
1153 };
1154 Some(base.with_file_name(new_name))
1155}
1156
1157/// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`.
1158pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
1159 let candidate = resolve_clip_candidate_path(clip, frame)?;
1160 path_exists(&candidate).then_some(candidate)
1161}