authoravatarclover caruso<git@paperclover.net>2026-12-01 14:24:00-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 14:35:36-08:00
log0d06255b2ac49ce8492948def1d13109fbe6e99a
tree597b956af36d4d72d429e401a8d182fcb4c22852
parent181d489f7ee6df2510df91aab084020aeccbf112
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): vectorize macOS 4K video decode/rotation and harden media cache/staging pool


6 files changed, 626 insertions(+), 258 deletions(-)

crates/engine/build.rs+1
......@@ -8,6 +8,7 @@ fn main() {
88 .compile("av_decode");
99
1010 for fw in [
11 "Accelerate",
1112 "AVFoundation",
1213 "CoreMedia",
1314 "CoreVideo",
crates/engine/src/av_decode.m+188-38
......@@ -1,3 +1,4 @@
1#import <Accelerate/Accelerate.h>
12#import <AVFoundation/AVFoundation.h>
23#import <CoreFoundation/CoreFoundation.h>
34#import <CoreMedia/CoreMedia.h>
......@@ -7,6 +8,9 @@
78#include <stdint.h>
89#include <stddef.h>
910#include <string.h>
11#if defined(__aarch64__)
12#include <arm_neon.h>
13#endif
1014
1115#pragma clang diagnostic push
1216#pragma clang diagnostic ignored "-Wdeprecated-declarations"
......@@ -76,6 +80,48 @@
7680
7781typedef struct AvVideoDecoder AvVideoDecoder;
7882
83static inline void bgra_to_rgba_pixel(const uint8_t *src, uint8_t *dst) {
84 dst[0] = src[2];
85 dst[1] = src[1];
86 dst[2] = src[0];
87 dst[3] = src[3];
88}
89
90#if defined(__aarch64__)
91static inline void neon_transpose4x4_bgra_to_rgba(
92 const uint8_t *r0,
93 const uint8_t *r1,
94 const uint8_t *r2,
95 const uint8_t *r3,
96 uint8x16_t swizTbl,
97 uint8_t *d0Out,
98 uint8_t *d1Out,
99 uint8_t *d2Out,
100 uint8_t *d3Out
101) {
102 uint32x4_t p0 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r0), swizTbl));
103 uint32x4_t p1 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r1), swizTbl));
104 uint32x4_t p2 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r2), swizTbl));
105 uint32x4_t p3 = vreinterpretq_u32_u8(vqtbl1q_u8(vld1q_u8(r3), swizTbl));
106 uint32x4_t t0 = vtrn1q_u32(p0, p1);
107 uint32x4_t t1 = vtrn2q_u32(p0, p1);
108 uint32x4_t t2 = vtrn1q_u32(p2, p3);
109 uint32x4_t t3 = vtrn2q_u32(p2, p3);
110 uint32x4_t d0 = vreinterpretq_u32_u64(
111 vtrn1q_u64(vreinterpretq_u64_u32(t0), vreinterpretq_u64_u32(t2)));
112 uint32x4_t d1 = vreinterpretq_u32_u64(
113 vtrn1q_u64(vreinterpretq_u64_u32(t1), vreinterpretq_u64_u32(t3)));
114 uint32x4_t d2 = vreinterpretq_u32_u64(
115 vtrn2q_u64(vreinterpretq_u64_u32(t0), vreinterpretq_u64_u32(t2)));
116 uint32x4_t d3 = vreinterpretq_u32_u64(
117 vtrn2q_u64(vreinterpretq_u64_u32(t1), vreinterpretq_u64_u32(t3)));
118 vst1q_u8(d0Out, vreinterpretq_u8_u32(d0));
119 vst1q_u8(d1Out, vreinterpretq_u8_u32(d1));
120 vst1q_u8(d2Out, vreinterpretq_u8_u32(d2));
121 vst1q_u8(d3Out, vreinterpretq_u8_u32(d3));
122}
123#endif
124
79125static int copy_bgra_to_rgba(
80126 CVImageBufferRef imgBuf,
81127 uint32_t outW,
......@@ -102,61 +148,165 @@ static int copy_bgra_to_rgba(
102148 const uint8_t *base = (const uint8_t *)CVPixelBufferGetBaseAddress(imgBuf);
103149
104150 int ok = 0;
105 if (base) {
151 if (base && srcW > 0 && srcH > 0 && bpr >= srcW * 4) {
152 const size_t dstBpr = (size_t)outW * 4;
153 const uint8_t permuteMap[4] = { 2, 1, 0, 3 };
154 // Disable internal vImage GCD tiling so parallel decoder threads do not oversubscribe cores.
155 const vImage_Flags vflags = kvImageDoNotTile;
156 vImage_Buffer srcBuf = { (void *)base, (vImagePixelCount)srcH, (vImagePixelCount)srcW, bpr };
157 vImage_Buffer dstBuf = { (void *)outRgba, (vImagePixelCount)outH, (vImagePixelCount)outW, dstBpr };
158
106159 if (rotation == 0 && srcW == outW && srcH == outH) {
107 for (size_t y = 0; y < srcH; y++) {
108 const uint8_t *src = base + y * bpr;
109 uint8_t *dst = outRgba + y * (size_t)outW * 4;
110 for (size_t x = 0; x < srcW; x++) {
111 dst[x * 4 + 0] = src[x * 4 + 2];
112 dst[x * 4 + 1] = src[x * 4 + 1];
113 dst[x * 4 + 2] = src[x * 4 + 0];
114 dst[x * 4 + 3] = src[x * 4 + 3];
160 if (vImagePermuteChannels_ARGB8888(&srcBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) {
161 ok = 1;
162 } else {
163 for (size_t y = 0; y < srcH; y++) {
164 const uint8_t *src = base + y * bpr;
165 uint8_t *dst = outRgba + y * dstBpr;
166 for (size_t x = 0; x < srcW; x++) {
167 bgra_to_rgba_pixel(src + x * 4, dst + x * 4);
168 }
115169 }
170 ok = 1;
116171 }
117 ok = 1;
118172 } else if (rotation == 90 && srcH == outW && srcW == outH) {
119 for (size_t y = 0; y < srcH; y++) {
120 const uint8_t *src = base + y * bpr;
121 size_t dx = srcH - 1 - y;
122 for (size_t x = 0; x < srcW; x++) {
123 size_t dy = x;
124 uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4;
125 dst[0] = src[x * 4 + 2];
126 dst[1] = src[x * 4 + 1];
127 dst[2] = src[x * 4 + 0];
128 dst[3] = src[x * 4 + 3];
173#if defined(__aarch64__)
174 const uint8_t swizTblBytes[16] = { 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 };
175 uint8x16_t swizTbl = vld1q_u8(swizTblBytes);
176 const size_t B = 32;
177 for (size_t by = 0; by < srcH; by += B) {
178 size_t bh = (by + B <= srcH) ? B : (srcH - by);
179 for (size_t bx = 0; bx < srcW; bx += B) {
180 size_t bw = (bx + B <= srcW) ? B : (srcW - bx);
181 size_t y = 0;
182 for (; y + 4 <= bh; y += 4) {
183 size_t sy = by + y;
184 size_t dxBase = srcH - 1 - (sy + 3);
185 const uint8_t *r0 = base + (sy + 0) * bpr + bx * 4;
186 const uint8_t *r1 = base + (sy + 1) * bpr + bx * 4;
187 const uint8_t *r2 = base + (sy + 2) * bpr + bx * 4;
188 const uint8_t *r3 = base + (sy + 3) * bpr + bx * 4;
189 size_t x = 0;
190 for (; x + 4 <= bw; x += 4) {
191 uint8_t *dst = outRgba + (bx + x) * dstBpr + dxBase * 4;
192 neon_transpose4x4_bgra_to_rgba(
193 r3 + x * 4, r2 + x * 4, r1 + x * 4, r0 + x * 4,
194 swizTbl,
195 dst + 0 * dstBpr, dst + 1 * dstBpr, dst + 2 * dstBpr, dst + 3 * dstBpr
196 );
197 }
198 for (; x < bw; x++) {
199 size_t dy = bx + x;
200 for (size_t k = 0; k < 4; k++) {
201 size_t dx = srcH - 1 - (sy + k);
202 bgra_to_rgba_pixel(
203 base + (sy + k) * bpr + (bx + x) * 4,
204 outRgba + dy * dstBpr + dx * 4
205 );
206 }
207 }
208 }
209 for (; y < bh; y++) {
210 size_t sy = by + y;
211 size_t dx = srcH - 1 - sy;
212 const uint8_t *src = base + sy * bpr + bx * 4;
213 for (size_t x = 0; x < bw; x++) {
214 size_t dy = bx + x;
215 bgra_to_rgba_pixel(src + x * 4, outRgba + dy * dstBpr + dx * 4);
216 }
217 }
129218 }
130219 }
131220 ok = 1;
221#else
222 const Pixel_8888 back = { 0, 0, 0, 0 };
223 if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate90DegreesClockwise, back, vflags) == kvImageNoError &&
224 vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) {
225 ok = 1;
226 }
227#endif
132228 } else if (rotation == 180 && srcW == outW && srcH == outH) {
229#if defined(__aarch64__)
230 const uint8_t revSwizBytes[16] = { 14, 13, 12, 15, 10, 9, 8, 11, 6, 5, 4, 7, 2, 1, 0, 3 };
231 uint8x16_t revSwiz = vld1q_u8(revSwizBytes);
133232 for (size_t y = 0; y < srcH; y++) {
134233 const uint8_t *src = base + y * bpr;
135 size_t dy = srcH - 1 - y;
136 for (size_t x = 0; x < srcW; x++) {
137 size_t dx = srcW - 1 - x;
138 uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4;
139 dst[0] = src[x * 4 + 2];
140 dst[1] = src[x * 4 + 1];
141 dst[2] = src[x * 4 + 0];
142 dst[3] = src[x * 4 + 3];
234 uint8_t *dstRow = outRgba + (srcH - 1 - y) * dstBpr;
235 size_t x = 0;
236 for (; x + 4 <= srcW; x += 4) {
237 uint8x16_t v = vld1q_u8(src + x * 4);
238 vst1q_u8(dstRow + (srcW - x - 4) * 4, vqtbl1q_u8(v, revSwiz));
239 }
240 for (; x < srcW; x++) {
241 bgra_to_rgba_pixel(src + x * 4, dstRow + (srcW - 1 - x) * 4);
143242 }
144243 }
145244 ok = 1;
245#else
246 const Pixel_8888 back = { 0, 0, 0, 0 };
247 if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate180DegreesClockwise, back, vflags) == kvImageNoError &&
248 vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) {
249 ok = 1;
250 }
251#endif
146252 } else if (rotation == 270 && srcH == outW && srcW == outH) {
147 for (size_t y = 0; y < srcH; y++) {
148 const uint8_t *src = base + y * bpr;
149 size_t dx = y;
150 for (size_t x = 0; x < srcW; x++) {
151 size_t dy = srcW - 1 - x;
152 uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4;
153 dst[0] = src[x * 4 + 2];
154 dst[1] = src[x * 4 + 1];
155 dst[2] = src[x * 4 + 0];
156 dst[3] = src[x * 4 + 3];
253#if defined(__aarch64__)
254 const uint8_t swizTblBytes[16] = { 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 };
255 uint8x16_t swizTbl = vld1q_u8(swizTblBytes);
256 const size_t B = 32;
257 for (size_t by = 0; by < srcH; by += B) {
258 size_t bh = (by + B <= srcH) ? B : (srcH - by);
259 for (size_t bx = 0; bx < srcW; bx += B) {
260 size_t bw = (bx + B <= srcW) ? B : (srcW - bx);
261 size_t y = 0;
262 for (; y + 4 <= bh; y += 4) {
263 size_t sy = by + y;
264 const uint8_t *r0 = base + (sy + 0) * bpr + bx * 4;
265 const uint8_t *r1 = base + (sy + 1) * bpr + bx * 4;
266 const uint8_t *r2 = base + (sy + 2) * bpr + bx * 4;
267 const uint8_t *r3 = base + (sy + 3) * bpr + bx * 4;
268 size_t x = 0;
269 for (; x + 4 <= bw; x += 4) {
270 size_t dyTop = srcW - 1 - (bx + x);
271 neon_transpose4x4_bgra_to_rgba(
272 r0 + x * 4, r1 + x * 4, r2 + x * 4, r3 + x * 4,
273 swizTbl,
274 outRgba + (dyTop - 0) * dstBpr + sy * 4,
275 outRgba + (dyTop - 1) * dstBpr + sy * 4,
276 outRgba + (dyTop - 2) * dstBpr + sy * 4,
277 outRgba + (dyTop - 3) * dstBpr + sy * 4
278 );
279 }
280 for (; x < bw; x++) {
281 size_t dy = srcW - 1 - (bx + x);
282 for (size_t k = 0; k < 4; k++) {
283 size_t dx = sy + k;
284 bgra_to_rgba_pixel(
285 base + (sy + k) * bpr + (bx + x) * 4,
286 outRgba + dy * dstBpr + dx * 4
287 );
288 }
289 }
290 }
291 for (; y < bh; y++) {
292 size_t sy = by + y;
293 size_t dx = sy;
294 const uint8_t *src = base + sy * bpr + bx * 4;
295 for (size_t x = 0; x < bw; x++) {
296 size_t dy = srcW - 1 - (bx + x);
297 bgra_to_rgba_pixel(src + x * 4, outRgba + dy * dstBpr + dx * 4);
298 }
299 }
157300 }
158301 }
159302 ok = 1;
303#else
304 const Pixel_8888 back = { 0, 0, 0, 0 };
305 if (vImageRotate90_ARGB8888(&srcBuf, &dstBuf, kRotate270DegreesClockwise, back, vflags) == kvImageNoError &&
306 vImagePermuteChannels_ARGB8888(&dstBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) {
307 ok = 1;
308 }
309#endif
160310 }
161311 }
162312
crates/engine/src/bin/render_check.rs-21
......@@ -111,13 +111,6 @@ fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box<dyn std::error::
111111 };
112112
113113 engine.set_cache_mode(CacheMode::Enabled);
114 engine.media.preload_frame_loaders_with_proxy(
115 comp,
116 target,
117 frame,
118 &engine.expr,
119 engine.use_proxy_clips,
120 );
121114 let (tex, cold) = engine.evaluate(comp, target, frame);
122115 let (_, warm) = engine.evaluate(comp, target, frame);
123116 engine.bust_gpu_cache();
......@@ -245,13 +238,6 @@ fn run_batch_render(
245238 let mut loop_err: Option<String> = None;
246239 const PREFETCH_LOOKAHEAD: usize = 12;
247240 engine.prewarm_core_pipelines();
248 engine.media.preload_frame_loaders_with_proxy(
249 &comp,
250 target,
251 start as f64,
252 &engine.expr,
253 engine.use_proxy_clips,
254 );
255241 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
256242 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);
257243 for (k, f) in ((start + 1)..=seed_end).enumerate() {
......@@ -782,13 +768,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
782768 if profile {
783769 engine.cache.begin_frame_profile_with_comp(&comp);
784770 }
785 engine.media.preload_frame_loaders_with_proxy(
786 &comp,
787 target,
788 frame,
789 &engine.expr,
790 engine.use_proxy_clips,
791 );
792771 let (tex, cold) = engine.evaluate(&comp, target, frame);
793772 let cold_profile = if profile {
794773 engine.cache.take_frame_profile().map(|mut fp| {
crates/engine/src/eval/io.rs+22
......@@ -123,6 +123,24 @@ impl Engine {
123123 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
124124 let needed = u64::from(padded_bpr) * u64::from(h);
125125 if let Some(buf) = self.media.acquire_upload_staging(&self.device, needed) {
126 struct StagingGuard<'a> {
127 media: &'a crate::media::MediaCache,
128 cap: u64,
129 armed: bool,
130 }
131 impl Drop for StagingGuard<'_> {
132 fn drop(&mut self) {
133 if self.armed {
134 self.media.release_failed_upload_staging(self.cap);
135 }
136 }
137 }
138 let mut staging_guard = StagingGuard {
139 media: &self.media,
140 cap: buf.size(),
141 armed: true,
142 };
143 let mut copied = false;
126144 if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() {
127145 if padded_bpr == unpadded_bpr {
128146 let total = (unpadded_bpr as usize) * (h as usize);
......@@ -137,6 +155,9 @@ impl Engine {
137155 }
138156 }
139157 drop(view);
158 copied = true;
159 }
160 if copied {
140161 buf.unmap();
141162 enc.copy_buffer_to_texture(
142163 wgpu::TexelCopyBufferInfo {
......@@ -154,6 +175,7 @@ impl Engine {
154175 depth_or_array_layers: 1,
155176 },
156177 );
178 staging_guard.armed = false;
157179 self.media.recycle_upload_staging(buf);
158180 return;
159181 }
crates/engine/src/export.rs+86-96
......@@ -308,13 +308,6 @@ pub fn export_saver_png_sequence_with_progress(
308308 let mut loop_err: Option<String> = None;
309309 const PREFETCH_LOOKAHEAD: usize = 12;
310310 engine.prewarm_core_pipelines();
311 engine.media.preload_frame_loaders_with_proxy(
312 comp,
313 target,
314 start as f64,
315 &engine.expr,
316 engine.use_proxy_clips,
317 );
318311 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
319312 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);
320313 for (k, f) in ((start + 1)..=seed_end).enumerate() {
......@@ -728,13 +721,7 @@ pub fn export_node_video_ffmpeg_with_progress(
728721 let node_name = comp.node(opts.target).name.clone();
729722
730723 // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output.
731 engine.media.preload_frame_loaders_with_proxy(
732 comp,
733 opts.target,
734 start as f64,
735 &engine.expr,
736 engine.use_proxy_clips,
737 );
724 engine.prewarm_core_pipelines();
738725 let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64);
739726 if first_tex.size[0] == 0 || first_tex.size[1] == 0 {
740727 return Err(format!(
......@@ -975,110 +962,113 @@ pub fn export_node_video_ffmpeg_with_progress(
975962 ctrl.update_progress(&first_prog);
976963 }
977964 on_progress(first_prog);
978
979 const PREFETCH_LOOKAHEAD: usize = 12;
980 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
981 let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end);
982 for (k, f) in ((start + 1)..=seed_end).enumerate() {
983 prefetch.enqueue_frame(
984 comp,
985 opts.target,
986 k,
987 f as f64,
988 &engine.expr,
989 engine.use_proxy_clips,
990 );
991 }
992 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;
993 for (idx, frame) in ((start + 1)..=end).enumerate() {
994 if writer_failed.load(Ordering::Acquire) {
995 break;
996 }
997 if control.is_some_and(ExportControl::is_cancelled) {
998 cancelled = true;
999 break;
1000 }
1001 prefetch.set_current_seq(idx);
1002 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;
1003 if ahead_frame <= end {
965 if control.is_some_and(ExportControl::is_cancelled) {
966 cancelled = true;
967 } else if start < end {
968 const PREFETCH_LOOKAHEAD: usize = 12;
969 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
970 let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end);
971 for (k, f) in ((start + 1)..=seed_end).enumerate() {
1004972 prefetch.enqueue_frame(
1005973 comp,
1006974 opts.target,
1007 idx + PREFETCH_LOOKAHEAD,
1008 ahead_frame as f64,
975 k,
976 f as f64,
1009977 &engine.expr,
1010978 engine.use_proxy_clips,
1011979 );
1012980 }
1013 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
1014 let next_rb = match engine.begin_readback_rgba(&tex) {
1015 Ok(rb) => rb,
1016 Err(e) => {
1017 pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
981 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;
982 for (idx, frame) in ((start + 1)..=end).enumerate() {
983 if writer_failed.load(Ordering::Acquire) {
1018984 break;
1019985 }
1020 };
1021 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) =
1022 pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms))
1023 {
1024 let pixels = match prev_rb.finish(engine) {
1025 Ok(px) => px,
1026 Err(e) => {
1027 pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
1028 break;
1029 }
1030 };
1031986 if control.is_some_and(ExportControl::is_cancelled) {
1032987 cancelled = true;
1033988 break;
1034989 }
1035 if tx.send((prev_frame, prev_size, pixels)).is_err() {
1036 break;
990 prefetch.set_current_seq(idx);
991 let ahead_frame = frame + PREFETCH_LOOKAHEAD as i64;
992 if ahead_frame <= end {
993 prefetch.enqueue_frame(
994 comp,
995 opts.target,
996 idx + PREFETCH_LOOKAHEAD,
997 ahead_frame as f64,
998 &engine.expr,
999 engine.use_proxy_clips,
1000 );
10371001 }
1038 let prog = make_progress(
1039 prev_frame,
1040 prev_idx + 1,
1041 total,
1042 prev_ms,
1043 opts.out_path.clone(),
1044 node_name.clone(),
1045 t0,
1046 );
1047 if let Some(ctrl) = control {
1048 ctrl.update_progress(&prog);
1002 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
1003 let next_rb = match engine.begin_readback_rgba(&tex) {
1004 Ok(rb) => rb,
1005 Err(e) => {
1006 pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
1007 break;
1008 }
1009 };
1010 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) =
1011 pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms))
1012 {
1013 let pixels = match prev_rb.finish(engine) {
1014 Ok(px) => px,
1015 Err(e) => {
1016 pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
1017 break;
1018 }
1019 };
1020 if control.is_some_and(ExportControl::is_cancelled) {
1021 cancelled = true;
1022 break;
1023 }
1024 if tx.send((prev_frame, prev_size, pixels)).is_err() {
1025 break;
1026 }
1027 let prog = make_progress(
1028 prev_frame,
1029 prev_idx + 1,
1030 total,
1031 prev_ms,
1032 opts.out_path.clone(),
1033 node_name.clone(),
1034 t0,
1035 );
1036 if let Some(ctrl) = control {
1037 ctrl.update_progress(&prog);
1038 }
1039 on_progress(prog);
10491040 }
1050 on_progress(prog);
10511041 }
1052 }
1053 if pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) {
1054 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() {
1055 match prev_rb.finish(engine) {
1056 Ok(pixels) => {
1057 if control.is_some_and(ExportControl::is_cancelled) {
1058 cancelled = true;
1059 } else if tx.send((prev_frame, prev_size, pixels)).is_ok() {
1060 let prog = make_progress(
1061 prev_frame,
1062 prev_idx + 1,
1063 total,
1064 prev_ms,
1065 opts.out_path.clone(),
1066 node_name.clone(),
1067 t0,
1068 );
1069 if let Some(ctrl) = control {
1070 ctrl.update_progress(&prog);
1042 if pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) {
1043 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() {
1044 match prev_rb.finish(engine) {
1045 Ok(pixels) => {
1046 if control.is_some_and(ExportControl::is_cancelled) {
1047 cancelled = true;
1048 } else if tx.send((prev_frame, prev_size, pixels)).is_ok() {
1049 let prog = make_progress(
1050 prev_frame,
1051 prev_idx + 1,
1052 total,
1053 prev_ms,
1054 opts.out_path.clone(),
1055 node_name.clone(),
1056 t0,
1057 );
1058 if let Some(ctrl) = control {
1059 ctrl.update_progress(&prog);
1060 }
1061 on_progress(prog);
10711062 }
1072 on_progress(prog);
10731063 }
1074 }
1075 Err(e) => {
1076 pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
1064 Err(e) => {
1065 pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
1066 }
10771067 }
10781068 }
10791069 }
1070 drop(prefetch);
10801071 }
1081 drop(prefetch);
10821072 }
10831073 drop(tx);
10841074
crates/engine/src/media.rs+329-103
......@@ -21,8 +21,8 @@ use crate::text_engine;
2121use model::{Node, default_main_input_port};
2222use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint};
2323#[cfg(not(target_arch = "wasm32"))]
24use std::collections::VecDeque;
25use std::collections::{HashMap, HashSet};
24use std::collections::{HashSet, VecDeque};
25use std::collections::HashMap;
2626use std::path::{Path, PathBuf};
2727use std::process::Command;
2828#[cfg(not(target_arch = "wasm32"))]
......@@ -195,7 +195,7 @@ struct ImageCacheKey {
195195}
196196
197197struct VideoDecoderSlot {
198 info: Option<VideoInfo>,
198 info: VideoInfo,
199199 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,
200200 last_used: u64,
201201}
......@@ -212,6 +212,7 @@ struct MediaState {
212212 in_flight: HashSet<ImageCacheKey>,
213213 #[cfg(not(target_arch = "wasm32"))]
214214 opening_videos: HashSet<PathBuf>,
215 #[cfg(not(target_arch = "wasm32"))]
215216 known_existing_paths: HashSet<PathBuf>,
216217}
217218
......@@ -229,10 +230,30 @@ impl MediaState {
229230 in_flight: HashSet::new(),
230231 #[cfg(not(target_arch = "wasm32"))]
231232 opening_videos: HashSet::new(),
233 #[cfg(not(target_arch = "wasm32"))]
232234 known_existing_paths: HashSet::new(),
233235 }
234236 }
235237
238 fn record_existing_path(&mut self, path: &Path) {
239 #[cfg(not(target_arch = "wasm32"))]
240 {
241 if self.known_existing_paths.len() > 8192 {
242 self.known_existing_paths.clear();
243 }
244 self.known_existing_paths.insert(path.to_path_buf());
245 }
246 #[cfg(target_arch = "wasm32")]
247 let _ = path;
248 }
249
250 fn evict_existing_path(&mut self, path: &Path) {
251 #[cfg(not(target_arch = "wasm32"))]
252 self.known_existing_paths.remove(path);
253 #[cfg(target_arch = "wasm32")]
254 let _ = path;
255 }
256
236257 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
237258 let bytes = decoded.byte_size();
238259 self.tick += 1;
......@@ -256,16 +277,20 @@ impl MediaState {
256277 fn put_video_decoder(
257278 &mut self,
258279 path: PathBuf,
259 info: Option<VideoInfo>,
280 info: VideoInfo,
260281 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,
261 ) {
282 ) -> Vec<VideoDecoderSlot> {
283 let mut evicted = Vec::new();
262284 self.tick += 1;
263285 let now_tick = self.tick;
286 let new_slot = VideoDecoderSlot {
287 info,
288 decoder,
289 last_used: now_tick,
290 };
264291 if let Some(slot) = self.video_decoders.get_mut(&path) {
265 slot.info = info;
266 slot.decoder = decoder;
267 slot.last_used = now_tick;
268 return;
292 evicted.push(std::mem::replace(slot, new_slot));
293 return evicted;
269294 }
270295 while self.video_decoders.len() >= MAX_VIDEO_DECODERS {
271296 let Some(oldest_path) = self
......@@ -276,16 +301,12 @@ impl MediaState {
276301 else {
277302 break;
278303 };
279 self.video_decoders.remove(&oldest_path);
280 }
281 self.video_decoders.insert(
282 path,
283 VideoDecoderSlot {
284 info,
285 decoder,
286 last_used: now_tick,
287 },
288 );
304 if let Some(removed) = self.video_decoders.remove(&oldest_path) {
305 evicted.push(removed);
306 }
307 }
308 self.video_decoders.insert(path, new_slot);
309 evicted
289310 }
290311}
291312
......@@ -308,18 +329,25 @@ impl MediaShared {
308329 if virtual_bytes(path).is_some() {
309330 return true;
310331 }
311 if let Ok(state) = self.state.lock() {
312 if state.known_existing_paths.contains(path) || state.video_decoders.contains_key(path) {
313 return true;
332 #[cfg(not(target_arch = "wasm32"))]
333 {
334 if let Ok(state) = self.state.lock() {
335 if state.known_existing_paths.contains(path) || state.video_decoders.contains_key(path) {
336 return true;
337 }
314338 }
315 }
316 if path.exists() {
317 if let Ok(mut state) = self.state.lock() {
318 state.known_existing_paths.insert(path.to_path_buf());
339 if path.exists() {
340 if let Ok(mut state) = self.state.lock() {
341 state.record_existing_path(path);
342 }
343 true
344 } else {
345 false
319346 }
320 true
321 } else {
322 false
347 }
348 #[cfg(target_arch = "wasm32")]
349 {
350 path.exists()
323351 }
324352 }
325353
......@@ -341,7 +369,7 @@ impl MediaShared {
341369 let now_tick = guard.tick;
342370 if let Some(slot) = guard.video_decoders.get_mut(path) {
343371 slot.last_used = now_tick;
344 return slot.info.map(|info| (info, Arc::clone(&slot.decoder)));
372 return Some((slot.info, Arc::clone(&slot.decoder)));
345373 }
346374
347375 #[cfg(not(target_arch = "wasm32"))]
......@@ -353,37 +381,51 @@ impl MediaShared {
353381
354382 struct OpenGuard<'a> {
355383 shared: &'a MediaShared,
356 path: PathBuf,
384 path: Option<PathBuf>,
357385 }
358386 impl Drop for OpenGuard<'_> {
359387 fn drop(&mut self) {
360388 #[cfg(not(target_arch = "wasm32"))]
361 if let Ok(mut state) = self.shared.state.lock() {
362 state.opening_videos.remove(&self.path);
363 self.shared.cv.notify_all();
389 if let Some(path) = self.path.take() {
390 if let Ok(mut state) = self.shared.state.lock() {
391 state.opening_videos.remove(&path);
392 self.shared.cv.notify_all();
393 }
364394 }
365395 #[cfg(target_arch = "wasm32")]
366396 let _ = (&self.shared, &self.path);
367397 }
368398 }
369 let _open_guard = OpenGuard {
399 let mut open_guard = OpenGuard {
370400 shared: self,
371 path: path.to_path_buf(),
401 path: Some(path.to_path_buf()),
372402 };
373403
374404 let decoder = open_video_decoder(path);
375405 let info = decoder.as_ref().map(|d| d.info());
376406 let slot_arc = Arc::new(Mutex::new(decoder));
377407
408 let mut evicted_decoders = Vec::new();
378409 if let Ok(mut state) = self.state.lock() {
379410 #[cfg(not(target_arch = "wasm32"))]
380411 state.opening_videos.remove(path);
381 if state.generation == cache_gen {
382 state.put_video_decoder(path.to_path_buf(), info, Arc::clone(&slot_arc));
412 open_guard.path = None;
413 if let Some(dec_info) = info {
414 if state.generation == cache_gen {
415 state.record_existing_path(path);
416 evicted_decoders = state.put_video_decoder(
417 path.to_path_buf(),
418 dec_info,
419 Arc::clone(&slot_arc),
420 );
421 }
422 } else {
423 state.evict_existing_path(path);
383424 }
384425 #[cfg(not(target_arch = "wasm32"))]
385426 self.cv.notify_all();
386427 }
428 drop(evicted_decoders);
387429 info.map(|i| (i, slot_arc))
388430 }
389431}
......@@ -550,6 +592,10 @@ impl UploadStagingPool {
550592 rx: None,
551593 });
552594 }
595
596 pub(crate) fn release_failed_upload(&mut self, capacity: u64) {
597 self.total_bytes = self.total_bytes.saturating_sub(capacity);
598 }
553599}
554600
555601pub struct MediaCache {
......@@ -591,14 +637,17 @@ impl MediaCache {
591637 }
592638
593639 pub fn clear(&mut self) {
640 let mut cleared_decoders = Vec::new();
594641 if let Ok(mut state) = self.shared.state.lock() {
595642 state.images.clear();
596643 state.lru.clear();
597 state.video_decoders.clear();
644 cleared_decoders.extend(state.video_decoders.drain().map(|(_, slot)| slot));
598645 state.total_bytes = 0;
599646 state.generation = state.generation.wrapping_add(1);
647 #[cfg(not(target_arch = "wasm32"))]
600648 state.known_existing_paths.clear();
601649 }
650 drop(cleared_decoders);
602651 #[cfg(not(target_arch = "wasm32"))]
603652 if let Ok(mut pool) = self.staging_pool.lock() {
604653 pool.clear();
......@@ -609,16 +658,22 @@ impl MediaCache {
609658 pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option<wgpu::Buffer> {
610659 self.staging_pool
611660 .lock()
612 .expect("staging pool lock")
661 .ok()?
613662 .acquire(device, needed)
614663 }
615664
616665 #[cfg(not(target_arch = "wasm32"))]
617666 pub(crate) fn recycle_upload_staging(&self, buffer: wgpu::Buffer) {
618 self.staging_pool
619 .lock()
620 .expect("staging pool lock")
621 .finish_upload(buffer);
667 if let Ok(mut pool) = self.staging_pool.lock() {
668 pool.finish_upload(buffer);
669 }
670 }
671
672 #[cfg(not(target_arch = "wasm32"))]
673 pub(crate) fn release_failed_upload_staging(&self, capacity: u64) {
674 if let Ok(mut pool) = self.staging_pool.lock() {
675 pool.release_failed_upload(capacity);
676 }
622677 }
623678
624679 /// Marks submitted upload staging buffers ready to begin asynchronous write-mapping
......@@ -800,9 +855,15 @@ impl MediaCache {
800855 exr_channels[2],
801856 exr_channels[3],
802857 false,
803 )?
858 )
804859 } else {
805 decode_raster_image(&resolved, post_multiply, true)?
860 decode_raster_image(&resolved, post_multiply, true)
861 };
862 let Some(decoded) = decoded else {
863 if let Ok(mut state) = self.shared.state.lock() {
864 state.evict_existing_path(&resolved);
865 }
866 return None;
806867 };
807868
808869 if let Ok(mut state) = self.shared.state.lock() {
......@@ -812,7 +873,7 @@ impl MediaCache {
812873 in_flight_guard.key = None;
813874 }
814875 if state.generation == cache_gen {
815 state.known_existing_paths.insert(resolved.clone());
876 state.record_existing_path(&resolved);
816877 state.insert_cached(cache_key, decoded.clone());
817878 }
818879 #[cfg(not(target_arch = "wasm32"))]
......@@ -848,9 +909,6 @@ impl MediaCache {
848909 }
849910 #[cfg(not(target_arch = "wasm32"))]
850911 {
851 if let Ok(mut pool) = self.staging_pool.lock() {
852 pool.mark_frame_start();
853 }
854912 let mut visited = HashSet::new();
855913 let mut jobs = MissingJobs::default();
856914 collect_missing_loader_jobs_shared(
......@@ -933,17 +991,8 @@ impl MediaCache {
933991 shared: &self.shared,
934992 key: Some(job.cache_key.clone()),
935993 };
936 if let Some(decoded) = decode_job(&job, true) {
937 if let Ok(mut state) = self.shared.state.lock() {
938 state.in_flight.remove(&job.cache_key);
939 guard.key = None;
940 if state.generation == cache_gen {
941 state.known_existing_paths.insert(job.cache_key.path.clone());
942 state.insert_cached(job.cache_key, decoded);
943 }
944 self.shared.cv.notify_all();
945 }
946 }
994 let decoded = decode_job(&job, true);
995 finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded);
947996 return;
948997 }
949998 self.decode_jobs_parallel(jobs);
......@@ -1065,17 +1114,14 @@ impl MediaCache {
10651114 shared: &self.shared,
10661115 key: Some(job.cache_key.clone()),
10671116 };
1068 if let Some(decoded) = decode_job(job, false) {
1069 if let Ok(mut state) = self.shared.state.lock() {
1070 state.in_flight.remove(&job.cache_key);
1071 guard.key = None;
1072 if state.generation == cache_gen {
1073 state.known_existing_paths.insert(job.cache_key.path.clone());
1074 state.insert_cached(job.cache_key.clone(), decoded);
1075 }
1076 self.shared.cv.notify_all();
1077 }
1078 }
1117 let decoded = decode_job(job, false);
1118 finish_raster_job(
1119 &self.shared,
1120 job.cache_key.clone(),
1121 cache_gen,
1122 &mut guard,
1123 decoded,
1124 );
10791125 }
10801126 });
10811127 }
......@@ -1083,6 +1129,29 @@ impl MediaCache {
10831129 }
10841130}
10851131
1132#[cfg(not(target_arch = "wasm32"))]
1133fn finish_raster_job(
1134 shared: &MediaShared,
1135 key: ImageCacheKey,
1136 cache_gen: u64,
1137 guard: &mut InFlightGuard<'_>,
1138 decoded: Option<DecodedImage>,
1139) {
1140 if let Ok(mut state) = shared.state.lock() {
1141 state.in_flight.remove(&key);
1142 guard.key = None;
1143 if let Some(decoded) = decoded {
1144 if state.generation == cache_gen {
1145 state.record_existing_path(&key.path);
1146 state.insert_cached(key, decoded);
1147 }
1148 } else {
1149 state.evict_existing_path(&key.path);
1150 }
1151 shared.cv.notify_all();
1152 }
1153}
1154
10861155#[cfg(not(target_arch = "wasm32"))]
10871156struct PrefetchQueueState {
10881157 raster: VecDeque<(usize, PreloadJob)>,
......@@ -1094,6 +1163,28 @@ struct PrefetchQueueState {
10941163 cancelled: bool,
10951164}
10961165
1166#[cfg(not(target_arch = "wasm32"))]
1167impl PrefetchQueueState {
1168 fn prune_stale(&mut self) {
1169 let cur = self.current_seq;
1170 if self.raster.iter().any(|&(seq, _)| seq < cur) {
1171 let mut kept = VecDeque::with_capacity(self.raster.len());
1172 while let Some((seq, job)) = self.raster.pop_front() {
1173 if seq >= cur {
1174 kept.push_back((seq, job));
1175 } else {
1176 self.queued_raster_keys.remove(&job.cache_key);
1177 }
1178 }
1179 self.raster = kept;
1180 }
1181 self.videos.retain(|_, vq| {
1182 vq.retain(|&(seq, _)| seq >= cur);
1183 !vq.is_empty()
1184 });
1185 }
1186}
1187
10971188#[cfg(not(target_arch = "wasm32"))]
10981189struct PrefetchQueue {
10991190 state: Mutex<PrefetchQueueState>,
......@@ -1154,6 +1245,7 @@ impl MediaPrefetchHandle {
11541245 pub fn set_current_seq(&self, seq_idx: usize) {
11551246 if let Ok(mut q) = self.queue.state.lock() {
11561247 q.current_seq = seq_idx;
1248 q.prune_stale();
11571249 self.queue.cv.notify_all();
11581250 }
11591251 }
......@@ -1184,7 +1276,7 @@ impl MediaPrefetchHandle {
11841276 return;
11851277 }
11861278 if let Ok(mut q) = self.queue.state.lock() {
1187 if q.cancelled {
1279 if q.cancelled || seq_idx < q.current_seq {
11881280 return;
11891281 }
11901282 for job in jobs.raster {
......@@ -1195,7 +1287,24 @@ impl MediaPrefetchHandle {
11951287 for (path, reqs) in jobs.videos {
11961288 let vq = q.videos.entry(path).or_default();
11971289 for req in reqs {
1198 vq.push_back((seq_idx, req));
1290 if let Some((existing_seq, _)) = vq.iter_mut().find(|(_, existing)| {
1291 existing.post_multiply == req.post_multiply
1292 && match (existing.resolved_frame_idx, req.resolved_frame_idx) {
1293 (Some(a), Some(b)) => a == b,
1294 _ => {
1295 existing.frame_i == req.frame_i
1296 && existing.clip.global_start == req.clip.global_start
1297 && existing.clip.trim_in == req.clip.trim_in
1298 && existing.clip.trim_out == req.clip.trim_out
1299 && existing.clip.reverse == req.clip.reverse
1300 && existing.clip.loop_clip == req.clip.loop_clip
1301 }
1302 }
1303 }) {
1304 *existing_seq = (*existing_seq).min(seq_idx);
1305 } else {
1306 vq.push_back((seq_idx, req));
1307 }
11991308 }
12001309 }
12011310 self.queue.cv.notify_all();
......@@ -1224,23 +1333,31 @@ impl MediaPrefetchHandle {
12241333 if q.cancelled {
12251334 return;
12261335 }
1227 let raster_seq = q.raster.front().map(|(seq, _)| *seq);
1228 let mut best_video: Option<(PathBuf, usize)> = None;
1336 q.prune_stale();
1337 let best_raster = q
1338 .raster
1339 .iter()
1340 .enumerate()
1341 .min_by_key(|&(_, (seq, _))| *seq)
1342 .map(|(idx, (seq, _))| (idx, *seq));
1343 let mut best_video: Option<(PathBuf, usize, usize)> = None;
12291344 for (path, vq) in &q.videos {
12301345 if q.active_videos.contains(path) {
12311346 continue;
12321347 }
1233 if let Some(&(seq, _)) = vq.front() {
1234 if best_video.as_ref().is_none_or(|&(_, bseq)| seq < bseq) {
1235 best_video = Some((path.clone(), seq));
1348 if let Some((v_idx, &(seq, _))) =
1349 vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq)
1350 {
1351 if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) {
1352 best_video = Some((path.clone(), v_idx, seq));
12361353 }
12371354 }
12381355 }
12391356
1240 let chosen_seq = match (raster_seq, &best_video) {
1241 (Some(rs), Some((_, vs))) => rs.min(*vs),
1242 (Some(rs), None) => rs,
1243 (None, Some((_, vs))) => *vs,
1357 let chosen_seq = match (best_raster, &best_video) {
1358 (Some((_, rs)), Some((_, _, vs))) => rs.min(*vs),
1359 (Some((_, rs)), None) => rs,
1360 (None, Some((_, _, vs))) => *vs,
12441361 (None, None) => {
12451362 q = match queue.cv.wait(q) {
12461363 Ok(g) => g,
......@@ -1271,9 +1388,9 @@ impl MediaPrefetchHandle {
12711388 }
12721389 }
12731390
1274 if let Some((path, vs)) = best_video {
1275 if raster_seq.is_none_or(|rs| vs <= rs) {
1276 if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.pop_front()) {
1391 if let Some((path, v_idx, vs)) = best_video {
1392 if best_raster.is_none_or(|(_, rs)| vs <= rs) {
1393 if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) {
12771394 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
12781395 q.videos.remove(&path);
12791396 }
......@@ -1282,9 +1399,11 @@ impl MediaPrefetchHandle {
12821399 }
12831400 }
12841401 }
1285 if let Some((_, job)) = q.raster.pop_front() {
1286 q.queued_raster_keys.remove(&job.cache_key);
1287 break PrefetchWorkItem::Raster(job);
1402 if let Some((r_idx, _)) = best_raster {
1403 if let Some((_, job)) = q.raster.remove(r_idx) {
1404 q.queued_raster_keys.remove(&job.cache_key);
1405 break PrefetchWorkItem::Raster(job);
1406 }
12881407 }
12891408 }
12901409 };
......@@ -1306,17 +1425,8 @@ impl MediaPrefetchHandle {
13061425 shared: &shared,
13071426 key: Some(job.cache_key.clone()),
13081427 };
1309 if let Some(decoded) = decode_job(&job, false) {
1310 if let Ok(mut state) = shared.state.lock() {
1311 state.in_flight.remove(&job.cache_key);
1312 guard.key = None;
1313 if state.generation == cache_gen {
1314 state.known_existing_paths.insert(job.cache_key.path.clone());
1315 state.insert_cached(job.cache_key, decoded);
1316 }
1317 shared.cv.notify_all();
1318 }
1319 }
1428 let decoded = decode_job(&job, false);
1429 finish_raster_job(&shared, job.cache_key, cache_gen, &mut guard, decoded);
13201430 }
13211431 PrefetchWorkItem::Video(path, req) => {
13221432 struct ActiveVideoGuard<'a> {
......@@ -1719,14 +1829,18 @@ fn collect_missing_loader_jobs_shared(
17191829 if video_frame_in_range(&effective_clip, frame_i)
17201830 && shared.path_exists_cached(base)
17211831 {
1832 let mut resolved_frame_idx = effective_clip
1833 .length
1834 .map(|_| compute_video_frame_idx(&effective_clip, frame_i, 1));
17221835 let need_decode = shared.state.lock().is_ok_and(|state| {
17231836 match state.video_decoders.get(base) {
1724 Some(slot) => slot.info.is_some_and(|info| {
1837 Some(slot) => {
17251838 let idx = compute_video_frame_idx(
17261839 &effective_clip,
17271840 frame_i,
1728 info.nb_frames,
1841 slot.info.nb_frames,
17291842 );
1843 resolved_frame_idx = Some(idx);
17301844 let cache_key = ImageCacheKey {
17311845 path: base.to_path_buf(),
17321846 frame_idx: idx,
......@@ -1735,7 +1849,7 @@ fn collect_missing_loader_jobs_shared(
17351849 };
17361850 !state.images.contains_key(&cache_key)
17371851 && !state.in_flight.contains(&cache_key)
1738 }),
1852 }
17391853 None => true,
17401854 }
17411855 });
......@@ -1747,6 +1861,7 @@ fn collect_missing_loader_jobs_shared(
17471861 clip: effective_clip,
17481862 frame_i,
17491863 post_multiply: post_mult,
1864 resolved_frame_idx,
17501865 });
17511866 }
17521867 }
......@@ -1877,6 +1992,7 @@ struct VideoFrameRequest {
18771992 clip: ClipSpec,
18781993 frame_i: i64,
18791994 post_multiply: bool,
1995 resolved_frame_idx: Option<i64>,
18801996}
18811997
18821998#[cfg(not(target_arch = "wasm32"))]
......@@ -2910,4 +3026,114 @@ mod tests {
29103026
29113027 let _ = std::fs::remove_dir_all(&dir);
29123028 }
3029
3030 #[cfg(not(target_arch = "wasm32"))]
3031 #[test]
3032 fn failed_opens_are_not_cached_and_evict_known_existing_paths() {
3033 let dir = std::env::temp_dir().join(format!("fission_evict_test_{}", std::process::id()));
3034 let _ = std::fs::remove_dir_all(&dir);
3035 std::fs::create_dir_all(&dir).unwrap();
3036
3037 let bad_vid = dir.join("corrupt.mp4");
3038 std::fs::write(&bad_vid, b"not a valid mp4").unwrap();
3039 let mut cache = MediaCache::new(64);
3040 assert!(cache.shared.path_exists_cached(&bad_vid));
3041 assert!(cache.shared.get_or_open_video_decoder(&bad_vid).is_none());
3042 assert_eq!(cache.video_decoder_count(), 0);
3043 assert!(!cache.shared.state.lock().unwrap().known_existing_paths.contains(&bad_vid));
3044
3045 let img_path = dir.join("gone.png");
3046 image::RgbaImage::from_pixel(2, 2, image::Rgba([10, 20, 30, 255]))
3047 .save(&img_path)
3048 .unwrap();
3049 assert!(cache.shared.path_exists_cached(&img_path));
3050 std::fs::remove_file(&img_path).unwrap();
3051 let clip = ClipSpec {
3052 filename: img_path.to_string_lossy().into_owned(),
3053 alternate_filename: None,
3054 start_frame: 0,
3055 length: Some(1),
3056 trim_in: 0,
3057 trim_out: 0,
3058 global_start: 0,
3059 global_end: 0,
3060 extend_first: 0,
3061 extend_last: 0,
3062 loop_clip: false,
3063 reverse: false,
3064 };
3065 assert!(cache.load_clip(&clip, 0, false, [None; 4]).is_none());
3066 assert!(!cache.shared.path_exists_cached(&img_path));
3067
3068 let _ = std::fs::remove_dir_all(&dir);
3069 }
3070
3071 #[cfg(not(target_arch = "wasm32"))]
3072 #[test]
3073 fn prefetch_queue_prunes_stale_and_avoids_hol_blocking() {
3074 let dir = std::env::temp_dir().join(format!("fission_hol_prefetch_{}", std::process::id()));
3075 let _ = std::fs::remove_dir_all(&dir);
3076 std::fs::create_dir_all(&dir).unwrap();
3077
3078 for i in 0..=10 {
3079 let p = dir.join(format!("seq_{i:04}.png"));
3080 image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8 * 20, 10, 200, 255]))
3081 .save(&p)
3082 .unwrap();
3083 }
3084 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3085 let p0 = dir.join("seq_0000.png");
3086 let comp_src = format!(
3087 r#"Composition {{
3088 CurrentTime = 0,
3089 RenderRange = {{ 0, 10 }},
3090 GlobalRange = {{ 0, 10 }},
3091 Tools = ordered() {{
3092 LD = Loader {{
3093 Clips = {{
3094 Clip {{
3095 ID = "Clip1",
3096 Filename = "{}",
3097 FormatID = "PNGFormat",
3098 StartFrame = 0,
3099 Length = 11,
3100 GlobalStart = 0,
3101 GlobalEnd = 10,
3102 }},
3103 }},
3104 }},
3105 }},
3106}}"#,
3107 esc(&p0)
3108 );
3109 let comp = Comp::from_fusion_str(&comp_src).expect("parse hol prefetch comp");
3110 let target = comp.find_node("LD").unwrap();
3111 let clip = comp.node(target).clips[0].clone();
3112 let expr = model::ExprEngine::new();
3113 let mut cache = MediaCache::new(64);
3114
3115 let mut handle = cache.start_frame_prefetch(2);
3116 // Enqueue far-future seq=10 first (outside lookahead=2), then seq=1 (within lookahead).
3117 handle.enqueue_frame(&comp, target, 10, 10.0, &expr, false);
3118 handle.enqueue_frame(&comp, target, 1, 1.0, &expr, false);
3119
3120 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
3121 while cache.entry_count() < 1 && std::time::Instant::now() < deadline {
3122 std::thread::sleep(std::time::Duration::from_millis(5));
3123 }
3124 assert_eq!(cache.entry_count(), 1);
3125 let (_, _, img1, from_disk1) = cache.load_clip(&clip, 1, false, [None; 4]).unwrap();
3126 assert!(!from_disk1, "seq=1 must not be head-of-line blocked by seq=10");
3127 assert_eq!(img1.rgba[0], 20);
3128
3129 // Advancing current_seq past 10 prunes seq=10 cleanly.
3130 handle.set_current_seq(11);
3131 {
3132 let q = handle.queue.state.lock().unwrap();
3133 assert!(q.raster.is_empty());
3134 assert!(q.queued_raster_keys.is_empty());
3135 }
3136 handle.cancel();
3137 let _ = std::fs::remove_dir_all(&dir);
3138 }
29133139}