| author | |
| committer | |
| log | 9f6cd5fe8fd066b899ef73513343ff2e092bd205 |
| tree | 2c817fae5260d74f6dcc672b4f55d06d0e09f06d |
| parent | 55cdc1e13f4125b23a1a296db6a19a27bb6b4996 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
5 files changed, 471 insertions(+), 69 deletions(-)
crates/app/src/export_ui.rs+21-7| ... | @@ -168,6 +168,9 @@ pub(crate) fn build_status_strip( | ... | @@ -168,6 +168,9 @@ pub(crate) fn build_status_strip( |
| 168 | actions | 168 | actions |
| 169 | } | 169 | } |
| 170 | 170 | ||
| 171 | const EXPORT_VRAM_BUDGET_BYTES: u64 = 256 * 1024 * 1024; | ||
| 172 | const EXPORT_MEDIA_BUDGET_BYTES: u64 = 128 * 1024 * 1024; | ||
| 173 | |||
| 171 | impl Studio { | 174 | impl Studio { |
| 172 | pub(crate) fn poll_export(&mut self) { | 175 | pub(crate) fn poll_export(&mut self) { |
| 173 | let Some(exp) = &self.active_export else { | 176 | let Some(exp) = &self.active_export else { |
| ... | @@ -179,6 +182,7 @@ impl Studio { | ... | @@ -179,6 +182,7 @@ impl Studio { |
| 179 | if let Some(handle) = finished.handle.take() { | 182 | if let Some(handle) = finished.handle.take() { |
| 180 | let _ = handle.join(); | 183 | let _ = handle.join(); |
| 181 | } | 184 | } |
| 185 | self.last_prefetch_sig = None; | ||
| 182 | match outcome { | 186 | match outcome { |
| 183 | ExportOutcome::Completed(msg) => { | 187 | ExportOutcome::Completed(msg) => { |
| 184 | eprintln!("{msg}"); | 188 | eprintln!("{msg}"); |
| ... | @@ -199,6 +203,7 @@ impl Studio { | ... | @@ -199,6 +203,7 @@ impl Studio { |
| 199 | if let Some(handle) = finished.handle.take() { | 203 | if let Some(handle) = finished.handle.take() { |
| 200 | let _ = handle.join(); | 204 | let _ = handle.join(); |
| 201 | } | 205 | } |
| 206 | self.last_prefetch_sig = None; | ||
| 202 | self.set_notice("Export worker stopped unexpectedly"); | 207 | self.set_notice("Export worker stopped unexpectedly"); |
| 203 | } | 208 | } |
| 204 | Err(mpsc::TryRecvError::Empty) => {} | 209 | Err(mpsc::TryRecvError::Empty) => {} |
| ... | @@ -218,6 +223,8 @@ impl Studio { | ... | @@ -218,6 +223,8 @@ impl Studio { |
| 218 | control.update_progress(&initial_progress); | 223 | control.update_progress(&initial_progress); |
| 219 | let ctrl_worker = control.clone(); | 224 | let ctrl_worker = control.clone(); |
| 220 | let proxy = self.redraw_proxy.clone(); | 225 | let proxy = self.redraw_proxy.clone(); |
| 226 | let export_device = self.engine.device_arc(); | ||
| 227 | let export_queue = self.engine.queue_arc(); | ||
| 221 | let (tx, rx) = mpsc::channel(); | 228 | let (tx, rx) = mpsc::channel(); |
| 222 | 229 | ||
| 223 | let handle = std::thread::Builder::new() | 230 | let handle = std::thread::Builder::new() |
| ... | @@ -228,19 +235,26 @@ impl Studio { | ... | @@ -228,19 +235,26 @@ impl Studio { |
| 228 | let _ = p.send_event(UserEvent::Redraw); | 235 | let _ = p.send_event(UserEvent::Redraw); |
| 229 | } | 236 | } |
| 230 | }; | 237 | }; |
| 231 | let outcome = match Engine::new_headless() { | 238 | let mut export_engine = Engine::new_with_device( |
| 232 | Ok(mut export_engine) => match job(&mut export_engine, &ctrl_worker, &notify_redraw) { | 239 | export_device, |
| 233 | Ok(msg) => ExportOutcome::Completed(msg), | 240 | export_queue, |
| 234 | Err(e) if e == "Cancelled" => ExportOutcome::Cancelled, | 241 | EXPORT_VRAM_BUDGET_BYTES, |
| 235 | Err(e) => ExportOutcome::Failed(e), | 242 | EXPORT_MEDIA_BUDGET_BYTES, |
| 236 | }, | 243 | ); |
| 237 | Err(e) => ExportOutcome::Failed(format!("Failed to initialize export GPU: {e}")), | 244 | let outcome = match job(&mut export_engine, &ctrl_worker, &notify_redraw) { |
| 245 | Ok(msg) => ExportOutcome::Completed(msg), | ||
| 246 | Err(e) if e == "Cancelled" => ExportOutcome::Cancelled, | ||
| 247 | Err(e) => ExportOutcome::Failed(e), | ||
| 238 | }; | 248 | }; |
| 239 | let _ = tx.send(outcome); | 249 | let _ = tx.send(outcome); |
| 240 | notify_redraw(); | 250 | notify_redraw(); |
| 241 | }) | 251 | }) |
| 242 | .map_err(|e| format!("Failed to start export thread: {e}"))?; | 252 | .map_err(|e| format!("Failed to start export thread: {e}"))?; |
| 243 | 253 | ||
| 254 | if let Some(pf) = &self.prefetcher { | ||
| 255 | pf.cancel(); | ||
| 256 | } | ||
| 257 | self.last_prefetch_sig = None; | ||
| 244 | self.active_export = Some(ActiveExport { | 258 | self.active_export = Some(ActiveExport { |
| 245 | kind, | 259 | kind, |
| 246 | control, | 260 | control, |
crates/app/src/main.rs+155-4| ... | @@ -158,6 +158,7 @@ impl Studio { | ... | @@ -158,6 +158,7 @@ impl Studio { |
| 158 | dual_viewer: bool, | 158 | dual_viewer: bool, |
| 159 | show_keyframes: bool, | 159 | show_keyframes: bool, |
| 160 | enable_audio: bool, | 160 | enable_audio: bool, |
| 161 | interactive: bool, | ||
| 161 | ) -> Self { | 162 | ) -> Self { |
| 162 | let engine = Engine::new(renderer.device().clone(), renderer.queue().clone()); | 163 | let engine = Engine::new(renderer.device().clone(), renderer.queue().clone()); |
| 163 | // Knife's soft toned Iris quiet-layered theme! | 164 | // Knife's soft toned Iris quiet-layered theme! |
| ... | @@ -294,8 +295,12 @@ impl Studio { | ... | @@ -294,8 +295,12 @@ impl Studio { |
| 294 | let inspector = InspectorState::new(&ui_theme); | 295 | let inspector = InspectorState::new(&ui_theme); |
| 295 | let add_tool = AddToolLauncher::new(); | 296 | let add_tool = AddToolLauncher::new(); |
| 296 | let ram_cache = RamFrameCache::new(DEFAULT_RAM_CACHE_MB); | 297 | let ram_cache = RamFrameCache::new(DEFAULT_RAM_CACHE_MB); |
| 297 | let prefetcher = if enable_audio { | 298 | let prefetcher = if interactive { |
| 298 | Some(RamPrefetcher::new(ram_cache.clone(), engine.vram_budget_mb())) | 299 | Some(RamPrefetcher::new_with_device( |
| 300 | engine.device_arc(), | ||
| 301 | engine.queue_arc(), | ||
| 302 | ram_cache.clone(), | ||
| 303 | )) | ||
| 299 | } else { | 304 | } else { |
| 300 | None | 305 | None |
| 301 | }; | 306 | }; |
| ... | @@ -963,6 +968,7 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box<dyn Error>> { | ... | @@ -963,6 +968,7 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box<dyn Error>> { |
| 963 | cli.dual_viewer, | 968 | cli.dual_viewer, |
| 964 | cli.show_keyframes, | 969 | cli.show_keyframes, |
| 965 | false, | 970 | false, |
| 971 | false, | ||
| 966 | ); | 972 | ); |
| 967 | // Load audio waveform peaks if available so snapshot verifies the waveform overlay too | 973 | // Load audio waveform peaks if available so snapshot verifies the waveform overlay too |
| 968 | load_snapshot_audio_peaks(&mut studio); | 974 | load_snapshot_audio_peaks(&mut studio); |
| ... | @@ -1073,6 +1079,7 @@ impl WindowHost { | ... | @@ -1073,6 +1079,7 @@ impl WindowHost { |
| 1073 | cli.dual_viewer, | 1079 | cli.dual_viewer, |
| 1074 | cli.show_keyframes, | 1080 | cli.show_keyframes, |
| 1075 | true, | 1081 | true, |
| 1082 | true, | ||
| 1076 | ); | 1083 | ); |
| 1077 | studio.redraw_proxy = Some(proxy.clone()); | 1084 | studio.redraw_proxy = Some(proxy.clone()); |
| 1078 | studio.ui.window_focused = window.has_focus(); | 1085 | studio.ui.window_focused = window.has_focus(); |
| ... | @@ -1287,13 +1294,17 @@ mod tests { | ... | @@ -1287,13 +1294,17 @@ mod tests { |
| 1287 | }, | 1294 | }, |
| 1288 | }"#; | 1295 | }"#; |
| 1289 | 1296 | ||
| 1290 | fn studio() -> Studio { | 1297 | fn studio_with_flags(enable_audio: bool, interactive: bool) -> Studio { |
| 1291 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); | 1298 | let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); |
| 1292 | let adapter = pollster::block_on(instance.request_adapter(&Default::default())).expect("adapter"); | 1299 | let adapter = pollster::block_on(instance.request_adapter(&Default::default())).expect("adapter"); |
| 1293 | let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).expect("device"); | 1300 | let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).expect("device"); |
| 1294 | let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm); | 1301 | let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm); |
| 1295 | let comp = Comp::from_fusion_str(COMP).expect("comp"); | 1302 | let comp = Comp::from_fusion_str(COMP).expect("comp"); |
| 1296 | Studio::new(renderer, comp, None, None, true, false, false) | 1303 | Studio::new(renderer, comp, None, None, true, false, enable_audio, interactive) |
| 1304 | } | ||
| 1305 | |||
| 1306 | fn studio() -> Studio { | ||
| 1307 | studio_with_flags(false, false) | ||
| 1297 | } | 1308 | } |
| 1298 | 1309 | ||
| 1299 | fn id(studio: &Studio, name: &str) -> NodeId { | 1310 | fn id(studio: &Studio, name: &str) -> NodeId { |
| ... | @@ -1380,4 +1391,144 @@ mod tests { | ... | @@ -1380,4 +1391,144 @@ mod tests { |
| 1380 | assert!(!studio.add_tool.open); | 1391 | assert!(!studio.add_tool.open); |
| 1381 | assert!(studio.status_notice.as_ref().is_some_and(|(m, _)| m.contains("read-only"))); | 1392 | assert!(studio.status_notice.as_ref().is_some_and(|(m, _)| m.contains("read-only"))); |
| 1382 | } | 1393 | } |
| 1394 | |||
| 1395 | #[test] | ||
| 1396 | fn interactive_flag_gates_prefetcher_independently_of_audio() { | ||
| 1397 | let interactive_no_audio = studio_with_flags(false, true); | ||
| 1398 | assert!(!interactive_no_audio.enable_audio); | ||
| 1399 | assert!(interactive_no_audio.audio_player.is_none()); | ||
| 1400 | assert!(interactive_no_audio.prefetcher.is_some()); | ||
| 1401 | |||
| 1402 | let non_interactive = studio_with_flags(false, false); | ||
| 1403 | assert!(non_interactive.prefetcher.is_none()); | ||
| 1404 | } | ||
| 1405 | |||
| 1406 | #[test] | ||
| 1407 | fn undo_redo_preserves_media_cache_while_bust_all_clears_it() { | ||
| 1408 | let mut studio = studio(); | ||
| 1409 | let dir = std::env::temp_dir().join("fission_undo_media_preserve_test"); | ||
| 1410 | let _ = std::fs::create_dir_all(&dir); | ||
| 1411 | let png_path = dir.join("tiny.png"); | ||
| 1412 | { | ||
| 1413 | let f = std::fs::File::create(&png_path).expect("create png"); | ||
| 1414 | let mut enc = png::Encoder::new(f, 2, 2); | ||
| 1415 | enc.set_color(png::ColorType::Rgba); | ||
| 1416 | enc.set_depth(png::BitDepth::Eight); | ||
| 1417 | enc.write_header() | ||
| 1418 | .unwrap() | ||
| 1419 | .write_image_data(&[255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255]) | ||
| 1420 | .unwrap(); | ||
| 1421 | } | ||
| 1422 | let clip = model::ClipSpec { | ||
| 1423 | filename: png_path.to_string_lossy().into_owned(), | ||
| 1424 | alternate_filename: None, | ||
| 1425 | start_frame: 0, | ||
| 1426 | length: Some(1), | ||
| 1427 | trim_in: 0, | ||
| 1428 | trim_out: 0, | ||
| 1429 | global_start: 0, | ||
| 1430 | global_end: 0, | ||
| 1431 | extend_first: 0, | ||
| 1432 | extend_last: 0, | ||
| 1433 | loop_clip: false, | ||
| 1434 | reverse: false, | ||
| 1435 | }; | ||
| 1436 | assert!(studio.engine.media.load_clip(&clip, 0, false, [None; 4]).is_some()); | ||
| 1437 | assert_eq!(studio.engine.media.entry_count(), 1); | ||
| 1438 | |||
| 1439 | // Seed GPU cache and stale RAM cache entry, then perform an edit + undo + redo. | ||
| 1440 | let merge = id(&studio, "Merge1"); | ||
| 1441 | let _ = studio.engine.evaluate(&studio.comp, merge, 0.0); | ||
| 1442 | assert!(studio.engine.cache.entry_count() > 0); | ||
| 1443 | let stale_rev = studio.comp.revision.wrapping_add(999); | ||
| 1444 | studio.ram_cache.insert( | ||
| 1445 | engine::RamFrameKey { | ||
| 1446 | target: merge, | ||
| 1447 | revision: stale_rev, | ||
| 1448 | frame: 0, | ||
| 1449 | proxy_scale: 1, | ||
| 1450 | hiq: true, | ||
| 1451 | use_proxy_clips: false, | ||
| 1452 | }, | ||
| 1453 | engine::RamFrame { | ||
| 1454 | size: [2, 2], | ||
| 1455 | rgba: Arc::new(vec![0u8; 16]), | ||
| 1456 | eval_ms: 0.1, | ||
| 1457 | }, | ||
| 1458 | ); | ||
| 1459 | assert_eq!(studio.ram_cache.entry_count(), 1); | ||
| 1460 | |||
| 1461 | studio.history.push_snapshot(&studio.comp, "Delete Nodes"); | ||
| 1462 | studio.comp.delete_nodes(&[merge]); | ||
| 1463 | studio.undo(); | ||
| 1464 | assert_eq!( | ||
| 1465 | studio.engine.media.entry_count(), | ||
| 1466 | 1, | ||
| 1467 | "Undo must preserve MediaCache entries" | ||
| 1468 | ); | ||
| 1469 | assert_eq!( | ||
| 1470 | studio.engine.cache.entry_count(), | ||
| 1471 | 0, | ||
| 1472 | "Undo must bust GPU node cache" | ||
| 1473 | ); | ||
| 1474 | assert_eq!( | ||
| 1475 | studio.ram_cache.entry_count(), | ||
| 1476 | 0, | ||
| 1477 | "Undo must evict stale RAM cache revisions" | ||
| 1478 | ); | ||
| 1479 | |||
| 1480 | let _ = studio.engine.evaluate(&studio.comp, id(&studio, "Merge1"), 0.0); | ||
| 1481 | studio.redo(); | ||
| 1482 | assert_eq!( | ||
| 1483 | studio.engine.media.entry_count(), | ||
| 1484 | 1, | ||
| 1485 | "Redo must preserve MediaCache entries" | ||
| 1486 | ); | ||
| 1487 | assert_eq!(studio.engine.cache.entry_count(), 0); | ||
| 1488 | |||
| 1489 | // Explicit Bust All still wipes MediaCache. | ||
| 1490 | studio.route_viewer_actions(vec![(0, ViewerAction::BustAll)], Instant::now()); | ||
| 1491 | assert_eq!(studio.engine.media.entry_count(), 0); | ||
| 1492 | |||
| 1493 | let _ = std::fs::remove_dir_all(&dir); | ||
| 1494 | } | ||
| 1495 | |||
| 1496 | #[test] | ||
| 1497 | fn export_pauses_and_resumes_ram_prefetcher() { | ||
| 1498 | let mut studio = studio_with_flags(false, true); | ||
| 1499 | let (gate_tx, gate_rx) = mpsc::channel::<()>(); | ||
| 1500 | let initial = engine::export::ExportProgress { | ||
| 1501 | total_frames: 1, | ||
| 1502 | label: "TestExport".to_owned(), | ||
| 1503 | ..Default::default() | ||
| 1504 | }; | ||
| 1505 | studio | ||
| 1506 | .spawn_export_worker(export_ui::ExportKind::SaverPngs, initial, move |eng, _, _| { | ||
| 1507 | // Verify shared device Engine can evaluate during export. | ||
| 1508 | let comp = Comp::from_fusion_str(COMP).unwrap(); | ||
| 1509 | let target = comp.find_node("Merge1").unwrap(); | ||
| 1510 | let (tex, _) = eng.evaluate(&comp, target, 0.0); | ||
| 1511 | assert_eq!(tex.size, [64, 64]); | ||
| 1512 | let _ = gate_rx.recv_timeout(Duration::from_secs(5)); | ||
| 1513 | Ok("done".to_owned()) | ||
| 1514 | }) | ||
| 1515 | .expect("spawn export"); | ||
| 1516 | |||
| 1517 | assert!(studio.active_export.is_some()); | ||
| 1518 | // While export is active, sync_ram_ranges_and_prefetch must NOT schedule lookahead. | ||
| 1519 | studio.sync_ram_ranges_and_prefetch(); | ||
| 1520 | assert!(studio.last_prefetch_sig.is_none()); | ||
| 1521 | |||
| 1522 | let _ = gate_tx.send(()); | ||
| 1523 | let deadline = Instant::now() + Duration::from_secs(5); | ||
| 1524 | while studio.active_export.is_some() && Instant::now() < deadline { | ||
| 1525 | studio.poll_export(); | ||
| 1526 | std::thread::sleep(Duration::from_millis(10)); | ||
| 1527 | } | ||
| 1528 | assert!(studio.active_export.is_none()); | ||
| 1529 | |||
| 1530 | // Once export completes, sync_ram_ranges_and_prefetch automatically resumes lookahead. | ||
| 1531 | studio.sync_ram_ranges_and_prefetch(); | ||
| 1532 | assert!(studio.last_prefetch_sig.is_some()); | ||
| 1533 | } | ||
| 1383 | } | 1534 | } |
crates/app/src/playback_ui.rs+31-29| ... | @@ -176,7 +176,7 @@ impl Studio { | ... | @@ -176,7 +176,7 @@ impl Studio { |
| 176 | if let Some(id) = node { | 176 | if let Some(id) = node { |
| 177 | self.engine.bust_subtree(id); | 177 | self.engine.bust_subtree(id); |
| 178 | } else { | 178 | } else { |
| 179 | self.engine.bust_all_caches(); | 179 | self.engine.bust_gpu_cache(); |
| 180 | } | 180 | } |
| 181 | self.ram_cache.invalidate_other_revisions(self.comp.revision); | 181 | self.ram_cache.invalidate_other_revisions(self.comp.revision); |
| 182 | if let Some(pf) = &self.prefetcher { | 182 | if let Some(pf) = &self.prefetcher { |
| ... | @@ -211,36 +211,38 @@ impl Studio { | ... | @@ -211,36 +211,38 @@ impl Studio { |
| 211 | } | 211 | } |
| 212 | self.keyframes.cached_ranges = self.viewers[0].ram_cached_ranges.clone(); | 212 | self.keyframes.cached_ranges = self.viewers[0].ram_cached_ranges.clone(); |
| 213 | 213 | ||
| 214 | let target = self.viewers[0].viewed_node.filter(|id| id.0 < self.comp.nodes.len()); | 214 | if self.active_export.is_none() { |
| 215 | if let (Some(target), Some(pf)) = (target, &mut self.prefetcher) { | 215 | let target = self.viewers[0].viewed_node.filter(|id| id.0 < self.comp.nodes.len()); |
| 216 | if self.engine.cache.mode == CacheMode::Enabled { | 216 | if let (Some(target), Some(pf)) = (target, &mut self.prefetcher) { |
| 217 | let cur_f = self.playback.current_frame.round() as i64; | 217 | if self.engine.cache.mode == CacheMode::Enabled { |
| 218 | let key = ( | 218 | let cur_f = self.playback.current_frame.round() as i64; |
| 219 | target, | 219 | let key = ( |
| 220 | self.comp.revision, | ||
| 221 | self.engine.proxy_scale, | ||
| 222 | self.engine.hiq, | ||
| 223 | self.engine.use_proxy_clips, | ||
| 224 | self.comp.render_range, | ||
| 225 | ); | ||
| 226 | // Re-plan only when the job changes or the playhead leaves the half of the window | ||
| 227 | // already being filled, so steady playback never re-clones the comp per frame. | ||
| 228 | let covered = self.last_prefetch_sig.is_some_and(|(k, center)| { | ||
| 229 | k == key && (center..=center + PREFETCH_LOOKAHEAD / 2).contains(&cur_f) | ||
| 230 | }); | ||
| 231 | if !covered { | ||
| 232 | self.last_prefetch_sig = Some((key, cur_f)); | ||
| 233 | self.ram_cache.invalidate_other_revisions(self.comp.revision); | ||
| 234 | pf.request_lookahead(PrefetchJob { | ||
| 235 | comp: self.comp.clone(), | ||
| 236 | target, | 220 | target, |
| 237 | center_frame: cur_f, | 221 | self.comp.revision, |
| 238 | range: self.comp.render_range, | 222 | self.engine.proxy_scale, |
| 239 | lookahead: PREFETCH_LOOKAHEAD, | 223 | self.engine.hiq, |
| 240 | proxy_scale: self.engine.proxy_scale, | 224 | self.engine.use_proxy_clips, |
| 241 | hiq: self.engine.hiq, | 225 | self.comp.render_range, |
| 242 | use_proxy_clips: self.engine.use_proxy_clips, | 226 | ); |
| 227 | // Re-plan only when the job changes or the playhead leaves the half of the window | ||
| 228 | // already being filled, so steady playback never re-clones the comp per frame. | ||
| 229 | let covered = self.last_prefetch_sig.is_some_and(|(k, center)| { | ||
| 230 | k == key && (center..=center + PREFETCH_LOOKAHEAD / 2).contains(&cur_f) | ||
| 243 | }); | 231 | }); |
| 232 | if !covered { | ||
| 233 | self.last_prefetch_sig = Some((key, cur_f)); | ||
| 234 | self.ram_cache.invalidate_other_revisions(self.comp.revision); | ||
| 235 | pf.request_lookahead(PrefetchJob { | ||
| 236 | comp: self.comp.clone(), | ||
| 237 | target, | ||
| 238 | center_frame: cur_f, | ||
| 239 | range: self.comp.render_range, | ||
| 240 | lookahead: PREFETCH_LOOKAHEAD, | ||
| 241 | proxy_scale: self.engine.proxy_scale, | ||
| 242 | hiq: self.engine.hiq, | ||
| 243 | use_proxy_clips: self.engine.use_proxy_clips, | ||
| 244 | }); | ||
| 245 | } | ||
| 244 | } | 246 | } |
| 245 | } | 247 | } |
| 246 | } | 248 | } |
crates/engine/src/eval/mod.rs+148-19| ... | @@ -393,6 +393,9 @@ impl ShaderRegistry { | ... | @@ -393,6 +393,9 @@ impl ShaderRegistry { |
| 393 | } | 393 | } |
| 394 | } | 394 | } |
| 395 | 395 | ||
| 396 | const MAX_OUTPUT_CACHE_BYTES: u64 = 128 * 1024 * 1024; | ||
| 397 | const MAX_OUTPUT_CACHE_ENTRIES: usize = 64; | ||
| 398 | |||
| 396 | pub struct Engine { | 399 | pub struct Engine { |
| 397 | device: wgpu::Device, | 400 | device: wgpu::Device, |
| 398 | queue: wgpu::Queue, | 401 | queue: wgpu::Queue, |
| ... | @@ -408,13 +411,14 @@ pub struct Engine { | ... | @@ -408,13 +411,14 @@ pub struct Engine { |
| 408 | sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, | 411 | sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, |
| 409 | ram_upload_tex: RefCell<Option<CachedTexture>>, | 412 | ram_upload_tex: RefCell<Option<CachedTexture>>, |
| 410 | dummy: CachedTexture, | 413 | dummy: CachedTexture, |
| 414 | vram_budget_bytes: u64, | ||
| 411 | pub cache: NodeCache, | 415 | pub cache: NodeCache, |
| 412 | pub media: MediaCache, | 416 | pub media: MediaCache, |
| 413 | pub expr: ExprEngine, | 417 | pub expr: ExprEngine, |
| 414 | /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. | 418 | /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. |
| 415 | frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, | 419 | frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, |
| 416 | /// Bounded LRU of recent final output textures (up to 8 entries) so tight VRAM caps on | 420 | /// Bounded LRU of recent final output textures capped by byte budget (`min(vram_budget / 4, 128 MiB)`), |
| 417 | /// 150+ node comps still deliver `<0.1ms` warm hits during pan/zoom/exposure/scrubbing. | 421 | /// always keeping at least the most recent frame for `<0.1ms` warm hits during pan/zoom/exposure/scrubbing. |
| 418 | output_cache: std::collections::VecDeque<(u64, CachedTexture, Vec<String>)>, | 422 | output_cache: std::collections::VecDeque<(u64, CachedTexture, Vec<String>)>, |
| 419 | /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default | 423 | /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default |
| 420 | /// to matching the dimensions & aspect ratio of the node they mask!). | 424 | /// to matching the dimensions & aspect ratio of the node they mask!). |
| ... | @@ -459,6 +463,7 @@ impl Engine { | ... | @@ -459,6 +463,7 @@ impl Engine { |
| 459 | sprite_cache: HashMap::new(), | 463 | sprite_cache: HashMap::new(), |
| 460 | ram_upload_tex: RefCell::new(None), | 464 | ram_upload_tex: RefCell::new(None), |
| 461 | dummy, | 465 | dummy, |
| 466 | vram_budget_bytes: crate::cache::DEFAULT_VRAM_BUDGET_MB.saturating_mul(1024 * 1024), | ||
| 462 | cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB), | 467 | cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB), |
| 463 | media: MediaCache::new(512), | 468 | media: MediaCache::new(512), |
| 464 | expr: ExprEngine::new(), | 469 | expr: ExprEngine::new(), |
| ... | @@ -478,6 +483,7 @@ impl Engine { | ... | @@ -478,6 +483,7 @@ impl Engine { |
| 478 | media_budget_bytes: u64, | 483 | media_budget_bytes: u64, |
| 479 | ) -> Self { | 484 | ) -> Self { |
| 480 | let mut eng = Self::new((*device).clone(), (*queue).clone()); | 485 | let mut eng = Self::new((*device).clone(), (*queue).clone()); |
| 486 | eng.vram_budget_bytes = vram_budget_bytes; | ||
| 481 | eng.cache.budget_bytes = vram_budget_bytes; | 487 | eng.cache.budget_bytes = vram_budget_bytes; |
| 482 | let media_mb = if media_budget_bytes == 0 { | 488 | let media_mb = if media_budget_bytes == 0 { |
| 483 | 0 | 489 | 0 |
| ... | @@ -607,19 +613,63 @@ impl Engine { | ... | @@ -607,19 +613,63 @@ impl Engine { |
| 607 | &self.queue | 613 | &self.queue |
| 608 | } | 614 | } |
| 609 | 615 | ||
| 616 | pub fn device_arc(&self) -> std::sync::Arc<wgpu::Device> { | ||
| 617 | std::sync::Arc::new(self.device.clone()) | ||
| 618 | } | ||
| 619 | |||
| 620 | pub fn queue_arc(&self) -> std::sync::Arc<wgpu::Queue> { | ||
| 621 | std::sync::Arc::new(self.queue.clone()) | ||
| 622 | } | ||
| 623 | |||
| 610 | pub fn set_cache_mode(&mut self, mode: CacheMode) { | 624 | pub fn set_cache_mode(&mut self, mode: CacheMode) { |
| 611 | self.cache.mode = mode; | 625 | self.cache.mode = mode; |
| 612 | } | 626 | } |
| 613 | 627 | ||
| 628 | fn output_cache_budget_bytes(&self) -> u64 { | ||
| 629 | if self.vram_budget_bytes < 64 * 1024 * 1024 { | ||
| 630 | 0 | ||
| 631 | } else { | ||
| 632 | (self.vram_budget_bytes / 4).min(MAX_OUTPUT_CACHE_BYTES) | ||
| 633 | } | ||
| 634 | } | ||
| 635 | |||
| 636 | /// Total GPU bytes held by `output_cache`. | ||
| 637 | pub fn output_cache_bytes(&self) -> u64 { | ||
| 638 | self.output_cache.iter().map(|(_, tex, _)| tex.bytes).sum() | ||
| 639 | } | ||
| 640 | |||
| 641 | /// Total resident GPU VRAM bytes across `NodeCache` (live + pooled) and `output_cache`. | ||
| 642 | pub fn vram_bytes(&self) -> u64 { | ||
| 643 | self.cache.total_vram_bytes().saturating_add(self.output_cache_bytes()) | ||
| 644 | } | ||
| 645 | |||
| 646 | pub fn vram_mb(&self) -> f64 { | ||
| 647 | self.vram_bytes() as f64 / (1024.0 * 1024.0) | ||
| 648 | } | ||
| 649 | |||
| 650 | fn sync_node_cache_budget(&mut self) { | ||
| 651 | let remaining_bytes = self.vram_budget_bytes.saturating_sub(self.output_cache_bytes()); | ||
| 652 | let remaining_mb = remaining_bytes / (1024 * 1024); | ||
| 653 | if self.cache.budget_bytes != remaining_mb.saturating_mul(1024 * 1024) { | ||
| 654 | self.cache.set_budget_mb(remaining_mb); | ||
| 655 | } | ||
| 656 | } | ||
| 657 | |||
| 614 | pub fn set_vram_budget_mb(&mut self, budget_mb: u64) { | 658 | pub fn set_vram_budget_mb(&mut self, budget_mb: u64) { |
| 615 | self.cache.set_budget_mb(budget_mb); | 659 | self.vram_budget_bytes = budget_mb.saturating_mul(1024 * 1024); |
| 616 | if budget_mb < 64 { | 660 | let cap = self.output_cache_budget_bytes(); |
| 661 | if cap == 0 { | ||
| 617 | self.output_cache.clear(); | 662 | self.output_cache.clear(); |
| 663 | } else { | ||
| 664 | while self.output_cache.len() > 1 && self.output_cache_bytes() > cap { | ||
| 665 | self.output_cache.pop_front(); | ||
| 666 | } | ||
| 618 | } | 667 | } |
| 668 | self.sync_node_cache_budget(); | ||
| 619 | } | 669 | } |
| 620 | 670 | ||
| 621 | pub fn vram_budget_mb(&self) -> u64 { | 671 | pub fn vram_budget_mb(&self) -> u64 { |
| 622 | self.cache.budget_mb() | 672 | self.vram_budget_bytes / (1024 * 1024) |
| 623 | } | 673 | } |
| 624 | 674 | ||
| 625 | pub fn set_media_budget_mb(&mut self, budget_mb: u64) { | 675 | pub fn set_media_budget_mb(&mut self, budget_mb: u64) { |
| ... | @@ -705,7 +755,7 @@ impl Engine { | ... | @@ -705,7 +755,7 @@ impl Engine { |
| 705 | eval_ms: t0.elapsed().as_secs_f64() * 1000.0, | 755 | eval_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| 706 | cache_hits: 1, | 756 | cache_hits: 1, |
| 707 | cached_entries: self.cache.entry_count(), | 757 | cached_entries: self.cache.entry_count(), |
| 708 | cached_vram_mb: self.cache.total_mb(), | 758 | cached_vram_mb: self.vram_mb(), |
| 709 | media_entries: self.media.entry_count(), | 759 | media_entries: self.media.entry_count(), |
| 710 | media_mb: self.media.total_mb(), | 760 | media_mb: self.media.total_mb(), |
| 711 | ..EvalStats::default() | 761 | ..EvalStats::default() |
| ... | @@ -713,8 +763,9 @@ impl Engine { | ... | @@ -713,8 +763,9 @@ impl Engine { |
| 713 | } | 763 | } |
| 714 | 764 | ||
| 715 | pub fn bust_all_caches(&mut self) { | 765 | pub fn bust_all_caches(&mut self) { |
| 716 | self.cache.bust_all(); | ||
| 717 | self.output_cache.clear(); | 766 | self.output_cache.clear(); |
| 767 | self.sync_node_cache_budget(); | ||
| 768 | self.cache.bust_all(); | ||
| 718 | self.media.clear(); | 769 | self.media.clear(); |
| 719 | self.particles.clear(); | 770 | self.particles.clear(); |
| 720 | self.sprite_cache.clear(); | 771 | self.sprite_cache.clear(); |
| ... | @@ -723,19 +774,22 @@ impl Engine { | ... | @@ -723,19 +774,22 @@ impl Engine { |
| 723 | } | 774 | } |
| 724 | 775 | ||
| 725 | pub fn bust_gpu_cache(&mut self) { | 776 | pub fn bust_gpu_cache(&mut self) { |
| 726 | self.cache.bust_all(); | ||
| 727 | self.output_cache.clear(); | 777 | self.output_cache.clear(); |
| 778 | self.sync_node_cache_budget(); | ||
| 779 | self.cache.bust_all(); | ||
| 728 | self.sprite_cache.clear(); | 780 | self.sprite_cache.clear(); |
| 729 | *self.ram_upload_tex.borrow_mut() = None; | 781 | *self.ram_upload_tex.borrow_mut() = None; |
| 730 | } | 782 | } |
| 731 | 783 | ||
| 732 | pub fn bust_frame(&mut self, frame: i64) -> usize { | 784 | pub fn bust_frame(&mut self, frame: i64) -> usize { |
| 733 | self.output_cache.clear(); | 785 | self.output_cache.clear(); |
| 786 | self.sync_node_cache_budget(); | ||
| 734 | self.cache.bust_frame(frame) | 787 | self.cache.bust_frame(frame) |
| 735 | } | 788 | } |
| 736 | 789 | ||
| 737 | pub fn bust_subtree(&mut self, node: NodeId) -> usize { | 790 | pub fn bust_subtree(&mut self, node: NodeId) -> usize { |
| 738 | self.output_cache.clear(); | 791 | self.output_cache.clear(); |
| 792 | self.sync_node_cache_budget(); | ||
| 739 | self.cache.bust_subtree(node) | 793 | self.cache.bust_subtree(node) |
| 740 | } | 794 | } |
| 741 | 795 | ||
| ... | @@ -766,16 +820,20 @@ impl Engine { | ... | @@ -766,16 +820,20 @@ impl Engine { |
| 766 | } | 820 | } |
| 767 | 821 | ||
| 768 | fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec<String>) { | 822 | fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec<String>) { |
| 769 | if self.cache.mode == CacheMode::Bypass || self.cache.budget_bytes < 64 * 1024 * 1024 { | 823 | let cap = self.output_cache_budget_bytes(); |
| 824 | if self.cache.mode == CacheMode::Bypass || cap == 0 { | ||
| 770 | return; | 825 | return; |
| 771 | } | 826 | } |
| 772 | if let Some(pos) = self.output_cache.iter().position(|(k, _, _)| *k == key) { | 827 | if let Some(pos) = self.output_cache.iter().position(|(k, _, _)| *k == key) { |
| 773 | self.output_cache.remove(pos); | 828 | self.output_cache.remove(pos); |
| 774 | } | 829 | } |
| 775 | self.output_cache.push_back((key, tex, unsupported)); | 830 | self.output_cache.push_back((key, tex, unsupported)); |
| 776 | while self.output_cache.len() > 8 { | 831 | while self.output_cache.len() > 1 |
| 832 | && (self.output_cache_bytes() > cap || self.output_cache.len() > MAX_OUTPUT_CACHE_ENTRIES) | ||
| 833 | { | ||
| 777 | self.output_cache.pop_front(); | 834 | self.output_cache.pop_front(); |
| 778 | } | 835 | } |
| 836 | self.sync_node_cache_budget(); | ||
| 779 | } | 837 | } |
| 780 | 838 | ||
| 781 | /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. | 839 | /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. |
| ... | @@ -792,7 +850,7 @@ impl Engine { | ... | @@ -792,7 +850,7 @@ impl Engine { |
| 792 | eval_ms: t0.elapsed().as_secs_f64() * 1000.0, | 850 | eval_ms: t0.elapsed().as_secs_f64() * 1000.0, |
| 793 | cache_hits: 1, | 851 | cache_hits: 1, |
| 794 | cached_entries: self.cache.entry_count(), | 852 | cached_entries: self.cache.entry_count(), |
| 795 | cached_vram_mb: self.cache.total_mb(), | 853 | cached_vram_mb: self.vram_mb(), |
| 796 | media_entries: self.media.entry_count(), | 854 | media_entries: self.media.entry_count(), |
| 797 | media_mb: self.media.total_mb(), | 855 | media_mb: self.media.total_mb(), |
| 798 | unsupported_nodes: unsupported, | 856 | unsupported_nodes: unsupported, |
| ... | @@ -814,12 +872,11 @@ impl Engine { | ... | @@ -814,12 +872,11 @@ impl Engine { |
| 814 | } | 872 | } |
| 815 | self.queue.submit(Some(encoder.finish())); | 873 | self.queue.submit(Some(encoder.finish())); |
| 816 | self.frame_memo.clear(); | 874 | self.frame_memo.clear(); |
| 817 | self.cache.flush_pending_pool(); | ||
| 818 | |||
| 819 | self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); | 875 | self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); |
| 876 | self.cache.flush_pending_pool(); | ||
| 820 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; | 877 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 821 | stats.cached_entries = self.cache.entry_count(); | 878 | stats.cached_entries = self.cache.entry_count(); |
| 822 | stats.cached_vram_mb = self.cache.total_mb(); | 879 | stats.cached_vram_mb = self.vram_mb(); |
| 823 | stats.media_entries = self.media.entry_count(); | 880 | stats.media_entries = self.media.entry_count(); |
| 824 | stats.media_mb = self.media.total_mb(); | 881 | stats.media_mb = self.media.total_mb(); |
| 825 | (tex, stats) | 882 | (tex, stats) |
| ... | @@ -841,16 +898,15 @@ impl Engine { | ... | @@ -841,16 +898,15 @@ impl Engine { |
| 841 | label: Some("comp-viewer-eval"), | 898 | label: Some("comp-viewer-eval"), |
| 842 | }); | 899 | }); |
| 843 | 900 | ||
| 844 | let tex = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { | 901 | let (tex, need_output_insert) = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { |
| 845 | stats.cache_hits = 1; | 902 | stats.cache_hits = 1; |
| 846 | stats.unsupported_nodes = unsupported; | 903 | stats.unsupported_nodes = unsupported; |
| 847 | cached | 904 | (cached, false) |
| 848 | } else { | 905 | } else { |
| 849 | let mut visiting = HashSet::new(); | 906 | let mut visiting = HashSet::new(); |
| 850 | self.frame_memo.clear(); | 907 | self.frame_memo.clear(); |
| 851 | let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); | 908 | let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); |
| 852 | self.output_cache_insert(out_key, t.clone(), stats.unsupported_nodes.clone()); | 909 | (t, true) |
| 853 | t | ||
| 854 | }; | 910 | }; |
| 855 | 911 | ||
| 856 | let dst_size = [dst_texture.width(), dst_texture.height()]; | 912 | let dst_size = [dst_texture.width(), dst_texture.height()]; |
| ... | @@ -885,11 +941,14 @@ impl Engine { | ... | @@ -885,11 +941,14 @@ impl Engine { |
| 885 | 941 | ||
| 886 | self.queue.submit(Some(encoder.finish())); | 942 | self.queue.submit(Some(encoder.finish())); |
| 887 | self.frame_memo.clear(); | 943 | self.frame_memo.clear(); |
| 944 | if need_output_insert { | ||
| 945 | self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone()); | ||
| 946 | } | ||
| 888 | self.cache.flush_pending_pool(); | 947 | self.cache.flush_pending_pool(); |
| 889 | 948 | ||
| 890 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; | 949 | stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; |
| 891 | stats.cached_entries = self.cache.entry_count(); | 950 | stats.cached_entries = self.cache.entry_count(); |
| 892 | stats.cached_vram_mb = self.cache.total_mb(); | 951 | stats.cached_vram_mb = self.vram_mb(); |
| 893 | stats.media_entries = self.media.entry_count(); | 952 | stats.media_entries = self.media.entry_count(); |
| 894 | stats.media_mb = self.media.total_mb(); | 953 | stats.media_mb = self.media.total_mb(); |
| 895 | stats | 954 | stats |
| ... | @@ -1806,4 +1865,74 @@ Composition { | ... | @@ -1806,4 +1865,74 @@ Composition { |
| 1806 | assert!((g - (-0.25)).abs() < 0.05, "expected negative HDR green ~-0.25, got {g}"); | 1865 | assert!((g - (-0.25)).abs() < 0.05, "expected negative HDR green ~-0.25, got {g}"); |
| 1807 | assert!((b - 0.5).abs() < 0.05, "expected blue ~0.5, got {b}"); | 1866 | assert!((b - 0.5).abs() < 0.05, "expected blue ~0.5, got {b}"); |
| 1808 | } | 1867 | } |
| 1868 | |||
| 1869 | #[test] | ||
| 1870 | fn output_cache_enforces_byte_budget_and_reports_in_vram_bytes() { | ||
| 1871 | let mut eng = Engine::new_headless().expect("gpu"); | ||
| 1872 | // 64 MiB total VRAM budget -> output_cache cap is 64 / 4 = 16 MiB. | ||
| 1873 | eng.set_vram_budget_mb(64); | ||
| 1874 | assert_eq!(eng.output_cache_budget_bytes(), 16 * 1024 * 1024); | ||
| 1875 | |||
| 1876 | // 2048x1024 RGBA8 = 8 MiB per frame (so 16 MiB cap fits 2 frames, evicting the 3rd). | ||
| 1877 | let src = r#" | ||
| 1878 | Composition { | ||
| 1879 | CurrentTime = 0, | ||
| 1880 | RenderRange = { 0, 5 }, | ||
| 1881 | GlobalRange = { 0, 5 }, | ||
| 1882 | Tools = ordered() { | ||
| 1883 | AnimRed = BezierSpline { | ||
| 1884 | KeyFrames = { | ||
| 1885 | [0] = { 0.1 }, | ||
| 1886 | [5] = { 0.9 }, | ||
| 1887 | }, | ||
| 1888 | }, | ||
| 1889 | BG = Background { | ||
| 1890 | Inputs = { | ||
| 1891 | Width = Input { Value = 2048, }, | ||
| 1892 | Height = Input { Value = 1024, }, | ||
| 1893 | TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, | ||
| 1894 | TopLeftAlpha = Input { Value = 1.0, }, | ||
| 1895 | }, | ||
| 1896 | }, | ||
| 1897 | }, | ||
| 1898 | } | ||
| 1899 | "#; | ||
| 1900 | let comp = Comp::from_fusion_str(src).expect("parse output_cache test comp"); | ||
| 1901 | let bg = comp.find_node("BG").unwrap(); | ||
| 1902 | |||
| 1903 | let (_, s0) = eng.evaluate(&comp, bg, 0.0); | ||
| 1904 | assert_eq!(eng.output_cache.len(), 1); | ||
| 1905 | assert_eq!(eng.output_cache_bytes(), 8 * 1024 * 1024); | ||
| 1906 | assert!(eng.vram_bytes() >= eng.output_cache_bytes()); | ||
| 1907 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); | ||
| 1908 | assert!((s0.cached_vram_mb - eng.vram_mb()).abs() < 0.01); | ||
| 1909 | |||
| 1910 | let (_, _) = eng.evaluate(&comp, bg, 1.0); | ||
| 1911 | assert_eq!(eng.output_cache.len(), 2); | ||
| 1912 | assert_eq!(eng.output_cache_bytes(), 16 * 1024 * 1024); | ||
| 1913 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); | ||
| 1914 | |||
| 1915 | // Touch frame 0 so frame 1 becomes LRU, then evaluate frame 2 -> frame 1 evicted. | ||
| 1916 | let (_, warm0) = eng.evaluate(&comp, bg, 0.0); | ||
| 1917 | assert_eq!(warm0.cache_hits, 1); | ||
| 1918 | |||
| 1919 | let (_, _) = eng.evaluate(&comp, bg, 2.0); | ||
| 1920 | assert_eq!(eng.output_cache.len(), 2); | ||
| 1921 | assert_eq!(eng.output_cache_bytes(), 16 * 1024 * 1024); | ||
| 1922 | assert!(eng.vram_bytes() <= 64 * 1024 * 1024); | ||
| 1923 | |||
| 1924 | // Frame 1 was evicted, so evaluating frame 1 misses output_cache; frame 2 hits. | ||
| 1925 | let k1 = eng.output_cache_key(&comp, bg, 1.0); | ||
| 1926 | let k2 = eng.output_cache_key(&comp, bg, 2.0); | ||
| 1927 | assert!(eng.output_cache_get(k1).is_none(), "LRU frame 1 should have been evicted"); | ||
| 1928 | assert!(eng.output_cache_get(k2).is_some(), "recent frame 2 should still be cached"); | ||
| 1929 | |||
| 1930 | // Even a single frame exceeding the byte cap (e.g., 4096x2048 RGBA8 = 32 MiB > 16 MiB) | ||
| 1931 | // must always keep at least the most recent frame in output_cache. | ||
| 1932 | let big_tex = create_texture(&eng.device, [4096, 2048], 0); | ||
| 1933 | assert_eq!(big_tex.bytes, 32 * 1024 * 1024); | ||
| 1934 | eng.output_cache_insert(999_999, big_tex, Vec::new()); | ||
| 1935 | assert_eq!(eng.output_cache.len(), 1); | ||
| 1936 | assert_eq!(eng.output_cache_bytes(), 32 * 1024 * 1024); | ||
| 1937 | } | ||
| 1809 | } | 1938 | } |
crates/engine/src/ram_cache.rs+116-10| ... | @@ -16,6 +16,10 @@ use std::thread::{self, JoinHandle}; | ... | @@ -16,6 +16,10 @@ use std::thread::{self, JoinHandle}; |
| 16 | 16 | ||
| 17 | /// Default RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames). | 17 | /// Default RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames). |
| 18 | pub const DEFAULT_RAM_CACHE_MB: u64 = 1024; | 18 | pub const DEFAULT_RAM_CACHE_MB: u64 = 1024; |
| 19 | /// Modest VRAM budget for the shared-device background prefetcher `Engine`. | ||
| 20 | pub const DEFAULT_PREFETCH_VRAM_MB: u64 = 256; | ||
| 21 | /// Modest media decode cache budget for the shared-device background prefetcher `Engine`. | ||
| 22 | pub const DEFAULT_PREFETCH_MEDIA_MB: u64 = 128; | ||
| 19 | 23 | ||
| 20 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | 24 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 21 | pub struct RamFrameKey { | 25 | pub struct RamFrameKey { |
| ... | @@ -81,6 +85,12 @@ impl Default for RamFrameCache { | ... | @@ -81,6 +85,12 @@ impl Default for RamFrameCache { |
| 81 | } | 85 | } |
| 82 | } | 86 | } |
| 83 | 87 | ||
| 88 | impl From<Arc<RamFrameCache>> for RamFrameCache { | ||
| 89 | fn from(arc: Arc<RamFrameCache>) -> Self { | ||
| 90 | (*arc).clone() | ||
| 91 | } | ||
| 92 | } | ||
| 93 | |||
| 84 | impl RamFrameCache { | 94 | impl RamFrameCache { |
| 85 | pub fn new(budget_mb: u64) -> Self { | 95 | pub fn new(budget_mb: u64) -> Self { |
| 86 | Self { | 96 | Self { |
| ... | @@ -275,14 +285,17 @@ struct WorkerSlot { | ... | @@ -275,14 +285,17 @@ struct WorkerSlot { |
| 275 | shutdown: bool, | 285 | shutdown: bool, |
| 276 | } | 286 | } |
| 277 | 287 | ||
| 278 | /// Background lookahead frame pre-fetcher backed by a dedicated headless `Engine`. | 288 | /// Background lookahead frame pre-fetcher backed by a background `Engine` (either sharing |
| 289 | /// the host `wgpu::Device`/`wgpu::Queue` or initializing a standalone headless device). | ||
| 279 | /// | 290 | /// |
| 280 | /// Calling `request_lookahead` or `cancel` immediately increments an atomic generation | 291 | /// Calling `request_lookahead` or `cancel` immediately increments an atomic generation |
| 281 | /// counter so any in-flight lookahead loop aborts before evaluating another frame. | 292 | /// counter so any in-flight lookahead loop aborts before evaluating another frame. |
| 282 | pub struct RamPrefetcher { | 293 | pub struct RamPrefetcher { |
| 283 | cache: RamFrameCache, | 294 | cache: RamFrameCache, |
| 284 | cache_epoch: Arc<AtomicU64>, | 295 | cache_epoch: Arc<AtomicU64>, |
| 296 | shared_device: Option<(Arc<wgpu::Device>, Arc<wgpu::Queue>)>, | ||
| 285 | vram_budget_mb: u64, | 297 | vram_budget_mb: u64, |
| 298 | media_budget_mb: u64, | ||
| 286 | generation: Arc<AtomicU64>, | 299 | generation: Arc<AtomicU64>, |
| 287 | busy: Arc<AtomicBool>, | 300 | busy: Arc<AtomicBool>, |
| 288 | completed_frames: Arc<AtomicU64>, | 301 | completed_frames: Arc<AtomicU64>, |
| ... | @@ -293,11 +306,37 @@ pub struct RamPrefetcher { | ... | @@ -293,11 +306,37 @@ pub struct RamPrefetcher { |
| 293 | 306 | ||
| 294 | impl RamPrefetcher { | 307 | impl RamPrefetcher { |
| 295 | pub fn new(cache: RamFrameCache, worker_vram_budget_mb: u64) -> Self { | 308 | pub fn new(cache: RamFrameCache, worker_vram_budget_mb: u64) -> Self { |
| 309 | Self::init(None, cache, worker_vram_budget_mb.max(128), 512) | ||
| 310 | } | ||
| 311 | |||
| 312 | /// Creates a `RamPrefetcher` whose worker `Engine` shares an existing `wgpu::Device` | ||
| 313 | /// and `wgpu::Queue` with modest budgets (256 MiB VRAM, 128 MiB media). | ||
| 314 | pub fn new_with_device( | ||
| 315 | device: Arc<wgpu::Device>, | ||
| 316 | queue: Arc<wgpu::Queue>, | ||
| 317 | cache: impl Into<RamFrameCache>, | ||
| 318 | ) -> Self { | ||
| 319 | Self::init( | ||
| 320 | Some((device, queue)), | ||
| 321 | cache.into(), | ||
| 322 | DEFAULT_PREFETCH_VRAM_MB, | ||
| 323 | DEFAULT_PREFETCH_MEDIA_MB, | ||
| 324 | ) | ||
| 325 | } | ||
| 326 | |||
| 327 | fn init( | ||
| 328 | shared_device: Option<(Arc<wgpu::Device>, Arc<wgpu::Queue>)>, | ||
| 329 | cache: RamFrameCache, | ||
| 330 | vram_budget_mb: u64, | ||
| 331 | media_budget_mb: u64, | ||
| 332 | ) -> Self { | ||
| 296 | let cache_epoch = cache.epoch_arc(); | 333 | let cache_epoch = cache.epoch_arc(); |
| 297 | Self { | 334 | Self { |
| 298 | cache, | 335 | cache, |
| 299 | cache_epoch, | 336 | cache_epoch, |
| 300 | vram_budget_mb: worker_vram_budget_mb.max(128), | 337 | shared_device, |
| 338 | vram_budget_mb, | ||
| 339 | media_budget_mb, | ||
| 301 | generation: Arc::new(AtomicU64::new(1)), | 340 | generation: Arc::new(AtomicU64::new(1)), |
| 302 | busy: Arc::new(AtomicBool::new(false)), | 341 | busy: Arc::new(AtomicBool::new(false)), |
| 303 | completed_frames: Arc::new(AtomicU64::new(0)), | 342 | completed_frames: Arc::new(AtomicU64::new(0)), |
| ... | @@ -353,7 +392,9 @@ impl RamPrefetcher { | ... | @@ -353,7 +392,9 @@ impl RamPrefetcher { |
| 353 | } | 392 | } |
| 354 | let cache = self.cache.clone(); | 393 | let cache = self.cache.clone(); |
| 355 | let cache_epoch = self.cache_epoch.clone(); | 394 | let cache_epoch = self.cache_epoch.clone(); |
| 395 | let shared_device = self.shared_device.clone(); | ||
| 356 | let vram_mb = self.vram_budget_mb; | 396 | let vram_mb = self.vram_budget_mb; |
| 397 | let media_mb = self.media_budget_mb; | ||
| 357 | let generation = self.generation.clone(); | 398 | let generation = self.generation.clone(); |
| 358 | let busy = self.busy.clone(); | 399 | let busy = self.busy.clone(); |
| 359 | let completed = self.completed_frames.clone(); | 400 | let completed = self.completed_frames.clone(); |
| ... | @@ -406,14 +447,23 @@ impl RamPrefetcher { | ... | @@ -406,14 +447,23 @@ impl RamPrefetcher { |
| 406 | } | 447 | } |
| 407 | 448 | ||
| 408 | if engine_opt.is_none() { | 449 | if engine_opt.is_none() { |
| 409 | match Engine::new_headless() { | 450 | if let Some((ref dev, ref q)) = shared_device { |
| 410 | Ok(mut eng) => { | 451 | engine_opt = Some(Engine::new_with_device( |
| 411 | eng.set_vram_budget_mb(vram_mb); | 452 | Arc::clone(dev), |
| 412 | engine_opt = Some(eng); | 453 | Arc::clone(q), |
| 413 | } | 454 | vram_mb.saturating_mul(1024 * 1024), |
| 414 | Err(_) => { | 455 | media_mb.saturating_mul(1024 * 1024), |
| 415 | // Headless GPU unavailable; stay idle until shutdown. | 456 | )); |
| 416 | continue; | 457 | } else { |
| 458 | match Engine::new_headless() { | ||
| 459 | Ok(mut eng) => { | ||
| 460 | eng.set_vram_budget_mb(vram_mb); | ||
| 461 | engine_opt = Some(eng); | ||
| 462 | } | ||
| 463 | Err(_) => { | ||
| 464 | // Headless GPU unavailable; stay idle until shutdown. | ||
| 465 | continue; | ||
| 466 | } | ||
| 417 | } | 467 | } |
| 418 | } | 468 | } |
| 419 | } | 469 | } |
| ... | @@ -739,4 +789,60 @@ Composition { | ... | @@ -739,4 +789,60 @@ Composition { |
| 739 | prefetcher.cancel(); | 789 | prefetcher.cancel(); |
| 740 | assert!(cache.epoch() > after_clear_epoch); | 790 | assert!(cache.epoch() > after_clear_epoch); |
| 741 | } | 791 | } |
| 792 | |||
| 793 | #[test] | ||
| 794 | fn ram_prefetcher_new_with_device_shares_device_and_renders_lookahead() { | ||
| 795 | let host_engine = Engine::new_headless().expect("gpu"); | ||
| 796 | let comp_src = r#" | ||
| 797 | Composition { | ||
| 798 | CurrentTime = 0, | ||
| 799 | RenderRange = { 0, 5 }, | ||
| 800 | GlobalRange = { 0, 5 }, | ||
| 801 | Tools = ordered() { | ||
| 802 | BG1 = Background { | ||
| 803 | Inputs = { | ||
| 804 | Width = Input { Value = 64, }, | ||
| 805 | Height = Input { Value = 64, }, | ||
| 806 | TopLeftGreen = Input { Value = 0.75, }, | ||
| 807 | TopLeftAlpha = Input { Value = 1.0, }, | ||
| 808 | }, | ||
| 809 | }, | ||
| 810 | }, | ||
| 811 | } | ||
| 812 | "#; | ||
| 813 | let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); | ||
| 814 | let target = comp.find_node("BG1").expect("BG1"); | ||
| 815 | let cache = RamFrameCache::new(64); | ||
| 816 | let mut prefetcher = RamPrefetcher::new_with_device( | ||
| 817 | host_engine.device_arc(), | ||
| 818 | host_engine.queue_arc(), | ||
| 819 | cache.clone(), | ||
| 820 | ); | ||
| 821 | assert_eq!(prefetcher.vram_budget_mb, DEFAULT_PREFETCH_VRAM_MB); | ||
| 822 | assert_eq!(prefetcher.media_budget_mb, DEFAULT_PREFETCH_MEDIA_MB); | ||
| 823 | |||
| 824 | prefetcher.request_lookahead(PrefetchJob { | ||
| 825 | comp: comp.clone(), | ||
| 826 | target, | ||
| 827 | center_frame: 0, | ||
| 828 | range: [0, 5], | ||
| 829 | lookahead: 3, | ||
| 830 | proxy_scale: 1, | ||
| 831 | hiq: true, | ||
| 832 | use_proxy_clips: false, | ||
| 833 | }); | ||
| 834 | |||
| 835 | let deadline = Instant::now() + Duration::from_secs(10); | ||
| 836 | while Instant::now() < deadline { | ||
| 837 | if cache.cached_frame_ranges(target, comp.revision, 1, true, false) == vec![(1, 3)] { | ||
| 838 | break; | ||
| 839 | } | ||
| 840 | thread::sleep(Duration::from_millis(15)); | ||
| 841 | } | ||
| 842 | assert_eq!( | ||
| 843 | cache.cached_frame_ranges(target, comp.revision, 1, true, false), | ||
| 844 | vec![(1, 3)] | ||
| 845 | ); | ||
| 846 | prefetcher.cancel(); | ||
| 847 | } | ||
| 742 | } | 848 | } |