Skip to main content

webp/dsp/
lossless_common.rs

1// libwebp v1.6.0, src/dsp/lossless_common.h:
2//
3// Copyright 2012 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// Image transforms and color space conversion methods for lossless decoder.
13//
14// Authors: Vikas Arora (vikaas.arora@gmail.com)
15//          Jyrki Alakuijala (jyrki@google.com)
16//          Vincent Rabaud (vrabaud@google.com)
17
18//! Translation of `src/dsp/lossless_common.h` from libwebp v1.6.0.
19//!
20//! Work package: WP3 (lossless shared).
21//!
22//! Exception: WP11 translates `VP8LFastLog2`, `VP8LFastSLog2`, `VP8LPrefixEncodeBits` and `VP8LPrefixEncode` from `src/dsp/lossless_common.h`, because they read `kLog2Table`, `kSLog2Table`, `VP8LFastLog2Slow`, `VP8LFastSLog2Slow`, `kPrefixEncodeCode` and `kPrefixEncodeExtraBitsValue`, which WP11 translates from `src/dsp/lossless_enc.c`.
23//!
24//! Not translated here, with the reason: the four functions of the exception
25//! above, which WP11 appends to this module with the tables they read
26//! (decided 2026-11-06). The declarations of those tables and slow functions
27//! belong with their definitions in `src/dsp/lossless_enc.rs`.
28//!
29//! # Deviations from upstream
30//!
31//! Changes of representation that the ADRs allow, or behavior that the Rust
32//! side cannot reproduce exactly. Each records the reason.
33//!
34//! 1. **`GENERATE_PREDICTOR_ADD`** is a `macro_rules!` macro of this module,
35//!    re-exported to the crate, which generates functions of the decoder form.
36//!    The C `assert(upper != NULL)` has no counterpart, because positions
37//!    cannot be `NULL`; the left position is formed with a wrapping
38//!    subtraction, as the C `&out[x - 1]` is formed, and only read by the
39//!    predictors that read it.
40//!
41//! # Excluded undefined behavior
42//!
43//! `VP8LSubSampleSize`, `RightShiftRound`, `DivRound` and the prefix encodings
44//! exclude inputs that are undefined behavior in C; they are listed in
45//! `src/utils/color_cache_utils.rs`, `# Excluded undefined behavior` (item 1).
46//!
47//! # Checks not applicable
48//!
49//! These checks do not apply, or cannot be made, with the reason:
50//!
51//! 1. **Floating point.** No translated function of the lossless utilities
52//!    computes in floating point. `LOG_2_RECIPROCAL` and
53//!    `LOG_2_RECIPROCAL_FIXED_DOUBLE` are constants and are compared as bit
54//!    patterns.
55
56use crate::utils::utils::bits_log2_floor;
57
58//------------------------------------------------------------------------------
59// Decoding
60
61// upstream: src/dsp/lossless_common.h VP8GetARGBIndex
62/// Color mapping related functions.
63#[must_use]
64#[inline]
65pub fn vp8_get_argb_index(idx: u32) -> u32 {
66    (idx >> 8) & 0xff
67}
68
69// upstream: src/dsp/lossless_common.h VP8GetAlphaIndex
70#[must_use]
71#[inline]
72pub fn vp8_get_alpha_index(idx: u8) -> u8 {
73    idx
74}
75
76// upstream: src/dsp/lossless_common.h VP8GetARGBValue
77#[must_use]
78#[inline]
79pub fn vp8_get_argb_value(val: u32) -> u32 {
80    val
81}
82
83// upstream: src/dsp/lossless_common.h VP8GetAlphaValue
84#[must_use]
85#[inline]
86pub fn vp8_get_alpha_value(val: u32) -> u8 {
87    ((val >> 8) & 0xff) as u8
88}
89
90//------------------------------------------------------------------------------
91// Misc methods.
92
93// upstream: src/dsp/lossless_common.h VP8LSubSampleSize
94/// Computes sampled size of `size` when sampling using `sampling_bits`.
95/// The `uint32_t` sum wraps, as in C.
96#[must_use]
97#[inline]
98pub fn vp8l_sub_sample_size(size: u32, sampling_bits: u32) -> u32 {
99    size.wrapping_add(1 << sampling_bits).wrapping_sub(1) >> sampling_bits
100}
101
102// upstream: src/dsp/lossless_common.h VP8LNearLosslessBits
103/// Converts near lossless quality into max number of bits shaved off.
104#[must_use]
105pub fn vp8l_near_lossless_bits(near_lossless_quality: i32) -> i32 {
106    //    100 -> 0
107    // 80..99 -> 1
108    // 60..79 -> 2
109    // 40..59 -> 3
110    // 20..39 -> 4
111    //  0..19 -> 5
112    5 - near_lossless_quality / 20
113}
114
115// -----------------------------------------------------------------------------
116// Faster logarithm for integers. Small values use a look-up table.
117
118// upstream: src/dsp/lossless_common.h APPROX_LOG_WITH_CORRECTION_MAX
119/// The threshold till approximate version of `log_2` can be used.
120/// Practically, we can get rid of the call to `log()` as the two values match
121/// to very high degree (the ratio of these two is 0.99999x).
122/// Keeping a high threshold for now.
123pub const APPROX_LOG_WITH_CORRECTION_MAX: i32 = 65536;
124// upstream: src/dsp/lossless_common.h APPROX_LOG_MAX
125pub const APPROX_LOG_MAX: i32 = 4096;
126// upstream: src/dsp/lossless_common.h LOG_2_PRECISION_BITS
127/// `VP8LFastLog2` and `VP8LFastSLog2` are used on elements from image
128/// histograms. The histogram values cannot exceed the maximum number of
129/// pixels, which is (1 << 14) * (1 << 14). Therefore S * log(S) < (1 << 33).
130/// No more than 32 bits of precision should be chosen.
131/// To match the original float implementation, 23 bits of precision are used.
132pub const LOG_2_PRECISION_BITS: i32 = 23;
133// upstream: src/dsp/lossless_common.h LOG_2_RECIPROCAL
134#[expect(clippy::approx_constant, reason = "the C literal of LOG_2_RECIPROCAL")]
135pub const LOG_2_RECIPROCAL: f64 = 1.442_695_040_888_963_387_004_650_940_070_86;
136// upstream: src/dsp/lossless_common.h LOG_2_RECIPROCAL_FIXED_DOUBLE
137/// `LOG_2_RECIPROCAL * (1 << LOG_2_PRECISION_BITS)`
138pub const LOG_2_RECIPROCAL_FIXED_DOUBLE: f64 = 12_102_203.161_561_485_379_934_310_913_085_937_500;
139// upstream: src/dsp/lossless_common.h LOG_2_RECIPROCAL_FIXED
140pub const LOG_2_RECIPROCAL_FIXED: u64 = 12_102_203;
141// upstream: src/dsp/lossless_common.h LOG_LOOKUP_IDX_MAX
142pub const LOG_LOOKUP_IDX_MAX: i32 = 256;
143
144// upstream: src/dsp/lossless_common.h RightShiftRound
145/// `v` shifted right by `shift`, rounded to nearest. The `uint64_t` sum wraps,
146/// as in C.
147#[must_use]
148#[inline]
149pub fn right_shift_round(v: u64, shift: u32) -> u64 {
150    v.wrapping_add(1_u64 << shift >> 1) >> shift
151}
152
153// upstream: src/dsp/lossless_common.h DivRound
154/// `a / b`, rounded half away from zero.
155#[must_use]
156#[inline]
157pub fn div_round(a: i64, b: i64) -> i64 {
158    if (a < 0) == (b < 0) {
159        (a + b / 2) / b
160    } else {
161        (a - b / 2) / b
162    }
163}
164
165// upstream: src/dsp/lossless_common.h WEBP_INT64_MAX
166pub const WEBP_INT64_MAX: i64 = ((1_u64 << 63) - 1).cast_signed();
167// upstream: src/dsp/lossless_common.h WEBP_UINT64_MAX
168pub const WEBP_UINT64_MAX: u64 = !0_u64;
169
170// -----------------------------------------------------------------------------
171// PrefixEncode()
172
173// upstream: src/dsp/lossless_common.h VP8LPrefixEncodeBitsNoLUT
174/// Splitting of distance and length codes into prefixes and extra bits. The
175/// prefixes are encoded with an entropy code while the extra bits are stored
176/// just as normal bits.
177///
178/// Returns `(code, extra_bits)`, the two out-parameters of the C function.
179/// `distance` must be at least 3; C shifts by a negative amount below that.
180#[must_use]
181#[inline]
182pub fn vp8l_prefix_encode_bits_no_lut(mut distance: i32) -> (i32, i32) {
183    distance -= 1;
184    let highest_bit = bits_log2_floor(distance.cast_unsigned());
185    let second_highest_bit = (distance >> (highest_bit - 1)) & 1;
186    let extra_bits = highest_bit - 1;
187    let code = 2 * highest_bit + second_highest_bit;
188    (code, extra_bits)
189}
190
191// upstream: src/dsp/lossless_common.h VP8LPrefixEncodeNoLUT
192/// Returns `(code, extra_bits, extra_bits_value)`, the three out-parameters of
193/// the C function. `distance` must be at least 3.
194#[must_use]
195#[inline]
196pub fn vp8l_prefix_encode_no_lut(mut distance: i32) -> (i32, i32, i32) {
197    distance -= 1;
198    let highest_bit = bits_log2_floor(distance.cast_unsigned());
199    let second_highest_bit = (distance >> (highest_bit - 1)) & 1;
200    let extra_bits = highest_bit - 1;
201    let extra_bits_value = distance & ((1 << extra_bits) - 1);
202    let code = 2 * highest_bit + second_highest_bit;
203    (code, extra_bits, extra_bits_value)
204}
205
206// upstream: src/dsp/lossless_common.h PREFIX_LOOKUP_IDX_MAX
207pub const PREFIX_LOOKUP_IDX_MAX: i32 = 512;
208
209// upstream: src/dsp/lossless_common.h VP8LPrefixCode
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
211pub struct VP8LPrefixCode {
212    pub code: i8,
213    pub extra_bits: i8,
214}
215
216// upstream: src/dsp/lossless_common.h VP8LAddPixels
217/// Sum of each component, mod 256.
218#[must_use]
219#[inline]
220pub fn vp8l_add_pixels(a: u32, b: u32) -> u32 {
221    let alpha_and_green = (a & 0xff00_ff00).wrapping_add(b & 0xff00_ff00);
222    let red_and_blue = (a & 0x00ff_00ff).wrapping_add(b & 0x00ff_00ff);
223    (alpha_and_green & 0xff00_ff00) | (red_and_blue & 0x00ff_00ff)
224}
225
226// upstream: src/dsp/lossless_common.h VP8LSubPixels
227/// Difference of each component, mod 256.
228#[must_use]
229#[inline]
230pub fn vp8l_sub_pixels(a: u32, b: u32) -> u32 {
231    let alpha_and_green = 0x00ff_00ff_u32
232        .wrapping_add(a & 0xff00_ff00)
233        .wrapping_sub(b & 0xff00_ff00);
234    let red_and_blue = 0xff00_ff00_u32
235        .wrapping_add(a & 0x00ff_00ff)
236        .wrapping_sub(b & 0x00ff_00ff);
237    (alpha_and_green & 0xff00_ff00) | (red_and_blue & 0x00ff_00ff)
238}
239
240//------------------------------------------------------------------------------
241// Transform-related functions used in both encoding and decoding.
242
243// upstream: src/dsp/lossless_common.h GENERATE_PREDICTOR_ADD
244/// Macros used to create a batch predictor that iteratively uses a one-pixel
245/// predictor.
246///
247/// The predictor is added to the output pixel (which is therefore considered
248/// as a residual) to get the final prediction. The generated function has the
249/// form of `VP8LPredictorAddSubFunc` in `src/dsp/lossless.rs`: `in`, `upper`
250/// and `out` are positions in one buffer `data`, because the decoder reads the
251/// row above the output, and transforms in place.
252macro_rules! generate_predictor_add {
253    ($predictor:path, $predictor_add:ident) => {
254        fn $predictor_add(
255            data: &mut [u32],
256            in_pos: usize,
257            upper_pos: usize,
258            num_pixels: i32,
259            out_pos: usize,
260        ) {
261            for x in 0..::core::primitive::usize::try_from(num_pixels).unwrap_or(0) {
262                let pred = $predictor(data, (out_pos + x).wrapping_sub(1), data, upper_pos + x);
263                data[out_pos + x] =
264                    $crate::dsp::lossless_common::vp8l_add_pixels(data[in_pos + x], pred);
265            }
266        }
267    };
268}
269pub(crate) use generate_predictor_add;
270
271// -----------------------------------------------------------------------------
272// WP11's exception (decided 2026-11-06): the four functions below read the
273// tables and slow functions that `src/dsp/lossless_enc.rs` defines.
274
275// upstream: src/dsp/lossless_common.h VP8LFastLog2
276/// `log2(v)` in fixed point with `LOG_2_PRECISION_BITS` fractional bits: a
277/// table entry for small values, `VP8LFastLog2Slow` otherwise.
278#[must_use]
279#[inline]
280pub fn vp8l_fast_log2(v: u32) -> u32 {
281    if v < LOG_LOOKUP_IDX_MAX.cast_unsigned() {
282        crate::dsp::lossless_enc::LOG2_TABLE[v as usize]
283    } else {
284        crate::dsp::lossless_enc::vp8l_fast_log2_slow(v)
285    }
286}
287
288// upstream: src/dsp/lossless_common.h VP8LFastSLog2
289/// Fast calculation of `v * log2(v)` for integer input.
290#[must_use]
291#[inline]
292pub fn vp8l_fast_s_log2(v: u32) -> u64 {
293    if v < LOG_LOOKUP_IDX_MAX.cast_unsigned() {
294        crate::dsp::lossless_enc::S_LOG2_TABLE[v as usize]
295    } else {
296        crate::dsp::lossless_enc::vp8l_fast_s_log2_slow(v)
297    }
298}
299
300// upstream: src/dsp/lossless_common.h VP8LPrefixEncodeBits
301/// Returns `(code, extra_bits)`, the two out-parameters of the C function: a
302/// table entry for distances below `PREFIX_LOOKUP_IDX_MAX`,
303/// `VP8LPrefixEncodeBitsNoLUT` otherwise.
304///
305/// # Panics
306///
307/// Panics for a negative distance, which C reads before the table.
308#[must_use]
309#[inline]
310pub fn vp8l_prefix_encode_bits(distance: i32) -> (i32, i32) {
311    if distance < PREFIX_LOOKUP_IDX_MAX {
312        let prefix_code = crate::dsp::lossless_enc::PREFIX_ENCODE_CODE
313            [usize::try_from(distance).expect("a distance is not negative")];
314        (
315            i32::from(prefix_code.code),
316            i32::from(prefix_code.extra_bits),
317        )
318    } else {
319        vp8l_prefix_encode_bits_no_lut(distance)
320    }
321}
322
323// upstream: src/dsp/lossless_common.h VP8LPrefixEncode
324/// Returns `(code, extra_bits, extra_bits_value)`, the three out-parameters of
325/// the C function.
326///
327/// # Panics
328///
329/// Panics for a negative distance, which C reads before the table.
330#[must_use]
331#[inline]
332pub fn vp8l_prefix_encode(distance: i32) -> (i32, i32, i32) {
333    if distance < PREFIX_LOOKUP_IDX_MAX {
334        let index = usize::try_from(distance).expect("a distance is not negative");
335        let prefix_code = crate::dsp::lossless_enc::PREFIX_ENCODE_CODE[index];
336        (
337            i32::from(prefix_code.code),
338            i32::from(prefix_code.extra_bits),
339            i32::from(crate::dsp::lossless_enc::PREFIX_ENCODE_EXTRA_BITS_VALUE[index]),
340        )
341    } else {
342        vp8l_prefix_encode_no_lut(distance)
343    }
344}