Skip to main content

webp/utils/
quant_levels_dec_utils.rs

1// libwebp v1.6.0, src/utils/quant_levels_dec_utils.c:
2//
3// Copyright 2013 Google Inc. All Rights Reserved.
4//
5// Use of this source code is governed by a BSD-style license
6// that can be found in the COPYING file in the root of the source
7// tree. An additional intellectual property rights grant can be found
8// in the file PATENTS. All contributing project authors may
9// be found in the AUTHORS file in the root of the source tree.
10// -----------------------------------------------------------------------------
11//
12// Implement gradient smoothing: we replace a current alpha value by its
13// surrounding average if it's close enough (that is: the change will be less
14// than the minimum distance between two quantized level).
15// We use sliding window for computing the 2d moving average.
16//
17// Author: Skal (pascal.massimino@gmail.com)
18
19// libwebp v1.6.0, src/utils/quant_levels_dec_utils.h:
20//
21// Copyright 2013 Google Inc. All Rights Reserved.
22//
23// Use of this source code is governed by a BSD-style license
24// that can be found in the COPYING file in the root of the source
25// tree. An additional intellectual property rights grant can be found
26// in the file PATENTS. All contributing project authors may
27// be found in the AUTHORS file in the root of the source tree.
28// -----------------------------------------------------------------------------
29//
30// Alpha plane de-quantization utility
31//
32// Author:  Vikas Arora (vikasa@google.com)
33
34//! Translation of `src/utils/quant_levels_dec_utils.c` and `src/utils/quant_levels_dec_utils.h` from libwebp v1.6.0.
35//!
36//! Work package: WP4 (pixel ops).
37//!
38//! # Deviations from upstream
39//!
40//! Changes of representation that the ADRs allow, or behavior that the Rust
41//! side cannot reproduce exactly. Each records the reason.
42//!
43//! 1. **Uninitialized scratch in `WebPDequantizeLevels`.** `VFilter` reads the
44//!    first `2 * radius + 1` rows of its ring before any row has been stored
45//!    there, and the C allocation (`WebPSafeMalloc`) is not initialized.
46//!    Reading it is undefined in C, and Rust zero-initializes the scratch
47//!    (ADR 0003, PORTING rule 8). The probe ran random planes with
48//!    `MallocScribble=1`, which fills allocations with `0xaa`, and the output
49//!    did not change. The differential test compares the C output as the build
50//!    prints it. The probe does not fill the heap itself: a fill before the
51//!    call did not reach the allocation on the development host.
52
53use crate::utils::utils::webp_safe_malloc;
54
55// upstream: src/utils/quant_levels_dec_utils.c FIX
56/// Fixed-point precision for averaging.
57const FIX: u32 = 16;
58// upstream: src/utils/quant_levels_dec_utils.c LFIX
59/// Extra precision for the look-up table.
60const LFIX: i32 = 2;
61// upstream: src/utils/quant_levels_dec_utils.c LUT_SIZE
62/// Look-up table size, on each side of zero.
63const LUT_SIZE: i32 = (1 << (8 + LFIX)) - 1;
64// upstream: src/utils/quant_levels_dec_utils.c DFIX
65/// Extra precision for ordered dithering. Dithering is not compiled
66/// (`USE_DITHERING` is undefined), so the precision is zero.
67const DFIX: i32 = 0;
68
69// upstream: src/utils/quant_levels_dec_utils.c CLIP_8b_MASK
70/// The bits above the byte, which `clip_8b` tests.
71#[expect(
72    clippy::cast_possible_wrap,
73    reason = "the C mask is an int made from an unsigned shift"
74)]
75const CLIP_8B_MASK: i32 = (!0_u32 << (8 + DFIX)) as i32;
76
77// upstream: src/utils/quant_levels_dec_utils.c clip_8b
78/// Clips an `int` to a byte, after the descaling by `DFIX`.
79#[must_use]
80#[expect(
81    clippy::cast_possible_truncation,
82    clippy::cast_sign_loss,
83    reason = "the C conversion keeps the low eight bits of the descaled value"
84)]
85fn clip_8b(v: i32) -> u8 {
86    if (v & CLIP_8B_MASK) == 0 {
87        (v >> DFIX) as u8
88    } else if v < 0 {
89        0
90    } else {
91        255
92    }
93}
94
95/// The low 16 bits of a value, as a C conversion to `uint16_t` keeps them.
96#[must_use]
97#[expect(
98    clippy::cast_possible_truncation,
99    clippy::cast_sign_loss,
100    reason = "the C conversion keeps the low 16 bits, as two's complement for negative values"
101)]
102fn wrap16(value: i32) -> u16 {
103    value as u16
104}
105
106/// The low 16 bits of an unsigned value.
107#[must_use]
108#[expect(
109    clippy::cast_possible_truncation,
110    reason = "the C conversion keeps the low 16 bits"
111)]
112fn low16(value: u32) -> u16 {
113    value as u16
114}
115
116// upstream: src/utils/quant_levels_dec_utils.c SmoothParams
117/// The state of the smoothing filter. The C scratch memory is one allocation:
118/// a ring of `R` rows of accumulated sums, the output row `end` after it, the
119/// horizontal averages and the correction table. The pointers of the C code
120/// become offsets into the ring, the averages and the table (ADR 0003).
121///
122/// `src` and `dst` are the input and output rows of `data`, which the C
123/// pointers `src` and `dst` denote; `dst` lags behind `src` by `radius` rows.
124struct SmoothParams<'a> {
125    /// dimension
126    width: usize,
127    height: usize,
128    /// stride in bytes
129    stride: usize,
130    /// current input row being processed
131    row: i32,
132    /// the plane
133    data: &'a mut [u8],
134    /// offset of the input row
135    src: usize,
136    /// offset of the output row
137    dst: usize,
138    /// filter radius (=delay)
139    radius: i32,
140    /// normalization factor, in FIX bits precision
141    scale: u32,
142    /// the ring of accumulated sums, `(2 * radius + 2)` rows of `width`
143    start: Vec<u16>,
144    /// offsets into `start` of the current row, the previous row and the output row
145    cur: usize,
146    top: usize,
147    end: usize,
148    /// horizontal averages
149    average: Vec<u16>,
150    /// the correction table, of `1 + 2 * LUT_SIZE` entries centered on `LUT_SIZE`
151    correction: Vec<i16>,
152    /// number of quantized levels
153    num_levels: i32,
154    /// min and max level values
155    min: i32,
156    max: i32,
157    /// smallest distance between two consecutive levels
158    min_level_dist: i32,
159}
160
161// upstream: src/utils/quant_levels_dec_utils.c VFilter
162/// Accumulates one input row vertically, and writes the vertical window sum of
163/// the last rows to the output row.
164fn v_filter(p: &mut SmoothParams<'_>) {
165    let w = p.width;
166    let mut sum: u16 = 0; // all arithmetic is modulo 16bit
167    for x in 0..w {
168        sum = sum.wrapping_add(u16::from(p.data[p.src + x]));
169        let new_value = p.start[p.top + x].wrapping_add(sum);
170        let out = p.end + x;
171        p.start[out] = new_value.wrapping_sub(p.start[p.cur + x]); // vertical sum of 'r' pixels.
172        p.start[p.cur + x] = new_value;
173    }
174    // move input pointers one row down
175    p.top = p.cur;
176    p.cur += w;
177    if p.cur == p.end {
178        p.cur = 0; // roll-over
179    }
180    // We replicate edges, as it's somewhat easier as a boundary condition.
181    // That's why we don't update the 'src' pointer on top/bottom area:
182    if p.row >= 0 && p.row < i32::try_from(p.height).expect("the height fits in int") - 1 {
183        p.src += p.stride;
184    }
185}
186
187// upstream: src/utils/quant_levels_dec_utils.c HFilter
188/// Averages the vertical sums of the output row along the rows, with mirrored
189/// edges.
190#[expect(
191    clippy::many_single_char_names,
192    reason = "the C names x, r, w and p of the horizontal filter"
193)]
194fn h_filter(p: &mut SmoothParams<'_>) {
195    let input = p.end;
196    let scale = p.scale;
197    let w = p.width;
198    let r = usize::try_from(p.radius).expect("the radius is positive");
199    let mut x = 0_usize;
200    while x <= r {
201        // left mirroring
202        let delta = p.start[input + x + r - 1].wrapping_add(p.start[input + r - x]);
203        p.average[x] = low16((u32::from(delta).wrapping_mul(scale)) >> FIX);
204        x += 1;
205    }
206    while x + r < w {
207        // bulk middle run
208        let delta = p.start[input + x + r].wrapping_sub(p.start[input + x - r - 1]);
209        p.average[x] = low16((u32::from(delta).wrapping_mul(scale)) >> FIX);
210        x += 1;
211    }
212    while x < w {
213        // right mirroring
214        let a = 2 * i32::from(p.start[input + w - 1]);
215        let b = i32::from(p.start[input + 2 * w - 2 - r - x]);
216        let c = i32::from(p.start[input + x - r - 1]);
217        let delta = wrap16(a - b - c);
218        p.average[x] = low16((u32::from(delta).wrapping_mul(scale)) >> FIX);
219        x += 1;
220    }
221}
222
223// upstream: src/utils/quant_levels_dec_utils.c ApplyFilter
224/// Emits one filtered output row: each sample that lies strictly between the
225/// extreme levels moves towards its horizontal average, by the correction table.
226fn apply_filter(p: &mut SmoothParams<'_>) {
227    let w = p.width;
228    let dst = p.dst;
229    for x in 0..w {
230        let v = i32::from(p.data[dst + x]);
231        if v < p.max && v > p.min {
232            let index = i32::from(p.average[x]) - (v << LFIX);
233            let table =
234                usize::try_from(LUT_SIZE + index).expect("the correction index is in the table");
235            let c = (v << DFIX) + i32::from(p.correction[table]);
236            p.data[dst + x] = clip_8b(c);
237        }
238    }
239    p.dst += p.stride; // advance output pointer
240}
241
242// upstream: src/utils/quant_levels_dec_utils.c InitCorrectionLUT
243/// Fills the correction table. The correction curve is `f(x) = x` up to
244/// `threshold2`, `0` from `threshold1`, and linear in between, with `f(-x) =
245/// -f(x)`; `threshold2` is three quarters of `threshold1`.
246fn init_correction_lut(lut: &mut [i16], min_dist: i32) {
247    let threshold1 = min_dist << LFIX;
248    let threshold2 = (3 * threshold1) >> 2;
249    let max_threshold = threshold2 << DFIX;
250    let delta = threshold1 - threshold2;
251    for i in 1..=LUT_SIZE {
252        let c = if i <= threshold2 {
253            i << DFIX
254        } else if i < threshold1 {
255            max_threshold * (threshold1 - i) / delta
256        } else {
257            0
258        };
259        let c = c >> LFIX;
260        let plus = usize::try_from(LUT_SIZE + i).expect("the table index is positive");
261        let minus = usize::try_from(LUT_SIZE - i).expect("the table index is positive");
262        lut[plus] = i16::try_from(c).expect("a correction fits in 16 bits");
263        lut[minus] = i16::try_from(-c).expect("a correction fits in 16 bits");
264    }
265    lut[usize::try_from(LUT_SIZE).expect("the table centre is positive")] = 0;
266}
267
268// upstream: src/utils/quant_levels_dec_utils.c CountLevels
269/// Finds the range of the plane, its number of levels and the smallest distance
270/// between two of its levels.
271fn count_levels(p: &mut SmoothParams<'_>) {
272    let mut used_levels = [false; 256];
273    p.min = 255;
274    p.max = 0;
275    for j in 0..p.height {
276        let row = p.src + j * p.stride;
277        for i in 0..p.width {
278            let v = i32::from(p.data[row + i]);
279            if v < p.min {
280                p.min = v;
281            }
282            if v > p.max {
283                p.max = v;
284            }
285            used_levels[p.data[row + i] as usize] = true;
286        }
287    }
288    // Compute the mininum distance between two non-zero levels.
289    p.min_level_dist = p.max - p.min;
290    let mut last_level = -1_i32;
291    for (level, &used) in used_levels.iter().enumerate() {
292        let i = i32::try_from(level).expect("a level fits in int");
293        if used {
294            p.num_levels += 1;
295            if last_level >= 0 {
296                let level_dist = i - last_level;
297                if level_dist < p.min_level_dist {
298                    p.min_level_dist = level_dist;
299                }
300            }
301            last_level = i;
302        }
303    }
304}
305
306// upstream: src/utils/quant_levels_dec_utils.c InitParams
307/// Allocates the scratch memory and sets the state of the filter over `data`.
308/// Returns `None` when the allocation fails, which the C code reports as 0.
309fn init_params(
310    data: &mut [u8],
311    width: i32,
312    height: i32,
313    stride: i32,
314    radius: i32,
315) -> Option<SmoothParams<'_>> {
316    let r_size = 2 * radius + 1; // total size of the kernel
317    let width_u = usize::try_from(width).expect("the width is positive");
318    let size_scratch_m = usize::try_from(r_size + 1).expect("the kernel is positive") * width_u * 2;
319    let size_m = width_u * 2;
320    let size_lut = (1 + 2 * usize::try_from(LUT_SIZE).expect("the table size is positive")) * 2;
321    let total_size = size_scratch_m + size_m + size_lut;
322    // The allocation test of WebPSafeMalloc(1U, total_size), which is the same
323    // as the one the C code applies to its scratch memory.
324    webp_safe_malloc::<u8>(1, total_size)?;
325    let rows = usize::try_from(r_size).expect("the kernel is positive");
326    let mut p = SmoothParams {
327        width: width_u,
328        height: usize::try_from(height).expect("the height is positive"),
329        stride: usize::try_from(stride).expect("the stride is positive"),
330        row: -radius,
331        data,
332        src: 0,
333        dst: 0,
334        radius,
335        scale: u32::try_from(
336            (1_i32 << (i32::try_from(FIX).expect("FIX fits in int") + LFIX)) / (r_size * r_size),
337        )
338        .expect("the normalization is positive"),
339        start: vec![0_u16; (rows + 1) * width_u],
340        cur: 0,
341        top: 0,
342        end: rows * width_u,
343        average: vec![0_u16; width_u],
344        correction: vec![
345            0_i16;
346            1 + 2 * usize::try_from(LUT_SIZE).expect("the table size is positive")
347        ],
348        num_levels: 0,
349        min: 0,
350        max: 0,
351        min_level_dist: 0,
352    };
353    // p->top = p->end - width, which is zeroed (the vectors start zeroed).
354    p.top = p.end - width_u;
355    count_levels(&mut p);
356    init_correction_lut(&mut p.correction, p.min_level_dist);
357    Some(p)
358}
359
360// upstream: src/utils/quant_levels_dec_utils.c WebPDequantizeLevels
361/// Smooths a plane that was quantized to a few levels, with a filter whose
362/// radius grows with `strength` (0 to 100). Returns `false` for a missing plane,
363/// a non-positive size, a strength outside `[0, 100]`, or an allocation failure;
364/// the plane is then unchanged.
365///
366/// # Panics
367///
368/// Panics when `data` is shorter than `stride * height` samples.
369#[must_use]
370pub fn webp_dequantize_levels(
371    data: Option<&mut [u8]>,
372    width: i32,
373    height: i32,
374    stride: i32,
375    strength: i32,
376) -> bool {
377    let mut radius = 4 * strength / 100;
378    if !(0..=100).contains(&strength) {
379        return false;
380    }
381    let Some(data) = data else {
382        return false;
383    };
384    if width <= 0 || height <= 0 {
385        return false; // bad params
386    }
387    // limit the filter size to not exceed the image dimensions
388    if 2 * radius + 1 > width {
389        radius = (width - 1) >> 1;
390    }
391    if 2 * radius + 1 > height {
392        radius = (height - 1) >> 1;
393    }
394    if radius > 0 {
395        let Some(mut p) = init_params(data, width, height, stride, radius) else {
396            return false;
397        };
398        if p.num_levels > 2 {
399            while p.row < i32::try_from(p.height).expect("the height fits in int") {
400                v_filter(&mut p); // accumulate average of input
401                // Need to wait few rows in order to prime the filter,
402                // before emitting some output.
403                if p.row >= p.radius {
404                    h_filter(&mut p);
405                    apply_filter(&mut p);
406                }
407                p.row += 1;
408            }
409        }
410    }
411    true
412}