Skip to main content

webp/utils/
quant_levels_utils.rs

1// libwebp v1.6.0, src/utils/quant_levels_utils.c:
2//
3// Copyright 2011 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// Quantize levels for specified number of quantization-levels ([2, 256]).
13// Min and max values are preserved (usual 0 and 255 for alpha plane).
14//
15// Author: Skal (pascal.massimino@gmail.com)
16
17// libwebp v1.6.0, src/utils/quant_levels_utils.h:
18//
19// Copyright 2011 Google Inc. All Rights Reserved.
20//
21// Use of this source code is governed by a BSD-style license
22// that can be found in the COPYING file in the root of the source
23// tree. An additional intellectual property rights grant can be found
24// in the file PATENTS. All contributing project authors may
25// be found in the AUTHORS file in the root of the source tree.
26// -----------------------------------------------------------------------------
27//
28// Alpha plane quantization utility
29//
30// Author:  Vikas Arora (vikasa@google.com)
31
32//! Translation of `src/utils/quant_levels_utils.c` and `src/utils/quant_levels_utils.h` from libwebp v1.6.0.
33//!
34//! Work package: WP4 (pixel ops).
35//!
36//! # Deviations from upstream
37//!
38//! Changes of representation that the ADRs allow, or behavior that the Rust
39//! side cannot reproduce exactly. Each records the reason.
40//!
41//! 1. **`QuantizeLevels` and `WebPDequantizeLevels`.** A NULL plane is `None`,
42//!    and a NULL `sse` is `None`. The early returns leave `sse` and the plane
43//!    unchanged, as in C. The conversions of the rounded centroids to `uint8_t`
44//!    and of the error to `uint64_t` are in range for every valid input.
45//!
46//! # Checks not applicable
47//!
48//! These checks do not apply, or cannot be made, with the reason:
49//!
50//! 1. **Floating point.** `QuantizeLevels` and the SSIM functions
51//!    (`src/dsp/ssim.rs`) are compared bit for bit on the development host
52//!    (arm64, Apple clang, `-ffp-contract=off`). Equality on other hosts is
53//!    recorded, not assumed (`docs/PORTING.md`).
54
55// upstream: src/utils/quant_levels_utils.c NUM_SYMBOLS
56/// The number of symbols of an 8-bit plane.
57const NUM_SYMBOLS: usize = 256;
58// upstream: src/utils/quant_levels_utils.c MAX_ITER
59/// Maximum number of convergence steps.
60const MAX_ITER: i32 = 6;
61// upstream: src/utils/quant_levels_utils.c ERROR_THRESHOLD
62/// MSE stopping criterion, per sample.
63const ERROR_THRESHOLD: f64 = 1.0e-4;
64
65// upstream: src/utils/quant_levels_utils.c QuantizeLevels
66/// Quantizes the levels of an 8-bit plane to `num_levels` values with k-means
67/// steps, and stores the sum of squared error in `sse` when it is given.
68///
69/// Returns `false` for a missing plane, a non-positive size, or a level count
70/// outside `[2, 256]`; the plane and `sse` are then unchanged. The plane is
71/// `width * height` samples, and `data` may be longer.
72///
73/// # Panics
74///
75/// Panics when `data` is shorter than `width * height`.
76#[must_use]
77#[expect(
78    clippy::cast_possible_truncation,
79    clippy::cast_sign_loss,
80    reason = "C casts the rounded centroids to uint8_t and the error to uint64_t"
81)]
82pub fn quantize_levels(
83    data: Option<&mut [u8]>,
84    width: i32,
85    height: i32,
86    num_levels: i32,
87    sse: Option<&mut u64>,
88) -> bool {
89    let Some(data) = data else {
90        return false;
91    };
92    if width <= 0 || height <= 0 {
93        return false;
94    }
95    if !(2..=256).contains(&num_levels) {
96        return false;
97    }
98    let size_int = height * width;
99    let data_size = usize::try_from(size_int).expect("the plane size is positive");
100    let mut freq = [0_i32; NUM_SYMBOLS];
101    let mut q_level = [0_i32; NUM_SYMBOLS];
102    let mut inv_q_level = [0.0_f64; NUM_SYMBOLS];
103    let mut min_s = 255_i32;
104    let mut max_s = 0_i32;
105    let mut num_levels_in = 0_i32;
106    let mut last_err = 1.0e38_f64;
107    let mut err = 0.0_f64;
108    let err_threshold = ERROR_THRESHOLD * f64::from(size_int);
109    for &sample in &data[..data_size] {
110        let value = i32::from(sample);
111        num_levels_in += i32::from(freq[usize::from(sample)] == 0);
112        if min_s > value {
113            min_s = value;
114        }
115        if max_s < value {
116            max_s = value;
117        }
118        freq[usize::from(sample)] += 1;
119    }
120    // nothing to do! when the plane already has few enough levels
121    if num_levels_in > num_levels {
122        // Start with uniformly spread centroids.
123        for i in 0..num_levels {
124            inv_q_level[i as usize] = f64::from(min_s)
125                + f64::from(max_s - min_s) * f64::from(i) / f64::from(num_levels - 1);
126        }
127        // Fixed values. Won't be changed.
128        q_level[min_s as usize] = 0;
129        q_level[max_s as usize] = num_levels - 1;
130        debug_assert_eq!(inv_q_level[0], f64::from(min_s));
131        debug_assert_eq!(inv_q_level[(num_levels - 1) as usize], f64::from(max_s));
132        // k-Means iterations.
133        for _ in 0..MAX_ITER {
134            let mut q_sum = [0.0_f64; NUM_SYMBOLS];
135            let mut q_count = [0.0_f64; NUM_SYMBOLS];
136            let mut slot = 0_i32;
137            // Assign classes to representatives.
138            for s in min_s..=max_s {
139                // Keep track of the nearest neighbour 'slot'
140                while slot < num_levels - 1
141                    && f64::from(2 * s)
142                        > inv_q_level[slot as usize] + inv_q_level[(slot + 1) as usize]
143                {
144                    slot += 1;
145                }
146                if freq[s as usize] > 0 {
147                    q_sum[slot as usize] += f64::from(s * freq[s as usize]);
148                    q_count[slot as usize] += f64::from(freq[s as usize]);
149                }
150                q_level[s as usize] = slot;
151            }
152            // Assign new representatives to classes.
153            if num_levels > 2 {
154                for slot in 1..num_levels - 1 {
155                    let count = q_count[slot as usize];
156                    if count > 0.0 {
157                        inv_q_level[slot as usize] = q_sum[slot as usize] / count;
158                    }
159                }
160            }
161            // Compute convergence error.
162            err = 0.0;
163            for s in min_s..=max_s {
164                let error = f64::from(s) - inv_q_level[q_level[s as usize] as usize];
165                err += f64::from(freq[s as usize]) * error * error;
166            }
167            // Check for convergence: we stop as soon as the error is no
168            // longer improving.
169            if last_err - err < err_threshold {
170                break;
171            }
172            last_err = err;
173        }
174        // Remap the alpha plane to quantized values.
175        let mut map = [0_u8; NUM_SYMBOLS];
176        for s in min_s..=max_s {
177            let slot = q_level[s as usize];
178            map[s as usize] = (inv_q_level[slot as usize] + 0.5) as u8;
179        }
180        // Final pass.
181        for sample in &mut data[..data_size] {
182            *sample = map[usize::from(*sample)];
183        }
184    }
185    // Store sum of squared error if needed.
186    if let Some(sse) = sse {
187        *sse = err as u64;
188    }
189    true
190}