diff --git a/crates/engine/src/custom_shader.rs b/crates/engine/src/custom_shader.rs index 0e116d97f5e8b1b5d4c5e581907fd5d3b649bb83..f8688055de54e42838515c0615f494b2110c7eca 100644 --- a/crates/engine/src/custom_shader.rs +++ b/crates/engine/src/custom_shader.rs @@ -900,14 +900,20 @@ fn custom_tool_op(@builtin(global_invocation_id) gid: vec3) {{ // Pipeline Cache & GPU Dispatch // ============================================================================ -const CUSTOM_UNIFORM_SLOTS: u32 = 256; +const CUSTOM_UNIFORM_SLOTS_PER_CHUNK: u32 = 256; const CUSTOM_BIND_GROUP_CACHE_CAPACITY: usize = 128; +const MAX_CUSTOM_PIPELINES: usize = 128; struct FormatLayouts { bgl: wgpu::BindGroupLayout, pl: wgpu::PipelineLayout, } +struct CustomPipelineEntry { + pipeline: Option, + last_used: u64, +} + struct CustomBindGroupKey { format: wgpu::TextureFormat, src_1: wgpu::TextureView, @@ -915,9 +921,11 @@ struct CustomBindGroupKey { src_3: wgpu::TextureView, mask: wgpu::TextureView, dst_view: wgpu::TextureView, + chunk_idx: usize, } impl CustomBindGroupKey { + #[allow(clippy::too_many_arguments)] fn matches( &self, format: wgpu::TextureFormat, @@ -926,6 +934,7 @@ impl CustomBindGroupKey { src_3: &wgpu::TextureView, mask: &wgpu::TextureView, dst_view: &wgpu::TextureView, + chunk_idx: usize, ) -> bool { self.format == format && &self.src_1 == src_1 @@ -933,6 +942,7 @@ impl CustomBindGroupKey { && &self.src_3 == src_3 && &self.mask == mask && &self.dst_view == dst_view + && self.chunk_idx == chunk_idx } } @@ -949,6 +959,7 @@ fn hash_custom_bind_group_key( src_3: &wgpu::TextureView, mask: &wgpu::TextureView, dst_view: &wgpu::TextureView, + chunk_idx: usize, ) -> u64 { let mut h = DefaultHasher::new(); format.hash(&mut h); @@ -957,19 +968,21 @@ fn hash_custom_bind_group_key( src_3.hash(&mut h); mask.hash(&mut h); dst_view.hash(&mut h); + chunk_idx.hash(&mut h); h.finish() } /// Caches dynamically compiled `CustomTool` compute pipelines keyed by -/// `(dst_texture_format, hash_of_normalized_program)`, plus a persistent dynamic-offset -/// uniform ring buffer and LRU-cached `BindGroup`s so repeated dispatches avoid per-frame -/// GPU buffer/bind-group allocations. +/// `(dst_texture_format, normalized_program)` with an LRU cap, plus a lazily growing +/// chunked dynamic-offset uniform ring buffer and LRU-cached `BindGroup`s so repeated +/// dispatches avoid per-frame GPU buffer/bind-group allocations. #[derive(Default)] pub struct CustomShaderCache { layouts: HashMap, sampler: Option, - pipelines: HashMap<(wgpu::TextureFormat, u64), Option>, - uniform_buf: Option, + pipelines: HashMap<(wgpu::TextureFormat, CustomProgram), CustomPipelineEntry>, + pipeline_tick: u64, + uniform_chunks: Vec, uniform_stride: u32, uniform_cursor: u32, bg_cache: HashMap>, @@ -1009,6 +1022,16 @@ impl CustomShaderCache { self.uniform_cursor = 0; } + /// Trims the dynamic uniform ring to at most `keep` chunks and resets the cursor. + /// Clears `bg_cache` whenever chunks are dropped so cached bind groups never reference freed buffers. + pub fn trim_uniform_chunks(&mut self, keep: usize) { + self.uniform_cursor = 0; + if self.uniform_chunks.len() > keep { + self.uniform_chunks.truncate(keep); + self.clear_bind_group_cache(); + } + } + fn ensure_format_layouts(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) { self.layouts.entry(format).or_insert_with(|| { let tex_entry = |binding| wgpu::BindGroupLayoutEntry { @@ -1076,21 +1099,13 @@ impl CustomShaderCache { } } - fn ensure_uniform_buffer(&mut self, device: &wgpu::Device) { - if self.uniform_buf.is_some() { + fn ensure_uniform_stride(&mut self, device: &wgpu::Device) { + if self.uniform_stride != 0 { return; } let uniform_size = std::mem::size_of::() as u32; let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); - let stride = uniform_size.div_ceil(min_align) * min_align; - let buf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("custom-tool-params-ring"), - size: u64::from(CUSTOM_UNIFORM_SLOTS) * u64::from(stride), - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - self.uniform_stride = stride; - self.uniform_buf = Some(buf); + self.uniform_stride = uniform_size.div_ceil(min_align) * min_align; } fn alloc_uniform_slot( @@ -1098,14 +1113,29 @@ impl CustomShaderCache { device: &wgpu::Device, queue: &wgpu::Queue, params: &CustomParams, - ) -> u32 { - self.ensure_uniform_buffer(device); - let slot = self.uniform_cursor; - let offset = slot * self.uniform_stride; - let ubuf = self.uniform_buf.as_ref().expect("uniform buffer initialized"); - queue.write_buffer(ubuf, u64::from(offset), bytemuck::bytes_of(params)); - self.uniform_cursor = (slot + 1) % CUSTOM_UNIFORM_SLOTS; - offset + ) -> (usize, u32) { + self.ensure_uniform_stride(device); + let slot_global = self.uniform_cursor; + let chunk_idx = (slot_global / CUSTOM_UNIFORM_SLOTS_PER_CHUNK) as usize; + let slot_in_chunk = slot_global % CUSTOM_UNIFORM_SLOTS_PER_CHUNK; + while chunk_idx >= self.uniform_chunks.len() { + let size = u64::from(CUSTOM_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("custom-tool-params-ring"), + size, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.uniform_chunks.push(buf); + } + let offset = slot_in_chunk * self.uniform_stride; + queue.write_buffer( + &self.uniform_chunks[chunk_idx], + u64::from(offset), + bytemuck::bytes_of(params), + ); + self.uniform_cursor = slot_global + 1; + (chunk_idx, offset) } #[allow(clippy::too_many_arguments)] @@ -1118,8 +1148,9 @@ impl CustomShaderCache { src_3: &wgpu::TextureView, mask: &wgpu::TextureView, dst_view: &wgpu::TextureView, + chunk_idx: usize, ) -> (u64, usize) { - let hash = hash_custom_bind_group_key(format, src_1, src_2, src_3, mask, dst_view); + let hash = hash_custom_bind_group_key(format, src_1, src_2, src_3, mask, dst_view, chunk_idx); self.bg_tick = self.bg_tick.wrapping_add(1); let tick = self.bg_tick; @@ -1127,7 +1158,7 @@ impl CustomShaderCache { && let Some((idx, entry)) = bucket .iter_mut() .enumerate() - .find(|(_, e)| e.key.matches(format, src_1, src_2, src_3, mask, dst_view)) + .find(|(_, e)| e.key.matches(format, src_1, src_2, src_3, mask, dst_view, chunk_idx)) { entry.last_used = tick; self.bg_hits += 1; @@ -1164,7 +1195,7 @@ impl CustomShaderCache { let layout = &self.layouts[&format].bgl; let sampler = self.sampler.as_ref().expect("sampler initialized"); - let ubuf = self.uniform_buf.as_ref().expect("uniform buffer initialized"); + let ubuf = &self.uniform_chunks[chunk_idx]; let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("custom-tool-bg"), layout, @@ -1196,6 +1227,7 @@ impl CustomShaderCache { src_3: src_3.clone(), mask: mask.clone(), dst_view: dst_view.clone(), + chunk_idx, }, bg, last_used: tick, @@ -1233,28 +1265,53 @@ impl CustomShaderCache { Some(pipeline) } - /// Compiles and caches the compute pipeline for `program` at `format`, returning `false` - /// if the program contains unsupported syntax (graceful fallback to passthrough). - pub fn ensure_compiled( + fn ensure_compiled_key( &mut self, device: &wgpu::Device, - program: &CustomProgram, - format: wgpu::TextureFormat, + key: &(wgpu::TextureFormat, CustomProgram), ) -> bool { - let norm = program.normalized(); - let key = (format, norm.program_hash()); - if let Some(entry) = self.pipelines.get(&key) { - return entry.is_some(); + self.pipeline_tick = self.pipeline_tick.wrapping_add(1); + let tick = self.pipeline_tick; + if let Some(entry) = self.pipelines.get_mut(key) { + entry.last_used = tick; + return entry.pipeline.is_some(); } - let pipeline = match compile_wgsl(&norm, format) { - Ok(wgsl) => self.compile_wgsl_pipeline(device, format, &wgsl), + let pipeline = match compile_wgsl(&key.1, key.0) { + Ok(wgsl) => self.compile_wgsl_pipeline(device, key.0, &wgsl), Err(_) => None, }; let ok = pipeline.is_some(); - self.pipelines.insert(key, pipeline); + if self.pipelines.len() >= MAX_CUSTOM_PIPELINES + && let Some(oldest_key) = self + .pipelines + .iter() + .min_by_key(|(_, entry)| entry.last_used) + .map(|(k, _)| k.clone()) + { + self.pipelines.remove(&oldest_key); + } + self.pipelines.insert( + key.clone(), + CustomPipelineEntry { + pipeline, + last_used: tick, + }, + ); ok } + /// Compiles and caches the compute pipeline for `program` at `format`, returning `false` + /// if the program contains unsupported syntax (graceful fallback to passthrough). + pub fn ensure_compiled( + &mut self, + device: &wgpu::Device, + program: &CustomProgram, + format: wgpu::TextureFormat, + ) -> bool { + let key = (format, program.normalized()); + self.ensure_compiled_key(device, &key) + } + /// Dispatches a compiled `CustomProgram` into `dst_view`. Returns `false` if compilation failed. #[allow(clippy::too_many_arguments)] pub fn dispatch( @@ -1272,18 +1329,25 @@ impl CustomShaderCache { dst_size: [u32; 2], params: &CustomParams, ) -> bool { - let norm = program.normalized(); - let key = (format, norm.program_hash()); - if !self.ensure_compiled(device, &norm, format) { - return false; - } - if !matches!(self.pipelines.get(&key), Some(Some(_))) { + let key = (format, program.normalized()); + if !self.ensure_compiled_key(device, &key) { return false; } - let offset = self.alloc_uniform_slot(device, queue, params); - let (bg_hash, bg_idx) = self.ensure_bind_group(device, format, src_1, src_2, src_3, mask, dst_view); - let pipeline = self.pipelines[&key].as_ref().expect("pipeline checked above"); + let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); + let (bg_hash, bg_idx) = self.ensure_bind_group( + device, + format, + src_1, + src_2, + src_3, + mask, + dst_view, + chunk_idx, + ); + let Some(Some(pipeline)) = self.pipelines.get(&key).map(|e| &e.pipeline) else { + return false; + }; let bg = &self.bg_cache[&bg_hash][bg_idx].bg; let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { @@ -1706,4 +1770,141 @@ mod tests { eng.queue().submit(Some(enc.finish())); assert_eq!(cache.cached_bind_group_count(), CUSTOM_BIND_GROUP_CACHE_CAPACITY); } + + #[test] + fn custom_shader_cache_grows_uniform_chunks_past_256_without_wrapping() { + let eng = Engine::new_headless().expect("gpu"); + let mut cache = CustomShaderCache::new(); + let prog = CustomProgram { + red: "n1".to_owned(), + green: "n2".to_owned(), + blue: "0".to_owned(), + alpha: "1".to_owned(), + ..Default::default() + }; + let dummy = create_texture(eng.device(), [1, 1], 0); + let dst_first = create_texture(eng.device(), [4, 4], 1); + let dst_mid = create_texture(eng.device(), [4, 4], 2); + let dst_last = create_texture(eng.device(), [4, 4], 3); + + let mut enc = eng.device().create_command_encoder(&Default::default()); + let first_params = CustomParams { + n0: [0.2, 0.8, 0.0, 0.0], + img_dims1: [4.0, 4.0, 4.0, 4.0], + ..Default::default() + }; + assert!(cache.dispatch( + eng.device(), + eng.queue(), + &mut enc, + &prog, + wgpu::TextureFormat::Rgba8Unorm, + &dummy.view, + &dummy.view, + &dummy.view, + &dummy.view, + &dst_first.view, + [4, 4], + &first_params, + )); + + // 260 intermediate dispatches push past slot 256 (into chunk 1) in a single unsubmitted encoder. + let fill_params = CustomParams { + n0: [0.9, 0.1, 0.0, 0.0], + img_dims1: [4.0, 4.0, 4.0, 4.0], + ..Default::default() + }; + for _ in 0..260 { + assert!(cache.dispatch( + eng.device(), + eng.queue(), + &mut enc, + &prog, + wgpu::TextureFormat::Rgba8Unorm, + &dummy.view, + &dummy.view, + &dummy.view, + &dummy.view, + &dst_mid.view, + [4, 4], + &fill_params, + )); + } + + let last_params = CustomParams { + n0: [0.6, 0.4, 0.0, 0.0], + img_dims1: [4.0, 4.0, 4.0, 4.0], + ..Default::default() + }; + assert!(cache.dispatch( + eng.device(), + eng.queue(), + &mut enc, + &prog, + wgpu::TextureFormat::Rgba8Unorm, + &dummy.view, + &dummy.view, + &dummy.view, + &dummy.view, + &dst_last.view, + [4, 4], + &last_params, + )); + + assert_eq!(cache.uniform_chunks.len(), 2); + assert_eq!(cache.uniform_cursor, 262); + assert!(cache.cached_bind_group_count() >= 2); + eng.queue().submit(Some(enc.finish())); + + let rgba_first = eng.readback_rgba(&dst_first).expect("readback first"); + let rgba_last = eng.readback_rgba(&dst_last).expect("readback last"); + assert!( + (rgba_first[0] as i32 - 51).abs() <= 1 && (rgba_first[1] as i32 - 204).abs() <= 1, + "slot 0 must not be overwritten by chunk 1 writes: got {:?}", + &rgba_first[..4] + ); + assert!( + (rgba_last[0] as i32 - 153).abs() <= 1 && (rgba_last[1] as i32 - 102).abs() <= 1, + "chunk 1 write must produce exact params: got {:?}", + &rgba_last[..4] + ); + + // Trimming chunks resets cursor and invalidates bind groups referencing trimmed buffers. + cache.trim_uniform_chunks(1); + assert_eq!(cache.uniform_chunks.len(), 1); + assert_eq!(cache.uniform_cursor, 0); + assert_eq!(cache.cached_bind_group_count(), 0); + } + + #[test] + fn custom_shader_cache_evicts_lru_pipelines_past_capacity() { + let eng = Engine::new_headless().expect("gpu"); + let mut cache = CustomShaderCache::new(); + let fmt = wgpu::TextureFormat::Rgba8Unorm; + let make_prog = |i: usize| CustomProgram { + red: format!("{i}.0 / 255.0"), + green: "0".to_owned(), + blue: "0".to_owned(), + alpha: "1".to_owned(), + ..Default::default() + }; + + for i in 0..MAX_CUSTOM_PIPELINES { + let p = make_prog(i); + assert!(cache.ensure_compiled(eng.device(), &p, fmt)); + } + assert_eq!(cache.cached_pipeline_count(), MAX_CUSTOM_PIPELINES); + + // Touch entry 0 so entry 1 becomes the least recently used pipeline. + let p0 = make_prog(0); + let p1 = make_prog(1); + assert!(cache.ensure_compiled(eng.device(), &p0, fmt)); + + let p_new = make_prog(MAX_CUSTOM_PIPELINES); + assert!(cache.ensure_compiled(eng.device(), &p_new, fmt)); + assert_eq!(cache.cached_pipeline_count(), MAX_CUSTOM_PIPELINES); + assert!(cache.pipelines.contains_key(&(fmt, p0.normalized()))); + assert!(!cache.pipelines.contains_key(&(fmt, p1.normalized()))); + assert!(cache.pipelines.contains_key(&(fmt, p_new.normalized()))); + } } diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 18b09f754ab197c68d84899c9a2e07829045a46c..604c626ce8ae8efea47728747597c6dc53295f9c 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -326,6 +326,7 @@ impl Engine { self.sync_node_cache_budget(); self.cache.bust_all(); self.custom_shaders.clear_bind_group_cache(); + self.custom_shaders.trim_uniform_chunks(2); self.clear_bind_group_caches(); self.trim_uniform_chunks(); if let Some(of) = self.optflow.get() { @@ -348,6 +349,7 @@ impl Engine { self.sync_node_cache_budget(); self.cache.bust_all(); self.custom_shaders.clear_bind_group_cache(); + self.custom_shaders.trim_uniform_chunks(2); self.clear_bind_group_caches(); self.trim_uniform_chunks(); if let Some(of) = self.optflow.get() { diff --git a/crates/engine/src/eval/output_cache.rs b/crates/engine/src/eval/output_cache.rs index d6e2bd39d928177edf125f0c6654355816603d3d..883bbca8e8ffba2fec2ba8a90541982b196f1210 100644 --- a/crates/engine/src/eval/output_cache.rs +++ b/crates/engine/src/eval/output_cache.rs @@ -145,12 +145,15 @@ impl Engine { } /// Total resident GPU VRAM bytes across `NodeCache` (live + pooled), unshared `output_cache` - /// entries, and pooled 3D shadow render targets. + /// entries, 3D shadow/depth/mesh buffers, and optical flow scratch/cache buffers. pub fn vram_bytes(&self) -> u64 { self.cache .total_vram_bytes() .saturating_add(self.output_cache.unshared_bytes()) .saturating_add(self.scene3d.shadow_vram_bytes()) + .saturating_add(self.scene3d.depth_vram_bytes()) + .saturating_add(self.scene3d.mesh_vram_bytes()) + .saturating_add(self.optflow.get().map_or(0, |of| of.vram_bytes())) } pub fn vram_mb(&self) -> f64 { @@ -231,4 +234,36 @@ mod tests { drop(tex); assert_eq!(cache.unshared_bytes(), tex_bytes + other_bytes); } + + #[test] + fn vram_bytes_includes_optflow_and_bust_caches_clears_scratch() { + let mut eng = Engine::new_headless().expect("gpu"); + assert_eq!(eng.vram_bytes(), 0); + + let a = eng.alloc_tex([64, 64], BitDepth::Int8, 10); + let b = eng.alloc_tex([64, 64], BitDepth::Int8, 11); + let optflow = eng + .optflow + .get_or_init(|| crate::optflow::OpticalFlowPipelines::new(&eng.device)); + let mut enc = eng.device.create_command_encoder(&Default::default()); + let _out = optflow.interpolate_flow( + &eng.device, + &eng.queue, + &mut enc, + &a, + &b, + 0.5, + wgpu::TextureFormat::Rgba8Unorm, + ); + eng.queue.submit(Some(enc.finish())); + + let optflow_bytes = eng.optflow.get().unwrap().vram_bytes(); + assert!(optflow_bytes > 0); + assert_eq!(eng.vram_bytes(), optflow_bytes); + + eng.bust_gpu_cache(); + let after_bust = eng.optflow.get().unwrap().vram_bytes(); + assert!(after_bust < optflow_bytes); + assert_eq!(eng.vram_bytes(), after_bust); + } } diff --git a/crates/engine/src/optflow.rs b/crates/engine/src/optflow.rs index 4e753e1a3c16d4fcfe0fcd8b56a5472459be066b..ef783ff7cea74298ad0942eb7eb6877034814e29 100644 --- a/crates/engine/src/optflow.rs +++ b/crates/engine/src/optflow.rs @@ -455,8 +455,6 @@ const FLOW_CACHE_CAP: usize = 4; /// Uniform slots allocated per ring chunk (`256 * 256 B = 64 KiB` at 256-byte alignment). const UNIFORM_SLOTS_PER_CHUNK: u32 = 256; -/// Maximum uniform ring chunks before wrapping (`32 * 256 = 8,192` slots, `<= 2 MiB`). -const MAX_UNIFORM_CHUNKS: u32 = 32; /// Maximum number of idle `Rgba16Float` pyramid textures retained in [`PyramidScratchPool`]. const PYRAMID_POOL_MAX_TEXTURES: usize = 32; @@ -485,14 +483,15 @@ impl UniformRing { } /// Writes `uniform` into the next aligned dynamic-offset slot and returns `(chunk_buffer, offset)`. + /// + /// Lazily appends chunks without wrapping mid-encoder; callers reset the cursor after submit. fn alloc_slot( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, uniform: &OptFlowUniform, ) -> (wgpu::Buffer, u32) { - let max_slots = UNIFORM_SLOTS_PER_CHUNK * MAX_UNIFORM_CHUNKS; - let slot_global = self.cursor % max_slots; + let slot_global = self.cursor; let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize; let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK; while chunk_idx >= self.chunks.len() { @@ -511,13 +510,24 @@ impl UniformRing { u64::from(offset), bytemuck::bytes_of(uniform), ); - self.cursor = (slot_global + 1) % max_slots; + self.cursor = slot_global + 1; (self.chunks[chunk_idx].clone(), offset) } fn reset_cursor(&mut self) { self.cursor = 0; } + + fn trim_uniform_chunks(&mut self, keep: usize) { + self.cursor = 0; + if self.chunks.len() > keep { + self.chunks.truncate(keep); + } + } + + fn vram_bytes(&self) -> u64 { + self.chunks.iter().map(wgpu::Buffer::size).sum() + } } struct PooledF16Tex { @@ -699,11 +709,28 @@ impl OpticalFlowPipelines { self.uniform_ring.lock().unwrap().reset_cursor(); } - /// Clears cached flow fields and pooled intermediate pyramid textures, and resets the uniform cursor. + /// Clears cached flow fields and pooled intermediate pyramid textures, and trims uniform ring chunks. pub fn clear_scratch(&self) { self.flow_cache.lock().unwrap().clear(); self.pyramid_pool.lock().unwrap().clear(); - self.uniform_ring.lock().unwrap().reset_cursor(); + self.uniform_ring.lock().unwrap().trim_uniform_chunks(2); + } + + /// Total resident GPU VRAM bytes currently held across pooled pyramid textures, + /// cached flow-field textures, and dynamic uniform ring buffers. + pub fn vram_bytes(&self) -> u64 { + let pool_bytes = self.pyramid_pool.lock().unwrap().total_bytes; + let flow_bytes: u64 = self + .flow_cache + .lock() + .unwrap() + .iter() + .map(|(_, _, _, size)| u64::from(size[0].max(1)) * u64::from(size[1].max(1)) * 8) + .sum(); + let ring_bytes = self.uniform_ring.lock().unwrap().vram_bytes(); + pool_bytes + .saturating_add(flow_bytes) + .saturating_add(ring_bytes) } fn ensure_target_pipeline( @@ -853,51 +880,59 @@ impl OpticalFlowPipelines { let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)]; let s1 = half_size(s0); - let flow_key = (frame_a.content_hash, frame_b.content_hash, s0); - let cached = { - let mut cache = self.flow_cache.lock().unwrap(); - cache.iter().position(|(k, _, _, _)| *k == flow_key).map(|i| { - let entry = cache.remove(i); - let view = entry.1.clone(); - cache.push(entry); - view - }) - }; - let flow1_view = match cached { - Some(view) => view, - None => { - // Evict the LRU flow field before computing the new one so its backing - // texture can be immediately reused by PyramidScratchPool. - let evicted_before = { - let mut cache = self.flow_cache.lock().unwrap(); - if cache.len() >= FLOW_CACHE_CAP { - Some(cache.remove(0)) - } else { - None + let unkeyed = frame_a.content_hash == 0 || frame_b.content_hash == 0; + let (flow1_view, uncached_flow): (wgpu::TextureView, Option) = if unkeyed { + let (flow1_tex, flow1_view) = + self.compute_flow_field(device, queue, enc, frame_a, frame_b); + (flow1_view, Some(flow1_tex)) + } else { + let flow_key = (frame_a.content_hash, frame_b.content_hash, s0); + let cached = { + let mut cache = self.flow_cache.lock().unwrap(); + cache.iter().position(|(k, _, _, _)| *k == flow_key).map(|i| { + let entry = cache.remove(i); + let view = entry.1.clone(); + cache.push(entry); + view + }) + }; + let flow1_view = match cached { + Some(view) => view, + None => { + // Evict the LRU flow field before computing the new one so its backing + // texture can be immediately reused by PyramidScratchPool. + let evicted_before = { + let mut cache = self.flow_cache.lock().unwrap(); + if cache.len() >= FLOW_CACHE_CAP { + Some(cache.remove(0)) + } else { + None + } + }; + if let Some((_, old_view, old_tex, old_size)) = evicted_before { + self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size); } - }; - if let Some((_, old_view, old_tex, old_size)) = evicted_before { - self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size); - } - let (flow1_tex, flow1_view) = - self.compute_flow_field(device, queue, enc, frame_a, frame_b); + let (flow1_tex, flow1_view) = + self.compute_flow_field(device, queue, enc, frame_a, frame_b); - let evicted_after = { - let mut cache = self.flow_cache.lock().unwrap(); - let extra = if cache.len() >= FLOW_CACHE_CAP { - Some(cache.remove(0)) - } else { - None + let evicted_after = { + let mut cache = self.flow_cache.lock().unwrap(); + let extra = if cache.len() >= FLOW_CACHE_CAP { + Some(cache.remove(0)) + } else { + None + }; + cache.push((flow_key, flow1_view.clone(), flow1_tex, s1)); + extra }; - cache.push((flow_key, flow1_view.clone(), flow1_tex, s1)); - extra - }; - if let Some((_, old_view, old_tex, old_size)) = evicted_after { - self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size); + if let Some((_, old_view, old_tex, old_size)) = evicted_after { + self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size); + } + flow1_view } - flow1_view - } + }; + (flow1_view, None) }; // Full-resolution bidirectional occlusion-aware warp & blend @@ -907,12 +942,17 @@ impl OpticalFlowPipelines { alpha.clamp(0.0, 1.0), 0.0, ]; - let guard = self.warp_pipelines.read().unwrap(); - let pipe = guard.get(&target_format).unwrap(); - self.run_pass( - device, queue, enc, pipe, "optflow-warp", - &frame_a.view, &frame_b.view, &flow1_view, &dst.view, s0, scale_1_to_0, - ); + { + let guard = self.warp_pipelines.read().unwrap(); + let pipe = guard.get(&target_format).unwrap(); + self.run_pass( + device, queue, enc, pipe, "optflow-warp", + &frame_a.view, &frame_b.view, &flow1_view, &dst.view, s0, scale_1_to_0, + ); + } + if let Some(flow1_tex) = uncached_flow { + self.pyramid_pool.lock().unwrap().release(flow1_tex, flow1_view, s1); + } dst } @@ -1759,6 +1799,124 @@ mod tests { assert_eq!(flow_last_px, readback_bytes(&device, &queue, &ref_last, 4)); } + #[test] + fn test_unkeyed_content_hash_zero_bypasses_flow_cache_and_releases_flow1() { + let (device, queue) = create_headless_device(); + let pipelines = OpticalFlowPipelines::new(&device); + let (w, h) = (96u32, 64u32); + let fmt = wgpu::TextureFormat::Rgba8Unorm; + + // Pair 1: both content_hash == 0 (unkeyed scratch textures). + let a1 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 8, 8), 0); + let b1 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 24, 8), 0); + let mut enc1 = device.create_command_encoder(&Default::default()); + let _out1 = pipelines.interpolate_flow(&device, &queue, &mut enc1, &a1, &b1, 0.5, fmt); + queue.submit(Some(enc1.finish())); + assert!( + pipelines.flow_cache.lock().unwrap().is_empty(), + "content_hash == 0 must bypass flow_cache" + ); + // All 14 textures (13 intermediate + temporary flow1) must be returned to pyramid_pool. + assert_eq!(pipelines.pyramid_pool.lock().unwrap().entries.len(), 14); + + // Pair 2: completely different box positions, also with content_hash == 0 (or one side 0). + let a2 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 40, 12), 0); + let b2 = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 40, 28), 99); + let mut enc2 = device.create_command_encoder(&Default::default()); + let out2 = pipelines.interpolate_flow(&device, &queue, &mut enc2, &a2, &b2, 0.5, fmt); + queue.submit(Some(enc2.finish())); + assert!(pipelines.flow_cache.lock().unwrap().is_empty()); + + let fresh = OpticalFlowPipelines::new(&device); + let mut fresh_enc = device.create_command_encoder(&Default::default()); + let fresh_out = fresh.interpolate_flow(&device, &queue, &mut fresh_enc, &a2, &b2, 0.5, fmt); + queue.submit(Some(fresh_enc.finish())); + assert_eq!( + readback_bytes(&device, &queue, &out2, 4), + readback_bytes(&device, &queue, &fresh_out, 4), + "unkeyed flow computation must not alias any stale cached flow field" + ); + } + + #[test] + fn test_optflow_vram_bytes_tracks_memory_and_clears() { + let (device, queue) = create_headless_device(); + let pipelines = OpticalFlowPipelines::new(&device); + assert_eq!(pipelines.vram_bytes(), 0); + + let (w, h) = (128u32, 64u32); + let a = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 16, 16), 11); + let b = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 32, 16), 12); + let mut enc = device.create_command_encoder(&Default::default()); + let _out = pipelines.interpolate_flow( + &device, + &queue, + &mut enc, + &a, + &b, + 0.5, + wgpu::TextureFormat::Rgba8Unorm, + ); + queue.submit(Some(enc.finish())); + + let pool_bytes = pipelines.pyramid_pool.lock().unwrap().total_bytes; + let flow_bytes = u64::from(w / 2) * u64::from(h / 2) * 8; + let ring_bytes = pipelines.uniform_ring.lock().unwrap().vram_bytes(); + assert!(pool_bytes > 0); + assert!(ring_bytes > 0); + assert_eq!(pipelines.vram_bytes(), pool_bytes + flow_bytes + ring_bytes); + + // Grow uniform ring beyond 2 chunks so clear_scratch() exercises trim_uniform_chunks(2). + { + let mut ring = pipelines.uniform_ring.lock().unwrap(); + let dummy_u = OptFlowUniform { + dst_size: [1.0; 4], + params: [0.0; 4], + }; + for _ in 0..(UNIFORM_SLOTS_PER_CHUNK * 3) { + ring.alloc_slot(&device, &queue, &dummy_u); + } + assert!(ring.chunks.len() >= 3); + } + assert!(pipelines.vram_bytes() > pool_bytes + flow_bytes + ring_bytes); + + pipelines.clear_scratch(); + assert_eq!(pipelines.pyramid_pool.lock().unwrap().total_bytes, 0); + assert!(pipelines.flow_cache.lock().unwrap().is_empty()); + assert_eq!(pipelines.uniform_ring.lock().unwrap().chunks.len(), 2); + let retained_ring = pipelines.uniform_ring.lock().unwrap().vram_bytes(); + assert_eq!(pipelines.vram_bytes(), retained_ring); + + pipelines.uniform_ring.lock().unwrap().trim_uniform_chunks(0); + assert_eq!(pipelines.vram_bytes(), 0); + } + + #[test] + fn test_optflow_uniform_ring_grows_dynamically_past_8192_slots_without_wrapping() { + let (device, queue) = create_headless_device(); + let mut ring = UniformRing::new(&device); + let dummy_u = OptFlowUniform { + dst_size: [64.0, 64.0, 1.0 / 64.0, 1.0 / 64.0], + params: [1.0, 1.0, 0.5, 0.0], + }; + + // 32 * 256 = 8,192 was the old modulo cap; allocate 8,197 slots without resetting cursor. + let total = 32 * UNIFORM_SLOTS_PER_CHUNK + 5; + let mut last = None; + for _ in 0..total { + last = Some(ring.alloc_slot(&device, &queue, &dummy_u)); + } + let (last_buf, last_offset) = last.expect("allocated slots"); + assert_eq!(ring.chunks.len(), 33, "must allocate chunk 32 instead of wrapping to 0"); + assert_eq!(ring.cursor, total); + assert_eq!(last_buf, ring.chunks[32]); + assert_eq!(last_offset, 4 * ring.stride); + + ring.trim_uniform_chunks(2); + assert_eq!(ring.chunks.len(), 2); + assert_eq!(ring.cursor, 0); + } + #[test] #[ignore] fn bench_optflow_10_frames_720p_1080p() {