authoravatarclover caruso<git@paperclover.net>2026-12-01 15:02:12-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 15:22:03-08:00
log912ea88b5351f38b8fce8bc609dca78748303360
tree0ee3144bfd1c391b8160aa663324dbb02ac553c5
parent145b969dbfe06655a9570f285ed18ce5f259ab79
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): pool OpticalFlowPipelines pyramid textures and dynamic uniform ring


1 files changed, 536 insertions(+), 45 deletions(-)

crates/engine/src/optflow.rs+536-45
...@@ -4,9 +4,10 @@...@@ -4,9 +4,10 @@
4use crate::cache::CachedTexture;4use crate::cache::CachedTexture;
5use bytemuck::{Pod, Zeroable};5use bytemuck::{Pod, Zeroable};
6use model::BitDepth;6use model::BitDepth;
7use std::collections::HashMap;7use std::collections::{HashMap, VecDeque};
8use std::collections::hash_map::DefaultHasher;8use std::collections::hash_map::DefaultHasher;
9use std::hash::{Hash, Hasher};9use std::hash::{Hash, Hasher};
10use std::num::NonZeroU64;
10use std::sync::{Mutex, RwLock};11use std::sync::{Mutex, RwLock};
1112
12#[repr(C)]13#[repr(C)]
...@@ -452,9 +453,137 @@ fn fs_warp_flow(in: VsOut) -> @location(0) vec4<f32> {...@@ -452,9 +453,137 @@ fn fs_warp_flow(in: VsOut) -> @location(0) vec4<f32> {
452/// Cached flow fields kept per `OpticalFlowPipelines`; one entry is a single frame pair.453/// Cached flow fields kept per `OpticalFlowPipelines`; one entry is a single frame pair.
453const FLOW_CACHE_CAP: usize = 4;454const FLOW_CACHE_CAP: usize = 4;
454455
456/// Uniform slots allocated per ring chunk (`256 * 256 B = 64 KiB` at 256-byte alignment).
457const UNIFORM_SLOTS_PER_CHUNK: u32 = 256;
458/// Maximum uniform ring chunks before wrapping (`32 * 256 = 8,192` slots, `<= 2 MiB`).
459const MAX_UNIFORM_CHUNKS: u32 = 32;
460
461/// Maximum number of idle `Rgba16Float` pyramid textures retained in [`PyramidScratchPool`].
462const PYRAMID_POOL_MAX_TEXTURES: usize = 32;
463/// Maximum total VRAM retained in [`PyramidScratchPool`] (256 MiB).
464const PYRAMID_POOL_MAX_BYTES: u64 = 256 * 1024 * 1024;
465
455/// `(content_hash_a, content_hash_b, full-res size)`.466/// `(content_hash_a, content_hash_b, full-res size)`.
456type FlowKey = (u64, u64, [u32; 2]);467type FlowKey = (u64, u64, [u32; 2]);
457468
469struct UniformRing {
470 stride: u32,
471 chunks: Vec<wgpu::Buffer>,
472 cursor: u32,
473}
474
475impl UniformRing {
476 fn new(device: &wgpu::Device) -> Self {
477 let uniform_size = std::mem::size_of::<OptFlowUniform>() as u32;
478 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
479 let stride = uniform_size.div_ceil(min_align) * min_align;
480 Self {
481 stride,
482 chunks: Vec::new(),
483 cursor: 0,
484 }
485 }
486
487 /// Writes `uniform` into the next aligned dynamic-offset slot and returns `(chunk_buffer, offset)`.
488 fn alloc_slot(
489 &mut self,
490 device: &wgpu::Device,
491 queue: &wgpu::Queue,
492 uniform: &OptFlowUniform,
493 ) -> (wgpu::Buffer, u32) {
494 let max_slots = UNIFORM_SLOTS_PER_CHUNK * MAX_UNIFORM_CHUNKS;
495 let slot_global = self.cursor % max_slots;
496 let chunk_idx = (slot_global / UNIFORM_SLOTS_PER_CHUNK) as usize;
497 let slot_in_chunk = slot_global % UNIFORM_SLOTS_PER_CHUNK;
498 while chunk_idx >= self.chunks.len() {
499 let size = u64::from(UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.stride);
500 let buf = device.create_buffer(&wgpu::BufferDescriptor {
501 label: Some("optflow-uniform-ring"),
502 size,
503 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
504 mapped_at_creation: false,
505 });
506 self.chunks.push(buf);
507 }
508 let offset = slot_in_chunk * self.stride;
509 queue.write_buffer(
510 &self.chunks[chunk_idx],
511 u64::from(offset),
512 bytemuck::bytes_of(uniform),
513 );
514 self.cursor = (slot_global + 1) % max_slots;
515 (self.chunks[chunk_idx].clone(), offset)
516 }
517
518 fn reset_cursor(&mut self) {
519 self.cursor = 0;
520 }
521}
522
523struct PooledF16Tex {
524 size: [u32; 2],
525 bytes: u64,
526 tex: wgpu::Texture,
527 view: wgpu::TextureView,
528}
529
530/// Bounded LRU pool of reusable `Rgba16Float` pyramid/flow scratch textures keyed by `[w, h]`.
531#[derive(Default)]
532struct PyramidScratchPool {
533 entries: VecDeque<PooledF16Tex>,
534 total_bytes: u64,
535 alloc_count: u64,
536 reuse_count: u64,
537}
538
539impl PyramidScratchPool {
540 fn acquire(
541 &mut self,
542 device: &wgpu::Device,
543 size: [u32; 2],
544 label: &str,
545 ) -> (wgpu::Texture, wgpu::TextureView) {
546 let size = [size[0].max(1), size[1].max(1)];
547 if let Some(idx) = self.entries.iter().rposition(|e| e.size == size) {
548 let entry = self.entries.remove(idx).expect("valid pool index");
549 self.total_bytes -= entry.bytes;
550 self.reuse_count += 1;
551 return (entry.tex, entry.view);
552 }
553 self.alloc_count += 1;
554 alloc_f16_tex(device, size, label)
555 }
556
557 fn release(&mut self, tex: wgpu::Texture, view: wgpu::TextureView, size: [u32; 2]) {
558 let size = [size[0].max(1), size[1].max(1)];
559 let bytes = u64::from(size[0]) * u64::from(size[1]) * 8;
560 if bytes > PYRAMID_POOL_MAX_BYTES {
561 return;
562 }
563 while self.entries.len() >= PYRAMID_POOL_MAX_TEXTURES
564 || self.total_bytes + bytes > PYRAMID_POOL_MAX_BYTES
565 {
566 if let Some(evicted) = self.entries.pop_front() {
567 self.total_bytes -= evicted.bytes;
568 } else {
569 break;
570 }
571 }
572 self.total_bytes += bytes;
573 self.entries.push_back(PooledF16Tex {
574 size,
575 bytes,
576 tex,
577 view,
578 });
579 }
580
581 fn clear(&mut self) {
582 self.entries.clear();
583 self.total_bytes = 0;
584 }
585}
586
458/// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation.587/// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation.
459pub struct OpticalFlowPipelines {588pub struct OpticalFlowPipelines {
460 shader: wgpu::ShaderModule,589 shader: wgpu::ShaderModule,
...@@ -468,8 +597,10 @@ pub struct OpticalFlowPipelines {...@@ -468,8 +597,10 @@ pub struct OpticalFlowPipelines {
468 flow_smooth: wgpu::RenderPipeline,597 flow_smooth: wgpu::RenderPipeline,
469 blend_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,598 blend_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,
470 warp_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,599 warp_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,
471 /// Half-resolution flow fields, least recently used first.600 /// Half-resolution flow fields, least recently used first: `(key, view, texture, size)`.
472 flow_cache: Mutex<Vec<(FlowKey, wgpu::TextureView)>>,601 flow_cache: Mutex<Vec<(FlowKey, wgpu::TextureView, wgpu::Texture, [u32; 2])>>,
602 uniform_ring: Mutex<UniformRing>,
603 pyramid_pool: Mutex<PyramidScratchPool>,
473}604}
474605
475impl OpticalFlowPipelines {606impl OpticalFlowPipelines {
...@@ -490,6 +621,7 @@ impl OpticalFlowPipelines {...@@ -490,6 +621,7 @@ impl OpticalFlowPipelines {
490 count: None,621 count: None,
491 };622 };
492623
624 let uniform_size = std::mem::size_of::<OptFlowUniform>() as u64;
493 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {625 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
494 label: Some("optflow-bgl"),626 label: Some("optflow-bgl"),
495 entries: &[627 entries: &[
...@@ -507,8 +639,8 @@ impl OpticalFlowPipelines {...@@ -507,8 +639,8 @@ impl OpticalFlowPipelines {
507 visibility: wgpu::ShaderStages::FRAGMENT,639 visibility: wgpu::ShaderStages::FRAGMENT,
508 ty: wgpu::BindingType::Buffer {640 ty: wgpu::BindingType::Buffer {
509 ty: wgpu::BufferBindingType::Uniform,641 ty: wgpu::BufferBindingType::Uniform,
510 has_dynamic_offset: false,642 has_dynamic_offset: true,
511 min_binding_size: None,643 min_binding_size: NonZeroU64::new(uniform_size),
512 },644 },
513 count: None,645 count: None,
514 },646 },
...@@ -556,9 +688,24 @@ impl OpticalFlowPipelines {...@@ -556,9 +688,24 @@ impl OpticalFlowPipelines {
556 blend_pipelines: RwLock::new(HashMap::new()),688 blend_pipelines: RwLock::new(HashMap::new()),
557 warp_pipelines: RwLock::new(HashMap::new()),689 warp_pipelines: RwLock::new(HashMap::new()),
558 flow_cache: Mutex::new(Vec::new()),690 flow_cache: Mutex::new(Vec::new()),
691 uniform_ring: Mutex::new(UniformRing::new(device)),
692 pyramid_pool: Mutex::new(PyramidScratchPool::default()),
559 }693 }
560 }694 }
561695
696 /// Resets the dynamic uniform ring cursor back to slot `0`.
697 /// Call only after all prior encoded passes on this pipeline have been submitted.
698 pub fn reset_uniform_cursor(&self) {
699 self.uniform_ring.lock().unwrap().reset_cursor();
700 }
701
702 /// Clears cached flow fields and pooled intermediate pyramid textures, and resets the uniform cursor.
703 pub fn clear_scratch(&self) {
704 self.flow_cache.lock().unwrap().clear();
705 self.pyramid_pool.lock().unwrap().clear();
706 self.uniform_ring.lock().unwrap().reset_cursor();
707 }
708
562 fn ensure_target_pipeline(709 fn ensure_target_pipeline(
563 &self,710 &self,
564 device: &wgpu::Device,711 device: &wgpu::Device,
...@@ -594,13 +741,10 @@ impl OpticalFlowPipelines {...@@ -594,13 +741,10 @@ impl OpticalFlowPipelines {
594 dst_size: [w, h, 1.0 / w, 1.0 / h],741 dst_size: [w, h, 1.0 / w, 1.0 / h],
595 params,742 params,
596 };743 };
597 let ubuf = device.create_buffer(&wgpu::BufferDescriptor {744 let (ubuf, dynamic_offset) = {
598 label: Some("optflow-uniform"),745 let mut ring = self.uniform_ring.lock().unwrap();
599 size: std::mem::size_of::<OptFlowUniform>() as u64,746 ring.alloc_slot(device, queue, &uniform)
600 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,747 };
601 mapped_at_creation: false,
602 });
603 queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uniform));
604748
605 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {749 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
606 label: Some(label),750 label: Some(label),
...@@ -624,7 +768,11 @@ impl OpticalFlowPipelines {...@@ -624,7 +768,11 @@ impl OpticalFlowPipelines {
624 },768 },
625 wgpu::BindGroupEntry {769 wgpu::BindGroupEntry {
626 binding: 4,770 binding: 4,
627 resource: ubuf.as_entire_binding(),771 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
772 buffer: &ubuf,
773 offset: 0,
774 size: NonZeroU64::new(std::mem::size_of::<OptFlowUniform>() as u64),
775 }),
628 },776 },
629 ],777 ],
630 });778 });
...@@ -646,7 +794,7 @@ impl OpticalFlowPipelines {...@@ -646,7 +794,7 @@ impl OpticalFlowPipelines {
646 multiview_mask: None,794 multiview_mask: None,
647 });795 });
648 rp.set_pipeline(pipeline);796 rp.set_pipeline(pipeline);
649 rp.set_bind_group(0, &bg, &[]);797 rp.set_bind_group(0, &bg, &[dynamic_offset]);
650 rp.draw(0..3, 0..1);798 rp.draw(0..3, 0..1);
651 }799 }
652800
...@@ -708,22 +856,49 @@ impl OpticalFlowPipelines {...@@ -708,22 +856,49 @@ impl OpticalFlowPipelines {
708 let flow_key = (frame_a.content_hash, frame_b.content_hash, s0);856 let flow_key = (frame_a.content_hash, frame_b.content_hash, s0);
709 let cached = {857 let cached = {
710 let mut cache = self.flow_cache.lock().unwrap();858 let mut cache = self.flow_cache.lock().unwrap();
711 cache.iter().position(|(k, _)| *k == flow_key).map(|i| {859 cache.iter().position(|(k, _, _, _)| *k == flow_key).map(|i| {
712 let entry = cache.remove(i);860 let entry = cache.remove(i);
713 let view = entry.1.clone();861 let view = entry.1.clone();
714 cache.push(entry);862 cache.push(entry);
715 view863 view
716 })864 })
717 };865 };
718 let flow1_view = cached.unwrap_or_else(|| {866 let flow1_view = match cached {
719 let view = self.compute_flow_field(device, queue, enc, frame_a, frame_b);867 Some(view) => view,
720 let mut cache = self.flow_cache.lock().unwrap();868 None => {
721 if cache.len() >= FLOW_CACHE_CAP {869 // Evict the LRU flow field before computing the new one so its backing
722 cache.remove(0);870 // texture can be immediately reused by PyramidScratchPool.
871 let evicted_before = {
872 let mut cache = self.flow_cache.lock().unwrap();
873 if cache.len() >= FLOW_CACHE_CAP {
874 Some(cache.remove(0))
875 } else {
876 None
877 }
878 };
879 if let Some((_, old_view, old_tex, old_size)) = evicted_before {
880 self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size);
881 }
882
883 let (flow1_tex, flow1_view) =
884 self.compute_flow_field(device, queue, enc, frame_a, frame_b);
885
886 let evicted_after = {
887 let mut cache = self.flow_cache.lock().unwrap();
888 let extra = if cache.len() >= FLOW_CACHE_CAP {
889 Some(cache.remove(0))
890 } else {
891 None
892 };
893 cache.push((flow_key, flow1_view.clone(), flow1_tex, s1));
894 extra
895 };
896 if let Some((_, old_view, old_tex, old_size)) = evicted_after {
897 self.pyramid_pool.lock().unwrap().release(old_tex, old_view, old_size);
898 }
899 flow1_view
723 }900 }
724 cache.push((flow_key, view.clone()));901 };
725 view
726 });
727902
728 // Full-resolution bidirectional occlusion-aware warp & blend903 // Full-resolution bidirectional occlusion-aware warp & blend
729 let scale_1_to_0 = [904 let scale_1_to_0 = [
...@@ -742,7 +917,7 @@ impl OpticalFlowPipelines {...@@ -742,7 +917,7 @@ impl OpticalFlowPipelines {
742 }917 }
743918
744 /// Encodes the 4-level (full, 1/2, 1/4, 1/8) coarse-to-fine flow estimate and returns the919 /// Encodes the 4-level (full, 1/2, 1/4, 1/8) coarse-to-fine flow estimate and returns the
745 /// half-resolution flow field.920 /// half-resolution flow field `(texture, view)`.
746 fn compute_flow_field(921 fn compute_flow_field(
747 &self,922 &self,
748 device: &wgpu::Device,923 device: &wgpu::Device,
...@@ -750,15 +925,50 @@ impl OpticalFlowPipelines {...@@ -750,15 +925,50 @@ impl OpticalFlowPipelines {
750 enc: &mut wgpu::CommandEncoder,925 enc: &mut wgpu::CommandEncoder,
751 frame_a: &CachedTexture,926 frame_a: &CachedTexture,
752 frame_b: &CachedTexture,927 frame_b: &CachedTexture,
753 ) -> wgpu::TextureView {928 ) -> (wgpu::Texture, wgpu::TextureView) {
754 let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)];929 let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)];
755 let s1 = half_size(s0);930 let s1 = half_size(s0);
756 let s2 = half_size(s1);931 let s2 = half_size(s1);
757 let s3 = half_size(s2);932 let s3 = half_size(s2);
758933
934 // Acquire all 14 distinct pyramid/feature/flow textures for this call so no texture is
935 // aliased within the unsubmitted CommandEncoder.
936 let (
937 (fa0_tex, fa0_view),
938 (fb0_tex, fb0_view),
939 (fa1_tex, fa1_view),
940 (fb1_tex, fb1_view),
941 (fa2_tex, fa2_view),
942 (fb2_tex, fb2_view),
943 (fa3_tex, fa3_view),
944 (fb3_tex, fb3_view),
945 (flow3_raw_tex, flow3_raw_view),
946 (flow3_tex, flow3_view),
947 (flow2_raw_tex, flow2_raw_view),
948 (flow2_tex, flow2_view),
949 (flow1_raw_tex, flow1_raw_view),
950 (flow1_tex, flow1_view),
951 ) = {
952 let mut pool = self.pyramid_pool.lock().unwrap();
953 (
954 pool.acquire(device, s0, "optflow-fa0"),
955 pool.acquire(device, s0, "optflow-fb0"),
956 pool.acquire(device, s1, "optflow-fa1"),
957 pool.acquire(device, s1, "optflow-fb1"),
958 pool.acquire(device, s2, "optflow-fa2"),
959 pool.acquire(device, s2, "optflow-fb2"),
960 pool.acquire(device, s3, "optflow-fa3"),
961 pool.acquire(device, s3, "optflow-fb3"),
962 pool.acquire(device, s3, "optflow-f3-raw"),
963 pool.acquire(device, s3, "optflow-f3"),
964 pool.acquire(device, s2, "optflow-f2-raw"),
965 pool.acquire(device, s2, "optflow-f2"),
966 pool.acquire(device, s1, "optflow-f1-raw"),
967 pool.acquire(device, s1, "optflow-f1"),
968 )
969 };
970
759 // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B971 // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B
760 let (fa0_tex, fa0_view) = alloc_f16_tex(device, s0, "optflow-fa0");
761 let (fb0_tex, fb0_view) = alloc_f16_tex(device, s0, "optflow-fb0");
762 self.run_pass(972 self.run_pass(
763 device, queue, enc, &self.extract_features, "optflow-extract-a",973 device, queue, enc, &self.extract_features, "optflow-extract-a",
764 &frame_a.view, &frame_a.view, &frame_a.view, &fa0_view, s0, [0.0; 4],974 &frame_a.view, &frame_a.view, &frame_a.view, &fa0_view, s0, [0.0; 4],
...@@ -768,8 +978,6 @@ impl OpticalFlowPipelines {...@@ -768,8 +978,6 @@ impl OpticalFlowPipelines {
768 &frame_b.view, &frame_b.view, &frame_b.view, &fb0_view, s0, [0.0; 4],978 &frame_b.view, &frame_b.view, &frame_b.view, &fb0_view, s0, [0.0; 4],
769 );979 );
770980
771 let (fa1_tex, fa1_view) = alloc_f16_tex(device, s1, "optflow-fa1");
772 let (fb1_tex, fb1_view) = alloc_f16_tex(device, s1, "optflow-fb1");
773 self.run_pass(981 self.run_pass(
774 device, queue, enc, &self.downsample, "optflow-down-a1",982 device, queue, enc, &self.downsample, "optflow-down-a1",
775 &fa0_view, &fa0_view, &fa0_view, &fa1_view, s1, [0.0; 4],983 &fa0_view, &fa0_view, &fa0_view, &fa1_view, s1, [0.0; 4],
...@@ -779,8 +987,6 @@ impl OpticalFlowPipelines {...@@ -779,8 +987,6 @@ impl OpticalFlowPipelines {
779 &fb0_view, &fb0_view, &fb0_view, &fb1_view, s1, [0.0; 4],987 &fb0_view, &fb0_view, &fb0_view, &fb1_view, s1, [0.0; 4],
780 );988 );
781989
782 let (fa2_tex, fa2_view) = alloc_f16_tex(device, s2, "optflow-fa2");
783 let (fb2_tex, fb2_view) = alloc_f16_tex(device, s2, "optflow-fb2");
784 self.run_pass(990 self.run_pass(
785 device, queue, enc, &self.downsample, "optflow-down-a2",991 device, queue, enc, &self.downsample, "optflow-down-a2",
786 &fa1_view, &fa1_view, &fa1_view, &fa2_view, s2, [0.0; 4],992 &fa1_view, &fa1_view, &fa1_view, &fa2_view, s2, [0.0; 4],
...@@ -790,8 +996,6 @@ impl OpticalFlowPipelines {...@@ -790,8 +996,6 @@ impl OpticalFlowPipelines {
790 &fb1_view, &fb1_view, &fb1_view, &fb2_view, s2, [0.0; 4],996 &fb1_view, &fb1_view, &fb1_view, &fb2_view, s2, [0.0; 4],
791 );997 );
792998
793 let (fa3_tex, fa3_view) = alloc_f16_tex(device, s3, "optflow-fa3");
794 let (fb3_tex, fb3_view) = alloc_f16_tex(device, s3, "optflow-fb3");
795 self.run_pass(999 self.run_pass(
796 device, queue, enc, &self.downsample, "optflow-down-a3",1000 device, queue, enc, &self.downsample, "optflow-down-a3",
797 &fa2_view, &fa2_view, &fa2_view, &fa3_view, s3, [0.0; 4],1001 &fa2_view, &fa2_view, &fa2_view, &fa3_view, s3, [0.0; 4],
...@@ -803,8 +1007,6 @@ impl OpticalFlowPipelines {...@@ -803,8 +1007,6 @@ impl OpticalFlowPipelines {
8031007
804 // 2. Coarse-to-fine bidirectional flow estimation1008 // 2. Coarse-to-fine bidirectional flow estimation
805 // Level 3 (1/8 res): exhaustive [-4..4] search + parabolic subpixel + bilateral smooth1009 // Level 3 (1/8 res): exhaustive [-4..4] search + parabolic subpixel + bilateral smooth
806 let (flow3_raw_tex, flow3_raw_view) = alloc_f16_tex(device, s3, "optflow-f3-raw");
807 let (flow3_tex, flow3_view) = alloc_f16_tex(device, s3, "optflow-f3");
808 self.run_pass(1010 self.run_pass(
809 device, queue, enc, &self.flow_coarse, "optflow-coarse-l3",1011 device, queue, enc, &self.flow_coarse, "optflow-coarse-l3",
810 &fa3_view, &fb3_view, &fa3_view, &flow3_raw_view, s3, [0.0; 4],1012 &fa3_view, &fb3_view, &fa3_view, &flow3_raw_view, s3, [0.0; 4],
...@@ -816,8 +1018,6 @@ impl OpticalFlowPipelines {...@@ -816,8 +1018,6 @@ impl OpticalFlowPipelines {
8161018
817 // Level 2 (1/4 res): upsample + [-2..2] refine + LK + bilateral smooth1019 // Level 2 (1/4 res): upsample + [-2..2] refine + LK + bilateral smooth
818 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];1020 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];
819 let (flow2_raw_tex, flow2_raw_view) = alloc_f16_tex(device, s2, "optflow-f2-raw");
820 let (flow2_tex, flow2_view) = alloc_f16_tex(device, s2, "optflow-f2");
821 self.run_pass(1021 self.run_pass(
822 device, queue, enc, &self.flow_refine, "optflow-refine-l2",1022 device, queue, enc, &self.flow_refine, "optflow-refine-l2",
823 &fa2_view, &fb2_view, &flow3_view, &flow2_raw_view, s2, scale_3_to_2,1023 &fa2_view, &fb2_view, &flow3_view, &flow2_raw_view, s2, scale_3_to_2,
...@@ -829,8 +1029,6 @@ impl OpticalFlowPipelines {...@@ -829,8 +1029,6 @@ impl OpticalFlowPipelines {
8291029
830 // Level 1 (1/2 res): upsample + [-2..2] refine + LK + bilateral smooth1030 // Level 1 (1/2 res): upsample + [-2..2] refine + LK + bilateral smooth
831 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];1031 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];
832 let (flow1_raw_tex, flow1_raw_view) = alloc_f16_tex(device, s1, "optflow-f1-raw");
833 let (flow1_tex, flow1_view) = alloc_f16_tex(device, s1, "optflow-f1");
834 self.run_pass(1032 self.run_pass(
835 device, queue, enc, &self.flow_refine, "optflow-refine-l1",1033 device, queue, enc, &self.flow_refine, "optflow-refine-l1",
836 &fa1_view, &fb1_view, &flow2_view, &flow1_raw_view, s1, scale_2_to_1,1034 &fa1_view, &fb1_view, &flow2_view, &flow1_raw_view, s1, scale_2_to_1,
...@@ -840,13 +1038,27 @@ impl OpticalFlowPipelines {...@@ -840,13 +1038,27 @@ impl OpticalFlowPipelines {
840 &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4],1038 &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4],
841 );1039 );
8421040
843 // Keep temporary textures alive until all passes are encoded into `enc`.1041 // Return intermediate scratch textures to the pool now that all passes reading/writing them
844 drop((1042 // are encoded in strict FIFO order on `enc`. Subsequent calls on the same or future
845 fa0_tex, fb0_tex, fa1_tex, fb1_tex, fa2_tex, fb2_tex, fa3_tex, fb3_tex,1043 // encoders execute strictly after these passes.
846 flow3_raw_tex, flow3_tex, flow2_raw_tex, flow2_tex, flow1_raw_tex, flow1_tex,1044 {
847 ));1045 let mut pool = self.pyramid_pool.lock().unwrap();
1046 pool.release(fa0_tex, fa0_view, s0);
1047 pool.release(fb0_tex, fb0_view, s0);
1048 pool.release(fa1_tex, fa1_view, s1);
1049 pool.release(fb1_tex, fb1_view, s1);
1050 pool.release(fa2_tex, fa2_view, s2);
1051 pool.release(fb2_tex, fb2_view, s2);
1052 pool.release(fa3_tex, fa3_view, s3);
1053 pool.release(fb3_tex, fb3_view, s3);
1054 pool.release(flow3_raw_tex, flow3_raw_view, s3);
1055 pool.release(flow3_tex, flow3_view, s3);
1056 pool.release(flow2_raw_tex, flow2_raw_view, s2);
1057 pool.release(flow2_tex, flow2_view, s2);
1058 pool.release(flow1_raw_tex, flow1_raw_view, s1);
1059 }
8481060
849 flow1_view1061 (flow1_tex, flow1_view)
850 }1062 }
851}1063}
8521064
...@@ -1329,4 +1541,283 @@ mod tests {...@@ -1329,4 +1541,283 @@ mod tests {
1329 let err = mae_rgba8(&f32_as_u8, &img_a);1541 let err = mae_rgba8(&f32_as_u8, &img_a);
1330 assert!(err < 0.5, "expected alpha=0 blend MAE ({err:.3}) < 0.5");1542 assert!(err < 0.5, "expected alpha=0 blend MAE ({err:.3}) < 0.5");
1331 }1543 }
1544
1545 #[test]
1546 fn test_optflow_pyramid_pool_reuses_textures_and_matches_unpooled_bit_for_bit() {
1547 let (device, queue) = create_headless_device();
1548 let pooled = OpticalFlowPipelines::new(&device);
1549
1550 let (w, h) = (192u32, 108u32);
1551 let fmt = wgpu::TextureFormat::Rgba8Unorm;
1552 let frames: Vec<CachedTexture> = (0..9)
1553 .map(|i| {
1554 let img = render_box_scene(w, h, 24 + i * 10, 20 + i * 4);
1555 upload_rgba8(&device, &queue, w, h, &img, 500 + i as u64)
1556 })
1557 .collect();
1558
1559 // 1. Direct compute_flow_field reuse: alloc_count stays flat at 14 after frame 1.
1560 for i in 0..4 {
1561 let mut enc = device.create_command_encoder(&Default::default());
1562 let (f_tex, f_view) =
1563 pooled.compute_flow_field(&device, &queue, &mut enc, &frames[i], &frames[i + 1]);
1564 queue.submit(Some(enc.finish()));
1565 pooled.pyramid_pool.lock().unwrap().release(f_tex, f_view, half_size([w, h]));
1566 assert_eq!(
1567 pooled.pyramid_pool.lock().unwrap().alloc_count,
1568 14,
1569 "direct compute_flow_field alloc_count should remain 14 on pair {i}"
1570 );
1571 }
1572
1573 // 2. Full interpolate_flow across 8 distinct frame pairs:
1574 // - Intermediate pyramid/feature textures reuse from frame 1 (alloc_count only grows by
1575 // 1 per flow_cache slot up to FLOW_CACHE_CAP, then stays completely flat).
1576 // - Output matches fresh unpooled OpticalFlowPipelines bit-for-bit.
1577 pooled.clear_scratch();
1578 pooled.pyramid_pool.lock().unwrap().alloc_count = 0;
1579 pooled.pyramid_pool.lock().unwrap().reuse_count = 0;
1580
1581 let mut stable_allocs = 0u64;
1582 for i in 0..8 {
1583 let mut enc = device.create_command_encoder(&Default::default());
1584 let out_pooled = pooled.interpolate_flow(
1585 &device,
1586 &queue,
1587 &mut enc,
1588 &frames[i],
1589 &frames[i + 1],
1590 0.5,
1591 fmt,
1592 );
1593 queue.submit(Some(enc.finish()));
1594 let pooled_bytes = readback_bytes(&device, &queue, &out_pooled, 4);
1595
1596 let allocs_now = pooled.pyramid_pool.lock().unwrap().alloc_count;
1597 if i < FLOW_CACHE_CAP {
1598 assert_eq!(allocs_now, 14 + i as u64);
1599 stable_allocs = allocs_now;
1600 } else {
1601 assert_eq!(
1602 allocs_now, stable_allocs,
1603 "alloc_count must stay flat once flow_cache reaches capacity (pair {i})"
1604 );
1605 }
1606
1607 // Fresh unpooled instance on the exact same pair
1608 let fresh = OpticalFlowPipelines::new(&device);
1609 let mut fresh_enc = device.create_command_encoder(&Default::default());
1610 let out_fresh = fresh.interpolate_flow(
1611 &device,
1612 &queue,
1613 &mut fresh_enc,
1614 &frames[i],
1615 &frames[i + 1],
1616 0.5,
1617 fmt,
1618 );
1619 queue.submit(Some(fresh_enc.finish()));
1620 let fresh_bytes = readback_bytes(&device, &queue, &out_fresh, 4);
1621
1622 assert_eq!(
1623 pooled_bytes, fresh_bytes,
1624 "pooled output must be bit-for-bit identical to unpooled reference (pair {i})"
1625 );
1626 }
1627 assert!(
1628 pooled.pyramid_pool.lock().unwrap().reuse_count >= 7 * 13,
1629 "expected substantial texture reuse across 8 distinct frame pairs"
1630 );
1631 }
1632
1633 #[test]
1634 fn test_optflow_uniform_ring_multiple_calls_in_single_encoder() {
1635 let (device, queue) = create_headless_device();
1636 let pipelines = OpticalFlowPipelines::new(&device);
1637
1638 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
1639 let stride = pipelines.uniform_ring.lock().unwrap().stride;
1640 assert_eq!(stride % min_align, 0);
1641
1642 let (w, h) = (64u32, 64u32);
1643 let solid = |r: u8, g: u8, b: u8| -> Vec<u8> {
1644 [r, g, b, 255].repeat((w * h) as usize)
1645 };
1646 let tex_black = upload_rgba8(&device, &queue, w, h, &solid(0, 0, 0), 701);
1647 let tex_white = upload_rgba8(&device, &queue, w, h, &solid(255, 255, 255), 702);
1648 let box_a = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 8, 8), 703);
1649 let box_b = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 16, 12), 704);
1650
1651 let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1652 label: Some("optflow-ring-single-enc"),
1653 });
1654
1655 // Mix blend_frames and interpolate_flow inside a single CommandEncoder, crossing
1656 // UNIFORM_SLOTS_PER_CHUNK (256) so chunk 0 and chunk 1 are both exercised before submit.
1657 let blend_first = pipelines.blend_frames(
1658 &device,
1659 &queue,
1660 &mut enc,
1661 &tex_black,
1662 &tex_white,
1663 0.0,
1664 wgpu::TextureFormat::Rgba8Unorm,
1665 );
1666 let flow_first = pipelines.interpolate_flow(
1667 &device,
1668 &queue,
1669 &mut enc,
1670 &box_a,
1671 &box_b,
1672 0.25,
1673 wgpu::TextureFormat::Rgba8Unorm,
1674 );
1675
1676 let mut mid_blends = Vec::new();
1677 for i in 0..270 {
1678 let alpha = if i == 128 { 0.5 } else { 0.8 };
1679 let out = pipelines.blend_frames(
1680 &device,
1681 &queue,
1682 &mut enc,
1683 &tex_black,
1684 &tex_white,
1685 alpha,
1686 wgpu::TextureFormat::Rgba8Unorm,
1687 );
1688 if i == 128 {
1689 mid_blends.push(out);
1690 }
1691 }
1692
1693 let flow_last = pipelines.interpolate_flow(
1694 &device,
1695 &queue,
1696 &mut enc,
1697 &box_a,
1698 &box_b,
1699 0.75,
1700 wgpu::TextureFormat::Rgba8Unorm,
1701 );
1702 let blend_last = pipelines.blend_frames(
1703 &device,
1704 &queue,
1705 &mut enc,
1706 &tex_black,
1707 &tex_white,
1708 1.0,
1709 wgpu::TextureFormat::Rgba8Unorm,
1710 );
1711 queue.submit(Some(enc.finish()));
1712
1713 assert!(
1714 pipelines.uniform_ring.lock().unwrap().chunks.len() >= 2,
1715 "expected > 256 passes to allocate at least 2 uniform chunks"
1716 );
1717
1718 let px_first = readback_bytes(&device, &queue, &blend_first, 4);
1719 let px_mid = readback_bytes(&device, &queue, &mid_blends[0], 4);
1720 let px_last = readback_bytes(&device, &queue, &blend_last, 4);
1721 assert!(px_first[0] <= 1, "first blend (alpha=0) got {}", px_first[0]);
1722 assert!(
1723 (126..=129).contains(&px_mid[0]),
1724 "mid blend (alpha=0.5) got {}",
1725 px_mid[0]
1726 );
1727 assert!(px_last[0] >= 254, "last blend (alpha=1) got {}", px_last[0]);
1728
1729 let flow_first_px = readback_bytes(&device, &queue, &flow_first, 4);
1730 let flow_last_px = readback_bytes(&device, &queue, &flow_last, 4);
1731 assert_ne!(
1732 flow_first_px, flow_last_px,
1733 "first (alpha=0.25) and last (alpha=0.75) flow passes must use distinct uniform slots"
1734 );
1735
1736 // Verify against standalone fresh runs that neither flow_first nor flow_last was corrupted.
1737 let ref_p = OpticalFlowPipelines::new(&device);
1738 let mut ref_enc = device.create_command_encoder(&Default::default());
1739 let ref_first = ref_p.interpolate_flow(
1740 &device,
1741 &queue,
1742 &mut ref_enc,
1743 &box_a,
1744 &box_b,
1745 0.25,
1746 wgpu::TextureFormat::Rgba8Unorm,
1747 );
1748 let ref_last = ref_p.interpolate_flow(
1749 &device,
1750 &queue,
1751 &mut ref_enc,
1752 &box_a,
1753 &box_b,
1754 0.75,
1755 wgpu::TextureFormat::Rgba8Unorm,
1756 );
1757 queue.submit(Some(ref_enc.finish()));
1758 assert_eq!(flow_first_px, readback_bytes(&device, &queue, &ref_first, 4));
1759 assert_eq!(flow_last_px, readback_bytes(&device, &queue, &ref_last, 4));
1760 }
1761
1762 #[test]
1763 #[ignore]
1764 fn bench_optflow_10_frames_720p_1080p() {
1765 use std::time::Instant;
1766 let (device, queue) = create_headless_device();
1767 let pipelines = OpticalFlowPipelines::new(&device);
1768
1769 for (label, w, h) in [("720p", 1280u32, 720u32), ("1080p", 1920u32, 1080u32)] {
1770 let frames: Vec<CachedTexture> = (0..11)
1771 .map(|i| {
1772 let img = render_box_scene(w, h, 200 + i * 16, 150 + i * 8);
1773 upload_rgba8(&device, &queue, w, h, &img, 1000 + i as u64)
1774 })
1775 .collect();
1776
1777 // Warmup 1 frame with distinct hash so all 10 benchmark frames miss flow_cache
1778 {
1779 let warm_a = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 200, 150), 9998);
1780 let warm_b = upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 216, 158), 9999);
1781 let mut enc = device.create_command_encoder(&Default::default());
1782 let _ = pipelines.interpolate_flow(
1783 &device,
1784 &queue,
1785 &mut enc,
1786 &warm_a,
1787 &warm_b,
1788 0.5,
1789 wgpu::TextureFormat::Rgba8Unorm,
1790 );
1791 queue.submit(Some(enc.finish()));
1792 let _ = device.poll(wgpu::PollType::Wait {
1793 submission_index: None,
1794 timeout: Some(std::time::Duration::from_secs(10)),
1795 });
1796 }
1797
1798 let t0 = Instant::now();
1799 for i in 0..10 {
1800 let mut enc = device.create_command_encoder(&Default::default());
1801 let _out = pipelines.interpolate_flow(
1802 &device,
1803 &queue,
1804 &mut enc,
1805 &frames[i],
1806 &frames[i + 1],
1807 0.5,
1808 wgpu::TextureFormat::Rgba8Unorm,
1809 );
1810 queue.submit(Some(enc.finish()));
1811 let _ = device.poll(wgpu::PollType::Wait {
1812 submission_index: None,
1813 timeout: Some(std::time::Duration::from_secs(10)),
1814 });
1815 }
1816 let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;
1817 println!(
1818 "BENCH {label} ({w}x{h}) 10 frames: total = {elapsed_ms:.2} ms, per_frame = {:.2} ms",
1819 elapsed_ms / 10.0
1820 );
1821 }
1822 }
1332}1823}