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() {...@@ -8,6 +8,7 @@ fn main() {
8 .compile("av_decode");8 .compile("av_decode");
99
10 for fw in [10 for fw in [
11 "Accelerate",
11 "AVFoundation",12 "AVFoundation",
12 "CoreMedia",13 "CoreMedia",
13 "CoreVideo",14 "CoreVideo",
crates/engine/src/av_decode.m+188-38
...@@ -1,3 +1,4 @@...@@ -1,3 +1,4 @@
1#import <Accelerate/Accelerate.h>
1#import <AVFoundation/AVFoundation.h>2#import <AVFoundation/AVFoundation.h>
2#import <CoreFoundation/CoreFoundation.h>3#import <CoreFoundation/CoreFoundation.h>
3#import <CoreMedia/CoreMedia.h>4#import <CoreMedia/CoreMedia.h>
...@@ -7,6 +8,9 @@...@@ -7,6 +8,9 @@
7#include <stdint.h>8#include <stdint.h>
8#include <stddef.h>9#include <stddef.h>
9#include <string.h>10#include <string.h>
11#if defined(__aarch64__)
12#include <arm_neon.h>
13#endif
1014
11#pragma clang diagnostic push15#pragma clang diagnostic push
12#pragma clang diagnostic ignored "-Wdeprecated-declarations"16#pragma clang diagnostic ignored "-Wdeprecated-declarations"
...@@ -76,6 +80,48 @@...@@ -76,6 +80,48 @@
7680
77typedef struct AvVideoDecoder AvVideoDecoder;81typedef 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
79static int copy_bgra_to_rgba(125static int copy_bgra_to_rgba(
80 CVImageBufferRef imgBuf,126 CVImageBufferRef imgBuf,
81 uint32_t outW,127 uint32_t outW,
...@@ -102,61 +148,165 @@ static int copy_bgra_to_rgba(...@@ -102,61 +148,165 @@ static int copy_bgra_to_rgba(
102 const uint8_t *base = (const uint8_t *)CVPixelBufferGetBaseAddress(imgBuf);148 const uint8_t *base = (const uint8_t *)CVPixelBufferGetBaseAddress(imgBuf);
103149
104 int ok = 0;150 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
106 if (rotation == 0 && srcW == outW && srcH == outH) {159 if (rotation == 0 && srcW == outW && srcH == outH) {
107 for (size_t y = 0; y < srcH; y++) {160 if (vImagePermuteChannels_ARGB8888(&srcBuf, &dstBuf, permuteMap, vflags) == kvImageNoError) {
108 const uint8_t *src = base + y * bpr;161 ok = 1;
109 uint8_t *dst = outRgba + y * (size_t)outW * 4;162 } else {
110 for (size_t x = 0; x < srcW; x++) {163 for (size_t y = 0; y < srcH; y++) {
111 dst[x * 4 + 0] = src[x * 4 + 2];164 const uint8_t *src = base + y * bpr;
112 dst[x * 4 + 1] = src[x * 4 + 1];165 uint8_t *dst = outRgba + y * dstBpr;
113 dst[x * 4 + 2] = src[x * 4 + 0];166 for (size_t x = 0; x < srcW; x++) {
114 dst[x * 4 + 3] = src[x * 4 + 3];167 bgra_to_rgba_pixel(src + x * 4, dst + x * 4);
168 }
115 }169 }
170 ok = 1;
116 }171 }
117 ok = 1;
118 } else if (rotation == 90 && srcH == outW && srcW == outH) {172 } else if (rotation == 90 && srcH == outW && srcW == outH) {
119 for (size_t y = 0; y < srcH; y++) {173#if defined(__aarch64__)
120 const uint8_t *src = base + y * bpr;174 const uint8_t swizTblBytes[16] = { 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 };
121 size_t dx = srcH - 1 - y;175 uint8x16_t swizTbl = vld1q_u8(swizTblBytes);
122 for (size_t x = 0; x < srcW; x++) {176 const size_t B = 32;
123 size_t dy = x;177 for (size_t by = 0; by < srcH; by += B) {
124 uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4;178 size_t bh = (by + B <= srcH) ? B : (srcH - by);
125 dst[0] = src[x * 4 + 2];179 for (size_t bx = 0; bx < srcW; bx += B) {
126 dst[1] = src[x * 4 + 1];180 size_t bw = (bx + B <= srcW) ? B : (srcW - bx);
127 dst[2] = src[x * 4 + 0];181 size_t y = 0;
128 dst[3] = src[x * 4 + 3];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 }
129 }218 }
130 }219 }
131 ok = 1;220 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
132 } else if (rotation == 180 && srcW == outW && srcH == outH) {228 } 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);
133 for (size_t y = 0; y < srcH; y++) {232 for (size_t y = 0; y < srcH; y++) {
134 const uint8_t *src = base + y * bpr;233 const uint8_t *src = base + y * bpr;
135 size_t dy = srcH - 1 - y;234 uint8_t *dstRow = outRgba + (srcH - 1 - y) * dstBpr;
136 for (size_t x = 0; x < srcW; x++) {235 size_t x = 0;
137 size_t dx = srcW - 1 - x;236 for (; x + 4 <= srcW; x += 4) {
138 uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4;237 uint8x16_t v = vld1q_u8(src + x * 4);
139 dst[0] = src[x * 4 + 2];238 vst1q_u8(dstRow + (srcW - x - 4) * 4, vqtbl1q_u8(v, revSwiz));
140 dst[1] = src[x * 4 + 1];239 }
141 dst[2] = src[x * 4 + 0];240 for (; x < srcW; x++) {
142 dst[3] = src[x * 4 + 3];241 bgra_to_rgba_pixel(src + x * 4, dstRow + (srcW - 1 - x) * 4);
143 }242 }
144 }243 }
145 ok = 1;244 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
146 } else if (rotation == 270 && srcH == outW && srcW == outH) {252 } else if (rotation == 270 && srcH == outW && srcW == outH) {
147 for (size_t y = 0; y < srcH; y++) {253#if defined(__aarch64__)
148 const uint8_t *src = base + y * bpr;254 const uint8_t swizTblBytes[16] = { 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15 };
149 size_t dx = y;255 uint8x16_t swizTbl = vld1q_u8(swizTblBytes);
150 for (size_t x = 0; x < srcW; x++) {256 const size_t B = 32;
151 size_t dy = srcW - 1 - x;257 for (size_t by = 0; by < srcH; by += B) {
152 uint8_t *dst = outRgba + (dy * (size_t)outW + dx) * 4;258 size_t bh = (by + B <= srcH) ? B : (srcH - by);
153 dst[0] = src[x * 4 + 2];259 for (size_t bx = 0; bx < srcW; bx += B) {
154 dst[1] = src[x * 4 + 1];260 size_t bw = (bx + B <= srcW) ? B : (srcW - bx);
155 dst[2] = src[x * 4 + 0];261 size_t y = 0;
156 dst[3] = src[x * 4 + 3];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 }
157 }300 }
158 }301 }
159 ok = 1;302 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
160 }310 }
161 }311 }
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::...@@ -111,13 +111,6 @@ fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box<dyn std::error::
111 };111 };
112112
113 engine.set_cache_mode(CacheMode::Enabled);113 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 );
121 let (tex, cold) = engine.evaluate(comp, target, frame);114 let (tex, cold) = engine.evaluate(comp, target, frame);
122 let (_, warm) = engine.evaluate(comp, target, frame);115 let (_, warm) = engine.evaluate(comp, target, frame);
123 engine.bust_gpu_cache();116 engine.bust_gpu_cache();
...@@ -245,13 +238,6 @@ fn run_batch_render(...@@ -245,13 +238,6 @@ fn run_batch_render(
245 let mut loop_err: Option<String> = None;238 let mut loop_err: Option<String> = None;
246 const PREFETCH_LOOKAHEAD: usize = 12;239 const PREFETCH_LOOKAHEAD: usize = 12;
247 engine.prewarm_core_pipelines();240 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 );
255 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);241 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
256 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);242 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);
257 for (k, f) in ((start + 1)..=seed_end).enumerate() {243 for (k, f) in ((start + 1)..=seed_end).enumerate() {
...@@ -782,13 +768,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -782,13 +768,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
782 if profile {768 if profile {
783 engine.cache.begin_frame_profile_with_comp(&comp);769 engine.cache.begin_frame_profile_with_comp(&comp);
784 }770 }
785 engine.media.preload_frame_loaders_with_proxy(
786 &comp,
787 target,
788 frame,
789 &engine.expr,
790 engine.use_proxy_clips,
791 );
792 let (tex, cold) = engine.evaluate(&comp, target, frame);771 let (tex, cold) = engine.evaluate(&comp, target, frame);
793 let cold_profile = if profile {772 let cold_profile = if profile {
794 engine.cache.take_frame_profile().map(|mut fp| {773 engine.cache.take_frame_profile().map(|mut fp| {
crates/engine/src/eval/io.rs+22
...@@ -123,6 +123,24 @@ impl Engine {...@@ -123,6 +123,24 @@ impl Engine {
123 let padded_bpr = unpadded_bpr.div_ceil(align) * align;123 let padded_bpr = unpadded_bpr.div_ceil(align) * align;
124 let needed = u64::from(padded_bpr) * u64::from(h);124 let needed = u64::from(padded_bpr) * u64::from(h);
125 if let Some(buf) = self.media.acquire_upload_staging(&self.device, needed) {125 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;
126 if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() {144 if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() {
127 if padded_bpr == unpadded_bpr {145 if padded_bpr == unpadded_bpr {
128 let total = (unpadded_bpr as usize) * (h as usize);146 let total = (unpadded_bpr as usize) * (h as usize);
...@@ -137,6 +155,9 @@ impl Engine {...@@ -137,6 +155,9 @@ impl Engine {
137 }155 }
138 }156 }
139 drop(view);157 drop(view);
158 copied = true;
159 }
160 if copied {
140 buf.unmap();161 buf.unmap();
141 enc.copy_buffer_to_texture(162 enc.copy_buffer_to_texture(
142 wgpu::TexelCopyBufferInfo {163 wgpu::TexelCopyBufferInfo {
...@@ -154,6 +175,7 @@ impl Engine {...@@ -154,6 +175,7 @@ impl Engine {
154 depth_or_array_layers: 1,175 depth_or_array_layers: 1,
155 },176 },
156 );177 );
178 staging_guard.armed = false;
157 self.media.recycle_upload_staging(buf);179 self.media.recycle_upload_staging(buf);
158 return;180 return;
159 }181 }
crates/engine/src/export.rs+86-96
...@@ -308,13 +308,6 @@ pub fn export_saver_png_sequence_with_progress(...@@ -308,13 +308,6 @@ pub fn export_saver_png_sequence_with_progress(
308 let mut loop_err: Option<String> = None;308 let mut loop_err: Option<String> = None;
309 const PREFETCH_LOOKAHEAD: usize = 12;309 const PREFETCH_LOOKAHEAD: usize = 12;
310 engine.prewarm_core_pipelines();310 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 );
318 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);311 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
319 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);312 let seed_end = (start + PREFETCH_LOOKAHEAD as i64 - 1).min(end);
320 for (k, f) in ((start + 1)..=seed_end).enumerate() {313 for (k, f) in ((start + 1)..=seed_end).enumerate() {
...@@ -728,13 +721,7 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -728,13 +721,7 @@ pub fn export_node_video_ffmpeg_with_progress(
728 let node_name = comp.node(opts.target).name.clone();721 let node_name = comp.node(opts.target).name.clone();
729722
730 // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output.723 // Evaluate the first frame before spawning ffmpeg so dimensions match actual GPU output.
731 engine.media.preload_frame_loaders_with_proxy(724 engine.prewarm_core_pipelines();
732 comp,
733 opts.target,
734 start as f64,
735 &engine.expr,
736 engine.use_proxy_clips,
737 );
738 let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64);725 let (first_tex, first_stats) = engine.evaluate(comp, opts.target, start as f64);
739 if first_tex.size[0] == 0 || first_tex.size[1] == 0 {726 if first_tex.size[0] == 0 || first_tex.size[1] == 0 {
740 return Err(format!(727 return Err(format!(
...@@ -975,110 +962,113 @@ pub fn export_node_video_ffmpeg_with_progress(...@@ -975,110 +962,113 @@ pub fn export_node_video_ffmpeg_with_progress(
975 ctrl.update_progress(&first_prog);962 ctrl.update_progress(&first_prog);
976 }963 }
977 on_progress(first_prog);964 on_progress(first_prog);
978965 if control.is_some_and(ExportControl::is_cancelled) {
979 const PREFETCH_LOOKAHEAD: usize = 12;966 cancelled = true;
980 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);967 } else if start < end {
981 let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end);968 const PREFETCH_LOOKAHEAD: usize = 12;
982 for (k, f) in ((start + 1)..=seed_end).enumerate() {969 let prefetch = engine.media.start_frame_prefetch(PREFETCH_LOOKAHEAD);
983 prefetch.enqueue_frame(970 let seed_end = (start + PREFETCH_LOOKAHEAD as i64).min(end);
984 comp,971 for (k, f) in ((start + 1)..=seed_end).enumerate() {
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 {
1004 prefetch.enqueue_frame(972 prefetch.enqueue_frame(
1005 comp,973 comp,
1006 opts.target,974 opts.target,
1007 idx + PREFETCH_LOOKAHEAD,975 k,
1008 ahead_frame as f64,976 f as f64,
1009 &engine.expr,977 &engine.expr,
1010 engine.use_proxy_clips,978 engine.use_proxy_clips,
1011 );979 );
1012 }980 }
1013 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);981 let mut pending: Option<(crate::eval::PendingReadback, i64, usize, [u32; 2], f64)> = None;
1014 let next_rb = match engine.begin_readback_rgba(&tex) {982 for (idx, frame) in ((start + 1)..=end).enumerate() {
1015 Ok(rb) => rb,983 if writer_failed.load(Ordering::Acquire) {
1016 Err(e) => {
1017 pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
1018 break;984 break;
1019 }985 }
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 };
1031 if control.is_some_and(ExportControl::is_cancelled) {986 if control.is_some_and(ExportControl::is_cancelled) {
1032 cancelled = true;987 cancelled = true;
1033 break;988 break;
1034 }989 }
1035 if tx.send((prev_frame, prev_size, pixels)).is_err() {990 prefetch.set_current_seq(idx);
1036 break;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 );
1037 }1001 }
1038 let prog = make_progress(1002 let (tex, stats) = engine.evaluate(comp, opts.target, frame as f64);
1039 prev_frame,1003 let next_rb = match engine.begin_readback_rgba(&tex) {
1040 prev_idx + 1,1004 Ok(rb) => rb,
1041 total,1005 Err(e) => {
1042 prev_ms,1006 pipe_err = Some(format!("GPU readback failed at frame {frame}: {e}"));
1043 opts.out_path.clone(),1007 break;
1044 node_name.clone(),1008 }
1045 t0,1009 };
1046 );1010 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) =
1047 if let Some(ctrl) = control {1011 pending.replace((next_rb, frame, idx, tex.size, stats.eval_ms))
1048 ctrl.update_progress(&prog);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);
1049 }1040 }
1050 on_progress(prog);
1051 }1041 }
1052 }1042 if pipe_err.is_none() && !cancelled && !writer_failed.load(Ordering::Acquire) {
1053 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() {
1054 if let Some((prev_rb, prev_frame, prev_idx, prev_size, prev_ms)) = pending.take() {1044 match prev_rb.finish(engine) {
1055 match prev_rb.finish(engine) {1045 Ok(pixels) => {
1056 Ok(pixels) => {1046 if control.is_some_and(ExportControl::is_cancelled) {
1057 if control.is_some_and(ExportControl::is_cancelled) {1047 cancelled = true;
1058 cancelled = true;1048 } else if tx.send((prev_frame, prev_size, pixels)).is_ok() {
1059 } else if tx.send((prev_frame, prev_size, pixels)).is_ok() {1049 let prog = make_progress(
1060 let prog = make_progress(1050 prev_frame,
1061 prev_frame,1051 prev_idx + 1,
1062 prev_idx + 1,1052 total,
1063 total,1053 prev_ms,
1064 prev_ms,1054 opts.out_path.clone(),
1065 opts.out_path.clone(),1055 node_name.clone(),
1066 node_name.clone(),1056 t0,
1067 t0,1057 );
1068 );1058 if let Some(ctrl) = control {
1069 if let Some(ctrl) = control {1059 ctrl.update_progress(&prog);
1070 ctrl.update_progress(&prog);1060 }
1061 on_progress(prog);
1071 }1062 }
1072 on_progress(prog);
1073 }1063 }
1074 }1064 Err(e) => {
1075 Err(e) => {1065 pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));
1076 pipe_err = Some(format!("GPU readback failed at frame {prev_frame}: {e}"));1066 }
1077 }1067 }
1078 }1068 }
1079 }1069 }
1070 drop(prefetch);
1080 }1071 }
1081 drop(prefetch);
1082 }1072 }
1083 drop(tx);1073 drop(tx);
10841074
crates/engine/src/media.rs+329-103
...@@ -21,8 +21,8 @@ use crate::text_engine;...@@ -21,8 +21,8 @@ use crate::text_engine;
21use model::{Node, default_main_input_port};21use model::{Node, default_main_input_port};
22use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint};22use model::{ClipSpec, ClsEntry, Comp, NodeId, PolyPoint};
23#[cfg(not(target_arch = "wasm32"))]23#[cfg(not(target_arch = "wasm32"))]
24use std::collections::VecDeque;24use std::collections::{HashSet, VecDeque};
25use std::collections::{HashMap, HashSet};25use std::collections::HashMap;
26use std::path::{Path, PathBuf};26use std::path::{Path, PathBuf};
27use std::process::Command;27use std::process::Command;
28#[cfg(not(target_arch = "wasm32"))]28#[cfg(not(target_arch = "wasm32"))]
...@@ -195,7 +195,7 @@ struct ImageCacheKey {...@@ -195,7 +195,7 @@ struct ImageCacheKey {
195}195}
196196
197struct VideoDecoderSlot {197struct VideoDecoderSlot {
198 info: Option<VideoInfo>,198 info: VideoInfo,
199 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,199 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,
200 last_used: u64,200 last_used: u64,
201}201}
...@@ -212,6 +212,7 @@ struct MediaState {...@@ -212,6 +212,7 @@ struct MediaState {
212 in_flight: HashSet<ImageCacheKey>,212 in_flight: HashSet<ImageCacheKey>,
213 #[cfg(not(target_arch = "wasm32"))]213 #[cfg(not(target_arch = "wasm32"))]
214 opening_videos: HashSet<PathBuf>,214 opening_videos: HashSet<PathBuf>,
215 #[cfg(not(target_arch = "wasm32"))]
215 known_existing_paths: HashSet<PathBuf>,216 known_existing_paths: HashSet<PathBuf>,
216}217}
217218
...@@ -229,10 +230,30 @@ impl MediaState {...@@ -229,10 +230,30 @@ impl MediaState {
229 in_flight: HashSet::new(),230 in_flight: HashSet::new(),
230 #[cfg(not(target_arch = "wasm32"))]231 #[cfg(not(target_arch = "wasm32"))]
231 opening_videos: HashSet::new(),232 opening_videos: HashSet::new(),
233 #[cfg(not(target_arch = "wasm32"))]
232 known_existing_paths: HashSet::new(),234 known_existing_paths: HashSet::new(),
233 }235 }
234 }236 }
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
236 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {257 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
237 let bytes = decoded.byte_size();258 let bytes = decoded.byte_size();
238 self.tick += 1;259 self.tick += 1;
...@@ -256,16 +277,20 @@ impl MediaState {...@@ -256,16 +277,20 @@ impl MediaState {
256 fn put_video_decoder(277 fn put_video_decoder(
257 &mut self,278 &mut self,
258 path: PathBuf,279 path: PathBuf,
259 info: Option<VideoInfo>,280 info: VideoInfo,
260 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,281 decoder: Arc<Mutex<Option<Box<dyn VideoDecoder>>>>,
261 ) {282 ) -> Vec<VideoDecoderSlot> {
283 let mut evicted = Vec::new();
262 self.tick += 1;284 self.tick += 1;
263 let now_tick = self.tick;285 let now_tick = self.tick;
286 let new_slot = VideoDecoderSlot {
287 info,
288 decoder,
289 last_used: now_tick,
290 };
264 if let Some(slot) = self.video_decoders.get_mut(&path) {291 if let Some(slot) = self.video_decoders.get_mut(&path) {
265 slot.info = info;292 evicted.push(std::mem::replace(slot, new_slot));
266 slot.decoder = decoder;293 return evicted;
267 slot.last_used = now_tick;
268 return;
269 }294 }
270 while self.video_decoders.len() >= MAX_VIDEO_DECODERS {295 while self.video_decoders.len() >= MAX_VIDEO_DECODERS {
271 let Some(oldest_path) = self296 let Some(oldest_path) = self
...@@ -276,16 +301,12 @@ impl MediaState {...@@ -276,16 +301,12 @@ impl MediaState {
276 else {301 else {
277 break;302 break;
278 };303 };
279 self.video_decoders.remove(&oldest_path);304 if let Some(removed) = self.video_decoders.remove(&oldest_path) {
280 }305 evicted.push(removed);
281 self.video_decoders.insert(306 }
282 path,307 }
283 VideoDecoderSlot {308 self.video_decoders.insert(path, new_slot);
284 info,309 evicted
285 decoder,
286 last_used: now_tick,
287 },
288 );
289 }310 }
290}311}
291312
...@@ -308,18 +329,25 @@ impl MediaShared {...@@ -308,18 +329,25 @@ impl MediaShared {
308 if virtual_bytes(path).is_some() {329 if virtual_bytes(path).is_some() {
309 return true;330 return true;
310 }331 }
311 if let Ok(state) = self.state.lock() {332 #[cfg(not(target_arch = "wasm32"))]
312 if state.known_existing_paths.contains(path) || state.video_decoders.contains_key(path) {333 {
313 return true;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 }
314 }338 }
315 }339 if path.exists() {
316 if path.exists() {340 if let Ok(mut state) = self.state.lock() {
317 if let Ok(mut state) = self.state.lock() {341 state.record_existing_path(path);
318 state.known_existing_paths.insert(path.to_path_buf());342 }
343 true
344 } else {
345 false
319 }346 }
320 true347 }
321 } else {348 #[cfg(target_arch = "wasm32")]
322 false349 {
350 path.exists()
323 }351 }
324 }352 }
325353
...@@ -341,7 +369,7 @@ impl MediaShared {...@@ -341,7 +369,7 @@ impl MediaShared {
341 let now_tick = guard.tick;369 let now_tick = guard.tick;
342 if let Some(slot) = guard.video_decoders.get_mut(path) {370 if let Some(slot) = guard.video_decoders.get_mut(path) {
343 slot.last_used = now_tick;371 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)));
345 }373 }
346374
347 #[cfg(not(target_arch = "wasm32"))]375 #[cfg(not(target_arch = "wasm32"))]
...@@ -353,37 +381,51 @@ impl MediaShared {...@@ -353,37 +381,51 @@ impl MediaShared {
353381
354 struct OpenGuard<'a> {382 struct OpenGuard<'a> {
355 shared: &'a MediaShared,383 shared: &'a MediaShared,
356 path: PathBuf,384 path: Option<PathBuf>,
357 }385 }
358 impl Drop for OpenGuard<'_> {386 impl Drop for OpenGuard<'_> {
359 fn drop(&mut self) {387 fn drop(&mut self) {
360 #[cfg(not(target_arch = "wasm32"))]388 #[cfg(not(target_arch = "wasm32"))]
361 if let Ok(mut state) = self.shared.state.lock() {389 if let Some(path) = self.path.take() {
362 state.opening_videos.remove(&self.path);390 if let Ok(mut state) = self.shared.state.lock() {
363 self.shared.cv.notify_all();391 state.opening_videos.remove(&path);
392 self.shared.cv.notify_all();
393 }
364 }394 }
365 #[cfg(target_arch = "wasm32")]395 #[cfg(target_arch = "wasm32")]
366 let _ = (&self.shared, &self.path);396 let _ = (&self.shared, &self.path);
367 }397 }
368 }398 }
369 let _open_guard = OpenGuard {399 let mut open_guard = OpenGuard {
370 shared: self,400 shared: self,
371 path: path.to_path_buf(),401 path: Some(path.to_path_buf()),
372 };402 };
373403
374 let decoder = open_video_decoder(path);404 let decoder = open_video_decoder(path);
375 let info = decoder.as_ref().map(|d| d.info());405 let info = decoder.as_ref().map(|d| d.info());
376 let slot_arc = Arc::new(Mutex::new(decoder));406 let slot_arc = Arc::new(Mutex::new(decoder));
377407
408 let mut evicted_decoders = Vec::new();
378 if let Ok(mut state) = self.state.lock() {409 if let Ok(mut state) = self.state.lock() {
379 #[cfg(not(target_arch = "wasm32"))]410 #[cfg(not(target_arch = "wasm32"))]
380 state.opening_videos.remove(path);411 state.opening_videos.remove(path);
381 if state.generation == cache_gen {412 open_guard.path = None;
382 state.put_video_decoder(path.to_path_buf(), info, Arc::clone(&slot_arc));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);
383 }424 }
384 #[cfg(not(target_arch = "wasm32"))]425 #[cfg(not(target_arch = "wasm32"))]
385 self.cv.notify_all();426 self.cv.notify_all();
386 }427 }
428 drop(evicted_decoders);
387 info.map(|i| (i, slot_arc))429 info.map(|i| (i, slot_arc))
388 }430 }
389}431}
...@@ -550,6 +592,10 @@ impl UploadStagingPool {...@@ -550,6 +592,10 @@ impl UploadStagingPool {
550 rx: None,592 rx: None,
551 });593 });
552 }594 }
595
596 pub(crate) fn release_failed_upload(&mut self, capacity: u64) {
597 self.total_bytes = self.total_bytes.saturating_sub(capacity);
598 }
553}599}
554600
555pub struct MediaCache {601pub struct MediaCache {
...@@ -591,14 +637,17 @@ impl MediaCache {...@@ -591,14 +637,17 @@ impl MediaCache {
591 }637 }
592638
593 pub fn clear(&mut self) {639 pub fn clear(&mut self) {
640 let mut cleared_decoders = Vec::new();
594 if let Ok(mut state) = self.shared.state.lock() {641 if let Ok(mut state) = self.shared.state.lock() {
595 state.images.clear();642 state.images.clear();
596 state.lru.clear();643 state.lru.clear();
597 state.video_decoders.clear();644 cleared_decoders.extend(state.video_decoders.drain().map(|(_, slot)| slot));
598 state.total_bytes = 0;645 state.total_bytes = 0;
599 state.generation = state.generation.wrapping_add(1);646 state.generation = state.generation.wrapping_add(1);
647 #[cfg(not(target_arch = "wasm32"))]
600 state.known_existing_paths.clear();648 state.known_existing_paths.clear();
601 }649 }
650 drop(cleared_decoders);
602 #[cfg(not(target_arch = "wasm32"))]651 #[cfg(not(target_arch = "wasm32"))]
603 if let Ok(mut pool) = self.staging_pool.lock() {652 if let Ok(mut pool) = self.staging_pool.lock() {
604 pool.clear();653 pool.clear();
...@@ -609,16 +658,22 @@ impl MediaCache {...@@ -609,16 +658,22 @@ impl MediaCache {
609 pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option<wgpu::Buffer> {658 pub(crate) fn acquire_upload_staging(&self, device: &wgpu::Device, needed: u64) -> Option<wgpu::Buffer> {
610 self.staging_pool659 self.staging_pool
611 .lock()660 .lock()
612 .expect("staging pool lock")661 .ok()?
613 .acquire(device, needed)662 .acquire(device, needed)
614 }663 }
615664
616 #[cfg(not(target_arch = "wasm32"))]665 #[cfg(not(target_arch = "wasm32"))]
617 pub(crate) fn recycle_upload_staging(&self, buffer: wgpu::Buffer) {666 pub(crate) fn recycle_upload_staging(&self, buffer: wgpu::Buffer) {
618 self.staging_pool667 if let Ok(mut pool) = self.staging_pool.lock() {
619 .lock()668 pool.finish_upload(buffer);
620 .expect("staging pool lock")669 }
621 .finish_upload(buffer);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 }
622 }677 }
623678
624 /// Marks submitted upload staging buffers ready to begin asynchronous write-mapping679 /// Marks submitted upload staging buffers ready to begin asynchronous write-mapping
...@@ -800,9 +855,15 @@ impl MediaCache {...@@ -800,9 +855,15 @@ impl MediaCache {
800 exr_channels[2],855 exr_channels[2],
801 exr_channels[3],856 exr_channels[3],
802 false,857 false,
803 )?858 )
804 } else {859 } 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;
806 };867 };
807868
808 if let Ok(mut state) = self.shared.state.lock() {869 if let Ok(mut state) = self.shared.state.lock() {
...@@ -812,7 +873,7 @@ impl MediaCache {...@@ -812,7 +873,7 @@ impl MediaCache {
812 in_flight_guard.key = None;873 in_flight_guard.key = None;
813 }874 }
814 if state.generation == cache_gen {875 if state.generation == cache_gen {
815 state.known_existing_paths.insert(resolved.clone());876 state.record_existing_path(&resolved);
816 state.insert_cached(cache_key, decoded.clone());877 state.insert_cached(cache_key, decoded.clone());
817 }878 }
818 #[cfg(not(target_arch = "wasm32"))]879 #[cfg(not(target_arch = "wasm32"))]
...@@ -848,9 +909,6 @@ impl MediaCache {...@@ -848,9 +909,6 @@ impl MediaCache {
848 }909 }
849 #[cfg(not(target_arch = "wasm32"))]910 #[cfg(not(target_arch = "wasm32"))]
850 {911 {
851 if let Ok(mut pool) = self.staging_pool.lock() {
852 pool.mark_frame_start();
853 }
854 let mut visited = HashSet::new();912 let mut visited = HashSet::new();
855 let mut jobs = MissingJobs::default();913 let mut jobs = MissingJobs::default();
856 collect_missing_loader_jobs_shared(914 collect_missing_loader_jobs_shared(
...@@ -933,17 +991,8 @@ impl MediaCache {...@@ -933,17 +991,8 @@ impl MediaCache {
933 shared: &self.shared,991 shared: &self.shared,
934 key: Some(job.cache_key.clone()),992 key: Some(job.cache_key.clone()),
935 };993 };
936 if let Some(decoded) = decode_job(&job, true) {994 let decoded = decode_job(&job, true);
937 if let Ok(mut state) = self.shared.state.lock() {995 finish_raster_job(&self.shared, job.cache_key, cache_gen, &mut guard, decoded);
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 }
947 return;996 return;
948 }997 }
949 self.decode_jobs_parallel(jobs);998 self.decode_jobs_parallel(jobs);
...@@ -1065,17 +1114,14 @@ impl MediaCache {...@@ -1065,17 +1114,14 @@ impl MediaCache {
1065 shared: &self.shared,1114 shared: &self.shared,
1066 key: Some(job.cache_key.clone()),1115 key: Some(job.cache_key.clone()),
1067 };1116 };
1068 if let Some(decoded) = decode_job(job, false) {1117 let decoded = decode_job(job, false);
1069 if let Ok(mut state) = self.shared.state.lock() {1118 finish_raster_job(
1070 state.in_flight.remove(&job.cache_key);1119 &self.shared,
1071 guard.key = None;1120 job.cache_key.clone(),
1072 if state.generation == cache_gen {1121 cache_gen,
1073 state.known_existing_paths.insert(job.cache_key.path.clone());1122 &mut guard,
1074 state.insert_cached(job.cache_key.clone(), decoded);1123 decoded,
1075 }1124 );
1076 self.shared.cv.notify_all();
1077 }
1078 }
1079 }1125 }
1080 });1126 });
1081 }1127 }
...@@ -1083,6 +1129,29 @@ impl MediaCache {...@@ -1083,6 +1129,29 @@ impl MediaCache {
1083 }1129 }
1084}1130}
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
1086#[cfg(not(target_arch = "wasm32"))]1155#[cfg(not(target_arch = "wasm32"))]
1087struct PrefetchQueueState {1156struct PrefetchQueueState {
1088 raster: VecDeque<(usize, PreloadJob)>,1157 raster: VecDeque<(usize, PreloadJob)>,
...@@ -1094,6 +1163,28 @@ struct PrefetchQueueState {...@@ -1094,6 +1163,28 @@ struct PrefetchQueueState {
1094 cancelled: bool,1163 cancelled: bool,
1095}1164}
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
1097#[cfg(not(target_arch = "wasm32"))]1188#[cfg(not(target_arch = "wasm32"))]
1098struct PrefetchQueue {1189struct PrefetchQueue {
1099 state: Mutex<PrefetchQueueState>,1190 state: Mutex<PrefetchQueueState>,
...@@ -1154,6 +1245,7 @@ impl MediaPrefetchHandle {...@@ -1154,6 +1245,7 @@ impl MediaPrefetchHandle {
1154 pub fn set_current_seq(&self, seq_idx: usize) {1245 pub fn set_current_seq(&self, seq_idx: usize) {
1155 if let Ok(mut q) = self.queue.state.lock() {1246 if let Ok(mut q) = self.queue.state.lock() {
1156 q.current_seq = seq_idx;1247 q.current_seq = seq_idx;
1248 q.prune_stale();
1157 self.queue.cv.notify_all();1249 self.queue.cv.notify_all();
1158 }1250 }
1159 }1251 }
...@@ -1184,7 +1276,7 @@ impl MediaPrefetchHandle {...@@ -1184,7 +1276,7 @@ impl MediaPrefetchHandle {
1184 return;1276 return;
1185 }1277 }
1186 if let Ok(mut q) = self.queue.state.lock() {1278 if let Ok(mut q) = self.queue.state.lock() {
1187 if q.cancelled {1279 if q.cancelled || seq_idx < q.current_seq {
1188 return;1280 return;
1189 }1281 }
1190 for job in jobs.raster {1282 for job in jobs.raster {
...@@ -1195,7 +1287,24 @@ impl MediaPrefetchHandle {...@@ -1195,7 +1287,24 @@ impl MediaPrefetchHandle {
1195 for (path, reqs) in jobs.videos {1287 for (path, reqs) in jobs.videos {
1196 let vq = q.videos.entry(path).or_default();1288 let vq = q.videos.entry(path).or_default();
1197 for req in reqs {1289 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 }
1199 }1308 }
1200 }1309 }
1201 self.queue.cv.notify_all();1310 self.queue.cv.notify_all();
...@@ -1224,23 +1333,31 @@ impl MediaPrefetchHandle {...@@ -1224,23 +1333,31 @@ impl MediaPrefetchHandle {
1224 if q.cancelled {1333 if q.cancelled {
1225 return;1334 return;
1226 }1335 }
1227 let raster_seq = q.raster.front().map(|(seq, _)| *seq);1336 q.prune_stale();
1228 let mut best_video: Option<(PathBuf, usize)> = None;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;
1229 for (path, vq) in &q.videos {1344 for (path, vq) in &q.videos {
1230 if q.active_videos.contains(path) {1345 if q.active_videos.contains(path) {
1231 continue;1346 continue;
1232 }1347 }
1233 if let Some(&(seq, _)) = vq.front() {1348 if let Some((v_idx, &(seq, _))) =
1234 if best_video.as_ref().is_none_or(|&(_, bseq)| seq < bseq) {1349 vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq)
1235 best_video = Some((path.clone(), seq));1350 {
1351 if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) {
1352 best_video = Some((path.clone(), v_idx, seq));
1236 }1353 }
1237 }1354 }
1238 }1355 }
12391356
1240 let chosen_seq = match (raster_seq, &best_video) {1357 let chosen_seq = match (best_raster, &best_video) {
1241 (Some(rs), Some((_, vs))) => rs.min(*vs),1358 (Some((_, rs)), Some((_, _, vs))) => rs.min(*vs),
1242 (Some(rs), None) => rs,1359 (Some((_, rs)), None) => rs,
1243 (None, Some((_, vs))) => *vs,1360 (None, Some((_, _, vs))) => *vs,
1244 (None, None) => {1361 (None, None) => {
1245 q = match queue.cv.wait(q) {1362 q = match queue.cv.wait(q) {
1246 Ok(g) => g,1363 Ok(g) => g,
...@@ -1271,9 +1388,9 @@ impl MediaPrefetchHandle {...@@ -1271,9 +1388,9 @@ impl MediaPrefetchHandle {
1271 }1388 }
1272 }1389 }
12731390
1274 if let Some((path, vs)) = best_video {1391 if let Some((path, v_idx, vs)) = best_video {
1275 if raster_seq.is_none_or(|rs| vs <= rs) {1392 if best_raster.is_none_or(|(_, rs)| vs <= rs) {
1276 if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.pop_front()) {1393 if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) {
1277 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {1394 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
1278 q.videos.remove(&path);1395 q.videos.remove(&path);
1279 }1396 }
...@@ -1282,9 +1399,11 @@ impl MediaPrefetchHandle {...@@ -1282,9 +1399,11 @@ impl MediaPrefetchHandle {
1282 }1399 }
1283 }1400 }
1284 }1401 }
1285 if let Some((_, job)) = q.raster.pop_front() {1402 if let Some((r_idx, _)) = best_raster {
1286 q.queued_raster_keys.remove(&job.cache_key);1403 if let Some((_, job)) = q.raster.remove(r_idx) {
1287 break PrefetchWorkItem::Raster(job);1404 q.queued_raster_keys.remove(&job.cache_key);
1405 break PrefetchWorkItem::Raster(job);
1406 }
1288 }1407 }
1289 }1408 }
1290 };1409 };
...@@ -1306,17 +1425,8 @@ impl MediaPrefetchHandle {...@@ -1306,17 +1425,8 @@ impl MediaPrefetchHandle {
1306 shared: &shared,1425 shared: &shared,
1307 key: Some(job.cache_key.clone()),1426 key: Some(job.cache_key.clone()),
1308 };1427 };
1309 if let Some(decoded) = decode_job(&job, false) {1428 let decoded = decode_job(&job, false);
1310 if let Ok(mut state) = shared.state.lock() {1429 finish_raster_job(&shared, job.cache_key, cache_gen, &mut guard, decoded);
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 }
1320 }1430 }
1321 PrefetchWorkItem::Video(path, req) => {1431 PrefetchWorkItem::Video(path, req) => {
1322 struct ActiveVideoGuard<'a> {1432 struct ActiveVideoGuard<'a> {
...@@ -1719,14 +1829,18 @@ fn collect_missing_loader_jobs_shared(...@@ -1719,14 +1829,18 @@ fn collect_missing_loader_jobs_shared(
1719 if video_frame_in_range(&effective_clip, frame_i)1829 if video_frame_in_range(&effective_clip, frame_i)
1720 && shared.path_exists_cached(base)1830 && shared.path_exists_cached(base)
1721 {1831 {
1832 let mut resolved_frame_idx = effective_clip
1833 .length
1834 .map(|_| compute_video_frame_idx(&effective_clip, frame_i, 1));
1722 let need_decode = shared.state.lock().is_ok_and(|state| {1835 let need_decode = shared.state.lock().is_ok_and(|state| {
1723 match state.video_decoders.get(base) {1836 match state.video_decoders.get(base) {
1724 Some(slot) => slot.info.is_some_and(|info| {1837 Some(slot) => {
1725 let idx = compute_video_frame_idx(1838 let idx = compute_video_frame_idx(
1726 &effective_clip,1839 &effective_clip,
1727 frame_i,1840 frame_i,
1728 info.nb_frames,1841 slot.info.nb_frames,
1729 );1842 );
1843 resolved_frame_idx = Some(idx);
1730 let cache_key = ImageCacheKey {1844 let cache_key = ImageCacheKey {
1731 path: base.to_path_buf(),1845 path: base.to_path_buf(),
1732 frame_idx: idx,1846 frame_idx: idx,
...@@ -1735,7 +1849,7 @@ fn collect_missing_loader_jobs_shared(...@@ -1735,7 +1849,7 @@ fn collect_missing_loader_jobs_shared(
1735 };1849 };
1736 !state.images.contains_key(&cache_key)1850 !state.images.contains_key(&cache_key)
1737 && !state.in_flight.contains(&cache_key)1851 && !state.in_flight.contains(&cache_key)
1738 }),1852 }
1739 None => true,1853 None => true,
1740 }1854 }
1741 });1855 });
...@@ -1747,6 +1861,7 @@ fn collect_missing_loader_jobs_shared(...@@ -1747,6 +1861,7 @@ fn collect_missing_loader_jobs_shared(
1747 clip: effective_clip,1861 clip: effective_clip,
1748 frame_i,1862 frame_i,
1749 post_multiply: post_mult,1863 post_multiply: post_mult,
1864 resolved_frame_idx,
1750 });1865 });
1751 }1866 }
1752 }1867 }
...@@ -1877,6 +1992,7 @@ struct VideoFrameRequest {...@@ -1877,6 +1992,7 @@ struct VideoFrameRequest {
1877 clip: ClipSpec,1992 clip: ClipSpec,
1878 frame_i: i64,1993 frame_i: i64,
1879 post_multiply: bool,1994 post_multiply: bool,
1995 resolved_frame_idx: Option<i64>,
1880}1996}
18811997
1882#[cfg(not(target_arch = "wasm32"))]1998#[cfg(not(target_arch = "wasm32"))]
...@@ -2910,4 +3026,114 @@ mod tests {...@@ -2910,4 +3026,114 @@ mod tests {
29103026
2911 let _ = std::fs::remove_dir_all(&dir);3027 let _ = std::fs::remove_dir_all(&dir);
2912 }3028 }
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 }
2913}3139}