From 9f6cd5fe8fd066b899ef73513343ff2e092bd205 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 20:45:50 -0800 Subject: [PATCH] Share wgpu Device/Queue across UI, prefetcher, and export; cap output_cache VRAM --- crates/app/src/export_ui.rs | 28 ++++-- crates/app/src/main.rs | 159 ++++++++++++++++++++++++++++++- crates/app/src/playback_ui.rs | 60 ++++++------ crates/engine/src/eval/mod.rs | 167 +++++++++++++++++++++++++++++---- crates/engine/src/ram_cache.rs | 126 +++++++++++++++++++++++-- 5 files changed, 471 insertions(+), 69 deletions(-) diff --git a/crates/app/src/export_ui.rs b/crates/app/src/export_ui.rs index fc8c4a4e7cf9378a3db679a4c083d69ce80d26a9..cfe756b81e641f9263b7bc747a639bfe91afd0f1 100644 --- a/crates/app/src/export_ui.rs +++ b/crates/app/src/export_ui.rs @@ -168,6 +168,9 @@ pub(crate) fn build_status_strip( actions } +const EXPORT_VRAM_BUDGET_BYTES: u64 = 256 * 1024 * 1024; +const EXPORT_MEDIA_BUDGET_BYTES: u64 = 128 * 1024 * 1024; + impl Studio { pub(crate) fn poll_export(&mut self) { let Some(exp) = &self.active_export else { @@ -179,6 +182,7 @@ impl Studio { if let Some(handle) = finished.handle.take() { let _ = handle.join(); } + self.last_prefetch_sig = None; match outcome { ExportOutcome::Completed(msg) => { eprintln!("{msg}"); @@ -199,6 +203,7 @@ impl Studio { if let Some(handle) = finished.handle.take() { let _ = handle.join(); } + self.last_prefetch_sig = None; self.set_notice("Export worker stopped unexpectedly"); } Err(mpsc::TryRecvError::Empty) => {} @@ -218,6 +223,8 @@ impl Studio { control.update_progress(&initial_progress); let ctrl_worker = control.clone(); let proxy = self.redraw_proxy.clone(); + let export_device = self.engine.device_arc(); + let export_queue = self.engine.queue_arc(); let (tx, rx) = mpsc::channel(); let handle = std::thread::Builder::new() @@ -228,19 +235,26 @@ impl Studio { let _ = p.send_event(UserEvent::Redraw); } }; - let outcome = match Engine::new_headless() { - Ok(mut export_engine) => match job(&mut export_engine, &ctrl_worker, ¬ify_redraw) { - Ok(msg) => ExportOutcome::Completed(msg), - Err(e) if e == "Cancelled" => ExportOutcome::Cancelled, - Err(e) => ExportOutcome::Failed(e), - }, - Err(e) => ExportOutcome::Failed(format!("Failed to initialize export GPU: {e}")), + let mut export_engine = Engine::new_with_device( + export_device, + export_queue, + EXPORT_VRAM_BUDGET_BYTES, + EXPORT_MEDIA_BUDGET_BYTES, + ); + let outcome = match job(&mut export_engine, &ctrl_worker, ¬ify_redraw) { + Ok(msg) => ExportOutcome::Completed(msg), + Err(e) if e == "Cancelled" => ExportOutcome::Cancelled, + Err(e) => ExportOutcome::Failed(e), }; let _ = tx.send(outcome); notify_redraw(); }) .map_err(|e| format!("Failed to start export thread: {e}"))?; + if let Some(pf) = &self.prefetcher { + pf.cancel(); + } + self.last_prefetch_sig = None; self.active_export = Some(ActiveExport { kind, control, diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 8fda658603df858fb76b5d486a7a70bf8497c406..6a01c696ed640ee6e23a053ba9cb661353be668c 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -158,6 +158,7 @@ impl Studio { dual_viewer: bool, show_keyframes: bool, enable_audio: bool, + interactive: bool, ) -> Self { let engine = Engine::new(renderer.device().clone(), renderer.queue().clone()); // Knife's soft toned Iris quiet-layered theme! @@ -294,8 +295,12 @@ impl Studio { let inspector = InspectorState::new(&ui_theme); let add_tool = AddToolLauncher::new(); let ram_cache = RamFrameCache::new(DEFAULT_RAM_CACHE_MB); - let prefetcher = if enable_audio { - Some(RamPrefetcher::new(ram_cache.clone(), engine.vram_budget_mb())) + let prefetcher = if interactive { + Some(RamPrefetcher::new_with_device( + engine.device_arc(), + engine.queue_arc(), + ram_cache.clone(), + )) } else { None }; @@ -963,6 +968,7 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box> { cli.dual_viewer, cli.show_keyframes, false, + false, ); // Load audio waveform peaks if available so snapshot verifies the waveform overlay too load_snapshot_audio_peaks(&mut studio); @@ -1073,6 +1079,7 @@ impl WindowHost { cli.dual_viewer, cli.show_keyframes, true, + true, ); studio.redraw_proxy = Some(proxy.clone()); studio.ui.window_focused = window.has_focus(); @@ -1287,13 +1294,17 @@ mod tests { }, }"#; - fn studio() -> Studio { + fn studio_with_flags(enable_audio: bool, interactive: bool) -> Studio { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); let adapter = pollster::block_on(instance.request_adapter(&Default::default())).expect("adapter"); let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).expect("device"); let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm); let comp = Comp::from_fusion_str(COMP).expect("comp"); - Studio::new(renderer, comp, None, None, true, false, false) + Studio::new(renderer, comp, None, None, true, false, enable_audio, interactive) + } + + fn studio() -> Studio { + studio_with_flags(false, false) } fn id(studio: &Studio, name: &str) -> NodeId { @@ -1380,4 +1391,144 @@ mod tests { assert!(!studio.add_tool.open); assert!(studio.status_notice.as_ref().is_some_and(|(m, _)| m.contains("read-only"))); } + + #[test] + fn interactive_flag_gates_prefetcher_independently_of_audio() { + let interactive_no_audio = studio_with_flags(false, true); + assert!(!interactive_no_audio.enable_audio); + assert!(interactive_no_audio.audio_player.is_none()); + assert!(interactive_no_audio.prefetcher.is_some()); + + let non_interactive = studio_with_flags(false, false); + assert!(non_interactive.prefetcher.is_none()); + } + + #[test] + fn undo_redo_preserves_media_cache_while_bust_all_clears_it() { + let mut studio = studio(); + let dir = std::env::temp_dir().join("fission_undo_media_preserve_test"); + let _ = std::fs::create_dir_all(&dir); + let png_path = dir.join("tiny.png"); + { + let f = std::fs::File::create(&png_path).expect("create png"); + let mut enc = png::Encoder::new(f, 2, 2); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.write_header() + .unwrap() + .write_image_data(&[255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255]) + .unwrap(); + } + let clip = model::ClipSpec { + filename: png_path.to_string_lossy().into_owned(), + alternate_filename: None, + start_frame: 0, + length: Some(1), + trim_in: 0, + trim_out: 0, + global_start: 0, + global_end: 0, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }; + assert!(studio.engine.media.load_clip(&clip, 0, false, [None; 4]).is_some()); + assert_eq!(studio.engine.media.entry_count(), 1); + + // Seed GPU cache and stale RAM cache entry, then perform an edit + undo + redo. + let merge = id(&studio, "Merge1"); + let _ = studio.engine.evaluate(&studio.comp, merge, 0.0); + assert!(studio.engine.cache.entry_count() > 0); + let stale_rev = studio.comp.revision.wrapping_add(999); + studio.ram_cache.insert( + engine::RamFrameKey { + target: merge, + revision: stale_rev, + frame: 0, + proxy_scale: 1, + hiq: true, + use_proxy_clips: false, + }, + engine::RamFrame { + size: [2, 2], + rgba: Arc::new(vec![0u8; 16]), + eval_ms: 0.1, + }, + ); + assert_eq!(studio.ram_cache.entry_count(), 1); + + studio.history.push_snapshot(&studio.comp, "Delete Nodes"); + studio.comp.delete_nodes(&[merge]); + studio.undo(); + assert_eq!( + studio.engine.media.entry_count(), + 1, + "Undo must preserve MediaCache entries" + ); + assert_eq!( + studio.engine.cache.entry_count(), + 0, + "Undo must bust GPU node cache" + ); + assert_eq!( + studio.ram_cache.entry_count(), + 0, + "Undo must evict stale RAM cache revisions" + ); + + let _ = studio.engine.evaluate(&studio.comp, id(&studio, "Merge1"), 0.0); + studio.redo(); + assert_eq!( + studio.engine.media.entry_count(), + 1, + "Redo must preserve MediaCache entries" + ); + assert_eq!(studio.engine.cache.entry_count(), 0); + + // Explicit Bust All still wipes MediaCache. + studio.route_viewer_actions(vec![(0, ViewerAction::BustAll)], Instant::now()); + assert_eq!(studio.engine.media.entry_count(), 0); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn export_pauses_and_resumes_ram_prefetcher() { + let mut studio = studio_with_flags(false, true); + let (gate_tx, gate_rx) = mpsc::channel::<()>(); + let initial = engine::export::ExportProgress { + total_frames: 1, + label: "TestExport".to_owned(), + ..Default::default() + }; + studio + .spawn_export_worker(export_ui::ExportKind::SaverPngs, initial, move |eng, _, _| { + // Verify shared device Engine can evaluate during export. + let comp = Comp::from_fusion_str(COMP).unwrap(); + let target = comp.find_node("Merge1").unwrap(); + let (tex, _) = eng.evaluate(&comp, target, 0.0); + assert_eq!(tex.size, [64, 64]); + let _ = gate_rx.recv_timeout(Duration::from_secs(5)); + Ok("done".to_owned()) + }) + .expect("spawn export"); + + assert!(studio.active_export.is_some()); + // While export is active, sync_ram_ranges_and_prefetch must NOT schedule lookahead. + studio.sync_ram_ranges_and_prefetch(); + assert!(studio.last_prefetch_sig.is_none()); + + let _ = gate_tx.send(()); + let deadline = Instant::now() + Duration::from_secs(5); + while studio.active_export.is_some() && Instant::now() < deadline { + studio.poll_export(); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(studio.active_export.is_none()); + + // Once export completes, sync_ram_ranges_and_prefetch automatically resumes lookahead. + studio.sync_ram_ranges_and_prefetch(); + assert!(studio.last_prefetch_sig.is_some()); + } } diff --git a/crates/app/src/playback_ui.rs b/crates/app/src/playback_ui.rs index 7c8d35b2e1ec77fe0f8b27d60accbebb02ca71ba..dd128f886b8854fe6602203e0d20f5dc55cadac7 100644 --- a/crates/app/src/playback_ui.rs +++ b/crates/app/src/playback_ui.rs @@ -176,7 +176,7 @@ impl Studio { if let Some(id) = node { self.engine.bust_subtree(id); } else { - self.engine.bust_all_caches(); + self.engine.bust_gpu_cache(); } self.ram_cache.invalidate_other_revisions(self.comp.revision); if let Some(pf) = &self.prefetcher { @@ -211,36 +211,38 @@ impl Studio { } self.keyframes.cached_ranges = self.viewers[0].ram_cached_ranges.clone(); - let target = self.viewers[0].viewed_node.filter(|id| id.0 < self.comp.nodes.len()); - if let (Some(target), Some(pf)) = (target, &mut self.prefetcher) { - if self.engine.cache.mode == CacheMode::Enabled { - let cur_f = self.playback.current_frame.round() as i64; - let key = ( - target, - self.comp.revision, - self.engine.proxy_scale, - self.engine.hiq, - self.engine.use_proxy_clips, - self.comp.render_range, - ); - // Re-plan only when the job changes or the playhead leaves the half of the window - // already being filled, so steady playback never re-clones the comp per frame. - let covered = self.last_prefetch_sig.is_some_and(|(k, center)| { - k == key && (center..=center + PREFETCH_LOOKAHEAD / 2).contains(&cur_f) - }); - if !covered { - self.last_prefetch_sig = Some((key, cur_f)); - self.ram_cache.invalidate_other_revisions(self.comp.revision); - pf.request_lookahead(PrefetchJob { - comp: self.comp.clone(), + if self.active_export.is_none() { + let target = self.viewers[0].viewed_node.filter(|id| id.0 < self.comp.nodes.len()); + if let (Some(target), Some(pf)) = (target, &mut self.prefetcher) { + if self.engine.cache.mode == CacheMode::Enabled { + let cur_f = self.playback.current_frame.round() as i64; + let key = ( target, - center_frame: cur_f, - range: self.comp.render_range, - lookahead: PREFETCH_LOOKAHEAD, - proxy_scale: self.engine.proxy_scale, - hiq: self.engine.hiq, - use_proxy_clips: self.engine.use_proxy_clips, + self.comp.revision, + self.engine.proxy_scale, + self.engine.hiq, + self.engine.use_proxy_clips, + self.comp.render_range, + ); + // Re-plan only when the job changes or the playhead leaves the half of the window + // already being filled, so steady playback never re-clones the comp per frame. + let covered = self.last_prefetch_sig.is_some_and(|(k, center)| { + k == key && (center..=center + PREFETCH_LOOKAHEAD / 2).contains(&cur_f) }); + if !covered { + self.last_prefetch_sig = Some((key, cur_f)); + self.ram_cache.invalidate_other_revisions(self.comp.revision); + pf.request_lookahead(PrefetchJob { + comp: self.comp.clone(), + target, + center_frame: cur_f, + range: self.comp.render_range, + lookahead: PREFETCH_LOOKAHEAD, + proxy_scale: self.engine.proxy_scale, + hiq: self.engine.hiq, + use_proxy_clips: self.engine.use_proxy_clips, + }); + } } } } diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index c6f891db3e520b2f8d87aba972ffcd1a76256222..636692a1126c419199cd21aa8dcfdf7c1e285919 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -393,6 +393,9 @@ impl ShaderRegistry { } } +const MAX_OUTPUT_CACHE_BYTES: u64 = 128 * 1024 * 1024; +const MAX_OUTPUT_CACHE_ENTRIES: usize = 64; + pub struct Engine { device: wgpu::Device, queue: wgpu::Queue, @@ -408,13 +411,14 @@ pub struct Engine { sprite_cache: HashMap<(NodeId, u64, i64), (crate::particles::SpriteImage, u64)>, ram_upload_tex: RefCell>, dummy: CachedTexture, + vram_budget_bytes: u64, pub cache: NodeCache, pub media: MediaCache, pub expr: ExprEngine, /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, - /// Bounded LRU of recent final output textures (up to 8 entries) so tight VRAM caps on - /// 150+ node comps still deliver `<0.1ms` warm hits during pan/zoom/exposure/scrubbing. + /// Bounded LRU of recent final output textures capped by byte budget (`min(vram_budget / 4, 128 MiB)`), + /// always keeping at least the most recent frame for `<0.1ms` warm hits during pan/zoom/exposure/scrubbing. output_cache: std::collections::VecDeque<(u64, CachedTexture, Vec)>, /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default /// to matching the dimensions & aspect ratio of the node they mask!). @@ -459,6 +463,7 @@ impl Engine { sprite_cache: HashMap::new(), ram_upload_tex: RefCell::new(None), dummy, + vram_budget_bytes: crate::cache::DEFAULT_VRAM_BUDGET_MB.saturating_mul(1024 * 1024), cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB), media: MediaCache::new(512), expr: ExprEngine::new(), @@ -478,6 +483,7 @@ impl Engine { media_budget_bytes: u64, ) -> Self { let mut eng = Self::new((*device).clone(), (*queue).clone()); + eng.vram_budget_bytes = vram_budget_bytes; eng.cache.budget_bytes = vram_budget_bytes; let media_mb = if media_budget_bytes == 0 { 0 @@ -607,19 +613,63 @@ impl Engine { &self.queue } + pub fn device_arc(&self) -> std::sync::Arc { + std::sync::Arc::new(self.device.clone()) + } + + pub fn queue_arc(&self) -> std::sync::Arc { + std::sync::Arc::new(self.queue.clone()) + } + pub fn set_cache_mode(&mut self, mode: CacheMode) { self.cache.mode = mode; } + fn output_cache_budget_bytes(&self) -> u64 { + if self.vram_budget_bytes < 64 * 1024 * 1024 { + 0 + } else { + (self.vram_budget_bytes / 4).min(MAX_OUTPUT_CACHE_BYTES) + } + } + + /// Total GPU bytes held by `output_cache`. + pub fn output_cache_bytes(&self) -> u64 { + self.output_cache.iter().map(|(_, tex, _)| tex.bytes).sum() + } + + /// Total resident GPU VRAM bytes across `NodeCache` (live + pooled) and `output_cache`. + pub fn vram_bytes(&self) -> u64 { + self.cache.total_vram_bytes().saturating_add(self.output_cache_bytes()) + } + + pub fn vram_mb(&self) -> f64 { + self.vram_bytes() as f64 / (1024.0 * 1024.0) + } + + fn sync_node_cache_budget(&mut self) { + let remaining_bytes = self.vram_budget_bytes.saturating_sub(self.output_cache_bytes()); + let remaining_mb = remaining_bytes / (1024 * 1024); + if self.cache.budget_bytes != remaining_mb.saturating_mul(1024 * 1024) { + self.cache.set_budget_mb(remaining_mb); + } + } + pub fn set_vram_budget_mb(&mut self, budget_mb: u64) { - self.cache.set_budget_mb(budget_mb); - if budget_mb < 64 { + self.vram_budget_bytes = budget_mb.saturating_mul(1024 * 1024); + let cap = self.output_cache_budget_bytes(); + if cap == 0 { self.output_cache.clear(); + } else { + while self.output_cache.len() > 1 && self.output_cache_bytes() > cap { + self.output_cache.pop_front(); + } } + self.sync_node_cache_budget(); } pub fn vram_budget_mb(&self) -> u64 { - self.cache.budget_mb() + self.vram_budget_bytes / (1024 * 1024) } pub fn set_media_budget_mb(&mut self, budget_mb: u64) { @@ -705,7 +755,7 @@ impl Engine { eval_ms: t0.elapsed().as_secs_f64() * 1000.0, cache_hits: 1, cached_entries: self.cache.entry_count(), - cached_vram_mb: self.cache.total_mb(), + cached_vram_mb: self.vram_mb(), media_entries: self.media.entry_count(), media_mb: self.media.total_mb(), ..EvalStats::default() @@ -713,8 +763,9 @@ impl Engine { } pub fn bust_all_caches(&mut self) { - self.cache.bust_all(); self.output_cache.clear(); + self.sync_node_cache_budget(); + self.cache.bust_all(); self.media.clear(); self.particles.clear(); self.sprite_cache.clear(); @@ -723,19 +774,22 @@ impl Engine { } pub fn bust_gpu_cache(&mut self) { - self.cache.bust_all(); self.output_cache.clear(); + self.sync_node_cache_budget(); + self.cache.bust_all(); self.sprite_cache.clear(); *self.ram_upload_tex.borrow_mut() = None; } pub fn bust_frame(&mut self, frame: i64) -> usize { self.output_cache.clear(); + self.sync_node_cache_budget(); self.cache.bust_frame(frame) } pub fn bust_subtree(&mut self, node: NodeId) -> usize { self.output_cache.clear(); + self.sync_node_cache_budget(); self.cache.bust_subtree(node) } @@ -766,16 +820,20 @@ impl Engine { } fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec) { - if self.cache.mode == CacheMode::Bypass || self.cache.budget_bytes < 64 * 1024 * 1024 { + let cap = self.output_cache_budget_bytes(); + if self.cache.mode == CacheMode::Bypass || cap == 0 { return; } if let Some(pos) = self.output_cache.iter().position(|(k, _, _)| *k == key) { self.output_cache.remove(pos); } self.output_cache.push_back((key, tex, unsupported)); - while self.output_cache.len() > 8 { + while self.output_cache.len() > 1 + && (self.output_cache_bytes() > cap || self.output_cache.len() > MAX_OUTPUT_CACHE_ENTRIES) + { self.output_cache.pop_front(); } + self.sync_node_cache_budget(); } /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. @@ -792,7 +850,7 @@ impl Engine { eval_ms: t0.elapsed().as_secs_f64() * 1000.0, cache_hits: 1, cached_entries: self.cache.entry_count(), - cached_vram_mb: self.cache.total_mb(), + cached_vram_mb: self.vram_mb(), media_entries: self.media.entry_count(), media_mb: self.media.total_mb(), unsupported_nodes: unsupported, @@ -814,12 +872,11 @@ impl Engine { } self.queue.submit(Some(encoder.finish())); self.frame_memo.clear(); - self.cache.flush_pending_pool(); - self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); + self.cache.flush_pending_pool(); stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; stats.cached_entries = self.cache.entry_count(); - stats.cached_vram_mb = self.cache.total_mb(); + stats.cached_vram_mb = self.vram_mb(); stats.media_entries = self.media.entry_count(); stats.media_mb = self.media.total_mb(); (tex, stats) @@ -841,16 +898,15 @@ impl Engine { label: Some("comp-viewer-eval"), }); - let tex = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { + let (tex, need_output_insert) = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { stats.cache_hits = 1; stats.unsupported_nodes = unsupported; - cached + (cached, false) } else { let mut visiting = HashSet::new(); self.frame_memo.clear(); let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); - self.output_cache_insert(out_key, t.clone(), stats.unsupported_nodes.clone()); - t + (t, true) }; let dst_size = [dst_texture.width(), dst_texture.height()]; @@ -885,11 +941,14 @@ impl Engine { self.queue.submit(Some(encoder.finish())); self.frame_memo.clear(); + if need_output_insert { + self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone()); + } self.cache.flush_pending_pool(); stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; stats.cached_entries = self.cache.entry_count(); - stats.cached_vram_mb = self.cache.total_mb(); + stats.cached_vram_mb = self.vram_mb(); stats.media_entries = self.media.entry_count(); stats.media_mb = self.media.total_mb(); stats @@ -1806,4 +1865,74 @@ Composition { assert!((g - (-0.25)).abs() < 0.05, "expected negative HDR green ~-0.25, got {g}"); assert!((b - 0.5).abs() < 0.05, "expected blue ~0.5, got {b}"); } + + #[test] + fn output_cache_enforces_byte_budget_and_reports_in_vram_bytes() { + let mut eng = Engine::new_headless().expect("gpu"); + // 64 MiB total VRAM budget -> output_cache cap is 64 / 4 = 16 MiB. + eng.set_vram_budget_mb(64); + assert_eq!(eng.output_cache_budget_bytes(), 16 * 1024 * 1024); + + // 2048x1024 RGBA8 = 8 MiB per frame (so 16 MiB cap fits 2 frames, evicting the 3rd). + let src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 5 }, + GlobalRange = { 0, 5 }, + Tools = ordered() { + AnimRed = BezierSpline { + KeyFrames = { + [0] = { 0.1 }, + [5] = { 0.9 }, + }, + }, + BG = Background { + Inputs = { + Width = Input { Value = 2048, }, + Height = Input { Value = 1024, }, + TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse output_cache test comp"); + let bg = comp.find_node("BG").unwrap(); + + let (_, s0) = eng.evaluate(&comp, bg, 0.0); + assert_eq!(eng.output_cache.len(), 1); + assert_eq!(eng.output_cache_bytes(), 8 * 1024 * 1024); + assert!(eng.vram_bytes() >= eng.output_cache_bytes()); + assert!(eng.vram_bytes() <= 64 * 1024 * 1024); + assert!((s0.cached_vram_mb - eng.vram_mb()).abs() < 0.01); + + let (_, _) = eng.evaluate(&comp, bg, 1.0); + assert_eq!(eng.output_cache.len(), 2); + assert_eq!(eng.output_cache_bytes(), 16 * 1024 * 1024); + assert!(eng.vram_bytes() <= 64 * 1024 * 1024); + + // Touch frame 0 so frame 1 becomes LRU, then evaluate frame 2 -> frame 1 evicted. + let (_, warm0) = eng.evaluate(&comp, bg, 0.0); + assert_eq!(warm0.cache_hits, 1); + + let (_, _) = eng.evaluate(&comp, bg, 2.0); + assert_eq!(eng.output_cache.len(), 2); + assert_eq!(eng.output_cache_bytes(), 16 * 1024 * 1024); + assert!(eng.vram_bytes() <= 64 * 1024 * 1024); + + // Frame 1 was evicted, so evaluating frame 1 misses output_cache; frame 2 hits. + let k1 = eng.output_cache_key(&comp, bg, 1.0); + let k2 = eng.output_cache_key(&comp, bg, 2.0); + assert!(eng.output_cache_get(k1).is_none(), "LRU frame 1 should have been evicted"); + assert!(eng.output_cache_get(k2).is_some(), "recent frame 2 should still be cached"); + + // Even a single frame exceeding the byte cap (e.g., 4096x2048 RGBA8 = 32 MiB > 16 MiB) + // must always keep at least the most recent frame in output_cache. + let big_tex = create_texture(&eng.device, [4096, 2048], 0); + assert_eq!(big_tex.bytes, 32 * 1024 * 1024); + eng.output_cache_insert(999_999, big_tex, Vec::new()); + assert_eq!(eng.output_cache.len(), 1); + assert_eq!(eng.output_cache_bytes(), 32 * 1024 * 1024); + } } diff --git a/crates/engine/src/ram_cache.rs b/crates/engine/src/ram_cache.rs index 70bf3ee93f77d6285998cbe6d75e7756d4ffe997..37ea27faf1c7d75c7cc4febb02fa256fc372be41 100644 --- a/crates/engine/src/ram_cache.rs +++ b/crates/engine/src/ram_cache.rs @@ -16,6 +16,10 @@ use std::thread::{self, JoinHandle}; /// Default RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames). pub const DEFAULT_RAM_CACHE_MB: u64 = 1024; +/// Modest VRAM budget for the shared-device background prefetcher `Engine`. +pub const DEFAULT_PREFETCH_VRAM_MB: u64 = 256; +/// Modest media decode cache budget for the shared-device background prefetcher `Engine`. +pub const DEFAULT_PREFETCH_MEDIA_MB: u64 = 128; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct RamFrameKey { @@ -81,6 +85,12 @@ impl Default for RamFrameCache { } } +impl From> for RamFrameCache { + fn from(arc: Arc) -> Self { + (*arc).clone() + } +} + impl RamFrameCache { pub fn new(budget_mb: u64) -> Self { Self { @@ -275,14 +285,17 @@ struct WorkerSlot { shutdown: bool, } -/// Background lookahead frame pre-fetcher backed by a dedicated headless `Engine`. +/// Background lookahead frame pre-fetcher backed by a background `Engine` (either sharing +/// the host `wgpu::Device`/`wgpu::Queue` or initializing a standalone headless device). /// /// Calling `request_lookahead` or `cancel` immediately increments an atomic generation /// counter so any in-flight lookahead loop aborts before evaluating another frame. pub struct RamPrefetcher { cache: RamFrameCache, cache_epoch: Arc, + shared_device: Option<(Arc, Arc)>, vram_budget_mb: u64, + media_budget_mb: u64, generation: Arc, busy: Arc, completed_frames: Arc, @@ -293,11 +306,37 @@ pub struct RamPrefetcher { impl RamPrefetcher { pub fn new(cache: RamFrameCache, worker_vram_budget_mb: u64) -> Self { + Self::init(None, cache, worker_vram_budget_mb.max(128), 512) + } + + /// Creates a `RamPrefetcher` whose worker `Engine` shares an existing `wgpu::Device` + /// and `wgpu::Queue` with modest budgets (256 MiB VRAM, 128 MiB media). + pub fn new_with_device( + device: Arc, + queue: Arc, + cache: impl Into, + ) -> Self { + Self::init( + Some((device, queue)), + cache.into(), + DEFAULT_PREFETCH_VRAM_MB, + DEFAULT_PREFETCH_MEDIA_MB, + ) + } + + fn init( + shared_device: Option<(Arc, Arc)>, + cache: RamFrameCache, + vram_budget_mb: u64, + media_budget_mb: u64, + ) -> Self { let cache_epoch = cache.epoch_arc(); Self { cache, cache_epoch, - vram_budget_mb: worker_vram_budget_mb.max(128), + shared_device, + vram_budget_mb, + media_budget_mb, generation: Arc::new(AtomicU64::new(1)), busy: Arc::new(AtomicBool::new(false)), completed_frames: Arc::new(AtomicU64::new(0)), @@ -353,7 +392,9 @@ impl RamPrefetcher { } let cache = self.cache.clone(); let cache_epoch = self.cache_epoch.clone(); + let shared_device = self.shared_device.clone(); let vram_mb = self.vram_budget_mb; + let media_mb = self.media_budget_mb; let generation = self.generation.clone(); let busy = self.busy.clone(); let completed = self.completed_frames.clone(); @@ -406,14 +447,23 @@ impl RamPrefetcher { } if engine_opt.is_none() { - match Engine::new_headless() { - Ok(mut eng) => { - eng.set_vram_budget_mb(vram_mb); - engine_opt = Some(eng); - } - Err(_) => { - // Headless GPU unavailable; stay idle until shutdown. - continue; + if let Some((ref dev, ref q)) = shared_device { + engine_opt = Some(Engine::new_with_device( + Arc::clone(dev), + Arc::clone(q), + vram_mb.saturating_mul(1024 * 1024), + media_mb.saturating_mul(1024 * 1024), + )); + } else { + match Engine::new_headless() { + Ok(mut eng) => { + eng.set_vram_budget_mb(vram_mb); + engine_opt = Some(eng); + } + Err(_) => { + // Headless GPU unavailable; stay idle until shutdown. + continue; + } } } } @@ -739,4 +789,60 @@ Composition { prefetcher.cancel(); assert!(cache.epoch() > after_clear_epoch); } + + #[test] + fn ram_prefetcher_new_with_device_shares_device_and_renders_lookahead() { + let host_engine = Engine::new_headless().expect("gpu"); + let comp_src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 5 }, + GlobalRange = { 0, 5 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftGreen = Input { Value = 0.75, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let target = comp.find_node("BG1").expect("BG1"); + let cache = RamFrameCache::new(64); + let mut prefetcher = RamPrefetcher::new_with_device( + host_engine.device_arc(), + host_engine.queue_arc(), + cache.clone(), + ); + assert_eq!(prefetcher.vram_budget_mb, DEFAULT_PREFETCH_VRAM_MB); + assert_eq!(prefetcher.media_budget_mb, DEFAULT_PREFETCH_MEDIA_MB); + + prefetcher.request_lookahead(PrefetchJob { + comp: comp.clone(), + target, + center_frame: 0, + range: [0, 5], + lookahead: 3, + proxy_scale: 1, + hiq: true, + use_proxy_clips: false, + }); + + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + if cache.cached_frame_ranges(target, comp.revision, 1, true, false) == vec![(1, 3)] { + break; + } + thread::sleep(Duration::from_millis(15)); + } + assert_eq!( + cache.cached_frame_ranges(target, comp.revision, 1, true, false), + vec![(1, 3)] + ); + prefetcher.cancel(); + } } -- 2.54.1