Skip to main content

ditherlib/effects/
blur.rs

1use crate::{DitherError, Effect, ErrorKind, Mask, Result};
2
3/// A fast three-pass approximation of Gaussian blur.
4///
5/// The blur reads the selected bounds plus a sampling margin before the
6/// renderer composites the selected area. Nearby pixels outside a selection
7/// can therefore influence the blurred pixels inside it. RGB channels are
8/// blurred directly and every alpha value is preserved from the source pixel.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct Blur {
11    sigma: f32,
12}
13
14impl Blur {
15    /// Creates a Gaussian blur. A sigma of zero produces an unchanged image.
16    ///
17    /// # Errors
18    ///
19    /// Returns [`ErrorKind::InvalidParameter`] when `sigma` is negative,
20    /// non-finite, or subnormal.
21    pub fn new(sigma: f32) -> Result<Self> {
22        if sigma != 0.0 && (!sigma.is_normal() || sigma.is_sign_negative()) {
23            return Err(DitherError::new(
24                ErrorKind::InvalidParameter,
25                "blur sigma must be zero or a positive normal number",
26            ));
27        }
28
29        Ok(Self { sigma })
30    }
31
32    /// Returns the Gaussian standard deviation in pixels.
33    pub const fn sigma(&self) -> f32 {
34        self.sigma
35    }
36}
37
38impl Effect for Blur {
39    fn apply(
40        &self,
41        input: &[u8],
42        output: &mut [u8],
43        dimensions: (u32, u32),
44        mask: &Mask,
45    ) -> Result<()> {
46        if self.sigma == 0.0 {
47            return Ok(());
48        }
49
50        let expected_length = rgba8_length(dimensions);
51        if mask.dimensions() != dimensions
52            || expected_length != Some(input.len())
53            || expected_length != Some(output.len())
54        {
55            return Err(DitherError::new(
56                ErrorKind::DimensionMismatch,
57                "blur buffers and mask must share image dimensions",
58            ));
59        }
60        let Some(bounds) = mask.coverage_bounds() else {
61            return Ok(());
62        };
63        let crop_bounds = expand_bounds(bounds, dimensions, sampling_margin(self.sigma));
64        let image = crop_image(input, dimensions.0, crop_bounds)?;
65        let blurred = image::imageops::fast_blur(&image, self.sigma);
66
67        copy_blurred_selection(
68            input,
69            output,
70            dimensions.0,
71            bounds,
72            crop_bounds,
73            blurred.as_raw(),
74            mask,
75        );
76
77        Ok(())
78    }
79}
80
81type Bounds = (u32, u32, u32, u32);
82
83/// Calculates the addressable byte length of an RGBA8 image.
84fn rgba8_length(dimensions: (u32, u32)) -> Option<usize> {
85    u64::from(dimensions.0)
86        .checked_mul(u64::from(dimensions.1))?
87        .checked_mul(4)?
88        .try_into()
89        .ok()
90}
91
92/// Returns a conservative sampling margin for the three box-blur passes.
93fn sampling_margin(sigma: f32) -> u32 {
94    ((sigma * 4.0).ceil() as u32).saturating_add(3)
95}
96
97/// Expands selection bounds by a sampling margin and clips them to the image.
98fn expand_bounds(bounds: Bounds, dimensions: (u32, u32), margin: u32) -> Bounds {
99    (
100        bounds.0.saturating_sub(margin),
101        bounds.1.saturating_sub(margin),
102        bounds.2.saturating_add(margin).min(dimensions.0),
103        bounds.3.saturating_add(margin).min(dimensions.1),
104    )
105}
106
107/// Copies RGB channels into a private buffer; source alpha is preserved later.
108fn crop_image(input: &[u8], image_width: u32, bounds: Bounds) -> Result<image::RgbImage> {
109    let width = bounds.2 - bounds.0;
110    let height = bounds.3 - bounds.1;
111    let row_length = width as usize * 4;
112    let mut pixels = Vec::with_capacity(width as usize * height as usize * 3);
113
114    for y in bounds.1..bounds.3 {
115        let start = (y as usize * image_width as usize + bounds.0 as usize) * 4;
116        for pixel in input[start..start + row_length].as_chunks::<4>().0 {
117            pixels.extend_from_slice(&pixel[..3]);
118        }
119    }
120
121    image::RgbImage::from_raw(width, height, pixels).ok_or_else(|| {
122        DitherError::new(
123            ErrorKind::DimensionMismatch,
124            "blur input does not match its image dimensions",
125        )
126    })
127}
128
129/// Copies blurred RGB values for the selected bounds while preserving alpha.
130fn copy_blurred_selection(
131    input: &[u8],
132    output: &mut [u8],
133    image_width: u32,
134    selection: Bounds,
135    crop: Bounds,
136    blurred: &[u8],
137    mask: &Mask,
138) {
139    let crop_width = crop.2 - crop.0;
140
141    for y in selection.1..selection.3 {
142        for x in selection.0..selection.2 {
143            let pixel_index = y as usize * image_width as usize + x as usize;
144            if mask.coverage_bytes()[pixel_index] == 0 {
145                continue;
146            }
147            let image_index = pixel_index * 4;
148            let crop_index =
149                ((y - crop.1) as usize * crop_width as usize + (x - crop.0) as usize) * 3;
150            output[image_index..image_index + 3]
151                .copy_from_slice(&blurred[crop_index..crop_index + 3]);
152            output[image_index + 3] = input[image_index + 3];
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::Blur;
160    use crate::{Effect, ErrorKind, Mask, Point, Polygon, Renderer, Selection, SourceImage};
161
162    /// Creates an immutable image from test pixels.
163    fn source(width: u32, height: u32, pixels: &[[u8; 4]]) -> SourceImage {
164        SourceImage {
165            width,
166            height,
167            pixels: pixels
168                .iter()
169                .flatten()
170                .copied()
171                .collect::<Vec<_>>()
172                .into_boxed_slice(),
173        }
174    }
175
176    #[test]
177    fn validates_sigma() {
178        assert_eq!(Blur::new(0.0).unwrap().sigma(), 0.0);
179        assert_eq!(Blur::new(1.5).unwrap().sigma(), 1.5);
180
181        for invalid in [-1.0, f32::NAN, f32::INFINITY, f32::MIN_POSITIVE / 2.0] {
182            assert_eq!(
183                Blur::new(invalid).unwrap_err().kind(),
184                ErrorKind::InvalidParameter
185            );
186        }
187    }
188
189    #[test]
190    fn zero_sigma_leaves_pixels_unchanged() {
191        let source = source(2, 1, &[[1, 2, 3, 4], [5, 6, 7, 8]]);
192        let rendered = Renderer::new()
193            .render(&source, &Blur::new(0.0).unwrap(), &Selection::All)
194            .unwrap();
195
196        assert_eq!(rendered.rgba8_bytes(), source.rgba8_bytes());
197    }
198
199    #[test]
200    fn blurs_across_image_boundaries_and_preserves_alpha() {
201        let source = source(3, 1, &[[0, 0, 0, 10], [255, 255, 255, 20], [0, 0, 0, 30]]);
202        let rendered = Renderer::new()
203            .render(&source, &Blur::new(1.0).unwrap(), &Selection::All)
204            .unwrap();
205        let left = rendered.pixel(0, 0).unwrap();
206        let centre = rendered.pixel(1, 0).unwrap();
207        let right = rendered.pixel(2, 0).unwrap();
208
209        assert_eq!(&left[..3], &right[..3]);
210        assert!(left[0] > 0);
211        assert!(centre[0] < 255);
212        assert!(centre[0] > 0);
213        assert_eq!([left[3], centre[3], right[3]], [10, 20, 30]);
214    }
215
216    #[test]
217    fn uses_exterior_samples_but_preserves_exterior_pixels() {
218        let mut pixels = [[255, 255, 255, 90]; 9];
219        pixels[4] = [0, 0, 0, 40];
220        let source = source(3, 3, &pixels);
221        let original = source.rgba8_bytes().to_vec();
222        let polygon = Polygon::new([
223            Point::new(1.0, 1.0),
224            Point::new(2.0, 1.0),
225            Point::new(2.0, 2.0),
226            Point::new(1.0, 2.0),
227        ])
228        .unwrap();
229        let rendered = Renderer::new()
230            .render(
231                &source,
232                &Blur::new(1.0).unwrap(),
233                &Selection::Polygon(polygon),
234            )
235            .unwrap();
236
237        assert!(rendered.pixel(1, 1).unwrap()[0] > 0);
238        assert_eq!(rendered.pixel(1, 1).unwrap()[3], 40);
239        for y in 0..3 {
240            for x in 0..3 {
241                if (x, y) != (1, 1) {
242                    assert_eq!(rendered.pixel(x, y), Some([255, 255, 255, 90]));
243                }
244            }
245        }
246        assert_eq!(source.rgba8_bytes(), original);
247    }
248
249    #[test]
250    fn cropped_blur_matches_full_image_blur_inside_the_selection() {
251        let pixels = (0..900)
252            .map(|index| {
253                let value = (index % 251) as u8;
254                [value, value.wrapping_add(40), value.wrapping_add(80), 123]
255            })
256            .collect::<Vec<_>>();
257        let source = source(30, 30, &pixels);
258        let full_image = image::RgbaImage::from_raw(30, 30, source.rgba8_bytes().to_vec()).unwrap();
259        let full_blur = image::imageops::fast_blur(&full_image, 1.0);
260        let polygon = Polygon::new([
261            Point::new(14.0, 14.0),
262            Point::new(16.0, 14.0),
263            Point::new(16.0, 16.0),
264            Point::new(14.0, 16.0),
265        ])
266        .unwrap();
267        let rendered = Renderer::new()
268            .render(
269                &source,
270                &Blur::new(1.0).unwrap(),
271                &Selection::Polygon(polygon),
272            )
273            .unwrap();
274
275        for y in 14..16 {
276            for x in 14..16 {
277                let expected = full_blur.get_pixel(x, y).0;
278                assert_eq!(rendered.pixel(x, y).unwrap()[..3], expected[..3]);
279                assert_eq!(rendered.pixel(x, y).unwrap()[3], 123);
280            }
281        }
282    }
283
284    #[test]
285    fn rgb_blur_matches_rgba_blur_with_varied_alpha_and_masks() {
286        for (width, height) in [(0, 0), (1, 1), (1, 31), (31, 1), (17, 19), (65, 49)] {
287            let input: Vec<u8> = (0..width * height)
288                .flat_map(|i| {
289                    [
290                        ((i * 97 + 13) % 256) as u8,
291                        ((i * 53 + 129) % 256) as u8,
292                        ((i * 193 + 251) % 256) as u8,
293                        (i * 73 % 256) as u8,
294                    ]
295                })
296                .collect();
297            let rgba = image::RgbaImage::from_raw(width, height, input.clone()).unwrap();
298            for sigma in [0.0, 0.1, 0.7, 1.0, 2.5, 8.0, 20.0] {
299                let reference = if sigma == 0.0 {
300                    rgba.clone()
301                } else {
302                    image::imageops::fast_blur(&rgba, sigma)
303                };
304                for mask_kind in 0..4 {
305                    let coverage: Vec<u8> = (0..width * height)
306                        .map(|i| match mask_kind {
307                            0 => 255,
308                            1 => 0,
309                            2 if (width / 3..width * 2 / 3).contains(&(i % width))
310                                && (height / 3..height * 2 / 3).contains(&(i / width)) =>
311                            {
312                                ((i * 37 + 1) % 256) as u8
313                            }
314                            3 if i % 5 == 0 => 255,
315                            _ => 0,
316                        })
317                        .collect();
318                    let mask = Mask::new(width, height, coverage).unwrap();
319                    let mut output = input.clone();
320                    Blur::new(sigma)
321                        .unwrap()
322                        .apply(&input, &mut output, (width, height), &mask)
323                        .unwrap();
324                    let mut expected = input.clone();
325                    for (i, pixel) in expected.as_chunks_mut::<4>().0.iter_mut().enumerate() {
326                        if mask.coverage_bytes()[i] != 0 {
327                            pixel[..3].copy_from_slice(&reference.as_raw()[i * 4..i * 4 + 3]);
328                        }
329                    }
330                    assert_eq!(
331                        output, expected,
332                        "{width}x{height}, sigma={sigma}, mask={mask_kind}"
333                    );
334                }
335            }
336        }
337    }
338}