4 * The following copying information applies to this specific source code file:
6 * Written in 2012-2014 by Eric Biggers <ebiggers3@gmail.com>
8 * To the extent possible under law, the author(s) have dedicated all copyright
9 * and related and neighboring rights to this software to the public domain
10 * worldwide via the Creative Commons Zero 1.0 Universal Public Domain
11 * Dedication (the "CC0").
13 * This software is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the CC0 for more details.
17 * You should have received a copy of the CC0 along with this software; if not
18 * see <http://creativecommons.org/publicdomain/zero/1.0/>.
27 #include "wimlib/compress_common.h"
28 #include "wimlib/util.h"
30 /* Given the binary tree node A[subtree_idx] whose children already
31 * satisfy the maxheap property, swap the node with its greater child
32 * until it is greater than both its children, so that the maxheap
33 * property is satisfied in the subtree rooted at A[subtree_idx]. */
35 heapify_subtree(u32 A[], unsigned length, unsigned subtree_idx)
42 parent_idx = subtree_idx;
43 while ((child_idx = parent_idx * 2) <= length) {
44 if (child_idx < length && A[child_idx + 1] > A[child_idx])
46 if (v >= A[child_idx])
48 A[parent_idx] = A[child_idx];
49 parent_idx = child_idx;
54 /* Rearrange the array 'A' so that it satisfies the maxheap property.
55 * 'A' uses 1-based indices, so the children of A[i] are A[i*2] and A[i*2 + 1].
58 heapify_array(u32 A[], unsigned length)
60 for (unsigned subtree_idx = length / 2; subtree_idx >= 1; subtree_idx--)
61 heapify_subtree(A, length, subtree_idx);
64 /* Sort the array 'A', which contains 'length' unsigned 32-bit integers. */
66 heapsort(u32 A[], unsigned length)
68 A--; /* Use 1-based indices */
70 heapify_array(A, length);
73 swap(A[1], A[length]);
75 heapify_subtree(A, length, 1);
79 #define NUM_SYMBOL_BITS 10
80 #define SYMBOL_MASK ((1 << NUM_SYMBOL_BITS) - 1)
83 * Sort the symbols primarily by frequency and secondarily by symbol
84 * value. Discard symbols with zero frequency and fill in an array with
85 * the remaining symbols, along with their frequencies. The low
86 * NUM_SYMBOL_BITS bits of each array entry will contain the symbol
87 * value, and the remaining bits will contain the frequency.
90 * Number of symbols in the alphabet.
91 * Can't be greater than (1 << NUM_SYMBOL_BITS).
94 * The frequency of each symbol.
97 * An array that eventually will hold the length of each codeword.
98 * This function only fills in the codeword lengths for symbols that
99 * have zero frequency, which are not well defined per se but will
103 * The output array, described above.
105 * Returns the number of entries in 'symout' that were filled. This is
106 * the number of symbols that have nonzero frequency.
109 sort_symbols(unsigned num_syms, const u32 freqs[restrict],
110 u8 lens[restrict], u32 symout[restrict])
112 unsigned num_used_syms;
113 unsigned num_counters;
115 /* We rely on heapsort, but with an added optimization. Since
116 * it's common for most symbol frequencies to be low, we first do
117 * a count sort using a limited number of counters. High
118 * frequencies will be counted in the last counter, and only they
119 * will be sorted with heapsort.
121 * Note: with more symbols, it is generally beneficial to have more
122 * counters. About 1 counter per 4 symbols seems fast.
124 * Note: I also tested radix sort, but even for large symbol
125 * counts (> 255) and frequencies bounded at 16 bits (enabling
126 * radix sort by just two base-256 digits), it didn't seem any
127 * faster than the method implemented here.
129 * Note: I tested the optimized quicksort implementation from
130 * glibc (with indirection overhead removed), but it was only
131 * marginally faster than the simple heapsort implemented here.
133 * Tests were done with building the codes for LZX. Results may
134 * vary for different compression algorithms...! */
136 num_counters = ALIGN(DIV_ROUND_UP(num_syms, 4), 4);
138 unsigned counters[num_counters];
140 memset(counters, 0, sizeof(counters));
142 /* Count the frequencies. */
143 for (unsigned sym = 0; sym < num_syms; sym++)
144 counters[min(freqs[sym], num_counters - 1)]++;
146 /* Make the counters cumulative, ignoring the zero-th, which
147 * counted symbols with zero frequency. As a side effect, this
148 * calculates the number of symbols with nonzero frequency. */
150 for (unsigned i = 1; i < num_counters; i++) {
151 unsigned count = counters[i];
152 counters[i] = num_used_syms;
153 num_used_syms += count;
156 /* Sort nonzero-frequency symbols using the counters. At the
157 * same time, set the codeword lengths of zero-frequency symbols
159 for (unsigned sym = 0; sym < num_syms; sym++) {
160 u32 freq = freqs[sym];
162 symout[counters[min(freq, num_counters - 1)]++] =
163 sym | (freq << NUM_SYMBOL_BITS);
169 /* Sort the symbols counted in the last counter. */
170 heapsort(symout + counters[num_counters - 2],
171 counters[num_counters - 1] - counters[num_counters - 2]);
173 return num_used_syms;
177 * Build the Huffman tree.
179 * This is an optimized implementation that
180 * (a) takes advantage of the frequencies being already sorted;
181 * (b) only generates non-leaf nodes, since the non-leaf nodes of a
182 * Huffman tree are sufficient to generate a canonical code;
183 * (c) Only stores parent pointers, not child pointers;
184 * (d) Produces the nodes in the same memory used for input
185 * frequency information.
187 * Array 'A', which contains 'sym_count' entries, is used for both input
188 * and output. For this function, 'sym_count' must be at least 2.
190 * For input, the array must contain the frequencies of the symbols,
191 * sorted in increasing order. Specifically, each entry must contain a
192 * frequency left shifted by NUM_SYMBOL_BITS bits. Any data in the low
193 * NUM_SYMBOL_BITS bits of the entries will be ignored by this function.
194 * Although these bits will, in fact, contain the symbols that correspond
195 * to the frequencies, this function is concerned with frequencies only
196 * and keeps the symbols as-is.
198 * For output, this function will produce the non-leaf nodes of the
199 * Huffman tree. These nodes will be stored in the first (sym_count - 1)
200 * entries of the array. Entry A[sym_count - 2] will represent the root
201 * node. Each other node will contain the zero-based index of its parent
202 * node in 'A', left shifted by NUM_SYMBOL_BITS bits. The low
203 * NUM_SYMBOL_BITS bits of each entry in A will be kept as-is. Again,
204 * note that although these low bits will, in fact, contain a symbol
205 * value, this symbol will have *no relationship* with the Huffman tree
206 * node that happens to occupy the same slot. This is because this
207 * implementation only generates the non-leaf nodes of the tree.
210 build_tree(u32 A[], unsigned sym_count)
212 /* Index, in 'A', of next lowest frequency symbol that has not
213 * yet been processed. */
216 /* Index, in 'A', of next lowest frequency parentless non-leaf
217 * node; or, if equal to 'e', then no such node exists yet. */
220 /* Index, in 'A', of next node to allocate as a non-leaf. */
227 /* Choose the two next lowest frequency entries. */
229 if (i != sym_count &&
230 (b == e || (A[i] >> NUM_SYMBOL_BITS) <= (A[b] >> NUM_SYMBOL_BITS)))
235 if (i != sym_count &&
236 (b == e || (A[i] >> NUM_SYMBOL_BITS) <= (A[b] >> NUM_SYMBOL_BITS)))
241 /* Allocate a non-leaf node and link the entries to it.
243 * If we link an entry that we're visiting for the first
244 * time (via index 'i'), then we're actually linking a
245 * leaf node and it will have no effect, since the leaf
246 * will be overwritten with a non-leaf when index 'e'
247 * catches up to it. But it's not any slower to
248 * unconditionally set the parent index.
250 * We also compute the frequency of the non-leaf node as
251 * the sum of its two children's frequencies. */
253 freq_shifted = (A[m] & ~SYMBOL_MASK) + (A[n] & ~SYMBOL_MASK);
255 A[m] = (A[m] & SYMBOL_MASK) | (e << NUM_SYMBOL_BITS);
256 A[n] = (A[n] & SYMBOL_MASK) | (e << NUM_SYMBOL_BITS);
257 A[e] = (A[e] & SYMBOL_MASK) | freq_shifted;
259 } while (sym_count - e > 1);
260 /* When just one entry remains, it is a "leaf" that was
261 * linked to some other node. We ignore it, since the
262 * rest of the array contains the non-leaves which we
263 * need. (Note that we're assuming the cases with 0 or 1
264 * symbols were handled separately.) */
268 * Given the stripped-down Huffman tree constructed by build_tree(),
269 * determine the number of codewords that should be assigned each
270 * possible length, taking into account the length-limited constraint.
273 * The array produced by build_tree(), containing parent index
274 * information for the non-leaf nodes of the Huffman tree. Each
275 * entry in this array is a node; a node's parent always has a
276 * greater index than that node itself. This function will
277 * overwrite the parent index information in this array, so
278 * essentially it will destroy the tree. However, the data in the
279 * low NUM_SYMBOL_BITS of each entry will be preserved.
282 * The 0-based index of the root node in 'A', and consequently one
283 * less than the number of tree node entries in 'A'. (Or, really 2
284 * less than the actual length of 'A'.)
287 * An array of length ('max_codeword_len' + 1) in which the number of
288 * codewords having each length <= max_codeword_len will be
292 * The maximum permissible codeword length.
295 compute_length_counts(u32 A[restrict], unsigned root_idx,
296 unsigned len_counts[restrict], unsigned max_codeword_len)
298 /* The key observations are:
300 * (1) We can traverse the non-leaf nodes of the tree, always
301 * visiting a parent before its children, by simply iterating
302 * through the array in reverse order. Consequently, we can
303 * compute the depth of each node in one pass, overwriting the
304 * parent indices with depths.
306 * (2) We can initially assume that in the real Huffman tree,
307 * both children of the root are leaves. This corresponds to two
308 * codewords of length 1. Then, whenever we visit a (non-leaf)
309 * node during the traversal, we modify this assumption to
310 * account for the current node *not* being a leaf, but rather
311 * its two children being leaves. This causes the loss of one
312 * codeword for the current depth and the addition of two
313 * codewords for the current depth plus one.
315 * (3) We can handle the length-limited constraint fairly easily
316 * by simply using the largest length available when a depth
317 * exceeds max_codeword_len.
320 for (unsigned len = 0; len <= max_codeword_len; len++)
324 /* Set the root node's depth to 0. */
325 A[root_idx] &= SYMBOL_MASK;
327 for (int node = root_idx - 1; node >= 0; node--) {
329 /* Calculate the depth of this node. */
331 unsigned parent = A[node] >> NUM_SYMBOL_BITS;
332 unsigned parent_depth = A[parent] >> NUM_SYMBOL_BITS;
333 unsigned depth = parent_depth + 1;
334 unsigned len = depth;
336 /* Set the depth of this node so that it is available
337 * when its children (if any) are processed. */
339 A[node] = (A[node] & SYMBOL_MASK) | (depth << NUM_SYMBOL_BITS);
341 /* If needed, decrease the length to meet the
342 * length-limited constraint. This is not the optimal
343 * method for generating length-limited Huffman codes!
344 * But it should be good enough. */
345 if (len >= max_codeword_len) {
346 len = max_codeword_len;
349 } while (len_counts[len] == 0);
352 /* Account for the fact that we have a non-leaf node at
353 * the current depth. */
355 len_counts[len + 1] += 2;
360 * Generate the codewords for a canonical Huffman code.
363 * The output array for codewords. In addition, initially this
364 * array must contain the symbols, sorted primarily by frequency and
365 * secondarily by symbol value, in the low NUM_SYMBOL_BITS bits of
369 * Output array for codeword lengths.
372 * An array that provides the number of codewords that will have
373 * each possible length <= max_codeword_len.
376 * Maximum length, in bits, of each codeword.
379 * Number of symbols in the alphabet, including symbols with zero
380 * frequency. This is the length of the 'A' and 'len' arrays.
383 gen_codewords(u32 A[restrict], u8 lens[restrict],
384 const unsigned len_counts[restrict],
385 unsigned max_codeword_len, unsigned num_syms)
387 u32 next_codewords[max_codeword_len + 1];
389 /* Given the number of codewords that will have each length,
390 * assign codeword lengths to symbols. We do this by assigning
391 * the lengths in decreasing order to the symbols sorted
392 * primarily by increasing frequency and secondarily by
393 * increasing symbol value. */
394 for (unsigned i = 0, len = max_codeword_len; len >= 1; len--) {
395 unsigned count = len_counts[len];
397 lens[A[i++] & SYMBOL_MASK] = len;
400 /* Generate the codewords themselves. We initialize the
401 * 'next_codewords' array to provide the lexicographically first
402 * codeword of each length, then assign codewords in symbol
403 * order. This produces a canonical code. */
404 next_codewords[0] = 0;
405 next_codewords[1] = 0;
406 for (unsigned len = 2; len <= max_codeword_len; len++)
407 next_codewords[len] =
408 (next_codewords[len - 1] + len_counts[len - 1]) << 1;
410 for (unsigned sym = 0; sym < num_syms; sym++)
411 A[sym] = next_codewords[lens[sym]]++;
415 * ---------------------------------------------------------------------
416 * make_canonical_huffman_code()
417 * ---------------------------------------------------------------------
419 * Given an alphabet and the frequency of each symbol in it, construct a
420 * length-limited canonical Huffman code.
423 * The number of symbols in the alphabet. The symbols are the
424 * integers in the range [0, num_syms - 1]. This parameter must be
425 * at least 2 and can't be greater than (1 << NUM_SYMBOL_BITS).
428 * The maximum permissible codeword length.
431 * An array of @num_syms entries, each of which specifies the
432 * frequency of the corresponding symbol. It is valid for some,
433 * none, or all of the frequencies to be 0.
436 * An array of @num_syms entries in which this function will return
437 * the length, in bits, of the codeword assigned to each symbol.
438 * Symbols with 0 frequency will not have codewords per se, but
439 * their entries in this array will be set to 0. No lengths greater
440 * than @max_codeword_len will be assigned.
443 * An array of @num_syms entries in which this function will return
444 * the codeword for each symbol, right-justified and padded on the
445 * left with zeroes. Codewords for symbols with 0 frequency will be
448 * ---------------------------------------------------------------------
450 * This function builds a length-limited canonical Huffman code.
452 * A length-limited Huffman code contains no codewords longer than some
453 * specified length, and has exactly (with some algorithms) or
454 * approximately (with the algorithm used here) the minimum weighted path
455 * length from the root, given this constraint.
457 * A canonical Huffman code satisfies the properties that a longer
458 * codeword never lexicographically precedes a shorter codeword, and the
459 * lexicographic ordering of codewords of the same length is the same as
460 * the lexicographic ordering of the corresponding symbols. A canonical
461 * Huffman code, or more generally a canonical prefix code, can be
462 * reconstructed from only a list containing the codeword length of each
465 * The classic algorithm to generate a Huffman code creates a node for
466 * each symbol, then inserts these nodes into a min-heap keyed by symbol
467 * frequency. Then, repeatedly, the two lowest-frequency nodes are
468 * removed from the min-heap and added as the children of a new node
469 * having frequency equal to the sum of its two children, which is then
470 * inserted into the min-heap. When only a single node remains in the
471 * min-heap, it is the root of the Huffman tree. The codeword for each
472 * symbol is determined by the path needed to reach the corresponding
473 * node from the root. Descending to the left child appends a 0 bit,
474 * whereas descending to the right child appends a 1 bit.
476 * The classic algorithm is relatively easy to understand, but it is
477 * subject to a number of inefficiencies. In practice, it is fastest to
478 * first sort the symbols by frequency. (This itself can be subject to
479 * an optimization based on the fact that most frequencies tend to be
480 * low.) At the same time, we sort secondarily by symbol value, which
481 * aids the process of generating a canonical code. Then, during tree
482 * construction, no heap is necessary because both the leaf nodes and the
483 * unparented non-leaf nodes can be easily maintained in sorted order.
484 * Consequently, there can never be more than two possibilities for the
485 * next-lowest-frequency node.
487 * In addition, because we're generating a canonical code, we actually
488 * don't need the leaf nodes of the tree at all, only the non-leaf nodes.
489 * This is because for canonical code generation we don't need to know
490 * where the symbols are in the tree. Rather, we only need to know how
491 * many leaf nodes have each depth (codeword length). And this
492 * information can, in fact, be quickly generated from the tree of
495 * Furthermore, we can build this stripped-down Huffman tree directly in
496 * the array in which the codewords are to be generated, provided that
497 * these array slots are large enough to hold a symbol and frequency
500 * Still furthermore, we don't even need to maintain explicit child
501 * pointers. We only need the parent pointers, and even those can be
502 * overwritten in-place with depth information as part of the process of
503 * extracting codeword lengths from the tree. So in summary, we do NOT
504 * need a big structure like:
506 * struct huffman_tree_node {
507 * unsigned int symbol;
508 * unsigned int frequency;
509 * unsigned int depth;
510 * struct huffman_tree_node *left_child;
511 * struct huffman_tree_node *right_child;
515 * ... which often gets used in "naive" implementations of Huffman code
518 * Most of these optimizations are based on the implementation in 7-Zip
519 * (source file: C/HuffEnc.c), which has been placed in the public domain
520 * by Igor Pavlov. But I've rewritten the code with extensive comments,
521 * as it took me a while to figure out what it was doing...!
523 * ---------------------------------------------------------------------
525 * NOTE: in general, the same frequencies can be used to generate
526 * different length-limited canonical Huffman codes. One choice we have
527 * is during tree construction, when we must decide whether to prefer a
528 * leaf or non-leaf when there is a tie in frequency. Another choice we
529 * have is how to deal with codewords that would exceed @max_codeword_len
530 * bits in length. Both of these choices affect the resulting codeword
531 * lengths, which otherwise can be mapped uniquely onto the resulting
532 * canonical Huffman code.
534 * Normally, there is no problem with choosing one valid code over
535 * another, provided that they produce similar compression ratios.
536 * However, the LZMS compression format uses adaptive Huffman coding. It
537 * requires that both the decompressor and compressor build a canonical
538 * code equivalent to that which can be generated by using the classic
539 * Huffman tree construction algorithm and always processing leaves
540 * before non-leaves when there is a frequency tie. Therefore, we make
541 * sure to do this. This method also has the advantage of sometimes
542 * shortening the longest codeword that is generated.
544 * There also is the issue of how codewords longer than @max_codeword_len
545 * are dealt with. Fortunately, for LZMS this is irrelevant because
546 * because for the LZMS alphabets no codeword can ever exceed
547 * LZMS_MAX_CODEWORD_LEN (= 15). Since the LZMS algorithm regularly
548 * halves all frequencies, the frequencies cannot become high enough for
549 * a length 16 codeword to be generated. Specifically, I think that if
550 * ties are broken in favor of non-leaves (as we do), the lowest total
551 * frequency that would give a length-16 codeword would be the sum of the
552 * frequencies 1 1 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364, which
553 * is 3570. And in LZMS we can't get a frequency that high based on the
554 * alphabet sizes, rebuild frequencies, and scaling factors. This
555 * worst-case scenario is based on the following degenerate case (only
556 * the bottom of the tree shown):
571 * Excluding the first leaves (those with value 1), each leaf value must
572 * be greater than the non-leaf up 1 and down 2 from it; otherwise that
573 * leaf would have taken precedence over that non-leaf and been combined
574 * with the leaf below, thereby decreasing the height compared to that
577 * Interesting fact: if we were to instead prioritize non-leaves over
578 * leaves, then the worst case frequencies would be the Fibonacci
579 * sequence, plus an extra frequency of 1. In this hypothetical
580 * scenario, it would be slightly easier for longer codewords to be
584 make_canonical_huffman_code(unsigned num_syms, unsigned max_codeword_len,
585 const u32 freqs[restrict],
586 u8 lens[restrict], u32 codewords[restrict])
589 unsigned num_used_syms;
591 /* We begin by sorting the symbols primarily by frequency and
592 * secondarily by symbol value. As an optimization, the array
593 * used for this purpose ('A') shares storage with the space in
594 * which we will eventually return the codewords. */
596 num_used_syms = sort_symbols(num_syms, freqs, lens, A);
598 /* 'num_used_syms' is the number of symbols with nonzero
599 * frequency. This may be less than @num_syms. 'num_used_syms'
600 * is also the number of entries in 'A' that are valid. Each
601 * entry consists of a distinct symbol and a nonzero frequency
602 * packed into a 32-bit integer. */
604 /* Handle special cases where only 0 or 1 symbols were used (had
605 * nonzero frequency). */
607 if (unlikely(num_used_syms == 0)) {
608 /* Code is empty. sort_symbols() already set all lengths
609 * to 0, so there is nothing more to do. */
613 if (unlikely(num_used_syms == 1)) {
614 /* Only one symbol was used, so we only need one
615 * codeword. But two codewords are needed to form the
616 * smallest complete Huffman code, which uses codewords 0
617 * and 1. Therefore, we choose another symbol to which
618 * to assign a codeword. We use 0 (if the used symbol is
619 * not 0) or 1 (if the used symbol is 0). In either
620 * case, the lesser-valued symbol must be assigned
621 * codeword 0 so that the resulting code is canonical. */
623 unsigned sym = A[0] & SYMBOL_MASK;
624 unsigned nonzero_idx = sym ? sym : 1;
628 codewords[nonzero_idx] = 1;
629 lens[nonzero_idx] = 1;
633 /* Build a stripped-down version of the Huffman tree, sharing the
634 * array 'A' with the symbol values. Then extract length counts
635 * from the tree and use them to generate the final codewords. */
637 build_tree(A, num_used_syms);
640 unsigned len_counts[max_codeword_len + 1];
642 compute_length_counts(A, num_used_syms - 2,
643 len_counts, max_codeword_len);
645 gen_codewords(A, lens, len_counts, max_codeword_len, num_syms);