Skip to main content

spatialrust_gpu/image/
vision_chain.rs

1//! Explicit upload-once GPU-resident Vision 2 chain.
2
3use spatialrust_core::SpatialResult;
4
5use super::{GpuAiTensor, GpuImage, GpuImageBorder, GpuMorphology};
6use crate::WgpuRuntime;
7
8/// Configuration for the resident resize-to-AI chain.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct GpuVisionChainOptions {
11    /// Resize output width.
12    pub width: u32,
13    /// Resize output height.
14    pub height: u32,
15    /// Odd box-blur kernel size.
16    pub blur_kernel: u32,
17    /// Odd morphology kernel size.
18    pub morphology_kernel: u32,
19    /// Morphology operation after Sobel.
20    pub morphology: GpuMorphology,
21    /// Input-value scale for AI packing.
22    pub scale: f32,
23    /// Per-channel means.
24    pub mean: [f32; 4],
25    /// Per-channel standard deviations.
26    pub std: [f32; 4],
27}
28
29impl Default for GpuVisionChainOptions {
30    fn default() -> Self {
31        Self {
32            width: 640,
33            height: 480,
34            blur_kernel: 3,
35            morphology_kernel: 3,
36            morphology: GpuMorphology::Dilate,
37            scale: 1.0 / 255.0,
38            mean: [0.0; 4],
39            std: [1.0; 4],
40        }
41    }
42}
43
44/// Runs resize → gray → blur → Sobel → morphology → planar AI packing.
45///
46/// Matching source/output dimensions omit resize and its device transfer stage.
47/// The caller owns the uploaded source. Every intermediate is recycled after
48/// its consumer has been submitted, and no host readback occurs.
49pub fn run_gpu_vision_chain(
50    runtime: &WgpuRuntime,
51    source: &GpuImage,
52    options: GpuVisionChainOptions,
53) -> SpatialResult<GpuAiTensor> {
54    run_gpu_vision_chain_with_profiler(runtime, source, options, None)
55}
56
57/// Runs the resident image chain with five to eight compute-pass timing samples.
58///
59/// Queries remain on the device until the caller explicitly collects the
60/// profiler. Small blur/morphology workloads need five unused stages for matching
61/// dimensions or six when resizing. Blur boxes with area at least 81 and at
62/// least 65,536 pixel/sample visits add one
63/// for the unrounded horizontal-sum pass. Morphology with area at least 81
64/// and at least 1,048,576 visits adds a horizontal extrema sample.
65pub fn run_gpu_vision_chain_profiled(
66    runtime: &WgpuRuntime,
67    source: &GpuImage,
68    options: GpuVisionChainOptions,
69    profiler: &mut crate::GpuStageProfiler,
70) -> SpatialResult<GpuAiTensor> {
71    profiler.validate(
72        runtime,
73        3 + u32::from(source.width() != options.width || source.height() != options.height)
74            + super::kernels::box_blur::blur_pass_count(
75                options.width,
76                options.height,
77                options.blur_kernel,
78                options.blur_kernel,
79            )
80            + super::kernels::spatial::morphology_pass_count(
81                options.width,
82                options.height,
83                options.morphology_kernel,
84                options.morphology_kernel,
85            ),
86    )?;
87    let result = run_gpu_vision_chain_with_profiler(runtime, source, options, Some(profiler));
88    profiler.finish_recording(&result);
89    result
90}
91
92pub(crate) fn run_gpu_vision_chain_with_profiler(
93    runtime: &WgpuRuntime,
94    source: &GpuImage,
95    options: GpuVisionChainOptions,
96    mut profiler: Option<&mut crate::GpuStageProfiler>,
97) -> SpatialResult<GpuAiTensor> {
98    let resized = if source.width() == options.width && source.height() == options.height {
99        // Preserve the original resize admission even when its identity copy is omitted.
100        source.validate_runtime(runtime)?;
101        super::kernels::spatial::validate_resize_dispatch(
102            [source.width(), source.height()],
103            [options.width, options.height],
104            &runtime.device().limits(),
105        )?;
106        None
107    } else {
108        Some(super::kernels::spatial::resize_nearest_gpu_with_profiler(
109            runtime,
110            source,
111            options.width,
112            options.height,
113            profiler.as_deref_mut(),
114        )?)
115    };
116    let gray = super::kernels::gray::rgb_to_gray_gpu_with_profiler(
117        runtime,
118        resized.as_ref().unwrap_or(source),
119        profiler.as_deref_mut(),
120    )?;
121    if let Some(resized) = resized {
122        resized.recycle(runtime);
123    }
124    let blurred = super::kernels::box_blur::box_blur_gpu_with_profiler(
125        runtime,
126        &gray,
127        options.blur_kernel,
128        options.blur_kernel,
129        GpuImageBorder::Replicate,
130        profiler.as_deref_mut(),
131    )?;
132    gray.recycle(runtime);
133    let edges = super::kernels::spatial::sobel_gpu_with_profiler(
134        runtime,
135        &blurred,
136        profiler.as_deref_mut(),
137    )?;
138    blurred.recycle(runtime);
139    let morphology = super::kernels::spatial::morphology_gpu_with_profiler(
140        runtime,
141        &edges,
142        options.morphology_kernel,
143        options.morphology_kernel,
144        options.morphology,
145        profiler.as_deref_mut(),
146    )?;
147    edges.recycle(runtime);
148    let tensor = super::ai_tensor::pack_ai_chw_gpu_with_profiler(
149        runtime,
150        &morphology,
151        options.scale,
152        options.mean,
153        options.std,
154        profiler,
155    )?;
156    morphology.recycle(runtime);
157    Ok(tensor)
158}
159
160#[cfg(all(test, not(target_arch = "wasm32")))]
161#[path = "vision_chain_identity_tests.rs"]
162mod identity_tests;