authoravatarclover caruso<git@paperclover.net>2026-12-01 21:58:26-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 22:07:29-08:00
logd030c95f46cc2ba3c53447e31f9b327fa8684e3e
treebb8d2a4fb945e30a489080941dc3b6e66e351b76
parent4bfee714f3fecab65dbb6919de5f1d8b6272452b
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

refactor(engine): split media.rs into png, prefetch, and tests submodules


4 files changed, 3022 insertions(+), 3006 deletions(-)

crates/engine/src/media.rs+11-3006
......@@ -2,10 +2,16 @@
22//! CPU rasterizers (`TextPlus` via `text_engine`, `PolylineMask` via `zeno`).
33
44mod exr;
5mod png;
6mod prefetch;
57mod raster;
8#[cfg(test)]
9mod tests;
610mod video;
711
812pub use exr::f32_to_f16_bits;
13#[cfg(not(target_arch = "wasm32"))]
14pub use prefetch::MediaPrefetchHandle;
915pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus};
1016#[cfg(target_os = "macos")]
1117pub use video::AvFoundationDecoder;
......@@ -14,6 +20,11 @@ use exr::{
1420 apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path,
1521 normalize_channel_opt,
1622};
23use png::decode_raster_image;
24#[cfg(test)]
25use png::{PngDecodeOutcome, decode_png_bytes, decode_raster_bytes};
26#[cfg(not(target_arch = "wasm32"))]
27use prefetch::PrefetchQueue;
1728use video::is_video_path;
1829
1930use crate::text_engine;
......@@ -129,254 +140,6 @@ fn path_exists(path: &Path) -> bool {
129140 virtual_bytes(path).is_some() || path.exists()
130141}
131142
132#[inline(always)]
133fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 {
134 ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8
135}
136
137const MAX_PNG_OUTPUT_BYTES: usize = 512 * 1024 * 1024;
138
139enum PngDecodeOutcome {
140 Decoded(([u32; 2], Vec<u8>, bool)),
141 Fallback,
142 Reject,
143}
144
145fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>(
146 reader: &mut png::Reader<R>,
147 line_size: usize,
148 out_len: usize,
149 row_out_bytes: usize,
150 mut convert_row: F,
151) -> Option<Vec<u8>>
152where
153 F: FnMut(&[u8], &mut [u8]),
154{
155 let mut rgba = Vec::new();
156 rgba.try_reserve_exact(out_len).ok()?;
157 rgba.resize(out_len, 0);
158 let mut row_buf = Vec::new();
159 row_buf.try_reserve_exact(line_size).ok()?;
160 row_buf.resize(line_size, 0);
161 for dst_row in rgba.chunks_exact_mut(row_out_bytes) {
162 reader.read_row(&mut row_buf).ok()??;
163 convert_row(&row_buf, dst_row);
164 }
165 Some(rgba)
166}
167
168/// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit.
169/// Returns `Fallback` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the
170/// caller falls back cleanly to `image::load_from_memory`, and `Reject` for corrupt or
171/// oversized PNGs so callers fail immediately without double-decoding or OOM.
172fn decode_png_bytes(bytes: &[u8]) -> PngDecodeOutcome {
173 const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
174 if !bytes.starts_with(&PNG_SIGNATURE) {
175 return PngDecodeOutcome::Fallback;
176 }
177
178 let mut decoder = png::Decoder::new_with_limits(
179 std::io::Cursor::new(bytes),
180 png::Limits {
181 bytes: MAX_PNG_OUTPUT_BYTES,
182 },
183 );
184 decoder.set_ignore_text_chunk(true);
185 decoder.set_transformations(png::Transformations::EXPAND);
186
187 let Ok(mut reader) = decoder.read_info() else {
188 return PngDecodeOutcome::Reject;
189 };
190 let info = reader.info();
191 let (w, h) = info.size();
192 if w == 0 || h == 0 {
193 return PngDecodeOutcome::Reject;
194 }
195
196 let Some(pixel_count) = (w as usize).checked_mul(h as usize) else {
197 return PngDecodeOutcome::Reject;
198 };
199 let Some(out_len) = pixel_count.checked_mul(4) else {
200 return PngDecodeOutcome::Reject;
201 };
202 if out_len > MAX_PNG_OUTPUT_BYTES {
203 return PngDecodeOutcome::Reject;
204 }
205
206 if info.interlaced
207 || info.icc_profile.is_some()
208 || info.animation_control.is_some()
209 || info.frame_control.is_some()
210 {
211 return PngDecodeOutcome::Fallback;
212 }
213
214 let (color_type, bit_depth) = reader.output_color_type();
215 let Some(row_out_bytes) = (w as usize).checked_mul(4) else {
216 return PngDecodeOutcome::Reject;
217 };
218 let Some(line_size) = reader.output_line_size(w) else {
219 return PngDecodeOutcome::Reject;
220 };
221
222 match (color_type, bit_depth) {
223 (png::ColorType::Rgba, png::BitDepth::Eight) => {
224 let mut rgba = Vec::new();
225 if rgba.try_reserve_exact(out_len).is_err() {
226 return PngDecodeOutcome::Reject;
227 }
228 rgba.resize(out_len, 0);
229 if reader.next_frame(&mut rgba).is_err() {
230 return PngDecodeOutcome::Reject;
231 }
232 PngDecodeOutcome::Decoded(([w, h], rgba, true))
233 }
234 (png::ColorType::Rgb, png::BitDepth::Eight) => {
235 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
236 let (src_chunks, _) = src.as_chunks::<3>();
237 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
238 for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) {
239 *dst_px = [r, g, b, 255];
240 }
241 }) else {
242 return PngDecodeOutcome::Reject;
243 };
244 PngDecodeOutcome::Decoded(([w, h], rgba, false))
245 }
246 (png::ColorType::Grayscale, png::BitDepth::Eight) => {
247 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
248 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
249 for (&g, dst_px) in src.iter().zip(dst_chunks) {
250 *dst_px = [g, g, g, 255];
251 }
252 }) else {
253 return PngDecodeOutcome::Reject;
254 };
255 PngDecodeOutcome::Decoded(([w, h], rgba, false))
256 }
257 (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => {
258 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
259 let (src_chunks, _) = src.as_chunks::<2>();
260 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
261 for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) {
262 *dst_px = [g, g, g, a];
263 }
264 }) else {
265 return PngDecodeOutcome::Reject;
266 };
267 PngDecodeOutcome::Decoded(([w, h], rgba, true))
268 }
269 (png::ColorType::Rgba, png::BitDepth::Sixteen) => {
270 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
271 let (src_chunks, _) = src.as_chunks::<8>();
272 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
273 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
274 *dst_px = [
275 u16_be_to_u8_rounded(s[0], s[1]),
276 u16_be_to_u8_rounded(s[2], s[3]),
277 u16_be_to_u8_rounded(s[4], s[5]),
278 u16_be_to_u8_rounded(s[6], s[7]),
279 ];
280 }
281 }) else {
282 return PngDecodeOutcome::Reject;
283 };
284 PngDecodeOutcome::Decoded(([w, h], rgba, true))
285 }
286 (png::ColorType::Rgb, png::BitDepth::Sixteen) => {
287 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
288 let (src_chunks, _) = src.as_chunks::<6>();
289 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
290 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
291 *dst_px = [
292 u16_be_to_u8_rounded(s[0], s[1]),
293 u16_be_to_u8_rounded(s[2], s[3]),
294 u16_be_to_u8_rounded(s[4], s[5]),
295 255,
296 ];
297 }
298 }) else {
299 return PngDecodeOutcome::Reject;
300 };
301 PngDecodeOutcome::Decoded(([w, h], rgba, false))
302 }
303 (png::ColorType::Grayscale, png::BitDepth::Sixteen) => {
304 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
305 let (src_chunks, _) = src.as_chunks::<2>();
306 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
307 for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) {
308 let g = u16_be_to_u8_rounded(hi, lo);
309 *dst_px = [g, g, g, 255];
310 }
311 }) else {
312 return PngDecodeOutcome::Reject;
313 };
314 PngDecodeOutcome::Decoded(([w, h], rgba, false))
315 }
316 (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => {
317 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
318 let (src_chunks, _) = src.as_chunks::<4>();
319 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
320 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
321 let g = u16_be_to_u8_rounded(s[0], s[1]);
322 *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])];
323 }
324 }) else {
325 return PngDecodeOutcome::Reject;
326 };
327 PngDecodeOutcome::Decoded(([w, h], rgba, true))
328 }
329 _ => PngDecodeOutcome::Fallback,
330 }
331}
332
333fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
334 match decode_png_bytes(bytes) {
335 PngDecodeOutcome::Decoded(decoded) => return Some(decoded),
336 PngDecodeOutcome::Reject => return None,
337 PngDecodeOutcome::Fallback => {}
338 }
339 let dyn_img = image::load_from_memory(bytes).ok()?;
340 let has_alpha = dyn_img.color().has_alpha();
341 let size = [dyn_img.width(), dyn_img.height()];
342 let raw = dyn_img.into_rgba8().into_raw();
343 Some((size, raw, has_alpha))
344}
345
346fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec<u8>, bool)> {
347 if let Some(bytes) = virtual_bytes(path) {
348 return decode_raster_bytes(&bytes);
349 }
350 // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares.
351 match std::fs::read(path) {
352 Ok(bytes) => return decode_raster_bytes(&bytes),
353 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
354 Err(_) => {}
355 }
356 let dyn_img = image::open(path).ok()?;
357 let has_alpha = dyn_img.color().has_alpha();
358 let size = [dyn_img.width(), dyn_img.height()];
359 let raw = dyn_img.into_rgba8().into_raw();
360 Some((size, raw, has_alpha))
361}
362
363fn decode_raster_image(
364 path: &Path,
365 post_multiply: bool,
366 allow_parallel_premult: bool,
367) -> Option<DecodedImage> {
368 let (size, mut raw, has_alpha) = open_raster_rgba(path)?;
369 if post_multiply && has_alpha {
370 apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult);
371 }
372 Some(DecodedImage {
373 size,
374 rgba: Arc::new(raw),
375 rgba_f16: None,
376 rgba_f32: None,
377 })
378}
379
380143pub(crate) fn media_cache_budget_mb_for_total_bytes(total_bytes: u64) -> u64 {
381144 let gib = total_bytes / (1024 * 1024 * 1024);
382145 if gib >= 128 {
......@@ -481,37 +244,6 @@ impl MediaState {
481244 let _ = path;
482245 }
483246
484 #[cfg(not(target_arch = "wasm32"))]
485 fn record_speculative_decode(&mut self, bytes: u64) {
486 self.speculative_bytes_since_seq = self.speculative_bytes_since_seq.saturating_add(bytes);
487 self.speculative_count_since_seq = self.speculative_count_since_seq.saturating_add(1);
488 self.last_speculative_bytes = bytes;
489 }
490
491 #[cfg(not(target_arch = "wasm32"))]
492 fn reset_speculative_window(&mut self, seq_idx: usize) {
493 if self.last_prefetch_seq != Some(seq_idx) {
494 self.last_prefetch_seq = Some(seq_idx);
495 self.speculative_bytes_since_seq = 0;
496 self.speculative_count_since_seq = 0;
497 }
498 }
499
500 #[cfg(not(target_arch = "wasm32"))]
501 fn should_throttle_lookahead(&self) -> bool {
502 const MIN_LOOKAHEAD_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
503 if self.budget_bytes < MIN_LOOKAHEAD_BUDGET_BYTES {
504 return true;
505 }
506 let avg_item_bytes = if self.speculative_count_since_seq > 0 {
507 self.speculative_bytes_since_seq / self.speculative_count_since_seq
508 } else {
509 self.last_speculative_bytes
510 };
511 let in_flight_est = (self.in_flight.len() as u64).saturating_mul(avg_item_bytes);
512 self.speculative_bytes_since_seq.saturating_add(in_flight_est) >= self.budget_bytes / 2
513 }
514
515247 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
516248 let bytes = decoded.byte_size();
517249 self.tick += 1;
......@@ -594,51 +326,6 @@ impl MediaShared {
594326 }
595327 }
596328
597 fn sync_lookahead_throttle(&self, state: &MediaState) -> bool {
598 #[cfg(not(target_arch = "wasm32"))]
599 {
600 let throttled = state.should_throttle_lookahead();
601 let was_throttled = self.lookahead_throttled.load(Ordering::Acquire);
602 self.lookahead_throttled.store(throttled, Ordering::Release);
603 was_throttled && !throttled
604 }
605 #[cfg(target_arch = "wasm32")]
606 {
607 let _ = state;
608 false
609 }
610 }
611
612 #[cfg(not(target_arch = "wasm32"))]
613 fn register_prefetch_queue(&self, queue: &Arc<PrefetchQueue>) {
614 if let Ok(mut queues) = self.prefetch_queues.lock() {
615 queues.retain(|w| w.strong_count() > 0);
616 queues.push(Arc::downgrade(queue));
617 }
618 }
619
620 #[cfg(not(target_arch = "wasm32"))]
621 fn notify_prefetch_waiters(&self) {
622 let live: Vec<Arc<PrefetchQueue>> = {
623 let Ok(mut queues) = self.prefetch_queues.lock() else { return };
624 let mut out = Vec::with_capacity(queues.len());
625 queues.retain(|w| {
626 if let Some(q) = w.upgrade() {
627 out.push(q);
628 true
629 } else {
630 false
631 }
632 });
633 out
634 };
635 for q in live {
636 if let Ok(_guard) = q.state.lock() {
637 q.cv.notify_all();
638 }
639 }
640 }
641
642329 fn insert_cached_locked(
643330 &self,
644331 state: &mut MediaState,
......@@ -1263,1142 +950,6 @@ impl MediaCache {
1263950 let _ = unthrottled;
1264951 Some((resolved, -1, decoded, true))
1265952 }
1266
1267 /// Walks reachable `Loader` nodes upstream of `target` at `time` and decodes any missing
1268 /// still/sequence/EXR frames into RAM in parallel when 2 or more distinct files are uncached.
1269 pub fn preload_frame_loaders(
1270 &mut self,
1271 comp: &Comp,
1272 target: NodeId,
1273 time: f64,
1274 expr: &model::ExprEngine,
1275 ) {
1276 self.preload_frame_loaders_with_proxy(comp, target, time, expr, false);
1277 }
1278
1279 /// Variant of [`Self::preload_frame_loaders`] honoring `use_proxy_clips`.
1280 pub fn preload_frame_loaders_with_proxy(
1281 &mut self,
1282 comp: &Comp,
1283 target: NodeId,
1284 time: f64,
1285 expr: &model::ExprEngine,
1286 use_proxy_clips: bool,
1287 ) {
1288 #[cfg(target_arch = "wasm32")]
1289 {
1290 let _ = (comp, target, time, expr, use_proxy_clips);
1291 }
1292 #[cfg(not(target_arch = "wasm32"))]
1293 {
1294 let mut visited = HashSet::new();
1295 let mut jobs = MissingJobs::default();
1296 collect_missing_loader_jobs_shared(
1297 &self.shared,
1298 comp,
1299 target,
1300 time,
1301 expr,
1302 use_proxy_clips,
1303 &mut visited,
1304 &mut jobs,
1305 );
1306 if jobs.total_units() < 2 {
1307 return;
1308 }
1309 self.decode_jobs_parallel(jobs);
1310 }
1311 }
1312
1313 /// Pre-decodes reachable `Loader` files for upcoming `frames` in parallel into `MediaCache`.
1314 pub fn prefetch_frames(
1315 &mut self,
1316 comp: &Comp,
1317 target: NodeId,
1318 frames: &[f64],
1319 expr: &model::ExprEngine,
1320 ) {
1321 self.prefetch_frames_with_proxy(comp, target, frames, expr, false);
1322 }
1323
1324 /// Variant of [`Self::prefetch_frames`] honoring `use_proxy_clips`.
1325 pub fn prefetch_frames_with_proxy(
1326 &mut self,
1327 comp: &Comp,
1328 target: NodeId,
1329 frames: &[f64],
1330 expr: &model::ExprEngine,
1331 use_proxy_clips: bool,
1332 ) {
1333 #[cfg(target_arch = "wasm32")]
1334 {
1335 let _ = (comp, target, frames, expr, use_proxy_clips);
1336 }
1337 #[cfg(not(target_arch = "wasm32"))]
1338 {
1339 if frames.is_empty() {
1340 return;
1341 }
1342 let mut visited = HashSet::new();
1343 let mut jobs = MissingJobs::default();
1344 for &time in frames {
1345 collect_missing_loader_jobs_shared(
1346 &self.shared,
1347 comp,
1348 target,
1349 time,
1350 expr,
1351 use_proxy_clips,
1352 &mut visited,
1353 &mut jobs,
1354 );
1355 }
1356 let total = jobs.total_units();
1357 if total == 0 {
1358 return;
1359 }
1360 if total == 1 && jobs.raster.len() == 1 {
1361 let job = jobs.raster.pop().expect("len == 1");
1362 let cache_gen = {
1363 let Ok(mut state) = self.shared.state.lock() else { return };
1364 if state.images.contains_key(&job.cache_key)
1365 || state.in_flight.contains(&job.cache_key)
1366 {
1367 return;
1368 }
1369 state.in_flight.insert(job.cache_key.clone());
1370 self.shared.sync_lookahead_throttle(&state);
1371 state.generation
1372 };
1373 let mut guard = InFlightGuard {
1374 shared: &self.shared,
1375 key: Some(job.cache_key.clone()),
1376 };
1377 let decoded = decode_job(&job, true);
1378 finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded, false);
1379 return;
1380 }
1381 self.decode_jobs_parallel(jobs);
1382 }
1383 }
1384
1385 /// Starts a non-blocking, cancellable background read-ahead worker pool that pre-decodes
1386 /// upcoming frames into `MediaCache` while the GPU renders the current frame.
1387 #[cfg(not(target_arch = "wasm32"))]
1388 pub fn start_frame_prefetch(&self, lookahead: usize) -> MediaPrefetchHandle {
1389 MediaPrefetchHandle::spawn(Arc::clone(&self.shared), lookahead.max(1))
1390 }
1391
1392 #[cfg(not(target_arch = "wasm32"))]
1393 fn decode_jobs_parallel(&mut self, mut jobs: MissingJobs) {
1394 let mut video_tasks: Vec<VideoDecodeTask> = jobs
1395 .videos
1396 .drain()
1397 .map(|(path, requests)| VideoDecodeTask { path, requests })
1398 .collect();
1399 let video_count = video_tasks.len();
1400 let raster_jobs = jobs.raster;
1401 let total_units = video_count + raster_jobs.len();
1402 if total_units == 0 {
1403 return;
1404 }
1405 let workers = std::thread::available_parallelism()
1406 .map(|n| n.get().clamp(2, 12))
1407 .unwrap_or(4)
1408 .min(total_units);
1409
1410 let next_idx = AtomicUsize::new(0);
1411 let video_inputs: Vec<Mutex<Option<VideoDecodeTask>>> =
1412 video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect();
1413
1414 std::thread::scope(|scope| {
1415 for _ in 0..workers {
1416 scope.spawn(|| loop {
1417 let idx = next_idx.fetch_add(1, Ordering::Relaxed);
1418 if idx >= total_units {
1419 break;
1420 }
1421 if idx < video_count {
1422 let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take());
1423 if let Some(task) = task {
1424 if let Some((info, dec_arc)) = self.shared.get_or_open_video_decoder(&task.path) {
1425 let mut seen_local = HashSet::new();
1426 for req in &task.requests {
1427 let frame_idx = compute_video_frame_idx(
1428 &req.clip,
1429 req.frame_i,
1430 info.nb_frames,
1431 );
1432 if !seen_local.insert((frame_idx, req.post_multiply)) {
1433 continue;
1434 }
1435 let key = ImageCacheKey {
1436 path: task.path.clone(),
1437 frame_idx,
1438 post_multiply: req.post_multiply,
1439 exr_channels: [None, None, None, None],
1440 };
1441 let cache_gen_opt = self.shared.state.lock().ok().and_then(|mut state| {
1442 if state.images.contains_key(&key)
1443 || state.in_flight.contains(&key)
1444 {
1445 None
1446 } else {
1447 state.in_flight.insert(key.clone());
1448 self.shared.sync_lookahead_throttle(&state);
1449 Some(state.generation)
1450 }
1451 });
1452 let Some(cache_gen) = cache_gen_opt else { continue };
1453 let mut guard = InFlightGuard {
1454 shared: &self.shared,
1455 key: Some(key.clone()),
1456 };
1457 let decoded_raw = dec_arc
1458 .lock()
1459 .ok()
1460 .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx));
1461 if let Some(mut raw) = decoded_raw {
1462 if req.post_multiply {
1463 apply_post_multiply_rgba8_parallel(&mut raw, false);
1464 }
1465 let decoded = DecodedImage {
1466 size: [info.width, info.height],
1467 rgba: Arc::new(raw),
1468 rgba_f16: None,
1469 rgba_f32: None,
1470 };
1471 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
1472 state.in_flight.remove(&key);
1473 guard.key = None;
1474 let unthrottled = if state.generation == cache_gen {
1475 self.shared
1476 .insert_cached_locked(&mut state, key, decoded)
1477 } else {
1478 self.shared.sync_lookahead_throttle(&state)
1479 };
1480 self.shared.cv.notify_all();
1481 unthrottled
1482 } else {
1483 false
1484 };
1485 if unthrottled {
1486 self.shared.notify_prefetch_waiters();
1487 }
1488 }
1489 }
1490 }
1491 }
1492 } else {
1493 let r_idx = idx - video_count;
1494 let job = &raster_jobs[r_idx];
1495 let cache_gen_opt = self.shared.state.lock().ok().and_then(|mut state| {
1496 if state.images.contains_key(&job.cache_key)
1497 || state.in_flight.contains(&job.cache_key)
1498 {
1499 None
1500 } else {
1501 state.in_flight.insert(job.cache_key.clone());
1502 self.shared.sync_lookahead_throttle(&state);
1503 Some(state.generation)
1504 }
1505 });
1506 let Some(cache_gen) = cache_gen_opt else { continue };
1507 let mut guard = InFlightGuard {
1508 shared: &self.shared,
1509 key: Some(job.cache_key.clone()),
1510 };
1511 let decoded = decode_job(job, false);
1512 finish_raster_job(
1513 &self.shared,
1514 job.cache_key.clone(),
1515 cache_gen,
1516 &mut guard,
1517 decoded,
1518 false,
1519 );
1520 }
1521 });
1522 }
1523 });
1524 }
1525}
1526
1527#[cfg(not(target_arch = "wasm32"))]
1528fn finish_raster_job(
1529 shared: &MediaShared,
1530 key: ImageCacheKey,
1531 cache_gen: u64,
1532 guard: &mut InFlightGuard<'_>,
1533 decoded: Option<DecodedImage>,
1534 is_speculative: bool,
1535) {
1536 let unthrottled = if let Ok(mut state) = shared.state.lock() {
1537 state.in_flight.remove(&key);
1538 guard.key = None;
1539 let unthrottled = if let Some(decoded) = decoded {
1540 if state.generation == cache_gen {
1541 state.record_existing_path(&key.path);
1542 if is_speculative {
1543 state.record_speculative_decode(decoded.byte_size());
1544 }
1545 shared.insert_cached_locked(&mut state, key, decoded)
1546 } else {
1547 shared.sync_lookahead_throttle(&state)
1548 }
1549 } else {
1550 state.evict_existing_path(&key.path);
1551 shared.sync_lookahead_throttle(&state)
1552 };
1553 shared.cv.notify_all();
1554 unthrottled
1555 } else {
1556 false
1557 };
1558 if unthrottled {
1559 shared.notify_prefetch_waiters();
1560 }
1561}
1562
1563#[cfg(not(target_arch = "wasm32"))]
1564struct PrefetchQueueState {
1565 raster: VecDeque<(usize, PreloadJob)>,
1566 videos: HashMap<PathBuf, VecDeque<(usize, VideoFrameRequest)>>,
1567 active_videos: HashSet<PathBuf>,
1568 queued_raster_keys: HashSet<ImageCacheKey>,
1569 current_seq: usize,
1570 lookahead: usize,
1571 cancelled: bool,
1572}
1573
1574#[cfg(not(target_arch = "wasm32"))]
1575impl PrefetchQueueState {
1576 fn prune_stale(&mut self) {
1577 let cur = self.current_seq;
1578 if self.raster.iter().any(|&(seq, _)| seq < cur) {
1579 let mut kept = VecDeque::with_capacity(self.raster.len());
1580 while let Some((seq, job)) = self.raster.pop_front() {
1581 if seq >= cur {
1582 kept.push_back((seq, job));
1583 } else {
1584 self.queued_raster_keys.remove(&job.cache_key);
1585 }
1586 }
1587 self.raster = kept;
1588 }
1589 self.videos.retain(|_, vq| {
1590 vq.retain(|&(seq, _)| seq >= cur);
1591 !vq.is_empty()
1592 });
1593 }
1594}
1595
1596#[cfg(not(target_arch = "wasm32"))]
1597struct PrefetchQueue {
1598 state: Mutex<PrefetchQueueState>,
1599 cv: Condvar,
1600}
1601
1602#[cfg(not(target_arch = "wasm32"))]
1603enum PrefetchWorkItem {
1604 Raster(usize, usize, PreloadJob),
1605 Video(usize, usize, PathBuf, VideoFrameRequest),
1606}
1607
1608/// Cancellable background read-ahead handle returned by [`MediaCache::start_frame_prefetch`].
1609///
1610/// Continuously pre-decodes upcoming frames into [`MediaCache`] while the GPU renders the
1611/// current frame, and cancels and joins all worker threads cleanly on drop.
1612#[cfg(not(target_arch = "wasm32"))]
1613pub struct MediaPrefetchHandle {
1614 shared: Arc<MediaShared>,
1615 queue: Arc<PrefetchQueue>,
1616 workers: Vec<std::thread::JoinHandle<()>>,
1617}
1618
1619#[cfg(not(target_arch = "wasm32"))]
1620impl MediaPrefetchHandle {
1621 fn spawn(shared: Arc<MediaShared>, lookahead: usize) -> Self {
1622 let queue = Arc::new(PrefetchQueue {
1623 state: Mutex::new(PrefetchQueueState {
1624 raster: VecDeque::new(),
1625 videos: HashMap::new(),
1626 active_videos: HashSet::new(),
1627 queued_raster_keys: HashSet::new(),
1628 current_seq: 0,
1629 lookahead,
1630 cancelled: false,
1631 }),
1632 cv: Condvar::new(),
1633 });
1634 shared.register_prefetch_queue(&queue);
1635 let worker_count = std::thread::available_parallelism()
1636 .map(|n| n.get().clamp(2, 12))
1637 .unwrap_or(4);
1638 let mut workers = Vec::with_capacity(worker_count);
1639 for _ in 0..worker_count {
1640 let s = Arc::clone(&shared);
1641 let q = Arc::clone(&queue);
1642 workers.push(std::thread::spawn(move || {
1643 Self::worker_loop(s, q);
1644 }));
1645 }
1646 Self {
1647 shared,
1648 queue,
1649 workers,
1650 }
1651 }
1652
1653 /// Updates the active render sequence index so read-ahead stays synchronized with playback/export.
1654 pub fn set_current_seq(&self, seq_idx: usize) {
1655 if let Ok(mut state) = self.shared.state.lock() {
1656 state.reset_speculative_window(seq_idx);
1657 self.shared.sync_lookahead_throttle(&state);
1658 }
1659 if let Ok(mut q) = self.queue.state.lock() {
1660 q.current_seq = seq_idx;
1661 q.prune_stale();
1662 self.queue.cv.notify_all();
1663 }
1664 }
1665
1666 /// Enqueues missing `Loader` decodes for `time` at sequence index `seq_idx`.
1667 pub fn enqueue_frame(
1668 &self,
1669 comp: &Comp,
1670 target: NodeId,
1671 seq_idx: usize,
1672 time: f64,
1673 expr: &model::ExprEngine,
1674 use_proxy_clips: bool,
1675 ) {
1676 let mut visited = HashSet::new();
1677 let mut jobs = MissingJobs::default();
1678 collect_missing_loader_jobs_shared(
1679 &self.shared,
1680 comp,
1681 target,
1682 time,
1683 expr,
1684 use_proxy_clips,
1685 &mut visited,
1686 &mut jobs,
1687 );
1688 if jobs.total_units() == 0 {
1689 return;
1690 }
1691 if let Ok(mut q) = self.queue.state.lock() {
1692 if q.cancelled || seq_idx < q.current_seq {
1693 return;
1694 }
1695 for job in jobs.raster {
1696 if q.queued_raster_keys.insert(job.cache_key.clone()) {
1697 q.raster.push_back((seq_idx, job));
1698 }
1699 }
1700 for (path, reqs) in jobs.videos {
1701 let vq = q.videos.entry(path).or_default();
1702 for req in reqs {
1703 if let Some((existing_seq, _)) = vq.iter_mut().find(|(_, existing)| {
1704 existing.post_multiply == req.post_multiply
1705 && match (existing.resolved_frame_idx, req.resolved_frame_idx) {
1706 (Some(a), Some(b)) => a == b,
1707 _ => {
1708 existing.frame_i == req.frame_i
1709 && existing.clip.global_start == req.clip.global_start
1710 && existing.clip.trim_in == req.clip.trim_in
1711 && existing.clip.trim_out == req.clip.trim_out
1712 && existing.clip.reverse == req.clip.reverse
1713 && existing.clip.loop_clip == req.clip.loop_clip
1714 }
1715 }
1716 }) {
1717 *existing_seq = (*existing_seq).min(seq_idx);
1718 } else {
1719 vq.push_back((seq_idx, req));
1720 }
1721 }
1722 }
1723 self.queue.cv.notify_all();
1724 }
1725 }
1726
1727 /// Cancels pending read-ahead work and joins all background worker threads.
1728 pub fn cancel(&mut self) {
1729 if let Ok(mut q) = self.queue.state.lock() {
1730 q.cancelled = true;
1731 q.raster.clear();
1732 q.videos.clear();
1733 q.queued_raster_keys.clear();
1734 self.queue.cv.notify_all();
1735 }
1736 for handle in self.workers.drain(..) {
1737 let _ = handle.join();
1738 }
1739 }
1740
1741 fn worker_loop(shared: Arc<MediaShared>, queue: Arc<PrefetchQueue>) {
1742 loop {
1743 let item = {
1744 let Ok(mut q) = queue.state.lock() else { return };
1745 loop {
1746 if q.cancelled {
1747 return;
1748 }
1749 let best_raster = q
1750 .raster
1751 .iter()
1752 .enumerate()
1753 .min_by_key(|&(_, (seq, _))| *seq)
1754 .map(|(idx, (seq, _))| (idx, *seq));
1755 let mut best_video: Option<(&PathBuf, usize, usize)> = None;
1756 for (path, vq) in &q.videos {
1757 if q.active_videos.contains(path) {
1758 continue;
1759 }
1760 if let Some((v_idx, &(seq, _))) =
1761 vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq)
1762 {
1763 if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) {
1764 best_video = Some((path, v_idx, seq));
1765 }
1766 }
1767 }
1768
1769 let chosen_seq = match (best_raster, &best_video) {
1770 (Some((_, rs)), Some((_, _, vs))) => rs.min(*vs),
1771 (Some((_, rs)), None) => rs,
1772 (None, Some((_, _, vs))) => *vs,
1773 (None, None) => {
1774 q = match queue.cv.wait(q) {
1775 Ok(g) => g,
1776 Err(_) => return,
1777 };
1778 continue;
1779 }
1780 };
1781
1782 if chosen_seq > q.current_seq.saturating_add(q.lookahead) {
1783 q = match queue.cv.wait(q) {
1784 Ok(g) => g,
1785 Err(_) => return,
1786 };
1787 continue;
1788 }
1789
1790 if chosen_seq > q.current_seq.saturating_add(1)
1791 && shared.lookahead_throttled.load(Ordering::Acquire)
1792 {
1793 q = match queue.cv.wait(q) {
1794 Ok(g) => g,
1795 Err(_) => return,
1796 };
1797 continue;
1798 }
1799
1800 let cur_seq = q.current_seq;
1801 let chosen_video = best_video
1802 .filter(|&(_, _, vs)| best_raster.is_none_or(|(_, rs)| vs <= rs))
1803 .map(|(path, v_idx, _)| (path.clone(), v_idx));
1804
1805 if let Some((path, v_idx)) = chosen_video {
1806 if let Some((seq, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) {
1807 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
1808 q.videos.remove(&path);
1809 }
1810 q.active_videos.insert(path.clone());
1811 break PrefetchWorkItem::Video(seq, cur_seq, path, req);
1812 }
1813 }
1814 if let Some((r_idx, _)) = best_raster {
1815 if let Some((seq, job)) = q.raster.remove(r_idx) {
1816 q.queued_raster_keys.remove(&job.cache_key);
1817 break PrefetchWorkItem::Raster(seq, cur_seq, job);
1818 }
1819 }
1820 }
1821 };
1822
1823 match item {
1824 PrefetchWorkItem::Raster(item_seq, cur_seq, job) => {
1825 let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| {
1826 if state.images.contains_key(&job.cache_key)
1827 || state.in_flight.contains(&job.cache_key)
1828 {
1829 None
1830 } else {
1831 state.in_flight.insert(job.cache_key.clone());
1832 shared.sync_lookahead_throttle(&state);
1833 Some(state.generation)
1834 }
1835 });
1836 let Some(cache_gen) = cache_gen_opt else { continue };
1837 let mut guard = InFlightGuard {
1838 shared: &shared,
1839 key: Some(job.cache_key.clone()),
1840 };
1841 let decoded = decode_job(&job, false);
1842 finish_raster_job(
1843 &shared,
1844 job.cache_key,
1845 cache_gen,
1846 &mut guard,
1847 decoded,
1848 item_seq > cur_seq,
1849 );
1850 }
1851 PrefetchWorkItem::Video(item_seq, cur_seq, path, req) => {
1852 struct ActiveVideoGuard<'a> {
1853 queue: &'a PrefetchQueue,
1854 path: PathBuf,
1855 }
1856 impl Drop for ActiveVideoGuard<'_> {
1857 fn drop(&mut self) {
1858 if let Ok(mut q) = self.queue.state.lock() {
1859 q.active_videos.remove(&self.path);
1860 self.queue.cv.notify_all();
1861 }
1862 }
1863 }
1864 let _active_guard = ActiveVideoGuard {
1865 queue: &queue,
1866 path: path.clone(),
1867 };
1868
1869 let Some((info, dec_arc)) = shared.get_or_open_video_decoder(&path) else {
1870 continue;
1871 };
1872 let frame_idx =
1873 compute_video_frame_idx(&req.clip, req.frame_i, info.nb_frames);
1874 let key = ImageCacheKey {
1875 path: path.clone(),
1876 frame_idx,
1877 post_multiply: req.post_multiply,
1878 exr_channels: [None, None, None, None],
1879 };
1880 let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| {
1881 if state.images.contains_key(&key) || state.in_flight.contains(&key) {
1882 None
1883 } else {
1884 state.in_flight.insert(key.clone());
1885 shared.sync_lookahead_throttle(&state);
1886 Some(state.generation)
1887 }
1888 });
1889 let Some(cache_gen) = cache_gen_opt else { continue };
1890 let mut guard = InFlightGuard {
1891 shared: &shared,
1892 key: Some(key.clone()),
1893 };
1894 let decoded_raw = dec_arc
1895 .lock()
1896 .ok()
1897 .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx));
1898 if let Some(mut raw) = decoded_raw {
1899 if req.post_multiply {
1900 apply_post_multiply_rgba8_parallel(&mut raw, false);
1901 }
1902 let decoded = DecodedImage {
1903 size: [info.width, info.height],
1904 rgba: Arc::new(raw),
1905 rgba_f16: None,
1906 rgba_f32: None,
1907 };
1908 let unthrottled = if let Ok(mut state) = shared.state.lock() {
1909 state.in_flight.remove(&key);
1910 guard.key = None;
1911 let unthrottled = if state.generation == cache_gen {
1912 if item_seq > cur_seq {
1913 state.record_speculative_decode(decoded.byte_size());
1914 }
1915 shared.insert_cached_locked(&mut state, key, decoded)
1916 } else {
1917 shared.sync_lookahead_throttle(&state)
1918 };
1919 shared.cv.notify_all();
1920 unthrottled
1921 } else {
1922 false
1923 };
1924 if unthrottled {
1925 shared.notify_prefetch_waiters();
1926 }
1927 }
1928 }
1929 }
1930 }
1931 }
1932}
1933
1934#[cfg(not(target_arch = "wasm32"))]
1935impl Drop for MediaPrefetchHandle {
1936 fn drop(&mut self) {
1937 self.cancel();
1938 }
1939}
1940
1941#[cfg(not(target_arch = "wasm32"))]
1942#[allow(clippy::too_many_arguments)]
1943fn collect_missing_loader_jobs_shared(
1944 shared: &MediaShared,
1945 comp: &Comp,
1946 node_id: NodeId,
1947 time: f64,
1948 expr: &model::ExprEngine,
1949 use_proxy_clips: bool,
1950 visited: &mut HashSet<(NodeId, i64)>,
1951 jobs: &mut MissingJobs,
1952) {
1953 const MAX_PRELOAD_DEPTH: usize = 256;
1954 if node_id.0 >= comp.nodes.len() || jobs.depth >= MAX_PRELOAD_DEPTH {
1955 return;
1956 }
1957 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
1958 if !visited.insert((node_id, time_key)) {
1959 return;
1960 }
1961 jobs.depth += 1;
1962 collect_missing_loader_jobs_inner(
1963 shared,
1964 comp,
1965 node_id,
1966 time,
1967 expr,
1968 use_proxy_clips,
1969 visited,
1970 jobs,
1971 );
1972 jobs.depth -= 1;
1973}
1974
1975#[cfg(not(target_arch = "wasm32"))]
1976#[allow(clippy::too_many_arguments)]
1977fn collect_missing_loader_jobs_inner(
1978 shared: &MediaShared,
1979 comp: &Comp,
1980 node_id: NodeId,
1981 time: f64,
1982 expr: &model::ExprEngine,
1983 use_proxy_clips: bool,
1984 visited: &mut HashSet<(NodeId, i64)>,
1985 jobs: &mut MissingJobs,
1986) {
1987 let node = comp.node(node_id);
1988
1989 if node.bypassed
1990 || matches!(
1991 node.kind.as_str(),
1992 "Saver"
1993 | "PipeRouter"
1994 | "Fuse.Wireless"
1995 | "Tracker"
1996 | "Dimension.OpticalFlow"
1997 | "OpticalFlow"
1998 | "Dimension.CopyAux"
1999 )
2000 {
2001 let port = default_main_input_port(&node.kind);
2002 if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) {
2003 collect_missing_loader_jobs_shared(
2004 shared,
2005 comp,
2006 src_id,
2007 time,
2008 expr,
2009 use_proxy_clips,
2010 visited,
2011 jobs,
2012 );
2013 }
2014 return;
2015 }
2016
2017 if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") {
2018 let next_id = node.macro_output.or_else(|| {
2019 node.connected_node("Input")
2020 .or_else(|| node.connected_node("MainInput1"))
2021 .and_then(|s| comp.find_node(s))
2022 });
2023 if let Some(src_id) = next_id {
2024 collect_missing_loader_jobs_shared(
2025 shared,
2026 comp,
2027 src_id,
2028 time,
2029 expr,
2030 use_proxy_clips,
2031 visited,
2032 jobs,
2033 );
2034 }
2035 return;
2036 }
2037
2038 if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") {
2039 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
2040 return;
2041 };
2042 let remapped = match node.kind.as_str() {
2043 "TimeStretcher" => comp.eval_number(node, "SourceTime", time, 0.0, expr),
2044 "TimeSpeed" => {
2045 let speed = comp.eval_number(node, "Speed", time, 1.0, expr);
2046 let delay = comp.eval_number(node, "Delay", time, 0.0, expr);
2047 let g_start = comp.global_range[0] as f64;
2048 let g_end = comp.global_range[1] as f64;
2049 if speed < 0.0 {
2050 ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end)
2051 } else {
2052 g_start + (time - delay - g_start) * speed
2053 }
2054 }
2055 _ => time,
2056 };
2057 let interp = comp
2058 .eval_number(node, "InterpolateBetweenFrames", time, 1.0, expr)
2059 .round() as i32;
2060 if interp <= 0 {
2061 let snapped = (remapped + 0.5).floor();
2062 collect_missing_loader_jobs_shared(
2063 shared,
2064 comp,
2065 src_id,
2066 snapped,
2067 expr,
2068 use_proxy_clips,
2069 visited,
2070 jobs,
2071 );
2072 return;
2073 }
2074 let f0 = remapped.floor();
2075 let frac = (remapped - f0) as f32;
2076 if frac > 1e-3 && frac < 1.0 - 1e-3 {
2077 let src_node = comp.node(src_id);
2078 let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow");
2079 let eval_src_id = if has_optflow {
2080 src_node
2081 .connected_node("Input")
2082 .and_then(|s| comp.find_node(s))
2083 .unwrap_or(src_id)
2084 } else {
2085 src_id
2086 };
2087 collect_missing_loader_jobs_shared(
2088 shared,
2089 comp,
2090 eval_src_id,
2091 f0,
2092 expr,
2093 use_proxy_clips,
2094 visited,
2095 jobs,
2096 );
2097 collect_missing_loader_jobs_shared(
2098 shared,
2099 comp,
2100 eval_src_id,
2101 f0 + 1.0,
2102 expr,
2103 use_proxy_clips,
2104 visited,
2105 jobs,
2106 );
2107 } else {
2108 collect_missing_loader_jobs_shared(
2109 shared,
2110 comp,
2111 src_id,
2112 remapped,
2113 expr,
2114 use_proxy_clips,
2115 visited,
2116 jobs,
2117 );
2118 }
2119 return;
2120 }
2121
2122 if node.kind == "Switch" || node.kind == "Fuse.Switch" {
2123 let is_native_zero_indexed = node.kind == "Switch"
2124 && (node.inputs.contains_key("Source")
2125 || node.inputs.contains_key("Input0")
2126 || !node.inputs.contains_key("Which"));
2127 let src_name = if is_native_zero_indexed {
2128 let source = comp
2129 .eval_number(node, "Source", time, 0.0, expr)
2130 .round()
2131 .max(0.0) as usize;
2132 let port = format!("Input{source}");
2133 node.connected_node(&port)
2134 .or_else(|| node.connected_node("Input0"))
2135 } else {
2136 let which = comp
2137 .eval_number(node, "Which", time, 1.0, expr)
2138 .round()
2139 .max(1.0) as usize;
2140 let port = format!("Input{which}");
2141 node.connected_node(&port)
2142 .or_else(|| node.connected_node("Input1"))
2143 };
2144 if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) {
2145 collect_missing_loader_jobs_shared(
2146 shared,
2147 comp,
2148 src_id,
2149 time,
2150 expr,
2151 use_proxy_clips,
2152 visited,
2153 jobs,
2154 );
2155 }
2156 return;
2157 }
2158
2159 if node.kind == "Fuse.SwitchElse" {
2160 let index = |name: &str, default: f64| {
2161 comp.eval_number(node, name, time, default, expr)
2162 .round()
2163 .max(1.0) as usize
2164 };
2165 let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| {
2166 node.connected_node(&format!("Input{i}"))
2167 .and_then(|s| comp.find_node(s))
2168 });
2169 if let Some(src_id) = picked {
2170 collect_missing_loader_jobs_shared(
2171 shared,
2172 comp,
2173 src_id,
2174 time,
2175 expr,
2176 use_proxy_clips,
2177 visited,
2178 jobs,
2179 );
2180 }
2181 return;
2182 }
2183
2184 if node.kind == "Merge" {
2185 if let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) {
2186 collect_missing_loader_jobs_shared(
2187 shared,
2188 comp,
2189 bg_id,
2190 time,
2191 expr,
2192 use_proxy_clips,
2193 visited,
2194 jobs,
2195 );
2196 }
2197 let blend = comp.eval_number(node, "Blend", time, 1.0, expr) as f32;
2198 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, expr) > 0.5;
2199 let mask_id = resolve_effect_mask_id_for_node(comp, node);
2200 if !(blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some())) {
2201 if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) {
2202 collect_missing_loader_jobs_shared(
2203 shared,
2204 comp,
2205 fg_id,
2206 time,
2207 expr,
2208 use_proxy_clips,
2209 visited,
2210 jobs,
2211 );
2212 }
2213 }
2214 if let Some(mid) = mask_id {
2215 collect_missing_loader_jobs_shared(
2216 shared,
2217 comp,
2218 mid,
2219 time,
2220 expr,
2221 use_proxy_clips,
2222 visited,
2223 jobs,
2224 );
2225 }
2226 return;
2227 }
2228
2229 if node.kind == "Loader" {
2230 if let Some(clip) = node.clips.first() {
2231 let frame_i = time.round() as i64;
2232 let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5;
2233 let exr_channels = [
2234 node.static_str("Clip1.OpenEXRFormat.RedName"),
2235 node.static_str("Clip1.OpenEXRFormat.GreenName"),
2236 node.static_str("Clip1.OpenEXRFormat.BlueName"),
2237 node.static_str("Clip1.OpenEXRFormat.AlphaName"),
2238 ];
2239 let mut effective_clip = clip.clone();
2240 if node.inputs.contains_key("GlobalIn") {
2241 effective_clip.global_start = comp
2242 .eval_number(node, "GlobalIn", time, effective_clip.global_start as f64, expr)
2243 .round() as i64;
2244 }
2245 if node.inputs.contains_key("GlobalOut") {
2246 effective_clip.global_end = comp
2247 .eval_number(node, "GlobalOut", time, effective_clip.global_end as f64, expr)
2248 .round() as i64;
2249 }
2250 if node.inputs.contains_key("Loop") {
2251 effective_clip.loop_clip = comp.eval_number(
2252 node,
2253 "Loop",
2254 time,
2255 if effective_clip.loop_clip { 1.0 } else { 0.0 },
2256 expr,
2257 ) > 0.5;
2258 }
2259 if node.inputs.contains_key("Reverse") {
2260 effective_clip.reverse = comp.eval_number(
2261 node,
2262 "Reverse",
2263 time,
2264 if effective_clip.reverse { 1.0 } else { 0.0 },
2265 expr,
2266 ) > 0.5;
2267 }
2268 if use_proxy_clips {
2269 let proxy_candidate = node
2270 .static_str("ProxyFilename")
2271 .filter(|s| !s.trim().is_empty())
2272 .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty()));
2273 if let Some(proxy_name) = proxy_candidate {
2274 let mut proxy_clip = effective_clip.clone();
2275 proxy_clip.filename = proxy_name.to_owned();
2276 if shared.resolve_clip_path_cached(&proxy_clip, frame_i).is_some() {
2277 effective_clip = proxy_clip;
2278 }
2279 }
2280 }
2281 let out_of_range = effective_clip.global_end >= effective_clip.global_start
2282 && (frame_i < effective_clip.global_start.saturating_sub(effective_clip.extend_first.max(0))
2283 || (!effective_clip.loop_clip
2284 && frame_i > effective_clip.global_end.saturating_add(effective_clip.extend_last.max(0))));
2285 if !out_of_range {
2286 let base = Path::new(&effective_clip.filename);
2287 if is_video_path(base) {
2288 if video_frame_in_range(&effective_clip, frame_i)
2289 && shared.path_exists_cached(base)
2290 {
2291 let mut resolved_frame_idx = effective_clip
2292 .length
2293 .map(|_| compute_video_frame_idx(&effective_clip, frame_i, 1));
2294 let need_decode = shared.state.lock().is_ok_and(|state| {
2295 match state.video_decoders.get(base) {
2296 Some(slot) => {
2297 let idx = compute_video_frame_idx(
2298 &effective_clip,
2299 frame_i,
2300 slot.info.nb_frames,
2301 );
2302 resolved_frame_idx = Some(idx);
2303 let cache_key = ImageCacheKey {
2304 path: base.to_path_buf(),
2305 frame_idx: idx,
2306 post_multiply: post_mult,
2307 exr_channels: [None, None, None, None],
2308 };
2309 !state.images.contains_key(&cache_key)
2310 && !state.in_flight.contains(&cache_key)
2311 }
2312 None => true,
2313 }
2314 });
2315 if need_decode {
2316 jobs.videos
2317 .entry(base.to_path_buf())
2318 .or_default()
2319 .push(VideoFrameRequest {
2320 clip: effective_clip,
2321 frame_i,
2322 post_multiply: post_mult,
2323 resolved_frame_idx,
2324 });
2325 }
2326 }
2327 } else if let Some(resolved) = resolve_clip_candidate_path(&effective_clip, frame_i) {
2328 let is_exr = is_exr_path(&resolved);
2329 let key_channels = if is_exr {
2330 [
2331 normalize_channel_opt(exr_channels[0]),
2332 normalize_channel_opt(exr_channels[1]),
2333 normalize_channel_opt(exr_channels[2]),
2334 normalize_channel_opt(exr_channels[3]),
2335 ]
2336 } else {
2337 [None, None, None, None]
2338 };
2339 let cache_key = ImageCacheKey {
2340 path: resolved.clone(),
2341 frame_idx: -1,
2342 post_multiply: post_mult && !is_exr,
2343 exr_channels: key_channels,
2344 };
2345 let missing = shared.state.lock().is_ok_and(|state| {
2346 !state.images.contains_key(&cache_key)
2347 && !state.in_flight.contains(&cache_key)
2348 });
2349 if missing
2350 && !jobs.seen_raster.contains(&cache_key)
2351 && shared.path_exists_cached(&resolved)
2352 {
2353 jobs.seen_raster.insert(cache_key.clone());
2354 jobs.raster.push(PreloadJob { cache_key, is_exr });
2355 }
2356 }
2357 }
2358 }
2359 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {
2360 collect_missing_loader_jobs_shared(
2361 shared,
2362 comp,
2363 mid,
2364 time,
2365 expr,
2366 use_proxy_clips,
2367 visited,
2368 jobs,
2369 );
2370 }
2371 return;
2372 }
2373
2374 // General node: traverse all wired upstream node inputs and inherited EffectMask.
2375 let mut child_ids = Vec::new();
2376 for binding in node.inputs.values() {
2377 if let Some(src) = binding.source_op.as_deref() {
2378 if let Some(cid) = comp.find_node(src) {
2379 if !child_ids.contains(&cid) {
2380 child_ids.push(cid);
2381 }
2382 }
2383 }
2384 }
2385 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {
2386 if !child_ids.contains(&mid) {
2387 child_ids.push(mid);
2388 }
2389 }
2390 for cid in child_ids {
2391 collect_missing_loader_jobs_shared(
2392 shared,
2393 comp,
2394 cid,
2395 time,
2396 expr,
2397 use_proxy_clips,
2398 visited,
2399 jobs,
2400 );
2401 }
2402953}
2403954
2404955fn video_frame_in_range(clip: &ClipSpec, frame: i64) -> bool {
......@@ -2432,98 +983,6 @@ fn compute_video_frame_idx(clip: &ClipSpec, frame: i64, nb_frames: i64) -> i64 {
2432983 if clip.reverse { trim_out.saturating_sub(rel) } else { trim_in.saturating_add(rel) }
2433984}
2434985
2435#[cfg(not(target_arch = "wasm32"))]
2436#[derive(Default)]
2437struct MissingJobs {
2438 raster: Vec<PreloadJob>,
2439 seen_raster: HashSet<ImageCacheKey>,
2440 videos: HashMap<PathBuf, Vec<VideoFrameRequest>>,
2441 depth: usize,
2442}
2443
2444#[cfg(not(target_arch = "wasm32"))]
2445impl MissingJobs {
2446 fn total_units(&self) -> usize {
2447 self.raster.len() + self.videos.len()
2448 }
2449}
2450
2451#[cfg(not(target_arch = "wasm32"))]
2452struct VideoFrameRequest {
2453 clip: ClipSpec,
2454 frame_i: i64,
2455 post_multiply: bool,
2456 resolved_frame_idx: Option<i64>,
2457}
2458
2459#[cfg(not(target_arch = "wasm32"))]
2460struct VideoDecodeTask {
2461 path: PathBuf,
2462 requests: Vec<VideoFrameRequest>,
2463}
2464
2465#[cfg(not(target_arch = "wasm32"))]
2466struct PreloadJob {
2467 cache_key: ImageCacheKey,
2468 is_exr: bool,
2469}
2470
2471#[cfg(not(target_arch = "wasm32"))]
2472fn decode_job(job: &PreloadJob, allow_parallel: bool) -> Option<DecodedImage> {
2473 if job.is_exr {
2474 decode_exr_rgba(
2475 &job.cache_key.path,
2476 job.cache_key.exr_channels[0].as_deref(),
2477 job.cache_key.exr_channels[1].as_deref(),
2478 job.cache_key.exr_channels[2].as_deref(),
2479 job.cache_key.exr_channels[3].as_deref(),
2480 false,
2481 allow_parallel,
2482 )
2483 } else {
2484 decode_raster_image(
2485 &job.cache_key.path,
2486 job.cache_key.post_multiply,
2487 allow_parallel,
2488 )
2489 }
2490}
2491
2492#[cfg(not(target_arch = "wasm32"))]
2493fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option<NodeId> {
2494 if let Some(id) = node.connected_node("EffectMask").and_then(|s| comp.find_node(s)) {
2495 return Some(id);
2496 }
2497 let has_explicit_mask_entry = |n: &Node| -> bool {
2498 n.raw
2499 .get_table("Inputs")
2500 .and_then(|t| t.get("EffectMask"))
2501 .is_some()
2502 };
2503 if has_explicit_mask_entry(node) {
2504 return None;
2505 }
2506 let mut visited = HashSet::new();
2507 visited.insert(node.id);
2508 let mut cur = node;
2509 for _ in 0..8 {
2510 let master_name = cur.raw.get_str("SourceOp")?;
2511 let mid = comp.find_node(master_name)?;
2512 if !visited.insert(mid) {
2513 break;
2514 }
2515 let master = comp.node(mid);
2516 if let Some(mask_id) = master.connected_node("EffectMask").and_then(|s| comp.find_node(s)) {
2517 return Some(mask_id);
2518 }
2519 if has_explicit_mask_entry(master) {
2520 return None;
2521 }
2522 cur = master;
2523 }
2524 None
2525}
2526
2527986fn resolve_clip_candidate_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
2528987 let base = Path::new(&clip.filename);
2529988 let len = clip.length.unwrap_or(1);
......@@ -2569,1457 +1028,3 @@ pub fn resolve_clip_path(clip: &ClipSpec, frame: i64) -> Option<PathBuf> {
25691028 let candidate = resolve_clip_candidate_path(clip, frame)?;
25701029 path_exists(&candidate).then_some(candidate)
25711030}
2572#[cfg(test)]
2573mod tests {
2574 use super::*;
2575 use std::time::Instant;
2576
2577 #[test]
2578 fn decoded_image_cache_separates_post_multiply() {
2579 let dir = std::env::temp_dir().join("fission_media_post_multiply_key_test");
2580 std::fs::create_dir_all(&dir).unwrap();
2581 let png = dir.join("half.png");
2582 image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 100, 50, 128])).save(&png).unwrap();
2583 let clip = ClipSpec {
2584 filename: png.to_string_lossy().into_owned(),
2585 alternate_filename: None,
2586 start_frame: 0,
2587 length: Some(1),
2588 trim_in: 0,
2589 trim_out: 0,
2590 global_start: 0,
2591 global_end: 0,
2592 extend_first: 0,
2593 extend_last: 0,
2594 loop_clip: false,
2595 reverse: false,
2596 };
2597 let mut cache = MediaCache::new(64);
2598 let mut first_px = |post_multiply| {
2599 let (_, _, img, from_disk) = cache.load_clip(&clip, 0, post_multiply, [None; 4]).unwrap();
2600 (img.rgba[..4].to_vec(), from_disk)
2601 };
2602 assert_eq!(first_px(false), (vec![200, 100, 50, 128], true));
2603 assert_eq!(first_px(true), (vec![100, 50, 25, 128], true));
2604 assert_eq!(first_px(false), (vec![200, 100, 50, 128], false));
2605 assert_eq!(first_px(true), (vec![100, 50, 25, 128], false));
2606 assert_eq!(cache.entry_count(), 2);
2607 let _ = std::fs::remove_dir_all(&dir);
2608 }
2609
2610 fn mean_abs_error_rgb(a: &[u8], b: &[u8]) -> f64 {
2611 assert_eq!(a.len(), b.len());
2612 let mut sum = 0u64;
2613 let mut count = 0u64;
2614 for (pa, pb) in a.chunks_exact(4).zip(b.chunks_exact(4)) {
2615 sum += pa[0].abs_diff(pb[0]) as u64;
2616 sum += pa[1].abs_diff(pb[1]) as u64;
2617 sum += pa[2].abs_diff(pb[2]) as u64;
2618 count += 3;
2619 }
2620 if count == 0 {
2621 0.0
2622 } else {
2623 sum as f64 / count as f64
2624 }
2625 }
2626
2627 fn verify_clip_matches_ffmpeg(path: &Path) {
2628 let mut dec = open_video_decoder(path).expect("open_video_decoder failed");
2629 let mut ff = FfmpegDecoder::open(path).expect("FfmpegDecoder::open failed");
2630
2631 #[cfg(target_os = "macos")]
2632 assert_eq!(
2633 dec.backend_name(),
2634 "AVFoundation/VideoToolbox",
2635 "expected AVFoundation backend for {}",
2636 path.display()
2637 );
2638
2639 let av_info = dec.info();
2640 let ff_info = ff.info();
2641 assert_eq!(av_info.width, ff_info.width, "width mismatch for {}", path.display());
2642 assert_eq!(av_info.height, ff_info.height, "height mismatch for {}", path.display());
2643 assert!(
2644 (av_info.fps - ff_info.fps).abs() < 0.2,
2645 "fps mismatch for {}: av={} ff={}",
2646 path.display(),
2647 av_info.fps,
2648 ff_info.fps
2649 );
2650
2651 let frames = [0_i64, 1, 2, 10, 0];
2652 let mut total_ms = 0.0;
2653 for &f in &frames {
2654 let t0 = Instant::now();
2655 let av_px = dec
2656 .decode_frame(f)
2657 .unwrap_or_else(|| panic!("av decode frame {f} failed for {}", path.display()));
2658 let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
2659 total_ms += elapsed_ms;
2660
2661 let ff_px = ff
2662 .decode_frame(f)
2663 .unwrap_or_else(|| panic!("ffmpeg decode frame {f} failed for {}", path.display()));
2664 let mae = mean_abs_error_rgb(&av_px, &ff_px);
2665 eprintln!(
2666 "[video-test] {} ({}x{} @{:.2}fps) frame {}: {:.2} ms, MAE vs ffmpeg = {:.2}",
2667 path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"),
2668 av_info.width,
2669 av_info.height,
2670 av_info.fps,
2671 f,
2672 elapsed_ms,
2673 mae
2674 );
2675 // Allow small YUV->RGB matrix/rounding differences between VideoToolbox and swscale.
2676 assert!(
2677 mae < 12.0,
2678 "high MAE ({mae:.2}) on {} frame {f} (possible orientation or PTS mismatch)",
2679 path.display()
2680 );
2681 }
2682 eprintln!(
2683 "[video-test] {} avg decode: {:.2} ms/frame",
2684 path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"),
2685 total_ms / frames.len() as f64
2686 );
2687 }
2688
2689 #[test]
2690 fn test_video_decoder_real_mov_clips() {
2691 let clips = [
2692 Path::new("/Volumes/Project/trees/EncodedMedia/A001_11071331_C002_4873-4988_d8716e17.mov"),
2693 Path::new("/Volumes/Project/trees/EncodedMedia/IMG_1767_2395-2547_7efe6416.mov"),
2694 ];
2695 for clip in clips {
2696 if clip.exists() {
2697 verify_clip_matches_ffmpeg(clip);
2698 }
2699 }
2700 }
2701
2702 #[test]
2703 fn test_video_decoder_synthetic_mp4() {
2704 let tmp = std::env::temp_dir().join("engine_test_synth_video.mp4");
2705 let status = Command::new("ffmpeg")
2706 .args([
2707 "-y",
2708 "-v",
2709 "error",
2710 "-f",
2711 "lavfi",
2712 "-i",
2713 "testsrc2=size=320x180:rate=24:duration=1.0",
2714 "-c:v",
2715 "libx264",
2716 "-pix_fmt",
2717 "yuv420p",
2718 ])
2719 .arg(&tmp)
2720 .status();
2721 if let Ok(st) = status {
2722 if st.success() {
2723 verify_clip_matches_ffmpeg(&tmp);
2724 let _ = std::fs::remove_file(&tmp);
2725 }
2726 }
2727 }
2728
2729 fn alpha_y_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> (i32, i32) {
2730 let [w, h] = size;
2731 let mut min_y = i32::MAX;
2732 let mut max_y = i32::MIN;
2733 for y in 0..h as usize {
2734 let row = y * w as usize * 4;
2735 for x in 0..w as usize {
2736 if rgba[row + x * 4 + 3] > 32 {
2737 let cy = origin[1] + y as i32;
2738 min_y = min_y.min(cy);
2739 max_y = max_y.max(cy);
2740 break;
2741 }
2742 }
2743 }
2744 (min_y, max_y)
2745 }
2746
2747 #[test]
2748 fn test_text_plus_calibrated_metrics_and_anchoring() {
2749 let base = |text: &str, v_tcb: f32, line_spacing: f32, dims: [u32; 2]| {
2750 rasterize_text_plus(
2751 dims,
2752 &TextPlusParams {
2753 text,
2754 font_family: "Helvetica Neue",
2755 font_style: "Regular",
2756 size_norm: 0.08,
2757 tracking: 1.0,
2758 line_spacing,
2759 center: [0.5, 0.5],
2760 h_lcr: 0.0,
2761 v_tcb,
2762 fill_rgba: [1.0, 1.0, 1.0, 1.0],
2763 write_on_start: 0.0,
2764 write_on_end: 1.0,
2765 shear_x: 0.0,
2766 cls: &[],
2767 outline_rgba: [0.0; 4],
2768 outline_width_px: 0.0,
2769 },
2770 0,
2771 )
2772 };
2773
2774 // 1. VerticalTopCenterBottom: -1 anchors top below cy=270, 0 centers around cy=270,
2775 // +1 anchors bottom baseline at cy=270 (so glyphs sit above cy=270).
2776 let (s_top, o_top, p_top) = base("HHHH", -1.0, 1.0, [960, 540]);
2777 let (s_ctr, o_ctr, p_ctr) = base("HHHH", 0.0, 1.0, [960, 540]);
2778 let (s_bot, o_bot, p_bot) = base("HHHH", 1.0, 1.0, [960, 540]);
2779 let (top_y0, top_y1) = alpha_y_bounds(s_top, o_top, &p_top);
2780 let (ctr_y0, ctr_y1) = alpha_y_bounds(s_ctr, o_ctr, &p_ctr);
2781 let (bot_y0, bot_y1) = alpha_y_bounds(s_bot, o_bot, &p_bot);
2782 assert!(top_y0 >= 268 && top_y1 > 300, "top-aligned should sit below cy=270: ({top_y0}, {top_y1})");
2783 assert!(ctr_y0 < 270 && ctr_y1 > 270, "center-aligned should straddle cy=270: ({ctr_y0}, {ctr_y1})");
2784 assert!(bot_y0 < 240 && bot_y1 <= 272, "bottom-aligned should sit above cy=270: ({bot_y0}, {bot_y1})");
2785
2786 // 2. LineSpacing=1.5 widens a 2-line block by 0.5 * (0.8 * 0.08 * 960 = 61.44px) = ~30.7px.
2787 let (s_ls1, o_ls1, p_ls1) = base("HHHH\nHHHH", 0.0, 1.0, [960, 540]);
2788 let (s_ls15, o_ls15, p_ls15) = base("HHHH\nHHHH", 0.0, 1.5, [960, 540]);
2789 let (ls1_y0, ls1_y1) = alpha_y_bounds(s_ls1, o_ls1, &p_ls1);
2790 let (ls15_y0, ls15_y1) = alpha_y_bounds(s_ls15, o_ls15, &p_ls15);
2791 let span_diff = (ls15_y1 - ls15_y0) - (ls1_y1 - ls1_y0);
2792 assert!(
2793 (28..=34).contains(&span_diff),
2794 "LineSpacing 1.5 vs 1.0 on 960x540 Size=0.08 should add ~31px span, got {span_diff}"
2795 );
2796
2797 // 3. Size scales with canvas width W, independent of height H.
2798 let (s_wide, o_wide, p_wide) = base("HHHH", 0.0, 1.0, [960, 540]);
2799 let (s_tall, o_tall, p_tall) = base("HHHH", 0.0, 1.0, [540, 960]);
2800 let (wy0, wy1) = alpha_y_bounds(s_wide, o_wide, &p_wide);
2801 let (ty0, ty1) = alpha_y_bounds(s_tall, o_tall, &p_tall);
2802 let wide_h = (wy1 - wy0) as f32;
2803 let tall_h = (ty1 - ty0) as f32;
2804 let ratio = wide_h / tall_h;
2805 assert!(
2806 (ratio - (960.0 / 540.0)).abs() < 0.15,
2807 "glyph pixel height should scale with W (expected ~1.78, got {ratio:.2}: {wide_h}/{tall_h})"
2808 );
2809 }
2810
2811 #[test]
2812 fn exr_channel_cache_isolation_and_non_beauty_guard() {
2813 use ::exr::prelude::*;
2814 let dir = std::env::temp_dir().join(format!("fission_exr_chan_test_{}", std::process::id()));
2815 let _ = std::fs::remove_dir_all(&dir);
2816 std::fs::create_dir_all(&dir).unwrap();
2817
2818 let multi_exr = dir.join("multi_aov.exr");
2819 let w = 4usize;
2820 let h = 4usize;
2821 let n = w * h;
2822 let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
2823 for (name, val) in [
2824 ("ViewLayer.Combined.R", 0.9_f32),
2825 ("ViewLayer.Combined.G", 0.2),
2826 ("ViewLayer.Combined.B", 0.1),
2827 ("ViewLayer.Combined.A", 1.0),
2828 ("ViewLayer.Specular.R", 0.1),
2829 ("ViewLayer.Specular.G", 0.8),
2830 ("ViewLayer.Specular.B", 0.7),
2831 ("ViewLayer.Specular.A", 1.0),
2832 ("ViewLayer.CryptoObject00.R", 0.5),
2833 ] {
2834 channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n])));
2835 }
2836 Image::from_layer(Layer::new(
2837 (w, h),
2838 LayerAttributes::named("main"),
2839 Encoding::FAST_LOSSLESS,
2840 AnyChannels::sort(channels),
2841 ))
2842 .write()
2843 .to_file(&multi_exr)
2844 .expect("write multi-layer EXR");
2845
2846 let clip = ClipSpec {
2847 filename: multi_exr.to_string_lossy().into_owned(),
2848 alternate_filename: None,
2849 start_frame: 0,
2850 length: Some(1),
2851 trim_in: 0,
2852 trim_out: 0,
2853 global_start: 0,
2854 global_end: 0,
2855 extend_first: 0,
2856 extend_last: 0,
2857 loop_clip: false,
2858 reverse: false,
2859 };
2860 let mut cache = MediaCache::new(64);
2861 let (_, _, beauty, beauty_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
2862 assert!(beauty_disk);
2863 let (_, _, spec, spec_disk) = cache
2864 .load_clip(
2865 &clip,
2866 0,
2867 false,
2868 [
2869 Some("Specular.R"),
2870 Some("Specular.G"),
2871 Some("Specular.B"),
2872 Some("Specular.A"),
2873 ],
2874 )
2875 .unwrap();
2876 assert!(spec_disk);
2877 assert_eq!(cache.entry_count(), 2);
2878
2879 let b_px = beauty.rgba_f32.as_ref().unwrap();
2880 let s_px = spec.rgba_f32.as_ref().unwrap();
2881 assert!((b_px[0] - 0.9).abs() < 1e-4 && (b_px[1] - 0.2).abs() < 1e-4);
2882 assert!((s_px[0] - 0.1).abs() < 1e-4 && (s_px[1] - 0.8).abs() < 1e-4);
2883
2884 // Warm hits keep both AOVs isolated.
2885 let (_, _, beauty_warm, beauty_disk2) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
2886 assert!(!beauty_disk2);
2887 assert!((beauty_warm.rgba_f32.as_ref().unwrap()[0] - 0.9).abs() < 1e-4);
2888
2889 // EXR containing ONLY CryptoObject00.R (no bare R or Combined.R) must NOT match beauty fallback.
2890 let crypto_only_exr = dir.join("crypto_only.exr");
2891 let mut crypto_channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
2892 for (name, val) in [
2893 ("CryptoObject00.R", 0.42_f32),
2894 ("CryptoObject00.G", 0.0),
2895 ("CryptoObject00.B", 0.0),
2896 ("CryptoObject00.A", 1.0),
2897 ] {
2898 crypto_channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n])));
2899 }
2900 Image::from_layer(Layer::new(
2901 (w, h),
2902 LayerAttributes::named("crypto"),
2903 Encoding::FAST_LOSSLESS,
2904 AnyChannels::sort(crypto_channels),
2905 ))
2906 .write()
2907 .to_file(&crypto_only_exr)
2908 .expect("write crypto-only EXR");
2909
2910 let crypto_clip = ClipSpec {
2911 filename: crypto_only_exr.to_string_lossy().into_owned(),
2912 ..clip
2913 };
2914 assert!(cache.load_clip(&crypto_clip, 0, false, [None; 4]).is_none());
2915 let (_, _, explicit, _) = cache
2916 .load_clip(
2917 &crypto_clip,
2918 0,
2919 false,
2920 [
2921 Some("CryptoObject00.R"),
2922 Some("CryptoObject00.G"),
2923 Some("CryptoObject00.B"),
2924 Some("CryptoObject00.A"),
2925 ],
2926 )
2927 .expect("explicit CryptoObject00 channel selection should succeed");
2928 assert!((explicit.rgba_f32.as_ref().unwrap()[0] - 0.42).abs() < 1e-4);
2929
2930 let _ = std::fs::remove_dir_all(&dir);
2931 }
2932
2933 #[test]
2934 fn video_decoder_clear_lru_cap_post_multiply_and_loop() {
2935 let dir = std::env::temp_dir().join(format!("fission_media_video_lru_{}", std::process::id()));
2936 let _ = std::fs::remove_dir_all(&dir);
2937 std::fs::create_dir_all(&dir).unwrap();
2938
2939 let base_mp4 = dir.join("clip_00.mp4");
2940 let ok = Command::new("ffmpeg")
2941 .args([
2942 "-y",
2943 "-v",
2944 "error",
2945 "-f",
2946 "lavfi",
2947 "-i",
2948 "color=c=red:size=32x32:rate=24:duration=0.25",
2949 "-c:v",
2950 "libx264",
2951 "-pix_fmt",
2952 "yuv420p",
2953 ])
2954 .arg(&base_mp4)
2955 .status()
2956 .is_ok_and(|s| s.success());
2957 assert!(ok, "ffmpeg failed to create tiny mp4");
2958
2959 let mut cache = MediaCache::new(64);
2960 for i in 0..15 {
2961 let p = if i == 0 {
2962 base_mp4.clone()
2963 } else {
2964 let dst = dir.join(format!("clip_{i:02}.mp4"));
2965 std::fs::copy(&base_mp4, &dst).unwrap();
2966 dst
2967 };
2968 let clip = ClipSpec {
2969 filename: p.to_string_lossy().into_owned(),
2970 alternate_filename: None,
2971 start_frame: 0,
2972 length: Some(6),
2973 trim_in: 0,
2974 trim_out: 5,
2975 global_start: 10,
2976 global_end: 15,
2977 extend_first: 5,
2978 extend_last: 0,
2979 loop_clip: true,
2980 reverse: false,
2981 };
2982 // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15]: ExtendFirst holds frame 0.
2983 let (_, local_idx, _, _) = cache
2984 .load_clip(&clip, 9, false, [None; 4])
2985 .expect("loop_clip inside ExtendFirst should resolve");
2986 assert_eq!(local_idx, 0);
2987 // Looping clips ignore GlobalEnd + ExtendLast: frame 20 -> rel 10 -> 10 % 6 = 4.
2988 let (_, local_idx, _, _) = cache
2989 .load_clip(&clip, 20, false, [None; 4])
2990 .expect("loop_clip past GlobalEnd should keep looping");
2991 assert_eq!(local_idx, 4);
2992 let once = ClipSpec { loop_clip: false, ..clip };
2993 assert!(cache.load_clip(&once, 20, false, [None; 4]).is_none());
2994 }
2995 assert!(
2996 cache.video_decoder_count() <= MAX_VIDEO_DECODERS,
2997 "expected LRU cap <= {MAX_VIDEO_DECODERS}, got {}",
2998 cache.video_decoder_count()
2999 );
3000 assert_eq!(cache.video_decoder_count(), MAX_VIDEO_DECODERS);
3001
3002 // Straight-alpha ProRes 4444 MOV test for post_multiply separation.
3003 let alpha_png = dir.join("straight_half.png");
3004 image::RgbaImage::from_pixel(32, 32, image::Rgba([200, 100, 50, 128]))
3005 .save(&alpha_png)
3006 .unwrap();
3007 let alpha_mov = dir.join("straight_half.mov");
3008 let mov_ok = Command::new("ffmpeg")
3009 .args([
3010 "-y",
3011 "-v",
3012 "error",
3013 "-loop",
3014 "1",
3015 "-i",
3016 ])
3017 .arg(&alpha_png)
3018 .args([
3019 "-t",
3020 "0.1",
3021 "-r",
3022 "24",
3023 "-c:v",
3024 "prores_ks",
3025 "-profile:v",
3026 "4",
3027 "-pix_fmt",
3028 "yuva444p10le",
3029 ])
3030 .arg(&alpha_mov)
3031 .status()
3032 .is_ok_and(|s| s.success());
3033 if mov_ok {
3034 let mov_clip = ClipSpec {
3035 filename: alpha_mov.to_string_lossy().into_owned(),
3036 alternate_filename: None,
3037 start_frame: 0,
3038 length: Some(2),
3039 trim_in: 0,
3040 trim_out: 1,
3041 global_start: 0,
3042 global_end: 1,
3043 extend_first: 0,
3044 extend_last: 0,
3045 loop_clip: false,
3046 reverse: false,
3047 };
3048 let (_, _, raw_vid, _) = cache.load_clip(&mov_clip, 0, false, [None; 4]).unwrap();
3049 let (_, _, pm_vid, _) = cache.load_clip(&mov_clip, 0, true, [None; 4]).unwrap();
3050 assert!(
3051 pm_vid.rgba[0] < raw_vid.rgba[0],
3052 "post_multiply should darken straight-alpha RGB ({} vs {})",
3053 pm_vid.rgba[0],
3054 raw_vid.rgba[0]
3055 );
3056 }
3057
3058 cache.clear();
3059 assert_eq!(cache.entry_count(), 0);
3060 assert_eq!(cache.video_decoder_count(), 0);
3061
3062 let _ = std::fs::remove_dir_all(&dir);
3063 }
3064
3065 #[test]
3066 fn resolve_clip_path_missing_mid_sequence_returns_none() {
3067 let dir = std::env::temp_dir().join(format!("fission_seq_missing_{}", std::process::id()));
3068 let _ = std::fs::remove_dir_all(&dir);
3069 std::fs::create_dir_all(&dir).unwrap();
3070
3071 let f0 = dir.join("shot_0000.png");
3072 let f2 = dir.join("shot_0002.png");
3073 image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).save(&f0).unwrap();
3074 image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])).save(&f2).unwrap();
3075
3076 let clip = ClipSpec {
3077 filename: f0.to_string_lossy().into_owned(),
3078 alternate_filename: None,
3079 start_frame: 0,
3080 length: Some(3),
3081 trim_in: 0,
3082 trim_out: 2,
3083 global_start: 0,
3084 global_end: 2,
3085 extend_first: 0,
3086 extend_last: 0,
3087 loop_clip: false,
3088 reverse: false,
3089 };
3090 assert_eq!(resolve_clip_path(&clip, 0), Some(f0));
3091 assert_eq!(resolve_clip_path(&clip, 1), None);
3092 assert_eq!(resolve_clip_path(&clip, 2), Some(f2));
3093
3094 let _ = std::fs::remove_dir_all(&dir);
3095 }
3096
3097 #[test]
3098 fn virtual_bytes_load_a_sequence_by_trailing_path() {
3099 let png = |rgba: [u8; 4]| {
3100 let mut out = std::io::Cursor::new(Vec::new());
3101 image::RgbaImage::from_pixel(2, 1, image::Rgba(rgba))
3102 .write_to(&mut out, image::ImageFormat::Png)
3103 .unwrap();
3104 out.into_inner()
3105 };
3106 MediaCache::insert_virtual_bytes("vf_proj\\vf_seq.0001.png", png([255, 0, 0, 255]));
3107 MediaCache::insert_virtual_bytes("./vf_proj/vf_seq.0002.png", png([0, 255, 0, 255]));
3108 let clip = ClipSpec {
3109 filename: "/not/on/disk/vf_proj/vf_seq.0001.png".to_owned(),
3110 alternate_filename: None,
3111 start_frame: 1,
3112 length: Some(2),
3113 trim_in: 0,
3114 trim_out: 1,
3115 global_start: 0,
3116 global_end: 1,
3117 extend_first: 0,
3118 extend_last: 0,
3119 loop_clip: false,
3120 reverse: false,
3121 };
3122 let mut cache = MediaCache::new(64);
3123 let (_, _, f0, from_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
3124 let (_, _, f1, _) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap();
3125 assert!(from_disk);
3126 assert_eq!((f0.size, &f0.rgba[..4]), ([2, 1], &[255, 0, 0, 255][..]));
3127 assert_eq!(&f1.rgba[..4], &[0, 255, 0, 255]);
3128
3129 MediaCache::insert_virtual_bytes("vf_proj/vf_seq.0002.png", png([0, 0, 255, 255]));
3130 let (_, _, f1, _) = MediaCache::new(64).load_clip(&clip, 1, false, [None; 4]).unwrap();
3131 assert_eq!(&f1.rgba[..4], &[0, 0, 255, 255]);
3132 assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png")));
3133 assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png")));
3134 }
3135
3136 fn file(path: &str, len: usize) -> VirtualFile {
3137 VirtualFile { parts: path_parts(Path::new(path)), bytes: vec![0; len].into() }
3138 }
3139
3140 fn found<'a>(files: &'a [VirtualFile], path: &str) -> Option<&'a [String]> {
3141 find_virtual(files, &path_parts(Path::new(path))).map(|f| f.parts.as_slice())
3142 }
3143
3144 #[test]
3145 fn virtual_paths_normalize_dots_and_separators() {
3146 assert_eq!(path_parts(Path::new("/a/./b/../c\\d.png")), ["a", "c", "d.png"]);
3147 assert_eq!(path_parts(Path::new("../../x.png")), ["x.png"]);
3148 }
3149
3150 #[test]
3151 fn virtual_matching_prefers_exact_and_rejects_ambiguous_basenames() {
3152 let files = [file("A/bg.png", 1), file("B/bg.png", 1), file("only.png", 1), file("Proj/Seq.exr", 1)];
3153 assert_eq!(found(&files, "/x/A/bg.png"), Some(&["A".to_owned(), "bg.png".to_owned()][..]));
3154 assert_eq!(found(&files, "/x/../B/./bg.png").map(<[String]>::len), Some(2));
3155 assert_eq!(found(&files, "/C/bg.png"), None, "two files share the basename");
3156 assert_eq!(found(&files, "bg.png"), None);
3157 assert!(found(&files, "/deep/elsewhere/only.png").is_some());
3158 assert!(found(&files, "/proj/seq.EXR").is_some(), "case-insensitive fallback");
3159 assert_eq!(found(&files, "/a/missing.png"), None);
3160 }
3161
3162 #[test]
3163 fn virtual_files_stop_at_the_memory_cap() {
3164 let mut files = Vec::new();
3165 let put = |files: &mut Vec<VirtualFile>, name: &str, len: usize| {
3166 insert_capped(files, 10, path_parts(Path::new(name)), vec![0; len].into())
3167 };
3168 assert!(put(&mut files, "a", 6));
3169 assert!(!put(&mut files, "b", 5));
3170 assert!(put(&mut files, "b", 4));
3171 assert!(put(&mut files, "a", 6), "replacing a file frees its old bytes");
3172 assert!(!put(&mut files, "a", 7));
3173 assert_eq!(files.iter().map(|f| f.bytes.len()).sum::<usize>(), 10);
3174 }
3175
3176 #[test]
3177 fn media_budget_scaling_matches_ram_tiers() {
3178 const GIB: u64 = 1024 * 1024 * 1024;
3179 assert_eq!(media_cache_budget_mb_for_total_bytes(8 * GIB), 512);
3180 assert_eq!(media_cache_budget_mb_for_total_bytes(16 * GIB), 1024);
3181 assert_eq!(media_cache_budget_mb_for_total_bytes(32 * GIB), 2048);
3182 assert_eq!(media_cache_budget_mb_for_total_bytes(64 * GIB), 4096);
3183 assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192);
3184 let default_cache = MediaCache::default();
3185 assert_eq!(
3186 default_cache.shared.state.lock().unwrap().budget_bytes,
3187 default_media_cache_budget_mb().saturating_mul(1024 * 1024)
3188 );
3189 let explicit = MediaCache::with_budget_mb(32);
3190 assert_eq!(
3191 explicit.shared.state.lock().unwrap().budget_bytes,
3192 32 * 1024 * 1024
3193 );
3194 }
3195
3196 #[test]
3197 fn parallel_post_multiply_matches_scalar_across_large_buffer() {
3198 let len = 4 * 1024 * 1024 * 4 + 64; // > 4 MP threshold
3199 let mut scalar = vec![0u8; len];
3200 for (i, px) in scalar.chunks_exact_mut(4).enumerate() {
3201 px[0] = ((i * 7) % 256) as u8;
3202 px[1] = ((i * 13) % 256) as u8;
3203 px[2] = ((i * 29) % 256) as u8;
3204 px[3] = (i % 256) as u8;
3205 }
3206 let mut parallel = scalar.clone();
3207 exr::apply_post_multiply_rgba8_parallel(&mut scalar, false);
3208 exr::apply_post_multiply_rgba8_parallel(&mut parallel, true);
3209 assert_eq!(scalar, parallel);
3210 }
3211
3212 #[cfg(not(target_arch = "wasm32"))]
3213 #[test]
3214 fn preload_frame_loaders_and_prefetch_frames_populate_cache_in_parallel() {
3215 let dir = std::env::temp_dir().join(format!("fission_preload_test_{}", std::process::id()));
3216 let _ = std::fs::remove_dir_all(&dir);
3217 std::fs::create_dir_all(&dir).unwrap();
3218
3219 let p_bg = dir.join("bg.png");
3220 let p_fg0 = dir.join("fg_0000.png");
3221 let p_fg1 = dir.join("fg_0001.png");
3222 let p_fg2 = dir.join("fg_0002.png");
3223 let p_pruned = dir.join("pruned.png");
3224 image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 40, 60, 255])).save(&p_bg).unwrap();
3225 image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 100, 50, 128])).save(&p_fg0).unwrap();
3226 image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 200, 50, 255])).save(&p_fg1).unwrap();
3227 image::RgbaImage::from_pixel(4, 4, image::Rgba([50, 0, 200, 255])).save(&p_fg2).unwrap();
3228 image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 9, 9, 255])).save(&p_pruned).unwrap();
3229
3230 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3231 let comp_src = format!(
3232 r#"Composition {{
3233 CurrentTime = 0,
3234 RenderRange = {{ 0, 2 }},
3235 GlobalRange = {{ 0, 2 }},
3236 Tools = ordered() {{
3237 BgLoader = Loader {{
3238 Clips = {{
3239 Clip {{
3240 ID = "Clip1",
3241 Filename = "{}",
3242 FormatID = "PNGFormat",
3243 Length = 1,
3244 GlobalStart = 0,
3245 GlobalEnd = 2,
3246 }},
3247 }},
3248 }},
3249 FgLoader = Loader {{
3250 Clips = {{
3251 Clip {{
3252 ID = "Clip1",
3253 Filename = "{}",
3254 FormatID = "PNGFormat",
3255 StartFrame = 0,
3256 Length = 3,
3257 GlobalStart = 0,
3258 GlobalEnd = 2,
3259 }},
3260 }},
3261 Inputs = {{
3262 ["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = 1, }},
3263 }},
3264 }},
3265 PrunedLoader = Loader {{
3266 Clips = {{
3267 Clip {{
3268 ID = "Clip1",
3269 Filename = "{}",
3270 FormatID = "PNGFormat",
3271 Length = 1,
3272 GlobalStart = 0,
3273 GlobalEnd = 2,
3274 }},
3275 }},
3276 }},
3277 PrunedMerge = Merge {{
3278 Inputs = {{
3279 Blend = Input {{ Value = 0, }},
3280 Background = Input {{ SourceOp = "BgLoader", Source = "Output", }},
3281 Foreground = Input {{ SourceOp = "PrunedLoader", Source = "Output", }},
3282 }},
3283 }},
3284 MainMerge = Merge {{
3285 Inputs = {{
3286 Background = Input {{ SourceOp = "PrunedMerge", Source = "Output", }},
3287 Foreground = Input {{ SourceOp = "FgLoader", Source = "Output", }},
3288 }},
3289 }},
3290 }},
3291}}"#,
3292 esc(&p_bg),
3293 esc(&p_fg0),
3294 esc(&p_pruned),
3295 );
3296 let comp = Comp::from_fusion_str(&comp_src).expect("parse preload comp");
3297 let target = comp.find_node("MainMerge").expect("MainMerge");
3298 let expr = model::ExprEngine::new();
3299 let mut cache = MediaCache::new(64);
3300
3301 cache.preload_frame_loaders(&comp, target, 0.0, &expr);
3302 // BgLoader + FgLoader(f0) are cached; PrunedLoader is skipped because PrunedMerge Blend == 0.
3303 assert_eq!(cache.entry_count(), 2);
3304
3305 let bg_clip = comp.node(comp.find_node("BgLoader").unwrap()).clips[0].clone();
3306 let fg_clip = comp.node(comp.find_node("FgLoader").unwrap()).clips[0].clone();
3307 let (_, _, bg_img, bg_from_disk) = cache.load_clip(&bg_clip, 0, false, [None; 4]).unwrap();
3308 let (_, _, fg0_img, fg0_from_disk) = cache.load_clip(&fg_clip, 0, true, [None; 4]).unwrap();
3309 assert!(!bg_from_disk);
3310 assert!(!fg0_from_disk);
3311 assert_eq!(&bg_img.rgba[..4], &[20, 40, 60, 255]);
3312 assert_eq!(&fg0_img.rgba[..4], &[100, 50, 25, 128]);
3313
3314 // Prefetch frames 1 and 2 ahead of playback.
3315 cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr);
3316 assert_eq!(cache.entry_count(), 4);
3317 let (_, _, fg1_img, fg1_from_disk) = cache.load_clip(&fg_clip, 1, true, [None; 4]).unwrap();
3318 let (_, _, fg2_img, fg2_from_disk) = cache.load_clip(&fg_clip, 2, true, [None; 4]).unwrap();
3319 assert!(!fg1_from_disk);
3320 assert!(!fg2_from_disk);
3321 assert_eq!(&fg1_img.rgba[..4], &[0, 200, 50, 255]);
3322 assert_eq!(&fg2_img.rgba[..4], &[50, 0, 200, 255]);
3323
3324 let _ = std::fs::remove_dir_all(&dir);
3325 }
3326
3327 #[cfg(not(target_arch = "wasm32"))]
3328 #[test]
3329 fn preload_frame_loaders_decodes_multiple_videos_in_parallel() {
3330 let dir = std::env::temp_dir().join(format!("fission_preload_vid_{}", std::process::id()));
3331 let _ = std::fs::remove_dir_all(&dir);
3332 std::fs::create_dir_all(&dir).unwrap();
3333
3334 let mk_mp4 = |name: &str, color: &str| {
3335 let p = dir.join(name);
3336 let ok = Command::new("ffmpeg")
3337 .args([
3338 "-y",
3339 "-v",
3340 "error",
3341 "-f",
3342 "lavfi",
3343 "-i",
3344 &format!("color=c={color}:size=32x32:rate=24:duration=0.2"),
3345 "-c:v",
3346 "libx264",
3347 "-pix_fmt",
3348 "yuv420p",
3349 ])
3350 .arg(&p)
3351 .status()
3352 .is_ok_and(|s| s.success());
3353 (p, ok)
3354 };
3355 let (v1, ok1) = mk_mp4("v1.mp4", "red");
3356 let (v2, ok2) = mk_mp4("v2.mp4", "blue");
3357 if !(ok1 && ok2) {
3358 let _ = std::fs::remove_dir_all(&dir);
3359 return;
3360 }
3361
3362 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3363 let comp_src = format!(
3364 r#"Composition {{
3365 CurrentTime = 0,
3366 RenderRange = {{ 0, 3 }},
3367 GlobalRange = {{ 0, 3 }},
3368 Tools = ordered() {{
3369 V1 = Loader {{
3370 Clips = {{
3371 Clip {{
3372 ID = "Clip1",
3373 Filename = "{}",
3374 FormatID = "QuickTimeMovies",
3375 Length = 4,
3376 GlobalStart = 0,
3377 GlobalEnd = 3,
3378 }},
3379 }},
3380 }},
3381 V2 = Loader {{
3382 Clips = {{
3383 Clip {{
3384 ID = "Clip1",
3385 Filename = "{}",
3386 FormatID = "QuickTimeMovies",
3387 Length = 4,
3388 GlobalStart = 0,
3389 GlobalEnd = 3,
3390 }},
3391 }},
3392 }},
3393 M = Merge {{
3394 Inputs = {{
3395 Background = Input {{ SourceOp = "V1", Source = "Output", }},
3396 Foreground = Input {{ SourceOp = "V2", Source = "Output", }},
3397 }},
3398 }},
3399 }},
3400}}"#,
3401 esc(&v1),
3402 esc(&v2),
3403 );
3404 let comp = Comp::from_fusion_str(&comp_src).expect("parse video preload comp");
3405 let target = comp.find_node("M").expect("M");
3406 let expr = model::ExprEngine::new();
3407 let mut cache = MediaCache::new(64);
3408
3409 cache.preload_frame_loaders(&comp, target, 0.0, &expr);
3410 assert_eq!(cache.video_decoder_count(), 2);
3411 assert_eq!(cache.entry_count(), 2);
3412
3413 let c1 = comp.node(comp.find_node("V1").unwrap()).clips[0].clone();
3414 let c2 = comp.node(comp.find_node("V2").unwrap()).clips[0].clone();
3415 let (_, _, img1, disk1) = cache.load_clip(&c1, 0, false, [None; 4]).unwrap();
3416 let (_, _, img2, disk2) = cache.load_clip(&c2, 0, false, [None; 4]).unwrap();
3417 assert!(!disk1);
3418 assert!(!disk2);
3419 assert!(img1.rgba[0] > 200 && img1.rgba[2] < 40);
3420 assert!(img2.rgba[2] > 200 && img2.rgba[0] < 40);
3421
3422 cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr);
3423 assert_eq!(cache.entry_count(), 6);
3424
3425 let _ = std::fs::remove_dir_all(&dir);
3426 }
3427
3428 #[cfg(not(target_arch = "wasm32"))]
3429 #[test]
3430 fn background_frame_prefetch_populates_and_cancels_cleanly() {
3431 let dir = std::env::temp_dir().join(format!("fission_bg_prefetch_{}", std::process::id()));
3432 let _ = std::fs::remove_dir_all(&dir);
3433 std::fs::create_dir_all(&dir).unwrap();
3434
3435 for i in 0..4 {
3436 let p = dir.join(format!("seq_{i:04}.png"));
3437 image::RgbaImage::from_pixel(4, 4, image::Rgba([i as u8 * 50, 10, 200, 255]))
3438 .save(&p)
3439 .unwrap();
3440 }
3441 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3442 let p0 = dir.join("seq_0000.png");
3443 let comp_src = format!(
3444 r#"Composition {{
3445 CurrentTime = 0,
3446 RenderRange = {{ 0, 3 }},
3447 GlobalRange = {{ 0, 3 }},
3448 Tools = ordered() {{
3449 LD = Loader {{
3450 Clips = {{
3451 Clip {{
3452 ID = "Clip1",
3453 Filename = "{}",
3454 FormatID = "PNGFormat",
3455 StartFrame = 0,
3456 Length = 4,
3457 GlobalStart = 0,
3458 GlobalEnd = 3,
3459 }},
3460 }},
3461 }},
3462 }},
3463}}"#,
3464 esc(&p0)
3465 );
3466 let comp = Comp::from_fusion_str(&comp_src).expect("parse bg prefetch comp");
3467 let target = comp.find_node("LD").unwrap();
3468 let clip = comp.node(target).clips[0].clone();
3469 let expr = model::ExprEngine::new();
3470 let mut cache = MediaCache::new(64);
3471
3472 let mut handle = cache.start_frame_prefetch(4);
3473 for f in 0..=3 {
3474 handle.enqueue_frame(&comp, target, f, f as f64, &expr, false);
3475 }
3476 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
3477 while cache.entry_count() < 4 && std::time::Instant::now() < deadline {
3478 std::thread::sleep(std::time::Duration::from_millis(5));
3479 }
3480 assert_eq!(cache.entry_count(), 4);
3481 for f in 0..=3 {
3482 let (_, _, img, from_disk) = cache.load_clip(&clip, f, false, [None; 4]).unwrap();
3483 assert!(!from_disk, "frame {f} should already be in MediaCache");
3484 assert_eq!(img.rgba[0], (f as u8) * 50);
3485 }
3486 handle.cancel();
3487 drop(handle);
3488
3489 let _ = std::fs::remove_dir_all(&dir);
3490 }
3491
3492 #[cfg(not(target_arch = "wasm32"))]
3493 #[test]
3494 fn failed_opens_are_not_cached_and_evict_known_existing_paths() {
3495 let dir = std::env::temp_dir().join(format!("fission_evict_test_{}", std::process::id()));
3496 let _ = std::fs::remove_dir_all(&dir);
3497 std::fs::create_dir_all(&dir).unwrap();
3498
3499 let bad_vid = dir.join("corrupt.mp4");
3500 std::fs::write(&bad_vid, b"not a valid mp4").unwrap();
3501 let mut cache = MediaCache::new(64);
3502 assert!(cache.shared.path_exists_cached(&bad_vid));
3503 assert!(cache.shared.get_or_open_video_decoder(&bad_vid).is_none());
3504 assert_eq!(cache.video_decoder_count(), 0);
3505 assert!(!cache.shared.state.lock().unwrap().known_existing_paths.contains(&bad_vid));
3506
3507 let img_path = dir.join("gone.png");
3508 image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 20, 30, 255]))
3509 .save(&img_path)
3510 .unwrap();
3511 assert!(cache.shared.path_exists_cached(&img_path));
3512 std::fs::remove_file(&img_path).unwrap();
3513 let clip = ClipSpec {
3514 filename: img_path.to_string_lossy().into_owned(),
3515 alternate_filename: None,
3516 start_frame: 0,
3517 length: Some(1),
3518 trim_in: 0,
3519 trim_out: 0,
3520 global_start: 0,
3521 global_end: 0,
3522 extend_first: 0,
3523 extend_last: 0,
3524 loop_clip: false,
3525 reverse: false,
3526 };
3527 assert!(cache.load_clip(&clip, 0, false, [None; 4]).is_none());
3528 assert!(!cache.shared.path_exists_cached(&img_path));
3529
3530 let _ = std::fs::remove_dir_all(&dir);
3531 }
3532
3533 #[cfg(not(target_arch = "wasm32"))]
3534 #[test]
3535 fn prefetch_queue_prunes_stale_and_avoids_hol_blocking() {
3536 let dir = std::env::temp_dir().join(format!("fission_hol_prefetch_{}", std::process::id()));
3537 let _ = std::fs::remove_dir_all(&dir);
3538 std::fs::create_dir_all(&dir).unwrap();
3539
3540 for i in 0..=10 {
3541 let p = dir.join(format!("seq_{i:04}.png"));
3542 image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8 * 20, 10, 200, 255]))
3543 .save(&p)
3544 .unwrap();
3545 }
3546 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3547 let p0 = dir.join("seq_0000.png");
3548 let comp_src = format!(
3549 r#"Composition {{
3550 CurrentTime = 0,
3551 RenderRange = {{ 0, 10 }},
3552 GlobalRange = {{ 0, 10 }},
3553 Tools = ordered() {{
3554 LD = Loader {{
3555 Clips = {{
3556 Clip {{
3557 ID = "Clip1",
3558 Filename = "{}",
3559 FormatID = "PNGFormat",
3560 StartFrame = 0,
3561 Length = 11,
3562 GlobalStart = 0,
3563 GlobalEnd = 10,
3564 }},
3565 }},
3566 }},
3567 }},
3568}}"#,
3569 esc(&p0)
3570 );
3571 let comp = Comp::from_fusion_str(&comp_src).expect("parse hol prefetch comp");
3572 let target = comp.find_node("LD").unwrap();
3573 let clip = comp.node(target).clips[0].clone();
3574 let expr = model::ExprEngine::new();
3575 let mut cache = MediaCache::new(64);
3576
3577 let mut handle = cache.start_frame_prefetch(2);
3578 // Enqueue far-future seq=10 first (outside lookahead=2), then seq=1 (within lookahead).
3579 handle.enqueue_frame(&comp, target, 10, 10.0, &expr, false);
3580 handle.enqueue_frame(&comp, target, 1, 1.0, &expr, false);
3581
3582 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
3583 while cache.entry_count() < 1 && std::time::Instant::now() < deadline {
3584 std::thread::sleep(std::time::Duration::from_millis(5));
3585 }
3586 assert_eq!(cache.entry_count(), 1);
3587 let (_, _, img1, from_disk1) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap();
3588 assert!(!from_disk1, "seq=1 must not be head-of-line blocked by seq=10");
3589 assert_eq!(img1.rgba[0], 20);
3590
3591 // Advancing current_seq past 10 prunes seq=10 cleanly.
3592 handle.set_current_seq(11);
3593 {
3594 let q = handle.queue.state.lock().unwrap();
3595 assert!(q.raster.is_empty());
3596 assert!(q.queued_raster_keys.is_empty());
3597 }
3598 handle.cancel();
3599 let _ = std::fs::remove_dir_all(&dir);
3600 }
3601
3602 #[cfg(not(target_arch = "wasm32"))]
3603 #[test]
3604 fn prefetch_handle_scales_and_decodes_nine_videos_concurrently() {
3605 let dir = std::env::temp_dir().join(format!("fission_9vid_prefetch_{}", std::process::id()));
3606 let _ = std::fs::remove_dir_all(&dir);
3607 std::fs::create_dir_all(&dir).unwrap();
3608
3609 let v0 = dir.join("v0.mp4");
3610 let ok = Command::new("ffmpeg")
3611 .args([
3612 "-y",
3613 "-v",
3614 "error",
3615 "-f",
3616 "lavfi",
3617 "-i",
3618 "color=c=green:size=16x16:rate=24:duration=0.15",
3619 "-c:v",
3620 "libx264",
3621 "-pix_fmt",
3622 "yuv420p",
3623 ])
3624 .arg(&v0)
3625 .status()
3626 .is_ok_and(|s| s.success());
3627 if !ok {
3628 let _ = std::fs::remove_dir_all(&dir);
3629 return;
3630 }
3631
3632 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3633 let mut tools = String::new();
3634 for i in 0..9 {
3635 let vi = dir.join(format!("v{i}.mp4"));
3636 if i > 0 {
3637 std::fs::copy(&v0, &vi).unwrap();
3638 }
3639 tools.push_str(&format!(
3640 r#" V{i} = Loader {{
3641 Clips = {{
3642 Clip {{
3643 ID = "Clip1",
3644 Filename = "{}",
3645 FormatID = "QuickTimeMovies",
3646 Length = 3,
3647 GlobalStart = 0,
3648 GlobalEnd = 2,
3649 }},
3650 }},
3651 }},
3652"#,
3653 esc(&vi)
3654 ));
3655 }
3656 let mut prev = "V0".to_owned();
3657 for i in 1..9 {
3658 let mname = format!("M{i}");
3659 tools.push_str(&format!(
3660 r#" {mname} = Merge {{
3661 Inputs = {{
3662 Background = Input {{ SourceOp = "{prev}", Source = "Output", }},
3663 Foreground = Input {{ SourceOp = "V{i}", Source = "Output", }},
3664 }},
3665 }},
3666"#
3667 ));
3668 prev = mname;
3669 }
3670 let comp_src = format!(
3671 "Composition {{\n CurrentTime = 0,\n RenderRange = {{ 0, 2 }},\n GlobalRange = {{ 0, 2 }},\n Tools = ordered() {{\n{tools} }},\n}}"
3672 );
3673 let comp = Comp::from_fusion_str(&comp_src).expect("parse 9-video comp");
3674 let target = comp.find_node("M8").expect("M8");
3675 let expr = model::ExprEngine::new();
3676 let cache = MediaCache::new(64);
3677
3678 let mut handle = cache.start_frame_prefetch(4);
3679 let expected_workers = std::thread::available_parallelism()
3680 .map(|n| n.get().clamp(2, 12))
3681 .unwrap_or(4);
3682 assert_eq!(handle.workers.len(), expected_workers);
3683
3684 handle.enqueue_frame(&comp, target, 0, 0.0, &expr, false);
3685 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
3686 while cache.entry_count() < 9 && std::time::Instant::now() < deadline {
3687 std::thread::sleep(std::time::Duration::from_millis(5));
3688 }
3689 assert_eq!(cache.video_decoder_count(), 9);
3690 assert_eq!(cache.entry_count(), 9);
3691 handle.cancel();
3692 let _ = std::fs::remove_dir_all(&dir);
3693 }
3694
3695 #[cfg(not(target_arch = "wasm32"))]
3696 #[test]
3697 fn warm_cache_over_75_percent_keeps_full_lookahead() {
3698 let dir = std::env::temp_dir().join(format!("fission_warm_lookahead_{}", std::process::id()));
3699 let _ = std::fs::remove_dir_all(&dir);
3700 std::fs::create_dir_all(&dir).unwrap();
3701
3702 for i in 0..=4 {
3703 let p = dir.join(format!("seq_{i:04}.png"));
3704 image::RgbaImage::from_pixel(512, 512, image::Rgba([i as u8 * 40, 20, 180, 255]))
3705 .save(&p)
3706 .unwrap();
3707 }
3708 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3709 let p0 = dir.join("seq_0000.png");
3710 let comp_src = format!(
3711 r#"Composition {{
3712 CurrentTime = 0,
3713 RenderRange = {{ 0, 4 }},
3714 GlobalRange = {{ 0, 4 }},
3715 Tools = ordered() {{
3716 LD = Loader {{
3717 Clips = {{
3718 Clip {{
3719 ID = "Clip1",
3720 Filename = "{}",
3721 FormatID = "PNGFormat",
3722 StartFrame = 0,
3723 Length = 5,
3724 GlobalStart = 0,
3725 GlobalEnd = 4,
3726 }},
3727 }},
3728 }},
3729 }},
3730}}"#,
3731 esc(&p0)
3732 );
3733 let comp = Comp::from_fusion_str(&comp_src).expect("parse warm lookahead comp");
3734 let target = comp.find_node("LD").unwrap();
3735 let clip = comp.node(target).clips[0].clone();
3736 let expr = model::ExprEngine::new();
3737 let mut cache = MediaCache::new(64);
3738
3739 // Warm the cache past 75% of its 64 MiB budget (13 x 4 MiB = 52 MiB = 81.25%).
3740 let four_mb = Arc::new(vec![128u8; 1024 * 1024 * 4]);
3741 {
3742 let mut state = cache.shared.state.lock().unwrap();
3743 for i in 0..13 {
3744 let key = ImageCacheKey {
3745 path: dir.join(format!("warm_{i:04}.png")),
3746 frame_idx: -1,
3747 post_multiply: false,
3748 exr_channels: [None, None, None, None],
3749 };
3750 let img = DecodedImage {
3751 size: [1024, 1024],
3752 rgba: Arc::clone(&four_mb),
3753 rgba_f16: None,
3754 rgba_f32: None,
3755 };
3756 cache.shared.insert_cached_locked(&mut state, key, img);
3757 }
3758 }
3759 assert!(
3760 cache.total_mb() > 48.0,
3761 "cache must be >75% of 64 MiB, got {:.2} MiB",
3762 cache.total_mb()
3763 );
3764
3765 let mut handle = cache.start_frame_prefetch(4);
3766 handle.set_current_seq(0);
3767 for seq in 1..=4 {
3768 handle.enqueue_frame(&comp, target, seq, seq as f64, &expr, false);
3769 }
3770
3771 // All 4 lookahead frames (through current_seq + 4) must be prefetched without collapsing
3772 // to current_seq + 1.
3773 let expected_keys: Vec<ImageCacheKey> = (1..=4)
3774 .map(|i| ImageCacheKey {
3775 path: dir.join(format!("seq_{i:04}.png")),
3776 frame_idx: -1,
3777 post_multiply: false,
3778 exr_channels: [None, None, None, None],
3779 })
3780 .collect();
3781 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
3782 loop {
3783 let all_cached = cache
3784 .shared
3785 .state
3786 .lock()
3787 .map(|s| expected_keys.iter().all(|k| s.images.contains_key(k)))
3788 .unwrap_or(false);
3789 if all_cached || std::time::Instant::now() >= deadline {
3790 break;
3791 }
3792 std::thread::sleep(std::time::Duration::from_millis(5));
3793 }
3794
3795 for i in 1..=4 {
3796 let (_, _, img, from_disk) = cache.load_clip(&clip, i, false, [None; 4]).unwrap();
3797 assert!(
3798 !from_disk,
3799 "frame {i} (current_seq + {i}) should have been prefetched while >75% warm"
3800 );
3801 assert_eq!(img.rgba[0], (i as u8) * 40);
3802 }
3803
3804 handle.cancel();
3805 let _ = std::fs::remove_dir_all(&dir);
3806 }
3807
3808 #[test]
3809 fn direct_png_decode_matches_image_crate_bit_for_bit_all_color_types() {
3810 fn encode_png(
3811 w: u32,
3812 h: u32,
3813 color: png::ColorType,
3814 depth: png::BitDepth,
3815 palette: Option<&[u8]>,
3816 trns: Option<&[u8]>,
3817 data: &[u8],
3818 ) -> Vec<u8> {
3819 let mut out = Vec::new();
3820 {
3821 let mut enc = png::Encoder::new(&mut out, w, h);
3822 enc.set_color(color);
3823 enc.set_depth(depth);
3824 if let Some(p) = palette {
3825 enc.set_palette(p);
3826 }
3827 if let Some(t) = trns {
3828 enc.set_trns(t);
3829 }
3830 let mut writer = enc.write_header().unwrap();
3831 writer.write_image_data(data).unwrap();
3832 }
3833 out
3834 }
3835
3836 let (w, h) = (17u32, 11u32);
3837 let n = (w * h) as usize;
3838 let cases: Vec<(&str, Vec<u8>)> = vec![
3839 (
3840 "rgba8",
3841 encode_png(
3842 w,
3843 h,
3844 png::ColorType::Rgba,
3845 png::BitDepth::Eight,
3846 None,
3847 None,
3848 &(0..n * 4).map(|i| ((i * 37 + 13) % 256) as u8).collect::<Vec<_>>(),
3849 ),
3850 ),
3851 (
3852 "rgb8",
3853 encode_png(
3854 w,
3855 h,
3856 png::ColorType::Rgb,
3857 png::BitDepth::Eight,
3858 None,
3859 None,
3860 &(0..n * 3).map(|i| ((i * 53 + 7) % 256) as u8).collect::<Vec<_>>(),
3861 ),
3862 ),
3863 (
3864 "gray8",
3865 encode_png(
3866 w,
3867 h,
3868 png::ColorType::Grayscale,
3869 png::BitDepth::Eight,
3870 None,
3871 None,
3872 &(0..n).map(|i| ((i * 29 + 3) % 256) as u8).collect::<Vec<_>>(),
3873 ),
3874 ),
3875 (
3876 "gray_alpha8",
3877 encode_png(
3878 w,
3879 h,
3880 png::ColorType::GrayscaleAlpha,
3881 png::BitDepth::Eight,
3882 None,
3883 None,
3884 &(0..n * 2).map(|i| ((i * 41 + 19) % 256) as u8).collect::<Vec<_>>(),
3885 ),
3886 ),
3887 (
3888 "palette_trns",
3889 encode_png(
3890 w,
3891 h,
3892 png::ColorType::Indexed,
3893 png::BitDepth::Eight,
3894 Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128, 255, 255, 255]),
3895 Some(&[0, 128, 255]),
3896 &(0..n).map(|i| (i % 4) as u8).collect::<Vec<_>>(),
3897 ),
3898 ),
3899 (
3900 "palette_opaque",
3901 encode_png(
3902 w,
3903 h,
3904 png::ColorType::Indexed,
3905 png::BitDepth::Eight,
3906 Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128]),
3907 None,
3908 &(0..n).map(|i| (i % 3) as u8).collect::<Vec<_>>(),
3909 ),
3910 ),
3911 (
3912 "rgba16",
3913 encode_png(
3914 w,
3915 h,
3916 png::ColorType::Rgba,
3917 png::BitDepth::Sixteen,
3918 None,
3919 None,
3920 // Include boundary values like 0x01ff (511 -> rounds to 2, not 1).
3921 &(0..n * 4)
3922 .flat_map(|i| (((i * 1021 + 255) % 65536) as u16).to_be_bytes())
3923 .collect::<Vec<_>>(),
3924 ),
3925 ),
3926 (
3927 "rgb16",
3928 encode_png(
3929 w,
3930 h,
3931 png::ColorType::Rgb,
3932 png::BitDepth::Sixteen,
3933 None,
3934 None,
3935 &(0..n * 3)
3936 .flat_map(|i| (((i * 997 + 511) % 65536) as u16).to_be_bytes())
3937 .collect::<Vec<_>>(),
3938 ),
3939 ),
3940 (
3941 "gray16",
3942 encode_png(
3943 w,
3944 h,
3945 png::ColorType::Grayscale,
3946 png::BitDepth::Sixteen,
3947 None,
3948 None,
3949 &(0..n)
3950 .flat_map(|i| (((i * 773 + 128) % 65536) as u16).to_be_bytes())
3951 .collect::<Vec<_>>(),
3952 ),
3953 ),
3954 (
3955 "gray_alpha16",
3956 encode_png(
3957 w,
3958 h,
3959 png::ColorType::GrayscaleAlpha,
3960 png::BitDepth::Sixteen,
3961 None,
3962 None,
3963 &(0..n * 2)
3964 .flat_map(|i| (((i * 613 + 384) % 65536) as u16).to_be_bytes())
3965 .collect::<Vec<_>>(),
3966 ),
3967 ),
3968 ];
3969
3970 for (label, bytes) in cases {
3971 let dyn_img = image::load_from_memory(&bytes).expect("image crate decode");
3972 let expected_has_alpha = dyn_img.color().has_alpha();
3973 let expected_size = [dyn_img.width(), dyn_img.height()];
3974 let expected_rgba = dyn_img.into_rgba8().into_raw();
3975
3976 let (got_size, got_rgba, got_has_alpha) = match decode_png_bytes(&bytes) {
3977 PngDecodeOutcome::Decoded(v) => v,
3978 PngDecodeOutcome::Fallback | PngDecodeOutcome::Reject => {
3979 panic!("direct decode failed for {label}")
3980 }
3981 };
3982 assert_eq!(got_size, expected_size, "size mismatch for {label}");
3983 assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}");
3984 assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}");
3985 }
3986 }
3987
3988 #[test]
3989 fn reject_spoofed_oversized_png_ihdr_without_allocating() {
3990 fn png_crc32(data: &[u8]) -> u32 {
3991 let mut crc = 0xFFFF_FFFFu32;
3992 for &b in data {
3993 crc ^= b as u32;
3994 for _ in 0..8 {
3995 let mask = (crc & 1).wrapping_neg();
3996 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
3997 }
3998 }
3999 !crc
4000 }
4001
4002 fn push_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], payload: &[u8]) {
4003 out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
4004 let crc_start = out.len();
4005 out.extend_from_slice(chunk_type);
4006 out.extend_from_slice(payload);
4007 let crc = png_crc32(&out[crc_start..]);
4008 out.extend_from_slice(&crc.to_be_bytes());
4009 }
4010
4011 let mut crafted = vec![137, 80, 78, 71, 13, 10, 26, 10];
4012 let mut ihdr = [0u8; 13];
4013 ihdr[0..4].copy_from_slice(&16u32.to_be_bytes());
4014 ihdr[4..8].copy_from_slice(&1_000_000_000u32.to_be_bytes());
4015 ihdr[8] = 8; // bit depth
4016 ihdr[9] = 6; // RGBA
4017 push_chunk(&mut crafted, b"IHDR", &ihdr);
4018 push_chunk(&mut crafted, b"IDAT", &[0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]);
4019 push_chunk(&mut crafted, b"IEND", &[]);
4020 assert_eq!(crafted.len(), 67);
4021
4022 assert!(matches!(decode_png_bytes(&crafted), PngDecodeOutcome::Reject));
4023 assert!(decode_raster_bytes(&crafted).is_none());
4024 }
4025}
crates/engine/src/media/png.rs created+250
......@@ -0,0 +1,250 @@
1use ::png;
2use super::*;
3
4#[inline(always)]
5fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 {
6 ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8
7}
8
9const MAX_PNG_OUTPUT_BYTES: usize = 512 * 1024 * 1024;
10
11pub(super) enum PngDecodeOutcome {
12 Decoded(([u32; 2], Vec<u8>, bool)),
13 Fallback,
14 Reject,
15}
16
17fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>(
18 reader: &mut png::Reader<R>,
19 line_size: usize,
20 out_len: usize,
21 row_out_bytes: usize,
22 mut convert_row: F,
23) -> Option<Vec<u8>>
24where
25 F: FnMut(&[u8], &mut [u8]),
26{
27 let mut rgba = Vec::new();
28 rgba.try_reserve_exact(out_len).ok()?;
29 rgba.resize(out_len, 0);
30 let mut row_buf = Vec::new();
31 row_buf.try_reserve_exact(line_size).ok()?;
32 row_buf.resize(line_size, 0);
33 for dst_row in rgba.chunks_exact_mut(row_out_bytes) {
34 reader.read_row(&mut row_buf).ok()??;
35 convert_row(&row_buf, dst_row);
36 }
37 Some(rgba)
38}
39
40/// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit.
41/// Returns `Fallback` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the
42/// caller falls back cleanly to `image::load_from_memory`, and `Reject` for corrupt or
43/// oversized PNGs so callers fail immediately without double-decoding or OOM.
44pub(super) fn decode_png_bytes(bytes: &[u8]) -> PngDecodeOutcome {
45 const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
46 if !bytes.starts_with(&PNG_SIGNATURE) {
47 return PngDecodeOutcome::Fallback;
48 }
49
50 let mut decoder = png::Decoder::new_with_limits(
51 std::io::Cursor::new(bytes),
52 png::Limits {
53 bytes: MAX_PNG_OUTPUT_BYTES,
54 },
55 );
56 decoder.set_ignore_text_chunk(true);
57 decoder.set_transformations(png::Transformations::EXPAND);
58
59 let Ok(mut reader) = decoder.read_info() else {
60 return PngDecodeOutcome::Reject;
61 };
62 let info = reader.info();
63 let (w, h) = info.size();
64 if w == 0 || h == 0 {
65 return PngDecodeOutcome::Reject;
66 }
67
68 let Some(pixel_count) = (w as usize).checked_mul(h as usize) else {
69 return PngDecodeOutcome::Reject;
70 };
71 let Some(out_len) = pixel_count.checked_mul(4) else {
72 return PngDecodeOutcome::Reject;
73 };
74 if out_len > MAX_PNG_OUTPUT_BYTES {
75 return PngDecodeOutcome::Reject;
76 }
77
78 if info.interlaced
79 || info.icc_profile.is_some()
80 || info.animation_control.is_some()
81 || info.frame_control.is_some()
82 {
83 return PngDecodeOutcome::Fallback;
84 }
85
86 let (color_type, bit_depth) = reader.output_color_type();
87 let Some(row_out_bytes) = (w as usize).checked_mul(4) else {
88 return PngDecodeOutcome::Reject;
89 };
90 let Some(line_size) = reader.output_line_size(w) else {
91 return PngDecodeOutcome::Reject;
92 };
93
94 match (color_type, bit_depth) {
95 (png::ColorType::Rgba, png::BitDepth::Eight) => {
96 let mut rgba = Vec::new();
97 if rgba.try_reserve_exact(out_len).is_err() {
98 return PngDecodeOutcome::Reject;
99 }
100 rgba.resize(out_len, 0);
101 if reader.next_frame(&mut rgba).is_err() {
102 return PngDecodeOutcome::Reject;
103 }
104 PngDecodeOutcome::Decoded(([w, h], rgba, true))
105 }
106 (png::ColorType::Rgb, png::BitDepth::Eight) => {
107 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
108 let (src_chunks, _) = src.as_chunks::<3>();
109 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
110 for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) {
111 *dst_px = [r, g, b, 255];
112 }
113 }) else {
114 return PngDecodeOutcome::Reject;
115 };
116 PngDecodeOutcome::Decoded(([w, h], rgba, false))
117 }
118 (png::ColorType::Grayscale, png::BitDepth::Eight) => {
119 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
120 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
121 for (&g, dst_px) in src.iter().zip(dst_chunks) {
122 *dst_px = [g, g, g, 255];
123 }
124 }) else {
125 return PngDecodeOutcome::Reject;
126 };
127 PngDecodeOutcome::Decoded(([w, h], rgba, false))
128 }
129 (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => {
130 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
131 let (src_chunks, _) = src.as_chunks::<2>();
132 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
133 for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) {
134 *dst_px = [g, g, g, a];
135 }
136 }) else {
137 return PngDecodeOutcome::Reject;
138 };
139 PngDecodeOutcome::Decoded(([w, h], rgba, true))
140 }
141 (png::ColorType::Rgba, png::BitDepth::Sixteen) => {
142 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
143 let (src_chunks, _) = src.as_chunks::<8>();
144 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
145 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
146 *dst_px = [
147 u16_be_to_u8_rounded(s[0], s[1]),
148 u16_be_to_u8_rounded(s[2], s[3]),
149 u16_be_to_u8_rounded(s[4], s[5]),
150 u16_be_to_u8_rounded(s[6], s[7]),
151 ];
152 }
153 }) else {
154 return PngDecodeOutcome::Reject;
155 };
156 PngDecodeOutcome::Decoded(([w, h], rgba, true))
157 }
158 (png::ColorType::Rgb, png::BitDepth::Sixteen) => {
159 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
160 let (src_chunks, _) = src.as_chunks::<6>();
161 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
162 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
163 *dst_px = [
164 u16_be_to_u8_rounded(s[0], s[1]),
165 u16_be_to_u8_rounded(s[2], s[3]),
166 u16_be_to_u8_rounded(s[4], s[5]),
167 255,
168 ];
169 }
170 }) else {
171 return PngDecodeOutcome::Reject;
172 };
173 PngDecodeOutcome::Decoded(([w, h], rgba, false))
174 }
175 (png::ColorType::Grayscale, png::BitDepth::Sixteen) => {
176 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
177 let (src_chunks, _) = src.as_chunks::<2>();
178 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
179 for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) {
180 let g = u16_be_to_u8_rounded(hi, lo);
181 *dst_px = [g, g, g, 255];
182 }
183 }) else {
184 return PngDecodeOutcome::Reject;
185 };
186 PngDecodeOutcome::Decoded(([w, h], rgba, false))
187 }
188 (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => {
189 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
190 let (src_chunks, _) = src.as_chunks::<4>();
191 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
192 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
193 let g = u16_be_to_u8_rounded(s[0], s[1]);
194 *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])];
195 }
196 }) else {
197 return PngDecodeOutcome::Reject;
198 };
199 PngDecodeOutcome::Decoded(([w, h], rgba, true))
200 }
201 _ => PngDecodeOutcome::Fallback,
202 }
203}
204
205pub(super) fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
206 match decode_png_bytes(bytes) {
207 PngDecodeOutcome::Decoded(decoded) => return Some(decoded),
208 PngDecodeOutcome::Reject => return None,
209 PngDecodeOutcome::Fallback => {}
210 }
211 let dyn_img = image::load_from_memory(bytes).ok()?;
212 let has_alpha = dyn_img.color().has_alpha();
213 let size = [dyn_img.width(), dyn_img.height()];
214 let raw = dyn_img.into_rgba8().into_raw();
215 Some((size, raw, has_alpha))
216}
217
218fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec<u8>, bool)> {
219 if let Some(bytes) = virtual_bytes(path) {
220 return decode_raster_bytes(&bytes);
221 }
222 // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares.
223 match std::fs::read(path) {
224 Ok(bytes) => return decode_raster_bytes(&bytes),
225 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
226 Err(_) => {}
227 }
228 let dyn_img = image::open(path).ok()?;
229 let has_alpha = dyn_img.color().has_alpha();
230 let size = [dyn_img.width(), dyn_img.height()];
231 let raw = dyn_img.into_rgba8().into_raw();
232 Some((size, raw, has_alpha))
233}
234
235pub(super) fn decode_raster_image(
236 path: &Path,
237 post_multiply: bool,
238 allow_parallel_premult: bool,
239) -> Option<DecodedImage> {
240 let (size, mut raw, has_alpha) = open_raster_rgba(path)?;
241 if post_multiply && has_alpha {
242 apply_post_multiply_rgba8_parallel(&mut raw, allow_parallel_premult);
243 }
244 Some(DecodedImage {
245 size,
246 rgba: Arc::new(raw),
247 rgba_f16: None,
248 rgba_f32: None,
249 })
250}
crates/engine/src/media/prefetch.rs created+1309
......@@ -0,0 +1,1309 @@
1use super::*;
2
3#[cfg(not(target_arch = "wasm32"))]
4impl MediaState {
5 pub(super) fn record_speculative_decode(&mut self, bytes: u64) {
6 self.speculative_bytes_since_seq = self.speculative_bytes_since_seq.saturating_add(bytes);
7 self.speculative_count_since_seq = self.speculative_count_since_seq.saturating_add(1);
8 self.last_speculative_bytes = bytes;
9 }
10
11 pub(super) fn reset_speculative_window(&mut self, seq_idx: usize) {
12 if self.last_prefetch_seq != Some(seq_idx) {
13 self.last_prefetch_seq = Some(seq_idx);
14 self.speculative_bytes_since_seq = 0;
15 self.speculative_count_since_seq = 0;
16 }
17 }
18
19 pub(super) fn should_throttle_lookahead(&self) -> bool {
20 const MIN_LOOKAHEAD_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
21 if self.budget_bytes < MIN_LOOKAHEAD_BUDGET_BYTES {
22 return true;
23 }
24 let avg_item_bytes = if self.speculative_count_since_seq > 0 {
25 self.speculative_bytes_since_seq / self.speculative_count_since_seq
26 } else {
27 self.last_speculative_bytes
28 };
29 let in_flight_est = (self.in_flight.len() as u64).saturating_mul(avg_item_bytes);
30 self.speculative_bytes_since_seq.saturating_add(in_flight_est) >= self.budget_bytes / 2
31 }
32}
33
34impl MediaShared {
35 pub(super) fn sync_lookahead_throttle(&self, state: &MediaState) -> bool {
36 #[cfg(not(target_arch = "wasm32"))]
37 {
38 let throttled = state.should_throttle_lookahead();
39 let was_throttled = self.lookahead_throttled.load(Ordering::Acquire);
40 self.lookahead_throttled.store(throttled, Ordering::Release);
41 was_throttled && !throttled
42 }
43 #[cfg(target_arch = "wasm32")]
44 {
45 let _ = state;
46 false
47 }
48 }
49
50 #[cfg(not(target_arch = "wasm32"))]
51 fn register_prefetch_queue(&self, queue: &Arc<PrefetchQueue>) {
52 if let Ok(mut queues) = self.prefetch_queues.lock() {
53 queues.retain(|w| w.strong_count() > 0);
54 queues.push(Arc::downgrade(queue));
55 }
56 }
57
58 #[cfg(not(target_arch = "wasm32"))]
59 pub(super) fn notify_prefetch_waiters(&self) {
60 let live: Vec<Arc<PrefetchQueue>> = {
61 let Ok(mut queues) = self.prefetch_queues.lock() else { return };
62 let mut out = Vec::with_capacity(queues.len());
63 queues.retain(|w| {
64 if let Some(q) = w.upgrade() {
65 out.push(q);
66 true
67 } else {
68 false
69 }
70 });
71 out
72 };
73 for q in live {
74 if let Ok(_guard) = q.state.lock() {
75 q.cv.notify_all();
76 }
77 }
78 }
79}
80
81impl MediaCache {
82 /// Walks reachable `Loader` nodes upstream of `target` at `time` and decodes any missing
83 /// still/sequence/EXR frames into RAM in parallel when 2 or more distinct files are uncached.
84 pub fn preload_frame_loaders(
85 &mut self,
86 comp: &Comp,
87 target: NodeId,
88 time: f64,
89 expr: &model::ExprEngine,
90 ) {
91 self.preload_frame_loaders_with_proxy(comp, target, time, expr, false);
92 }
93
94 /// Variant of [`Self::preload_frame_loaders`] honoring `use_proxy_clips`.
95 pub fn preload_frame_loaders_with_proxy(
96 &mut self,
97 comp: &Comp,
98 target: NodeId,
99 time: f64,
100 expr: &model::ExprEngine,
101 use_proxy_clips: bool,
102 ) {
103 #[cfg(target_arch = "wasm32")]
104 {
105 let _ = (comp, target, time, expr, use_proxy_clips);
106 }
107 #[cfg(not(target_arch = "wasm32"))]
108 {
109 let mut visited = HashSet::new();
110 let mut jobs = MissingJobs::default();
111 collect_missing_loader_jobs_shared(
112 &self.shared,
113 comp,
114 target,
115 time,
116 expr,
117 use_proxy_clips,
118 &mut visited,
119 &mut jobs,
120 );
121 if jobs.total_units() < 2 {
122 return;
123 }
124 self.decode_jobs_parallel(jobs);
125 }
126 }
127
128 /// Pre-decodes reachable `Loader` files for upcoming `frames` in parallel into `MediaCache`.
129 pub fn prefetch_frames(
130 &mut self,
131 comp: &Comp,
132 target: NodeId,
133 frames: &[f64],
134 expr: &model::ExprEngine,
135 ) {
136 self.prefetch_frames_with_proxy(comp, target, frames, expr, false);
137 }
138
139 /// Variant of [`Self::prefetch_frames`] honoring `use_proxy_clips`.
140 pub fn prefetch_frames_with_proxy(
141 &mut self,
142 comp: &Comp,
143 target: NodeId,
144 frames: &[f64],
145 expr: &model::ExprEngine,
146 use_proxy_clips: bool,
147 ) {
148 #[cfg(target_arch = "wasm32")]
149 {
150 let _ = (comp, target, frames, expr, use_proxy_clips);
151 }
152 #[cfg(not(target_arch = "wasm32"))]
153 {
154 if frames.is_empty() {
155 return;
156 }
157 let mut visited = HashSet::new();
158 let mut jobs = MissingJobs::default();
159 for &time in frames {
160 collect_missing_loader_jobs_shared(
161 &self.shared,
162 comp,
163 target,
164 time,
165 expr,
166 use_proxy_clips,
167 &mut visited,
168 &mut jobs,
169 );
170 }
171 let total = jobs.total_units();
172 if total == 0 {
173 return;
174 }
175 if total == 1 && jobs.raster.len() == 1 {
176 let job = jobs.raster.pop().expect("len == 1");
177 let cache_gen = {
178 let Ok(mut state) = self.shared.state.lock() else { return };
179 if state.images.contains_key(&job.cache_key)
180 || state.in_flight.contains(&job.cache_key)
181 {
182 return;
183 }
184 state.in_flight.insert(job.cache_key.clone());
185 self.shared.sync_lookahead_throttle(&state);
186 state.generation
187 };
188 let mut guard = InFlightGuard {
189 shared: &self.shared,
190 key: Some(job.cache_key.clone()),
191 };
192 let decoded = decode_job(&job, true);
193 finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded, false);
194 return;
195 }
196 self.decode_jobs_parallel(jobs);
197 }
198 }
199
200 /// Starts a non-blocking, cancellable background read-ahead worker pool that pre-decodes
201 /// upcoming frames into `MediaCache` while the GPU renders the current frame.
202 #[cfg(not(target_arch = "wasm32"))]
203 pub fn start_frame_prefetch(&self, lookahead: usize) -> MediaPrefetchHandle {
204 MediaPrefetchHandle::spawn(Arc::clone(&self.shared), lookahead.max(1))
205 }
206
207 #[cfg(not(target_arch = "wasm32"))]
208 fn decode_jobs_parallel(&mut self, mut jobs: MissingJobs) {
209 let mut video_tasks: Vec<VideoDecodeTask> = jobs
210 .videos
211 .drain()
212 .map(|(path, requests)| VideoDecodeTask { path, requests })
213 .collect();
214 let video_count = video_tasks.len();
215 let raster_jobs = jobs.raster;
216 let total_units = video_count + raster_jobs.len();
217 if total_units == 0 {
218 return;
219 }
220 let workers = std::thread::available_parallelism()
221 .map(|n| n.get().clamp(2, 12))
222 .unwrap_or(4)
223 .min(total_units);
224
225 let next_idx = AtomicUsize::new(0);
226 let video_inputs: Vec<Mutex<Option<VideoDecodeTask>>> =
227 video_tasks.drain(..).map(|t| Mutex::new(Some(t))).collect();
228
229 std::thread::scope(|scope| {
230 for _ in 0..workers {
231 scope.spawn(|| loop {
232 let idx = next_idx.fetch_add(1, Ordering::Relaxed);
233 if idx >= total_units {
234 break;
235 }
236 if idx < video_count {
237 let task = video_inputs[idx].lock().ok().and_then(|mut g| g.take());
238 if let Some(task) = task {
239 if let Some((info, dec_arc)) = self.shared.get_or_open_video_decoder(&task.path) {
240 let mut seen_local = HashSet::new();
241 for req in &task.requests {
242 let frame_idx = compute_video_frame_idx(
243 &req.clip,
244 req.frame_i,
245 info.nb_frames,
246 );
247 if !seen_local.insert((frame_idx, req.post_multiply)) {
248 continue;
249 }
250 let key = ImageCacheKey {
251 path: task.path.clone(),
252 frame_idx,
253 post_multiply: req.post_multiply,
254 exr_channels: [None, None, None, None],
255 };
256 let cache_gen_opt = self.shared.state.lock().ok().and_then(|mut state| {
257 if state.images.contains_key(&key)
258 || state.in_flight.contains(&key)
259 {
260 None
261 } else {
262 state.in_flight.insert(key.clone());
263 self.shared.sync_lookahead_throttle(&state);
264 Some(state.generation)
265 }
266 });
267 let Some(cache_gen) = cache_gen_opt else { continue };
268 let mut guard = InFlightGuard {
269 shared: &self.shared,
270 key: Some(key.clone()),
271 };
272 let decoded_raw = dec_arc
273 .lock()
274 .ok()
275 .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx));
276 if let Some(mut raw) = decoded_raw {
277 if req.post_multiply {
278 apply_post_multiply_rgba8_parallel(&mut raw, false);
279 }
280 let decoded = DecodedImage {
281 size: [info.width, info.height],
282 rgba: Arc::new(raw),
283 rgba_f16: None,
284 rgba_f32: None,
285 };
286 let unthrottled = if let Ok(mut state) = self.shared.state.lock() {
287 state.in_flight.remove(&key);
288 guard.key = None;
289 let unthrottled = if state.generation == cache_gen {
290 self.shared
291 .insert_cached_locked(&mut state, key, decoded)
292 } else {
293 self.shared.sync_lookahead_throttle(&state)
294 };
295 self.shared.cv.notify_all();
296 unthrottled
297 } else {
298 false
299 };
300 if unthrottled {
301 self.shared.notify_prefetch_waiters();
302 }
303 }
304 }
305 }
306 }
307 } else {
308 let r_idx = idx - video_count;
309 let job = &raster_jobs[r_idx];
310 let cache_gen_opt = self.shared.state.lock().ok().and_then(|mut state| {
311 if state.images.contains_key(&job.cache_key)
312 || state.in_flight.contains(&job.cache_key)
313 {
314 None
315 } else {
316 state.in_flight.insert(job.cache_key.clone());
317 self.shared.sync_lookahead_throttle(&state);
318 Some(state.generation)
319 }
320 });
321 let Some(cache_gen) = cache_gen_opt else { continue };
322 let mut guard = InFlightGuard {
323 shared: &self.shared,
324 key: Some(job.cache_key.clone()),
325 };
326 let decoded = decode_job(job, false);
327 finish_raster_job(
328 &self.shared,
329 job.cache_key.clone(),
330 cache_gen,
331 &mut guard,
332 decoded,
333 false,
334 );
335 }
336 });
337 }
338 });
339 }
340}
341
342#[cfg(not(target_arch = "wasm32"))]
343fn finish_raster_job(
344 shared: &MediaShared,
345 key: ImageCacheKey,
346 cache_gen: u64,
347 guard: &mut InFlightGuard<'_>,
348 decoded: Option<DecodedImage>,
349 is_speculative: bool,
350) {
351 let unthrottled = if let Ok(mut state) = shared.state.lock() {
352 state.in_flight.remove(&key);
353 guard.key = None;
354 let unthrottled = if let Some(decoded) = decoded {
355 if state.generation == cache_gen {
356 state.record_existing_path(&key.path);
357 if is_speculative {
358 state.record_speculative_decode(decoded.byte_size());
359 }
360 shared.insert_cached_locked(&mut state, key, decoded)
361 } else {
362 shared.sync_lookahead_throttle(&state)
363 }
364 } else {
365 state.evict_existing_path(&key.path);
366 shared.sync_lookahead_throttle(&state)
367 };
368 shared.cv.notify_all();
369 unthrottled
370 } else {
371 false
372 };
373 if unthrottled {
374 shared.notify_prefetch_waiters();
375 }
376}
377
378#[cfg(not(target_arch = "wasm32"))]
379pub(super) struct PrefetchQueueState {
380 pub(super) raster: VecDeque<(usize, PreloadJob)>,
381 videos: HashMap<PathBuf, VecDeque<(usize, VideoFrameRequest)>>,
382 active_videos: HashSet<PathBuf>,
383 pub(super) queued_raster_keys: HashSet<ImageCacheKey>,
384 current_seq: usize,
385 lookahead: usize,
386 cancelled: bool,
387}
388
389#[cfg(not(target_arch = "wasm32"))]
390impl PrefetchQueueState {
391 fn prune_stale(&mut self) {
392 let cur = self.current_seq;
393 if self.raster.iter().any(|&(seq, _)| seq < cur) {
394 let mut kept = VecDeque::with_capacity(self.raster.len());
395 while let Some((seq, job)) = self.raster.pop_front() {
396 if seq >= cur {
397 kept.push_back((seq, job));
398 } else {
399 self.queued_raster_keys.remove(&job.cache_key);
400 }
401 }
402 self.raster = kept;
403 }
404 self.videos.retain(|_, vq| {
405 vq.retain(|&(seq, _)| seq >= cur);
406 !vq.is_empty()
407 });
408 }
409}
410
411#[cfg(not(target_arch = "wasm32"))]
412pub(super) struct PrefetchQueue {
413 pub(super) state: Mutex<PrefetchQueueState>,
414 cv: Condvar,
415}
416
417#[cfg(not(target_arch = "wasm32"))]
418enum PrefetchWorkItem {
419 Raster(usize, usize, PreloadJob),
420 Video(usize, usize, PathBuf, VideoFrameRequest),
421}
422
423/// Cancellable background read-ahead handle returned by [`MediaCache::start_frame_prefetch`].
424///
425/// Continuously pre-decodes upcoming frames into [`MediaCache`] while the GPU renders the
426/// current frame, and cancels and joins all worker threads cleanly on drop.
427#[cfg(not(target_arch = "wasm32"))]
428pub struct MediaPrefetchHandle {
429 shared: Arc<MediaShared>,
430 pub(super) queue: Arc<PrefetchQueue>,
431 pub(super) workers: Vec<std::thread::JoinHandle<()>>,
432}
433
434#[cfg(not(target_arch = "wasm32"))]
435impl MediaPrefetchHandle {
436 fn spawn(shared: Arc<MediaShared>, lookahead: usize) -> Self {
437 let queue = Arc::new(PrefetchQueue {
438 state: Mutex::new(PrefetchQueueState {
439 raster: VecDeque::new(),
440 videos: HashMap::new(),
441 active_videos: HashSet::new(),
442 queued_raster_keys: HashSet::new(),
443 current_seq: 0,
444 lookahead,
445 cancelled: false,
446 }),
447 cv: Condvar::new(),
448 });
449 shared.register_prefetch_queue(&queue);
450 let worker_count = std::thread::available_parallelism()
451 .map(|n| n.get().clamp(2, 12))
452 .unwrap_or(4);
453 let mut workers = Vec::with_capacity(worker_count);
454 for _ in 0..worker_count {
455 let s = Arc::clone(&shared);
456 let q = Arc::clone(&queue);
457 workers.push(std::thread::spawn(move || {
458 Self::worker_loop(s, q);
459 }));
460 }
461 Self {
462 shared,
463 queue,
464 workers,
465 }
466 }
467
468 /// Updates the active render sequence index so read-ahead stays synchronized with playback/export.
469 pub fn set_current_seq(&self, seq_idx: usize) {
470 if let Ok(mut state) = self.shared.state.lock() {
471 state.reset_speculative_window(seq_idx);
472 self.shared.sync_lookahead_throttle(&state);
473 }
474 if let Ok(mut q) = self.queue.state.lock() {
475 q.current_seq = seq_idx;
476 q.prune_stale();
477 self.queue.cv.notify_all();
478 }
479 }
480
481 /// Enqueues missing `Loader` decodes for `time` at sequence index `seq_idx`.
482 pub fn enqueue_frame(
483 &self,
484 comp: &Comp,
485 target: NodeId,
486 seq_idx: usize,
487 time: f64,
488 expr: &model::ExprEngine,
489 use_proxy_clips: bool,
490 ) {
491 let mut visited = HashSet::new();
492 let mut jobs = MissingJobs::default();
493 collect_missing_loader_jobs_shared(
494 &self.shared,
495 comp,
496 target,
497 time,
498 expr,
499 use_proxy_clips,
500 &mut visited,
501 &mut jobs,
502 );
503 if jobs.total_units() == 0 {
504 return;
505 }
506 if let Ok(mut q) = self.queue.state.lock() {
507 if q.cancelled || seq_idx < q.current_seq {
508 return;
509 }
510 for job in jobs.raster {
511 if q.queued_raster_keys.insert(job.cache_key.clone()) {
512 q.raster.push_back((seq_idx, job));
513 }
514 }
515 for (path, reqs) in jobs.videos {
516 let vq = q.videos.entry(path).or_default();
517 for req in reqs {
518 if let Some((existing_seq, _)) = vq.iter_mut().find(|(_, existing)| {
519 existing.post_multiply == req.post_multiply
520 && match (existing.resolved_frame_idx, req.resolved_frame_idx) {
521 (Some(a), Some(b)) => a == b,
522 _ => {
523 existing.frame_i == req.frame_i
524 && existing.clip.global_start == req.clip.global_start
525 && existing.clip.trim_in == req.clip.trim_in
526 && existing.clip.trim_out == req.clip.trim_out
527 && existing.clip.reverse == req.clip.reverse
528 && existing.clip.loop_clip == req.clip.loop_clip
529 }
530 }
531 }) {
532 *existing_seq = (*existing_seq).min(seq_idx);
533 } else {
534 vq.push_back((seq_idx, req));
535 }
536 }
537 }
538 self.queue.cv.notify_all();
539 }
540 }
541
542 /// Cancels pending read-ahead work and joins all background worker threads.
543 pub fn cancel(&mut self) {
544 if let Ok(mut q) = self.queue.state.lock() {
545 q.cancelled = true;
546 q.raster.clear();
547 q.videos.clear();
548 q.queued_raster_keys.clear();
549 self.queue.cv.notify_all();
550 }
551 for handle in self.workers.drain(..) {
552 let _ = handle.join();
553 }
554 }
555
556 fn worker_loop(shared: Arc<MediaShared>, queue: Arc<PrefetchQueue>) {
557 loop {
558 let item = {
559 let Ok(mut q) = queue.state.lock() else { return };
560 loop {
561 if q.cancelled {
562 return;
563 }
564 let best_raster = q
565 .raster
566 .iter()
567 .enumerate()
568 .min_by_key(|&(_, (seq, _))| *seq)
569 .map(|(idx, (seq, _))| (idx, *seq));
570 let mut best_video: Option<(&PathBuf, usize, usize)> = None;
571 for (path, vq) in &q.videos {
572 if q.active_videos.contains(path) {
573 continue;
574 }
575 if let Some((v_idx, &(seq, _))) =
576 vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq)
577 {
578 if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) {
579 best_video = Some((path, v_idx, seq));
580 }
581 }
582 }
583
584 let chosen_seq = match (best_raster, &best_video) {
585 (Some((_, rs)), Some((_, _, vs))) => rs.min(*vs),
586 (Some((_, rs)), None) => rs,
587 (None, Some((_, _, vs))) => *vs,
588 (None, None) => {
589 q = match queue.cv.wait(q) {
590 Ok(g) => g,
591 Err(_) => return,
592 };
593 continue;
594 }
595 };
596
597 if chosen_seq > q.current_seq.saturating_add(q.lookahead) {
598 q = match queue.cv.wait(q) {
599 Ok(g) => g,
600 Err(_) => return,
601 };
602 continue;
603 }
604
605 if chosen_seq > q.current_seq.saturating_add(1)
606 && shared.lookahead_throttled.load(Ordering::Acquire)
607 {
608 q = match queue.cv.wait(q) {
609 Ok(g) => g,
610 Err(_) => return,
611 };
612 continue;
613 }
614
615 let cur_seq = q.current_seq;
616 let chosen_video = best_video
617 .filter(|&(_, _, vs)| best_raster.is_none_or(|(_, rs)| vs <= rs))
618 .map(|(path, v_idx, _)| (path.clone(), v_idx));
619
620 if let Some((path, v_idx)) = chosen_video {
621 if let Some((seq, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) {
622 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
623 q.videos.remove(&path);
624 }
625 q.active_videos.insert(path.clone());
626 break PrefetchWorkItem::Video(seq, cur_seq, path, req);
627 }
628 }
629 if let Some((r_idx, _)) = best_raster {
630 if let Some((seq, job)) = q.raster.remove(r_idx) {
631 q.queued_raster_keys.remove(&job.cache_key);
632 break PrefetchWorkItem::Raster(seq, cur_seq, job);
633 }
634 }
635 }
636 };
637
638 match item {
639 PrefetchWorkItem::Raster(item_seq, cur_seq, job) => {
640 let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| {
641 if state.images.contains_key(&job.cache_key)
642 || state.in_flight.contains(&job.cache_key)
643 {
644 None
645 } else {
646 state.in_flight.insert(job.cache_key.clone());
647 shared.sync_lookahead_throttle(&state);
648 Some(state.generation)
649 }
650 });
651 let Some(cache_gen) = cache_gen_opt else { continue };
652 let mut guard = InFlightGuard {
653 shared: &shared,
654 key: Some(job.cache_key.clone()),
655 };
656 let decoded = decode_job(&job, false);
657 finish_raster_job(
658 &shared,
659 job.cache_key,
660 cache_gen,
661 &mut guard,
662 decoded,
663 item_seq > cur_seq,
664 );
665 }
666 PrefetchWorkItem::Video(item_seq, cur_seq, path, req) => {
667 struct ActiveVideoGuard<'a> {
668 queue: &'a PrefetchQueue,
669 path: PathBuf,
670 }
671 impl Drop for ActiveVideoGuard<'_> {
672 fn drop(&mut self) {
673 if let Ok(mut q) = self.queue.state.lock() {
674 q.active_videos.remove(&self.path);
675 self.queue.cv.notify_all();
676 }
677 }
678 }
679 let _active_guard = ActiveVideoGuard {
680 queue: &queue,
681 path: path.clone(),
682 };
683
684 let Some((info, dec_arc)) = shared.get_or_open_video_decoder(&path) else {
685 continue;
686 };
687 let frame_idx =
688 compute_video_frame_idx(&req.clip, req.frame_i, info.nb_frames);
689 let key = ImageCacheKey {
690 path: path.clone(),
691 frame_idx,
692 post_multiply: req.post_multiply,
693 exr_channels: [None, None, None, None],
694 };
695 let cache_gen_opt = shared.state.lock().ok().and_then(|mut state| {
696 if state.images.contains_key(&key) || state.in_flight.contains(&key) {
697 None
698 } else {
699 state.in_flight.insert(key.clone());
700 shared.sync_lookahead_throttle(&state);
701 Some(state.generation)
702 }
703 });
704 let Some(cache_gen) = cache_gen_opt else { continue };
705 let mut guard = InFlightGuard {
706 shared: &shared,
707 key: Some(key.clone()),
708 };
709 let decoded_raw = dec_arc
710 .lock()
711 .ok()
712 .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx));
713 if let Some(mut raw) = decoded_raw {
714 if req.post_multiply {
715 apply_post_multiply_rgba8_parallel(&mut raw, false);
716 }
717 let decoded = DecodedImage {
718 size: [info.width, info.height],
719 rgba: Arc::new(raw),
720 rgba_f16: None,
721 rgba_f32: None,
722 };
723 let unthrottled = if let Ok(mut state) = shared.state.lock() {
724 state.in_flight.remove(&key);
725 guard.key = None;
726 let unthrottled = if state.generation == cache_gen {
727 if item_seq > cur_seq {
728 state.record_speculative_decode(decoded.byte_size());
729 }
730 shared.insert_cached_locked(&mut state, key, decoded)
731 } else {
732 shared.sync_lookahead_throttle(&state)
733 };
734 shared.cv.notify_all();
735 unthrottled
736 } else {
737 false
738 };
739 if unthrottled {
740 shared.notify_prefetch_waiters();
741 }
742 }
743 }
744 }
745 }
746 }
747}
748
749#[cfg(not(target_arch = "wasm32"))]
750impl Drop for MediaPrefetchHandle {
751 fn drop(&mut self) {
752 self.cancel();
753 }
754}
755
756#[cfg(not(target_arch = "wasm32"))]
757#[allow(clippy::too_many_arguments)]
758fn collect_missing_loader_jobs_shared(
759 shared: &MediaShared,
760 comp: &Comp,
761 node_id: NodeId,
762 time: f64,
763 expr: &model::ExprEngine,
764 use_proxy_clips: bool,
765 visited: &mut HashSet<(NodeId, i64)>,
766 jobs: &mut MissingJobs,
767) {
768 const MAX_PRELOAD_DEPTH: usize = 256;
769 if node_id.0 >= comp.nodes.len() || jobs.depth >= MAX_PRELOAD_DEPTH {
770 return;
771 }
772 let time_key = (if time == 0.0 { 0.0 } else { time }).to_bits() as i64;
773 if !visited.insert((node_id, time_key)) {
774 return;
775 }
776 jobs.depth += 1;
777 collect_missing_loader_jobs_inner(
778 shared,
779 comp,
780 node_id,
781 time,
782 expr,
783 use_proxy_clips,
784 visited,
785 jobs,
786 );
787 jobs.depth -= 1;
788}
789
790#[cfg(not(target_arch = "wasm32"))]
791#[allow(clippy::too_many_arguments)]
792fn collect_missing_loader_jobs_inner(
793 shared: &MediaShared,
794 comp: &Comp,
795 node_id: NodeId,
796 time: f64,
797 expr: &model::ExprEngine,
798 use_proxy_clips: bool,
799 visited: &mut HashSet<(NodeId, i64)>,
800 jobs: &mut MissingJobs,
801) {
802 let node = comp.node(node_id);
803
804 if node.bypassed
805 || matches!(
806 node.kind.as_str(),
807 "Saver"
808 | "PipeRouter"
809 | "Fuse.Wireless"
810 | "Tracker"
811 | "Dimension.OpticalFlow"
812 | "OpticalFlow"
813 | "Dimension.CopyAux"
814 )
815 {
816 let port = default_main_input_port(&node.kind);
817 if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) {
818 collect_missing_loader_jobs_shared(
819 shared,
820 comp,
821 src_id,
822 time,
823 expr,
824 use_proxy_clips,
825 visited,
826 jobs,
827 );
828 }
829 return;
830 }
831
832 if matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") {
833 let next_id = node.macro_output.or_else(|| {
834 node.connected_node("Input")
835 .or_else(|| node.connected_node("MainInput1"))
836 .and_then(|s| comp.find_node(s))
837 });
838 if let Some(src_id) = next_id {
839 collect_missing_loader_jobs_shared(
840 shared,
841 comp,
842 src_id,
843 time,
844 expr,
845 use_proxy_clips,
846 visited,
847 jobs,
848 );
849 }
850 return;
851 }
852
853 if matches!(node.kind.as_str(), "TimeStretcher" | "TimeSpeed") {
854 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
855 return;
856 };
857 let remapped = match node.kind.as_str() {
858 "TimeStretcher" => comp.eval_number(node, "SourceTime", time, 0.0, expr),
859 "TimeSpeed" => {
860 let speed = comp.eval_number(node, "Speed", time, 1.0, expr);
861 let delay = comp.eval_number(node, "Delay", time, 0.0, expr);
862 let g_start = comp.global_range[0] as f64;
863 let g_end = comp.global_range[1] as f64;
864 if speed < 0.0 {
865 ((g_end + 1.0) + (time - delay - g_start) * speed).min(g_end)
866 } else {
867 g_start + (time - delay - g_start) * speed
868 }
869 }
870 _ => time,
871 };
872 let interp = comp
873 .eval_number(node, "InterpolateBetweenFrames", time, 1.0, expr)
874 .round() as i32;
875 if interp <= 0 {
876 let snapped = (remapped + 0.5).floor();
877 collect_missing_loader_jobs_shared(
878 shared,
879 comp,
880 src_id,
881 snapped,
882 expr,
883 use_proxy_clips,
884 visited,
885 jobs,
886 );
887 return;
888 }
889 let f0 = remapped.floor();
890 let frac = (remapped - f0) as f32;
891 if frac > 1e-3 && frac < 1.0 - 1e-3 {
892 let src_node = comp.node(src_id);
893 let has_optflow = matches!(src_node.kind.as_str(), "Dimension.OpticalFlow" | "OpticalFlow");
894 let eval_src_id = if has_optflow {
895 src_node
896 .connected_node("Input")
897 .and_then(|s| comp.find_node(s))
898 .unwrap_or(src_id)
899 } else {
900 src_id
901 };
902 collect_missing_loader_jobs_shared(
903 shared,
904 comp,
905 eval_src_id,
906 f0,
907 expr,
908 use_proxy_clips,
909 visited,
910 jobs,
911 );
912 collect_missing_loader_jobs_shared(
913 shared,
914 comp,
915 eval_src_id,
916 f0 + 1.0,
917 expr,
918 use_proxy_clips,
919 visited,
920 jobs,
921 );
922 } else {
923 collect_missing_loader_jobs_shared(
924 shared,
925 comp,
926 src_id,
927 remapped,
928 expr,
929 use_proxy_clips,
930 visited,
931 jobs,
932 );
933 }
934 return;
935 }
936
937 if node.kind == "Switch" || node.kind == "Fuse.Switch" {
938 let is_native_zero_indexed = node.kind == "Switch"
939 && (node.inputs.contains_key("Source")
940 || node.inputs.contains_key("Input0")
941 || !node.inputs.contains_key("Which"));
942 let src_name = if is_native_zero_indexed {
943 let source = comp
944 .eval_number(node, "Source", time, 0.0, expr)
945 .round()
946 .max(0.0) as usize;
947 let port = format!("Input{source}");
948 node.connected_node(&port)
949 .or_else(|| node.connected_node("Input0"))
950 } else {
951 let which = comp
952 .eval_number(node, "Which", time, 1.0, expr)
953 .round()
954 .max(1.0) as usize;
955 let port = format!("Input{which}");
956 node.connected_node(&port)
957 .or_else(|| node.connected_node("Input1"))
958 };
959 if let Some(src_id) = src_name.and_then(|s| comp.find_node(s)) {
960 collect_missing_loader_jobs_shared(
961 shared,
962 comp,
963 src_id,
964 time,
965 expr,
966 use_proxy_clips,
967 visited,
968 jobs,
969 );
970 }
971 return;
972 }
973
974 if node.kind == "Fuse.SwitchElse" {
975 let index = |name: &str, default: f64| {
976 comp.eval_number(node, name, time, default, expr)
977 .round()
978 .max(1.0) as usize
979 };
980 let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| {
981 node.connected_node(&format!("Input{i}"))
982 .and_then(|s| comp.find_node(s))
983 });
984 if let Some(src_id) = picked {
985 collect_missing_loader_jobs_shared(
986 shared,
987 comp,
988 src_id,
989 time,
990 expr,
991 use_proxy_clips,
992 visited,
993 jobs,
994 );
995 }
996 return;
997 }
998
999 if node.kind == "Merge" {
1000 if let Some(bg_id) = node.connected_node("Background").and_then(|s| comp.find_node(s)) {
1001 collect_missing_loader_jobs_shared(
1002 shared,
1003 comp,
1004 bg_id,
1005 time,
1006 expr,
1007 use_proxy_clips,
1008 visited,
1009 jobs,
1010 );
1011 }
1012 let blend = comp.eval_number(node, "Blend", time, 1.0, expr) as f32;
1013 let mbm = comp.eval_number(node, "MultiplyByMask", time, 0.0, expr) > 0.5;
1014 let mask_id = resolve_effect_mask_id_for_node(comp, node);
1015 if !(blend <= 1e-6 && !(mbm && node.connected_node("EffectMask").is_some())) {
1016 if let Some(fg_id) = node.connected_node("Foreground").and_then(|s| comp.find_node(s)) {
1017 collect_missing_loader_jobs_shared(
1018 shared,
1019 comp,
1020 fg_id,
1021 time,
1022 expr,
1023 use_proxy_clips,
1024 visited,
1025 jobs,
1026 );
1027 }
1028 }
1029 if let Some(mid) = mask_id {
1030 collect_missing_loader_jobs_shared(
1031 shared,
1032 comp,
1033 mid,
1034 time,
1035 expr,
1036 use_proxy_clips,
1037 visited,
1038 jobs,
1039 );
1040 }
1041 return;
1042 }
1043
1044 if node.kind == "Loader" {
1045 if let Some(clip) = node.clips.first() {
1046 let frame_i = time.round() as i64;
1047 let post_mult = node.static_number("Clip1.PNGFormat.PostMultiply").unwrap_or(0.0) > 0.5;
1048 let exr_channels = [
1049 node.static_str("Clip1.OpenEXRFormat.RedName"),
1050 node.static_str("Clip1.OpenEXRFormat.GreenName"),
1051 node.static_str("Clip1.OpenEXRFormat.BlueName"),
1052 node.static_str("Clip1.OpenEXRFormat.AlphaName"),
1053 ];
1054 let mut effective_clip = clip.clone();
1055 if node.inputs.contains_key("GlobalIn") {
1056 effective_clip.global_start = comp
1057 .eval_number(node, "GlobalIn", time, effective_clip.global_start as f64, expr)
1058 .round() as i64;
1059 }
1060 if node.inputs.contains_key("GlobalOut") {
1061 effective_clip.global_end = comp
1062 .eval_number(node, "GlobalOut", time, effective_clip.global_end as f64, expr)
1063 .round() as i64;
1064 }
1065 if node.inputs.contains_key("Loop") {
1066 effective_clip.loop_clip = comp.eval_number(
1067 node,
1068 "Loop",
1069 time,
1070 if effective_clip.loop_clip { 1.0 } else { 0.0 },
1071 expr,
1072 ) > 0.5;
1073 }
1074 if node.inputs.contains_key("Reverse") {
1075 effective_clip.reverse = comp.eval_number(
1076 node,
1077 "Reverse",
1078 time,
1079 if effective_clip.reverse { 1.0 } else { 0.0 },
1080 expr,
1081 ) > 0.5;
1082 }
1083 if use_proxy_clips {
1084 let proxy_candidate = node
1085 .static_str("ProxyFilename")
1086 .filter(|s| !s.trim().is_empty())
1087 .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty()));
1088 if let Some(proxy_name) = proxy_candidate {
1089 let mut proxy_clip = effective_clip.clone();
1090 proxy_clip.filename = proxy_name.to_owned();
1091 if shared.resolve_clip_path_cached(&proxy_clip, frame_i).is_some() {
1092 effective_clip = proxy_clip;
1093 }
1094 }
1095 }
1096 let out_of_range = effective_clip.global_end >= effective_clip.global_start
1097 && (frame_i < effective_clip.global_start.saturating_sub(effective_clip.extend_first.max(0))
1098 || (!effective_clip.loop_clip
1099 && frame_i > effective_clip.global_end.saturating_add(effective_clip.extend_last.max(0))));
1100 if !out_of_range {
1101 let base = Path::new(&effective_clip.filename);
1102 if is_video_path(base) {
1103 if video_frame_in_range(&effective_clip, frame_i)
1104 && shared.path_exists_cached(base)
1105 {
1106 let mut resolved_frame_idx = effective_clip
1107 .length
1108 .map(|_| compute_video_frame_idx(&effective_clip, frame_i, 1));
1109 let need_decode = shared.state.lock().is_ok_and(|state| {
1110 match state.video_decoders.get(base) {
1111 Some(slot) => {
1112 let idx = compute_video_frame_idx(
1113 &effective_clip,
1114 frame_i,
1115 slot.info.nb_frames,
1116 );
1117 resolved_frame_idx = Some(idx);
1118 let cache_key = ImageCacheKey {
1119 path: base.to_path_buf(),
1120 frame_idx: idx,
1121 post_multiply: post_mult,
1122 exr_channels: [None, None, None, None],
1123 };
1124 !state.images.contains_key(&cache_key)
1125 && !state.in_flight.contains(&cache_key)
1126 }
1127 None => true,
1128 }
1129 });
1130 if need_decode {
1131 jobs.videos
1132 .entry(base.to_path_buf())
1133 .or_default()
1134 .push(VideoFrameRequest {
1135 clip: effective_clip,
1136 frame_i,
1137 post_multiply: post_mult,
1138 resolved_frame_idx,
1139 });
1140 }
1141 }
1142 } else if let Some(resolved) = resolve_clip_candidate_path(&effective_clip, frame_i) {
1143 let is_exr = is_exr_path(&resolved);
1144 let key_channels = if is_exr {
1145 [
1146 normalize_channel_opt(exr_channels[0]),
1147 normalize_channel_opt(exr_channels[1]),
1148 normalize_channel_opt(exr_channels[2]),
1149 normalize_channel_opt(exr_channels[3]),
1150 ]
1151 } else {
1152 [None, None, None, None]
1153 };
1154 let cache_key = ImageCacheKey {
1155 path: resolved.clone(),
1156 frame_idx: -1,
1157 post_multiply: post_mult && !is_exr,
1158 exr_channels: key_channels,
1159 };
1160 let missing = shared.state.lock().is_ok_and(|state| {
1161 !state.images.contains_key(&cache_key)
1162 && !state.in_flight.contains(&cache_key)
1163 });
1164 if missing
1165 && !jobs.seen_raster.contains(&cache_key)
1166 && shared.path_exists_cached(&resolved)
1167 {
1168 jobs.seen_raster.insert(cache_key.clone());
1169 jobs.raster.push(PreloadJob { cache_key, is_exr });
1170 }
1171 }
1172 }
1173 }
1174 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {
1175 collect_missing_loader_jobs_shared(
1176 shared,
1177 comp,
1178 mid,
1179 time,
1180 expr,
1181 use_proxy_clips,
1182 visited,
1183 jobs,
1184 );
1185 }
1186 return;
1187 }
1188
1189 // General node: traverse all wired upstream node inputs and inherited EffectMask.
1190 let mut child_ids = Vec::new();
1191 for binding in node.inputs.values() {
1192 if let Some(src) = binding.source_op.as_deref() {
1193 if let Some(cid) = comp.find_node(src) {
1194 if !child_ids.contains(&cid) {
1195 child_ids.push(cid);
1196 }
1197 }
1198 }
1199 }
1200 if let Some(mid) = resolve_effect_mask_id_for_node(comp, node) {
1201 if !child_ids.contains(&mid) {
1202 child_ids.push(mid);
1203 }
1204 }
1205 for cid in child_ids {
1206 collect_missing_loader_jobs_shared(
1207 shared,
1208 comp,
1209 cid,
1210 time,
1211 expr,
1212 use_proxy_clips,
1213 visited,
1214 jobs,
1215 );
1216 }
1217}
1218
1219#[cfg(not(target_arch = "wasm32"))]
1220#[derive(Default)]
1221struct MissingJobs {
1222 raster: Vec<PreloadJob>,
1223 seen_raster: HashSet<ImageCacheKey>,
1224 videos: HashMap<PathBuf, Vec<VideoFrameRequest>>,
1225 depth: usize,
1226}
1227
1228#[cfg(not(target_arch = "wasm32"))]
1229impl MissingJobs {
1230 fn total_units(&self) -> usize {
1231 self.raster.len() + self.videos.len()
1232 }
1233}
1234
1235#[cfg(not(target_arch = "wasm32"))]
1236struct VideoFrameRequest {
1237 clip: ClipSpec,
1238 frame_i: i64,
1239 post_multiply: bool,
1240 resolved_frame_idx: Option<i64>,
1241}
1242
1243#[cfg(not(target_arch = "wasm32"))]
1244struct VideoDecodeTask {
1245 path: PathBuf,
1246 requests: Vec<VideoFrameRequest>,
1247}
1248
1249#[cfg(not(target_arch = "wasm32"))]
1250pub(super) struct PreloadJob {
1251 cache_key: ImageCacheKey,
1252 is_exr: bool,
1253}
1254
1255#[cfg(not(target_arch = "wasm32"))]
1256fn decode_job(job: &PreloadJob, allow_parallel: bool) -> Option<DecodedImage> {
1257 if job.is_exr {
1258 decode_exr_rgba(
1259 &job.cache_key.path,
1260 job.cache_key.exr_channels[0].as_deref(),
1261 job.cache_key.exr_channels[1].as_deref(),
1262 job.cache_key.exr_channels[2].as_deref(),
1263 job.cache_key.exr_channels[3].as_deref(),
1264 false,
1265 allow_parallel,
1266 )
1267 } else {
1268 decode_raster_image(
1269 &job.cache_key.path,
1270 job.cache_key.post_multiply,
1271 allow_parallel,
1272 )
1273 }
1274}
1275
1276#[cfg(not(target_arch = "wasm32"))]
1277fn resolve_effect_mask_id_for_node(comp: &Comp, node: &Node) -> Option<NodeId> {
1278 if let Some(id) = node.connected_node("EffectMask").and_then(|s| comp.find_node(s)) {
1279 return Some(id);
1280 }
1281 let has_explicit_mask_entry = |n: &Node| -> bool {
1282 n.raw
1283 .get_table("Inputs")
1284 .and_then(|t| t.get("EffectMask"))
1285 .is_some()
1286 };
1287 if has_explicit_mask_entry(node) {
1288 return None;
1289 }
1290 let mut visited = HashSet::new();
1291 visited.insert(node.id);
1292 let mut cur = node;
1293 for _ in 0..8 {
1294 let master_name = cur.raw.get_str("SourceOp")?;
1295 let mid = comp.find_node(master_name)?;
1296 if !visited.insert(mid) {
1297 break;
1298 }
1299 let master = comp.node(mid);
1300 if let Some(mask_id) = master.connected_node("EffectMask").and_then(|s| comp.find_node(s)) {
1301 return Some(mask_id);
1302 }
1303 if has_explicit_mask_entry(master) {
1304 return None;
1305 }
1306 cur = master;
1307 }
1308 None
1309}
crates/engine/src/media/tests.rs created+1452
......@@ -0,0 +1,1452 @@
1use ::png;
2use super::*;
3use std::time::Instant;
4
5#[test]
6fn decoded_image_cache_separates_post_multiply() {
7 let dir = std::env::temp_dir().join("fission_media_post_multiply_key_test");
8 std::fs::create_dir_all(&dir).unwrap();
9 let png = dir.join("half.png");
10 image::RgbaImage::from_pixel(2, 2, image::Rgba([200, 100, 50, 128])).save(&png).unwrap();
11 let clip = ClipSpec {
12 filename: png.to_string_lossy().into_owned(),
13 alternate_filename: None,
14 start_frame: 0,
15 length: Some(1),
16 trim_in: 0,
17 trim_out: 0,
18 global_start: 0,
19 global_end: 0,
20 extend_first: 0,
21 extend_last: 0,
22 loop_clip: false,
23 reverse: false,
24 };
25 let mut cache = MediaCache::new(64);
26 let mut first_px = |post_multiply| {
27 let (_, _, img, from_disk) = cache.load_clip(&clip, 0, post_multiply, [None; 4]).unwrap();
28 (img.rgba[..4].to_vec(), from_disk)
29 };
30 assert_eq!(first_px(false), (vec![200, 100, 50, 128], true));
31 assert_eq!(first_px(true), (vec![100, 50, 25, 128], true));
32 assert_eq!(first_px(false), (vec![200, 100, 50, 128], false));
33 assert_eq!(first_px(true), (vec![100, 50, 25, 128], false));
34 assert_eq!(cache.entry_count(), 2);
35 let _ = std::fs::remove_dir_all(&dir);
36}
37
38fn mean_abs_error_rgb(a: &[u8], b: &[u8]) -> f64 {
39 assert_eq!(a.len(), b.len());
40 let mut sum = 0u64;
41 let mut count = 0u64;
42 for (pa, pb) in a.chunks_exact(4).zip(b.chunks_exact(4)) {
43 sum += pa[0].abs_diff(pb[0]) as u64;
44 sum += pa[1].abs_diff(pb[1]) as u64;
45 sum += pa[2].abs_diff(pb[2]) as u64;
46 count += 3;
47 }
48 if count == 0 {
49 0.0
50 } else {
51 sum as f64 / count as f64
52 }
53}
54
55fn verify_clip_matches_ffmpeg(path: &Path) {
56 let mut dec = open_video_decoder(path).expect("open_video_decoder failed");
57 let mut ff = FfmpegDecoder::open(path).expect("FfmpegDecoder::open failed");
58
59 #[cfg(target_os = "macos")]
60 assert_eq!(
61 dec.backend_name(),
62 "AVFoundation/VideoToolbox",
63 "expected AVFoundation backend for {}",
64 path.display()
65 );
66
67 let av_info = dec.info();
68 let ff_info = ff.info();
69 assert_eq!(av_info.width, ff_info.width, "width mismatch for {}", path.display());
70 assert_eq!(av_info.height, ff_info.height, "height mismatch for {}", path.display());
71 assert!(
72 (av_info.fps - ff_info.fps).abs() < 0.2,
73 "fps mismatch for {}: av={} ff={}",
74 path.display(),
75 av_info.fps,
76 ff_info.fps
77 );
78
79 let frames = [0_i64, 1, 2, 10, 0];
80 let mut total_ms = 0.0;
81 for &f in &frames {
82 let t0 = Instant::now();
83 let av_px = dec
84 .decode_frame(f)
85 .unwrap_or_else(|| panic!("av decode frame {f} failed for {}", path.display()));
86 let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
87 total_ms += elapsed_ms;
88
89 let ff_px = ff
90 .decode_frame(f)
91 .unwrap_or_else(|| panic!("ffmpeg decode frame {f} failed for {}", path.display()));
92 let mae = mean_abs_error_rgb(&av_px, &ff_px);
93 eprintln!(
94 "[video-test] {} ({}x{} @{:.2}fps) frame {}: {:.2} ms, MAE vs ffmpeg = {:.2}",
95 path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"),
96 av_info.width,
97 av_info.height,
98 av_info.fps,
99 f,
100 elapsed_ms,
101 mae
102 );
103 // Allow small YUV->RGB matrix/rounding differences between VideoToolbox and swscale.
104 assert!(
105 mae < 12.0,
106 "high MAE ({mae:.2}) on {} frame {f} (possible orientation or PTS mismatch)",
107 path.display()
108 );
109 }
110 eprintln!(
111 "[video-test] {} avg decode: {:.2} ms/frame",
112 path.file_name().and_then(|s| s.to_str()).unwrap_or("clip"),
113 total_ms / frames.len() as f64
114 );
115}
116
117#[test]
118fn test_video_decoder_real_mov_clips() {
119 let clips = [
120 Path::new("/Volumes/Project/trees/EncodedMedia/A001_11071331_C002_4873-4988_d8716e17.mov"),
121 Path::new("/Volumes/Project/trees/EncodedMedia/IMG_1767_2395-2547_7efe6416.mov"),
122 ];
123 for clip in clips {
124 if clip.exists() {
125 verify_clip_matches_ffmpeg(clip);
126 }
127 }
128}
129
130#[test]
131fn test_video_decoder_synthetic_mp4() {
132 let tmp = std::env::temp_dir().join("engine_test_synth_video.mp4");
133 let status = Command::new("ffmpeg")
134 .args([
135 "-y",
136 "-v",
137 "error",
138 "-f",
139 "lavfi",
140 "-i",
141 "testsrc2=size=320x180:rate=24:duration=1.0",
142 "-c:v",
143 "libx264",
144 "-pix_fmt",
145 "yuv420p",
146 ])
147 .arg(&tmp)
148 .status();
149 if let Ok(st) = status {
150 if st.success() {
151 verify_clip_matches_ffmpeg(&tmp);
152 let _ = std::fs::remove_file(&tmp);
153 }
154 }
155}
156
157fn alpha_y_bounds(size: [u32; 2], origin: [i32; 2], rgba: &[u8]) -> (i32, i32) {
158 let [w, h] = size;
159 let mut min_y = i32::MAX;
160 let mut max_y = i32::MIN;
161 for y in 0..h as usize {
162 let row = y * w as usize * 4;
163 for x in 0..w as usize {
164 if rgba[row + x * 4 + 3] > 32 {
165 let cy = origin[1] + y as i32;
166 min_y = min_y.min(cy);
167 max_y = max_y.max(cy);
168 break;
169 }
170 }
171 }
172 (min_y, max_y)
173}
174
175#[test]
176fn test_text_plus_calibrated_metrics_and_anchoring() {
177 let base = |text: &str, v_tcb: f32, line_spacing: f32, dims: [u32; 2]| {
178 rasterize_text_plus(
179 dims,
180 &TextPlusParams {
181 text,
182 font_family: "Helvetica Neue",
183 font_style: "Regular",
184 size_norm: 0.08,
185 tracking: 1.0,
186 line_spacing,
187 center: [0.5, 0.5],
188 h_lcr: 0.0,
189 v_tcb,
190 fill_rgba: [1.0, 1.0, 1.0, 1.0],
191 write_on_start: 0.0,
192 write_on_end: 1.0,
193 shear_x: 0.0,
194 cls: &[],
195 outline_rgba: [0.0; 4],
196 outline_width_px: 0.0,
197 },
198 0,
199 )
200 };
201
202 // 1. VerticalTopCenterBottom: -1 anchors top below cy=270, 0 centers around cy=270,
203 // +1 anchors bottom baseline at cy=270 (so glyphs sit above cy=270).
204 let (s_top, o_top, p_top) = base("HHHH", -1.0, 1.0, [960, 540]);
205 let (s_ctr, o_ctr, p_ctr) = base("HHHH", 0.0, 1.0, [960, 540]);
206 let (s_bot, o_bot, p_bot) = base("HHHH", 1.0, 1.0, [960, 540]);
207 let (top_y0, top_y1) = alpha_y_bounds(s_top, o_top, &p_top);
208 let (ctr_y0, ctr_y1) = alpha_y_bounds(s_ctr, o_ctr, &p_ctr);
209 let (bot_y0, bot_y1) = alpha_y_bounds(s_bot, o_bot, &p_bot);
210 assert!(top_y0 >= 268 && top_y1 > 300, "top-aligned should sit below cy=270: ({top_y0}, {top_y1})");
211 assert!(ctr_y0 < 270 && ctr_y1 > 270, "center-aligned should straddle cy=270: ({ctr_y0}, {ctr_y1})");
212 assert!(bot_y0 < 240 && bot_y1 <= 272, "bottom-aligned should sit above cy=270: ({bot_y0}, {bot_y1})");
213
214 // 2. LineSpacing=1.5 widens a 2-line block by 0.5 * (0.8 * 0.08 * 960 = 61.44px) = ~30.7px.
215 let (s_ls1, o_ls1, p_ls1) = base("HHHH\nHHHH", 0.0, 1.0, [960, 540]);
216 let (s_ls15, o_ls15, p_ls15) = base("HHHH\nHHHH", 0.0, 1.5, [960, 540]);
217 let (ls1_y0, ls1_y1) = alpha_y_bounds(s_ls1, o_ls1, &p_ls1);
218 let (ls15_y0, ls15_y1) = alpha_y_bounds(s_ls15, o_ls15, &p_ls15);
219 let span_diff = (ls15_y1 - ls15_y0) - (ls1_y1 - ls1_y0);
220 assert!(
221 (28..=34).contains(&span_diff),
222 "LineSpacing 1.5 vs 1.0 on 960x540 Size=0.08 should add ~31px span, got {span_diff}"
223 );
224
225 // 3. Size scales with canvas width W, independent of height H.
226 let (s_wide, o_wide, p_wide) = base("HHHH", 0.0, 1.0, [960, 540]);
227 let (s_tall, o_tall, p_tall) = base("HHHH", 0.0, 1.0, [540, 960]);
228 let (wy0, wy1) = alpha_y_bounds(s_wide, o_wide, &p_wide);
229 let (ty0, ty1) = alpha_y_bounds(s_tall, o_tall, &p_tall);
230 let wide_h = (wy1 - wy0) as f32;
231 let tall_h = (ty1 - ty0) as f32;
232 let ratio = wide_h / tall_h;
233 assert!(
234 (ratio - (960.0 / 540.0)).abs() < 0.15,
235 "glyph pixel height should scale with W (expected ~1.78, got {ratio:.2}: {wide_h}/{tall_h})"
236 );
237}
238
239#[test]
240fn exr_channel_cache_isolation_and_non_beauty_guard() {
241 use ::exr::prelude::*;
242 let dir = std::env::temp_dir().join(format!("fission_exr_chan_test_{}", std::process::id()));
243 let _ = std::fs::remove_dir_all(&dir);
244 std::fs::create_dir_all(&dir).unwrap();
245
246 let multi_exr = dir.join("multi_aov.exr");
247 let w = 4usize;
248 let h = 4usize;
249 let n = w * h;
250 let mut channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
251 for (name, val) in [
252 ("ViewLayer.Combined.R", 0.9_f32),
253 ("ViewLayer.Combined.G", 0.2),
254 ("ViewLayer.Combined.B", 0.1),
255 ("ViewLayer.Combined.A", 1.0),
256 ("ViewLayer.Specular.R", 0.1),
257 ("ViewLayer.Specular.G", 0.8),
258 ("ViewLayer.Specular.B", 0.7),
259 ("ViewLayer.Specular.A", 1.0),
260 ("ViewLayer.CryptoObject00.R", 0.5),
261 ] {
262 channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n])));
263 }
264 Image::from_layer(Layer::new(
265 (w, h),
266 LayerAttributes::named("main"),
267 Encoding::FAST_LOSSLESS,
268 AnyChannels::sort(channels),
269 ))
270 .write()
271 .to_file(&multi_exr)
272 .expect("write multi-layer EXR");
273
274 let clip = ClipSpec {
275 filename: multi_exr.to_string_lossy().into_owned(),
276 alternate_filename: None,
277 start_frame: 0,
278 length: Some(1),
279 trim_in: 0,
280 trim_out: 0,
281 global_start: 0,
282 global_end: 0,
283 extend_first: 0,
284 extend_last: 0,
285 loop_clip: false,
286 reverse: false,
287 };
288 let mut cache = MediaCache::new(64);
289 let (_, _, beauty, beauty_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
290 assert!(beauty_disk);
291 let (_, _, spec, spec_disk) = cache
292 .load_clip(
293 &clip,
294 0,
295 false,
296 [
297 Some("Specular.R"),
298 Some("Specular.G"),
299 Some("Specular.B"),
300 Some("Specular.A"),
301 ],
302 )
303 .unwrap();
304 assert!(spec_disk);
305 assert_eq!(cache.entry_count(), 2);
306
307 let b_px = beauty.rgba_f32.as_ref().unwrap();
308 let s_px = spec.rgba_f32.as_ref().unwrap();
309 assert!((b_px[0] - 0.9).abs() < 1e-4 && (b_px[1] - 0.2).abs() < 1e-4);
310 assert!((s_px[0] - 0.1).abs() < 1e-4 && (s_px[1] - 0.8).abs() < 1e-4);
311
312 // Warm hits keep both AOVs isolated.
313 let (_, _, beauty_warm, beauty_disk2) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
314 assert!(!beauty_disk2);
315 assert!((beauty_warm.rgba_f32.as_ref().unwrap()[0] - 0.9).abs() < 1e-4);
316
317 // EXR containing ONLY CryptoObject00.R (no bare R or Combined.R) must NOT match beauty fallback.
318 let crypto_only_exr = dir.join("crypto_only.exr");
319 let mut crypto_channels = SmallVec::<[AnyChannel<FlatSamples>; 4]>::new();
320 for (name, val) in [
321 ("CryptoObject00.R", 0.42_f32),
322 ("CryptoObject00.G", 0.0),
323 ("CryptoObject00.B", 0.0),
324 ("CryptoObject00.A", 1.0),
325 ] {
326 crypto_channels.push(AnyChannel::new(name, FlatSamples::F32(vec![val; n])));
327 }
328 Image::from_layer(Layer::new(
329 (w, h),
330 LayerAttributes::named("crypto"),
331 Encoding::FAST_LOSSLESS,
332 AnyChannels::sort(crypto_channels),
333 ))
334 .write()
335 .to_file(&crypto_only_exr)
336 .expect("write crypto-only EXR");
337
338 let crypto_clip = ClipSpec {
339 filename: crypto_only_exr.to_string_lossy().into_owned(),
340 ..clip
341 };
342 assert!(cache.load_clip(&crypto_clip, 0, false, [None; 4]).is_none());
343 let (_, _, explicit, _) = cache
344 .load_clip(
345 &crypto_clip,
346 0,
347 false,
348 [
349 Some("CryptoObject00.R"),
350 Some("CryptoObject00.G"),
351 Some("CryptoObject00.B"),
352 Some("CryptoObject00.A"),
353 ],
354 )
355 .expect("explicit CryptoObject00 channel selection should succeed");
356 assert!((explicit.rgba_f32.as_ref().unwrap()[0] - 0.42).abs() < 1e-4);
357
358 let _ = std::fs::remove_dir_all(&dir);
359}
360
361#[test]
362fn video_decoder_clear_lru_cap_post_multiply_and_loop() {
363 let dir = std::env::temp_dir().join(format!("fission_media_video_lru_{}", std::process::id()));
364 let _ = std::fs::remove_dir_all(&dir);
365 std::fs::create_dir_all(&dir).unwrap();
366
367 let base_mp4 = dir.join("clip_00.mp4");
368 let ok = Command::new("ffmpeg")
369 .args([
370 "-y",
371 "-v",
372 "error",
373 "-f",
374 "lavfi",
375 "-i",
376 "color=c=red:size=32x32:rate=24:duration=0.25",
377 "-c:v",
378 "libx264",
379 "-pix_fmt",
380 "yuv420p",
381 ])
382 .arg(&base_mp4)
383 .status()
384 .is_ok_and(|s| s.success());
385 assert!(ok, "ffmpeg failed to create tiny mp4");
386
387 let mut cache = MediaCache::new(64);
388 for i in 0..15 {
389 let p = if i == 0 {
390 base_mp4.clone()
391 } else {
392 let dst = dir.join(format!("clip_{i:02}.mp4"));
393 std::fs::copy(&base_mp4, &dst).unwrap();
394 dst
395 };
396 let clip = ClipSpec {
397 filename: p.to_string_lossy().into_owned(),
398 alternate_filename: None,
399 start_frame: 0,
400 length: Some(6),
401 trim_in: 0,
402 trim_out: 5,
403 global_start: 10,
404 global_end: 15,
405 extend_first: 5,
406 extend_last: 0,
407 loop_clip: true,
408 reverse: false,
409 };
410 // Frame 9 with global_start = 10, extend_first = 5 -> inside [5, 15]: ExtendFirst holds frame 0.
411 let (_, local_idx, _, _) = cache
412 .load_clip(&clip, 9, false, [None; 4])
413 .expect("loop_clip inside ExtendFirst should resolve");
414 assert_eq!(local_idx, 0);
415 // Looping clips ignore GlobalEnd + ExtendLast: frame 20 -> rel 10 -> 10 % 6 = 4.
416 let (_, local_idx, _, _) = cache
417 .load_clip(&clip, 20, false, [None; 4])
418 .expect("loop_clip past GlobalEnd should keep looping");
419 assert_eq!(local_idx, 4);
420 let once = ClipSpec { loop_clip: false, ..clip };
421 assert!(cache.load_clip(&once, 20, false, [None; 4]).is_none());
422 }
423 assert!(
424 cache.video_decoder_count() <= MAX_VIDEO_DECODERS,
425 "expected LRU cap <= {MAX_VIDEO_DECODERS}, got {}",
426 cache.video_decoder_count()
427 );
428 assert_eq!(cache.video_decoder_count(), MAX_VIDEO_DECODERS);
429
430 // Straight-alpha ProRes 4444 MOV test for post_multiply separation.
431 let alpha_png = dir.join("straight_half.png");
432 image::RgbaImage::from_pixel(32, 32, image::Rgba([200, 100, 50, 128]))
433 .save(&alpha_png)
434 .unwrap();
435 let alpha_mov = dir.join("straight_half.mov");
436 let mov_ok = Command::new("ffmpeg")
437 .args([
438 "-y",
439 "-v",
440 "error",
441 "-loop",
442 "1",
443 "-i",
444 ])
445 .arg(&alpha_png)
446 .args([
447 "-t",
448 "0.1",
449 "-r",
450 "24",
451 "-c:v",
452 "prores_ks",
453 "-profile:v",
454 "4",
455 "-pix_fmt",
456 "yuva444p10le",
457 ])
458 .arg(&alpha_mov)
459 .status()
460 .is_ok_and(|s| s.success());
461 if mov_ok {
462 let mov_clip = ClipSpec {
463 filename: alpha_mov.to_string_lossy().into_owned(),
464 alternate_filename: None,
465 start_frame: 0,
466 length: Some(2),
467 trim_in: 0,
468 trim_out: 1,
469 global_start: 0,
470 global_end: 1,
471 extend_first: 0,
472 extend_last: 0,
473 loop_clip: false,
474 reverse: false,
475 };
476 let (_, _, raw_vid, _) = cache.load_clip(&mov_clip, 0, false, [None; 4]).unwrap();
477 let (_, _, pm_vid, _) = cache.load_clip(&mov_clip, 0, true, [None; 4]).unwrap();
478 assert!(
479 pm_vid.rgba[0] < raw_vid.rgba[0],
480 "post_multiply should darken straight-alpha RGB ({} vs {})",
481 pm_vid.rgba[0],
482 raw_vid.rgba[0]
483 );
484 }
485
486 cache.clear();
487 assert_eq!(cache.entry_count(), 0);
488 assert_eq!(cache.video_decoder_count(), 0);
489
490 let _ = std::fs::remove_dir_all(&dir);
491}
492
493#[test]
494fn resolve_clip_path_missing_mid_sequence_returns_none() {
495 let dir = std::env::temp_dir().join(format!("fission_seq_missing_{}", std::process::id()));
496 let _ = std::fs::remove_dir_all(&dir);
497 std::fs::create_dir_all(&dir).unwrap();
498
499 let f0 = dir.join("shot_0000.png");
500 let f2 = dir.join("shot_0002.png");
501 image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).save(&f0).unwrap();
502 image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])).save(&f2).unwrap();
503
504 let clip = ClipSpec {
505 filename: f0.to_string_lossy().into_owned(),
506 alternate_filename: None,
507 start_frame: 0,
508 length: Some(3),
509 trim_in: 0,
510 trim_out: 2,
511 global_start: 0,
512 global_end: 2,
513 extend_first: 0,
514 extend_last: 0,
515 loop_clip: false,
516 reverse: false,
517 };
518 assert_eq!(resolve_clip_path(&clip, 0), Some(f0));
519 assert_eq!(resolve_clip_path(&clip, 1), None);
520 assert_eq!(resolve_clip_path(&clip, 2), Some(f2));
521
522 let _ = std::fs::remove_dir_all(&dir);
523}
524
525#[test]
526fn virtual_bytes_load_a_sequence_by_trailing_path() {
527 let png = |rgba: [u8; 4]| {
528 let mut out = std::io::Cursor::new(Vec::new());
529 image::RgbaImage::from_pixel(2, 1, image::Rgba(rgba))
530 .write_to(&mut out, image::ImageFormat::Png)
531 .unwrap();
532 out.into_inner()
533 };
534 MediaCache::insert_virtual_bytes("vf_proj\\vf_seq.0001.png", png([255, 0, 0, 255]));
535 MediaCache::insert_virtual_bytes("./vf_proj/vf_seq.0002.png", png([0, 255, 0, 255]));
536 let clip = ClipSpec {
537 filename: "/not/on/disk/vf_proj/vf_seq.0001.png".to_owned(),
538 alternate_filename: None,
539 start_frame: 1,
540 length: Some(2),
541 trim_in: 0,
542 trim_out: 1,
543 global_start: 0,
544 global_end: 1,
545 extend_first: 0,
546 extend_last: 0,
547 loop_clip: false,
548 reverse: false,
549 };
550 let mut cache = MediaCache::new(64);
551 let (_, _, f0, from_disk) = cache.load_clip(&clip, 0, false, [None; 4]).unwrap();
552 let (_, _, f1, _) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap();
553 assert!(from_disk);
554 assert_eq!((f0.size, &f0.rgba[..4]), ([2, 1], &[255, 0, 0, 255][..]));
555 assert_eq!(&f1.rgba[..4], &[0, 255, 0, 255]);
556
557 MediaCache::insert_virtual_bytes("vf_proj/vf_seq.0002.png", png([0, 0, 255, 255]));
558 let (_, _, f1, _) = MediaCache::new(64).load_clip(&clip, 1, false, [None; 4]).unwrap();
559 assert_eq!(&f1.rgba[..4], &[0, 0, 255, 255]);
560 assert!(path_exists(Path::new("elsewhere/vf_seq.0002.png")));
561 assert!(!path_exists(Path::new("vf_proj/vf_seq.0003.png")));
562}
563
564fn file(path: &str, len: usize) -> VirtualFile {
565 VirtualFile { parts: path_parts(Path::new(path)), bytes: vec![0; len].into() }
566}
567
568fn found<'a>(files: &'a [VirtualFile], path: &str) -> Option<&'a [String]> {
569 find_virtual(files, &path_parts(Path::new(path))).map(|f| f.parts.as_slice())
570}
571
572#[test]
573fn virtual_paths_normalize_dots_and_separators() {
574 assert_eq!(path_parts(Path::new("/a/./b/../c\\d.png")), ["a", "c", "d.png"]);
575 assert_eq!(path_parts(Path::new("../../x.png")), ["x.png"]);
576}
577
578#[test]
579fn virtual_matching_prefers_exact_and_rejects_ambiguous_basenames() {
580 let files = [file("A/bg.png", 1), file("B/bg.png", 1), file("only.png", 1), file("Proj/Seq.exr", 1)];
581 assert_eq!(found(&files, "/x/A/bg.png"), Some(&["A".to_owned(), "bg.png".to_owned()][..]));
582 assert_eq!(found(&files, "/x/../B/./bg.png").map(<[String]>::len), Some(2));
583 assert_eq!(found(&files, "/C/bg.png"), None, "two files share the basename");
584 assert_eq!(found(&files, "bg.png"), None);
585 assert!(found(&files, "/deep/elsewhere/only.png").is_some());
586 assert!(found(&files, "/proj/seq.EXR").is_some(), "case-insensitive fallback");
587 assert_eq!(found(&files, "/a/missing.png"), None);
588}
589
590#[test]
591fn virtual_files_stop_at_the_memory_cap() {
592 let mut files = Vec::new();
593 let put = |files: &mut Vec<VirtualFile>, name: &str, len: usize| {
594 insert_capped(files, 10, path_parts(Path::new(name)), vec![0; len].into())
595 };
596 assert!(put(&mut files, "a", 6));
597 assert!(!put(&mut files, "b", 5));
598 assert!(put(&mut files, "b", 4));
599 assert!(put(&mut files, "a", 6), "replacing a file frees its old bytes");
600 assert!(!put(&mut files, "a", 7));
601 assert_eq!(files.iter().map(|f| f.bytes.len()).sum::<usize>(), 10);
602}
603
604#[test]
605fn media_budget_scaling_matches_ram_tiers() {
606 const GIB: u64 = 1024 * 1024 * 1024;
607 assert_eq!(media_cache_budget_mb_for_total_bytes(8 * GIB), 512);
608 assert_eq!(media_cache_budget_mb_for_total_bytes(16 * GIB), 1024);
609 assert_eq!(media_cache_budget_mb_for_total_bytes(32 * GIB), 2048);
610 assert_eq!(media_cache_budget_mb_for_total_bytes(64 * GIB), 4096);
611 assert_eq!(media_cache_budget_mb_for_total_bytes(128 * GIB), 8192);
612 let default_cache = MediaCache::default();
613 assert_eq!(
614 default_cache.shared.state.lock().unwrap().budget_bytes,
615 default_media_cache_budget_mb().saturating_mul(1024 * 1024)
616 );
617 let explicit = MediaCache::with_budget_mb(32);
618 assert_eq!(
619 explicit.shared.state.lock().unwrap().budget_bytes,
620 32 * 1024 * 1024
621 );
622}
623
624#[test]
625fn parallel_post_multiply_matches_scalar_across_large_buffer() {
626 let len = 4 * 1024 * 1024 * 4 + 64; // > 4 MP threshold
627 let mut scalar = vec![0u8; len];
628 for (i, px) in scalar.chunks_exact_mut(4).enumerate() {
629 px[0] = ((i * 7) % 256) as u8;
630 px[1] = ((i * 13) % 256) as u8;
631 px[2] = ((i * 29) % 256) as u8;
632 px[3] = (i % 256) as u8;
633 }
634 let mut parallel = scalar.clone();
635 exr::apply_post_multiply_rgba8_parallel(&mut scalar, false);
636 exr::apply_post_multiply_rgba8_parallel(&mut parallel, true);
637 assert_eq!(scalar, parallel);
638}
639
640#[cfg(not(target_arch = "wasm32"))]
641#[test]
642fn preload_frame_loaders_and_prefetch_frames_populate_cache_in_parallel() {
643 let dir = std::env::temp_dir().join(format!("fission_preload_test_{}", std::process::id()));
644 let _ = std::fs::remove_dir_all(&dir);
645 std::fs::create_dir_all(&dir).unwrap();
646
647 let p_bg = dir.join("bg.png");
648 let p_fg0 = dir.join("fg_0000.png");
649 let p_fg1 = dir.join("fg_0001.png");
650 let p_fg2 = dir.join("fg_0002.png");
651 let p_pruned = dir.join("pruned.png");
652 image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 40, 60, 255])).save(&p_bg).unwrap();
653 image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 100, 50, 128])).save(&p_fg0).unwrap();
654 image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 200, 50, 255])).save(&p_fg1).unwrap();
655 image::RgbaImage::from_pixel(4, 4, image::Rgba([50, 0, 200, 255])).save(&p_fg2).unwrap();
656 image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 9, 9, 255])).save(&p_pruned).unwrap();
657
658 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
659 let comp_src = format!(
660 r#"Composition {{
661CurrentTime = 0,
662RenderRange = {{ 0, 2 }},
663GlobalRange = {{ 0, 2 }},
664Tools = ordered() {{
665 BgLoader = Loader {{
666 Clips = {{
667 Clip {{
668 ID = "Clip1",
669 Filename = "{}",
670 FormatID = "PNGFormat",
671 Length = 1,
672 GlobalStart = 0,
673 GlobalEnd = 2,
674 }},
675 }},
676 }},
677 FgLoader = Loader {{
678 Clips = {{
679 Clip {{
680 ID = "Clip1",
681 Filename = "{}",
682 FormatID = "PNGFormat",
683 StartFrame = 0,
684 Length = 3,
685 GlobalStart = 0,
686 GlobalEnd = 2,
687 }},
688 }},
689 Inputs = {{
690 ["Clip1.PNGFormat.PostMultiply"] = Input {{ Value = 1, }},
691 }},
692 }},
693 PrunedLoader = Loader {{
694 Clips = {{
695 Clip {{
696 ID = "Clip1",
697 Filename = "{}",
698 FormatID = "PNGFormat",
699 Length = 1,
700 GlobalStart = 0,
701 GlobalEnd = 2,
702 }},
703 }},
704 }},
705 PrunedMerge = Merge {{
706 Inputs = {{
707 Blend = Input {{ Value = 0, }},
708 Background = Input {{ SourceOp = "BgLoader", Source = "Output", }},
709 Foreground = Input {{ SourceOp = "PrunedLoader", Source = "Output", }},
710 }},
711 }},
712 MainMerge = Merge {{
713 Inputs = {{
714 Background = Input {{ SourceOp = "PrunedMerge", Source = "Output", }},
715 Foreground = Input {{ SourceOp = "FgLoader", Source = "Output", }},
716 }},
717 }},
718}},
719}}"#,
720 esc(&p_bg),
721 esc(&p_fg0),
722 esc(&p_pruned),
723 );
724 let comp = Comp::from_fusion_str(&comp_src).expect("parse preload comp");
725 let target = comp.find_node("MainMerge").expect("MainMerge");
726 let expr = model::ExprEngine::new();
727 let mut cache = MediaCache::new(64);
728
729 cache.preload_frame_loaders(&comp, target, 0.0, &expr);
730 // BgLoader + FgLoader(f0) are cached; PrunedLoader is skipped because PrunedMerge Blend == 0.
731 assert_eq!(cache.entry_count(), 2);
732
733 let bg_clip = comp.node(comp.find_node("BgLoader").unwrap()).clips[0].clone();
734 let fg_clip = comp.node(comp.find_node("FgLoader").unwrap()).clips[0].clone();
735 let (_, _, bg_img, bg_from_disk) = cache.load_clip(&bg_clip, 0, false, [None; 4]).unwrap();
736 let (_, _, fg0_img, fg0_from_disk) = cache.load_clip(&fg_clip, 0, true, [None; 4]).unwrap();
737 assert!(!bg_from_disk);
738 assert!(!fg0_from_disk);
739 assert_eq!(&bg_img.rgba[..4], &[20, 40, 60, 255]);
740 assert_eq!(&fg0_img.rgba[..4], &[100, 50, 25, 128]);
741
742 // Prefetch frames 1 and 2 ahead of playback.
743 cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr);
744 assert_eq!(cache.entry_count(), 4);
745 let (_, _, fg1_img, fg1_from_disk) = cache.load_clip(&fg_clip, 1, true, [None; 4]).unwrap();
746 let (_, _, fg2_img, fg2_from_disk) = cache.load_clip(&fg_clip, 2, true, [None; 4]).unwrap();
747 assert!(!fg1_from_disk);
748 assert!(!fg2_from_disk);
749 assert_eq!(&fg1_img.rgba[..4], &[0, 200, 50, 255]);
750 assert_eq!(&fg2_img.rgba[..4], &[50, 0, 200, 255]);
751
752 let _ = std::fs::remove_dir_all(&dir);
753}
754
755#[cfg(not(target_arch = "wasm32"))]
756#[test]
757fn preload_frame_loaders_decodes_multiple_videos_in_parallel() {
758 let dir = std::env::temp_dir().join(format!("fission_preload_vid_{}", std::process::id()));
759 let _ = std::fs::remove_dir_all(&dir);
760 std::fs::create_dir_all(&dir).unwrap();
761
762 let mk_mp4 = |name: &str, color: &str| {
763 let p = dir.join(name);
764 let ok = Command::new("ffmpeg")
765 .args([
766 "-y",
767 "-v",
768 "error",
769 "-f",
770 "lavfi",
771 "-i",
772 &format!("color=c={color}:size=32x32:rate=24:duration=0.2"),
773 "-c:v",
774 "libx264",
775 "-pix_fmt",
776 "yuv420p",
777 ])
778 .arg(&p)
779 .status()
780 .is_ok_and(|s| s.success());
781 (p, ok)
782 };
783 let (v1, ok1) = mk_mp4("v1.mp4", "red");
784 let (v2, ok2) = mk_mp4("v2.mp4", "blue");
785 if !(ok1 && ok2) {
786 let _ = std::fs::remove_dir_all(&dir);
787 return;
788 }
789
790 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
791 let comp_src = format!(
792 r#"Composition {{
793CurrentTime = 0,
794RenderRange = {{ 0, 3 }},
795GlobalRange = {{ 0, 3 }},
796Tools = ordered() {{
797 V1 = Loader {{
798 Clips = {{
799 Clip {{
800 ID = "Clip1",
801 Filename = "{}",
802 FormatID = "QuickTimeMovies",
803 Length = 4,
804 GlobalStart = 0,
805 GlobalEnd = 3,
806 }},
807 }},
808 }},
809 V2 = Loader {{
810 Clips = {{
811 Clip {{
812 ID = "Clip1",
813 Filename = "{}",
814 FormatID = "QuickTimeMovies",
815 Length = 4,
816 GlobalStart = 0,
817 GlobalEnd = 3,
818 }},
819 }},
820 }},
821 M = Merge {{
822 Inputs = {{
823 Background = Input {{ SourceOp = "V1", Source = "Output", }},
824 Foreground = Input {{ SourceOp = "V2", Source = "Output", }},
825 }},
826 }},
827}},
828}}"#,
829 esc(&v1),
830 esc(&v2),
831 );
832 let comp = Comp::from_fusion_str(&comp_src).expect("parse video preload comp");
833 let target = comp.find_node("M").expect("M");
834 let expr = model::ExprEngine::new();
835 let mut cache = MediaCache::new(64);
836
837 cache.preload_frame_loaders(&comp, target, 0.0, &expr);
838 assert_eq!(cache.video_decoder_count(), 2);
839 assert_eq!(cache.entry_count(), 2);
840
841 let c1 = comp.node(comp.find_node("V1").unwrap()).clips[0].clone();
842 let c2 = comp.node(comp.find_node("V2").unwrap()).clips[0].clone();
843 let (_, _, img1, disk1) = cache.load_clip(&c1, 0, false, [None; 4]).unwrap();
844 let (_, _, img2, disk2) = cache.load_clip(&c2, 0, false, [None; 4]).unwrap();
845 assert!(!disk1);
846 assert!(!disk2);
847 assert!(img1.rgba[0] > 200 && img1.rgba[2] < 40);
848 assert!(img2.rgba[2] > 200 && img2.rgba[0] < 40);
849
850 cache.prefetch_frames(&comp, target, &[1.0, 2.0], &expr);
851 assert_eq!(cache.entry_count(), 6);
852
853 let _ = std::fs::remove_dir_all(&dir);
854}
855
856#[cfg(not(target_arch = "wasm32"))]
857#[test]
858fn background_frame_prefetch_populates_and_cancels_cleanly() {
859 let dir = std::env::temp_dir().join(format!("fission_bg_prefetch_{}", std::process::id()));
860 let _ = std::fs::remove_dir_all(&dir);
861 std::fs::create_dir_all(&dir).unwrap();
862
863 for i in 0..4 {
864 let p = dir.join(format!("seq_{i:04}.png"));
865 image::RgbaImage::from_pixel(4, 4, image::Rgba([i as u8 * 50, 10, 200, 255]))
866 .save(&p)
867 .unwrap();
868 }
869 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
870 let p0 = dir.join("seq_0000.png");
871 let comp_src = format!(
872 r#"Composition {{
873CurrentTime = 0,
874RenderRange = {{ 0, 3 }},
875GlobalRange = {{ 0, 3 }},
876Tools = ordered() {{
877 LD = Loader {{
878 Clips = {{
879 Clip {{
880 ID = "Clip1",
881 Filename = "{}",
882 FormatID = "PNGFormat",
883 StartFrame = 0,
884 Length = 4,
885 GlobalStart = 0,
886 GlobalEnd = 3,
887 }},
888 }},
889 }},
890}},
891}}"#,
892 esc(&p0)
893 );
894 let comp = Comp::from_fusion_str(&comp_src).expect("parse bg prefetch comp");
895 let target = comp.find_node("LD").unwrap();
896 let clip = comp.node(target).clips[0].clone();
897 let expr = model::ExprEngine::new();
898 let mut cache = MediaCache::new(64);
899
900 let mut handle = cache.start_frame_prefetch(4);
901 for f in 0..=3 {
902 handle.enqueue_frame(&comp, target, f, f as f64, &expr, false);
903 }
904 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
905 while cache.entry_count() < 4 && std::time::Instant::now() < deadline {
906 std::thread::sleep(std::time::Duration::from_millis(5));
907 }
908 assert_eq!(cache.entry_count(), 4);
909 for f in 0..=3 {
910 let (_, _, img, from_disk) = cache.load_clip(&clip, f, false, [None; 4]).unwrap();
911 assert!(!from_disk, "frame {f} should already be in MediaCache");
912 assert_eq!(img.rgba[0], (f as u8) * 50);
913 }
914 handle.cancel();
915 drop(handle);
916
917 let _ = std::fs::remove_dir_all(&dir);
918}
919
920#[cfg(not(target_arch = "wasm32"))]
921#[test]
922fn failed_opens_are_not_cached_and_evict_known_existing_paths() {
923 let dir = std::env::temp_dir().join(format!("fission_evict_test_{}", std::process::id()));
924 let _ = std::fs::remove_dir_all(&dir);
925 std::fs::create_dir_all(&dir).unwrap();
926
927 let bad_vid = dir.join("corrupt.mp4");
928 std::fs::write(&bad_vid, b"not a valid mp4").unwrap();
929 let mut cache = MediaCache::new(64);
930 assert!(cache.shared.path_exists_cached(&bad_vid));
931 assert!(cache.shared.get_or_open_video_decoder(&bad_vid).is_none());
932 assert_eq!(cache.video_decoder_count(), 0);
933 assert!(!cache.shared.state.lock().unwrap().known_existing_paths.contains(&bad_vid));
934
935 let img_path = dir.join("gone.png");
936 image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 20, 30, 255]))
937 .save(&img_path)
938 .unwrap();
939 assert!(cache.shared.path_exists_cached(&img_path));
940 std::fs::remove_file(&img_path).unwrap();
941 let clip = ClipSpec {
942 filename: img_path.to_string_lossy().into_owned(),
943 alternate_filename: None,
944 start_frame: 0,
945 length: Some(1),
946 trim_in: 0,
947 trim_out: 0,
948 global_start: 0,
949 global_end: 0,
950 extend_first: 0,
951 extend_last: 0,
952 loop_clip: false,
953 reverse: false,
954 };
955 assert!(cache.load_clip(&clip, 0, false, [None; 4]).is_none());
956 assert!(!cache.shared.path_exists_cached(&img_path));
957
958 let _ = std::fs::remove_dir_all(&dir);
959}
960
961#[cfg(not(target_arch = "wasm32"))]
962#[test]
963fn prefetch_queue_prunes_stale_and_avoids_hol_blocking() {
964 let dir = std::env::temp_dir().join(format!("fission_hol_prefetch_{}", std::process::id()));
965 let _ = std::fs::remove_dir_all(&dir);
966 std::fs::create_dir_all(&dir).unwrap();
967
968 for i in 0..=10 {
969 let p = dir.join(format!("seq_{i:04}.png"));
970 image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8 * 20, 10, 200, 255]))
971 .save(&p)
972 .unwrap();
973 }
974 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
975 let p0 = dir.join("seq_0000.png");
976 let comp_src = format!(
977 r#"Composition {{
978CurrentTime = 0,
979RenderRange = {{ 0, 10 }},
980GlobalRange = {{ 0, 10 }},
981Tools = ordered() {{
982 LD = Loader {{
983 Clips = {{
984 Clip {{
985 ID = "Clip1",
986 Filename = "{}",
987 FormatID = "PNGFormat",
988 StartFrame = 0,
989 Length = 11,
990 GlobalStart = 0,
991 GlobalEnd = 10,
992 }},
993 }},
994 }},
995}},
996}}"#,
997 esc(&p0)
998 );
999 let comp = Comp::from_fusion_str(&comp_src).expect("parse hol prefetch comp");
1000 let target = comp.find_node("LD").unwrap();
1001 let clip = comp.node(target).clips[0].clone();
1002 let expr = model::ExprEngine::new();
1003 let mut cache = MediaCache::new(64);
1004
1005 let mut handle = cache.start_frame_prefetch(2);
1006 // Enqueue far-future seq=10 first (outside lookahead=2), then seq=1 (within lookahead).
1007 handle.enqueue_frame(&comp, target, 10, 10.0, &expr, false);
1008 handle.enqueue_frame(&comp, target, 1, 1.0, &expr, false);
1009
1010 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
1011 while cache.entry_count() < 1 && std::time::Instant::now() < deadline {
1012 std::thread::sleep(std::time::Duration::from_millis(5));
1013 }
1014 assert_eq!(cache.entry_count(), 1);
1015 let (_, _, img1, from_disk1) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap();
1016 assert!(!from_disk1, "seq=1 must not be head-of-line blocked by seq=10");
1017 assert_eq!(img1.rgba[0], 20);
1018
1019 // Advancing current_seq past 10 prunes seq=10 cleanly.
1020 handle.set_current_seq(11);
1021 {
1022 let q = handle.queue.state.lock().unwrap();
1023 assert!(q.raster.is_empty());
1024 assert!(q.queued_raster_keys.is_empty());
1025 }
1026 handle.cancel();
1027 let _ = std::fs::remove_dir_all(&dir);
1028}
1029
1030#[cfg(not(target_arch = "wasm32"))]
1031#[test]
1032fn prefetch_handle_scales_and_decodes_nine_videos_concurrently() {
1033 let dir = std::env::temp_dir().join(format!("fission_9vid_prefetch_{}", std::process::id()));
1034 let _ = std::fs::remove_dir_all(&dir);
1035 std::fs::create_dir_all(&dir).unwrap();
1036
1037 let v0 = dir.join("v0.mp4");
1038 let ok = Command::new("ffmpeg")
1039 .args([
1040 "-y",
1041 "-v",
1042 "error",
1043 "-f",
1044 "lavfi",
1045 "-i",
1046 "color=c=green:size=16x16:rate=24:duration=0.15",
1047 "-c:v",
1048 "libx264",
1049 "-pix_fmt",
1050 "yuv420p",
1051 ])
1052 .arg(&v0)
1053 .status()
1054 .is_ok_and(|s| s.success());
1055 if !ok {
1056 let _ = std::fs::remove_dir_all(&dir);
1057 return;
1058 }
1059
1060 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
1061 let mut tools = String::new();
1062 for i in 0..9 {
1063 let vi = dir.join(format!("v{i}.mp4"));
1064 if i > 0 {
1065 std::fs::copy(&v0, &vi).unwrap();
1066 }
1067 tools.push_str(&format!(
1068 r#" V{i} = Loader {{
1069 Clips = {{
1070 Clip {{
1071 ID = "Clip1",
1072 Filename = "{}",
1073 FormatID = "QuickTimeMovies",
1074 Length = 3,
1075 GlobalStart = 0,
1076 GlobalEnd = 2,
1077 }},
1078 }},
1079 }},
1080"#,
1081 esc(&vi)
1082 ));
1083 }
1084 let mut prev = "V0".to_owned();
1085 for i in 1..9 {
1086 let mname = format!("M{i}");
1087 tools.push_str(&format!(
1088 r#" {mname} = Merge {{
1089 Inputs = {{
1090 Background = Input {{ SourceOp = "{prev}", Source = "Output", }},
1091 Foreground = Input {{ SourceOp = "V{i}", Source = "Output", }},
1092 }},
1093 }},
1094"#
1095 ));
1096 prev = mname;
1097 }
1098 let comp_src = format!(
1099 "Composition {{\n CurrentTime = 0,\n RenderRange = {{ 0, 2 }},\n GlobalRange = {{ 0, 2 }},\n Tools = ordered() {{\n{tools} }},\n}}"
1100 );
1101 let comp = Comp::from_fusion_str(&comp_src).expect("parse 9-video comp");
1102 let target = comp.find_node("M8").expect("M8");
1103 let expr = model::ExprEngine::new();
1104 let cache = MediaCache::new(64);
1105
1106 let mut handle = cache.start_frame_prefetch(4);
1107 let expected_workers = std::thread::available_parallelism()
1108 .map(|n| n.get().clamp(2, 12))
1109 .unwrap_or(4);
1110 assert_eq!(handle.workers.len(), expected_workers);
1111
1112 handle.enqueue_frame(&comp, target, 0, 0.0, &expr, false);
1113 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1114 while cache.entry_count() < 9 && std::time::Instant::now() < deadline {
1115 std::thread::sleep(std::time::Duration::from_millis(5));
1116 }
1117 assert_eq!(cache.video_decoder_count(), 9);
1118 assert_eq!(cache.entry_count(), 9);
1119 handle.cancel();
1120 let _ = std::fs::remove_dir_all(&dir);
1121}
1122
1123#[cfg(not(target_arch = "wasm32"))]
1124#[test]
1125fn warm_cache_over_75_percent_keeps_full_lookahead() {
1126 let dir = std::env::temp_dir().join(format!("fission_warm_lookahead_{}", std::process::id()));
1127 let _ = std::fs::remove_dir_all(&dir);
1128 std::fs::create_dir_all(&dir).unwrap();
1129
1130 for i in 0..=4 {
1131 let p = dir.join(format!("seq_{i:04}.png"));
1132 image::RgbaImage::from_pixel(512, 512, image::Rgba([i as u8 * 40, 20, 180, 255]))
1133 .save(&p)
1134 .unwrap();
1135 }
1136 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
1137 let p0 = dir.join("seq_0000.png");
1138 let comp_src = format!(
1139 r#"Composition {{
1140CurrentTime = 0,
1141RenderRange = {{ 0, 4 }},
1142GlobalRange = {{ 0, 4 }},
1143Tools = ordered() {{
1144 LD = Loader {{
1145 Clips = {{
1146 Clip {{
1147 ID = "Clip1",
1148 Filename = "{}",
1149 FormatID = "PNGFormat",
1150 StartFrame = 0,
1151 Length = 5,
1152 GlobalStart = 0,
1153 GlobalEnd = 4,
1154 }},
1155 }},
1156 }},
1157}},
1158}}"#,
1159 esc(&p0)
1160 );
1161 let comp = Comp::from_fusion_str(&comp_src).expect("parse warm lookahead comp");
1162 let target = comp.find_node("LD").unwrap();
1163 let clip = comp.node(target).clips[0].clone();
1164 let expr = model::ExprEngine::new();
1165 let mut cache = MediaCache::new(64);
1166
1167 // Warm the cache past 75% of its 64 MiB budget (13 x 4 MiB = 52 MiB = 81.25%).
1168 let four_mb = Arc::new(vec![128u8; 1024 * 1024 * 4]);
1169 {
1170 let mut state = cache.shared.state.lock().unwrap();
1171 for i in 0..13 {
1172 let key = ImageCacheKey {
1173 path: dir.join(format!("warm_{i:04}.png")),
1174 frame_idx: -1,
1175 post_multiply: false,
1176 exr_channels: [None, None, None, None],
1177 };
1178 let img = DecodedImage {
1179 size: [1024, 1024],
1180 rgba: Arc::clone(&four_mb),
1181 rgba_f16: None,
1182 rgba_f32: None,
1183 };
1184 cache.shared.insert_cached_locked(&mut state, key, img);
1185 }
1186 }
1187 assert!(
1188 cache.total_mb() > 48.0,
1189 "cache must be >75% of 64 MiB, got {:.2} MiB",
1190 cache.total_mb()
1191 );
1192
1193 let mut handle = cache.start_frame_prefetch(4);
1194 handle.set_current_seq(0);
1195 for seq in 1..=4 {
1196 handle.enqueue_frame(&comp, target, seq, seq as f64, &expr, false);
1197 }
1198
1199 // All 4 lookahead frames (through current_seq + 4) must be prefetched without collapsing
1200 // to current_seq + 1.
1201 let expected_keys: Vec<ImageCacheKey> = (1..=4)
1202 .map(|i| ImageCacheKey {
1203 path: dir.join(format!("seq_{i:04}.png")),
1204 frame_idx: -1,
1205 post_multiply: false,
1206 exr_channels: [None, None, None, None],
1207 })
1208 .collect();
1209 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
1210 loop {
1211 let all_cached = cache
1212 .shared
1213 .state
1214 .lock()
1215 .map(|s| expected_keys.iter().all(|k| s.images.contains_key(k)))
1216 .unwrap_or(false);
1217 if all_cached || std::time::Instant::now() >= deadline {
1218 break;
1219 }
1220 std::thread::sleep(std::time::Duration::from_millis(5));
1221 }
1222
1223 for i in 1..=4 {
1224 let (_, _, img, from_disk) = cache.load_clip(&clip, i, false, [None; 4]).unwrap();
1225 assert!(
1226 !from_disk,
1227 "frame {i} (current_seq + {i}) should have been prefetched while >75% warm"
1228 );
1229 assert_eq!(img.rgba[0], (i as u8) * 40);
1230 }
1231
1232 handle.cancel();
1233 let _ = std::fs::remove_dir_all(&dir);
1234}
1235
1236#[test]
1237fn direct_png_decode_matches_image_crate_bit_for_bit_all_color_types() {
1238 fn encode_png(
1239 w: u32,
1240 h: u32,
1241 color: png::ColorType,
1242 depth: png::BitDepth,
1243 palette: Option<&[u8]>,
1244 trns: Option<&[u8]>,
1245 data: &[u8],
1246 ) -> Vec<u8> {
1247 let mut out = Vec::new();
1248 {
1249 let mut enc = png::Encoder::new(&mut out, w, h);
1250 enc.set_color(color);
1251 enc.set_depth(depth);
1252 if let Some(p) = palette {
1253 enc.set_palette(p);
1254 }
1255 if let Some(t) = trns {
1256 enc.set_trns(t);
1257 }
1258 let mut writer = enc.write_header().unwrap();
1259 writer.write_image_data(data).unwrap();
1260 }
1261 out
1262 }
1263
1264 let (w, h) = (17u32, 11u32);
1265 let n = (w * h) as usize;
1266 let cases: Vec<(&str, Vec<u8>)> = vec![
1267 (
1268 "rgba8",
1269 encode_png(
1270 w,
1271 h,
1272 png::ColorType::Rgba,
1273 png::BitDepth::Eight,
1274 None,
1275 None,
1276 &(0..n * 4).map(|i| ((i * 37 + 13) % 256) as u8).collect::<Vec<_>>(),
1277 ),
1278 ),
1279 (
1280 "rgb8",
1281 encode_png(
1282 w,
1283 h,
1284 png::ColorType::Rgb,
1285 png::BitDepth::Eight,
1286 None,
1287 None,
1288 &(0..n * 3).map(|i| ((i * 53 + 7) % 256) as u8).collect::<Vec<_>>(),
1289 ),
1290 ),
1291 (
1292 "gray8",
1293 encode_png(
1294 w,
1295 h,
1296 png::ColorType::Grayscale,
1297 png::BitDepth::Eight,
1298 None,
1299 None,
1300 &(0..n).map(|i| ((i * 29 + 3) % 256) as u8).collect::<Vec<_>>(),
1301 ),
1302 ),
1303 (
1304 "gray_alpha8",
1305 encode_png(
1306 w,
1307 h,
1308 png::ColorType::GrayscaleAlpha,
1309 png::BitDepth::Eight,
1310 None,
1311 None,
1312 &(0..n * 2).map(|i| ((i * 41 + 19) % 256) as u8).collect::<Vec<_>>(),
1313 ),
1314 ),
1315 (
1316 "palette_trns",
1317 encode_png(
1318 w,
1319 h,
1320 png::ColorType::Indexed,
1321 png::BitDepth::Eight,
1322 Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128, 255, 255, 255]),
1323 Some(&[0, 128, 255]),
1324 &(0..n).map(|i| (i % 4) as u8).collect::<Vec<_>>(),
1325 ),
1326 ),
1327 (
1328 "palette_opaque",
1329 encode_png(
1330 w,
1331 h,
1332 png::ColorType::Indexed,
1333 png::BitDepth::Eight,
1334 Some(&[10, 20, 30, 200, 150, 50, 0, 255, 128]),
1335 None,
1336 &(0..n).map(|i| (i % 3) as u8).collect::<Vec<_>>(),
1337 ),
1338 ),
1339 (
1340 "rgba16",
1341 encode_png(
1342 w,
1343 h,
1344 png::ColorType::Rgba,
1345 png::BitDepth::Sixteen,
1346 None,
1347 None,
1348 // Include boundary values like 0x01ff (511 -> rounds to 2, not 1).
1349 &(0..n * 4)
1350 .flat_map(|i| (((i * 1021 + 255) % 65536) as u16).to_be_bytes())
1351 .collect::<Vec<_>>(),
1352 ),
1353 ),
1354 (
1355 "rgb16",
1356 encode_png(
1357 w,
1358 h,
1359 png::ColorType::Rgb,
1360 png::BitDepth::Sixteen,
1361 None,
1362 None,
1363 &(0..n * 3)
1364 .flat_map(|i| (((i * 997 + 511) % 65536) as u16).to_be_bytes())
1365 .collect::<Vec<_>>(),
1366 ),
1367 ),
1368 (
1369 "gray16",
1370 encode_png(
1371 w,
1372 h,
1373 png::ColorType::Grayscale,
1374 png::BitDepth::Sixteen,
1375 None,
1376 None,
1377 &(0..n)
1378 .flat_map(|i| (((i * 773 + 128) % 65536) as u16).to_be_bytes())
1379 .collect::<Vec<_>>(),
1380 ),
1381 ),
1382 (
1383 "gray_alpha16",
1384 encode_png(
1385 w,
1386 h,
1387 png::ColorType::GrayscaleAlpha,
1388 png::BitDepth::Sixteen,
1389 None,
1390 None,
1391 &(0..n * 2)
1392 .flat_map(|i| (((i * 613 + 384) % 65536) as u16).to_be_bytes())
1393 .collect::<Vec<_>>(),
1394 ),
1395 ),
1396 ];
1397
1398 for (label, bytes) in cases {
1399 let dyn_img = image::load_from_memory(&bytes).expect("image crate decode");
1400 let expected_has_alpha = dyn_img.color().has_alpha();
1401 let expected_size = [dyn_img.width(), dyn_img.height()];
1402 let expected_rgba = dyn_img.into_rgba8().into_raw();
1403
1404 let (got_size, got_rgba, got_has_alpha) = match decode_png_bytes(&bytes) {
1405 PngDecodeOutcome::Decoded(v) => v,
1406 PngDecodeOutcome::Fallback | PngDecodeOutcome::Reject => {
1407 panic!("direct decode failed for {label}")
1408 }
1409 };
1410 assert_eq!(got_size, expected_size, "size mismatch for {label}");
1411 assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}");
1412 assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}");
1413 }
1414}
1415
1416#[test]
1417fn reject_spoofed_oversized_png_ihdr_without_allocating() {
1418 fn png_crc32(data: &[u8]) -> u32 {
1419 let mut crc = 0xFFFF_FFFFu32;
1420 for &b in data {
1421 crc ^= b as u32;
1422 for _ in 0..8 {
1423 let mask = (crc & 1).wrapping_neg();
1424 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
1425 }
1426 }
1427 !crc
1428 }
1429
1430 fn push_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], payload: &[u8]) {
1431 out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
1432 let crc_start = out.len();
1433 out.extend_from_slice(chunk_type);
1434 out.extend_from_slice(payload);
1435 let crc = png_crc32(&out[crc_start..]);
1436 out.extend_from_slice(&crc.to_be_bytes());
1437 }
1438
1439 let mut crafted = vec![137, 80, 78, 71, 13, 10, 26, 10];
1440 let mut ihdr = [0u8; 13];
1441 ihdr[0..4].copy_from_slice(&16u32.to_be_bytes());
1442 ihdr[4..8].copy_from_slice(&1_000_000_000u32.to_be_bytes());
1443 ihdr[8] = 8; // bit depth
1444 ihdr[9] = 6; // RGBA
1445 push_chunk(&mut crafted, b"IHDR", &ihdr);
1446 push_chunk(&mut crafted, b"IDAT", &[0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]);
1447 push_chunk(&mut crafted, b"IEND", &[]);
1448 assert_eq!(crafted.len(), 67);
1449
1450 assert!(matches!(decode_png_bytes(&crafted), PngDecodeOutcome::Reject));
1451 assert!(decode_raster_bytes(&crafted).is_none());
1452}