4 * Functions used for decompression.
8 * Copyright (C) 2012, 2013 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 3 of the License, or (at your option)
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more
22 * You should have received a copy of the GNU General Public License
23 * along with wimlib; if not, see http://www.gnu.org/licenses/.
30 #include "wimlib/decompress.h"
31 #include "wimlib/util.h"
36 * make_huffman_decode_table: - Builds a fast huffman decoding table from an
37 * array that gives the length of the codeword for each symbol in the alphabet.
38 * Originally based on code written by David Tritscher (taken the original LZX
39 * decompression code); also heavily modified to add some optimizations used in
40 * the zlib code, as well as more comments.
42 * @decode_table: The array in which to create the fast huffman decoding
43 * table. It must have a length of at least
44 * (2**table_bits) + 2 * num_syms to guarantee
45 * that there is enough space.
47 * @num_syms: Number of symbols in the alphabet, including symbols
48 * that do not appear in this particular input chunk.
50 * @table_bits: Any symbols with a code length of table_bits or less can
51 * be decoded in one lookup of the table. 2**table_bits
52 * must be greater than or equal to @num_syms if there are
53 * any Huffman codes longer than @table_bits.
55 * @lens: An array of length @num_syms, indexable by symbol, that
56 * gives the length of the Huffman codeword for that
57 * symbol. Because the Huffman tree is in canonical form,
58 * it can be reconstructed by only knowing the length of
59 * the codeword for each symbol. It is assumed, but not
60 * checked, that every length is less than
63 * @max_codeword_len: The longest codeword length allowed in the compression
66 * Returns 0 on success; returns -1 if the length values do not correspond to a
69 * The format of the Huffamn decoding table is as follows. The first (1 <<
70 * table_bits) entries of the table are indexed by chunks of the input of size
71 * @table_bits. If the next Huffman codeword in the input happens to have a
72 * length of exactly @table_bits, the symbol is simply read directly from the
73 * decoding table. Alternatively, if the next Huffman codeword has length _less
74 * than_ @table_bits, the symbol is also read directly from the decode table;
75 * this is possible because every entry in the table that is indexed by an
76 * integer that has the shorter codeword as a binary prefix is filled in with
77 * the appropriate symbol. If a codeword has length n <= table_bits, it will
78 * have 2**(table_bits - n) possible suffixes, and thus that many entries in the
81 * It's a bit more complicated if the next Huffman codeword has length of more
82 * than @table_bits. The table entry indexed by the first @table_bits of that
83 * codeword cannot give the appropriate symbol directly, because that entry is
84 * guaranteed to be referenced by the Huffman codewords of multiple symbols.
85 * And while the LZX compression format does not allow codes longer than 16
86 * bits, a table of size (2 ** 16) = 65536 entries would be too slow to create.
88 * There are several different ways to make it possible to look up the symbols
89 * for codewords longer than @table_bits. One way is to make the entries for
90 * the prefixes of length @table_bits of those entries be pointers to additional
91 * decoding tables that are indexed by some number of additional bits of the
92 * codeword. The technique used here is a bit simpler, however: just store the
93 * needed subtrees of the Huffman tree in the decoding table after the lookup
94 * entries, beginning at index (2**table_bits). Real pointers are replaced by
95 * indices into the decoding table, and symbol entries are distinguished from
96 * pointers by the fact that values less than @num_syms must be symbol values.
99 make_huffman_decode_table(u16 * restrict decode_table, unsigned num_syms,
100 unsigned table_bits, const u8 * restrict lens,
101 unsigned max_codeword_len)
103 unsigned len_counts[max_codeword_len + 1];
104 u16 sorted_syms[num_syms];
105 unsigned offsets[max_codeword_len + 1];
106 const unsigned table_num_entries = 1 << table_bits;
108 /* accumulate lengths for codes */
109 for (unsigned i = 0; i <= max_codeword_len; i++)
112 for (unsigned sym = 0; sym < num_syms; sym++) {
113 wimlib_assert2(lens[sym] <= max_codeword_len);
114 len_counts[lens[sym]]++;
117 /* check for an over-subscribed or incomplete set of lengths */
119 for (unsigned len = 1; len <= max_codeword_len; len++) {
121 left -= len_counts[len];
122 if (left < 0) { /* over-subscribed */
123 ERROR("Invalid Huffman code (over-subscribed)");
127 if (left != 0) /* incomplete set */{
128 if (left == 1 << max_codeword_len) {
129 /* Empty code--- okay in XPRESS and LZX */
130 memset(decode_table, 0,
131 table_num_entries * sizeof(decode_table[0]));
134 ERROR("Invalid Huffman code (incomplete set)");
139 /* Generate offsets into symbol table for each length for sorting */
141 for (unsigned len = 1; len < max_codeword_len; len++)
142 offsets[len + 1] = offsets[len] + len_counts[len];
144 /* Sort symbols primarily by length and secondarily by symbol order.
145 * This is basically a count-sort over the codeword lengths.
146 * In the process, calculate the number of symbols that have nonzero
147 * length and are therefore used in the symbol stream. */
148 unsigned num_used_syms = 0;
149 for (unsigned sym = 0; sym < num_syms; sym++) {
150 if (lens[sym] != 0) {
151 sorted_syms[offsets[lens[sym]]++] = sym;
156 /* Fill entries for codewords short enough for a direct mapping. We can
157 * take advantage of the ordering of the codewords, since the Huffman
158 * code is canonical. It must be the case that all the codewords of
159 * some length L numerically precede all the codewords of length L + 1.
160 * Furthermore, if we have 2 symbols A and B with the same codeword
161 * length but symbol A is sorted before symbol B, then then we know that
162 * the codeword for A numerically precedes the codeword for B. */
163 unsigned decode_table_pos = 0;
166 wimlib_assert2(num_used_syms != 0);
168 unsigned sym = sorted_syms[i];
169 unsigned codeword_len = lens[sym];
170 if (codeword_len > table_bits)
173 unsigned num_entries = 1 << (table_bits - codeword_len);
175 /* Fill in the Huffman decode table entries one 16-bit
176 * integer at a time. */
178 decode_table[decode_table_pos++] = sym;
179 } while (--num_entries);
181 wimlib_assert2(decode_table_pos <= table_num_entries);
182 if (++i == num_used_syms) {
183 wimlib_assert2(decode_table_pos == table_num_entries);
184 /* No codewords were longer than @table_bits, so the
185 * table is now entirely filled with the codewords. */
190 wimlib_assert2(i < num_used_syms);
191 wimlib_assert2(decode_table_pos < table_num_entries);
193 /* Fill in the remaining entries, which correspond to codes longer than
196 * First, zero out the rest of the entries. This is necessary so that
197 * the entries appear as "unallocated" in the next part. */
199 unsigned j = decode_table_pos;
202 } while (++j != table_num_entries);
205 /* Assert that 2**table_bits is at least num_syms. If this wasn't the
206 * case, we wouldn't be able to distinguish pointer entries from symbol
208 wimlib_assert2(table_num_entries >= num_syms);
210 /* The current Huffman codeword */
211 unsigned cur_codeword = decode_table_pos;
213 /* The tree nodes are allocated starting at decode_table[1 <<
214 * table_bits]. Remember that the full size of the table, including the
215 * extra space for the tree nodes, is actually 2**table_bits + 2 *
216 * num_syms slots, while table_num_entries is only 2**table_Bits. */
217 unsigned next_free_tree_slot = table_num_entries;
219 /* Go through every codeword of length greater than @table_bits,
220 * primarily in order of codeword length and secondarily in order of
222 unsigned prev_codeword_len = table_bits;
224 unsigned sym = sorted_syms[i];
225 unsigned codeword_len = lens[sym];
226 unsigned extra_bits = codeword_len - table_bits;
228 cur_codeword <<= (codeword_len - prev_codeword_len);
229 prev_codeword_len = codeword_len;
231 /* index of the current node; find it from the prefix of the
232 * current Huffman codeword. */
233 unsigned node_idx = cur_codeword >> extra_bits;
234 wimlib_assert2(node_idx < table_num_entries);
236 /* Go through each bit of the current Huffman codeword beyond
237 * the prefix of length @table_bits and walk the tree,
238 * allocating any slots that have not yet been allocated. */
241 /* If the current tree node points to nowhere
242 * but we need to follow it, allocate a new node
243 * for it to point to. */
244 if (decode_table[node_idx] == 0) {
245 decode_table[node_idx] = next_free_tree_slot;
246 decode_table[next_free_tree_slot++] = 0;
247 decode_table[next_free_tree_slot++] = 0;
248 wimlib_assert2(next_free_tree_slot <=
249 table_num_entries + 2 * num_syms);
252 /* Set node_idx to left child */
253 node_idx = decode_table[node_idx];
255 /* Is the next bit 0 or 1? If 0, go left (already done).
256 * If 1, go right by incrementing node_idx. */
258 node_idx += (cur_codeword >> extra_bits) & 1;
259 } while (extra_bits != 0);
261 /* node_idx is now the index of the leaf entry into which the
262 * actual symbol will go. */
263 decode_table[node_idx] = sym;
265 /* cur_codeword is always incremented because this is
266 * how canonical Huffman codes are generated (add 1 for
267 * each code, then left shift whenever the code length
270 } while (++i != num_used_syms);
274 /* Reads a Huffman-encoded symbol from the bistream when the number of remaining
275 * bits is less than the maximum codeword length. */
277 read_huffsym_near_end_of_input(struct input_bitstream *istream,
278 const u16 decode_table[],
284 unsigned bitsleft = istream->bitsleft;
289 if (table_bits > bitsleft) {
292 key_bits = bitstream_peek_bits(istream, key_size) <<
293 (table_bits - key_size);
295 key_size = table_bits;
296 bitsleft -= table_bits;
297 key_bits = bitstream_peek_bits(istream, table_bits);
300 sym = decode_table[key_bits];
301 if (sym >= num_syms) {
302 bitstream_remove_bits(istream, key_size);
305 ERROR("Input stream exhausted");
308 key_bits = sym + bitstream_peek_bits(istream, 1);
309 bitstream_remove_bits(istream, 1);
311 } while ((sym = decode_table[key_bits]) >= num_syms);
313 bitstream_remove_bits(istream, lens[sym]);