diff --git a/crates/engine/build.rs b/crates/engine/build.rs index 227f8f07a7b23ef35f76e5a0fc6cbb30771d9833..664a90c8d4ba6cd393a4834a2fe4742733f0ba46 100644 --- a/crates/engine/build.rs +++ b/crates/engine/build.rs @@ -8,6 +8,7 @@ fn main() { .compile("av_decode"); for fw in [ + "Accelerate", "AVFoundation", "CoreMedia", "CoreVideo", diff --git a/crates/engine/src/av_decode.m b/crates/engine/src/av_decode.m index 9e9c0ddf3a0019cf66eb8d7ebe13dc7b0e8dbf91..aaf61a0f130d6ce00311904add6e0618a57bb322 100644 --- a/crates/engine/src/av_decode.m +++ b/crates/engine/src/av_decode.m @@ -1,3 +1,4 @@ +#import #import #import #import @@ -7,6 +8,9 @@ #include #include #include +#if defined(__aarch64__) +#include +#endif #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" @@ -76,6 +80,48 @@ typedef struct AvVideoDecoder AvVideoDecoder; +static inline void bgra_to_rgba_pixel(const uint8_t *src, uint8_t *dst) { + dst[0] = src[2]; + dst[1] = src[1]; + dst[2] = src[0]; + dst[3] = src[3]; +} + +#if defined(__aarch64__) +static inline void neon_transpose4x4_bgra_to_rgba( + const uint8_t *r0, + const uint8_t *r1, + const uint8_t *r2, + const uint8_t *r3, + uint8x16_t swizTbl, + uint8_t *d0Out, + uint8_t *d1Out, + uint8_t *d2Out, + uint8_t *d3Out +) { + uint32x4_t p0 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r0), swizTbl)); + uint32x4_t p1 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r1), swizTbl)); + uint32x4_t p2 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r2), swizTbl)); + uint32x4_t p3 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r3), swizTbl)); + uint32x4_t t0 = vtrn1q_u32(p0, p1); + uint32x4_t t1 = vtrn2q_u32(p0, p1); + uint32x4_t t2 = vtrn1q_u32(p2, p3); + uint32x4_t t3 = vtrn2q_u32(p2, p3); + uint32x4_t d0 = vreinterpretq_u32_u64( + vtrn1q_u64(vreinterpretq_u64_u32(t0), vreinterpretq_u64_u32(t2))); + uint32x4_t d1 = vreinterpretq_u32_u64( + vtrn1q_u64(vreinterpretq_u64_u32(t1), vreinterpretq_u64_u32(t3))); + uint32x4_t d2 = vreinterpretq_u32_u64( + vtrn2q_u64(vreinterpretq_u64_u32(t0), vreinterpretq_u64_u32(t2))); + uint32x4_t d3 = vreinterpretq_u32_u64( + vtrn2q_u64(vreinterpretq_u64_u32(t1), vreinterpretq_u64_u32(t3))); + vst1q_u8(d0Out, vreinterpretq_u8_u32(d0)); + vst1q_u8(d1Out, vreinterpretq_u8_u32(d1)); + vst1q_u8(d2Out, vreinterpretq_u8_u32(d2)); + vst1q_u8(d3Out, vreinterpretq_u8_u32(d3)); +} +#endif + static int copy_bgra_to_rgba( CVImageBufferRef imgBuf, uint32_t outW, @@ -102,61 +148,165 @@ static int copy_bgra_to_rgba( const uint8_t *base = (const uint8_t *)CVPixelBufferGetBaseAddress(imgBuf); int ok = 0; - if (base) { + if (base && srcW > 0 && srcH > 0 && bpr >= srcW * 4) { + const size_t dstBpr = (size_t)outW * 4; + const uint8_t permuteMap[4] = { 2, 1, 0, 3 }; + // Disable internal vImage GCD tiling so parallel decoder threads do not oversubscribe cores. + const vImage_Flags vflags = kvImageDoNotTile; + vImage_Buffer srcBuf = { (void *)base, (vImagePixelCount)srcH, (vImagePixelCount)srcW, bpr }; + vImage_Buffer dstBuf = { (void *)outRgba, (vImagePixelCount)outH, (vImagePixelCount)outW, dstBpr }; + if (rotation == 0 && srcW == outW && srcH == outH) { - for (size_t y = 0; y < srcH; y++) { - const uint8_t *src = base + y * bpr; - uint8_t *dst = outRgba + y * (size_t)outW * 4; - for (size_t x = 0; x < srcW; x++) { - dst[x * 4 + 0] = src[x * 4 + 2]; - dst[x * 4 + 1] = src[x * 4 + 1]; - dst[x * 4 + 2] = src[x * 4 + 0]; - dst[x * 4 + 3] = src[x * 4 + 3]; + if (vImagePermuteChannels_ARGB8888(&srcBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) { + ok = 1; + } else { + for (size_t y = 0; y < srcH; y++) { + const uint8_t *src = base + y * bpr; + uint8_t *dst = outRgba + y * dstBpr; + for (size_t x = 0; x < srcW; x++) { + bgra_to_rgba_pixel(src + x * 4, dst + x * 4); + } } + ok = 1; } - ok = 1; } else if (rotation == 90 && srcH == outW && srcW == outH) { - for (size_t y = 0; y < srcH; y++) { - const uint8_t *src = base + y * bpr; - size_t dx = srcH - 1 - y; - for (size_t x = 0; x < srcW; x++) { - size_t dy = x; - uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4; - dst[0] = src[x * 4 + 2]; - dst[1] = src[x * 4 + 1]; - dst[2] = src[x * 4 + 0]; - dst[3] = src[x * 4 + 3]; +#if defined(__aarch64__) + const uint8_t swizTblBytes[16] = { 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 }; + uint8x16_t swizTbl = vld1q_u8(swizTblBytes); + const size_t B = 32; + for (size_t by = 0; by < srcH; by += B) { + size_t bh = (by + B <= srcH) ? B : (srcH - by); + for (size_t bx = 0; bx < srcW; bx += B) { + size_t bw = (bx + B <= srcW) ? B : (srcW - bx); + size_t y = 0; + for (; y + 4 <= bh; y += 4) { + size_t sy = by + y; + size_t dxBase = srcH - 1 - (sy + 3); + const uint8_t *r0 = base + (sy + 0) * bpr + bx * 4; + const uint8_t *r1 = base + (sy + 1) * bpr + bx * 4; + const uint8_t *r2 = base + (sy + 2) * bpr + bx * 4; + const uint8_t *r3 = base + (sy + 3) * bpr + bx * 4; + size_t x = 0; + for (; x + 4 <= bw; x += 4) { + uint8_t *dst = outRgba + (bx + x) * dstBpr + dxBase * 4; + neon_transpose4x4_bgra_to_rgba( + r3 + x * 4, r2 + x * 4, r1 + x * 4, r0 + x * 4, + swizTbl, + dst + 0 * dstBpr, dst + 1 * dstBpr, dst + 2 * dstBpr, dst + 3 * dstBpr + ); + } + for (; x < bw; x++) { + size_t dy = bx + x; + for (size_t k = 0; k < 4; k++) { + size_t dx = srcH - 1 - (sy + k); + bgra_to_rgba_pixel( + base + (sy + k) * bpr + (bx + x) * 4, + outRgba + dy * dstBpr + dx * 4 + ); + } + } + } + for (; y < bh; y++) { + size_t sy = by + y; + size_t dx = srcH - 1 - sy; + const uint8_t *src = base + sy * bpr + bx * 4; + for (size_t x = 0; x < bw; x++) { + size_t dy = bx + x; + bgra_to_rgba_pixel(src + x * 4, outRgba + dy * dstBpr + dx * 4); + } + } } } ok = 1; +#else + const Pixel_8888 back = { 0, 0, 0, 0 }; + if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate90DegreesClockwise, back, vflags) == kvImageNoError && + vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) { + ok = 1; + } +#endif } else if (rotation == 180 && srcW == outW && srcH == outH) { +#if defined(__aarch64__) + const uint8_t revSwizBytes[16] = { 14, 13, 12, 15, 10, 9, 8, 11, 6, 5, 4, 7, 2, 1, 0, 3 }; + uint8x16_t revSwiz = vld1q_u8(revSwizBytes); for (size_t y = 0; y < srcH; y++) { const uint8_t *src = base + y * bpr; - size_t dy = srcH - 1 - y; - for (size_t x = 0; x < srcW; x++) { - size_t dx = srcW - 1 - x; - uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4; - dst[0] = src[x * 4 + 2]; - dst[1] = src[x * 4 + 1]; - dst[2] = src[x * 4 + 0]; - dst[3] = src[x * 4 + 3]; + uint8_t *dstRow = outRgba + (srcH - 1 - y) * dstBpr; + size_t x = 0; + for (; x + 4 <= srcW; x += 4) { + uint8x16_t v = vld1q_u8(src + x * 4); + vst1q_u8(dstRow + (srcW - x - 4) * 4, vqtbl1q_u8(v, revSwiz)); + } + for (; x < srcW; x++) { + bgra_to_rgba_pixel(src + x * 4, dstRow + (srcW - 1 - x) * 4); } } ok = 1; +#else + const Pixel_8888 back = { 0, 0, 0, 0 }; + if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate180DegreesClockwise, back, vflags) == kvImageNoError && + vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) { + ok = 1; + } +#endif } else if (rotation == 270 && srcH == outW && srcW == outH) { - for (size_t y = 0; y < srcH; y++) { - const uint8_t *src = base + y * bpr; - size_t dx = y; - for (size_t x = 0; x < srcW; x++) { - size_t dy = srcW - 1 - x; - uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4; - dst[0] = src[x * 4 + 2]; - dst[1] = src[x * 4 + 1]; - dst[2] = src[x * 4 + 0]; - dst[3] = src[x * 4 + 3]; +#if defined(__aarch64__) + const uint8_t swizTblBytes[16] = { 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 }; + uint8x16_t swizTbl = vld1q_u8(swizTblBytes); + const size_t B = 32; + for (size_t by = 0; by < srcH; by += B) { + size_t bh = (by + B <= srcH) ? B : (srcH - by); + for (size_t bx = 0; bx < srcW; bx += B) { + size_t bw = (bx + B <= srcW) ? B : (srcW - bx); + size_t y = 0; + for (; y + 4 <= bh; y += 4) { + size_t sy = by + y; + const uint8_t *r0 = base + (sy + 0) * bpr + bx * 4; + const uint8_t *r1 = base + (sy + 1) * bpr + bx * 4; + const uint8_t *r2 = base + (sy + 2) * bpr + bx * 4; + const uint8_t *r3 = base + (sy + 3) * bpr + bx * 4; + size_t x = 0; + for (; x + 4 <= bw; x += 4) { + size_t dyTop = srcW - 1 - (bx + x); + neon_transpose4x4_bgra_to_rgba( + r0 + x * 4, r1 + x * 4, r2 + x * 4, r3 + x * 4, + swizTbl, + outRgba + (dyTop - 0) * dstBpr + sy * 4, + outRgba + (dyTop - 1) * dstBpr + sy * 4, + outRgba + (dyTop - 2) * dstBpr + sy * 4, + outRgba + (dyTop - 3) * dstBpr + sy * 4 + ); + } + for (; x < bw; x++) { + size_t dy = srcW - 1 - (bx + x); + for (size_t k = 0; k < 4; k++) { + size_t dx = sy + k; + bgra_to_rgba_pixel( + base + (sy + k) * bpr + (bx + x) * 4, + outRgba + dy * dstBpr + dx * 4 + ); + } + } + } + for (; y < bh; y++) { + size_t sy = by + y; + size_t dx = sy; + const uint8_t *src = base + sy * bpr + bx * 4; + for (size_t x = 0; x < bw; x++) { + size_t dy = srcW - 1 - (bx + x); + bgra_to_rgba_pixel(src + x * 4, outRgba + dy * dstBpr + dx * 4); + } + } } } ok = 1; +#else + const Pixel_8888 back = { 0, 0, 0, 0 }; + if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate270DegreesClockwise, back, vflags) == kvImageNoError && + vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) { + ok = 1; + } +#endif } } diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index 37d2c091f6e25e6ad3d1ca9929db1f82041e5786..d568d741803590e9e926c936471f0fbe23b61ba4 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -111,13 +111,6 @@ fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box = None; const PREFETCH_LOOKAHEAD: usize = 12; engine.prewarm_core_pipelines(); - engine.media.preload_frame_loaders_with_proxy( - &comp, - target, - start as f64, - &engine.expr, - engine.use_proxy_clips, - ); let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end); for (k, f) in ((start + 1)..=seed_end).enumerate() { @@ -782,13 +768,6 @@ fn main() -> Result<(), Box> { if profile { engine.cache.begin_frame_profile_with_comp(&comp); } - engine.media.preload_frame_loaders_with_proxy( - &comp, - target, - frame, - &engine.expr, - engine.use_proxy_clips, - ); let (tex, cold) = engine.evaluate(&comp, target, frame); let cold_profile = if profile { engine.cache.take_frame_profile().map(|mut fp| { diff --git a/crates/engine/src/eval/io.rs b/crates/engine/src/eval/io.rs index f53ce5d5eb4b69d3932b78e2223054061abeccaf..7d7a3e5b5a6b6872b5a38a06a0652be3a609302f 100644 --- a/crates/engine/src/eval/io.rs +++ b/crates/engine/src/eval/io.rs @@ -123,6 +123,24 @@ impl Engine { let padded_bpr = unpadded_bpr.div_ceil(align) * align; let needed = u64::from(padded_bpr) * u64::from(h); if let Some(buf) = self.media.acquire_upload_staging(&self.device, needed) { + struct StagingGuard<'a> { + media: &'a crate::media::MediaCache, + cap: u64, + armed: bool, + } + impl Drop for StagingGuard<'_> { + fn drop(&mut self) { + if self.armed { + self.media.release_failed_upload_staging(self.cap); + } + } + } + let mut staging_guard = StagingGuard { + media: &self.media, + cap: buf.size(), + armed: true, + }; + let mut copied = false; if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() { if padded_bpr == unpadded_bpr { let total = (unpadded_bpr as usize) * (h as usize); @@ -137,6 +155,9 @@ impl Engine { } } drop(view); + copied = true; + } + if copied { buf.unmap(); enc.copy_buffer_to_texture( wgpu::TexelCopyBufferInfo { @@ -154,6 +175,7 @@ impl Engine { depth_or_array_layers: 1, }, ); + staging_guard.armed = false; self.media.recycle_upload_staging(buf); return; } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 66bfe39b9c35275e1d2333b68e1273e8b092788d..a980a4588f3a0a6264e9ed8d813b18187b39909c 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -308,13 +308,6 @@ pub fn export_saver_png_sequence_with_progress( let mut loop_err: Option = None; const PREFETCH_LOOKAHEAD: usize = 12; engine.prewarm_core_pipelines(); - engine.media.preload_frame_loaders_with_proxy( - comp, - target, - start as f64, - &engine.expr, - engine.use_proxy_clips, - ); let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end); for (k, f) in ((start + 1)..=seed_end).enumerate() { @@ -728,13 +721,7 @@ pub fn export_node_video_ffmpeg_with_progress( let node_name = comp.node(opts.target).name.clone(); // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output. - engine.media.preload_frame_loaders_with_proxy( - comp, - opts.target, - start as f64, - &engine.expr, - engine.use_proxy_clips, - ); + engine.prewarm_core_pipelines(); let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64); if first_tex.size[0] == 0 || first_tex.size[1] == 0 { return Err(format!( @@ -975,110 +962,113 @@ pub fn export_node_video_ffmpeg_with_progress( ctrl.update_progress(&first_prog); } on_progress(first_prog); - - const PREFETCH_LOOKAHEAD: usize = 12; - let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); - let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end); - for (k, f) in ((start + 1)..=seed_end).enumerate() { - prefetch.enqueue_frame( - comp, - opts.target, - k, - f as f64, - &engine.expr, - engine.use_proxy_clips, - ); - } - let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None; - for (idx, frame) in ((start + 1)..=end).enumerate() { - if writer_failed.load(Ordering::Acquire) { - break; - } - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - break; - } - prefetch.set_current_seq(idx); - let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; - if ahead_frame <= end { + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } else if start < end { + const PREFETCH_LOOKAHEAD: usize = 12; + let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD); + let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end); + for (k, f) in ((start + 1)..=seed_end).enumerate() { prefetch.enqueue_frame( comp, opts.target, - idx + PREFETCH_LOOKAHEAD, - ahead_frame as f64, + k, + f as f64, &engine.expr, engine.use_proxy_clips, ); } - let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); - let next_rb = match engine.begin_readback_rgba(&tex) { - Ok(rb) => rb, - Err(e) => { - pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}")); + let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None; + for (idx, frame) in ((start + 1)..=end).enumerate() { + if writer_failed.load(Ordering::Acquire) { break; } - }; - if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = - pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms)) - { - let pixels = match prev_rb.finish(engine) { - Ok(px) => px, - Err(e) => { - pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); - break; - } - }; if control.is_some_and(ExportControl::is_cancelled) { cancelled = true; break; } - if tx.send((prev_frame, prev_size, pixels)).is_err() { - break; + prefetch.set_current_seq(idx); + let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64; + if ahead_frame <= end { + prefetch.enqueue_frame( + comp, + opts.target, + idx + PREFETCH_LOOKAHEAD, + ahead_frame as f64, + &engine.expr, + engine.use_proxy_clips, + ); } - let prog = make_progress( - prev_frame, - prev_idx + 1, - total, - prev_ms, - opts.out_path.clone(), - node_name.clone(), - t0, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); + let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64); + let next_rb = match engine.begin_readback_rgba(&tex) { + Ok(rb) => rb, + Err(e) => { + pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}")); + break; + } + }; + if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = + pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms)) + { + let pixels = match prev_rb.finish(engine) { + Ok(px) => px, + Err(e) => { + pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); + break; + } + }; + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + break; + } + if tx.send((prev_frame, prev_size, pixels)).is_err() { + break; + } + let prog = make_progress( + prev_frame, + prev_idx + 1, + total, + prev_ms, + opts.out_path.clone(), + node_name.clone(), + t0, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); + } + on_progress(prog); } - on_progress(prog); } - } - if pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) { - if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() { - match prev_rb.finish(engine) { - Ok(pixels) => { - if control.is_some_and(ExportControl::is_cancelled) { - cancelled = true; - } else if tx.send((prev_frame, prev_size, pixels)).is_ok() { - let prog = make_progress( - prev_frame, - prev_idx + 1, - total, - prev_ms, - opts.out_path.clone(), - node_name.clone(), - t0, - ); - if let Some(ctrl) = control { - ctrl.update_progress(&prog); + if pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) { + if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() { + match prev_rb.finish(engine) { + Ok(pixels) => { + if control.is_some_and(ExportControl::is_cancelled) { + cancelled = true; + } else if tx.send((prev_frame, prev_size, pixels)).is_ok() { + let prog = make_progress( + prev_frame, + prev_idx + 1, + total, + prev_ms, + opts.out_path.clone(), + node_name.clone(), + t0, + ); + if let Some(ctrl) = control { + ctrl.update_progress(&prog); + } + on_progress(prog); } - on_progress(prog); } - } - Err(e) => { - pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); + Err(e) => { + pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}")); + } } } } + drop(prefetch); } - drop(prefetch); } drop(tx); diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 43c64ec9f875dfc88e9f5473c8a54c5adfb55a3a..87926249f8353981a0e1208186e6b50904cae16d 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -21,8 +21,8 @@ use crate::text_engine; use model::{Node, default_main_input_port}; use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint}; #[cfg(not(target_arch = "wasm32"))] -use std::collections::VecDeque; -use std::collections::{HashMap, HashSet}; +use std::collections::{HashSet, VecDeque}; +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::process::Command; #[cfg(not(target_arch = "wasm32"))] @@ -195,7 +195,7 @@ struct ImageCacheKey { } struct VideoDecoderSlot { - info: Option, + info: VideoInfo, decoder: Arc>>>, last_used: u64, } @@ -212,6 +212,7 @@ struct MediaState { in_flight: HashSet, #[cfg(not(target_arch = "wasm32"))] opening_videos: HashSet, + #[cfg(not(target_arch = "wasm32"))] known_existing_paths: HashSet, } @@ -229,10 +230,30 @@ impl MediaState { in_flight: HashSet::new(), #[cfg(not(target_arch = "wasm32"))] opening_videos: HashSet::new(), + #[cfg(not(target_arch = "wasm32"))] known_existing_paths: HashSet::new(), } } + fn record_existing_path(&mut self, path: &Path) { + #[cfg(not(target_arch = "wasm32"))] + { + if self.known_existing_paths.len() > 8192 { + self.known_existing_paths.clear(); + } + self.known_existing_paths.insert(path.to_path_buf()); + } + #[cfg(target_arch = "wasm32")] + let _ = path; + } + + fn evict_existing_path(&mut self, path: &Path) { + #[cfg(not(target_arch = "wasm32"))] + self.known_existing_paths.remove(path); + #[cfg(target_arch = "wasm32")] + let _ = path; + } + fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { let bytes = decoded.byte_size(); self.tick += 1; @@ -256,16 +277,20 @@ impl MediaState { fn put_video_decoder( &mut self, path: PathBuf, - info: Option, + info: VideoInfo, decoder: Arc>>>, - ) { + ) -> Vec { + let mut evicted = Vec::new(); self.tick += 1; let now_tick = self.tick; + let new_slot = VideoDecoderSlot { + info, + decoder, + last_used: now_tick, + }; if let Some(slot) = self.video_decoders.get_mut(&path) { - slot.info = info; - slot.decoder = decoder; - slot.last_used = now_tick; - return; + evicted.push(std::mem::replace(slot, new_slot)); + return evicted; } while self.video_decoders.len() >= MAX_VIDEO_DECODERS { let Some(oldest_path) = self @@ -276,16 +301,12 @@ impl MediaState { else { break; }; - self.video_decoders.remove(&oldest_path); + if let Some(removed) = self.video_decoders.remove(&oldest_path) { + evicted.push(removed); + } } - self.video_decoders.insert( - path, - VideoDecoderSlot { - info, - decoder, - last_used: now_tick, - }, - ); + self.video_decoders.insert(path, new_slot); + evicted } } @@ -308,18 +329,25 @@ impl MediaShared { if virtual_bytes(path).is_some() { return true; } - if let Ok(state) = self.state.lock() { - if state.known_existing_paths.contains(path) || state.video_decoders.contains_key(path) { - return true; + #[cfg(not(target_arch = "wasm32"))] + { + if let Ok(state) = self.state.lock() { + if state.known_existing_paths.contains(path) || state.video_decoders.contains_key(path) { + return true; + } + } + if path.exists() { + if let Ok(mut state) = self.state.lock() { + state.record_existing_path(path); + } + true + } else { + false } } - if path.exists() { - if let Ok(mut state) = self.state.lock() { - state.known_existing_paths.insert(path.to_path_buf()); - } - true - } else { - false + #[cfg(target_arch = "wasm32")] + { + path.exists() } } @@ -341,7 +369,7 @@ impl MediaShared { let now_tick = guard.tick; if let Some(slot) = guard.video_decoders.get_mut(path) { slot.last_used = now_tick; - return slot.info.map(|info| (info, Arc::clone(&slot.decoder))); + return Some((slot.info, Arc::clone(&slot.decoder))); } #[cfg(not(target_arch = "wasm32"))] @@ -353,37 +381,51 @@ impl MediaShared { struct OpenGuard<'a> { shared: &'a MediaShared, - path: PathBuf, + path: Option, } impl Drop for OpenGuard<'_> { fn drop(&mut self) { #[cfg(not(target_arch = "wasm32"))] - if let Ok(mut state) = self.shared.state.lock() { - state.opening_videos.remove(&self.path); - self.shared.cv.notify_all(); + if let Some(path) = self.path.take() { + if let Ok(mut state) = self.shared.state.lock() { + state.opening_videos.remove(&path); + self.shared.cv.notify_all(); + } } #[cfg(target_arch = "wasm32")] let _ = (&self.shared, &self.path); } } - let _open_guard = OpenGuard { + let mut open_guard = OpenGuard { shared: self, - path: path.to_path_buf(), + path: Some(path.to_path_buf()), }; let decoder = open_video_decoder(path); let info = decoder.as_ref().map(|d| d.info()); let slot_arc = Arc::new(Mutex::new(decoder)); + let mut evicted_decoders = Vec::new(); if let Ok(mut state) = self.state.lock() { #[cfg(not(target_arch = "wasm32"))] state.opening_videos.remove(path); - if state.generation == cache_gen { - state.put_video_decoder(path.to_path_buf(), info, Arc::clone(&slot_arc)); + open_guard.path = None; + if let Some(dec_info) = info { + if state.generation == cache_gen { + state.record_existing_path(path); + evicted_decoders = state.put_video_decoder( + path.to_path_buf(), + dec_info, + Arc::clone(&slot_arc), + ); + } + } else { + state.evict_existing_path(path); } #[cfg(not(target_arch = "wasm32"))] self.cv.notify_all(); } + drop(evicted_decoders); info.map(|i| (i, slot_arc)) } } @@ -550,6 +592,10 @@ impl UploadStagingPool { rx: None, }); } + + pub(crate) fn release_failed_upload(&mut self, capacity: u64) { + self.total_bytes = self.total_bytes.saturating_sub(capacity); + } } pub struct MediaCache { @@ -591,14 +637,17 @@ impl MediaCache { } pub fn clear(&mut self) { + let mut cleared_decoders = Vec::new(); if let Ok(mut state) = self.shared.state.lock() { state.images.clear(); state.lru.clear(); - state.video_decoders.clear(); + cleared_decoders.extend(state.video_decoders.drain().map(|(_, slot)| slot)); state.total_bytes = 0; state.generation = state.generation.wrapping_add(1); + #[cfg(not(target_arch = "wasm32"))] state.known_existing_paths.clear(); } + drop(cleared_decoders); #[cfg(not(target_arch = "wasm32"))] if let Ok(mut pool) = self.staging_pool.lock() { pool.clear(); @@ -609,16 +658,22 @@ impl MediaCache { pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option { self.staging_pool .lock() - .expect("staging pool lock") + .ok()? .acquire(device, needed) } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn recycle_upload_staging(&self, buffer: wgpu::Buffer) { - self.staging_pool - .lock() - .expect("staging pool lock") - .finish_upload(buffer); + if let Ok(mut pool) = self.staging_pool.lock() { + pool.finish_upload(buffer); + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn release_failed_upload_staging(&self, capacity: u64) { + if let Ok(mut pool) = self.staging_pool.lock() { + pool.release_failed_upload(capacity); + } } /// Marks submitted upload staging buffers ready to begin asynchronous write-mapping @@ -800,9 +855,15 @@ impl MediaCache { exr_channels[2], exr_channels[3], false, - )? + ) } else { - decode_raster_image(&resolved, post_multiply, true)? + decode_raster_image(&resolved, post_multiply, true) + }; + let Some(decoded) = decoded else { + if let Ok(mut state) = self.shared.state.lock() { + state.evict_existing_path(&resolved); + } + return None; }; if let Ok(mut state) = self.shared.state.lock() { @@ -812,7 +873,7 @@ impl MediaCache { in_flight_guard.key = None; } if state.generation == cache_gen { - state.known_existing_paths.insert(resolved.clone()); + state.record_existing_path(&resolved); state.insert_cached(cache_key, decoded.clone()); } #[cfg(not(target_arch = "wasm32"))] @@ -848,9 +909,6 @@ impl MediaCache { } #[cfg(not(target_arch = "wasm32"))] { - if let Ok(mut pool) = self.staging_pool.lock() { - pool.mark_frame_start(); - } let mut visited = HashSet::new(); let mut jobs = MissingJobs::default(); collect_missing_loader_jobs_shared( @@ -933,17 +991,8 @@ impl MediaCache { shared: &self.shared, key: Some(job.cache_key.clone()), }; - if let Some(decoded) = decode_job(&job, true) { - if let Ok(mut state) = self.shared.state.lock() { - state.in_flight.remove(&job.cache_key); - guard.key = None; - if state.generation == cache_gen { - state.known_existing_paths.insert(job.cache_key.path.clone()); - state.insert_cached(job.cache_key, decoded); - } - self.shared.cv.notify_all(); - } - } + let decoded = decode_job(&job, true); + finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded); return; } self.decode_jobs_parallel(jobs); @@ -1065,17 +1114,14 @@ impl MediaCache { shared: &self.shared, key: Some(job.cache_key.clone()), }; - if let Some(decoded) = decode_job(job, false) { - if let Ok(mut state) = self.shared.state.lock() { - state.in_flight.remove(&job.cache_key); - guard.key = None; - if state.generation == cache_gen { - state.known_existing_paths.insert(job.cache_key.path.clone()); - state.insert_cached(job.cache_key.clone(), decoded); - } - self.shared.cv.notify_all(); - } - } + let decoded = decode_job(job, false); + finish_raster_job( + &self.shared, + job.cache_key.clone(), + cache_gen, + &mut guard, + decoded, + ); } }); } @@ -1083,6 +1129,29 @@ impl MediaCache { } } +#[cfg(not(target_arch = "wasm32"))] +fn finish_raster_job( + shared: &MediaShared, + key: ImageCacheKey, + cache_gen: u64, + guard: &mut InFlightGuard<'_>, + decoded: Option, +) { + if let Ok(mut state) = shared.state.lock() { + state.in_flight.remove(&key); + guard.key = None; + if let Some(decoded) = decoded { + if state.generation == cache_gen { + state.record_existing_path(&key.path); + state.insert_cached(key, decoded); + } + } else { + state.evict_existing_path(&key.path); + } + shared.cv.notify_all(); + } +} + #[cfg(not(target_arch = "wasm32"))] struct PrefetchQueueState { raster: VecDeque<(usize, PreloadJob)>, @@ -1094,6 +1163,28 @@ struct PrefetchQueueState { cancelled: bool, } +#[cfg(not(target_arch = "wasm32"))] +impl PrefetchQueueState { + fn prune_stale(&mut self) { + let cur = self.current_seq; + if self.raster.iter().any(|&(seq, _)| seq < cur) { + let mut kept = VecDeque::with_capacity(self.raster.len()); + while let Some((seq, job)) = self.raster.pop_front() { + if seq >= cur { + kept.push_back((seq, job)); + } else { + self.queued_raster_keys.remove(&job.cache_key); + } + } + self.raster = kept; + } + self.videos.retain(|_, vq| { + vq.retain(|&(seq, _)| seq >= cur); + !vq.is_empty() + }); + } +} + #[cfg(not(target_arch = "wasm32"))] struct PrefetchQueue { state: Mutex, @@ -1154,6 +1245,7 @@ impl MediaPrefetchHandle { pub fn set_current_seq(&self, seq_idx: usize) { if let Ok(mut q) = self.queue.state.lock() { q.current_seq = seq_idx; + q.prune_stale(); self.queue.cv.notify_all(); } } @@ -1184,7 +1276,7 @@ impl MediaPrefetchHandle { return; } if let Ok(mut q) = self.queue.state.lock() { - if q.cancelled { + if q.cancelled || seq_idx < q.current_seq { return; } for job in jobs.raster { @@ -1195,7 +1287,24 @@ impl MediaPrefetchHandle { for (path, reqs) in jobs.videos { let vq = q.videos.entry(path).or_default(); for req in reqs { - vq.push_back((seq_idx, req)); + if let Some((existing_seq, _)) = vq.iter_mut().find(|(_, existing)| { + existing.post_multiply == req.post_multiply + && match (existing.resolved_frame_idx, req.resolved_frame_idx) { + (Some(a), Some(b)) => a == b, + _ => { + existing.frame_i == req.frame_i + && existing.clip.global_start == req.clip.global_start + && existing.clip.trim_in == req.clip.trim_in + && existing.clip.trim_out == req.clip.trim_out + && existing.clip.reverse == req.clip.reverse + && existing.clip.loop_clip == req.clip.loop_clip + } + } + }) { + *existing_seq = (*existing_seq).min(seq_idx); + } else { + vq.push_back((seq_idx, req)); + } } } self.queue.cv.notify_all(); @@ -1224,23 +1333,31 @@ impl MediaPrefetchHandle { if q.cancelled { return; } - let raster_seq = q.raster.front().map(|(seq, _)| *seq); - let mut best_video: Option<(PathBuf, usize)> = None; + q.prune_stale(); + let best_raster = q + .raster + .iter() + .enumerate() + .min_by_key(|&(_, (seq, _))| *seq) + .map(|(idx, (seq, _))| (idx, *seq)); + let mut best_video: Option<(PathBuf, usize, usize)> = None; for (path, vq) in &q.videos { if q.active_videos.contains(path) { continue; } - if let Some(&(seq, _)) = vq.front() { - if best_video.as_ref().is_none_or(|&(_, bseq)| seq < bseq) { - best_video = Some((path.clone(), seq)); + if let Some((v_idx, &(seq, _))) = + vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq) + { + if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) { + best_video = Some((path.clone(), v_idx, seq)); } } } - let chosen_seq = match (raster_seq, &best_video) { - (Some(rs), Some((_, vs))) => rs.min(*vs), - (Some(rs), None) => rs, - (None, Some((_, vs))) => *vs, + let chosen_seq = match (best_raster, &best_video) { + (Some((_, rs)), Some((_, _, vs))) => rs.min(*vs), + (Some((_, rs)), None) => rs, + (None, Some((_, _, vs))) => *vs, (None, None) => { q = match queue.cv.wait(q) { Ok(g) => g, @@ -1271,9 +1388,9 @@ impl MediaPrefetchHandle { } } - if let Some((path, vs)) = best_video { - if raster_seq.is_none_or(|rs| vs <= rs) { - if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.pop_front()) { + if let Some((path, v_idx, vs)) = best_video { + if best_raster.is_none_or(|(_, rs)| vs <= rs) { + if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) { if q.videos.get(&path).is_some_and(VecDeque::is_empty) { q.videos.remove(&path); } @@ -1282,9 +1399,11 @@ impl MediaPrefetchHandle { } } } - if let Some((_, job)) = q.raster.pop_front() { - q.queued_raster_keys.remove(&job.cache_key); - break PrefetchWorkItem::Raster(job); + if let Some((r_idx, _)) = best_raster { + if let Some((_, job)) = q.raster.remove(r_idx) { + q.queued_raster_keys.remove(&job.cache_key); + break PrefetchWorkItem::Raster(job); + } } } }; @@ -1306,17 +1425,8 @@ impl MediaPrefetchHandle { shared: &shared, key: Some(job.cache_key.clone()), }; - if let Some(decoded) = decode_job(&job, false) { - if let Ok(mut state) = shared.state.lock() { - state.in_flight.remove(&job.cache_key); - guard.key = None; - if state.generation == cache_gen { - state.known_existing_paths.insert(job.cache_key.path.clone()); - state.insert_cached(job.cache_key, decoded); - } - shared.cv.notify_all(); - } - } + let decoded = decode_job(&job, false); + finish_raster_job(&shared, job.cache_key, cache_gen, &mut guard, decoded); } PrefetchWorkItem::Video(path, req) => { struct ActiveVideoGuard<'a> { @@ -1719,14 +1829,18 @@ fn collect_missing_loader_jobs_shared( if video_frame_in_range(&effective_clip, frame_i) && shared.path_exists_cached(base) { + let mut resolved_frame_idx = effective_clip + .length + .map(|_| compute_video_frame_idx(&effective_clip, frame_i, 1)); let need_decode = shared.state.lock().is_ok_and(|state| { match state.video_decoders.get(base) { - Some(slot) => slot.info.is_some_and(|info| { + Some(slot) => { let idx = compute_video_frame_idx( &effective_clip, frame_i, - info.nb_frames, + slot.info.nb_frames, ); + resolved_frame_idx = Some(idx); let cache_key = ImageCacheKey { path: base.to_path_buf(), frame_idx: idx, @@ -1735,7 +1849,7 @@ fn collect_missing_loader_jobs_shared( }; !state.images.contains_key(&cache_key) && !state.in_flight.contains(&cache_key) - }), + } None => true, } }); @@ -1747,6 +1861,7 @@ fn collect_missing_loader_jobs_shared( clip: effective_clip, frame_i, post_multiply: post_mult, + resolved_frame_idx, }); } } @@ -1877,6 +1992,7 @@ struct VideoFrameRequest { clip: ClipSpec, frame_i: i64, post_multiply: bool, + resolved_frame_idx: Option, } #[cfg(not(target_arch = "wasm32"))] @@ -2910,4 +3026,114 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn failed_opens_are_not_cached_and_evict_known_existing_paths() { + let dir = std::env::temp_dir().join(format!("fission_evict_test_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let bad_vid = dir.join("corrupt.mp4"); + std::fs::write(&bad_vid, b"not a valid mp4").unwrap(); + let mut cache = MediaCache::new(64); + assert!(cache.shared.path_exists_cached(&bad_vid)); + assert!(cache.shared.get_or_open_video_decoder(&bad_vid).is_none()); + assert_eq!(cache.video_decoder_count(), 0); + assert!(!cache.shared.state.lock().unwrap().known_existing_paths.contains(&bad_vid)); + + let img_path = dir.join("gone.png"); + image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 20, 30, 255])) + .save(&img_path) + .unwrap(); + assert!(cache.shared.path_exists_cached(&img_path)); + std::fs::remove_file(&img_path).unwrap(); + let clip = ClipSpec { + filename: img_path.to_string_lossy().into_owned(), + alternate_filename: None, + start_frame: 0, + length: Some(1), + trim_in: 0, + trim_out: 0, + global_start: 0, + global_end: 0, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }; + assert!(cache.load_clip(&clip, 0, false, [None; 4]).is_none()); + assert!(!cache.shared.path_exists_cached(&img_path)); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn prefetch_queue_prunes_stale_and_avoids_hol_blocking() { + let dir = std::env::temp_dir().join(format!("fission_hol_prefetch_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + for i in 0..=10 { + let p = dir.join(format!("seq_{i:04}.png")); + image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8 * 20, 10, 200, 255])) + .save(&p) + .unwrap(); + } + let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\"); + let p0 = dir.join("seq_0000.png"); + let comp_src = format!( + r#"Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 10 }}, + GlobalRange = {{ 0, 10 }}, + Tools = ordered() {{ + LD = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + FormatID = "PNGFormat", + StartFrame = 0, + Length = 11, + GlobalStart = 0, + GlobalEnd = 10, + }}, + }}, + }}, + }}, +}}"#, + esc(&p0) + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse hol prefetch comp"); + let target = comp.find_node("LD").unwrap(); + let clip = comp.node(target).clips[0].clone(); + let expr = model::ExprEngine::new(); + let mut cache = MediaCache::new(64); + + let mut handle = cache.start_frame_prefetch(2); + // Enqueue far-future seq=10 first (outside lookahead=2), then seq=1 (within lookahead). + handle.enqueue_frame(&comp, target, 10, 10.0, &expr, false); + handle.enqueue_frame(&comp, target, 1, 1.0, &expr, false); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while cache.entry_count() < 1 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(cache.entry_count(), 1); + let (_, _, img1, from_disk1) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap(); + assert!(!from_disk1, "seq=1 must not be head-of-line blocked by seq=10"); + assert_eq!(img1.rgba[0], 20); + + // Advancing current_seq past 10 prunes seq=10 cleanly. + handle.set_current_seq(11); + { + let q = handle.queue.state.lock().unwrap(); + assert!(q.raster.is_empty()); + assert!(q.queued_raster_keys.is_empty()); + } + handle.cancel(); + let _ = std::fs::remove_dir_all(&dir); + } }