webp/utils/huffman_utils.rs
1// libwebp v1.6.0, src/utils/huffman_utils.c:
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// Utilities for building and looking up Huffman trees.
13//
14// Author: Urvang Joshi (urvang@google.com)
15
16// libwebp v1.6.0, src/utils/huffman_utils.h:
17//
18// Copyright 2012 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// Utilities for building and looking up Huffman trees.
28//
29// Author: Urvang Joshi (urvang@google.com)
30
31//! Translation of `src/utils/huffman_utils.c` and `src/utils/huffman_utils.h` from libwebp v1.6.0.
32//!
33//! Work package: WP3 (lossless shared).
34//!
35//! Representation (ADR 0003, "Readers over input"): C chains the segments of a
36//! [`HuffmanTables`] through pointers, and the decoder keeps pointers to table
37//! entries. Here the tables own their segments, `root` and then
38//! `next_segments` in chain order, and a table reference is a
39//! [`HuffmanTablesOffset`]: the index of the segment and the position of the
40//! entry inside it. The owner of the tables passes them to each function that
41//! reads an entry.
42//!
43//! # Deviations from upstream
44//!
45//! Changes of representation that the ADRs allow, or behavior that the Rust
46//! side cannot reproduce exactly. Each records the reason.
47//!
48//! 1. **`HuffmanTables` stores positions (ADR 0003, "Readers over input").**
49//! The tables own their segments: `root`, then `next_segments` in the order
50//! of the C `next` chain, so `HuffmanTablesSegment` has no `next` field.
51//! `curr_segment` is the segment's index (0 is `root`), and `curr_table` is
52//! a position in the segment's `start`. A C `HuffmanCode*` into the tables
53//! is a `HuffmanTablesOffset { segment, offset }`, and `HTreeGroup::htrees`
54//! holds five of them; the owner (the decoder's `VP8LMetadata`) passes the
55//! tables to whatever reads an entry. `segment()` and `segment_mut()`
56//! resolve an index. A second-level table is addressed as in C, relative to
57//! its root entry in the same segment.
58//! 2. **Segment lifetimes.** `VP8LHuffmanTablesAllocate` drops the old chain
59//! where C cuts it with `root->next = NULL` without freeing; `Deallocate`
60//! empties `root.start` and drops the chain. As in C, `Deallocate` leaves
61//! `curr_segment`, `root.curr_table` and `root.size` alone; a stale
62//! `curr_segment` panics on use where the C pointer dangles. A new segment
63//! replaces the chain after the current one, as `curr_segment->next = next`
64//! does; the current segment is always the last.
65//! 3. **Tree groups.** `VP8LHtreeGroupsNew` returns `Option<Vec<HTreeGroup>>`
66//! with default groups (C leaves them uninitialized). `VP8LHtreeGroupsFree`
67//! only frees, so the owner drops the vector instead, as for `WebPSafeFree`
68//! (see the module documentation of `src/utils/utils.rs`). The flags
69//! `is_trivial_literal`, `is_trivial_code` and `use_packed_table` are
70//! `bool`, because C uses them only as predicates.
71//!
72//! # Excluded undefined behavior
73//!
74//! Inputs that are undefined behavior (or assertion failures) in C and are
75//! therefore excluded from the oracle comparison (PORTING rule 8):
76//!
77//! 1. `VP8LBuildHuffmanTable` with a negative code length (C writes outside its
78//! histogram; Rust panics), with no code lengths (C asserts), or with
79//! `root_bits` above `MAX_ALLOWED_CODE_LENGTH` (C reads its histogram past
80//! the end). The decoder passes 7 or 8; the tests use 1 to 12.
81//! 2. `VP8LHuffmanTablesAllocate(0)` and `VP8LHtreeGroupsNew(0)`: the zero-size
82//! request of `WebPSafeMalloc` (`src/utils/utils.rs`,
83//! `# Excluded undefined behavior`, item 2). `VP8LHtreeGroupsNew` above
84//! `MAX_HTREE_GROUPS` with a successful allocation asserts in C.
85//!
86//! # Checks not applicable
87//!
88//! These checks do not apply, or cannot be made, with the reason:
89//!
90//! 1. **Host refusals of an allocation.** The size tests of `WebPSafeMalloc`
91//! are compared through negative sizes (`alloc`, `groups`) and counts above
92//! the limit. A refusal by the host of an accepted size (the new segment,
93//! the heap-sorted array, the co-occurrence matrix) cannot be provoked here;
94//! the Rust code returns the same failure where C does (`try_reserve`,
95//! `webp_safe_malloc`).
96//! 2. **Uninitialized C memory.** `VP8LHuffmanTablesAllocate`, the new segments
97//! and `VP8LHtreeGroupsNew` use `WebPSafeMalloc` without initialization;
98//! Rust initializes (ADR 0003). `BuildHuffmanTable` writes every entry of
99//! the range it returns for an accepted code, and only that range is
100//! compared. The lines of `CoOccurrenceBuild` are written before they are
101//! read.
102//! 3. **`NULL` arguments.** `VP8LHtreeGroupsFree(NULL)`,
103//! `VP8LHuffmanTablesDeallocate(NULL)` and `VP8LColorCacheClear(NULL)` exist
104//! only at the C ABI (PORTING rule 8); none of these headers is public.
105
106use crate::utils::utils::webp_safe_malloc;
107use crate::webp::format_constants::{
108 HUFFMAN_CODES_PER_META_CODE, MAX_ALLOWED_CODE_LENGTH, MAX_CACHE_BITS, NUM_LENGTH_CODES,
109 NUM_LITERAL_CODES,
110};
111
112// upstream: src/utils/huffman_utils.h HUFFMAN_TABLE_BITS
113pub const HUFFMAN_TABLE_BITS: i32 = 8;
114// upstream: src/utils/huffman_utils.h HUFFMAN_TABLE_MASK
115pub const HUFFMAN_TABLE_MASK: i32 = (1 << HUFFMAN_TABLE_BITS) - 1;
116
117// upstream: src/utils/huffman_utils.h LENGTHS_TABLE_BITS
118pub const LENGTHS_TABLE_BITS: i32 = 7;
119// upstream: src/utils/huffman_utils.h LENGTHS_TABLE_MASK
120pub const LENGTHS_TABLE_MASK: i32 = (1 << LENGTHS_TABLE_BITS) - 1;
121
122// upstream: src/utils/huffman_utils.h HuffmanCode
123/// Huffman lookup table entry.
124#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
125pub struct HuffmanCode {
126 /// Number of bits used for this symbol.
127 pub bits: u8,
128 /// Symbol value or table offset.
129 pub value: u16,
130}
131
132impl HuffmanCode {
133 /// The C `sizeof(HuffmanCode)`, the `size` argument of its allocations.
134 pub const C_SIZE: usize = 4;
135}
136
137// upstream: src/utils/huffman_utils.h HuffmanCode32
138/// Long version of [`HuffmanCode`] for holding 32-bit values.
139#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
140pub struct HuffmanCode32 {
141 /// Number of bits used for this symbol, or an impossible value if not a
142 /// literal code.
143 pub bits: i32,
144 /// 32-bit packed ARGB value if literal, or non-literal symbol otherwise.
145 pub value: u32,
146}
147
148/// A C `HuffmanCode*` into the segments of a [`HuffmanTables`]: the segment
149/// (0 is `root`, `n` is `next_segments[n - 1]`) and the entry inside it. This
150/// type has no C counterpart (ADR 0003, "Readers over input").
151#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
152pub struct HuffmanTablesOffset {
153 /// The segment that holds the entry.
154 pub segment: usize,
155 /// The position of the entry inside the segment's `start`.
156 pub offset: usize,
157}
158
159// upstream: src/utils/huffman_utils.h HuffmanTablesSegment
160/// Contiguous memory segment of `HuffmanCode`s.
161///
162/// The C `next` pointer is the order of [`HuffmanTables::next_segments`].
163#[derive(Clone, Debug, Default, PartialEq, Eq)]
164pub struct HuffmanTablesSegment {
165 /// The codes of the segment; empty where C has `start == NULL`.
166 pub start: Vec<HuffmanCode>,
167 /// Where we are writing into the segment, as a position in `start`. Starts
168 /// at 0 and cannot go beyond `size`.
169 pub curr_table: usize,
170 /// The number of codes in the segment.
171 pub size: i32,
172}
173
174impl HuffmanTablesSegment {
175 /// The C `sizeof(HuffmanTablesSegment)`: three pointers and an `int`,
176 /// padded to the pointer alignment.
177 pub const C_SIZE: usize = (3 * size_of::<usize>() + 4).next_multiple_of(size_of::<usize>());
178}
179
180// upstream: src/utils/huffman_utils.h HuffmanTables
181/// Chained memory segments of `HuffmanCode`s.
182#[derive(Clone, Debug, Default, PartialEq, Eq)]
183pub struct HuffmanTables {
184 /// The first segment.
185 pub root: HuffmanTablesSegment,
186 /// The segments after `root`, in the order of the C `next` chain.
187 pub next_segments: Vec<HuffmanTablesSegment>,
188 /// Currently processed segment: 0 is `root`, `n` is `next_segments[n - 1]`.
189 /// At first, this is `root`.
190 pub curr_segment: usize,
191}
192
193impl HuffmanTables {
194 /// The segment with index `segment`: 0 is `root`, `n` is
195 /// `next_segments[n - 1]`.
196 ///
197 /// # Panics
198 ///
199 /// Panics when there is no such segment.
200 #[must_use]
201 pub fn segment(&self, segment: usize) -> &HuffmanTablesSegment {
202 match segment.checked_sub(1) {
203 None => &self.root,
204 Some(index) => &self.next_segments[index],
205 }
206 }
207
208 /// The segment with index `segment`, mutably; see [`HuffmanTables::segment`].
209 ///
210 /// # Panics
211 ///
212 /// Panics when there is no such segment.
213 pub fn segment_mut(&mut self, segment: usize) -> &mut HuffmanTablesSegment {
214 match segment.checked_sub(1) {
215 None => &mut self.root,
216 Some(index) => &mut self.next_segments[index],
217 }
218 }
219}
220
221// upstream: src/utils/huffman_utils.h HUFFMAN_PACKED_BITS
222pub const HUFFMAN_PACKED_BITS: i32 = 6;
223// upstream: src/utils/huffman_utils.h HUFFMAN_PACKED_TABLE_SIZE
224pub const HUFFMAN_PACKED_TABLE_SIZE: u32 = 1 << HUFFMAN_PACKED_BITS;
225
226// upstream: src/utils/huffman_utils.h HTreeGroup
227/// Huffman table group.
228///
229/// Includes special handling for the following cases:
230/// - `is_trivial_literal`: one common literal base for RED/BLUE/ALPHA (not GREEN)
231/// - `is_trivial_code`: only 1 code (no bit is read from bitstream)
232/// - `use_packed_table`: few enough literal symbols, so all the bit codes
233/// can fit into a small look-up table `packed_table[]`
234///
235/// The common literal base, if applicable, is stored in `literal_arb`.
236#[derive(Clone, Debug, PartialEq, Eq)]
237pub struct HTreeGroup {
238 /// The first entry of each tree, in the tables of the owner.
239 pub htrees: [HuffmanTablesOffset; HUFFMAN_CODES_PER_META_CODE as usize],
240 /// True, if huffman trees for Red, Blue & Alpha Symbols are trivial (have
241 /// a single code).
242 pub is_trivial_literal: bool,
243 /// If `is_trivial_literal` is true, this is the ARGB value of the pixel,
244 /// with Green channel being set to zero.
245 pub literal_arb: u32,
246 /// True if `is_trivial_literal` with only one code.
247 pub is_trivial_code: bool,
248 /// Use packed table below for short literal code.
249 pub use_packed_table: bool,
250 /// Table mapping input bits to a packed values, or escape case to literal code.
251 pub packed_table: [HuffmanCode32; HUFFMAN_PACKED_TABLE_SIZE as usize],
252}
253
254impl Default for HTreeGroup {
255 fn default() -> Self {
256 Self {
257 htrees: [HuffmanTablesOffset::default(); HUFFMAN_CODES_PER_META_CODE as usize],
258 is_trivial_literal: false,
259 literal_arb: 0,
260 is_trivial_code: false,
261 use_packed_table: false,
262 packed_table: [HuffmanCode32::default(); HUFFMAN_PACKED_TABLE_SIZE as usize],
263 }
264 }
265}
266
267impl HTreeGroup {
268 /// The C `sizeof(HTreeGroup)`: five pointers, four 32-bit fields and the
269 /// packed table of 8-byte entries, padded to the pointer alignment.
270 pub const C_SIZE: usize = (HUFFMAN_CODES_PER_META_CODE as usize * size_of::<usize>()
271 + 4 * 4
272 + HUFFMAN_PACKED_TABLE_SIZE as usize * 8)
273 .next_multiple_of(size_of::<usize>());
274}
275
276// upstream: src/utils/huffman_utils.c MAX_HTREE_GROUPS
277/// Huffman data read via `DecodeImageStream` is represented in two (red and
278/// green) bytes.
279const MAX_HTREE_GROUPS: i32 = 0x10000;
280
281/// The C conversion of an `int` count to the `uint64_t` element count of
282/// `WebPSafeMalloc`, which turns a negative count into a huge one.
283fn element_count(count: i32) -> u64 {
284 i64::from(count).cast_unsigned()
285}
286
287// upstream: src/utils/huffman_utils.c VP8LHtreeGroupsNew
288/// Creates the instance of `HTreeGroup` with specified number of tree-groups.
289///
290/// Returns `None` where C returns `NULL`. C leaves the groups uninitialized;
291/// they are default values here (ADR 0003).
292///
293/// # Panics
294///
295/// Panics only if an accepted count were negative, which the size test of
296/// `WebPSafeMalloc` excludes.
297#[must_use]
298pub fn vp8l_htree_groups_new(num_htree_groups: i32) -> Option<Vec<HTreeGroup>> {
299 let mut htree_groups =
300 webp_safe_malloc::<HTreeGroup>(element_count(num_htree_groups), HTreeGroup::C_SIZE)?;
301 debug_assert!(num_htree_groups <= MAX_HTREE_GROUPS);
302 let count = usize::try_from(num_htree_groups).expect("an accepted count is not negative");
303 htree_groups.resize(count, HTreeGroup::default());
304 Some(htree_groups)
305}
306
307/// Converts an index or a length of the table construction, which is never
308/// negative, to a slice position.
309fn position(value: i32) -> usize {
310 usize::try_from(value).expect("a table position is not negative")
311}
312
313// upstream: src/utils/huffman_utils.c GetNextKey
314/// Returns reverse(reverse(key, len) + 1, len), where reverse(key, len) is the
315/// bit-wise reversal of the len least significant bits of key.
316#[must_use]
317fn get_next_key(key: u32, len: i32) -> u32 {
318 let mut step: u32 = 1 << (len - 1);
319 while key & step != 0 {
320 step >>= 1;
321 }
322 if step != 0 {
323 (key & (step - 1)) + step
324 } else {
325 key
326 }
327}
328
329// upstream: src/utils/huffman_utils.c ReplicateValue
330/// Stores code in `table[base]`, `table[base + step]`, `table[base + 2*step]`,
331/// ..., `table[base + end - step]`. Assumes that end is an integer multiple of
332/// step.
333fn replicate_value(
334 table: &mut [HuffmanCode],
335 base: usize,
336 step: i32,
337 mut end: i32,
338 code: HuffmanCode,
339) {
340 debug_assert_eq!(end % step, 0);
341 loop {
342 end -= step;
343 table[base + position(end)] = code;
344 if end <= 0 {
345 break;
346 }
347 }
348}
349
350// upstream: src/utils/huffman_utils.c NextTableBitSize
351/// Returns the table width of the next 2nd level table. `count` is the
352/// histogram of bit lengths for the remaining symbols, `len` is the code length
353/// of the next processed symbol.
354#[must_use]
355fn next_table_bit_size(count: &[i32], mut len: i32, root_bits: i32) -> i32 {
356 let mut left = 1 << (len - root_bits);
357 while len < MAX_ALLOWED_CODE_LENGTH {
358 left -= count[position(len)];
359 if left <= 0 {
360 break;
361 }
362 len += 1;
363 left <<= 1;
364 }
365 len - root_bits
366}
367
368/// Truncates a code length or a table width to the `uint8_t` of
369/// `HuffmanCode::bits`, as the C cast does.
370#[expect(
371 clippy::cast_possible_truncation,
372 clippy::cast_sign_loss,
373 reason = "the C (uint8_t) cast"
374)]
375fn code_bits(value: i32) -> u8 {
376 value as u8
377}
378
379// upstream: src/utils/huffman_utils.c BuildHuffmanTable
380/// Builds the table of `code_lengths` into `root_table`, or only validates the
381/// code lengths when `root_table` is `None`. `sorted` is a pre-allocated
382/// array for sorting symbols by code length; it is `None` exactly when
383/// `root_table` is. Returns the built table size, or 0 for an invalid tree.
384///
385/// # Panics
386///
387/// Panics for a negative code length, where C writes outside its histogram.
388#[expect(
389 clippy::too_many_lines,
390 reason = "mirrors the single C function BuildHuffmanTable"
391)]
392fn build_huffman_table(
393 mut root_table: Option<&mut [HuffmanCode]>,
394 root_bits: i32,
395 code_lengths: &[i32],
396 mut sorted: Option<&mut [u16]>,
397) -> i32 {
398 const COUNT_LEN: usize = MAX_ALLOWED_CODE_LENGTH as usize + 1;
399 let code_lengths_size =
400 i32::try_from(code_lengths.len()).expect("a code length array fits an int");
401 // next available space in table, as a position in root_table
402 let mut table: usize = 0;
403 // total size root table + 2nd level table
404 let mut total_size: i32 = 1 << root_bits;
405 // number of codes of each length:
406 let mut count = [0_i32; COUNT_LEN];
407 // offsets in sorted table for each length:
408 let mut offset = [0_i32; COUNT_LEN];
409
410 debug_assert!(code_lengths_size != 0);
411 debug_assert_eq!(root_table.is_some(), sorted.is_some());
412 debug_assert!(root_bits > 0);
413
414 // Build histogram of code lengths.
415 for &code_length in code_lengths {
416 if code_length > MAX_ALLOWED_CODE_LENGTH {
417 return 0;
418 }
419 count[position(code_length)] += 1;
420 }
421
422 // Error, all code lengths are zeros.
423 if count[0] == code_lengths_size {
424 return 0;
425 }
426
427 // Generate offsets into sorted symbol table by code length.
428 offset[1] = 0;
429 for len in 1..MAX_ALLOWED_CODE_LENGTH as usize {
430 if count[len] > (1 << len) {
431 return 0;
432 }
433 offset[len + 1] = offset[len] + count[len];
434 }
435
436 // Sort symbols by length, by symbol order within each length.
437 for (symbol, &symbol_code_length) in code_lengths.iter().enumerate() {
438 if symbol_code_length > 0 {
439 let length = position(symbol_code_length);
440 if let Some(sorted) = sorted.as_deref_mut() {
441 if offset[length] >= code_lengths_size {
442 return 0;
443 }
444 sorted[position(offset[length])] =
445 u16::try_from(symbol).expect("a symbol index fits uint16_t");
446 offset[length] += 1;
447 } else {
448 offset[length] += 1;
449 }
450 }
451 }
452
453 // Special case code with only one value.
454 if offset[MAX_ALLOWED_CODE_LENGTH as usize] == 1 {
455 if let Some(sorted) = sorted.as_deref() {
456 let code = HuffmanCode {
457 bits: 0,
458 value: sorted[0],
459 };
460 let root_table = root_table
461 .as_deref_mut()
462 .expect("a sorted array comes with a root table");
463 replicate_value(root_table, table, 1, total_size, code);
464 }
465 return total_size;
466 }
467
468 {
469 // step size to replicate values in current table
470 let mut step: i32;
471 // low bits for current root entry
472 let mut low: u32 = 0xffff_ffff;
473 // mask for low bits
474 let mask: u32 = (total_size - 1).cast_unsigned();
475 // reversed prefix code
476 let mut key: u32 = 0;
477 // number of Huffman tree nodes
478 let mut num_nodes: i32 = 1;
479 // number of open branches in current tree level
480 let mut num_open: i32 = 1;
481 // key length of current table
482 let mut table_bits: i32;
483 // size of current table
484 let mut table_size: i32 = 1 << root_bits;
485 // symbol index in the sorted table
486 let mut symbol: usize = 0;
487 // Fill in root table.
488 let mut len: i32 = 1;
489 step = 2;
490 while len <= root_bits {
491 num_open <<= 1;
492 num_nodes += num_open;
493 num_open -= count[position(len)];
494 if num_open < 0 {
495 return 0;
496 }
497 if let (Some(root_table), Some(sorted)) = (root_table.as_deref_mut(), sorted.as_deref())
498 {
499 while count[position(len)] > 0 {
500 let code = HuffmanCode {
501 bits: code_bits(len),
502 value: sorted[symbol],
503 };
504 symbol += 1;
505 replicate_value(root_table, table + key as usize, step, table_size, code);
506 key = get_next_key(key, len);
507 count[position(len)] -= 1;
508 }
509 }
510 len += 1;
511 step <<= 1;
512 }
513
514 // Fill in 2nd level tables and add pointers to root table.
515 len = root_bits + 1;
516 step = 2;
517 while len <= MAX_ALLOWED_CODE_LENGTH {
518 num_open <<= 1;
519 num_nodes += num_open;
520 num_open -= count[position(len)];
521 if num_open < 0 {
522 return 0;
523 }
524 while count[position(len)] > 0 {
525 if (key & mask) != low {
526 if root_table.is_some() {
527 table += position(table_size);
528 }
529 table_bits = next_table_bit_size(&count, len, root_bits);
530 table_size = 1 << table_bits;
531 total_size += table_size;
532 low = key & mask;
533 if let Some(root_table) = root_table.as_deref_mut() {
534 let entry = &mut root_table[low as usize];
535 entry.bits = code_bits(table_bits + root_bits);
536 entry.value = table_value(table - low as usize);
537 }
538 }
539 if let (Some(root_table), Some(sorted)) =
540 (root_table.as_deref_mut(), sorted.as_deref())
541 {
542 let code = HuffmanCode {
543 bits: code_bits(len - root_bits),
544 value: sorted[symbol],
545 };
546 symbol += 1;
547 replicate_value(
548 root_table,
549 table + (key >> root_bits) as usize,
550 step,
551 table_size,
552 code,
553 );
554 }
555 key = get_next_key(key, len);
556 count[position(len)] -= 1;
557 }
558 len += 1;
559 step <<= 1;
560 }
561
562 // Check if tree is full.
563 if num_nodes != 2 * offset[MAX_ALLOWED_CODE_LENGTH as usize] - 1 {
564 return 0;
565 }
566 }
567
568 total_size
569}
570
571/// Truncates the distance from a root entry to its 2nd level table to the
572/// `uint16_t` of `HuffmanCode::value`, as the C cast does.
573#[expect(clippy::cast_possible_truncation, reason = "the C (uint16_t) cast")]
574fn table_value(distance: usize) -> u16 {
575 distance as u16
576}
577
578// upstream: src/utils/huffman_utils.c MAX_CODE_LENGTHS_SIZE
579/// Maximum `code_lengths_size` is 2328 (reached for 11-bit
580/// `color_cache_bits`). More commonly, the value is around ~280.
581const MAX_CODE_LENGTHS_SIZE: i32 = (1 << MAX_CACHE_BITS) + NUM_LITERAL_CODES + NUM_LENGTH_CODES;
582// upstream: src/utils/huffman_utils.c SORTED_SIZE_CUTOFF
583/// Cut-off value for switching between heap and stack allocation.
584const SORTED_SIZE_CUTOFF: usize = 512;
585
586// upstream: src/utils/huffman_utils.c VP8LBuildHuffmanTable
587/// Builds Huffman lookup table assuming code lengths are in symbol order.
588///
589/// `code_lengths` holds the `code_lengths_size` lengths of the C call. With
590/// `root_table == None` the code lengths are only validated, and nothing is
591/// built. The table is built at `curr_table` of the current segment, which
592/// grows a new segment when the current one is too small; `curr_table` itself
593/// does not move. Returns built table size or 0 in case of error (invalid tree
594/// or memory error).
595///
596/// # Panics
597///
598/// Panics for an empty `code_lengths` or a negative code length; C asserts the
599/// first and writes outside its histogram for the second.
600#[must_use]
601pub fn vp8l_build_huffman_table(
602 root_table: Option<&mut HuffmanTables>,
603 root_bits: i32,
604 code_lengths: &[i32],
605) -> i32 {
606 let total_size = build_huffman_table(None, root_bits, code_lengths, None);
607 let code_lengths_size =
608 i32::try_from(code_lengths.len()).expect("a code length array fits an int");
609 debug_assert!(code_lengths_size <= MAX_CODE_LENGTHS_SIZE);
610 let Some(root_table) = root_table else {
611 return total_size;
612 };
613 if total_size == 0 {
614 return total_size;
615 }
616
617 let curr_segment = root_table.segment(root_table.curr_segment);
618 if curr_segment.curr_table + position(total_size) >= position(curr_segment.size) {
619 // If 'root_table' does not have enough memory, allocate a new segment.
620 // The available part of root_table->curr_segment is left unused because we
621 // need a contiguous buffer.
622 let segment_size = curr_segment.size;
623 // The C segment struct: WebPSafeMalloc(1, sizeof(*next)) always passes the
624 // size test, so only a refusal of the host remains.
625 if root_table.next_segments.try_reserve(1).is_err() {
626 return 0;
627 }
628 // Fill the new segment.
629 // We need at least 'total_size' but if that value is small, it is better to
630 // allocate a big chunk to prevent more allocations later. 'segment_size' is
631 // therefore chosen (any other arbitrary value could be chosen).
632 let size = if total_size > segment_size {
633 total_size
634 } else {
635 segment_size
636 };
637 let Some(mut start) =
638 webp_safe_malloc::<HuffmanCode>(element_count(size), HuffmanCode::C_SIZE)
639 else {
640 return 0;
641 };
642 start.resize(position(size), HuffmanCode::default());
643 // Point to the new segment: it becomes the `next` of the current segment.
644 root_table.next_segments.truncate(root_table.curr_segment);
645 root_table.next_segments.push(HuffmanTablesSegment {
646 start,
647 curr_table: 0,
648 size,
649 });
650 root_table.curr_segment = root_table.next_segments.len();
651 }
652 let curr_segment = root_table.segment_mut(root_table.curr_segment);
653 let table = &mut curr_segment.start[curr_segment.curr_table..];
654 if code_lengths.len() <= SORTED_SIZE_CUTOFF {
655 // use local stack-allocated array.
656 let mut sorted = [0_u16; SORTED_SIZE_CUTOFF];
657 build_huffman_table(Some(table), root_bits, code_lengths, Some(&mut sorted));
658 } else {
659 // rare case. Use heap allocation.
660 let Some(mut sorted) = webp_safe_malloc::<u16>(element_count(code_lengths_size), 2) else {
661 return 0;
662 };
663 sorted.resize(code_lengths.len(), 0);
664 build_huffman_table(Some(table), root_bits, code_lengths, Some(&mut sorted));
665 }
666 total_size
667}
668
669// upstream: src/utils/huffman_utils.c VP8LHuffmanTablesAllocate
670/// Allocates a `HuffmanTables` with `size` contiguous `HuffmanCode`s. Returns
671/// `false` on memory allocation error, `true` otherwise.
672///
673/// As in C, the current segment becomes `root` and the chain after it is cut
674/// before the allocation, and a failure leaves `root.start` empty while
675/// `root.curr_table` and `root.size` keep their values.
676#[must_use]
677pub fn vp8l_huffman_tables_allocate(size: i32, huffman_tables: &mut HuffmanTables) -> bool {
678 // Have 'segment' point to the first segment for now, 'root'.
679 huffman_tables.curr_segment = 0;
680 huffman_tables.next_segments = Vec::new();
681 let root = &mut huffman_tables.root;
682 // Allocate root.
683 let Some(mut start) = webp_safe_malloc::<HuffmanCode>(element_count(size), HuffmanCode::C_SIZE)
684 else {
685 root.start = Vec::new();
686 return false;
687 };
688 start.resize(position(size), HuffmanCode::default());
689 root.start = start;
690 root.curr_table = 0;
691 root.size = size;
692 true
693}
694
695// upstream: src/utils/huffman_utils.c VP8LHuffmanTablesDeallocate
696/// Frees the codes of every segment: `root.start` becomes empty and the chain
697/// after it is dropped. `curr_segment`, `root.curr_table` and `root.size` keep
698/// their values, as in C.
699pub fn vp8l_huffman_tables_deallocate(huffman_tables: &mut HuffmanTables) {
700 // Free the root node.
701 huffman_tables.root.start = Vec::new();
702 // Free the following nodes.
703 huffman_tables.next_segments = Vec::new();
704}