diff --git a/crates/engine/src/cache.rs b/crates/engine/src/cache.rs index e3cee7d8029e22e5a5e097bfb96adfa5d9392814..7256736bdd7920afcda38f80475256a573967e38 100644 --- a/crates/engine/src/cache.rs +++ b/crates/engine/src/cache.rs @@ -5,6 +5,7 @@ use crate::profile::{FrameProfile, ProfileRecorder}; use model::{BitDepth, Comp, NodeId}; use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -456,6 +457,9 @@ pub struct NodeCache { total_bytes: u64, tick: u64, evictions: u64, + /// Monotonic counter incremented whenever a texture is dropped without being pooled + /// or evicted from `TexturePool`, used to invalidate `BindGroup` caches before they pin VRAM. + vram_drops: AtomicU64, /// Monotonic salt bumped when busting GPU cache globally. pub gpu_salt: u64, /// Per-node salt bumped when surgically busting a subtree. @@ -479,6 +483,7 @@ impl NodeCache { total_bytes: 0, tick: 0, evictions: 0, + vram_drops: AtomicU64::new(0), gpu_salt: 0, node_salts: HashMap::new(), pool: Mutex::new(TexturePool::new()), @@ -512,6 +517,10 @@ impl NodeCache { self.evictions } + pub fn vram_drops(&self) -> u64 { + self.vram_drops.load(Ordering::Relaxed) + } + pub fn node_salt(&self, id: NodeId) -> u64 { self.node_salts.get(&id).copied().unwrap_or(0) } @@ -583,16 +592,7 @@ impl NodeCache { } pool.misses += 1; // Evict oldest pooled textures upfront so live + pooled + new allocation stays within budget. - while self - .total_bytes - .saturating_add(pool.total_bytes) - .saturating_add(bytes) - > self.budget_bytes - { - if !pool.evict_oldest() { - break; - } - } + self.trim_pool_locked(&mut pool, bytes); } let texture = device.create_texture(&wgpu::TextureDescriptor { @@ -741,6 +741,9 @@ impl NodeCache { fn defer_to_pool(&mut self, tex: CachedTexture) { if tex.bytes == 0 || tex.bytes > self.budget_bytes { + if tex.bytes > 0 { + self.vram_drops.fetch_add(1, Ordering::Relaxed); + } return; } let mut pending_bytes: u64 = self.pending_pool.iter().map(|t| t.bytes).sum(); @@ -764,6 +767,7 @@ impl NodeCache { } pending_bytes = pending_bytes.saturating_sub(dropped.bytes); self.pending_pool.pop_front(); + self.vram_drops.fetch_add(1, Ordering::Relaxed); } if self .total_bytes @@ -772,6 +776,8 @@ impl NodeCache { <= self.budget_bytes { self.pending_pool.push_back(tex); + } else { + self.vram_drops.fetch_add(1, Ordering::Relaxed); } } } @@ -795,26 +801,35 @@ impl NodeCache { } } + fn trim_pool_locked(&self, pool: &mut TexturePool, reserve_bytes: u64) { + while self + .total_bytes + .saturating_add(pool.total_bytes) + .saturating_add(reserve_bytes) + > self.budget_bytes + { + if !pool.evict_oldest() { + break; + } + self.vram_drops.fetch_add(1, Ordering::Relaxed); + } + } + fn return_to_pool(&self, tex: &CachedTexture) { if tex.bytes == 0 || tex.bytes > self.budget_bytes { + if tex.bytes > 0 { + self.vram_drops.fetch_add(1, Ordering::Relaxed); + } return; } let mut pool = self.pool.lock().expect("texture pool lock"); pool.push(tex); - while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { - if !pool.evict_oldest() { - break; - } - } + self.trim_pool_locked(&mut pool, 0); } fn trim_pool_to_budget(&self) { let mut pool = self.pool.lock().expect("texture pool lock"); - while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { - if !pool.evict_oldest() { - break; - } - } + self.trim_pool_locked(&mut pool, 0); } fn evict_over_budget(&mut self) { @@ -868,22 +883,31 @@ impl NodeCache { for tex in recycle_scratch { if tex.bytes > 0 && tex.bytes <= self.budget_bytes { pool.push(&tex); + } else if tex.bytes > 0 { + self.vram_drops.fetch_add(1, Ordering::Relaxed); } } for tex in pending { if tex.bytes > 0 && tex.bytes <= self.budget_bytes { pool.push(&tex); + } else if tex.bytes > 0 { + self.vram_drops.fetch_add(1, Ordering::Relaxed); } } for entry in drained { if entry.tex.bytes > 0 && entry.tex.bytes <= self.budget_bytes { pool.push(&entry.tex); + } else if entry.tex.bytes > 0 { + self.vram_drops.fetch_add(1, Ordering::Relaxed); } } - while self.total_bytes.saturating_add(pool.total_bytes) > self.budget_bytes { - if !pool.evict_oldest() { - break; - } + self.trim_pool_locked(&mut pool, 0); + } else { + let dropped = drained.iter().filter(|e| e.tex.bytes > 0).count() + + pending.iter().filter(|t| t.bytes > 0).count() + + recycle_scratch.iter().filter(|t| t.bytes > 0).count(); + if dropped > 0 { + self.vram_drops.fetch_add(dropped as u64, Ordering::Relaxed); } } count @@ -1235,4 +1259,33 @@ mod tests { assert_eq!(Arc::as_ptr(&reused.texture), ptr); assert_eq!(cache.pool_stats().hits, 1); } + + #[test] + fn vram_drops_increments_on_eviction_overflow_and_pool_trim() { + let eng = Engine::new_headless().expect("gpu"); + let device = eng.device(); + let usage = NodeCache::default_texture_usage(); + // 4 MiB budget: each 512x512 RGBA8 is 1 MiB. + let mut cache = NodeCache::new(4); + assert_eq!(cache.vram_drops(), 0); + + // Insert 5 entries -> 1 is evicted to pending_pool; flushing exceeds 4 MiB and drops it. + for i in 0..5u64 { + let t = cache.acquire_texture(device, 512, 512, wgpu::TextureFormat::Rgba8Unorm, usage); + cache.insert(i, t, NodeId(i as usize), 0); + } + cache.flush_pending_pool(); + let after_overflow = cache.vram_drops(); + assert!(after_overflow >= 1, "expected vram_drops >= 1 after overflow, got {after_overflow}"); + + // Lowering budget below live bytes evicts & drops entries monotonically. + cache.set_budget_mb(1); + assert!(cache.vram_drops() > after_overflow); + + // Busting with 0 budget drops all remaining entries. + let before_bust = cache.vram_drops(); + cache.set_budget_mb(0); + cache.bust_all(); + assert!(cache.vram_drops() > before_bust); + } } diff --git a/crates/engine/src/eval/dispatch.rs b/crates/engine/src/eval/dispatch.rs index 69e5341faefd569b525ab0c5754e6dd53c5e036b..f311a3e8bbeca17ded32aef0f73e0b9d8416c55e 100644 --- a/crates/engine/src/eval/dispatch.rs +++ b/crates/engine/src/eval/dispatch.rs @@ -36,6 +36,8 @@ pub struct PendingReadback { #[cfg(not(target_arch = "wasm32"))] buf: wgpu::Buffer, #[cfg(not(target_arch = "wasm32"))] + submission_index: wgpu::SubmissionIndex, + #[cfg(not(target_arch = "wasm32"))] rx: std::sync::mpsc::Receiver>, #[cfg(not(target_arch = "wasm32"))] width: u32, @@ -60,15 +62,18 @@ impl PendingReadback { } #[cfg(not(target_arch = "wasm32"))] { + // Poll non-blockingly first so already-completed readbacks fire immediately. + let _ = engine.device.poll(wgpu::PollType::Poll); let map_res = match self.rx.try_recv() { Ok(res) => res, - Err(_) => { + Err(std::sync::mpsc::TryRecvError::Empty) => { engine.device.poll(wgpu::PollType::Wait { - submission_index: None, + submission_index: Some(self.submission_index), timeout: Some(std::time::Duration::from_secs(10)), })?; self.rx.recv()? } + Err(err @ std::sync::mpsc::TryRecvError::Disconnected) => return Err(err.into()), }; map_res?; let slice = self.buf.slice(..self.required_bytes); @@ -98,6 +103,16 @@ impl Engine { self.pipelines.borrow_mut().prewarm_core(&self.device); } + /// Pre-compiles core WGSL shader modules and compute pipelines for `Int8` (viewer/readback) + /// and `depth` when `hiq` is active (e.g. `BitDepth::Float16` for EXR/HiQ comps). + pub fn prewarm_for_depth(&self, depth: BitDepth) { + self.pipelines.borrow_mut().prewarm_core(&self.device); + let eff = self.effective_depth(depth); + if eff != BitDepth::Int8 { + self.pipelines_for(eff).borrow_mut().prewarm_core(&self.device); + } + } + pub(super) fn alloc_tex(&self, size: [u32; 2], depth: BitDepth, content_hash: u64) -> CachedTexture { self.alloc_tex_dod(size, [0, 0], size, depth, content_hash) } @@ -239,7 +254,7 @@ impl Engine { ]; params.p[1] = display.uv_rect; params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0]; - self.dispatch_to_view( + self.dispatch_to_view_uncached( &mut encoder, ShaderOp::DisplayBlit, &src.view, @@ -250,6 +265,7 @@ impl Engine { ¶ms, ); self.queue.submit(Some(encoder.finish())); + self.reset_uniform_cursors(); EvalStats { eval_ms: t0.elapsed().as_secs_f64() * 1000.0, @@ -276,30 +292,31 @@ impl Engine { } #[cfg(not(target_arch = "wasm32"))] { - let [w, h] = tex.size; + let needs_conv = tex.format != wgpu::TextureFormat::Rgba8Unorm; + let converted = if needs_conv { + let mut reg = self.pipelines.borrow_mut(); + Some(reg.readback_pool.acquire_conv_tex(&self.device, tex.size)) + } else { + None + }; + let src_tex = converted.as_ref().unwrap_or(tex); + let [w, h] = src_tex.size; let bpp = 4u32; let unpadded_bpr = w * bpp; let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; let padded_bpr = unpadded_bpr.div_ceil(align) * align; let required_bytes = u64::from(padded_bpr) * u64::from(h); - let needs_conv = tex.format != wgpu::TextureFormat::Rgba8Unorm; - - let (buf, converted) = { - let mut reg = self.pipelines.borrow_mut(); - let buf = reg.readback_pool.acquire_buffer(&self.device, required_bytes); - let conv = if needs_conv { - Some(reg.readback_pool.acquire_conv_tex(&self.device, tex.size)) - } else { - None - }; - (buf, conv) - }; + let buf = self + .pipelines + .borrow_mut() + .readback_pool + .acquire_buffer(&self.device, required_bytes); let mut enc = self.device.create_command_encoder(&Default::default()); - let src_tex = if let Some(conv) = converted.as_ref() { + if let Some(conv) = converted.as_ref() { let mut params = UniformParams::default(); params.p[0] = [1.0, 1.0, 0.0, 0.0]; - self.dispatch_to_view( + self.dispatch_to_view_uncached( &mut enc, ShaderOp::DisplayBlit, &tex.view, @@ -309,10 +326,7 @@ impl Engine { conv.size, ¶ms, ); - conv - } else { - tex - }; + } enc.copy_texture_to_buffer( src_tex.texture.as_image_copy(), wgpu::TexelCopyBufferInfo { @@ -325,7 +339,8 @@ impl Engine { }, wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, ); - self.queue.submit(Some(enc.finish())); + let submission_index = self.queue.submit(Some(enc.finish())); + self.reset_uniform_cursors(); let slice = buf.slice(..required_bytes); let (tx, rx) = std::sync::mpsc::channel(); @@ -334,6 +349,7 @@ impl Engine { }); Ok(PendingReadback { buf, + submission_index, rx, width: w, height: h, @@ -363,23 +379,40 @@ impl Engine { dst_view: &wgpu::TextureView, dst_size: [u32; 2], params: &UniformParams, + cache_bg: bool, ) { - let (dynamic_offset, bg_hash, bg_idx) = { + let (dynamic_offset, uncached_bg, cached_key) = { let mut reg = reg_cell.borrow_mut(); reg.ensure_pipeline(&self.device, op); let (chunk_idx, dynamic_offset) = reg.alloc_uniform_slot(&self.device, &self.queue, params); - let (bg_hash, bg_idx) = reg.ensure_bind_group( - &self.device, - src_a, - src_b, - mask, - dst_view, - chunk_idx, - ); - (dynamic_offset, bg_hash, bg_idx) + if cache_bg { + let (bg_hash, bg_idx) = reg.ensure_bind_group( + &self.device, + src_a, + src_b, + mask, + dst_view, + chunk_idx, + ); + (dynamic_offset, None, Some((bg_hash, bg_idx))) + } else { + let bg = reg.create_bind_group( + &self.device, + src_a, + src_b, + mask, + dst_view, + chunk_idx, + ); + (dynamic_offset, Some(bg), None) + } }; let reg = reg_cell.borrow(); - let bg = reg.get_bind_group(bg_hash, bg_idx); + let bg = match (&uncached_bg, cached_key) { + (Some(bg), _) => bg, + (None, Some((bg_hash, bg_idx))) => reg.get_bind_group(bg_hash, bg_idx), + (None, None) => unreachable!(), + }; let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("comp-op"), @@ -412,11 +445,14 @@ impl Engine { &dst.view, dst.size, params, + true, ); } + /// Dispatches a compute shader into an ephemeral `TextureView` (e.g. viewer surface or + /// one-shot readback conversion) without inserting into `bg_cache`. #[allow(clippy::too_many_arguments)] - pub(super) fn dispatch_to_view( + pub(super) fn dispatch_to_view_uncached( &self, enc: &mut wgpu::CommandEncoder, op: ShaderOp, @@ -437,6 +473,7 @@ impl Engine { dst_view, dst_size, params, + false, ); } } @@ -719,4 +756,64 @@ mod tests { eng.pipelines.borrow_mut().clear_bind_group_cache(); assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0); } + + #[test] + fn pending_readback_tracks_submission_index_and_bypasses_bg_cache() { + let Ok(eng) = Engine::new_headless() else { + return; + }; + let fill = |tex: &CachedTexture, rgba: [f32; 4]| { + let mut enc = eng.device.create_command_encoder(&Default::default()); + let mut u = UniformParams::default(); + u.p[0] = rgba; + u.p[1] = rgba; + u.p[2] = rgba; + u.p[3] = rgba; + eng.dispatch_op( + &mut enc, + ShaderOp::Bg, + &eng.dummy.view, + &eng.dummy.view, + &eng.dummy.view, + tex, + &u, + ); + eng.queue.submit(Some(enc.finish())); + eng.reset_uniform_cursors(); + }; + + let f16_a = eng.alloc_tex([16, 16], BitDepth::Float16, 0); + let f16_b = eng.alloc_tex([16, 16], BitDepth::Float16, 0); + fill(&f16_a, [0.2, 0.4, 0.8, 1.0]); + fill(&f16_b, [0.9, 0.1, 0.5, 1.0]); + + eng.pipelines.borrow_mut().clear_bind_group_cache(); + let misses_before = eng.pipelines.borrow().bg_misses; + + // Overlapping double-buffered readbacks: finish out of order (b then a) via SubmissionIndex. + let pend_a = eng.begin_readback_rgba(&f16_a).expect("begin a"); + let pend_b = eng.begin_readback_rgba(&f16_b).expect("begin b"); + assert_ne!( + format!("{:?}", pend_a.submission_index), + format!("{:?}", pend_b.submission_index) + ); + assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0); + assert_eq!(eng.pipelines.borrow().bg_misses, misses_before); + + let px_b = pend_b.finish(&eng).expect("finish b"); + let px_a = pend_a.finish(&eng).expect("finish a"); + assert!((px_a[0] as i32 - 51).abs() <= 2); + assert!((px_b[0] as i32 - 230).abs() <= 2); + + // render_ram_frame_into_viewer must also bypass bg_cache and reset uniform cursors. + let dst = eng.alloc_tex([16, 16], BitDepth::Int8, 0); + let ram_frame = crate::ram_cache::RamFrame { + size: [16, 16], + rgba: std::sync::Arc::new(vec![128u8; 16 * 16 * 4]), + eval_ms: 0.0, + }; + let _ = eng.render_ram_frame_into_viewer(&ram_frame, &dst.texture, DisplaySettings::default()); + assert_eq!(eng.pipelines.borrow().bg_entry_count(), 0); + assert_eq!(eng.pipelines.borrow().bg_misses, misses_before); + } } diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index f877db217c9ff77cc0d000f638df36532fc2d543..6261b0221d2ce4e85e47600ec3cf36f4a2feb04c 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -4,7 +4,7 @@ use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port}; -use std::cell::{OnceCell, RefCell}; +use std::cell::{Cell, OnceCell, RefCell}; use std::collections::{HashMap, HashSet}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -76,9 +76,12 @@ pub struct Engine { ram_upload_tex: RefCell>, dummy: CachedTexture, vram_budget_bytes: u64, + last_bg_vram_drops: Cell, pub cache: NodeCache, pub media: MediaCache, pub expr: ExprEngine, + /// Active evaluation target node (set during `evaluate` / `render_into_viewer`). + pub(super) frame_eval_target: Option, /// 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>, /// Lazily populated downstream adjacency list `(consumer_id, port_name)` for the current comp revision. @@ -135,9 +138,11 @@ impl Engine { ram_upload_tex: RefCell::new(None), dummy, vram_budget_bytes: default_vram_mb.saturating_mul(1024 * 1024), + last_bg_vram_drops: Cell::new(0), cache: NodeCache::new(default_vram_mb), - media: MediaCache::new(512), + media: MediaCache::default(), expr: ExprEngine::new(), + frame_eval_target: None, frame_memo: HashMap::new(), frame_consumers: Vec::new(), frame_consumers_rev: None, @@ -240,16 +245,36 @@ impl Engine { self.media.set_budget_mb(budget_mb); } - fn clear_bind_group_caches(&self) { - self.pipelines.borrow_mut().clear_bind_group_cache(); + fn for_each_registry(&self, mut f: impl FnMut(&mut ShaderRegistry)) { + f(&mut self.pipelines.borrow_mut()); if let Some(r) = self.pipelines_int16.get() { - r.borrow_mut().clear_bind_group_cache(); + f(&mut r.borrow_mut()); } if let Some(r) = self.pipelines_f16.get() { - r.borrow_mut().clear_bind_group_cache(); + f(&mut r.borrow_mut()); } if let Some(r) = self.pipelines_f32.get() { - r.borrow_mut().clear_bind_group_cache(); + f(&mut r.borrow_mut()); + } + } + + fn clear_bind_group_caches(&self) { + self.for_each_registry(|r| r.clear_bind_group_cache()); + self.last_bg_vram_drops.set(self.cache.vram_drops()); + } + + pub(super) fn reset_uniform_cursors(&self) { + self.for_each_registry(|r| r.reset_uniform_cursor()); + } + + fn trim_uniform_chunks(&self) { + self.for_each_registry(|r| r.trim_uniform_chunks(2)); + } + + pub(super) fn sync_bg_cache_with_vram_drops(&self) { + let drops = self.cache.vram_drops(); + if drops != self.last_bg_vram_drops.get() { + self.clear_bind_group_caches(); } } @@ -258,6 +283,9 @@ impl Engine { self.sync_node_cache_budget(); self.cache.bust_all(); self.clear_bind_group_caches(); + self.trim_uniform_chunks(); + #[cfg(not(target_arch = "wasm32"))] + self.pipelines.borrow_mut().readback_pool.clear(); self.media.clear(); self.particles.clear(); self.sprite_cache.clear(); @@ -273,6 +301,9 @@ impl Engine { self.sync_node_cache_budget(); self.cache.bust_all(); self.clear_bind_group_caches(); + self.trim_uniform_chunks(); + #[cfg(not(target_arch = "wasm32"))] + self.pipelines.borrow_mut().readback_pool.clear(); self.sprite_cache.clear(); self.scene3d.clear_shadow_targets(); *self.ram_upload_tex.borrow_mut() = None; @@ -281,18 +312,21 @@ impl Engine { pub fn bust_frame(&mut self, frame: i64) -> usize { self.output_cache.clear(); self.sync_node_cache_budget(); + let busted = self.cache.bust_frame(frame); self.clear_bind_group_caches(); - self.cache.bust_frame(frame) + busted } pub fn bust_subtree(&mut self, node: NodeId) -> usize { self.output_cache.clear(); self.sync_node_cache_budget(); + let busted = self.cache.bust_subtree(node); self.clear_bind_group_caches(); - self.cache.bust_subtree(node) + busted } fn prepare_frame_scratch(&mut self, comp: &Comp) -> HashSet<(NodeId, i64)> { + self.frame_eval_target = None; self.frame_memo.clear(); self.frame_roi_memo.clear(); if self.frame_consumers_rev != Some(comp.revision) @@ -307,6 +341,7 @@ impl Engine { } fn finish_frame_scratch(&mut self, mut visiting: HashSet<(NodeId, i64)>) { + self.frame_eval_target = None; self.frame_memo.clear(); self.frame_roi_memo.clear(); visiting.clear(); @@ -321,6 +356,7 @@ impl Engine { time: f64, ) -> (CachedTexture, EvalStats) { let t0 = Instant::now(); + self.sync_bg_cache_with_vram_drops(); let out_key = self.output_cache_key(comp, target, time); if let Some((tex, unsupported)) = self.output_cache_get(out_key) { let stats = EvalStats { @@ -339,6 +375,7 @@ impl Engine { self.media .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); let mut visiting = self.prepare_frame_scratch(comp); + self.frame_eval_target = Some(target); let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("comp-eval"), }); @@ -349,11 +386,13 @@ impl Engine { tex = self.crop_to_canvas(&mut encoder, tex); } self.queue.submit(Some(encoder.finish())); + self.reset_uniform_cursors(); #[cfg(not(target_arch = "wasm32"))] self.media.flush_upload_staging_after_submit(&self.device); self.finish_frame_scratch(visiting); self.cache.flush_pending_pool(); self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); + self.sync_bg_cache_with_vram_drops(); stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; stats.cached_entries = self.cache.entry_count(); stats.cached_vram_mb = self.vram_mb(); @@ -372,6 +411,7 @@ impl Engine { display: DisplaySettings, ) -> EvalStats { let t0 = Instant::now(); + self.sync_bg_cache_with_vram_drops(); let out_key = self.output_cache_key(comp, target, time); let mut stats = EvalStats::default(); let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { @@ -386,6 +426,7 @@ impl Engine { self.media .preload_frame_loaders_with_proxy(comp, target, time, &self.expr, self.use_proxy_clips); let mut visiting = self.prepare_frame_scratch(comp); + self.frame_eval_target = Some(target); let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); (t, Some(visiting)) }; @@ -409,7 +450,7 @@ impl Engine { tex.canvas_size[1] as f32, ]; } - self.dispatch_to_view( + self.dispatch_to_view_uncached( &mut encoder, ShaderOp::DisplayBlit, &tex.view, @@ -421,6 +462,7 @@ impl Engine { ); self.queue.submit(Some(encoder.finish())); + self.reset_uniform_cursors(); #[cfg(not(target_arch = "wasm32"))] self.media.flush_upload_staging_after_submit(&self.device); if let Some(visiting) = visiting_opt { @@ -428,6 +470,7 @@ impl Engine { self.output_cache_insert(out_key, tex, stats.unsupported_nodes.clone()); } self.cache.flush_pending_pool(); + self.sync_bg_cache_with_vram_drops(); stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; stats.cached_entries = self.cache.entry_count(); @@ -1472,4 +1515,79 @@ Composition { assert!(!eng.frame_consumers[fg_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); assert!(eng.frame_consumers[fg2_id.0].iter().any(|(id, port)| *id == m_id && port == "Foreground")); } + + #[test] + fn vram_drops_clear_bind_groups_and_viewer_blit_bypasses_bg_cache() { + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + // Default Engine::new wires RAM-scaled MediaCache::default(). + assert!(crate::media::default_media_cache_budget_mb() >= 512); + + // Tight 8 MiB VRAM budget: 1024x1024 RGBA8 = 4 MiB per texture. + eng.set_vram_budget_mb(8); + + let src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 10 }, + GlobalRange = { 0, 10 }, + Tools = ordered() { + AnimRed = BezierSpline { + KeyFrames = { + [0] = { 0.1 }, + [10] = { 0.9 }, + }, + }, + BG = Background { + Inputs = { + Width = Input { Value = 1024, }, + Height = Input { Value = 1024, }, + TopLeftRed = Input { SourceOp = "AnimRed", Source = "Value", }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + BC = BrightnessContrast { + Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + Gain = Input { Value = 1.2, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(src).expect("parse vram bg test comp"); + let bc = comp.find_node("BC").unwrap(); + + // Evaluate frame 0 -> uniform_cursor resets to 0 after submit, bg_cache populated. + let _ = eng.evaluate(&comp, bc, 0.0); + assert!(eng.frame_eval_target.is_none()); + assert_eq!(eng.pipelines.borrow().uniform_chunks.len(), 1); + // Next uniform slot allocated must start at chunk 0, offset 0 (cursor was reset post-submit). + { + let mut reg = eng.pipelines.borrow_mut(); + let slot = reg.alloc_uniform_slot(&eng.device, &eng.queue, &UniformParams::default()); + assert_eq!(slot, (0, 0)); + reg.reset_uniform_cursor(); + } + assert!(eng.pipelines.borrow().bg_entry_count() > 0); + + // Render into ephemeral viewer textures on frame 0 (output_cache hit): must not grow bg_cache! + let bg_before_viewer = eng.pipelines.borrow().bg_entry_count(); + let misses_before_viewer = eng.pipelines.borrow().bg_misses; + let viewer_tex_a = create_texture(&eng.device, [512, 512], 0); + let viewer_tex_b = create_texture(&eng.device, [640, 360], 0); + let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_a.texture, DisplaySettings::default()); + let _ = eng.render_into_viewer(&comp, bc, 0.0, &viewer_tex_b.texture, DisplaySettings::default()); + assert_eq!(eng.pipelines.borrow().bg_entry_count(), bg_before_viewer); + assert_eq!(eng.pipelines.borrow().bg_misses, misses_before_viewer); + + // Evaluate frames 1..=3 under 8 MiB budget -> organic eviction increments vram_drops + // and sync_bg_cache_with_vram_drops clears bg_cache so evicted textures aren't pinned. + for f in 1..=3 { + let _ = eng.evaluate(&comp, bc, f as f64); + } + assert!(eng.cache.vram_drops() > 0); + assert_eq!(eng.last_bg_vram_drops.get(), eng.cache.vram_drops()); + } } diff --git a/crates/engine/src/eval/registry.rs b/crates/engine/src/eval/registry.rs index 901c776dddb01eaa3f0d6e663b6f90a82e9706b7..448095f8260ee0086a2902ff4bf152ba73f49bd8 100644 --- a/crates/engine/src/eval/registry.rs +++ b/crates/engine/src/eval/registry.rs @@ -238,7 +238,6 @@ impl ShaderOp { const COMMON_WGSL: &str = include_str!("../shaders/common.wgsl"); const UNIFORM_SLOTS_PER_CHUNK: u32 = 1024; -const MAX_UNIFORM_CHUNKS: usize = 16; const LUT_CACHE_CAPACITY: usize = 64; #[cfg(not(target_arch = "wasm32"))] const MAX_READBACK_BUFFERS: usize = 3; @@ -401,7 +400,6 @@ impl ReadbackPool { tex } - #[allow(dead_code)] pub(super) fn clear(&mut self) { self.buffers.clear(); self.conv_tex = None; @@ -548,9 +546,8 @@ impl ShaderRegistry { /// Writes `params` into the next aligned slot in the chunked dynamic uniform ring /// and returns `(chunk_index, dynamic_byte_offset)`. /// - /// Lazily allocates 1,024-slot chunks up to `MAX_UNIFORM_CHUNKS` (16,384 slots) so a - /// single unsubmitted `CommandEncoder` never overwrites earlier slots while long - /// multi-frame playback stays memory-bounded. + /// Lazily allocates 1,024-slot chunks without wrapping mid-encoder; callers reset the + /// cursor back to `0` after each `queue.submit` so normal frames stay in chunk `0`. pub(super) fn alloc_uniform_slot( &mut self, device: &wgpu::Device, @@ -560,7 +557,7 @@ impl ShaderRegistry { let slot_global = self.uniform_cursor; let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize; let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK; - if chunk_idx >= self.uniform_chunks.len() { + while chunk_idx >= self.uniform_chunks.len() { let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); let buf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("op-params-ring"), @@ -576,12 +573,21 @@ impl ShaderRegistry { u64::from(offset), bytemuck::bytes_of(params), ); - let next = slot_global + 1; - let max_slots = (MAX_UNIFORM_CHUNKS as u32) * UNIFORM_SLOTS_PER_CHUNK; - self.uniform_cursor = if next >= max_slots { 0 } else { next }; + self.uniform_cursor = slot_global + 1; (chunk_idx, offset) } + pub(super) fn reset_uniform_cursor(&mut self) { + self.uniform_cursor = 0; + } + + pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { + self.uniform_cursor = 0; + if self.uniform_chunks.len() > max_chunks { + self.uniform_chunks.truncate(max_chunks); + } + } + /// Returns a cached tiny LUT/curve texture for `(size, format, bytes)` or uploads and /// inserts one into the bounded 64-entry LRU cache. #[allow(clippy::too_many_arguments)] @@ -657,6 +663,38 @@ impl ShaderRegistry { tex } + /// Builds a `wgpu::BindGroup` for the four `TextureView` bindings and uniform `chunk_idx` + /// without inserting into `bg_cache` (used for ephemeral viewer/readback targets). + pub(super) fn create_bind_group( + &self, + device: &wgpu::Device, + src_a: &wgpu::TextureView, + src_b: &wgpu::TextureView, + mask: &wgpu::TextureView, + dst_view: &wgpu::TextureView, + chunk_idx: usize, + ) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("op-bg"), + layout: &self.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) }, + wgpu::BindGroupEntry { + binding: 5, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.uniform_chunks[chunk_idx], + offset: 0, + size: NonZeroU64::new(std::mem::size_of::() as u64), + }), + }, + ], + }) + } + /// Looks up or creates a cached `wgpu::BindGroup` keyed by the four `TextureView` /// handles and dynamic-uniform `chunk_idx`. Holding cloned `TextureView` handles inside /// cached entries keeps their underlying resources alive while cached, preventing ABA reuse. @@ -712,25 +750,7 @@ impl ShaderRegistry { } } - let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("op-bg"), - layout: &self.bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_a) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_b) }, - wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(mask) }, - wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) }, - wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(dst_view) }, - wgpu::BindGroupEntry { - binding: 5, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: &self.uniform_chunks[chunk_idx], - offset: 0, - size: NonZeroU64::new(std::mem::size_of::() as u64), - }), - }, - ], - }); + let bg = self.create_bind_group(device, src_a, src_b, mask, dst_view, chunk_idx); let bucket = self.bg_cache.entry(hash).or_default(); let idx = bucket.len(); @@ -753,7 +773,6 @@ impl ShaderRegistry { &self.bg_cache[&hash][idx].bg } - #[allow(dead_code)] pub(super) fn clear_bind_group_cache(&mut self) { self.bg_cache.clear(); self.bg_count = 0; @@ -918,4 +937,46 @@ mod tests { } let _ = prewarm_ms; } + + #[test] + fn uniform_ring_grows_past_16_chunks_without_wrapping_and_resets() { + let Ok(eng) = Engine::new_headless() else { + return; + }; + let params = super::super::dispatch::UniformParams::default(); + let mut reg = eng.pipelines.borrow_mut(); + + let total = 16 * UNIFORM_SLOTS_PER_CHUNK + 5; + let mut last = (0usize, 0u32); + for _ in 0..total { + last = reg.alloc_uniform_slot(&eng.device, &eng.queue, ¶ms); + } + assert_eq!(last.0, 16, "cursor must grow to chunk 16 instead of wrapping to 0"); + assert_eq!(last.1, 4 * reg.uniform_stride); + assert_eq!(reg.uniform_chunks.len(), 17); + + reg.reset_uniform_cursor(); + let after_reset = reg.alloc_uniform_slot(&eng.device, &eng.queue, ¶ms); + assert_eq!(after_reset, (0, 0)); + + reg.trim_uniform_chunks(2); + assert_eq!(reg.uniform_chunks.len(), 2); + assert_eq!(reg.uniform_cursor, 0); + } + + #[test] + fn prewarm_for_depth_warms_float16_in_hiq_only() { + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + eng.hiq = false; + eng.prewarm_for_depth(model::BitDepth::Float16); + assert_eq!(eng.pipelines.borrow().pipelines.len(), CORE_PREWARM_OPS.len()); + assert!(eng.pipelines_f16.get().is_none()); + + eng.hiq = true; + eng.prewarm_for_depth(model::BitDepth::Float16); + let f16 = eng.pipelines_f16.get().expect("f16 registry initialized"); + assert_eq!(f16.borrow().pipelines.len(), CORE_PREWARM_OPS.len()); + } }