| ... | @@ -26,7 +26,7 @@ use std::collections::HashMap; | ... | @@ -26,7 +26,7 @@ use std::collections::HashMap; |
| 26 | use std::path::{Path, PathBuf}; | 26 | use std::path::{Path, PathBuf}; |
| 27 | use std::process::Command; | 27 | use std::process::Command; |
| 28 | #[cfg(not(target_arch = "wasm32"))] | 28 | #[cfg(not(target_arch = "wasm32"))] |
| 29 | use std::sync::atomic::{AtomicUsize, Ordering}; | 29 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 30 | #[cfg(not(target_arch = "wasm32"))] | 30 | #[cfg(not(target_arch = "wasm32"))] |
| 31 | use std::sync::{Condvar, mpsc}; | 31 | use std::sync::{Condvar, mpsc}; |
| 32 | use std::sync::{Arc, Mutex, RwLock}; | 32 | use std::sync::{Arc, Mutex, RwLock}; |
| ... | @@ -254,6 +254,11 @@ impl MediaState { | ... | @@ -254,6 +254,11 @@ impl MediaState { |
| 254 | let _ = path; | 254 | let _ = path; |
| 255 | } | 255 | } |
| 256 | | 256 | |
| | 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 | |
| 257 | fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { | 262 | fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { |
| 258 | let bytes = decoded.byte_size(); | 263 | let bytes = decoded.byte_size(); |
| 259 | self.tick += 1; | 264 | self.tick += 1; |
| ... | @@ -314,6 +319,8 @@ struct MediaShared { | ... | @@ -314,6 +319,8 @@ struct MediaShared { |
| 314 | state: Mutex<MediaState>, | 319 | state: Mutex<MediaState>, |
| 315 | #[cfg(not(target_arch = "wasm32"))] | 320 | #[cfg(not(target_arch = "wasm32"))] |
| 316 | cv: Condvar, | 321 | cv: Condvar, |
| | 322 | #[cfg(not(target_arch = "wasm32"))] |
| | 323 | soft_budget_exceeded: AtomicBool, |
| 317 | } | 324 | } |
| 318 | | 325 | |
| 319 | impl MediaShared { | 326 | impl MediaShared { |
| ... | @@ -322,9 +329,29 @@ impl MediaShared { | ... | @@ -322,9 +329,29 @@ impl MediaShared { |
| 322 | state: Mutex::new(MediaState::new(budget_bytes)), | 329 | state: Mutex::new(MediaState::new(budget_bytes)), |
| 323 | #[cfg(not(target_arch = "wasm32"))] | 330 | #[cfg(not(target_arch = "wasm32"))] |
| 324 | cv: Condvar::new(), | 331 | cv: Condvar::new(), |
| | 332 | #[cfg(not(target_arch = "wasm32"))] |
| | 333 | soft_budget_exceeded: AtomicBool::new(false), |
| 325 | } | 334 | } |
| 326 | } | 335 | } |
| 327 | | 336 | |
| | 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 | |
| 328 | fn path_exists_cached(&self, path: &Path) -> bool { | 355 | fn path_exists_cached(&self, path: &Path) -> bool { |
| 329 | if virtual_bytes(path).is_some() { | 356 | if virtual_bytes(path).is_some() { |
| 330 | return true; | 357 | return true; |
| ... | @@ -646,6 +673,7 @@ impl MediaCache { | ... | @@ -646,6 +673,7 @@ impl MediaCache { |
| 646 | state.generation = state.generation.wrapping_add(1); | 673 | state.generation = state.generation.wrapping_add(1); |
| 647 | #[cfg(not(target_arch = "wasm32"))] | 674 | #[cfg(not(target_arch = "wasm32"))] |
| 648 | state.known_existing_paths.clear(); | 675 | state.known_existing_paths.clear(); |
| | 676 | self.shared.sync_soft_budget(&state); |
| 649 | } | 677 | } |
| 650 | drop(cleared_decoders); | 678 | drop(cleared_decoders); |
| 651 | #[cfg(not(target_arch = "wasm32"))] | 679 | #[cfg(not(target_arch = "wasm32"))] |
| ... | @@ -698,6 +726,7 @@ impl MediaCache { | ... | @@ -698,6 +726,7 @@ impl MediaCache { |
| 698 | state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size()); | 726 | state.total_bytes = state.total_bytes.saturating_sub(removed.byte_size()); |
| 699 | } | 727 | } |
| 700 | } | 728 | } |
| | 729 | self.shared.sync_soft_budget(&state); |
| 701 | } | 730 | } |
| 702 | | 731 | |
| 703 | pub fn entry_count(&self) -> usize { | 732 | pub fn entry_count(&self) -> usize { |
| ... | @@ -790,7 +819,8 @@ impl MediaCache { | ... | @@ -790,7 +819,8 @@ impl MediaCache { |
| 790 | in_flight_guard.key = None; | 819 | in_flight_guard.key = None; |
| 791 | } | 820 | } |
| 792 | if state.generation == cache_gen { | 821 | 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()); |
| 794 | } | 824 | } |
| 795 | #[cfg(not(target_arch = "wasm32"))] | 825 | #[cfg(not(target_arch = "wasm32"))] |
| 796 | self.shared.cv.notify_all(); | 826 | self.shared.cv.notify_all(); |
| ... | @@ -874,7 +904,8 @@ impl MediaCache { | ... | @@ -874,7 +904,8 @@ impl MediaCache { |
| 874 | } | 904 | } |
| 875 | if state.generation == cache_gen { | 905 | if state.generation == cache_gen { |
| 876 | state.record_existing_path(&resolved); | 906 | 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()); |
| 878 | } | 909 | } |
| 879 | #[cfg(not(target_arch = "wasm32"))] | 910 | #[cfg(not(target_arch = "wasm32"))] |
| 880 | self.shared.cv.notify_all(); | 911 | self.shared.cv.notify_all(); |
| ... | @@ -1020,7 +1051,7 @@ impl MediaCache { | ... | @@ -1020,7 +1051,7 @@ impl MediaCache { |
| 1020 | return; | 1051 | return; |
| 1021 | } | 1052 | } |
| 1022 | let workers = std::thread::available_parallelism() | 1053 | let workers = std::thread::available_parallelism() |
| 1023 | .map(|n| n.get().clamp(1, 8)) | 1054 | .map(|n| n.get().clamp(2, 12)) |
| 1024 | .unwrap_or(4) | 1055 | .unwrap_or(4) |
| 1025 | .min(total_units); | 1056 | .min(total_units); |
| 1026 | | 1057 | |
| ... | @@ -1088,7 +1119,8 @@ impl MediaCache { | ... | @@ -1088,7 +1119,8 @@ impl MediaCache { |
| 1088 | state.in_flight.remove(&key); | 1119 | state.in_flight.remove(&key); |
| 1089 | guard.key = None; | 1120 | guard.key = None; |
| 1090 | if state.generation == cache_gen { | 1121 | if state.generation == cache_gen { |
| 1091 | state.insert_cached(key, decoded); | 1122 | self.shared |
| | 1123 | .insert_cached_locked(&mut state, key, decoded); |
| 1092 | } | 1124 | } |
| 1093 | self.shared.cv.notify_all(); | 1125 | self.shared.cv.notify_all(); |
| 1094 | } | 1126 | } |
| ... | @@ -1143,7 +1175,7 @@ fn finish_raster_job( | ... | @@ -1143,7 +1175,7 @@ fn finish_raster_job( |
| 1143 | if let Some(decoded) = decoded { | 1175 | if let Some(decoded) = decoded { |
| 1144 | if state.generation == cache_gen { | 1176 | if state.generation == cache_gen { |
| 1145 | state.record_existing_path(&key.path); | 1177 | state.record_existing_path(&key.path); |
| 1146 | state.insert_cached(key, decoded); | 1178 | shared.insert_cached_locked(&mut state, key, decoded); |
| 1147 | } | 1179 | } |
| 1148 | } else { | 1180 | } else { |
| 1149 | state.evict_existing_path(&key.path); | 1181 | state.evict_existing_path(&key.path); |
| ... | @@ -1224,7 +1256,7 @@ impl MediaPrefetchHandle { | ... | @@ -1224,7 +1256,7 @@ impl MediaPrefetchHandle { |
| 1224 | cv: Condvar::new(), | 1256 | cv: Condvar::new(), |
| 1225 | }); | 1257 | }); |
| 1226 | let worker_count = std::thread::available_parallelism() | 1258 | let worker_count = std::thread::available_parallelism() |
| 1227 | .map(|n| n.get().clamp(2, 6)) | 1259 | .map(|n| n.get().clamp(2, 12)) |
| 1228 | .unwrap_or(4); | 1260 | .unwrap_or(4); |
| 1229 | let mut workers = Vec::with_capacity(worker_count); | 1261 | let mut workers = Vec::with_capacity(worker_count); |
| 1230 | for _ in 0..worker_count { | 1262 | for _ in 0..worker_count { |
| ... | @@ -1333,14 +1365,13 @@ impl MediaPrefetchHandle { | ... | @@ -1333,14 +1365,13 @@ impl MediaPrefetchHandle { |
| 1333 | if q.cancelled { | 1365 | if q.cancelled { |
| 1334 | return; | 1366 | return; |
| 1335 | } | 1367 | } |
| 1336 | q.prune_stale(); | | |
| 1337 | let best_raster = q | 1368 | let best_raster = q |
| 1338 | .raster | 1369 | .raster |
| 1339 | .iter() | 1370 | .iter() |
| 1340 | .enumerate() | 1371 | .enumerate() |
| 1341 | .min_by_key(|&(_, (seq, _))| *seq) | 1372 | .min_by_key(|&(_, (seq, _))| *seq) |
| 1342 | .map(|(idx, (seq, _))| (idx, *seq)); | 1373 | .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; |
| 1344 | for (path, vq) in &q.videos { | 1375 | for (path, vq) in &q.videos { |
| 1345 | if q.active_videos.contains(path) { | 1376 | if q.active_videos.contains(path) { |
| 1346 | continue; | 1377 | continue; |
| ... | @@ -1349,7 +1380,7 @@ impl MediaPrefetchHandle { | ... | @@ -1349,7 +1380,7 @@ impl MediaPrefetchHandle { |
| 1349 | vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq) | 1380 | vq.iter().enumerate().min_by_key(|&(_, (seq, _))| *seq) |
| 1350 | { | 1381 | { |
| 1351 | if best_video.as_ref().is_none_or(|&(_, _, bseq)| seq < bseq) { | 1382 | 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)); |
| 1353 | } | 1384 | } |
| 1354 | } | 1385 | } |
| 1355 | } | 1386 | } |
| ... | @@ -1375,28 +1406,27 @@ impl MediaPrefetchHandle { | ... | @@ -1375,28 +1406,27 @@ impl MediaPrefetchHandle { |
| 1375 | continue; | 1406 | continue; |
| 1376 | } | 1407 | } |
| 1377 | | 1408 | |
| 1378 | if chosen_seq > q.current_seq.saturating_add(1) { | 1409 | if chosen_seq > q.current_seq.saturating_add(1) |
| 1379 | let over_soft_budget = shared.state.lock().is_ok_and(|s| { | 1410 | && shared.soft_budget_exceeded.load(Ordering::Relaxed) |
| 1380 | s.budget_bytes > 0 && s.total_bytes >= (s.budget_bytes * 3) / 4 | 1411 | { |
| 1381 | }); | 1412 | q = match queue.cv.wait(q) { |
| 1382 | if over_soft_budget { | 1413 | Ok(g) => g, |
| 1383 | q = match queue.cv.wait(q) { | 1414 | Err(_) => return, |
| 1384 | Ok(g) => g, | 1415 | }; |
| 1385 | Err(_) => return, | 1416 | continue; |
| 1386 | }; | | |
| 1387 | continue; | | |
| 1388 | } | | |
| 1389 | } | 1417 | } |
| 1390 | | 1418 | |
| 1391 | if let Some((path, v_idx, vs)) = best_video { | 1419 | let chosen_video = best_video |
| 1392 | if best_raster.is_none_or(|(_, rs)| vs <= rs) { | 1420 | .filter(|&(_, _, vs)| 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)) { | 1421 | .map(|(path, v_idx, _)| (path.clone(), v_idx)); |
| 1394 | if q.videos.get(&path).is_some_and(VecDeque::is_empty) { | 1422 | |
| 1395 | q.videos.remove(&path); | 1423 | if let Some((path, v_idx)) = chosen_video { |
| 1396 | } | 1424 | if let Some((_, req)) = q.videos.get_mut(&path).and_then(|vq| vq.remove(v_idx)) { |
| 1397 | q.active_videos.insert(path.clone()); | 1425 | if q.videos.get(&path).is_some_and(VecDeque::is_empty) { |
| 1398 | break PrefetchWorkItem::Video(path, req); | 1426 | q.videos.remove(&path); |
| 1399 | } | 1427 | } |
| | 1428 | q.active_videos.insert(path.clone()); |
| | 1429 | break PrefetchWorkItem::Video(path, req); |
| 1400 | } | 1430 | } |
| 1401 | } | 1431 | } |
| 1402 | if let Some((r_idx, _)) = best_raster { | 1432 | if let Some((r_idx, _)) = best_raster { |
| ... | @@ -1437,7 +1467,9 @@ impl MediaPrefetchHandle { | ... | @@ -1437,7 +1467,9 @@ impl MediaPrefetchHandle { |
| 1437 | fn drop(&mut self) { | 1467 | fn drop(&mut self) { |
| 1438 | if let Ok(mut q) = self.queue.state.lock() { | 1468 | if let Ok(mut q) = self.queue.state.lock() { |
| 1439 | q.active_videos.remove(&self.path); | 1469 | 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 | } |
| 1441 | } | 1473 | } |
| 1442 | } | 1474 | } |
| 1443 | } | 1475 | } |
| ... | @@ -1488,7 +1520,7 @@ impl MediaPrefetchHandle { | ... | @@ -1488,7 +1520,7 @@ impl MediaPrefetchHandle { |
| 1488 | state.in_flight.remove(&key); | 1520 | state.in_flight.remove(&key); |
| 1489 | guard.key = None; | 1521 | guard.key = None; |
| 1490 | if state.generation == cache_gen { | 1522 | if state.generation == cache_gen { |
| 1491 | state.insert_cached(key, decoded); | 1523 | shared.insert_cached_locked(&mut state, key, decoded); |
| 1492 | } | 1524 | } |
| 1493 | shared.cv.notify_all(); | 1525 | shared.cv.notify_all(); |
| 1494 | } | 1526 | } |
| ... | @@ -3136,4 +3168,97 @@ mod tests { | ... | @@ -3136,4 +3168,97 @@ mod tests { |
| 3136 | handle.cancel(); | 3168 | handle.cancel(); |
| 3137 | let _ = std::fs::remove_dir_all(&dir); | 3169 | let _ = std::fs::remove_dir_all(&dir); |
| 3138 | } | 3170 | } |
| | 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 | } |
| 3139 | } | 3264 | } |