authoravatarclover caruso<git@paperclover.net>2026-12-01 15:01:32-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 15:22:03-08:00
log363e27e89e6fc142cb10daaee490f76794346570
tree6b0cd82f2216bc3b46b679e2f7b639c7224378bc
parent53404bff5dc1ccb3684ef4a655cd94d7f761d0b6
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): scale media prefetch workers to 12 and parallelize EXR f16/rgba8 conversion


2 files changed, 333 insertions(+), 63 deletions(-)

crates/engine/src/media.rs+156-31
......@@ -26,7 +26,7 @@ use std::collections::HashMap;
2626use std::path::{Path, PathBuf};
2727use std::process::Command;
2828#[cfg(not(target_arch = "wasm32"))]
29use std::sync::atomic::{AtomicUsize, Ordering};
29use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
3030#[cfg(not(target_arch = "wasm32"))]
3131use std::sync::{Condvar, mpsc};
3232use std::sync::{Arc, Mutex, RwLock};
......@@ -254,6 +254,11 @@ impl MediaState {
254254 let _ = path;
255255 }
256256
257 #[cfg(not(target_arch = "wasm32"))]
258 fn is_over_soft_budget(&self) -> bool {
259 self.budget_bytes > 0 && self.total_bytes >= (self.budget_bytes * 3) / 4
260 }
261
257262 fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) {
258263 let bytes = decoded.byte_size();
259264 self.tick += 1;
......@@ -314,6 +319,8 @@ struct MediaShared {
314319 state: Mutex<MediaState>,
315320 #[cfg(not(target_arch = "wasm32"))]
316321 cv: Condvar,
322 #[cfg(not(target_arch = "wasm32"))]
323 soft_budget_exceeded: AtomicBool,
317324}
318325
319326impl MediaShared {
......@@ -322,9 +329,29 @@ impl MediaShared {
322329 state: Mutex::new(MediaState::new(budget_bytes)),
323330 #[cfg(not(target_arch = "wasm32"))]
324331 cv: Condvar::new(),
332 #[cfg(not(target_arch = "wasm32"))]
333 soft_budget_exceeded: AtomicBool::new(false),
325334 }
326335 }
327336
337 fn sync_soft_budget(&self, state: &MediaState) {
338 #[cfg(not(target_arch = "wasm32"))]
339 self.soft_budget_exceeded
340 .store(state.is_over_soft_budget(), Ordering::Relaxed);
341 #[cfg(target_arch = "wasm32")]
342 let _ = state;
343 }
344
345 fn insert_cached_locked(
346 &self,
347 state: &mut MediaState,
348 cache_key: ImageCacheKey,
349 decoded: DecodedImage,
350 ) {
351 state.insert_cached(cache_key, decoded);
352 self.sync_soft_budget(state);
353 }
354
328355 fn path_exists_cached(&self, path: &Path) -> bool {
329356 if virtual_bytes(path).is_some() {
330357 return true;
......@@ -646,6 +673,7 @@ impl MediaCache {
646673 state.generation = state.generation.wrapping_add(1);
647674 #[cfg(not(target_arch = "wasm32"))]
648675 state.known_existing_paths.clear();
676 self.shared.sync_soft_budget(&state);
649677 }
650678 drop(cleared_decoders);
651679 #[cfg(not(target_arch = "wasm32"))]
......@@ -698,6 +726,7 @@ impl MediaCache {
698726 state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size());
699727 }
700728 }
729 self.shared.sync_soft_budget(&state);
701730 }
702731
703732 pub fn entry_count(&self) -> usize {
......@@ -790,7 +819,8 @@ impl MediaCache {
790819 in_flight_guard.key = None;
791820 }
792821 if state.generation == cache_gen {
793 state.insert_cached(cache_key, decoded.clone());
822 self.shared
823 .insert_cached_locked(&mut state, cache_key, decoded.clone());
794824 }
795825 #[cfg(not(target_arch = "wasm32"))]
796826 self.shared.cv.notify_all();
......@@ -874,7 +904,8 @@ impl MediaCache {
874904 }
875905 if state.generation == cache_gen {
876906 state.record_existing_path(&resolved);
877 state.insert_cached(cache_key, decoded.clone());
907 self.shared
908 .insert_cached_locked(&mut state, cache_key, decoded.clone());
878909 }
879910 #[cfg(not(target_arch = "wasm32"))]
880911 self.shared.cv.notify_all();
......@@ -1020,7 +1051,7 @@ impl MediaCache {
10201051 return;
10211052 }
10221053 let workers = std::thread::available_parallelism()
1023 .map(|n| n.get().clamp(1, 8))
1054 .map(|n| n.get().clamp(2, 12))
10241055 .unwrap_or(4)
10251056 .min(total_units);
10261057
......@@ -1088,7 +1119,8 @@ impl MediaCache {
10881119 state.in_flight.remove(&key);
10891120 guard.key = None;
10901121 if state.generation == cache_gen {
1091 state.insert_cached(key, decoded);
1122 self.shared
1123 .insert_cached_locked(&mut state, key, decoded);
10921124 }
10931125 self.shared.cv.notify_all();
10941126 }
......@@ -1143,7 +1175,7 @@ fn finish_raster_job(
11431175 if let Some(decoded) = decoded {
11441176 if state.generation == cache_gen {
11451177 state.record_existing_path(&key.path);
1146 state.insert_cached(key, decoded);
1178 shared.insert_cached_locked(&mut state, key, decoded);
11471179 }
11481180 } else {
11491181 state.evict_existing_path(&key.path);
......@@ -1224,7 +1256,7 @@ impl MediaPrefetchHandle {
12241256 cv: Condvar::new(),
12251257 });
12261258 let worker_count = std::thread::available_parallelism()
1227 .map(|n| n.get().clamp(2, 6))
1259 .map(|n| n.get().clamp(2, 12))
12281260 .unwrap_or(4);
12291261 let mut workers = Vec::with_capacity(worker_count);
12301262 for _ in 0..worker_count {
......@@ -1333,14 +1365,13 @@ impl MediaPrefetchHandle {
13331365 if q.cancelled {
13341366 return;
13351367 }
1336 q.prune_stale();
13371368 let best_raster = q
13381369 .raster
13391370 .iter()
13401371 .enumerate()
13411372 .min_by_key(|&(_, (seq, _))| *seq)
13421373 .map(|(idx, (seq, _))| (idx, *seq));
1343 let mut best_video: Option<(PathBuf, usize, usize)> = None;
1374 let mut best_video: Option<(&PathBuf, usize, usize)> = None;
13441375 for (path, vq) in &q.videos {
13451376 if q.active_videos.contains(path) {
13461377 continue;
......@@ -1349,7 +1380,7 @@ impl MediaPrefetchHandle {
13491380 vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq)
13501381 {
13511382 if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) {
1352 best_video = Some((path.clone(), v_idx, seq));
1383 best_video = Some((path, v_idx, seq));
13531384 }
13541385 }
13551386 }
......@@ -1375,28 +1406,27 @@ impl MediaPrefetchHandle {
13751406 continue;
13761407 }
13771408
1378 if chosen_seq > q.current_seq.saturating_add(1) {
1379 let over_soft_budget = shared.state.lock().is_ok_and(|s| {
1380 s.budget_bytes > 0 && s.total_bytes >= (s.budget_bytes * 3) / 4
1381 });
1382 if over_soft_budget {
1383 q = match queue.cv.wait(q) {
1384 Ok(g) => g,
1385 Err(_) => return,
1386 };
1387 continue;
1388 }
1409 if chosen_seq > q.current_seq.saturating_add(1)
1410 && shared.soft_budget_exceeded.load(Ordering::Relaxed)
1411 {
1412 q = match queue.cv.wait(q) {
1413 Ok(g) => g,
1414 Err(_) => return,
1415 };
1416 continue;
13891417 }
13901418
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)) {
1394 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
1395 q.videos.remove(&path);
1396 }
1397 q.active_videos.insert(path.clone());
1398 break PrefetchWorkItem::Video(path, req);
1419 let chosen_video = best_video
1420 .filter(|&(_, _, vs)| best_raster.is_none_or(|(_, rs)| vs <= rs))
1421 .map(|(path, v_idx, _)| (path.clone(), v_idx));
1422
1423 if let Some((path, v_idx)) = chosen_video {
1424 if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) {
1425 if q.videos.get(&path).is_some_and(VecDeque::is_empty) {
1426 q.videos.remove(&path);
13991427 }
1428 q.active_videos.insert(path.clone());
1429 break PrefetchWorkItem::Video(path, req);
14001430 }
14011431 }
14021432 if let Some((r_idx, _)) = best_raster {
......@@ -1437,7 +1467,9 @@ impl MediaPrefetchHandle {
14371467 fn drop(&mut self) {
14381468 if let Ok(mut q) = self.queue.state.lock() {
14391469 q.active_videos.remove(&self.path);
1440 self.queue.cv.notify_all();
1470 if q.videos.contains_key(&self.path) || !q.raster.is_empty() {
1471 self.queue.cv.notify_one();
1472 }
14411473 }
14421474 }
14431475 }
......@@ -1488,7 +1520,7 @@ impl MediaPrefetchHandle {
14881520 state.in_flight.remove(&key);
14891521 guard.key = None;
14901522 if state.generation == cache_gen {
1491 state.insert_cached(key, decoded);
1523 shared.insert_cached_locked(&mut state, key, decoded);
14921524 }
14931525 shared.cv.notify_all();
14941526 }
......@@ -3136,4 +3168,97 @@ mod tests {
31363168 handle.cancel();
31373169 let _ = std::fs::remove_dir_all(&dir);
31383170 }
3171
3172 #[cfg(not(target_arch = "wasm32"))]
3173 #[test]
3174 fn prefetch_handle_scales_and_decodes_nine_videos_concurrently() {
3175 let dir = std::env::temp_dir().join(format!("fission_9vid_prefetch_{}", std::process::id()));
3176 let _ = std::fs::remove_dir_all(&dir);
3177 std::fs::create_dir_all(&dir).unwrap();
3178
3179 let v0 = dir.join("v0.mp4");
3180 let ok = Command::new("ffmpeg")
3181 .args([
3182 "-y",
3183 "-v",
3184 "error",
3185 "-f",
3186 "lavfi",
3187 "-i",
3188 "color=c=green:size=16x16:rate=24:duration=0.15",
3189 "-c:v",
3190 "libx264",
3191 "-pix_fmt",
3192 "yuv420p",
3193 ])
3194 .arg(&v0)
3195 .status()
3196 .is_ok_and(|s| s.success());
3197 if !ok {
3198 let _ = std::fs::remove_dir_all(&dir);
3199 return;
3200 }
3201
3202 let esc = |p: &Path| p.to_string_lossy().replace('\\', "\\\\");
3203 let mut tools = String::new();
3204 for i in 0..9 {
3205 let vi = dir.join(format!("v{i}.mp4"));
3206 if i > 0 {
3207 std::fs::copy(&v0, &vi).unwrap();
3208 }
3209 tools.push_str(&format!(
3210 r#" V{i} = Loader {{
3211 Clips = {{
3212 Clip {{
3213 ID = "Clip1",
3214 Filename = "{}",
3215 FormatID = "QuickTimeMovies",
3216 Length = 3,
3217 GlobalStart = 0,
3218 GlobalEnd = 2,
3219 }},
3220 }},
3221 }},
3222"#,
3223 esc(&vi)
3224 ));
3225 }
3226 let mut prev = "V0".to_owned();
3227 for i in 1..9 {
3228 let mname = format!("M{i}");
3229 tools.push_str(&format!(
3230 r#" {mname} = Merge {{
3231 Inputs = {{
3232 Background = Input {{ SourceOp = "{prev}", Source = "Output", }},
3233 Foreground = Input {{ SourceOp = "V{i}", Source = "Output", }},
3234 }},
3235 }},
3236"#
3237 ));
3238 prev = mname;
3239 }
3240 let comp_src = format!(
3241 "Composition {{\n CurrentTime = 0,\n RenderRange = {{ 0, 2 }},\n GlobalRange = {{ 0, 2 }},\n Tools = ordered() {{\n{tools} }},\n}}"
3242 );
3243 let comp = Comp::from_fusion_str(&comp_src).expect("parse 9-video comp");
3244 let target = comp.find_node("M8").expect("M8");
3245 let expr = model::ExprEngine::new();
3246 let cache = MediaCache::new(64);
3247
3248 let mut handle = cache.start_frame_prefetch(4);
3249 let expected_workers = std::thread::available_parallelism()
3250 .map(|n| n.get().clamp(2, 12))
3251 .unwrap_or(4);
3252 assert_eq!(handle.workers.len(), expected_workers);
3253
3254 handle.enqueue_frame(&comp, target, 0, 0.0, &expr, false);
3255 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
3256 while cache.entry_count() < 9 && std::time::Instant::now() < deadline {
3257 std::thread::sleep(std::time::Duration::from_millis(5));
3258 }
3259 assert_eq!(cache.video_decoder_count(), 9);
3260 assert_eq!(cache.entry_count(), 9);
3261 handle.cancel();
3262 let _ = std::fs::remove_dir_all(&dir);
3263 }
31393264}
crates/engine/src/media/exr.rs+177-32
......@@ -198,6 +198,108 @@ pub(super) fn decode_exr_rgba(
198198 }
199199}
200200
201fn convert_exr_rgba_slice(
202 raw_f32: &mut [f32],
203 raw_f16: &mut [u16],
204 raw: &mut [u8],
205 has_g: bool,
206 has_b: bool,
207 has_a: bool,
208 post_multiply: bool,
209) {
210 debug_assert_eq!(raw_f32.len(), raw_f16.len());
211 debug_assert_eq!(raw_f32.len(), raw.len());
212 debug_assert_eq!(raw_f32.len() % 4, 0);
213
214 for ((px_f32, px_f16), px_u8) in raw_f32
215 .chunks_exact_mut(4)
216 .zip(raw_f16.chunks_exact_mut(4))
217 .zip(raw.chunks_exact_mut(4))
218 {
219 let mut r_raw = px_f32[0];
220 let mut g_raw = if has_g { px_f32[1] } else { r_raw };
221 let mut b_raw = if has_b { px_f32[2] } else { r_raw };
222 let a_raw = if has_a { px_f32[3] } else { 1.0 };
223
224 if post_multiply && a_raw < 1.0 {
225 let a_mul = a_raw.clamp(0.0, 1.0);
226 r_raw *= a_mul;
227 g_raw *= a_mul;
228 b_raw *= a_mul;
229 }
230 px_f32[0] = r_raw;
231 px_f32[1] = g_raw;
232 px_f32[2] = b_raw;
233 px_f32[3] = a_raw;
234
235 px_f16[0] = f32_to_f16_bits(r_raw);
236 px_f16[1] = f32_to_f16_bits(g_raw);
237 px_f16[2] = f32_to_f16_bits(b_raw);
238 px_f16[3] = f32_to_f16_bits(a_raw);
239
240 let a = a_raw.clamp(0.0, 1.0);
241 let r = r_raw.clamp(0.0, 1.0);
242 let g = g_raw.clamp(0.0, 1.0);
243 let b = b_raw.clamp(0.0, 1.0);
244 px_u8[0] = (r * 255.0 + 0.5) as u8;
245 px_u8[1] = (g * 255.0 + 0.5) as u8;
246 px_u8[2] = (b * 255.0 + 0.5) as u8;
247 px_u8[3] = (a * 255.0 + 0.5) as u8;
248 }
249}
250
251fn convert_exr_rgba_buffers(
252 raw_f32: &mut [f32],
253 raw_f16: &mut [u16],
254 raw: &mut [u8],
255 has_g: bool,
256 has_b: bool,
257 has_a: bool,
258 post_multiply: bool,
259) {
260 #[cfg(not(target_arch = "wasm32"))]
261 {
262 const PARALLEL_THRESHOLD_PIXELS: usize = 512 * 512;
263 let total_px = raw_f32.len() / 4;
264 if total_px >= PARALLEL_THRESHOLD_PIXELS {
265 let workers = std::thread::available_parallelism()
266 .map(|n| n.get().clamp(2, 12))
267 .unwrap_or(4)
268 .min(total_px);
269 let chunk_elems = total_px.div_ceil(workers).max(1) * 4;
270 std::thread::scope(|scope| {
271 for ((f32_chunk, f16_chunk), u8_chunk) in raw_f32
272 .chunks_mut(chunk_elems)
273 .zip(raw_f16.chunks_mut(chunk_elems))
274 .zip(raw.chunks_mut(chunk_elems))
275 {
276 scope.spawn(move || {
277 convert_exr_rgba_slice(
278 f32_chunk,
279 f16_chunk,
280 u8_chunk,
281 has_g,
282 has_b,
283 has_a,
284 post_multiply,
285 );
286 });
287 }
288 });
289 return;
290 }
291 }
292 convert_exr_rgba_slice(
293 raw_f32,
294 raw_f16,
295 raw,
296 has_g,
297 has_b,
298 has_a,
299 post_multiply,
300 );
301}
302
201303fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
202304 reader: R,
203305 [red_name, green_name, blue_name, alpha_name]: [Option<&str>; 4],
......@@ -290,38 +392,15 @@ fn decode_exr_from<R: std::io::Read + std::io::Seek + Send>(
290392
291393 let mut raw = vec![0u8; w * h * 4];
292394 let mut raw_f16 = vec![0u16; w * h * 4];
293 for i in 0..(w * h) {
294 let off = i * 4;
295 let mut r_raw = raw_f32[off];
296 let mut g_raw = if g_loc.is_some() { raw_f32[off + 1] } else { r_raw };
297 let mut b_raw = if b_loc.is_some() { raw_f32[off + 2] } else { r_raw };
298 let a_raw = if a_loc.is_some() { raw_f32[off + 3] } else { 1.0 };
299
300 if post_multiply && a_raw < 1.0 {
301 let a_mul = a_raw.clamp(0.0, 1.0);
302 r_raw *= a_mul;
303 g_raw *= a_mul;
304 b_raw *= a_mul;
305 }
306 raw_f32[off] = r_raw;
307 raw_f32[off + 1] = g_raw;
308 raw_f32[off + 2] = b_raw;
309 raw_f32[off + 3] = a_raw;
310
311 raw_f16[off] = f32_to_f16_bits(r_raw);
312 raw_f16[off + 1] = f32_to_f16_bits(g_raw);
313 raw_f16[off + 2] = f32_to_f16_bits(b_raw);
314 raw_f16[off + 3] = f32_to_f16_bits(a_raw);
315
316 let a = a_raw.clamp(0.0, 1.0);
317 let r = r_raw.clamp(0.0, 1.0);
318 let g = g_raw.clamp(0.0, 1.0);
319 let b = b_raw.clamp(0.0, 1.0);
320 raw[off] = (r * 255.0 + 0.5) as u8;
321 raw[off + 1] = (g * 255.0 + 0.5) as u8;
322 raw[off + 2] = (b * 255.0 + 0.5) as u8;
323 raw[off + 3] = (a * 255.0 + 0.5) as u8;
324 }
395 convert_exr_rgba_buffers(
396 &mut raw_f32,
397 &mut raw_f16,
398 &mut raw,
399 g_loc.is_some(),
400 b_loc.is_some(),
401 a_loc.is_some(),
402 post_multiply,
403 );
325404 Some(DecodedImage {
326405 size: [w as u32, h as u32],
327406 rgba: Arc::new(raw),
......@@ -346,4 +425,70 @@ mod tests {
346425 assert_eq!(decoded.size, [2, 1]);
347426 assert_eq!(&decoded.rgba_f32.unwrap()[..4], &[2.5, 0.5, 0.0, 1.0]);
348427 }
428
429 #[test]
430 fn parallel_exr_conversion_matches_scalar_bit_for_bit() {
431 let pixels = 512 * 512 + 17;
432 let special: [[f32; 4]; 10] = [
433 [0.0, 0.25, 0.5, 1.0],
434 [12.5, 1.0001, 65504.0, 0.5],
435 [100000.0, -0.5, -12.25, 0.25],
436 [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.75],
437 [1.0e-7, -1.0e-7, 5.960_464_5e-8, 0.0],
438 [0.3333, 0.6667, 0.9999, 1.5],
439 [-0.0, 0.0, f32::from_bits(0x7fc0_0123), -0.25],
440 [2.0, 4.0, 8.0, f32::NAN],
441 [6.103_515_6e-5, 3.051_757_8e-5, 1.525_878_9e-5, 0.999],
442 [0.5, 0.25, 0.125, f32::INFINITY],
443 ];
444 let mut base = Vec::with_capacity(pixels * 4);
445 for i in 0..pixels {
446 let s = special[i % special.len()];
447 let scale = if (i % 7) == 0 { 1.0 } else { ((i % 23) as f32) * 0.125 };
448 if s[0].is_finite() && s[1].is_finite() && s[2].is_finite() && s[3].is_finite() {
449 base.extend_from_slice(&[s[0] * scale, s[1], s[2] + 0.001 * (i % 5) as f32, s[3]]);
450 } else {
451 base.extend_from_slice(&s);
452 }
453 }
454
455 for &(has_g, has_b, has_a, post_multiply) in &[
456 (true, true, true, false),
457 (true, true, true, true),
458 (false, false, false, true),
459 (true, false, true, true),
460 ] {
461 let mut par_f32 = base.clone();
462 let mut par_f16 = vec![0u16; pixels * 4];
463 let mut par_u8 = vec![0u8; pixels * 4];
464 convert_exr_rgba_buffers(
465 &mut par_f32,
466 &mut par_f16,
467 &mut par_u8,
468 has_g,
469 has_b,
470 has_a,
471 post_multiply,
472 );
473
474 let mut seq_f32 = base.clone();
475 let mut seq_f16 = vec![0u16; pixels * 4];
476 let mut seq_u8 = vec![0u8; pixels * 4];
477 convert_exr_rgba_slice(
478 &mut seq_f32,
479 &mut seq_f16,
480 &mut seq_u8,
481 has_g,
482 has_b,
483 has_a,
484 post_multiply,
485 );
486
487 assert_eq!(par_f16, seq_f16, "f16 mismatch for ({has_g},{has_b},{has_a},{post_multiply})");
488 assert_eq!(par_u8, seq_u8, "u8 mismatch for ({has_g},{has_b},{has_a},{post_multiply})");
489 let par_bits: Vec<u32> = par_f32.iter().map(|v| v.to_bits()).collect();
490 let seq_bits: Vec<u32> = seq_f32.iter().map(|v| v.to_bits()).collect();
491 assert_eq!(par_bits, seq_bits, "f32 bits mismatch for ({has_g},{has_b},{has_a},{post_multiply})");
492 }
493 }
349494}