Skip to main content

spatialrust_gpu/image/kernels/
median.rs

1//! Exact per-channel median selection on resident integer textures.
2use bytemuck::{Pod, Zeroable};
3use spatialrust_core::{SpatialError, SpatialResult};
4use std::{fmt::Write, sync::OnceLock};
5use wgpu::util::DeviceExt;
6
7use super::GpuImageBorder;
8use crate::image::gpu_image::{create_texture, GpuImage};
9use crate::WgpuRuntime;
10
11const WORKGROUP: u32 = 16;
12
13#[repr(C)]
14#[derive(Clone, Copy, Pod, Zeroable)]
15struct Params {
16    width: u32,
17    height: u32,
18    border: u32,
19    padding: u32,
20}
21
22fn plan(width: u32, height: u32, kernel: u32, limits: &wgpu::Limits) -> SpatialResult<u64> {
23    let radius = kernel / 2;
24    if !matches!(kernel, 3 | 5)
25        || width == 0
26        || height == 0
27        || width > limits.max_texture_dimension_2d
28        || height > limits.max_texture_dimension_2d
29        || u64::from(width - 1) + u64::from(radius) > i32::MAX as u64
30        || u64::from(height - 1) + u64::from(radius) > i32::MAX as u64
31        || limits.max_compute_workgroup_size_x < WORKGROUP
32        || limits.max_compute_workgroup_size_y < WORKGROUP
33        || limits.max_compute_workgroup_size_z == 0
34        || limits.max_compute_invocations_per_workgroup < WORKGROUP * WORKGROUP
35        || width.div_ceil(WORKGROUP) > limits.max_compute_workgroups_per_dimension
36        || height.div_ceil(WORKGROUP) > limits.max_compute_workgroups_per_dimension
37        || limits.max_sampled_textures_per_shader_stage == 0
38        || limits.max_storage_textures_per_shader_stage == 0
39        || limits.max_uniform_buffers_per_shader_stage == 0
40        || limits.max_uniform_buffer_binding_size < 16
41        || limits.max_buffer_size < 16
42        || limits.max_bind_groups == 0
43        || limits.max_bindings_per_bind_group < 3
44    {
45        return Err(SpatialError::InvalidArgument(
46            "GPU median requires a 3x3 or 5x5 kernel and supported texture/coordinate/compute limits"
47                .to_owned(),
48        ));
49    }
50    Ok(u64::from(width) * u64::from(height) * 4)
51}
52
53#[derive(Clone, Copy)]
54struct Comparator {
55    a: usize,
56    b: usize,
57    ascending: bool,
58}
59
60// Batcher's odd-even merge combines two recursively sorted interleaved halves.
61fn odd_even_merge(pairs: &mut Vec<Comparator>, start: usize, count: usize, stride: usize) {
62    let step = stride * 2;
63    if step < count {
64        odd_even_merge(pairs, start, count, step);
65        odd_even_merge(pairs, start + stride, count, step);
66        for a in (start + stride..start + count - stride).step_by(step) {
67            pairs.push(Comparator { a, b: a + stride, ascending: true });
68        }
69    } else {
70        pairs.push(Comparator { a: start, b: start + stride, ascending: true });
71    }
72}
73
74fn odd_even_sort(pairs: &mut Vec<Comparator>, start: usize, count: usize) {
75    if count > 1 {
76        odd_even_sort(pairs, start, count / 2);
77        odd_even_sort(pairs, start + count / 2, count / 2);
78        odd_even_merge(pairs, start, count, 1);
79    }
80}
81
82// Use a short 3x3 selection network. For 5x5, remove identity comparisons with
83// maximal byte padding, then retain only the odd-even network's median ancestors.
84fn network(kernel: u32) -> Vec<Comparator> {
85    if kernel == 3 {
86        // Sort three triples; the median is the median of the largest minimum,
87        // middle median and smallest maximum. The three groups are disjoint.
88        return [
89            (0, 1),
90            (1, 2),
91            (0, 1),
92            (3, 4),
93            (4, 5),
94            (3, 4),
95            (6, 7),
96            (7, 8),
97            (6, 7),
98            (0, 3),
99            (3, 6),
100            (1, 4),
101            (4, 7),
102            (1, 4),
103            (5, 8),
104            (2, 5),
105            (2, 4),
106            (4, 6),
107            (2, 4),
108        ]
109        .into_iter()
110        .map(|(a, b)| Comparator { a, b, ascending: true })
111        .collect();
112    }
113    let count = (kernel * kernel) as usize;
114    let padded = count.next_power_of_two();
115    let mut pairs = Vec::new();
116    odd_even_sort(&mut pairs, 0, padded);
117    // All pairs are ascending with a < b. A suffix of 255-valued padding stays
118    // maximal, so comparisons touching it are identities for every u8 lane.
119    pairs.retain(|pair| pair.b < count);
120    let mut needed = vec![false; padded];
121    needed[count / 2] = true;
122    let mut selected = Vec::new();
123    for pair in pairs.into_iter().rev() {
124        if needed[pair.a] || needed[pair.b] {
125            needed[pair.a] = true;
126            needed[pair.b] = true;
127            selected.push(pair);
128        }
129    }
130    selected.reverse();
131    selected
132}
133
134fn shader(kernel: u32) -> String {
135    let mut source = String::from(include_str!("median_params.wgsl"));
136    source.push_str("@compute @workgroup_size(16, 16)\nfn median(@builtin(global_invocation_id) gid: vec3<u32>) {\nif (gid.x >= params.width || gid.y >= params.height) { return; }\nlet xy = vec2<i32>(gid.xy);\n");
137    let count = kernel * kernel;
138    let radius = (kernel / 2) as i32;
139    for i in 0..count.next_power_of_two() {
140        if i < count {
141            writeln!(
142                source,
143                "var s{i} = sample_at(xy + vec2<i32>({}, {}));",
144                (i % kernel) as i32 - radius,
145                (i / kernel) as i32 - radius
146            )
147            .unwrap();
148        } else {
149            writeln!(source, "var s{i} = vec4<u32>(255u);").unwrap();
150        }
151    }
152    for Comparator { a, b, ascending } in network(kernel) {
153        let (low, high) = if ascending { (a, b) } else { (b, a) };
154        writeln!(source, "{{ let old = s{a}; let other = s{b}; s{low} = min(old, other); s{high} = max(old, other); }}").unwrap();
155    }
156    writeln!(source, "textureStore(output_px, xy, s{});\n}}", count / 2).unwrap();
157    source
158}
159
160pub(crate) struct MedianPipelines {
161    layout: wgpu::BindGroupLayout,
162    kernels: [OnceLock<wgpu::ComputePipeline>; 2],
163}
164
165impl MedianPipelines {
166    fn new(device: &wgpu::Device) -> Self {
167        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
168            label: Some("gpu-median-layout"),
169            entries: &[
170                wgpu::BindGroupLayoutEntry {
171                    binding: 0,
172                    visibility: wgpu::ShaderStages::COMPUTE,
173                    ty: wgpu::BindingType::Buffer {
174                        ty: wgpu::BufferBindingType::Uniform,
175                        has_dynamic_offset: false,
176                        min_binding_size: None,
177                    },
178                    count: None,
179                },
180                wgpu::BindGroupLayoutEntry {
181                    binding: 1,
182                    visibility: wgpu::ShaderStages::COMPUTE,
183                    ty: wgpu::BindingType::Texture {
184                        sample_type: wgpu::TextureSampleType::Uint,
185                        view_dimension: wgpu::TextureViewDimension::D2,
186                        multisampled: false,
187                    },
188                    count: None,
189                },
190                wgpu::BindGroupLayoutEntry {
191                    binding: 2,
192                    visibility: wgpu::ShaderStages::COMPUTE,
193                    ty: wgpu::BindingType::StorageTexture {
194                        access: wgpu::StorageTextureAccess::WriteOnly,
195                        format: wgpu::TextureFormat::Rgba8Uint,
196                        view_dimension: wgpu::TextureViewDimension::D2,
197                    },
198                    count: None,
199                },
200            ],
201        });
202        Self { layout, kernels: std::array::from_fn(|_| OnceLock::new()) }
203    }
204
205    fn kernel(&self, device: &wgpu::Device, kernel: u32) -> &wgpu::ComputePipeline {
206        self.kernels[usize::from(kernel == 5)].get_or_init(|| {
207            let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
208                label: Some("gpu-median-selection"),
209                source: wgpu::ShaderSource::Wgsl(shader(kernel).into()),
210            });
211            let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
212                label: Some("gpu-median-pipeline-layout"),
213                bind_group_layouts: &[&self.layout],
214                push_constant_ranges: &[],
215            });
216            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
217                label: Some("gpu-median"),
218                layout: Some(&layout),
219                module: &module,
220                entry_point: Some("median"),
221                compilation_options: Default::default(),
222                cache: None,
223            })
224        })
225    }
226}
227
228/// Selects the exact per-channel median of a 3x3 or 5x5 square neighborhood.
229/// Supports all 1..=4 logical u8 channels and retains metadata. Each component,
230/// including alpha, is filtered independently.
231/// Replicate and constant-zero borders match the corresponding CPU median.
232/// One ordered device pass returns an owned image without host transfer/wait
233/// or image-sized scratch. Upload/readback remain explicit caller operations.
234/// Runtime, kernel and device limits reject before output/cache allocation.
235pub fn median_blur_gpu(
236    runtime: &WgpuRuntime,
237    source: &GpuImage,
238    kernel_size: u32,
239    border: GpuImageBorder,
240) -> SpatialResult<GpuImage> {
241    source.validate_runtime(runtime)?;
242    let bytes = plan(source.width(), source.height(), kernel_size, &runtime.device().limits())?;
243    let cache =
244        runtime.image_median_pipelines.get_or_init(|| MedianPipelines::new(runtime.device()));
245    let pipeline = cache.kernel(runtime.device(), kernel_size);
246    let output = create_texture(runtime, source.width(), source.height(), "gpu-median-output");
247    let params = Params {
248        width: source.width(),
249        height: source.height(),
250        border: u32::from(border == GpuImageBorder::ConstantZero),
251        padding: 0,
252    };
253    let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
254        label: Some("gpu-median-params"),
255        contents: bytemuck::bytes_of(&params),
256        usage: wgpu::BufferUsages::UNIFORM,
257    });
258    let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
259        label: Some("gpu-median-group"),
260        layout: &cache.layout,
261        entries: &[
262            wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
263            wgpu::BindGroupEntry {
264                binding: 1,
265                resource: wgpu::BindingResource::TextureView(&source.view()),
266            },
267            wgpu::BindGroupEntry {
268                binding: 2,
269                resource: wgpu::BindingResource::TextureView(
270                    &output.create_view(&Default::default()),
271                ),
272            },
273        ],
274    });
275    let mut encoder = runtime.device().create_command_encoder(&Default::default());
276    {
277        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
278            label: Some("median_blur_gpu"),
279            timestamp_writes: None,
280        });
281        pass.set_pipeline(pipeline);
282        pass.set_bind_group(0, &group, &[]);
283        pass.dispatch_workgroups(
284            source.width().div_ceil(WORKGROUP),
285            source.height().div_ceil(WORKGROUP),
286            1,
287        );
288    }
289    runtime.queue().submit(Some(encoder.finish()));
290    let mut receipt = source.receipt().clone();
291    receipt.record_gpu_to_gpu(bytes, "median_blur_gpu");
292    GpuImage::from_parts(
293        runtime,
294        source.width(),
295        source.height(),
296        source.channels(),
297        output,
298        source.metadata(),
299        receipt,
300    )
301}
302
303#[cfg(all(test, not(target_arch = "wasm32")))]
304#[path = "median_tests.rs"]
305mod tests;
306
307#[cfg(all(test, not(target_arch = "wasm32")))]
308#[path = "median_nine_reference.rs"]
309mod nine_reference;
310
311#[cfg(all(test, not(target_arch = "wasm32")))]
312#[path = "median_five_reference.rs"]
313mod five_reference;