Skip to main content

spatialrust_gpu/image/kernels/
box_blur.rs

1//! Exact integer gray box blur with bounded device-resident separable sums.
2
3use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult};
5use std::sync::OnceLock;
6use wgpu::util::DeviceExt;
7
8use crate::image::gpu_image::{create_texture, GpuImage};
9use crate::{scratch::ScratchBuffers, GpuStageProfiler, WgpuRuntime};
10
11const WORKGROUP: u32 = 256;
12const SEPARABLE_MIN_AREA: u64 = 81;
13const SEPARABLE_MIN_SAMPLES: u64 = 65_536;
14const ROW_PREFIX_BYTES: u32 = 4096 * 4;
15const SHADERS: [&str; 7] = [
16    include_str!("box_blur_serial.wgsl"),
17    concat!(include_str!("box_blur_params.wgsl"), include_str!("box_blur_horizontal.wgsl")),
18    concat!(include_str!("box_blur_params.wgsl"), include_str!("box_blur_vertical.wgsl")),
19    concat!(include_str!("box_blur_params.wgsl"), include_str!("box_blur_packed_horizontal.wgsl")),
20    concat!(include_str!("box_blur_params.wgsl"), include_str!("box_blur_packed_vertical.wgsl")),
21    concat!(include_str!("box_blur_params.wgsl"), include_str!("box_blur_row_prefix.wgsl")),
22    concat!(include_str!("box_blur_params.wgsl"), include_str!("box_blur_column_prefix.wgsl")),
23];
24
25fn row_prefix_enabled(width: u32, height: u32, kw: u32, limits: &wgpu::Limits) -> bool {
26    (512..=4096).contains(&width)
27        && height >= 128
28        && kw >= 259
29        && limits.max_compute_workgroup_storage_size >= ROW_PREFIX_BYTES
30}
31
32fn column_prefix_enabled(width: u32, height: u32, kw: u32, kh: u32, limits: &wgpu::Limits) -> bool {
33    width >= 128
34        && (512..=4096).contains(&height)
35        && kw >= 259
36        && kh >= 259
37        && u64::from(height) * u64::from(kw) * 255 <= u64::from(u32::MAX)
38        && limits.max_compute_workgroup_storage_size >= ROW_PREFIX_BYTES
39}
40
41/// Border extrapolation for GPU image filters.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum GpuImageBorder {
44    /// Clamp coordinates to the nearest valid edge pixel (replicate).
45    Replicate,
46    /// Treat out-of-bounds samples as zero.
47    ConstantZero,
48}
49
50#[repr(C)]
51#[derive(Clone, Copy, Pod, Zeroable)]
52struct BlurParams {
53    width: u32,
54    height: u32,
55    kernel_width: u32,
56    kernel_height: u32,
57    border_mode: u32,
58    groups: u32,
59    pixel_count: u32,
60    _pad: u32,
61}
62
63struct Plan {
64    params: BlurParams,
65    separable: bool,
66    bytes: u64,
67    scratch_bytes: u64,
68    packed: bool,
69}
70
71pub(crate) fn blur_pass_count(
72    width: u32,
73    height: u32,
74    kernel_width: u32,
75    kernel_height: u32,
76) -> u32 {
77    let area = u64::from(kernel_width) * u64::from(kernel_height);
78    let count = u64::from(width) * u64::from(height);
79    // Compare via division so even unvalidated profiler inputs cannot overflow.
80    1 + u32::from(area >= SEPARABLE_MIN_AREA && count >= SEPARABLE_MIN_SAMPLES.div_ceil(area))
81}
82
83fn plan(
84    width: u32,
85    height: u32,
86    kw: u32,
87    kh: u32,
88    border: GpuImageBorder,
89    limits: &wgpu::Limits,
90) -> SpatialResult<Plan> {
91    let invalid = || {
92        SpatialError::InvalidArgument(
93        "GPU box blur requires positive odd kernels, supported texture/compute limits, bounded u32 pixels/sums and supported separable scratch".to_owned())
94    };
95    let count = u64::from(width) * u64::from(height);
96    let area = u64::from(kw) * u64::from(kh);
97    let separable = blur_pass_count(width, height, kw, kh) == 2;
98    let bytes = count.checked_mul(4).ok_or_else(invalid)?;
99    if width == 0
100        || height == 0
101        || kw == 0
102        || kh == 0
103        || kw % 2 == 0
104        || kh % 2 == 0
105        || count > u64::from(u32::MAX)
106        || area > u64::from(u32::MAX) / 255
107        || area * 255 + area / 2 > u64::from(u32::MAX)
108        || width > limits.max_texture_dimension_2d
109        || height > limits.max_texture_dimension_2d
110        || width > i32::MAX as u32
111        || height > i32::MAX as u32
112        || u64::from(width - 1) + u64::from(kw / 2) > i32::MAX as u64
113        || u64::from(height - 1) + u64::from(kh / 2) > i32::MAX as u64
114        || limits.max_compute_invocations_per_workgroup < WORKGROUP
115        || limits.max_compute_workgroup_size_x < WORKGROUP
116        || limits.max_compute_workgroups_per_dimension == 0
117        || limits.max_sampled_textures_per_shader_stage == 0
118        || limits.max_storage_textures_per_shader_stage == 0
119        || limits.max_uniform_buffers_per_shader_stage == 0
120        || limits.max_uniform_buffer_binding_size < std::mem::size_of::<BlurParams>() as u32
121        || (separable
122            && (limits.max_storage_buffers_per_shader_stage == 0
123                || bytes
124                    > limits
125                        .max_buffer_size
126                        .min(u64::from(limits.max_storage_buffer_binding_size))))
127    {
128        return Err(invalid());
129    }
130    let groups = (count as u32)
131        .div_ceil(WORKGROUP)
132        .min(4096)
133        .min(limits.max_compute_workgroups_per_dimension);
134    // The original checks above still validate the full uncompressed extent.
135    let packed = separable && kw <= 257;
136    let scratch_bytes = if packed { count.div_ceil(2) * 4 } else { bytes };
137    Ok(Plan {
138        params: BlurParams {
139            width,
140            height,
141            kernel_width: kw,
142            kernel_height: kh,
143            border_mode: u32::from(border == GpuImageBorder::ConstantZero),
144            groups,
145            pixel_count: count as u32,
146            _pad: 0,
147        },
148        separable,
149        bytes,
150        scratch_bytes,
151        packed,
152    })
153}
154
155struct Variant {
156    layout: wgpu::BindGroupLayout,
157    pipeline: wgpu::ComputePipeline,
158}
159
160pub(crate) struct BlurPipeline {
161    variants: [OnceLock<Variant>; 7],
162}
163
164impl BlurPipeline {
165    fn new() -> Self {
166        Self { variants: std::array::from_fn(|_| OnceLock::new()) }
167    }
168
169    fn variant(&self, device: &wgpu::Device, index: usize) -> &Variant {
170        self.variants[index].get_or_init(|| {
171            let buffer = |ty| wgpu::BindingType::Buffer {
172                ty,
173                has_dynamic_offset: false,
174                min_binding_size: None,
175            };
176            let texture = wgpu::BindingType::Texture {
177                sample_type: wgpu::TextureSampleType::Uint,
178                view_dimension: wgpu::TextureViewDimension::D2,
179                multisampled: false,
180            };
181            let output = wgpu::BindingType::StorageTexture {
182                access: wgpu::StorageTextureAccess::WriteOnly,
183                format: wgpu::TextureFormat::Rgba8Uint,
184                view_dimension: wgpu::TextureViewDimension::D2,
185            };
186            let types = [
187                buffer(wgpu::BufferBindingType::Uniform),
188                if matches!(index, 2 | 4 | 6) {
189                    buffer(wgpu::BufferBindingType::Storage { read_only: true })
190                } else {
191                    texture
192                },
193                if matches!(index, 1 | 3 | 5) {
194                    buffer(wgpu::BufferBindingType::Storage { read_only: false })
195                } else {
196                    output
197                },
198            ];
199            let entries: Vec<_> = types
200                .into_iter()
201                .enumerate()
202                .map(|(binding, ty)| wgpu::BindGroupLayoutEntry {
203                    binding: binding as u32,
204                    visibility: wgpu::ShaderStages::COMPUTE,
205                    ty,
206                    count: None,
207                })
208                .collect();
209            let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
210                label: Some("gpu-blur-bgl"),
211                entries: &entries,
212            });
213            let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
214                label: Some("gpu-blur-shader"),
215                source: wgpu::ShaderSource::Wgsl(SHADERS[index].into()),
216            });
217            let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
218                label: Some("gpu-blur-pl"),
219                bind_group_layouts: &[&layout],
220                push_constant_ranges: &[],
221            });
222            let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
223                label: Some("gpu-blur-pipeline"),
224                layout: Some(&pipeline_layout),
225                module: &shader,
226                entry_point: Some("main"),
227                compilation_options: Default::default(),
228                cache: None,
229            });
230            Variant { layout, pipeline }
231        })
232    }
233}
234
235#[allow(clippy::too_many_arguments)]
236fn encode(
237    runtime: &WgpuRuntime,
238    cache: &BlurPipeline,
239    p: &Plan,
240    source: &wgpu::TextureView,
241    output: &wgpu::TextureView,
242    uniform: &wgpu::Buffer,
243    sums: Option<&wgpu::Buffer>,
244    encoder: &mut wgpu::CommandEncoder,
245    mut profiler: Option<&mut GpuStageProfiler>,
246) {
247    let limits = runtime.device().limits();
248    let horizontal =
249        if row_prefix_enabled(p.params.width, p.params.height, p.params.kernel_width, &limits) {
250            5
251        } else {
252            1
253        };
254    let vertical = if column_prefix_enabled(
255        p.params.width,
256        p.params.height,
257        p.params.kernel_width,
258        p.params.kernel_height,
259        &limits,
260    ) {
261        6
262    } else {
263        2
264    };
265    let indices: &[usize] = if p.packed {
266        &[3, 4]
267    } else if p.separable {
268        &[horizontal, vertical]
269    } else {
270        &[0]
271    };
272    for &index in indices {
273        let variant = cache.variant(runtime.device(), index);
274        let input = if matches!(index, 2 | 4 | 6) {
275            sums.unwrap().as_entire_binding()
276        } else {
277            wgpu::BindingResource::TextureView(source)
278        };
279        let target = if matches!(index, 1 | 3 | 5) {
280            sums.unwrap().as_entire_binding()
281        } else {
282            wgpu::BindingResource::TextureView(output)
283        };
284        let stage =
285            if matches!(index, 1 | 3 | 5) { "box_blur_horizontal_gpu" } else { "box_blur_gpu" };
286        let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
287            label: Some(stage),
288            layout: &variant.layout,
289            entries: &[
290                wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
291                wgpu::BindGroupEntry { binding: 1, resource: input },
292                wgpu::BindGroupEntry { binding: 2, resource: target },
293            ],
294        });
295        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
296            label: Some(stage),
297            timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, stage),
298        });
299        pass.set_pipeline(&variant.pipeline);
300        pass.set_bind_group(0, &group, &[]);
301        pass.dispatch_workgroups(p.params.groups, 1, 1);
302    }
303}
304
305/// Applies an integer mean box blur to a single-channel `GpuImage`.
306///
307/// Positive odd kernels round half upward once after summing the entire box.
308/// Boxes with area at least 81 and at least 65,536 total pixel/sample visits
309/// use two passes. Widths up to 257 pack two exact horizontal sums per u32
310/// (four scratch bytes per pixel pair); wider kernels keep four bytes per
311/// pixel. Smaller workloads use one pass. Transfers stay explicit and bounded.
312pub fn box_blur_gpu(
313    runtime: &WgpuRuntime,
314    source: &GpuImage,
315    kernel_width: u32,
316    kernel_height: u32,
317    border: GpuImageBorder,
318) -> SpatialResult<GpuImage> {
319    box_blur_gpu_with_profiler(runtime, source, kernel_width, kernel_height, border, None)
320}
321
322pub(crate) fn box_blur_gpu_with_profiler(
323    runtime: &WgpuRuntime,
324    source: &GpuImage,
325    kernel_width: u32,
326    kernel_height: u32,
327    border: GpuImageBorder,
328    profiler: Option<&mut GpuStageProfiler>,
329) -> SpatialResult<GpuImage> {
330    source.validate_runtime(runtime)?;
331    if source.channels() != 1 {
332        return Err(SpatialError::InvalidArgument(
333            "GPU box blur requires one logical channel".to_owned(),
334        ));
335    }
336    let p = plan(
337        source.width(),
338        source.height(),
339        kernel_width,
340        kernel_height,
341        border,
342        &runtime.device().limits(),
343    )?;
344    let cache = runtime.image_blur_pipeline.get_or_init(BlurPipeline::new);
345    let mut scratch = ScratchBuffers::new(runtime);
346    let sums = p.separable.then(|| scratch.acquire("gpu-blur-horizontal-sums", p.scratch_bytes));
347    let output = create_texture(runtime, source.width(), source.height(), "gpu-image-blur-out");
348    let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
349        label: Some("gpu-image-blur-params"),
350        contents: bytemuck::bytes_of(&p.params),
351        usage: wgpu::BufferUsages::UNIFORM,
352    });
353    let mut encoder = runtime.device().create_command_encoder(&Default::default());
354    encode(
355        runtime,
356        cache,
357        &p,
358        &source.view(),
359        &output.create_view(&Default::default()),
360        &uniform,
361        sums.as_ref(),
362        &mut encoder,
363        profiler,
364    );
365    scratch.submit_and_recycle(encoder);
366    let mut receipt = source.receipt().clone();
367    if p.separable {
368        receipt.record_gpu_to_gpu(p.scratch_bytes, "box_blur_horizontal_gpu");
369    }
370    receipt.record_gpu_to_gpu(p.bytes, "box_blur_gpu");
371    GpuImage::from_parts(
372        runtime,
373        source.width(),
374        source.height(),
375        1,
376        output,
377        source.metadata(),
378        receipt,
379    )
380}
381
382#[cfg(all(test, not(target_arch = "wasm32")))]
383#[path = "box_blur_tests.rs"]
384mod tests;