diff --git a/crates/engine/src/optflow.rs b/crates/engine/src/optflow.rs index 39ddda5b3bda86c5405670f83f98b063f50e348f..4e753e1a3c16d4fcfe0fcd8b56a5472459be066b 100644 --- a/crates/engine/src/optflow.rs +++ b/crates/engine/src/optflow.rs @@ -4,9 +4,10 @@ use crate::cache::CachedTexture; use bytemuck::{Pod, Zeroable}; use model::BitDepth; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; +use std::num::NonZeroU64; use std::sync::{Mutex, RwLock}; #[repr(C)] @@ -452,9 +453,137 @@ fn fs_warp_flow(in: VsOut) -> @location(0) vec4 { /// Cached flow fields kept per `OpticalFlowPipelines`; one entry is a single frame pair. 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; +/// Maximum total VRAM retained in [`PyramidScratchPool`] (256 MiB). +const PYRAMID_POOL_MAX_BYTES: u64 = 256 * 1024 * 1024; + /// `(content_hash_a, content_hash_b, full-res size)`. type FlowKey = (u64, u64, [u32; 2]); +struct UniformRing { + stride: u32, + chunks: Vec, + cursor: u32, +} + +impl UniformRing { + fn new(device: &wgpu::Device) -> Self { + 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; + Self { + stride, + chunks: Vec::new(), + cursor: 0, + } + } + + /// Writes `uniform` into the next aligned dynamic-offset slot and returns `(chunk_buffer, offset)`. + 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 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() { + let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.stride); + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("optflow-uniform-ring"), + size, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.chunks.push(buf); + } + let offset = slot_in_chunk * self.stride; + queue.write_buffer( + &self.chunks[chunk_idx], + u64::from(offset), + bytemuck::bytes_of(uniform), + ); + self.cursor = (slot_global + 1) % max_slots; + (self.chunks[chunk_idx].clone(), offset) + } + + fn reset_cursor(&mut self) { + self.cursor = 0; + } +} + +struct PooledF16Tex { + size: [u32; 2], + bytes: u64, + tex: wgpu::Texture, + view: wgpu::TextureView, +} + +/// Bounded LRU pool of reusable `Rgba16Float` pyramid/flow scratch textures keyed by `[w, h]`. +#[derive(Default)] +struct PyramidScratchPool { + entries: VecDeque, + total_bytes: u64, + alloc_count: u64, + reuse_count: u64, +} + +impl PyramidScratchPool { + fn acquire( + &mut self, + device: &wgpu::Device, + size: [u32; 2], + label: &str, + ) -> (wgpu::Texture, wgpu::TextureView) { + let size = [size[0].max(1), size[1].max(1)]; + if let Some(idx) = self.entries.iter().rposition(|e| e.size == size) { + let entry = self.entries.remove(idx).expect("valid pool index"); + self.total_bytes -= entry.bytes; + self.reuse_count += 1; + return (entry.tex, entry.view); + } + self.alloc_count += 1; + alloc_f16_tex(device, size, label) + } + + fn release(&mut self, tex: wgpu::Texture, view: wgpu::TextureView, size: [u32; 2]) { + let size = [size[0].max(1), size[1].max(1)]; + let bytes = u64::from(size[0]) * u64::from(size[1]) * 8; + if bytes > PYRAMID_POOL_MAX_BYTES { + return; + } + while self.entries.len() >= PYRAMID_POOL_MAX_TEXTURES + || self.total_bytes + bytes > PYRAMID_POOL_MAX_BYTES + { + if let Some(evicted) = self.entries.pop_front() { + self.total_bytes -= evicted.bytes; + } else { + break; + } + } + self.total_bytes += bytes; + self.entries.push_back(PooledF16Tex { + size, + bytes, + tex, + view, + }); + } + + fn clear(&mut self) { + self.entries.clear(); + self.total_bytes = 0; + } +} + /// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation. pub struct OpticalFlowPipelines { shader: wgpu::ShaderModule, @@ -468,8 +597,10 @@ pub struct OpticalFlowPipelines { flow_smooth: wgpu::RenderPipeline, blend_pipelines: RwLock>, warp_pipelines: RwLock>, - /// Half-resolution flow fields, least recently used first. - flow_cache: Mutex>, + /// Half-resolution flow fields, least recently used first: `(key, view, texture, size)`. + flow_cache: Mutex>, + uniform_ring: Mutex, + pyramid_pool: Mutex, } impl OpticalFlowPipelines { @@ -490,6 +621,7 @@ impl OpticalFlowPipelines { count: None, }; + let uniform_size = std::mem::size_of::() as u64; let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("optflow-bgl"), entries: &[ @@ -507,8 +639,8 @@ impl OpticalFlowPipelines { visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, + has_dynamic_offset: true, + min_binding_size: NonZeroU64::new(uniform_size), }, count: None, }, @@ -556,9 +688,24 @@ impl OpticalFlowPipelines { blend_pipelines: RwLock::new(HashMap::new()), warp_pipelines: RwLock::new(HashMap::new()), flow_cache: Mutex::new(Vec::new()), + uniform_ring: Mutex::new(UniformRing::new(device)), + pyramid_pool: Mutex::new(PyramidScratchPool::default()), } } + /// Resets the dynamic uniform ring cursor back to slot `0`. + /// Call only after all prior encoded passes on this pipeline have been submitted. + pub fn reset_uniform_cursor(&self) { + self.uniform_ring.lock().unwrap().reset_cursor(); + } + + /// Clears cached flow fields and pooled intermediate pyramid textures, and resets the uniform cursor. + pub fn clear_scratch(&self) { + self.flow_cache.lock().unwrap().clear(); + self.pyramid_pool.lock().unwrap().clear(); + self.uniform_ring.lock().unwrap().reset_cursor(); + } + fn ensure_target_pipeline( &self, device: &wgpu::Device, @@ -594,13 +741,10 @@ impl OpticalFlowPipelines { dst_size: [w, h, 1.0 / w, 1.0 / h], params, }; - let ubuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("optflow-uniform"), - size: std::mem::size_of::() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uniform)); + let (ubuf, dynamic_offset) = { + let mut ring = self.uniform_ring.lock().unwrap(); + ring.alloc_slot(device, queue, &uniform) + }; let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(label), @@ -624,7 +768,11 @@ impl OpticalFlowPipelines { }, wgpu::BindGroupEntry { binding: 4, - resource: ubuf.as_entire_binding(), + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &ubuf, + offset: 0, + size: NonZeroU64::new(std::mem::size_of::() as u64), + }), }, ], }); @@ -646,7 +794,7 @@ impl OpticalFlowPipelines { multiview_mask: None, }); rp.set_pipeline(pipeline); - rp.set_bind_group(0, &bg, &[]); + rp.set_bind_group(0, &bg, &[dynamic_offset]); rp.draw(0..3, 0..1); } @@ -708,22 +856,49 @@ impl OpticalFlowPipelines { 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| { + 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 = cached.unwrap_or_else(|| { - let view = self.compute_flow_field(device, queue, enc, frame_a, frame_b); - let mut cache = self.flow_cache.lock().unwrap(); - if cache.len() >= FLOW_CACHE_CAP { - cache.remove(0); + 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); + } + + 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 + }; + 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); + } + flow1_view } - cache.push((flow_key, view.clone())); - view - }); + }; // Full-resolution bidirectional occlusion-aware warp & blend let scale_1_to_0 = [ @@ -742,7 +917,7 @@ impl OpticalFlowPipelines { } /// Encodes the 4-level (full, 1/2, 1/4, 1/8) coarse-to-fine flow estimate and returns the - /// half-resolution flow field. + /// half-resolution flow field `(texture, view)`. fn compute_flow_field( &self, device: &wgpu::Device, @@ -750,15 +925,50 @@ impl OpticalFlowPipelines { enc: &mut wgpu::CommandEncoder, frame_a: &CachedTexture, frame_b: &CachedTexture, - ) -> wgpu::TextureView { + ) -> (wgpu::Texture, wgpu::TextureView) { let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)]; let s1 = half_size(s0); let s2 = half_size(s1); let s3 = half_size(s2); + // Acquire all 14 distinct pyramid/feature/flow textures for this call so no texture is + // aliased within the unsubmitted CommandEncoder. + let ( + (fa0_tex, fa0_view), + (fb0_tex, fb0_view), + (fa1_tex, fa1_view), + (fb1_tex, fb1_view), + (fa2_tex, fa2_view), + (fb2_tex, fb2_view), + (fa3_tex, fa3_view), + (fb3_tex, fb3_view), + (flow3_raw_tex, flow3_raw_view), + (flow3_tex, flow3_view), + (flow2_raw_tex, flow2_raw_view), + (flow2_tex, flow2_view), + (flow1_raw_tex, flow1_raw_view), + (flow1_tex, flow1_view), + ) = { + let mut pool = self.pyramid_pool.lock().unwrap(); + ( + pool.acquire(device, s0, "optflow-fa0"), + pool.acquire(device, s0, "optflow-fb0"), + pool.acquire(device, s1, "optflow-fa1"), + pool.acquire(device, s1, "optflow-fb1"), + pool.acquire(device, s2, "optflow-fa2"), + pool.acquire(device, s2, "optflow-fb2"), + pool.acquire(device, s3, "optflow-fa3"), + pool.acquire(device, s3, "optflow-fb3"), + pool.acquire(device, s3, "optflow-f3-raw"), + pool.acquire(device, s3, "optflow-f3"), + pool.acquire(device, s2, "optflow-f2-raw"), + pool.acquire(device, s2, "optflow-f2"), + pool.acquire(device, s1, "optflow-f1-raw"), + pool.acquire(device, s1, "optflow-f1"), + ) + }; + // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B - let (fa0_tex, fa0_view) = alloc_f16_tex(device, s0, "optflow-fa0"); - let (fb0_tex, fb0_view) = alloc_f16_tex(device, s0, "optflow-fb0"); self.run_pass( device, queue, enc, &self.extract_features, "optflow-extract-a", &frame_a.view, &frame_a.view, &frame_a.view, &fa0_view, s0, [0.0; 4], @@ -768,8 +978,6 @@ impl OpticalFlowPipelines { &frame_b.view, &frame_b.view, &frame_b.view, &fb0_view, s0, [0.0; 4], ); - let (fa1_tex, fa1_view) = alloc_f16_tex(device, s1, "optflow-fa1"); - let (fb1_tex, fb1_view) = alloc_f16_tex(device, s1, "optflow-fb1"); self.run_pass( device, queue, enc, &self.downsample, "optflow-down-a1", &fa0_view, &fa0_view, &fa0_view, &fa1_view, s1, [0.0; 4], @@ -779,8 +987,6 @@ impl OpticalFlowPipelines { &fb0_view, &fb0_view, &fb0_view, &fb1_view, s1, [0.0; 4], ); - let (fa2_tex, fa2_view) = alloc_f16_tex(device, s2, "optflow-fa2"); - let (fb2_tex, fb2_view) = alloc_f16_tex(device, s2, "optflow-fb2"); self.run_pass( device, queue, enc, &self.downsample, "optflow-down-a2", &fa1_view, &fa1_view, &fa1_view, &fa2_view, s2, [0.0; 4], @@ -790,8 +996,6 @@ impl OpticalFlowPipelines { &fb1_view, &fb1_view, &fb1_view, &fb2_view, s2, [0.0; 4], ); - let (fa3_tex, fa3_view) = alloc_f16_tex(device, s3, "optflow-fa3"); - let (fb3_tex, fb3_view) = alloc_f16_tex(device, s3, "optflow-fb3"); self.run_pass( device, queue, enc, &self.downsample, "optflow-down-a3", &fa2_view, &fa2_view, &fa2_view, &fa3_view, s3, [0.0; 4], @@ -803,8 +1007,6 @@ impl OpticalFlowPipelines { // 2. Coarse-to-fine bidirectional flow estimation // Level 3 (1/8 res): exhaustive [-4..4] search + parabolic subpixel + bilateral smooth - let (flow3_raw_tex, flow3_raw_view) = alloc_f16_tex(device, s3, "optflow-f3-raw"); - let (flow3_tex, flow3_view) = alloc_f16_tex(device, s3, "optflow-f3"); self.run_pass( device, queue, enc, &self.flow_coarse, "optflow-coarse-l3", &fa3_view, &fb3_view, &fa3_view, &flow3_raw_view, s3, [0.0; 4], @@ -816,8 +1018,6 @@ impl OpticalFlowPipelines { // Level 2 (1/4 res): upsample + [-2..2] refine + LK + bilateral smooth let scale_3_to_2 = [s2[0] as f32 / s3[0] as f32, s2[1] as f32 / s3[1] as f32, 0.0, 0.0]; - let (flow2_raw_tex, flow2_raw_view) = alloc_f16_tex(device, s2, "optflow-f2-raw"); - let (flow2_tex, flow2_view) = alloc_f16_tex(device, s2, "optflow-f2"); self.run_pass( device, queue, enc, &self.flow_refine, "optflow-refine-l2", &fa2_view, &fb2_view, &flow3_view, &flow2_raw_view, s2, scale_3_to_2, @@ -829,8 +1029,6 @@ impl OpticalFlowPipelines { // Level 1 (1/2 res): upsample + [-2..2] refine + LK + bilateral smooth let scale_2_to_1 = [s1[0] as f32 / s2[0] as f32, s1[1] as f32 / s2[1] as f32, 0.0, 0.0]; - let (flow1_raw_tex, flow1_raw_view) = alloc_f16_tex(device, s1, "optflow-f1-raw"); - let (flow1_tex, flow1_view) = alloc_f16_tex(device, s1, "optflow-f1"); self.run_pass( device, queue, enc, &self.flow_refine, "optflow-refine-l1", &fa1_view, &fb1_view, &flow2_view, &flow1_raw_view, s1, scale_2_to_1, @@ -840,13 +1038,27 @@ impl OpticalFlowPipelines { &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4], ); - // Keep temporary textures alive until all passes are encoded into `enc`. - drop(( - fa0_tex, fb0_tex, fa1_tex, fb1_tex, fa2_tex, fb2_tex, fa3_tex, fb3_tex, - flow3_raw_tex, flow3_tex, flow2_raw_tex, flow2_tex, flow1_raw_tex, flow1_tex, - )); + // Return intermediate scratch textures to the pool now that all passes reading/writing them + // are encoded in strict FIFO order on `enc`. Subsequent calls on the same or future + // encoders execute strictly after these passes. + { + let mut pool = self.pyramid_pool.lock().unwrap(); + pool.release(fa0_tex, fa0_view, s0); + pool.release(fb0_tex, fb0_view, s0); + pool.release(fa1_tex, fa1_view, s1); + pool.release(fb1_tex, fb1_view, s1); + pool.release(fa2_tex, fa2_view, s2); + pool.release(fb2_tex, fb2_view, s2); + pool.release(fa3_tex, fa3_view, s3); + pool.release(fb3_tex, fb3_view, s3); + pool.release(flow3_raw_tex, flow3_raw_view, s3); + pool.release(flow3_tex, flow3_view, s3); + pool.release(flow2_raw_tex, flow2_raw_view, s2); + pool.release(flow2_tex, flow2_view, s2); + pool.release(flow1_raw_tex, flow1_raw_view, s1); + } - flow1_view + (flow1_tex, flow1_view) } } @@ -1329,4 +1541,283 @@ mod tests { let err = mae_rgba8(&f32_as_u8, &img_a); assert!(err < 0.5, "expected alpha=0 blend MAE ({err:.3}) < 0.5"); } + + #[test] + fn test_optflow_pyramid_pool_reuses_textures_and_matches_unpooled_bit_for_bit() { + let (device, queue) = create_headless_device(); + let pooled = OpticalFlowPipelines::new(&device); + + let (w, h) = (192u32, 108u32); + let fmt = wgpu::TextureFormat::Rgba8Unorm; + let frames: Vec = (0..9) + .map(|i| { + let img = render_box_scene(w, h, 24 + i * 10, 20 + i * 4); + upload_rgba8(&device, &queue, w, h, &img, 500 + i as u64) + }) + .collect(); + + // 1. Direct compute_flow_field reuse: alloc_count stays flat at 14 after frame 1. + for i in 0..4 { + let mut enc = device.create_command_encoder(&Default::default()); + let (f_tex, f_view) = + pooled.compute_flow_field(&device, &queue, &mut enc, &frames[i], &frames[i + 1]); + queue.submit(Some(enc.finish())); + pooled.pyramid_pool.lock().unwrap().release(f_tex, f_view, half_size([w, h])); + assert_eq!( + pooled.pyramid_pool.lock().unwrap().alloc_count, + 14, + "direct compute_flow_field alloc_count should remain 14 on pair {i}" + ); + } + + // 2. Full interpolate_flow across 8 distinct frame pairs: + // - Intermediate pyramid/feature textures reuse from frame 1 (alloc_count only grows by + // 1 per flow_cache slot up to FLOW_CACHE_CAP, then stays completely flat). + // - Output matches fresh unpooled OpticalFlowPipelines bit-for-bit. + pooled.clear_scratch(); + pooled.pyramid_pool.lock().unwrap().alloc_count = 0; + pooled.pyramid_pool.lock().unwrap().reuse_count = 0; + + let mut stable_allocs = 0u64; + for i in 0..8 { + let mut enc = device.create_command_encoder(&Default::default()); + let out_pooled = pooled.interpolate_flow( + &device, + &queue, + &mut enc, + &frames[i], + &frames[i + 1], + 0.5, + fmt, + ); + queue.submit(Some(enc.finish())); + let pooled_bytes = readback_bytes(&device, &queue, &out_pooled, 4); + + let allocs_now = pooled.pyramid_pool.lock().unwrap().alloc_count; + if i < FLOW_CACHE_CAP { + assert_eq!(allocs_now, 14 + i as u64); + stable_allocs = allocs_now; + } else { + assert_eq!( + allocs_now, stable_allocs, + "alloc_count must stay flat once flow_cache reaches capacity (pair {i})" + ); + } + + // Fresh unpooled instance on the exact same pair + let fresh = OpticalFlowPipelines::new(&device); + let mut fresh_enc = device.create_command_encoder(&Default::default()); + let out_fresh = fresh.interpolate_flow( + &device, + &queue, + &mut fresh_enc, + &frames[i], + &frames[i + 1], + 0.5, + fmt, + ); + queue.submit(Some(fresh_enc.finish())); + let fresh_bytes = readback_bytes(&device, &queue, &out_fresh, 4); + + assert_eq!( + pooled_bytes, fresh_bytes, + "pooled output must be bit-for-bit identical to unpooled reference (pair {i})" + ); + } + assert!( + pooled.pyramid_pool.lock().unwrap().reuse_count >= 7 * 13, + "expected substantial texture reuse across 8 distinct frame pairs" + ); + } + + #[test] + fn test_optflow_uniform_ring_multiple_calls_in_single_encoder() { + let (device, queue) = create_headless_device(); + let pipelines = OpticalFlowPipelines::new(&device); + + let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); + let stride = pipelines.uniform_ring.lock().unwrap().stride; + assert_eq!(stride % min_align, 0); + + let (w, h) = (64u32, 64u32); + let solid = |r: u8, g: u8, b: u8| -> Vec { + [r, g, b, 255].repeat((w * h) as usize) + }; + let tex_black = upload_rgba8(&device, &queue, w, h, &solid(0, 0, 0), 701); + let tex_white = upload_rgba8(&device, &queue, w, h, &solid(255, 255, 255), 702); + let box_a = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 8, 8), 703); + let box_b = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 16, 12), 704); + + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("optflow-ring-single-enc"), + }); + + // Mix blend_frames and interpolate_flow inside a single CommandEncoder, crossing + // UNIFORM_SLOTS_PER_CHUNK (256) so chunk 0 and chunk 1 are both exercised before submit. + let blend_first = pipelines.blend_frames( + &device, + &queue, + &mut enc, + &tex_black, + &tex_white, + 0.0, + wgpu::TextureFormat::Rgba8Unorm, + ); + let flow_first = pipelines.interpolate_flow( + &device, + &queue, + &mut enc, + &box_a, + &box_b, + 0.25, + wgpu::TextureFormat::Rgba8Unorm, + ); + + let mut mid_blends = Vec::new(); + for i in 0..270 { + let alpha = if i == 128 { 0.5 } else { 0.8 }; + let out = pipelines.blend_frames( + &device, + &queue, + &mut enc, + &tex_black, + &tex_white, + alpha, + wgpu::TextureFormat::Rgba8Unorm, + ); + if i == 128 { + mid_blends.push(out); + } + } + + let flow_last = pipelines.interpolate_flow( + &device, + &queue, + &mut enc, + &box_a, + &box_b, + 0.75, + wgpu::TextureFormat::Rgba8Unorm, + ); + let blend_last = pipelines.blend_frames( + &device, + &queue, + &mut enc, + &tex_black, + &tex_white, + 1.0, + wgpu::TextureFormat::Rgba8Unorm, + ); + queue.submit(Some(enc.finish())); + + assert!( + pipelines.uniform_ring.lock().unwrap().chunks.len() >= 2, + "expected > 256 passes to allocate at least 2 uniform chunks" + ); + + let px_first = readback_bytes(&device, &queue, &blend_first, 4); + let px_mid = readback_bytes(&device, &queue, &mid_blends[0], 4); + let px_last = readback_bytes(&device, &queue, &blend_last, 4); + assert!(px_first[0] <= 1, "first blend (alpha=0) got {}", px_first[0]); + assert!( + (126..=129).contains(&px_mid[0]), + "mid blend (alpha=0.5) got {}", + px_mid[0] + ); + assert!(px_last[0] >= 254, "last blend (alpha=1) got {}", px_last[0]); + + let flow_first_px = readback_bytes(&device, &queue, &flow_first, 4); + let flow_last_px = readback_bytes(&device, &queue, &flow_last, 4); + assert_ne!( + flow_first_px, flow_last_px, + "first (alpha=0.25) and last (alpha=0.75) flow passes must use distinct uniform slots" + ); + + // Verify against standalone fresh runs that neither flow_first nor flow_last was corrupted. + let ref_p = OpticalFlowPipelines::new(&device); + let mut ref_enc = device.create_command_encoder(&Default::default()); + let ref_first = ref_p.interpolate_flow( + &device, + &queue, + &mut ref_enc, + &box_a, + &box_b, + 0.25, + wgpu::TextureFormat::Rgba8Unorm, + ); + let ref_last = ref_p.interpolate_flow( + &device, + &queue, + &mut ref_enc, + &box_a, + &box_b, + 0.75, + wgpu::TextureFormat::Rgba8Unorm, + ); + queue.submit(Some(ref_enc.finish())); + assert_eq!(flow_first_px, readback_bytes(&device, &queue, &ref_first, 4)); + assert_eq!(flow_last_px, readback_bytes(&device, &queue, &ref_last, 4)); + } + + #[test] + #[ignore] + fn bench_optflow_10_frames_720p_1080p() { + use std::time::Instant; + let (device, queue) = create_headless_device(); + let pipelines = OpticalFlowPipelines::new(&device); + + for (label, w, h) in [("720p", 1280u32, 720u32), ("1080p", 1920u32, 1080u32)] { + let frames: Vec = (0..11) + .map(|i| { + let img = render_box_scene(w, h, 200 + i * 16, 150 + i * 8); + upload_rgba8(&device, &queue, w, h, &img, 1000 + i as u64) + }) + .collect(); + + // Warmup 1 frame with distinct hash so all 10 benchmark frames miss flow_cache + { + let warm_a = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 200, 150), 9998); + let warm_b = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 216, 158), 9999); + let mut enc = device.create_command_encoder(&Default::default()); + let _ = pipelines.interpolate_flow( + &device, + &queue, + &mut enc, + &warm_a, + &warm_b, + 0.5, + wgpu::TextureFormat::Rgba8Unorm, + ); + queue.submit(Some(enc.finish())); + let _ = device.poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(10)), + }); + } + + let t0 = Instant::now(); + for i in 0..10 { + let mut enc = device.create_command_encoder(&Default::default()); + let _out = pipelines.interpolate_flow( + &device, + &queue, + &mut enc, + &frames[i], + &frames[i + 1], + 0.5, + wgpu::TextureFormat::Rgba8Unorm, + ); + queue.submit(Some(enc.finish())); + let _ = device.poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(10)), + }); + } + let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0; + println!( + "BENCH {label} ({w}x{h}) 10 frames: total = {elapsed_ms:.2} ms, per_frame = {:.2} ms", + elapsed_ms / 10.0 + ); + } + } }