authoravatarclover caruso<git@paperclover.net>2026-12-01 13:39:36-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 14:03:22-08:00
logc26f1ac7c5e4f0fcad7be3a75554b0b40851277f
tree96d986113deefab407c5c8ca6e2dfca5c4047d25
parentbf1ed86702ae29e7fc65907391240bc9d53d6679
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): async loader read-ahead and upload optimization


4 files changed, 1522 insertions(+), 581 deletions(-)

crates/engine/src/bin/render_check.rs+27-7
...@@ -243,19 +243,38 @@ fn run_batch_render(...@@ -243,19 +243,38 @@ fn run_batch_render(
243 }243 }
244244
245 let mut loop_err: Option<String> = None;245 let mut loop_err: Option<String> = None;
246 const PREFETCH_WINDOW: usize = 8;246 const PREFETCH_LOOKAHEAD: usize = 12;
247 engine.media.preload_frame_loaders_with_proxy(
248 &comp,
249 target,
250 start as f64,
251 &engine.expr,
252 engine.use_proxy_clips,
253 );
254 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
255 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);
256 for (k, f) in ((start + 1)..=seed_end).enumerate() {
257 prefetch.enqueue_frame(
258 &comp,
259 target,
260 k + 1,
261 f as f64,
262 &engine.expr,
263 engine.use_proxy_clips,
264 );
265 }
247 for (idx, f) in (start..=end).enumerate() {266 for (idx, f) in (start..=end).enumerate() {
248 if failed.load(Ordering::Acquire) {267 if failed.load(Ordering::Acquire) {
249 break;268 break;
250 }269 }
251 if idx % PREFETCH_WINDOW == 0 {270 prefetch.set_current_seq(idx);
252 let win_end = (idx + PREFETCH_WINDOW).min(total);271 let ahead_frame = f + PREFETCH_LOOKAHEAD as i64;
253 let window: Vec<f64> =272 if ahead_frame <= end {
254 (idx..win_end).map(|k| (start + k as i64) as f64).collect();273 prefetch.enqueue_frame(
255 engine.media.prefetch_frames_with_proxy(
256 &comp,274 &comp,
257 target,275 target,
258 &window,276 idx + PREFETCH_LOOKAHEAD,
277 ahead_frame as f64,
259 &engine.expr,278 &engine.expr,
260 engine.use_proxy_clips,279 engine.use_proxy_clips,
261 );280 );
...@@ -292,6 +311,7 @@ fn run_batch_render(...@@ -292,6 +311,7 @@ fn run_batch_render(
292 }311 }
293 }312 }
294313
314 drop(prefetch);
295 drop(tx);315 drop(tx);
296 for h in handles {316 for h in handles {
297 let _ = h.join();317 let _ = h.join();
crates/engine/src/eval/io.rs+93-45
...@@ -86,6 +86,95 @@ impl Engine {...@@ -86,6 +86,95 @@ impl Engine {
86 }86 }
87 }87 }
8888
89 fn upload_loader_texture(
90 &self,
91 enc: &mut wgpu::CommandEncoder,
92 tex: &CachedTexture,
93 data: &[u8],
94 bytes_per_pixel: u32,
95 size: [u32; 2],
96 ) {
97 #[cfg(target_arch = "wasm32")]
98 {
99 let _ = enc;
100 self.queue.write_texture(
101 tex.texture.as_image_copy(),
102 data,
103 wgpu::TexelCopyBufferLayout {
104 offset: 0,
105 bytes_per_row: Some(size[0] * bytes_per_pixel),
106 rows_per_image: Some(size[1]),
107 },
108 wgpu::Extent3d {
109 width: size[0],
110 height: size[1],
111 depth_or_array_layers: 1,
112 },
113 );
114 }
115 #[cfg(not(target_arch = "wasm32"))]
116 {
117 let [w, h] = size;
118 if w == 0 || h == 0 {
119 return;
120 }
121 let unpadded_bpr = w * bytes_per_pixel;
122 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
123 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
124 let needed = u64::from(padded_bpr) * u64::from(h);
125 if let Some(buf) = self.media.acquire_upload_staging(&self.device, needed) {
126 if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() {
127 if padded_bpr == unpadded_bpr {
128 let total = (unpadded_bpr as usize) * (h as usize);
129 view.slice(..total).copy_from_slice(&data[..total]);
130 } else {
131 let src_stride = unpadded_bpr as usize;
132 let dst_stride = padded_bpr as usize;
133 let mut wo = view.slice(..needed as usize);
134 for (row_idx, src_row) in data.chunks_exact(src_stride).enumerate() {
135 let off = row_idx * dst_stride;
136 wo.slice(off..off + src_stride).copy_from_slice(src_row);
137 }
138 }
139 drop(view);
140 buf.unmap();
141 enc.copy_buffer_to_texture(
142 wgpu::TexelCopyBufferInfo {
143 buffer: &buf,
144 layout: wgpu::TexelCopyBufferLayout {
145 offset: 0,
146 bytes_per_row: Some(padded_bpr),
147 rows_per_image: Some(h),
148 },
149 },
150 tex.texture.as_image_copy(),
151 wgpu::Extent3d {
152 width: w,
153 height: h,
154 depth_or_array_layers: 1,
155 },
156 );
157 self.media.recycle_upload_staging(buf);
158 return;
159 }
160 }
161 self.queue.write_texture(
162 tex.texture.as_image_copy(),
163 data,
164 wgpu::TexelCopyBufferLayout {
165 offset: 0,
166 bytes_per_row: Some(unpadded_bpr),
167 rows_per_image: Some(h),
168 },
169 wgpu::Extent3d {
170 width: w,
171 height: h,
172 depth_or_array_layers: 1,
173 },
174 );
175 }
176 }
177
89 pub(super) fn eval_loader(178 pub(super) fn eval_loader(
90 &mut self,179 &mut self,
91 comp: &Comp,180 comp: &Comp,
...@@ -120,9 +209,7 @@ impl Engine {...@@ -120,9 +209,7 @@ impl Engine {
120 if let Some(proxy_name) = proxy_candidate {209 if let Some(proxy_name) = proxy_candidate {
121 let mut proxy_clip = effective_clip.clone();210 let mut proxy_clip = effective_clip.clone();
122 proxy_clip.filename = proxy_name.to_owned();211 proxy_clip.filename = proxy_name.to_owned();
123 if crate::media::resolve_clip_path(&proxy_clip, frame_i)212 if self.media.resolve_clip_path_cached(&proxy_clip, frame_i).is_some() {
124 .is_some_and(|p| p.exists())
125 {
126 effective_clip = proxy_clip;213 effective_clip = proxy_clip;
127 }214 }
128 }215 }
...@@ -236,54 +323,15 @@ impl Engine {...@@ -236,54 +323,15 @@ impl Engine {
236 let f32_px = img.rgba_f32.as_ref().expect("checked is_some");323 let f32_px = img.rgba_f32.as_ref().expect("checked is_some");
237 let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key });324 let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key });
238 if tex.format == wgpu::TextureFormat::Rgba32Float {325 if tex.format == wgpu::TextureFormat::Rgba32Float {
239 self.queue.write_texture(326 self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f32_px), 16, img.size);
240 tex.texture.as_image_copy(),
241 bytemuck::cast_slice(f32_px),
242 wgpu::TexelCopyBufferLayout {
243 offset: 0,
244 bytes_per_row: Some(img.size[0] * 16),
245 rows_per_image: Some(img.size[1]),
246 },
247 wgpu::Extent3d {
248 width: img.size[0],
249 height: img.size[1],
250 depth_or_array_layers: 1,
251 },
252 );
253 } else {327 } else {
254 let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16");328 let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16");
255 self.queue.write_texture(329 self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f16_bits), 8, img.size);
256 tex.texture.as_image_copy(),
257 bytemuck::cast_slice(f16_bits),
258 wgpu::TexelCopyBufferLayout {
259 offset: 0,
260 bytes_per_row: Some(img.size[0] * 8),
261 rows_per_image: Some(img.size[1]),
262 },
263 wgpu::Extent3d {
264 width: img.size[0],
265 height: img.size[1],
266 depth_or_array_layers: 1,
267 },
268 );
269 }330 }
270 tex331 tex
271 } else {332 } else {
272 let tex = self.alloc_tex(img.size, BitDepth::Int8, if need_post { 0 } else { key });333 let tex = self.alloc_tex(img.size, BitDepth::Int8, if need_post { 0 } else { key });
273 self.queue.write_texture(334 self.upload_loader_texture(enc, &tex, &img.rgba, 4, img.size);
274 tex.texture.as_image_copy(),
275 &img.rgba,
276 wgpu::TexelCopyBufferLayout {
277 offset: 0,
278 bytes_per_row: Some(img.size[0] * 4),
279 rows_per_image: Some(img.size[1]),
280 },
281 wgpu::Extent3d {
282 width: img.size[0],
283 height: img.size[1],
284 depth_or_array_layers: 1,
285 },
286 );
287 tex335 tex
288 };336 };
289 let work_depth = if use_float_upload { dst_depth } else { BitDepth::Int8 };337 let work_depth = if use_float_upload { dst_depth } else { BitDepth::Int8 };
crates/engine/src/export.rs+47-13
...@@ -306,7 +306,26 @@ pub fn export_saver_png_sequence_with_progress(...@@ -306,7 +306,26 @@ pub fn export_saver_png_sequence_with_progress(
306 }306 }
307307
308 let mut loop_err: Option<String> = None;308 let mut loop_err: Option<String> = None;
309 const PREFETCH_WINDOW: usize = 8;309 const PREFETCH_LOOKAHEAD: usize = 12;
310 engine.media.preload_frame_loaders_with_proxy(
311 comp,
312 target,
313 start as f64,
314 &engine.expr,
315 engine.use_proxy_clips,
316 );
317 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
318 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);
319 for (k, f) in ((start + 1)..=seed_end).enumerate() {
320 prefetch.enqueue_frame(
321 comp,
322 target,
323 k + 1,
324 f as f64,
325 &engine.expr,
326 engine.use_proxy_clips,
327 );
328 }
310 for (idx, frame) in (start..=end).enumerate() {329 for (idx, frame) in (start..=end).enumerate() {
311 if failed.load(Ordering::Acquire) {330 if failed.load(Ordering::Acquire) {
312 break;331 break;
...@@ -315,13 +334,14 @@ pub fn export_saver_png_sequence_with_progress(...@@ -315,13 +334,14 @@ pub fn export_saver_png_sequence_with_progress(
315 cancelled.store(true, Ordering::Release);334 cancelled.store(true, Ordering::Release);
316 break;335 break;
317 }336 }
318 if idx % PREFETCH_WINDOW == 0 {337 prefetch.set_current_seq(idx);
319 let win_end = (idx + PREFETCH_WINDOW).min(total);338 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;
320 let window: Vec<f64> = (idx..win_end).map(|k| (start + k as i64) as f64).collect();339 if ahead_frame <= end {
321 engine.media.prefetch_frames_with_proxy(340 prefetch.enqueue_frame(
322 comp,341 comp,
323 target,342 target,
324 &window,343 idx + PREFETCH_LOOKAHEAD,
344 ahead_frame as f64,
325 &engine.expr,345 &engine.expr,
326 engine.use_proxy_clips,346 engine.use_proxy_clips,
327 );347 );
...@@ -379,6 +399,7 @@ pub fn export_saver_png_sequence_with_progress(...@@ -379,6 +399,7 @@ pub fn export_saver_png_sequence_with_progress(
379 frames_written += 1;399 frames_written += 1;
380 }400 }
381401
402 drop(prefetch);
382 drop(tx);403 drop(tx);
383 for h in handles {404 for h in handles {
384 let _ = h.join();405 let _ = h.join();
...@@ -901,8 +922,19 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -901,8 +922,19 @@ pub fn export_node_video_ffmpeg_with_progress(
901 }922 }
902 on_progress(first_prog);923 on_progress(first_prog);
903924
904 const PREFETCH_WINDOW: usize = 8;925 const PREFETCH_LOOKAHEAD: usize = 12;
905 let remaining = total.saturating_sub(1);926 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
927 let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end);
928 for (k, f) in ((start + 1)..=seed_end).enumerate() {
929 prefetch.enqueue_frame(
930 comp,
931 opts.target,
932 k,
933 f as f64,
934 &engine.expr,
935 engine.use_proxy_clips,
936 );
937 }
906 for (idx, frame) in ((start + 1)..=end).enumerate() {938 for (idx, frame) in ((start + 1)..=end).enumerate() {
907 if writer_failed.load(Ordering::Acquire) {939 if writer_failed.load(Ordering::Acquire) {
908 break;940 break;
...@@ -911,13 +943,14 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -911,13 +943,14 @@ pub fn export_node_video_ffmpeg_with_progress(
911 cancelled = true;943 cancelled = true;
912 break;944 break;
913 }945 }
914 if idx % PREFETCH_WINDOW == 0 {946 prefetch.set_current_seq(idx);
915 let win_end = (idx + PREFETCH_WINDOW).min(remaining);947 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;
916 let window: Vec<f64> = (idx..win_end).map(|k| (start + 1 + k as i64) as f64).collect();948 if ahead_frame <= end {
917 engine.media.prefetch_frames_with_proxy(949 prefetch.enqueue_frame(
918 comp,950 comp,
919 opts.target,951 opts.target,
920 &window,952 idx + PREFETCH_LOOKAHEAD,
953 ahead_frame as f64,
921 &engine.expr,954 &engine.expr,
922 engine.use_proxy_clips,955 engine.use_proxy_clips,
923 );956 );
...@@ -951,6 +984,7 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -951,6 +984,7 @@ pub fn export_node_video_ffmpeg_with_progress(
951 }984 }
952 on_progress(prog);985 on_progress(prog);
953 }986 }
987 drop(prefetch);
954 }988 }
955 drop(tx);989 drop(tx);
956990
crates/engine/src/media.rs+1355-516
...@@ -21,15 +21,15 @@ use crate::text_engine;...@@ -21,15 +21,15 @@ use crate::text_engine;
21use model::{Node, default_main_input_port};21use model::{Node, default_main_input_port};
22use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint};22use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint};
23#[cfg(not(target_arch = "wasm32"))]23#[cfg(not(target_arch = "wasm32"))]
24use std::collections::HashSet;24use std::collections::VecDeque;
25use std::collections::HashMap;25use std::collections::{HashMap, HashSet};
26use std::path::{Path, PathBuf};26use std::path::{Path, PathBuf};
27use std::process::Command;27use std::process::Command;
28#[cfg(not(target_arch = "wasm32"))]28#[cfg(not(target_arch = "wasm32"))]
29use std::sync::Mutex;
30use std::sync::{Arc, RwLock};
31#[cfg(not(target_arch = "wasm32"))]
32use std::sync::atomic::{AtomicUsize, Ordering};29use std::sync::atomic::{AtomicUsize, Ordering};
30#[cfg(not(target_arch = "wasm32"))]
31use std::sync::{Condvar, mpsc};
32use std::sync::{Arc, Mutex, RwLock};
3333
34#[derive(Clone)]34#[derive(Clone)]
35pub struct DecodedImage {35pub struct DecodedImage {
...@@ -134,10 +134,14 @@ fn open_image(path: &Path) -> Option<image::DynamicImage> {...@@ -134,10 +134,14 @@ fn open_image(path: &Path) -> Option<image::DynamicImage> {
134 return image::load_from_memory(&bytes).ok();134 return image::load_from_memory(&bytes).ok();
135 }135 }
136 // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares.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) {137 match std::fs::read(path) {
138 if let Ok(img) = image::load_from_memory(&bytes) {138 Ok(bytes) => {
139 return Some(img);139 if let Ok(img) = image::load_from_memory(&bytes) {
140 return Some(img);
141 }
140 }142 }
143 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
144 Err(_) => {}
141 }145 }
142 image::open(path).ok()146 image::open(path).ok()
143}147}
...@@ -190,87 +194,45 @@ struct ImageCacheKey {...@@ -190,87 +194,45 @@ struct ImageCacheKey {
190 exr_channels: [Option<String>; 4],194 exr_channels: [Option<String>; 4],
191}195}
192196
193struct VideoDecoderEntry {197struct VideoDecoderSlot {
194 decoder: Option<Box<dyn VideoDecoder>>,198 info: Option<VideoInfo>,
199 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,
195 last_used: u64,200 last_used: u64,
196}201}
197202
198pub struct MediaCache {203struct MediaState {
199 images: HashMap<ImageCacheKey, DecodedImage>,204 images: HashMap<ImageCacheKey, DecodedImage>,
200 video_decoders: HashMap<PathBuf, VideoDecoderEntry>,205 video_decoders: HashMap<PathBuf, VideoDecoderSlot>,
201 total_bytes: u64,206 total_bytes: u64,
202 budget_bytes: u64,207 budget_bytes: u64,
203 lru: HashMap<ImageCacheKey, u64>,208 lru: HashMap<ImageCacheKey, u64>,
204 tick: u64,209 tick: u64,
210 generation: u64,
211 #[cfg(not(target_arch = "wasm32"))]
212 in_flight: HashSet<ImageCacheKey>,
213 #[cfg(not(target_arch = "wasm32"))]
214 opening_videos: HashSet<PathBuf>,
215 known_existing_paths: HashSet<PathBuf>,
205}216}
206217
207impl Default for MediaCache {218impl MediaState {
208 fn default() -> Self {219 fn new(budget_bytes: u64) -> Self {
209 Self::new(default_media_cache_budget_mb())
210 }
211}
212
213impl MediaCache {
214 pub fn new(budget_mb: u64) -> Self {
215 Self {220 Self {
216 images: HashMap::new(),221 images: HashMap::new(),
217 video_decoders: HashMap::new(),222 video_decoders: HashMap::new(),
218 total_bytes: 0,223 total_bytes: 0,
219 budget_bytes: budget_mb.saturating_mul(1024 * 1024),224 budget_bytes,
220 lru: HashMap::new(),225 lru: HashMap::new(),
221 tick: 0,226 tick: 0,
227 generation: 0,
228 #[cfg(not(target_arch = "wasm32"))]
229 in_flight: HashSet::new(),
230 #[cfg(not(target_arch = "wasm32"))]
231 opening_videos: HashSet::new(),
232 known_existing_paths: HashSet::new(),
222 }233 }
223 }234 }
224235
225 pub fn with_budget_mb(budget_mb: u64) -> Self {
226 Self::new(budget_mb)
227 }
228
229 /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false`
230 /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged.
231 pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) -> bool {
232 let Ok(mut files) = VIRTUAL_FILES.write() else { return false };
233 insert_capped(&mut files, MAX_VIRTUAL_BYTES, path_parts(path.as_ref()), bytes.into())
234 }
235
236 pub fn clear_virtual_bytes() {
237 if let Ok(mut files) = VIRTUAL_FILES.write() {
238 files.clear();
239 }
240 }
241
242 pub fn clear(&mut self) {
243 self.images.clear();
244 self.lru.clear();
245 self.video_decoders.clear();
246 self.total_bytes = 0;
247 }
248
249 pub fn set_budget_mb(&mut self, budget_mb: u64) {
250 self.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
251 while self.total_bytes > self.budget_bytes && self.images.len() > 1 {
252 let Some((oldest_key, _)) = self.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else {
253 break;
254 };
255 self.lru.remove(&oldest_key);
256 if let Some(removed) = self.images.remove(&oldest_key) {
257 self.total_bytes = self.total_bytes.saturating_sub(removed.byte_size());
258 }
259 }
260 }
261
262 pub fn entry_count(&self) -> usize {
263 self.images.len()
264 }
265
266 pub fn video_decoder_count(&self) -> usize {
267 self.video_decoders.len()
268 }
269
270 pub fn total_mb(&self) -> f64 {
271 self.total_bytes as f64 / (1024.0 * 1024.0)
272 }
273
274 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {236 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
275 let bytes = decoded.byte_size();237 let bytes = decoded.byte_size();
276 self.tick += 1;238 self.tick += 1;
...@@ -291,12 +253,18 @@ impl MediaCache {...@@ -291,12 +253,18 @@ impl MediaCache {
291 }253 }
292 }254 }
293255
294 fn put_video_decoder(&mut self, path: PathBuf, decoder: Option<Box<dyn VideoDecoder>>) {256 fn put_video_decoder(
257 &mut self,
258 path: PathBuf,
259 info: Option<VideoInfo>,
260 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,
261 ) {
295 self.tick += 1;262 self.tick += 1;
296 let now_tick = self.tick;263 let now_tick = self.tick;
297 if let Some(entry) = self.video_decoders.get_mut(&path) {264 if let Some(slot) = self.video_decoders.get_mut(&path) {
298 entry.decoder = decoder;265 slot.info = info;
299 entry.last_used = now_tick;266 slot.decoder = decoder;
267 slot.last_used = now_tick;
300 return;268 return;
301 }269 }
302 while self.video_decoders.len() >= MAX_VIDEO_DECODERS {270 while self.video_decoders.len() >= MAX_VIDEO_DECODERS {
...@@ -312,24 +280,378 @@ impl MediaCache {...@@ -312,24 +280,378 @@ impl MediaCache {
312 }280 }
313 self.video_decoders.insert(281 self.video_decoders.insert(
314 path,282 path,
315 VideoDecoderEntry {283 VideoDecoderSlot {
284 info,
316 decoder,285 decoder,
317 last_used: now_tick,286 last_used: now_tick,
318 },287 },
319 );288 );
320 }289 }
290}
321291
322 fn get_or_open_video_decoder(&mut self, path: &Path) -> Option<VideoInfo> {292struct MediaShared {
323 self.tick += 1;293 state: Mutex<MediaState>,
324 let now_tick = self.tick;294 #[cfg(not(target_arch = "wasm32"))]
325 if let Some(entry) = self.video_decoders.get_mut(path) {295 cv: Condvar,
326 entry.last_used = now_tick;296}
327 return entry.decoder.as_ref().map(|d| d.info());297
298impl MediaShared {
299 fn new(budget_bytes: u64) -> Self {
300 Self {
301 state: Mutex::new(MediaState::new(budget_bytes)),
302 #[cfg(not(target_arch = "wasm32"))]
303 cv: Condvar::new(),
304 }
305 }
306
307 fn path_exists_cached(&self, path: &Path) -> bool {
308 if virtual_bytes(path).is_some() {
309 return true;
310 }
311 if let Ok(state) = self.state.lock() {
312 if state.known_existing_paths.contains(path) || state.video_decoders.contains_key(path) {
313 return true;
314 }
315 }
316 if path.exists() {
317 if let Ok(mut state) = self.state.lock() {
318 state.known_existing_paths.insert(path.to_path_buf());
319 }
320 true
321 } else {
322 false
323 }
324 }
325
326 fn resolve_clip_path_cached(&self, clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
327 let candidate = resolve_clip_candidate_path(clip, frame)?;
328 self.path_exists_cached(&candidate).then_some(candidate)
329 }
330
331 fn get_or_open_video_decoder(
332 &self,
333 path: &Path,
334 ) -> Option<(VideoInfo, Arc<Mutex<Option<Box<dyn VideoDecoder>>>>)> {
335 let mut guard = self.state.lock().ok()?;
336 #[cfg(not(target_arch = "wasm32"))]
337 while guard.opening_videos.contains(path) {
338 guard = self.cv.wait(guard).ok()?;
339 }
340 guard.tick += 1;
341 let now_tick = guard.tick;
342 if let Some(slot) = guard.video_decoders.get_mut(path) {
343 slot.last_used = now_tick;
344 return slot.info.map(|info| (info, Arc::clone(&slot.decoder)));
345 }
346
347 #[cfg(not(target_arch = "wasm32"))]
348 {
349 guard.opening_videos.insert(path.to_path_buf());
350 }
351 let cache_gen = guard.generation;
352 drop(guard);
353
354 struct OpenGuard<'a> {
355 shared: &'a MediaShared,
356 path: PathBuf,
357 }
358 impl Drop for OpenGuard<'_> {
359 fn drop(&mut self) {
360 #[cfg(not(target_arch = "wasm32"))]
361 if let Ok(mut state) = self.shared.state.lock() {
362 state.opening_videos.remove(&self.path);
363 self.shared.cv.notify_all();
364 }
365 #[cfg(target_arch = "wasm32")]
366 let _ = (&self.shared, &self.path);
367 }
328 }368 }
369 let _open_guard = OpenGuard {
370 shared: self,
371 path: path.to_path_buf(),
372 };
373
329 let decoder = open_video_decoder(path);374 let decoder = open_video_decoder(path);
330 let info = decoder.as_ref().map(|d| d.info());375 let info = decoder.as_ref().map(|d| d.info());
331 self.put_video_decoder(path.to_path_buf(), decoder);376 let slot_arc = Arc::new(Mutex::new(decoder));
332 info377
378 if let Ok(mut state) = self.state.lock() {
379 #[cfg(not(target_arch = "wasm32"))]
380 state.opening_videos.remove(path);
381 if state.generation == cache_gen {
382 state.put_video_decoder(path.to_path_buf(), info, Arc::clone(&slot_arc));
383 }
384 #[cfg(not(target_arch = "wasm32"))]
385 self.cv.notify_all();
386 }
387 info.map(|i| (i, slot_arc))
388 }
389}
390
391#[cfg(not(target_arch = "wasm32"))]
392struct InFlightGuard<'a> {
393 shared: &'a MediaShared,
394 key: Option<ImageCacheKey>,
395}
396
397#[cfg(not(target_arch = "wasm32"))]
398impl Drop for InFlightGuard<'_> {
399 fn drop(&mut self) {
400 if let Some(key) = self.key.take() {
401 if let Ok(mut state) = self.shared.state.lock() {
402 state.in_flight.remove(&key);
403 self.shared.cv.notify_all();
404 }
405 }
406 }
407}
408
409#[cfg(not(target_arch = "wasm32"))]
410struct StagingBufferEntry {
411 buffer: wgpu::Buffer,
412 capacity: u64,
413 rx: Option<mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>>,
414}
415
416#[cfg(not(target_arch = "wasm32"))]
417pub(crate) struct UploadStagingPool {
418 ready: Vec<StagingBufferEntry>,
419 pending_submit: Vec<StagingBufferEntry>,
420 mapping: Vec<StagingBufferEntry>,
421 total_bytes: u64,
422 max_bytes: u64,
423 needs_begin_frame: bool,
424}
425
426#[cfg(not(target_arch = "wasm32"))]
427impl UploadStagingPool {
428 fn new(max_bytes: u64) -> Self {
429 Self {
430 ready: Vec::new(),
431 pending_submit: Vec::new(),
432 mapping: Vec::new(),
433 total_bytes: 0,
434 max_bytes,
435 needs_begin_frame: false,
436 }
437 }
438
439 fn mark_frame_start(&mut self) {
440 self.needs_begin_frame = true;
441 }
442
443 fn clear(&mut self) {
444 self.ready.clear();
445 self.pending_submit.clear();
446 self.mapping.clear();
447 self.total_bytes = 0;
448 self.needs_begin_frame = false;
449 }
450
451 fn flush_pending_if_needed(&mut self, device: &wgpu::Device) {
452 if !self.needs_begin_frame {
453 return;
454 }
455 self.needs_begin_frame = false;
456 if !self.pending_submit.is_empty() {
457 for mut entry in self.pending_submit.drain(..) {
458 let (tx, rx) = mpsc::channel();
459 entry.buffer.slice(..).map_async(wgpu::MapMode::Write, move |res| {
460 let _ = tx.send(res);
461 });
462 entry.rx = Some(rx);
463 self.mapping.push(entry);
464 }
465 }
466 self.harvest_ready(device, false);
467 }
468
469 fn harvest_ready(&mut self, device: &wgpu::Device, wait: bool) {
470 if self.mapping.is_empty() {
471 return;
472 }
473 let poll_mode = if wait {
474 wgpu::PollType::Wait {
475 submission_index: None,
476 timeout: Some(std::time::Duration::from_secs(5)),
477 }
478 } else {
479 wgpu::PollType::Poll
480 };
481 let _ = device.poll(poll_mode);
482 let mut i = 0;
483 while i < self.mapping.len() {
484 let status = match self.mapping[i].rx.as_ref() {
485 Some(rx) => rx.try_recv(),
486 None => Ok(Ok(())),
487 };
488 match status {
489 Ok(Ok(())) => {
490 let mut entry = self.mapping.swap_remove(i);
491 entry.rx = None;
492 self.ready.push(entry);
493 }
494 Ok(Err(_)) | Err(mpsc::TryRecvError::Disconnected) => {
495 let entry = self.mapping.swap_remove(i);
496 self.total_bytes = self.total_bytes.saturating_sub(entry.capacity);
497 }
498 Err(mpsc::TryRecvError::Empty) => {
499 i += 1;
500 }
501 }
502 }
503 }
504
505 fn take_ready(&mut self, needed: u64) -> Option<wgpu::Buffer> {
506 let max_acceptable = needed.saturating_mul(2).max(needed.saturating_add(4 * 1024 * 1024));
507 let mut best_idx = None;
508 let mut best_cap = u64::MAX;
509 for (i, entry) in self.ready.iter().enumerate() {
510 if entry.capacity >= needed && entry.capacity <= max_acceptable && entry.capacity < best_cap {
511 best_cap = entry.capacity;
512 best_idx = Some(i);
513 }
514 }
515 best_idx.map(|idx| self.ready.swap_remove(idx).buffer)
516 }
517
518 pub(crate) fn acquire(&mut self, device: &wgpu::Device, needed: u64) -> Option<wgpu::Buffer> {
519 self.flush_pending_if_needed(device);
520 if let Some(buf) = self.take_ready(needed) {
521 return Some(buf);
522 }
523 self.harvest_ready(device, false);
524 if let Some(buf) = self.take_ready(needed) {
525 return Some(buf);
526 }
527 while self.total_bytes.saturating_add(needed) > self.max_bytes && !self.ready.is_empty() {
528 let evicted = self.ready.remove(0);
529 self.total_bytes = self.total_bytes.saturating_sub(evicted.capacity);
530 }
531 if self.total_bytes.saturating_add(needed) > self.max_bytes {
532 return None;
533 }
534 let alloc_size = needed.max(4096);
535 let buffer = device.create_buffer(&wgpu::BufferDescriptor {
536 label: Some("loader-upload-staging"),
537 size: alloc_size,
538 usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::MAP_WRITE,
539 mapped_at_creation: true,
540 });
541 self.total_bytes = self.total_bytes.saturating_add(alloc_size);
542 Some(buffer)
543 }
544
545 pub(crate) fn finish_upload(&mut self, buffer: wgpu::Buffer) {
546 let capacity = buffer.size();
547 self.pending_submit.push(StagingBufferEntry {
548 buffer,
549 capacity,
550 rx: None,
551 });
552 }
553}
554
555pub struct MediaCache {
556 shared: Arc<MediaShared>,
557 #[cfg(not(target_arch = "wasm32"))]
558 staging_pool: Mutex<UploadStagingPool>,
559}
560
561impl Default for MediaCache {
562 fn default() -> Self {
563 Self::new(default_media_cache_budget_mb())
564 }
565}
566
567impl MediaCache {
568 pub fn new(budget_mb: u64) -> Self {
569 Self {
570 shared: Arc::new(MediaShared::new(budget_mb.saturating_mul(1024 * 1024))),
571 #[cfg(not(target_arch = "wasm32"))]
572 staging_pool: Mutex::new(UploadStagingPool::new(320 * 1024 * 1024)),
573 }
574 }
575
576 pub fn with_budget_mb(budget_mb: u64) -> Self {
577 Self::new(budget_mb)
578 }
579
580 /// Registers `bytes` as the file at `path` for every `MediaCache` in the process. `false`
581 /// when the files held would pass [`MAX_VIRTUAL_BYTES`], leaving the registry unchanged.
582 pub fn insert_virtual_bytes(path: impl AsRef<Path>, bytes: impl Into<Arc<[u8]>>) -> bool {
583 let Ok(mut files) = VIRTUAL_FILES.write() else { return false };
584 insert_capped(&mut files, MAX_VIRTUAL_BYTES, path_parts(path.as_ref()), bytes.into())
585 }
586
587 pub fn clear_virtual_bytes() {
588 if let Ok(mut files) = VIRTUAL_FILES.write() {
589 files.clear();
590 }
591 }
592
593 pub fn clear(&mut self) {
594 if let Ok(mut state) = self.shared.state.lock() {
595 state.images.clear();
596 state.lru.clear();
597 state.video_decoders.clear();
598 state.total_bytes = 0;
599 state.generation = state.generation.wrapping_add(1);
600 state.known_existing_paths.clear();
601 }
602 #[cfg(not(target_arch = "wasm32"))]
603 if let Ok(mut pool) = self.staging_pool.lock() {
604 pool.clear();
605 }
606 }
607
608 #[cfg(not(target_arch = "wasm32"))]
609 pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option<wgpu::Buffer> {
610 self.staging_pool
611 .lock()
612 .expect("staging pool lock")
613 .acquire(device, needed)
614 }
615
616 #[cfg(not(target_arch = "wasm32"))]
617 pub(crate) fn recycle_upload_staging(&self, buffer: wgpu::Buffer) {
618 self.staging_pool
619 .lock()
620 .expect("staging pool lock")
621 .finish_upload(buffer);
622 }
623
624 pub fn set_budget_mb(&mut self, budget_mb: u64) {
625 let Ok(mut state) = self.shared.state.lock() else { return };
626 state.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
627 while state.total_bytes > state.budget_bytes && state.images.len() > 1 {
628 let Some((oldest_key, _)) = state.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else {
629 break;
630 };
631 state.lru.remove(&oldest_key);
632 if let Some(removed) = state.images.remove(&oldest_key) {
633 state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size());
634 }
635 }
636 }
637
638 pub fn entry_count(&self) -> usize {
639 self.shared.state.lock().map_or(0, |s| s.images.len())
640 }
641
642 pub fn video_decoder_count(&self) -> usize {
643 self.shared.state.lock().map_or(0, |s| s.video_decoders.len())
644 }
645
646 pub fn total_mb(&self) -> f64 {
647 self.shared
648 .state
649 .lock()
650 .map_or(0.0, |s| s.total_bytes as f64 / (1024.0 * 1024.0))
651 }
652
653 pub(crate) fn resolve_clip_path_cached(&self, clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
654 self.shared.resolve_clip_path_cached(clip, frame)
333 }655 }
334656
335 /// Loads a Fusion `ClipSpec` (still image, numbered sequence, OpenEXR, or `.mov`/`.mp4` video) at `frame`.657 /// Loads a Fusion `ClipSpec` (still image, numbered sequence, OpenEXR, or `.mov`/`.mp4` video) at `frame`.
...@@ -343,11 +665,11 @@ impl MediaCache {...@@ -343,11 +665,11 @@ impl MediaCache {
343 ) -> Option<(PathBuf, i64, DecodedImage, bool)> {665 ) -> Option<(PathBuf, i64, DecodedImage, bool)> {
344 let base = Path::new(&clip.filename);666 let base = Path::new(&clip.filename);
345 if is_video_path(base) {667 if is_video_path(base) {
346 if !base.exists() || !video_frame_in_range(clip, frame) {668 if !video_frame_in_range(clip, frame) || !self.shared.path_exists_cached(base) {
347 return None;669 return None;
348 }670 }
349 let base_buf = base.to_path_buf();671 let base_buf = base.to_path_buf();
350 let info = self.get_or_open_video_decoder(base)?;672 let (info, decoder_arc) = self.shared.get_or_open_video_decoder(base)?;
351 let idx = compute_video_frame_idx(clip, frame, info.nb_frames);673 let idx = compute_video_frame_idx(clip, frame, info.nb_frames);
352 let cache_key = ImageCacheKey {674 let cache_key = ImageCacheKey {
353 path: base_buf.clone(),675 path: base_buf.clone(),
...@@ -355,16 +677,37 @@ impl MediaCache {...@@ -355,16 +677,37 @@ impl MediaCache {
355 post_multiply,677 post_multiply,
356 exr_channels: [None, None, None, None],678 exr_channels: [None, None, None, None],
357 };679 };
358 if let Some(img) = self.images.get(&cache_key).cloned() {680
359 self.tick += 1;681 let cache_gen = {
360 self.lru.insert(cache_key, self.tick);682 let mut state = self.shared.state.lock().ok()?;
361 return Some((base_buf, idx, img, false));683 loop {
362 }684 if let Some(img) = state.images.get(&cache_key).cloned() {
363 let mut raw = self685 state.tick += 1;
364 .video_decoders686 let t = state.tick;
365 .get_mut(&base_buf)687 state.lru.insert(cache_key, t);
366 .and_then(|e| e.decoder.as_mut())?688 return Some((base_buf, idx, img, false));
367 .decode_frame(idx)?;689 }
690 #[cfg(not(target_arch = "wasm32"))]
691 if state.in_flight.contains(&cache_key) {
692 state = self.shared.cv.wait(state).ok()?;
693 continue;
694 }
695 #[cfg(not(target_arch = "wasm32"))]
696 state.in_flight.insert(cache_key.clone());
697 break state.generation;
698 }
699 };
700
701 #[cfg(not(target_arch = "wasm32"))]
702 let mut in_flight_guard = InFlightGuard {
703 shared: &self.shared,
704 key: Some(cache_key.clone()),
705 };
706
707 let mut raw = {
708 let mut dec_guard = decoder_arc.lock().ok()?;
709 dec_guard.as_mut()?.decode_frame(idx)?
710 };
368 if post_multiply {711 if post_multiply {
369 apply_post_multiply_rgba8(&mut raw);712 apply_post_multiply_rgba8(&mut raw);
370 }713 }
...@@ -374,11 +717,23 @@ impl MediaCache {...@@ -374,11 +717,23 @@ impl MediaCache {
374 rgba_f16: None,717 rgba_f16: None,
375 rgba_f32: None,718 rgba_f32: None,
376 };719 };
377 self.insert_cached(cache_key, decoded.clone());720
721 if let Ok(mut state) = self.shared.state.lock() {
722 #[cfg(not(target_arch = "wasm32"))]
723 {
724 state.in_flight.remove(&cache_key);
725 in_flight_guard.key = None;
726 }
727 if state.generation == cache_gen {
728 state.insert_cached(cache_key, decoded.clone());
729 }
730 #[cfg(not(target_arch = "wasm32"))]
731 self.shared.cv.notify_all();
732 }
378 return Some((base_buf, idx, decoded, true));733 return Some((base_buf, idx, decoded, true));
379 }734 }
380735
381 let resolved = resolve_clip_path(clip, frame)?;736 let resolved = resolve_clip_candidate_path(clip, frame)?;
382 let is_exr = is_exr_path(&resolved);737 let is_exr = is_exr_path(&resolved);
383 let key_channels = if is_exr {738 let key_channels = if is_exr {
384 [739 [
...@@ -396,13 +751,37 @@ impl MediaCache {...@@ -396,13 +751,37 @@ impl MediaCache {
396 post_multiply: post_multiply && !is_exr,751 post_multiply: post_multiply && !is_exr,
397 exr_channels: key_channels,752 exr_channels: key_channels,
398 };753 };
399 if let Some(img) = self.images.get(&cache_key).cloned() {754
400 self.tick += 1;755 let cache_gen = {
401 self.lru.insert(cache_key, self.tick);756 let mut state = self.shared.state.lock().ok()?;
402 return Some((resolved, -1, img, false));757 loop {
403 }758 if let Some(img) = state.images.get(&cache_key).cloned() {
759 state.tick += 1;
760 let t = state.tick;
761 state.lru.insert(cache_key, t);
762 return Some((resolved, -1, img, false));
763 }
764 #[cfg(not(target_arch = "wasm32"))]
765 if state.in_flight.contains(&cache_key) {
766 state = self.shared.cv.wait(state).ok()?;
767 continue;
768 }
769 #[cfg(not(target_arch = "wasm32"))]
770 state.in_flight.insert(cache_key.clone());
771 break state.generation;
772 }
773 };
774
775 #[cfg(not(target_arch = "wasm32"))]
776 let mut in_flight_guard = InFlightGuard {
777 shared: &self.shared,
778 key: Some(cache_key.clone()),
779 };
404780
405 let decoded = if is_exr {781 let decoded = if is_exr {
782 if !self.shared.path_exists_cached(&resolved) {
783 return None;
784 }
406 // OpenEXR is already premultiplied in Blender/Fusion; never double-premultiply!785 // OpenEXR is already premultiplied in Blender/Fusion; never double-premultiply!
407 decode_exr_rgba(786 decode_exr_rgba(
408 &resolved,787 &resolved,
...@@ -415,7 +794,20 @@ impl MediaCache {...@@ -415,7 +794,20 @@ impl MediaCache {
415 } else {794 } else {
416 decode_raster_image(&resolved, post_multiply, true)?795 decode_raster_image(&resolved, post_multiply, true)?
417 };796 };
418 self.insert_cached(cache_key, decoded.clone());797
798 if let Ok(mut state) = self.shared.state.lock() {
799 #[cfg(not(target_arch = "wasm32"))]
800 {
801 state.in_flight.remove(&cache_key);
802 in_flight_guard.key = None;
803 }
804 if state.generation == cache_gen {
805 state.known_existing_paths.insert(resolved.clone());
806 state.insert_cached(cache_key, decoded.clone());
807 }
808 #[cfg(not(target_arch = "wasm32"))]
809 self.shared.cv.notify_all();
810 }
419 Some((resolved, -1, decoded, true))811 Some((resolved, -1, decoded, true))
420 }812 }
421813
...@@ -446,9 +838,13 @@ impl MediaCache {...@@ -446,9 +838,13 @@ impl MediaCache {
446 }838 }
447 #[cfg(not(target_arch = "wasm32"))]839 #[cfg(not(target_arch = "wasm32"))]
448 {840 {
841 if let Ok(mut pool) = self.staging_pool.lock() {
842 pool.mark_frame_start();
843 }
449 let mut visited = HashSet::new();844 let mut visited = HashSet::new();
450 let mut jobs = MissingJobs::default();845 let mut jobs = MissingJobs::default();
451 self.collect_missing_loader_jobs(846 collect_missing_loader_jobs_shared(
847 &self.shared,
452 comp,848 comp,
453 target,849 target,
454 time,850 time,
...@@ -496,7 +892,8 @@ impl MediaCache {...@@ -496,7 +892,8 @@ impl MediaCache {
496 let mut visited = HashSet::new();892 let mut visited = HashSet::new();
497 let mut jobs = MissingJobs::default();893 let mut jobs = MissingJobs::default();
498 for &time in frames {894 for &time in frames {
499 self.collect_missing_loader_jobs(895 collect_missing_loader_jobs_shared(
896 &self.shared,
500 comp,897 comp,
501 target,898 target,
502 time,899 time,
...@@ -512,8 +909,30 @@ impl MediaCache {...@@ -512,8 +909,30 @@ impl MediaCache {
512 }909 }
513 if total == 1 && jobs.raster.len() == 1 {910 if total == 1 && jobs.raster.len() == 1 {
514 let job = jobs.raster.pop().expect("len == 1");911 let job = jobs.raster.pop().expect("len == 1");
912 let cache_gen = {
913 let Ok(mut state) = self.shared.state.lock() else { return };
914 if state.images.contains_key(&job.cache_key)
915 || state.in_flight.contains(&job.cache_key)
916 {
917 return;
918 }
919 state.in_flight.insert(job.cache_key.clone());
920 state.generation
921 };
922 let mut guard = InFlightGuard {
923 shared: &self.shared,
924 key: Some(job.cache_key.clone()),
925 };
515 if let Some(decoded) = decode_job(&job, true) {926 if let Some(decoded) = decode_job(&job, true) {
516 self.insert_cached(job.cache_key, decoded);927 if let Ok(mut state) = self.shared.state.lock() {
928 state.in_flight.remove(&job.cache_key);
929 guard.key = None;
930 if state.generation == cache_gen {
931 state.known_existing_paths.insert(job.cache_key.path.clone());
932 state.insert_cached(job.cache_key, decoded);
933 }
934 self.shared.cv.notify_all();
935 }
517 }936 }
518 return;937 return;
519 }938 }
...@@ -521,22 +940,19 @@ impl MediaCache {...@@ -521,22 +940,19 @@ impl MediaCache {
521 }940 }
522 }941 }
523942
943 /// Starts a non-blocking, cancellable background read-ahead worker pool that pre-decodes
944 /// upcoming frames into `MediaCache` while the GPU renders the current frame.
945 #[cfg(not(target_arch = "wasm32"))]
946 pub fn start_frame_prefetch(&self, lookahead: usize) -> MediaPrefetchHandle {
947 MediaPrefetchHandle::spawn(Arc::clone(&self.shared), lookahead.max(1))
948 }
949
524 #[cfg(not(target_arch = "wasm32"))]950 #[cfg(not(target_arch = "wasm32"))]
525 fn decode_jobs_parallel(&mut self, mut jobs: MissingJobs) {951 fn decode_jobs_parallel(&mut self, mut jobs: MissingJobs) {
526 let mut video_tasks: Vec<VideoDecodeTask> = jobs952 let mut video_tasks: Vec<VideoDecodeTask> = jobs
527 .videos953 .videos
528 .drain()954 .drain()
529 .map(|(path, requests)| {955 .map(|(path, requests)| VideoDecodeTask { 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();956 .collect();
541 let video_count = video_tasks.len();957 let video_count = video_tasks.len();
542 let raster_jobs = jobs.raster;958 let raster_jobs = jobs.raster;
...@@ -550,12 +966,6 @@ impl MediaCache {...@@ -550,12 +966,6 @@ impl MediaCache {
550 .min(total_units);966 .min(total_units);
551967
552 let next_idx = AtomicUsize::new(0);968 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>>> =969 let video_inputs: Vec<Mutex<Option<VideoDecodeTask>>> =
560 video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect();970 video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect();
561971
...@@ -568,12 +978,8 @@ impl MediaCache {...@@ -568,12 +978,8 @@ impl MediaCache {
568 }978 }
569 if idx < video_count {979 if idx < video_count {
570 let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take());980 let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take());
571 if let Some(mut task) = task {981 if let Some(task) = task {
572 let mut dec_opt =982 if let Some((info, dec_arc)) = self.shared.get_or_open_video_decoder(&task.path) {
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();983 let mut seen_local = HashSet::new();
578 for req in &task.requests {984 for req in &task.requests {
579 let frame_idx = compute_video_frame_idx(985 let frame_idx = compute_video_frame_idx(
...@@ -584,260 +990,640 @@ impl MediaCache {...@@ -584,260 +990,640 @@ impl MediaCache {
584 if !seen_local.insert((frame_idx, req.post_multiply)) {990 if !seen_local.insert((frame_idx, req.post_multiply)) {
585 continue;991 continue;
586 }992 }
587 if let Some(mut raw) = dec.decode_frame(frame_idx) {993 let key = ImageCacheKey {
994 path: task.path.clone(),
995 frame_idx,
996 post_multiply: req.post_multiply,
997 exr_channels: [None, None, None, None],
998 };
999 let cache_gen_opt = self.shared.state.lock().ok().and_then(|mut state| {
1000 if state.images.contains_key(&key)
1001 || state.in_flight.contains(&key)
1002 {
1003 None
1004 } else {
1005 state.in_flight.insert(key.clone());
1006 Some(state.generation)
1007 }
1008 });
1009 let Some(cache_gen) = cache_gen_opt else { continue };
1010 let mut guard = InFlightGuard {
1011 shared: &self.shared,
1012 key: Some(key.clone()),
1013 };
1014 let decoded_raw = dec_arc
1015 .lock()
1016 .ok()
1017 .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx));
1018 if let Some(mut raw) = decoded_raw {
588 if req.post_multiply {1019 if req.post_multiply {
589 apply_post_multiply_rgba8_parallel(&mut raw, false);1020 apply_post_multiply_rgba8_parallel(&mut raw, false);
590 }1021 }
591 let key = ImageCacheKey {1022 let decoded = DecodedImage {
592 path: task.path.clone(),1023 size: [info.width, info.height],
593 frame_idx,1024 rgba: Arc::new(raw),
594 post_multiply: req.post_multiply,1025 rgba_f16: None,
595 exr_channels: [None, None, None, None],1026 rgba_f32: None,
596 };1027 };
597 decoded_frames.push((1028 if let Ok(mut state) = self.shared.state.lock() {
598 key,1029 state.in_flight.remove(&key);
599 DecodedImage {1030 guard.key = None;
600 size: [info.width, info.height],1031 if state.generation == cache_gen {
601 rgba: Arc::new(raw),1032 state.insert_cached(key, decoded);
602 rgba_f16: None,1033 }
603 rgba_f32: None,1034 self.shared.cv.notify_all();
604 },1035 }
605 ));
606 }1036 }
607 }1037 }
608 }1038 }
609 if let Ok(mut slot) = video_slots[idx].lock() {
610 *slot = Some((task.path, dec_opt, decoded_frames));
611 }
612 }1039 }
613 } else {1040 } else {
614 let r_idx = idx - video_count;1041 let r_idx = idx - video_count;
615 let decoded = decode_job(&raster_jobs[r_idx], false);1042 let job = &raster_jobs[r_idx];
616 if let Ok(mut slot) = raster_slots[r_idx].lock() {1043 let cache_gen_opt = self.shared.state.lock().ok().and_then(|mut state| {
617 *slot = decoded;1044 if state.images.contains_key(&job.cache_key)
1045 || state.in_flight.contains(&job.cache_key)
1046 {
1047 None
1048 } else {
1049 state.in_flight.insert(job.cache_key.clone());
1050 Some(state.generation)
1051 }
1052 });
1053 let Some(cache_gen) = cache_gen_opt else { continue };
1054 let mut guard = InFlightGuard {
1055 shared: &self.shared,
1056 key: Some(job.cache_key.clone()),
1057 };
1058 if let Some(decoded) = decode_job(job, false) {
1059 if let Ok(mut state) = self.shared.state.lock() {
1060 state.in_flight.remove(&job.cache_key);
1061 guard.key = None;
1062 if state.generation == cache_gen {
1063 state.known_existing_paths.insert(job.cache_key.path.clone());
1064 state.insert_cached(job.cache_key.clone(), decoded);
1065 }
1066 self.shared.cv.notify_all();
1067 }
618 }1068 }
619 }1069 }
620 });1070 });
621 }1071 }
622 });1072 });
1073 }
1074}
6231075
624 for slot in video_slots {1076#[cfg(not(target_arch = "wasm32"))]
625 if let Ok(mut guard) = slot.into_inner() {1077struct PrefetchQueueState {
626 if let Some((path, dec_opt, frames)) = guard.take() {1078 raster: VecDeque<(usize, PreloadJob)>,
627 self.put_video_decoder(path, dec_opt);1079 videos: HashMap<PathBuf, VecDeque<(usize, VideoFrameRequest)>>,
628 for (key, img) in frames {1080 active_videos: HashSet<PathBuf>,
629 self.insert_cached(key, img);1081 queued_raster_keys: HashSet<ImageCacheKey>,
630 }1082 current_seq: usize,
1083 lookahead: usize,
1084 cancelled: bool,
1085}
1086
1087#[cfg(not(target_arch = "wasm32"))]
1088struct PrefetchQueue {
1089 state: Mutex<PrefetchQueueState>,
1090 cv: Condvar,
1091}
1092
1093#[cfg(not(target_arch = "wasm32"))]
1094enum PrefetchWorkItem {
1095 Raster(PreloadJob),
1096 Video(PathBuf, VideoFrameRequest),
1097}
1098
1099/// Cancellable background read-ahead handle returned by [`MediaCache::start_frame_prefetch`].
1100///
1101/// Continuously pre-decodes upcoming frames into [`MediaCache`] while the GPU renders the
1102/// current frame, and cancels and joins all worker threads cleanly on drop.
1103#[cfg(not(target_arch = "wasm32"))]
1104pub struct MediaPrefetchHandle {
1105 shared: Arc<MediaShared>,
1106 queue: Arc<PrefetchQueue>,
1107 workers: Vec<std::thread::JoinHandle<()>>,
1108}
1109
1110#[cfg(not(target_arch = "wasm32"))]
1111impl MediaPrefetchHandle {
1112 fn spawn(shared: Arc<MediaShared>, lookahead: usize) -> Self {
1113 let queue = Arc::new(PrefetchQueue {
1114 state: Mutex::new(PrefetchQueueState {
1115 raster: VecDeque::new(),
1116 videos: HashMap::new(),
1117 active_videos: HashSet::new(),
1118 queued_raster_keys: HashSet::new(),
1119 current_seq: 0,
1120 lookahead,
1121 cancelled: false,
1122 }),
1123 cv: Condvar::new(),
1124 });
1125 let worker_count = std::thread::available_parallelism()
1126 .map(|n| n.get().clamp(2, 6))
1127 .unwrap_or(4);
1128 let mut workers = Vec::with_capacity(worker_count);
1129 for _ in 0..worker_count {
1130 let s = Arc::clone(&shared);
1131 let q = Arc::clone(&queue);
1132 workers.push(std::thread::spawn(move || {
1133 Self::worker_loop(s, q);
1134 }));
1135 }
1136 Self {
1137 shared,
1138 queue,
1139 workers,
1140 }
1141 }
1142
1143 /// Updates the active render sequence index so read-ahead stays synchronized with playback/export.
1144 pub fn set_current_seq(&self, seq_idx: usize) {
1145 if let Ok(mut q) = self.queue.state.lock() {
1146 q.current_seq = seq_idx;
1147 self.queue.cv.notify_all();
1148 }
1149 }
1150
1151 /// Enqueues missing `Loader` decodes for `time` at sequence index `seq_idx`.
1152 pub fn enqueue_frame(
1153 &self,
1154 comp: &Comp,
1155 target: NodeId,
1156 seq_idx: usize,
1157 time: f64,
1158 expr: &model::ExprEngine,
1159 use_proxy_clips: bool,
1160 ) {
1161 let mut visited = HashSet::new();
1162 let mut jobs = MissingJobs::default();
1163 collect_missing_loader_jobs_shared(
1164 &self.shared,
1165 comp,
1166 target,
1167 time,
1168 expr,
1169 use_proxy_clips,
1170 &mut visited,
1171 &mut jobs,
1172 );
1173 if jobs.total_units() == 0 {
1174 return;
1175 }
1176 if let Ok(mut q) = self.queue.state.lock() {
1177 if q.cancelled {
1178 return;
1179 }
1180 for job in jobs.raster {
1181 if q.queued_raster_keys.insert(job.cache_key.clone()) {
1182 q.raster.push_back((seq_idx, job));
1183 }
1184 }
1185 for (path, reqs) in jobs.videos {
1186 let vq = q.videos.entry(path).or_default();
1187 for req in reqs {
1188 vq.push_back((seq_idx, req));
631 }1189 }
632 }1190 }
1191 self.queue.cv.notify_all();
633 }1192 }
634 for (job, slot) in raster_jobs.into_iter().zip(raster_slots) {1193 }
635 if let Ok(mut guard) = slot.into_inner() {1194
636 if let Some(decoded) = guard.take() {1195 /// Cancels pending read-ahead work and joins all background worker threads.
637 self.insert_cached(job.cache_key, decoded);1196 pub fn cancel(&mut self) {
1197 if let Ok(mut q) = self.queue.state.lock() {
1198 q.cancelled = true;
1199 q.raster.clear();
1200 q.videos.clear();
1201 q.queued_raster_keys.clear();
1202 self.queue.cv.notify_all();
1203 }
1204 for handle in self.workers.drain(..) {
1205 let _ = handle.join();
1206 }
1207 }
1208
1209 fn worker_loop(shared: Arc<MediaShared>, queue: Arc<PrefetchQueue>) {
1210 loop {
1211 let item = {
1212 let Ok(mut q) = queue.state.lock() else { return };
1213 loop {
1214 if q.cancelled {
1215 return;
1216 }
1217 let raster_seq = q.raster.front().map(|(seq, _)| *seq);
1218 let mut best_video: Option<(PathBuf, usize)> = None;
1219 for (path, vq) in &q.videos {
1220 if q.active_videos.contains(path) {
1221 continue;
1222 }
1223 if let Some(&(seq, _)) = vq.front() {
1224 if best_video.as_ref().is_none_or(|&(_, bseq)| seq < bseq) {
1225 best_video = Some((path.clone(), seq));
1226 }
1227 }
1228 }
1229
1230 let chosen_seq = match (raster_seq, &best_video) {
1231 (Some(rs), Some((_, vs))) => rs.min(*vs),
1232 (Some(rs), None) => rs,
1233 (None, Some((_, vs))) => *vs,
1234 (None, None) => {
1235 q = match queue.cv.wait(q) {
1236 Ok(g) => g,
1237 Err(_) => return,
1238 };
1239 continue;
1240 }
1241 };
1242
1243 if chosen_seq > q.current_seq.saturating_add(q.lookahead) {
1244 q = match queue.cv.wait(q) {
1245 Ok(g) => g,
1246 Err(_) => return,
1247 };
1248 continue;
1249 }
1250
1251 if chosen_seq > q.current_seq.saturating_add(1) {
1252 let over_soft_budget = shared.state.lock().is_ok_and(|s| {
1253 s.budget_bytes > 0 && s.total_bytes >= (s.budget_bytes * 3) / 4
1254 });
1255 if over_soft_budget {
1256 q = match queue.cv.wait(q) {
1257 Ok(g) => g,
1258 Err(_) => return,
1259 };
1260 continue;
1261 }
1262 }
1263
1264 if let Some((path, vs)) = best_video {
1265 if raster_seq.is_none_or(|rs| vs <= rs) {
1266 if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.pop_front()) {
1267 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
1268 q.videos.remove(&path);
1269 }
1270 q.active_videos.insert(path.clone());
1271 break PrefetchWorkItem::Video(path, req);
1272 }
1273 }
1274 }
1275 if let Some((_, job)) = q.raster.pop_front() {
1276 q.queued_raster_keys.remove(&job.cache_key);
1277 break PrefetchWorkItem::Raster(job);
1278 }
1279 }
1280 };
1281
1282 match item {
1283 PrefetchWorkItem::Raster(job) => {
1284 let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| {
1285 if state.images.contains_key(&job.cache_key)
1286 || state.in_flight.contains(&job.cache_key)
1287 {
1288 None
1289 } else {
1290 state.in_flight.insert(job.cache_key.clone());
1291 Some(state.generation)
1292 }
1293 });
1294 let Some(cache_gen) = cache_gen_opt else { continue };
1295 let mut guard = InFlightGuard {
1296 shared: &shared,
1297 key: Some(job.cache_key.clone()),
1298 };
1299 if let Some(decoded) = decode_job(&job, false) {
1300 if let Ok(mut state) = shared.state.lock() {
1301 state.in_flight.remove(&job.cache_key);
1302 guard.key = None;
1303 if state.generation == cache_gen {
1304 state.known_existing_paths.insert(job.cache_key.path.clone());
1305 state.insert_cached(job.cache_key, decoded);
1306 }
1307 shared.cv.notify_all();
1308 }
1309 }
1310 }
1311 PrefetchWorkItem::Video(path, req) => {
1312 struct ActiveVideoGuard<'a> {
1313 queue: &'a PrefetchQueue,
1314 path: PathBuf,
1315 }
1316 impl Drop for ActiveVideoGuard<'_> {
1317 fn drop(&mut self) {
1318 if let Ok(mut q) = self.queue.state.lock() {
1319 q.active_videos.remove(&self.path);
1320 self.queue.cv.notify_all();
1321 }
1322 }
1323 }
1324 let _active_guard = ActiveVideoGuard {
1325 queue: &queue,
1326 path: path.clone(),
1327 };
1328
1329 let Some((info, dec_arc)) = shared.get_or_open_video_decoder(&path) else {
1330 continue;
1331 };
1332 let frame_idx =
1333 compute_video_frame_idx(&req.clip, req.frame_i, info.nb_frames);
1334 let key = ImageCacheKey {
1335 path: path.clone(),
1336 frame_idx,
1337 post_multiply: req.post_multiply,
1338 exr_channels: [None, None, None, None],
1339 };
1340 let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| {
1341 if state.images.contains_key(&key) || state.in_flight.contains(&key) {
1342 None
1343 } else {
1344 state.in_flight.insert(key.clone());
1345 Some(state.generation)
1346 }
1347 });
1348 let Some(cache_gen) = cache_gen_opt else { continue };
1349 let mut guard = InFlightGuard {
1350 shared: &shared,
1351 key: Some(key.clone()),
1352 };
1353 let decoded_raw = dec_arc
1354 .lock()
1355 .ok()
1356 .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx));
1357 if let Some(mut raw) = decoded_raw {
1358 if req.post_multiply {
1359 apply_post_multiply_rgba8_parallel(&mut raw, false);
1360 }
1361 let decoded = DecodedImage {
1362 size: [info.width, info.height],
1363 rgba: Arc::new(raw),
1364 rgba_f16: None,
1365 rgba_f32: None,
1366 };
1367 if let Ok(mut state) = shared.state.lock() {
1368 state.in_flight.remove(&key);
1369 guard.key = None;
1370 if state.generation == cache_gen {
1371 state.insert_cached(key, decoded);
1372 }
1373 shared.cv.notify_all();
1374 }
1375 }
638 }1376 }
639 }1377 }
640 }1378 }
641 }1379 }
1380}
1381
1382#[cfg(not(target_arch = "wasm32"))]
1383impl Drop for MediaPrefetchHandle {
1384 fn drop(&mut self) {
1385 self.cancel();
1386 }
1387}
1388
1389#[cfg(not(target_arch = "wasm32"))]
1390#[allow(clippy::too_many_arguments)]
1391fn collect_missing_loader_jobs_shared(
1392 shared: &MediaShared,
1393 comp: &Comp,
1394 node_id: NodeId,
1395 time: f64,
1396 expr: &model::ExprEngine,
1397 use_proxy_clips: bool,
1398 visited: &mut HashSet<(NodeId, i64)>,
1399 jobs: &mut MissingJobs,
1400) {
1401 if node_id.0 >= comp.nodes.len() {
1402 return;
1403 }
1404 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
1405 if !visited.insert((node_id, time_key)) {
1406 return;
1407 }
1408 let node = comp.node(node_id);
1409
1410 if node.bypassed
1411 || matches!(
1412 node.kind.as_str(),
1413 "Saver"
1414 | "PipeRouter"
1415 | "Fuse.Wireless"
1416 | "Tracker"
1417 | "Dimension.OpticalFlow"
1418 | "OpticalFlow"
1419 | "Dimension.CopyAux"
1420 )
1421 {
1422 let port = default_main_input_port(&node.kind);
1423 if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) {
1424 collect_missing_loader_jobs_shared(
1425 shared,
1426 comp,
1427 src_id,
1428 time,
1429 expr,
1430 use_proxy_clips,
1431 visited,
1432 jobs,
1433 );
1434 }
1435 return;
1436 }
1437
1438 if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") {
1439 let next_id = node.macro_output.or_else(|| {
1440 node.connected_node("Input")
1441 .or_else(|| node.connected_node("MainInput1"))
1442 .and_then(|s| comp.find_node(s))
1443 });
1444 if let Some(src_id) = next_id {
1445 collect_missing_loader_jobs_shared(
1446 shared,
1447 comp,
1448 src_id,
1449 time,
1450 expr,
1451 use_proxy_clips,
1452 visited,
1453 jobs,
1454 );
1455 }
1456 return;
1457 }
6421458
643 #[cfg(not(target_arch = "wasm32"))]1459 if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") {
644 #[allow(clippy::too_many_arguments)]1460 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
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;1461 return;
657 }1462 };
658 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;1463 let remapped = match node.kind.as_str() {
659 if !visited.insert((node_id, time_key)) {1464 "TimeStretcher" => comp.eval_number(node, "SourceTime", time, 0.0, expr),
660 return;1465 "TimeSpeed" => {
661 }1466 let speed = comp.eval_number(node, "Speed", time, 1.0, expr);
662 let node = comp.node(node_id);1467 let delay = comp.eval_number(node, "Delay", time, 0.0, expr);
6631468 let g_start = comp.global_range[0] as f64;
664 if node.bypassed1469 let g_end = comp.global_range[1] as f64;
665 || matches!(1470 if speed < 0.0 {
666 node.kind.as_str(),1471 ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end)
667 "Saver"1472 } else {
668 | "PipeRouter"1473 g_start + (time - delay - g_start) * speed
669 | "Fuse.Wireless"1474 }
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 }1475 }
1476 _ => time,
1477 };
1478 let interp = comp
1479 .eval_number(node, "InterpolateBetweenFrames", time, 1.0, expr)
1480 .round() as i32;
1481 if interp <= 0 {
1482 let snapped = (remapped + 0.5).floor();
1483 collect_missing_loader_jobs_shared(
1484 shared,
1485 comp,
1486 src_id,
1487 snapped,
1488 expr,
1489 use_proxy_clips,
1490 visited,
1491 jobs,
1492 );
688 return;1493 return;
689 }1494 }
6901495 let f0 = remapped.floor();
691 if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") {1496 let frac = (remapped - f0) as f32;
692 let next_id = node.macro_output.or_else(|| {1497 if frac > 1e-3 && frac < 1.0 - 1e-3 {
693 node.connected_node("Input")1498 let src_node = comp.node(src_id);
694 .or_else(|| node.connected_node("MainInput1"))1499 let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow");
1500 let eval_src_id = if has_optflow {
1501 src_node
1502 .connected_node("Input")
695 .and_then(|s| comp.find_node(s))1503 .and_then(|s| comp.find_node(s))
696 });1504 .unwrap_or(src_id)
697 if let Some(src_id) = next_id {1505 } else {
698 self.collect_missing_loader_jobs(1506 src_id
699 comp,1507 };
700 src_id,1508 collect_missing_loader_jobs_shared(
701 time,1509 shared,
702 expr,1510 comp,
703 use_proxy_clips,1511 eval_src_id,
704 visited,1512 f0,
705 jobs,1513 expr,
706 );1514 use_proxy_clips,
707 }1515 visited,
708 return;1516 jobs,
1517 );
1518 collect_missing_loader_jobs_shared(
1519 shared,
1520 comp,
1521 eval_src_id,
1522 f0 + 1.0,
1523 expr,
1524 use_proxy_clips,
1525 visited,
1526 jobs,
1527 );
1528 } else {
1529 collect_missing_loader_jobs_shared(
1530 shared,
1531 comp,
1532 src_id,
1533 remapped,
1534 expr,
1535 use_proxy_clips,
1536 visited,
1537 jobs,
1538 );
709 }1539 }
1540 return;
1541 }
7101542
711 if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") {1543 if node.kind == "Switch" || node.kind == "Fuse.Switch" {
712 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {1544 let is_native_zero_indexed = node.kind == "Switch"
713 return;1545 && (node.inputs.contains_key("Source")
714 };1546 || node.inputs.contains_key("Input0")
715 let remapped = match node.kind.as_str() {1547 || !node.inputs.contains_key("Which"));
716 "TimeStretcher" => comp.eval_number(node, "SourceTime", time, 0.0, expr),1548 let src_name = if is_native_zero_indexed {
717 "TimeSpeed" => {1549 let source = comp
718 let speed = comp.eval_number(node, "Speed", time, 1.0, expr);1550 .eval_number(node, "Source", time, 0.0, expr)
719 let delay = comp.eval_number(node, "Delay", time, 0.0, expr);1551 .round()
720 let g_start = comp.global_range[0] as f64;1552 .max(0.0) as usize;
721 let g_end = comp.global_range[1] as f64;1553 let port = format!("Input{source}");
722 if speed < 0.0 {1554 node.connected_node(&port)
723 ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end)1555 .or_else(|| node.connected_node("Input0"))
724 } else {1556 } else {
725 g_start + (time - delay - g_start) * speed1557 let which = comp
726 }1558 .eval_number(node, "Which", time, 1.0, expr)
727 }1559 .round()
728 _ => time,1560 .max(1.0) as usize;
729 };1561 let port = format!("Input{which}");
730 let interp = comp1562 node.connected_node(&port)
731 .eval_number(node, "InterpolateBetweenFrames", time, 1.0, expr)1563 .or_else(|| node.connected_node("Input1"))
732 .round() as i32;1564 };
733 if interp <= 0 {1565 if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) {
734 let snapped = (remapped + 0.5).floor();1566 collect_missing_loader_jobs_shared(
735 self.collect_missing_loader_jobs(1567 shared,
736 comp,1568 comp,
737 src_id,1569 src_id,
738 snapped,1570 time,
739 expr,1571 expr,
740 use_proxy_clips,1572 use_proxy_clips,
741 visited,1573 visited,
742 jobs,1574 jobs,
743 );1575 );
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 }1576 }
1577 return;
1578 }
7901579
791 if node.kind == "Switch" || node.kind == "Fuse.Switch" {1580 if node.kind == "Fuse.SwitchElse" {
792 let is_native_zero_indexed = node.kind == "Switch"1581 let index = |name: &str, default: f64| {
793 && (node.inputs.contains_key("Source")1582 comp.eval_number(node, name, time, default, expr)
794 || node.inputs.contains_key("Input0")1583 .round()
795 || !node.inputs.contains_key("Which"));1584 .max(1.0) as usize
796 let src_name = if is_native_zero_indexed {1585 };
797 let source = comp1586 let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| {
798 .eval_number(node, "Source", time, 0.0, expr)1587 node.connected_node(&format!("Input{i}"))
799 .round()1588 .and_then(|s| comp.find_node(s))
800 .max(0.0) as usize;1589 });
801 let port = format!("Input{source}");1590 if let Some(src_id) = picked {
802 node.connected_node(&port)1591 collect_missing_loader_jobs_shared(
803 .or_else(|| node.connected_node("Input0"))1592 shared,
804 } else {1593 comp,
805 let which = comp1594 src_id,
806 .eval_number(node, "Which", time, 1.0, expr)1595 time,
807 .round()1596 expr,
808 .max(1.0) as usize;1597 use_proxy_clips,
809 let port = format!("Input{which}");1598 visited,
810 node.connected_node(&port)1599 jobs,
811 .or_else(|| node.connected_node("Input1"))1600 );
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 }1601 }
1602 return;
1603 }
8261604
827 if node.kind == "Fuse.SwitchElse" {1605 if node.kind == "Merge" {
828 let index = |name: &str, default: f64| {1606 if let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) {
829 comp.eval_number(node, name, time, default, expr)1607 collect_missing_loader_jobs_shared(
830 .round()1608 shared,
831 .max(1.0) as usize1609 comp,
832 };1610 bg_id,
833 let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| {1611 time,
834 node.connected_node(&format!("Input{i}"))1612 expr,
835 .and_then(|s| comp.find_node(s))1613 use_proxy_clips,
836 });1614 visited,
837 if let Some(src_id) = picked {1615 jobs,
838 self.collect_missing_loader_jobs(1616 );
1617 }
1618 let blend = comp.eval_number(node, "Blend", time, 1.0, expr) as f32;
1619 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, expr) > 0.5;
1620 let mask_id = resolve_effect_mask_id_for_node(comp, node);
1621 if !(blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some())) {
1622 if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) {
1623 collect_missing_loader_jobs_shared(
1624 shared,
839 comp,1625 comp,
840 src_id,1626 fg_id,
841 time,1627 time,
842 expr,1628 expr,
843 use_proxy_clips,1629 use_proxy_clips,
...@@ -845,117 +1631,91 @@ impl MediaCache {...@@ -845,117 +1631,91 @@ impl MediaCache {
845 jobs,1631 jobs,
846 );1632 );
847 }1633 }
848 return;
849 }1634 }
1635 if let Some(mid) = mask_id {
1636 collect_missing_loader_jobs_shared(
1637 shared,
1638 comp,
1639 mid,
1640 time,
1641 expr,
1642 use_proxy_clips,
1643 visited,
1644 jobs,
1645 );
1646 }
1647 return;
1648 }
8501649
851 if node.kind == "Merge" {1650 if node.kind == "Loader" {
852 if let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) {1651 if let Some(clip) = node.clips.first() {
853 self.collect_missing_loader_jobs(1652 let frame_i = time.round() as i64;
854 comp,1653 let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5;
855 bg_id,1654 let exr_channels = [
1655 node.static_str("Clip1.OpenEXRFormat.RedName"),
1656 node.static_str("Clip1.OpenEXRFormat.GreenName"),
1657 node.static_str("Clip1.OpenEXRFormat.BlueName"),
1658 node.static_str("Clip1.OpenEXRFormat.AlphaName"),
1659 ];
1660 let mut effective_clip = clip.clone();
1661 if node.inputs.contains_key("GlobalIn") {
1662 effective_clip.global_start = comp
1663 .eval_number(node, "GlobalIn", time, effective_clip.global_start as f64, expr)
1664 .round() as i64;
1665 }
1666 if node.inputs.contains_key("GlobalOut") {
1667 effective_clip.global_end = comp
1668 .eval_number(node, "GlobalOut", time, effective_clip.global_end as f64, expr)
1669 .round() as i64;
1670 }
1671 if node.inputs.contains_key("Loop") {
1672 effective_clip.loop_clip = comp.eval_number(
1673 node,
1674 "Loop",
856 time,1675 time,
1676 if effective_clip.loop_clip { 1.0 } else { 0.0 },
857 expr,1677 expr,
858 use_proxy_clips,1678 ) > 0.5;
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 }1679 }
879 if let Some(mid) = mask_id {1680 if node.inputs.contains_key("Reverse") {
880 self.collect_missing_loader_jobs(1681 effective_clip.reverse = comp.eval_number(
881 comp,1682 node,
882 mid,1683 "Reverse",
883 time,1684 time,
1685 if effective_clip.reverse { 1.0 } else { 0.0 },
884 expr,1686 expr,
885 use_proxy_clips,1687 ) > 0.5;
886 visited,
887 jobs,
888 );
889 }1688 }
890 return;1689 if use_proxy_clips {
891 }1690 let proxy_candidate = node
8921691 .static_str("ProxyFilename")
893 if node.kind == "Loader" {1692 .filter(|s| !s.trim().is_empty())
894 if let Some(clip) = node.clips.first() {1693 .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty()));
895 let frame_i = time.round() as i64;1694 if let Some(proxy_name) = proxy_candidate {
896 let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5;1695 let mut proxy_clip = effective_clip.clone();
897 let exr_channels = [1696 proxy_clip.filename = proxy_name.to_owned();
898 node.static_str("Clip1.OpenEXRFormat.RedName"),1697 if shared.resolve_clip_path_cached(&proxy_clip, frame_i).is_some() {
899 node.static_str("Clip1.OpenEXRFormat.GreenName"),1698 effective_clip = proxy_clip;
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 }1699 }
944 }1700 }
945 let out_of_range = effective_clip.global_end >= effective_clip.global_start1701 }
946 && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0)1702 let out_of_range = effective_clip.global_end >= effective_clip.global_start
947 || (!effective_clip.loop_clip1703 && (frame_i < effective_clip.global_start - effective_clip.extend_first.max(0)
948 && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0)));1704 || (!effective_clip.loop_clip
949 if !out_of_range {1705 && frame_i > effective_clip.global_end + effective_clip.extend_last.max(0)));
950 let base = Path::new(&effective_clip.filename);1706 if !out_of_range {
951 if is_video_path(base) {1707 let base = Path::new(&effective_clip.filename);
952 if base.exists() && video_frame_in_range(&effective_clip, frame_i) {1708 if is_video_path(base) {
953 let need_decode = match self.video_decoders.get(base) {1709 if video_frame_in_range(&effective_clip, frame_i)
954 Some(entry) => entry.decoder.as_ref().is_some_and(|dec| {1710 && shared.path_exists_cached(base)
1711 {
1712 let need_decode = shared.state.lock().is_ok_and(|state| {
1713 match state.video_decoders.get(base) {
1714 Some(slot) => slot.info.is_some_and(|info| {
955 let idx = compute_video_frame_idx(1715 let idx = compute_video_frame_idx(
956 &effective_clip,1716 &effective_clip,
957 frame_i,1717 frame_i,
958 dec.info().nb_frames,1718 info.nb_frames,
959 );1719 );
960 let cache_key = ImageCacheKey {1720 let cache_key = ImageCacheKey {
961 path: base.to_path_buf(),1721 path: base.to_path_buf(),
...@@ -963,81 +1723,60 @@ impl MediaCache {...@@ -963,81 +1723,60 @@ impl MediaCache {
963 post_multiply: post_mult,1723 post_multiply: post_mult,
964 exr_channels: [None, None, None, None],1724 exr_channels: [None, None, None, None],
965 };1725 };
966 !self.images.contains_key(&cache_key)1726 !state.images.contains_key(&cache_key)
1727 && !state.in_flight.contains(&cache_key)
967 }),1728 }),
968 None => true,1729 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 }1730 }
980 }1731 });
981 } else if let Some(resolved) = resolve_clip_path(&effective_clip, frame_i) {1732 if need_decode {
982 let is_exr = is_exr_path(&resolved);1733 jobs.videos
983 let key_channels = if is_exr {1734 .entry(base.to_path_buf())
984 [1735 .or_default()
985 normalize_channel_opt(exr_channels[0]),1736 .push(VideoFrameRequest {
986 normalize_channel_opt(exr_channels[1]),1737 clip: effective_clip,
987 normalize_channel_opt(exr_channels[2]),1738 frame_i,
988 normalize_channel_opt(exr_channels[3]),1739 post_multiply: post_mult,
989 ]1740 });
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 }1741 }
1004 }1742 }
1005 }1743 } else if let Some(resolved) = resolve_clip_candidate_path(&effective_clip, frame_i) {
1006 }1744 let is_exr = is_exr_path(&resolved);
1007 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {1745 let key_channels = if is_exr {
1008 self.collect_missing_loader_jobs(1746 [
1009 comp,1747 normalize_channel_opt(exr_channels[0]),
1010 mid,1748 normalize_channel_opt(exr_channels[1]),
1011 time,1749 normalize_channel_opt(exr_channels[2]),
1012 expr,1750 normalize_channel_opt(exr_channels[3]),
1013 use_proxy_clips,1751 ]
1014 visited,1752 } else {
1015 jobs,1753 [None, None, None, None]
1016 );1754 };
1017 }1755 let cache_key = ImageCacheKey {
1018 return;1756 path: resolved.clone(),
1019 }1757 frame_idx: -1,
10201758 post_multiply: post_mult && !is_exr,
1021 // General node: traverse all wired upstream node inputs and inherited EffectMask.1759 exr_channels: key_channels,
1022 let mut child_ids = Vec::new();1760 };
1023 for binding in node.inputs.values() {1761 let missing = shared.state.lock().is_ok_and(|state| {
1024 if let Some(src) = binding.source_op.as_deref() {1762 !state.images.contains_key(&cache_key)
1025 if let Some(cid) = comp.find_node(src) {1763 && !state.in_flight.contains(&cache_key)
1026 if !child_ids.contains(&cid) {1764 });
1027 child_ids.push(cid);1765 if missing
1766 && !jobs.seen_raster.contains(&cache_key)
1767 && shared.path_exists_cached(&resolved)
1768 {
1769 jobs.seen_raster.insert(cache_key.clone());
1770 jobs.raster.push(PreloadJob { cache_key, is_exr });
1028 }1771 }
1029 }1772 }
1030 }1773 }
1031 }1774 }
1032 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {1775 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {
1033 if !child_ids.contains(&mid) {1776 collect_missing_loader_jobs_shared(
1034 child_ids.push(mid);1777 shared,
1035 }
1036 }
1037 for cid in child_ids {
1038 self.collect_missing_loader_jobs(
1039 comp,1778 comp,
1040 cid,1779 mid,
1041 time,1780 time,
1042 expr,1781 expr,
1043 use_proxy_clips,1782 use_proxy_clips,
...@@ -1045,6 +1784,36 @@ impl MediaCache {...@@ -1045,6 +1784,36 @@ impl MediaCache {
1045 jobs,1784 jobs,
1046 );1785 );
1047 }1786 }
1787 return;
1788 }
1789
1790 // General node: traverse all wired upstream node inputs and inherited EffectMask.
1791 let mut child_ids = Vec::new();
1792 for binding in node.inputs.values() {
1793 if let Some(src) = binding.source_op.as_deref() {
1794 if let Some(cid) = comp.find_node(src) {
1795 if !child_ids.contains(&cid) {
1796 child_ids.push(cid);
1797 }
1798 }
1799 }
1800 }
1801 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {
1802 if !child_ids.contains(&mid) {
1803 child_ids.push(mid);
1804 }
1805 }
1806 for cid in child_ids {
1807 collect_missing_loader_jobs_shared(
1808 shared,
1809 comp,
1810 cid,
1811 time,
1812 expr,
1813 use_proxy_clips,
1814 visited,
1815 jobs,
1816 );
1048 }1817 }
1049}1818}
10501819
...@@ -1103,7 +1872,6 @@ struct VideoFrameRequest {...@@ -1103,7 +1872,6 @@ struct VideoFrameRequest {
1103#[cfg(not(target_arch = "wasm32"))]1872#[cfg(not(target_arch = "wasm32"))]
1104struct VideoDecodeTask {1873struct VideoDecodeTask {
1105 path: PathBuf,1874 path: PathBuf,
1106 decoder: Option<Box<dyn VideoDecoder>>,
1107 requests: Vec<VideoFrameRequest>,1875 requests: Vec<VideoFrameRequest>,
1108}1876}
11091877
...@@ -1168,8 +1936,7 @@ fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option<NodeId> {...@@ -1168,8 +1936,7 @@ fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option<NodeId> {
1168 None1936 None
1169}1937}
11701938
1171/// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`.1939fn resolve_clip_candidate_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
1172pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
1173 let base = Path::new(&clip.filename);1940 let base = Path::new(&clip.filename);
1174 let len = clip.length.unwrap_or(1);1941 let len = clip.length.unwrap_or(1);
1175 let stem = base.file_stem()?.to_str()?;1942 let stem = base.file_stem()?.to_str()?;
...@@ -1179,7 +1946,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {...@@ -1179,7 +1946,7 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
1179 let digits = &stem[digit_start..];1946 let digits = &stem[digit_start..];
1180 let is_seq = len > 1 && (clip.start_frame >= 0 || !digits.is_empty());1947 let is_seq = len > 1 && (clip.start_frame >= 0 || !digits.is_empty());
1181 if !is_seq || digits.is_empty() {1948 if !is_seq || digits.is_empty() {
1182 return path_exists(base).then(|| base.to_path_buf());1949 return Some(base.to_path_buf());
1183 }1950 }
11841951
1185 let seq_start = if clip.start_frame >= 0 { clip.start_frame } else { 0 };1952 let seq_start = if clip.start_frame >= 0 { clip.start_frame } else { 0 };
...@@ -1206,7 +1973,12 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {...@@ -1206,7 +1973,12 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
1206 } else {1973 } else {
1207 format!("{prefix}{idx:0width$}.{ext}")1974 format!("{prefix}{idx:0width$}.{ext}")
1208 };1975 };
1209 let candidate = base.with_file_name(new_name);1976 Some(base.with_file_name(new_name))
1977}
1978
1979/// Resolves a Fusion `ClipSpec` (still image or numbered image sequence) at `frame`.
1980pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
1981 let candidate = resolve_clip_candidate_path(clip, frame)?;
1210 path_exists(&candidate).then_some(candidate)1982 path_exists(&candidate).then_some(candidate)
1211}1983}
1212#[cfg(test)]1984#[cfg(test)]
...@@ -1823,11 +2595,14 @@ mod tests {...@@ -1823,11 +2595,14 @@ mod tests {
1823 assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192);2595 assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192);
1824 let default_cache = MediaCache::default();2596 let default_cache = MediaCache::default();
1825 assert_eq!(2597 assert_eq!(
1826 default_cache.budget_bytes,2598 default_cache.shared.state.lock().unwrap().budget_bytes,
1827 default_media_cache_budget_mb().saturating_mul(1024 * 1024)2599 default_media_cache_budget_mb().saturating_mul(1024 * 1024)
1828 );2600 );
1829 let explicit = MediaCache::with_budget_mb(32);2601 let explicit = MediaCache::with_budget_mb(32);
1830 assert_eq!(explicit.budget_bytes, 32 * 1024 * 1024);2602 assert_eq!(
2603 explicit.shared.state.lock().unwrap().budget_bytes,
2604 32 * 1024 * 1024
2605 );
1831 }2606 }
18322607
1833 #[test]2608 #[test]
...@@ -2061,4 +2836,68 @@ mod tests {...@@ -2061,4 +2836,68 @@ mod tests {
20612836
2062 let _ = std::fs::remove_dir_all(&dir);2837 let _ = std::fs::remove_dir_all(&dir);
2063 }2838 }
2839
2840 #[cfg(not(target_arch = "wasm32"))]
2841 #[test]
2842 fn background_frame_prefetch_populates_and_cancels_cleanly() {
2843 let dir = std::env::temp_dir().join(format!("fission_bg_prefetch_{}", std::process::id()));
2844 let _ = std::fs::remove_dir_all(&dir);
2845 std::fs::create_dir_all(&dir).unwrap();
2846
2847 for i in 0..4 {
2848 let p = dir.join(format!("seq_{i:04}.png"));
2849 image::RgbaImage::from_pixel(4, 4, image::Rgba([i as u8 * 50, 10, 200, 255]))
2850 .save(&p)
2851 .unwrap();
2852 }
2853 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
2854 let p0 = dir.join("seq_0000.png");
2855 let comp_src = format!(
2856 r#"Composition {{
2857 CurrentTime = 0,
2858 RenderRange = {{ 0, 3 }},
2859 GlobalRange = {{ 0, 3 }},
2860 Tools = ordered() {{
2861 LD = Loader {{
2862 Clips = {{
2863 Clip {{
2864 ID = "Clip1",
2865 Filename = "{}",
2866 FormatID = "PNGFormat",
2867 StartFrame = 0,
2868 Length = 4,
2869 GlobalStart = 0,
2870 GlobalEnd = 3,
2871 }},
2872 }},
2873 }},
2874 }},
2875}}"#,
2876 esc(&p0)
2877 );
2878 let comp = Comp::from_fusion_str(&comp_src).expect("parse bg prefetch comp");
2879 let target = comp.find_node("LD").unwrap();
2880 let clip = comp.node(target).clips[0].clone();
2881 let expr = model::ExprEngine::new();
2882 let mut cache = MediaCache::new(64);
2883
2884 let mut handle = cache.start_frame_prefetch(4);
2885 for f in 0..=3 {
2886 handle.enqueue_frame(&comp, target, f, f as f64, &expr, false);
2887 }
2888 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2889 while cache.entry_count() < 4 && std::time::Instant::now() < deadline {
2890 std::thread::sleep(std::time::Duration::from_millis(5));
2891 }
2892 assert_eq!(cache.entry_count(), 4);
2893 for f in 0..=3 {
2894 let (_, _, img, from_disk) = cache.load_clip(&clip, f, false, [None; 4]).unwrap();
2895 assert!(!from_disk, "frame {f} should already be in MediaCache");
2896 assert_eq!(img.rgba[0], (f as u8) * 50);
2897 }
2898 handle.cancel();
2899 drop(handle);
2900
2901 let _ = std::fs::remove_dir_all(&dir);
2902 }
2064}2903}