Skip to main content

webp/utils/
huffman_encode_utils.rs

1// libwebp v1.6.0, src/utils/huffman_encode_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// Author: Jyrki Alakuijala (jyrki@google.com)
13//
14// Entropy encoding (Huffman) for webp lossless.
15
16// libwebp v1.6.0, src/utils/huffman_encode_utils.h:
17//
18// Copyright 2011 Google Inc. All Rights Reserved.
19//
20// Use of this source code is governed by a BSD-style license
21// that can be found in the COPYING file in the root of the source
22// tree. An additional intellectual property rights grant can be found
23// in the file PATENTS. All contributing project authors may
24// be found in the AUTHORS file in the root of the source tree.
25// -----------------------------------------------------------------------------
26//
27// Author: Jyrki Alakuijala (jyrki@google.com)
28//
29// Entropy encoding (Huffman) for webp lossless
30
31//! Translation of `src/utils/huffman_encode_utils.c` and `src/utils/huffman_encode_utils.h` from libwebp v1.6.0.
32//!
33//! Work package: WP3 (lossless shared).
34//!
35//! Representation: `HuffmanTreeCode` owns its code lengths and codes. The C
36//! encoder carves both arrays of every code from one allocation; ADR 0003
37//! lets the Rust caller check that total and allocate separate buffers.
38//!
39//! # Deviations from upstream
40//!
41//! Changes of representation that the ADRs allow, or behavior that the Rust
42//! side cannot reproduce exactly. Each records the reason.
43//!
44//! 1. **`HuffmanTreeCode` owns its arrays.** `code_lengths: Vec<u8>` and
45//!    `codes: Vec<u16>` replace the two pointers. The encoder carves both
46//!    arrays of every code from one allocation (`GetHuffBitLengthsAndCodes` in
47//!    `src/enc/vp8l_enc.c`); ADR 0003 lets the Rust caller check that total and
48//!    allocate separate buffers. `StoreFullHuffmanCode` builds its 19-entry
49//!    code the same way. `src/enc/vp8l_enc.rs` consumes this form.
50//!
51//! # Excluded undefined behavior
52//!
53//! Inputs that are undefined behavior (or assertion failures) in C and are
54//! therefore excluded from the oracle comparison (PORTING rule 8):
55//!
56//! 1. `OptimizeHuffmanForRle` with counts of 2^31 or more: the conversion to
57//!    `int` is implementation-defined and `abs(a - b)` can overflow. The
58//!    histograms stay below 2^26.
59//! 2. `GenerateOptimalTree` with stale code lengths above the depth limit for
60//!    unused symbols, which never satisfy the limit (C loops forever), or with
61//!    more used symbols than `1 << (limit - 1)` (C asserts). The encoder starts
62//!    from zeros.
63
64use core::cmp::Ordering;
65
66use crate::webp::format_constants::MAX_ALLOWED_CODE_LENGTH;
67
68// upstream: src/utils/huffman_encode_utils.h HuffmanTreeToken
69/// Struct for holding the tree header in coded form.
70#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
71pub struct HuffmanTreeToken {
72    /// Value (0..15) or escape code (16, 17, 18).
73    pub code: u8,
74    /// Extra bits for escape codes.
75    pub extra_bits: u8,
76}
77
78impl HuffmanTreeToken {
79    /// The C `sizeof(HuffmanTreeToken)`, the `size` argument of its allocations.
80    pub const C_SIZE: usize = 2;
81}
82
83// upstream: src/utils/huffman_encode_utils.h HuffmanTreeCode
84/// Struct to represent the tree codes (depth and bits array).
85#[derive(Clone, Debug, Default, PartialEq, Eq)]
86pub struct HuffmanTreeCode {
87    /// Number of symbols.
88    pub num_symbols: i32,
89    /// Code lengths of the symbols; at least `num_symbols` of them.
90    pub code_lengths: Vec<u8>,
91    /// Symbol Codes; at least `num_symbols` of them.
92    pub codes: Vec<u16>,
93}
94
95impl HuffmanTreeCode {
96    /// The C `sizeof(HuffmanTreeCode)`: an `int` and two pointers, with the
97    /// `int` padded to the pointer alignment.
98    pub const C_SIZE: usize = 3 * size_of::<usize>();
99}
100
101// upstream: src/utils/huffman_encode_utils.h HuffmanTree
102/// Struct to represent the Huffman tree.
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104pub struct HuffmanTree {
105    /// Symbol frequency.
106    pub total_count: u32,
107    /// Symbol value.
108    pub value: i32,
109    /// Index for the left sub-tree.
110    pub pool_index_left: i32,
111    /// Index for the right sub-tree.
112    pub pool_index_right: i32,
113}
114
115impl HuffmanTree {
116    /// The C `sizeof(HuffmanTree)`, the `size` argument of its allocations.
117    pub const C_SIZE: usize = 16;
118}
119
120/// Converts an index of the tree construction, which is never negative, to a
121/// slice position.
122fn position(value: i32) -> usize {
123    usize::try_from(value).expect("a tree index is not negative")
124}
125
126// -----------------------------------------------------------------------------
127// Util function to optimize the symbol map for RLE coding
128
129// upstream: src/utils/huffman_encode_utils.c ValuesShouldBeCollapsedToStrideAverage
130/// Heuristics for selecting the stride ranges to collapse.
131#[must_use]
132fn values_should_be_collapsed_to_stride_average(a: i32, b: i32) -> bool {
133    (a - b).abs() < 4
134}
135
136// upstream: src/utils/huffman_encode_utils.c OptimizeHuffmanForRle
137/// Change the population counts in a way that the consequent Huffman tree
138/// compression, especially its RLE-part, give smaller output.
139///
140/// The C `uint32_t` arithmetic wraps; the conversion of a count to the `int`
141/// parameters of the heuristic keeps its bits, as Clang and GCC convert.
142fn optimize_huffman_for_rle(mut length: i32, good_for_rle: &mut [u8], counts: &mut [u32]) {
143    // 1) Let's make the Huffman code more compatible with rle encoding.
144    while length >= 0 {
145        if length == 0 {
146            return; // All zeros.
147        }
148        if counts[position(length - 1)] != 0 {
149            // Now counts[0..length - 1] does not have trailing zeros.
150            break;
151        }
152        length -= 1;
153    }
154    // 2) Let's mark all population counts that already can be encoded
155    // with an rle code.
156    {
157        // Let's not spoil any of the existing good rle codes.
158        // Mark any seq of 0's that is longer as 5 as a good_for_rle.
159        // Mark any seq of non-0's that is longer as 7 as a good_for_rle.
160        let mut symbol: u32 = counts[0];
161        let mut stride: i32 = 0;
162        for i in 0..=length {
163            if i == length || counts[position(i)] != symbol {
164                if (symbol == 0 && stride >= 5) || (symbol != 0 && stride >= 7) {
165                    for k in 0..stride {
166                        good_for_rle[position(i - k - 1)] = 1;
167                    }
168                }
169                stride = 1;
170                if i != length {
171                    symbol = counts[position(i)];
172                }
173            } else {
174                stride += 1;
175            }
176        }
177    }
178    // 3) Let's replace those population counts that lead to more rle codes.
179    {
180        let mut stride: u32 = 0;
181        let mut limit: u32 = counts[0];
182        let mut sum: u32 = 0;
183        for i in 0..=length {
184            if i == length
185                || good_for_rle[position(i)] != 0
186                || (i != 0 && good_for_rle[position(i - 1)] != 0)
187                || !values_should_be_collapsed_to_stride_average(
188                    counts[position(i)].cast_signed(),
189                    limit.cast_signed(),
190                )
191            {
192                if stride >= 4 || (stride >= 3 && sum == 0) {
193                    // The stride must end, collapse what we have, if we have enough (4).
194                    let mut count: u32 = sum.wrapping_add(stride / 2) / stride;
195                    if count < 1 {
196                        count = 1;
197                    }
198                    if sum == 0 {
199                        // Don't make an all zeros stride to be upgraded to ones.
200                        count = 0;
201                    }
202                    for k in 0..stride {
203                        // We don't want to change value at counts[i],
204                        // that is already belonging to the next stride. Thus - 1.
205                        counts[position(i) - k as usize - 1] = count;
206                    }
207                }
208                stride = 0;
209                sum = 0;
210                if i < length - 3 {
211                    // All interesting strides have a count of at least 4,
212                    // at least when non-zeros.
213                    let at = position(i);
214                    limit = counts[at]
215                        .wrapping_add(counts[at + 1])
216                        .wrapping_add(counts[at + 2])
217                        .wrapping_add(counts[at + 3])
218                        .wrapping_add(2)
219                        / 4;
220                } else if i < length {
221                    limit = counts[position(i)];
222                } else {
223                    limit = 0;
224                }
225            }
226            stride += 1;
227            if i != length {
228                sum = sum.wrapping_add(counts[position(i)]);
229                if stride >= 4 {
230                    limit = sum.wrapping_add(stride / 2) / stride;
231                }
232            }
233        }
234    }
235}
236
237// upstream: src/utils/huffman_encode_utils.c CompareHuffmanTrees
238/// A comparer function for two Huffman trees: sorts first by `total_count`
239/// (more comes first), and then by `value` (more comes first).
240///
241/// The values of the sorted leaves are distinct symbols, so no two trees
242/// compare equal and every sort algorithm gives the order of the C `qsort`.
243#[expect(
244    clippy::comparison_chain,
245    reason = "mirrors the if chain of the C comparator"
246)]
247fn compare_huffman_trees(t1: &HuffmanTree, t2: &HuffmanTree) -> Ordering {
248    if t1.total_count > t2.total_count {
249        Ordering::Less
250    } else if t1.total_count < t2.total_count {
251        Ordering::Greater
252    } else {
253        debug_assert_ne!(t1.value, t2.value);
254        if t1.value < t2.value {
255            Ordering::Less
256        } else {
257            Ordering::Greater
258        }
259    }
260}
261
262// upstream: src/utils/huffman_encode_utils.c SetBitDepths
263/// Stores the depth of every leaf under `tree`, whose sub-trees are in `pool`.
264/// The depth is truncated to the `uint8_t` of `bit_depths`, as in C.
265#[expect(
266    clippy::cast_possible_truncation,
267    clippy::cast_sign_loss,
268    reason = "the C conversion of the int level to uint8_t"
269)]
270fn set_bit_depths(tree: &HuffmanTree, pool: &[HuffmanTree], bit_depths: &mut [u8], level: i32) {
271    if tree.pool_index_left >= 0 {
272        set_bit_depths(
273            &pool[position(tree.pool_index_left)],
274            pool,
275            bit_depths,
276            level + 1,
277        );
278        set_bit_depths(
279            &pool[position(tree.pool_index_right)],
280            pool,
281            bit_depths,
282            level + 1,
283        );
284    } else {
285        bit_depths[position(tree.value)] = level as u8;
286    }
287}
288
289// upstream: src/utils/huffman_encode_utils.c GenerateOptimalTree
290/// Create an optimal Huffman tree.
291///
292/// (histogram, `histogram_size`): population counts.
293/// `tree_depth_limit`: maximum bit depth (inclusive) of the codes.
294/// `bit_depths[]`: how many bits are used for the symbol.
295///
296/// The catch here is that the tree cannot be arbitrarily deep.
297///
298/// `count_min` is the value that is to be faked as the minimum value
299/// and this minimum value is raised until the tree matches the
300/// maximum length requirement.
301///
302/// This algorithm is not of excellent performance for very long data blocks,
303/// especially when population counts are longer than 2**`tree_limit`, but
304/// we are not planning to use this with extremely long blocks.
305///
306/// See <https://en.wikipedia.org/wiki/Huffman_coding>
307///
308/// The leaves are the first `tree_size_orig` entries of `tree`, and the pool of
309/// sub-trees follows them, as in C. The depths of symbols with a zero count are
310/// left as they are.
311fn generate_optimal_tree(
312    histogram: &[u32],
313    histogram_size: i32,
314    tree: &mut [HuffmanTree],
315    tree_depth_limit: i32,
316    bit_depths: &mut [u8],
317) {
318    let histogram = &histogram[..position(histogram_size)];
319    let mut tree_size_orig: i32 = 0;
320
321    for &count in histogram {
322        if count != 0 {
323            tree_size_orig += 1;
324        }
325    }
326
327    if tree_size_orig == 0 {
328        // pretty optimal already!
329        return;
330    }
331
332    let (tree, tree_pool) = tree.split_at_mut(position(tree_size_orig));
333
334    // For block sizes with less than 64k symbols we never need to do a
335    // second iteration of this loop.
336    // If we actually start running inside this loop a lot, we would perhaps
337    // be better off with the Katajainen algorithm.
338    debug_assert!(tree_size_orig <= (1 << (tree_depth_limit - 1)));
339    let mut count_min: u32 = 1;
340    loop {
341        let mut tree_size = tree_size_orig;
342        // We need to pack the Huffman tree in tree_depth_limit bits.
343        // So, we try by faking histogram entries to be at least 'count_min'.
344        let mut idx: usize = 0;
345        for (j, &count) in histogram.iter().enumerate() {
346            if count != 0 {
347                let count = if count < count_min { count_min } else { count };
348                tree[idx].total_count = count;
349                tree[idx].value = i32::try_from(j).expect("a symbol fits an int");
350                tree[idx].pool_index_left = -1;
351                tree[idx].pool_index_right = -1;
352                idx += 1;
353            }
354        }
355
356        // Build the Huffman tree.
357        tree[..position(tree_size)].sort_unstable_by(compare_huffman_trees);
358
359        if tree_size > 1 {
360            // Normal case.
361            let mut tree_pool_size: i32 = 0;
362            while tree_size > 1 {
363                // Finish when we have only one root.
364                tree_pool[position(tree_pool_size)] = tree[position(tree_size - 1)];
365                tree_pool_size += 1;
366                tree_pool[position(tree_pool_size)] = tree[position(tree_size - 2)];
367                tree_pool_size += 1;
368                let count: u32 = tree_pool[position(tree_pool_size - 1)]
369                    .total_count
370                    .wrapping_add(tree_pool[position(tree_pool_size - 2)].total_count);
371                tree_size -= 2;
372                {
373                    // Search for the insertion point.
374                    let mut k: i32 = 0;
375                    while k < tree_size {
376                        if tree[position(k)].total_count <= count {
377                            break;
378                        }
379                        k += 1;
380                    }
381                    tree.copy_within(position(k)..position(tree_size), position(k + 1));
382                    let node = &mut tree[position(k)];
383                    node.total_count = count;
384                    node.value = -1;
385
386                    node.pool_index_left = tree_pool_size - 1;
387                    node.pool_index_right = tree_pool_size - 2;
388                    tree_size += 1;
389                }
390            }
391            set_bit_depths(&tree[0], tree_pool, bit_depths, 0);
392        } else if tree_size == 1 {
393            // Trivial case: only one element.
394            bit_depths[position(tree[0].value)] = 1;
395        }
396
397        {
398            // Test if this Huffman tree satisfies our 'tree_depth_limit' criteria.
399            let mut max_depth = i32::from(bit_depths[0]);
400            for &depth in &bit_depths[1..histogram.len()] {
401                if max_depth < i32::from(depth) {
402                    max_depth = i32::from(depth);
403                }
404            }
405            if max_depth <= tree_depth_limit {
406                break;
407            }
408        }
409        count_min = count_min.wrapping_mul(2);
410    }
411}
412
413// -----------------------------------------------------------------------------
414// Coding of the Huffman tree values
415
416/// Truncates a code or an extra-bits value to the `uint8_t` of
417/// `HuffmanTreeToken`, as the C assignment does.
418#[expect(
419    clippy::cast_possible_truncation,
420    clippy::cast_sign_loss,
421    reason = "the C conversion of an int to uint8_t"
422)]
423fn token_byte(value: i32) -> u8 {
424    value as u8
425}
426
427// upstream: src/utils/huffman_encode_utils.c CodeRepeatedValues
428/// Writes the tokens for `repetitions` copies of `value` at `tokens[pos..]`
429/// and returns the position after them.
430fn code_repeated_values(
431    mut repetitions: i32,
432    tokens: &mut [HuffmanTreeToken],
433    mut pos: usize,
434    value: i32,
435    prev_value: i32,
436) -> usize {
437    debug_assert!(value <= MAX_ALLOWED_CODE_LENGTH);
438    if value != prev_value {
439        tokens[pos].code = token_byte(value);
440        tokens[pos].extra_bits = 0;
441        pos += 1;
442        repetitions -= 1;
443    }
444    while repetitions >= 1 {
445        if repetitions < 3 {
446            for _ in 0..repetitions {
447                tokens[pos].code = token_byte(value);
448                tokens[pos].extra_bits = 0;
449                pos += 1;
450            }
451            break;
452        } else if repetitions < 7 {
453            tokens[pos].code = 16;
454            tokens[pos].extra_bits = token_byte(repetitions - 3);
455            pos += 1;
456            break;
457        }
458        tokens[pos].code = 16;
459        tokens[pos].extra_bits = 3;
460        pos += 1;
461        repetitions -= 6;
462    }
463    pos
464}
465
466// upstream: src/utils/huffman_encode_utils.c CodeRepeatedZeros
467/// Writes the tokens for `repetitions` zeros at `tokens[pos..]` and returns
468/// the position after them.
469fn code_repeated_zeros(
470    mut repetitions: i32,
471    tokens: &mut [HuffmanTreeToken],
472    mut pos: usize,
473) -> usize {
474    while repetitions >= 1 {
475        if repetitions < 3 {
476            for _ in 0..repetitions {
477                tokens[pos].code = 0; // 0-value
478                tokens[pos].extra_bits = 0;
479                pos += 1;
480            }
481            break;
482        } else if repetitions < 11 {
483            tokens[pos].code = 17;
484            tokens[pos].extra_bits = token_byte(repetitions - 3);
485            pos += 1;
486            break;
487        } else if repetitions < 139 {
488            tokens[pos].code = 18;
489            tokens[pos].extra_bits = token_byte(repetitions - 11);
490            pos += 1;
491            break;
492        }
493        tokens[pos].code = 18;
494        tokens[pos].extra_bits = 0x7f; // 138 repeated 0s
495        pos += 1;
496        repetitions -= 138;
497    }
498    pos
499}
500
501// upstream: src/utils/huffman_encode_utils.c VP8LCreateCompressedHuffmanTree
502/// Turn the Huffman tree into a token sequence.
503/// Returns the number of tokens used.
504///
505/// `tokens` holds the `max_tokens` tokens of the C call.
506///
507/// # Panics
508///
509/// Panics when the tokens do not fit, where C asserts and writes past
510/// `max_tokens`.
511#[must_use]
512pub fn vp8l_create_compressed_huffman_tree(
513    tree: &HuffmanTreeCode,
514    tokens: &mut [HuffmanTreeToken],
515) -> i32 {
516    let ending_token = tokens.len();
517    let depth_size = tree.num_symbols;
518    let mut prev_value: i32 = 8; // 8 is the initial value for rle.
519    let mut pos: usize = 0;
520    let mut i: i32 = 0;
521    while i < depth_size {
522        let value = i32::from(tree.code_lengths[position(i)]);
523        let mut k = i + 1;
524        while k < depth_size && i32::from(tree.code_lengths[position(k)]) == value {
525            k += 1;
526        }
527        let runs = k - i;
528        if value == 0 {
529            pos = code_repeated_zeros(runs, tokens, pos);
530        } else {
531            pos = code_repeated_values(runs, tokens, pos, value, prev_value);
532            prev_value = value;
533        }
534        i += runs;
535        debug_assert!(pos <= ending_token);
536    }
537    i32::try_from(pos).expect("the token count fits an int")
538}
539
540// -----------------------------------------------------------------------------
541
542// upstream: src/utils/huffman_encode_utils.c kReversedBits
543/// Pre-reversed 4-bit values.
544const REVERSED_BITS: [u8; 16] = [
545    0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf,
546];
547
548// upstream: src/utils/huffman_encode_utils.c ReverseBits
549/// Reverses the `num_bits` low bits of `bits`.
550#[must_use]
551fn reverse_bits(num_bits: i32, mut bits: u32) -> u32 {
552    let mut retval: u32 = 0;
553    let mut i: i32 = 0;
554    while i < num_bits {
555        i += 4;
556        retval |=
557            u32::from(REVERSED_BITS[(bits & 0xf) as usize]) << (MAX_ALLOWED_CODE_LENGTH + 1 - i);
558        bits >>= 4;
559    }
560    retval >>= MAX_ALLOWED_CODE_LENGTH + 1 - num_bits;
561    retval
562}
563
564// upstream: src/utils/huffman_encode_utils.c ConvertBitDepthsToSymbols
565/// Get the actual bit values for a tree of bit depths.
566#[expect(
567    clippy::cast_possible_truncation,
568    reason = "the C conversion of the reversed code to uint16_t"
569)]
570fn convert_bit_depths_to_symbols(tree: &mut HuffmanTreeCode) {
571    const DEPTHS: usize = MAX_ALLOWED_CODE_LENGTH as usize + 1;
572    // 0 bit-depth means that the symbol does not exist.
573    let mut next_code = [0_u32; DEPTHS];
574    let mut depth_count = [0_i32; DEPTHS];
575
576    let len = position(tree.num_symbols);
577    for &code_length in &tree.code_lengths[..len] {
578        debug_assert!(i32::from(code_length) <= MAX_ALLOWED_CODE_LENGTH);
579        depth_count[usize::from(code_length)] += 1;
580    }
581    depth_count[0] = 0; // ignore unused symbol
582    next_code[0] = 0;
583    {
584        let mut code: u32 = 0;
585        for i in 1..DEPTHS {
586            code = code.wrapping_add(depth_count[i - 1].cast_unsigned()) << 1;
587            next_code[i] = code;
588        }
589    }
590    for i in 0..len {
591        let code_length = usize::from(tree.code_lengths[i]);
592        tree.codes[i] =
593            reverse_bits(i32::from(tree.code_lengths[i]), next_code[code_length]) as u16;
594        next_code[code_length] = next_code[code_length].wrapping_add(1);
595    }
596}
597
598// -----------------------------------------------------------------------------
599// Main entry point
600
601// upstream: src/utils/huffman_encode_utils.c VP8LCreateHuffmanTree
602/// Create an optimized tree, and tokenize it.
603/// `buf_rle` and `huff_tree` are pre-allocated and the `tree` is the
604/// constructed huffman code tree.
605///
606/// `histogram` is changed by the RLE optimization, as in C. `huff_tree` needs
607/// room for the leaves and the pool: `3 * num_symbols` entries suffice.
608pub fn vp8l_create_huffman_tree(
609    histogram: &mut [u32],
610    tree_depth_limit: i32,
611    buf_rle: &mut [u8],
612    huff_tree: &mut [HuffmanTree],
613    huff_code: &mut HuffmanTreeCode,
614) {
615    let num_symbols = huff_code.num_symbols;
616    buf_rle[..position(num_symbols)].fill(0);
617    optimize_huffman_for_rle(num_symbols, buf_rle, histogram);
618    generate_optimal_tree(
619        histogram,
620        num_symbols,
621        huff_tree,
622        tree_depth_limit,
623        &mut huff_code.code_lengths,
624    );
625    // Create the actual bit codes for the bit lengths.
626    convert_bit_depths_to_symbols(huff_code);
627}