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 decode_table[], unsigned num_syms,
100 unsigned table_bits, const u8 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);
174 const unsigned entries_per_long = sizeof(unsigned long) /
175 sizeof(decode_table[0]);
176 if (num_entries >= entries_per_long) {
177 /* Fill in the Huffman decode table entries one unsigned
178 * long at a time. On 32-bit systems this is 2 entries
179 * per store, while on 64-bit systems this is 4 entries
181 wimlib_assert2(decode_table_pos % entries_per_long == 0);
182 BUILD_BUG_ON(sizeof(unsigned long) != 4 &&
183 sizeof(unsigned long) != 8);
185 unsigned long *p = (unsigned long *)&decode_table[decode_table_pos];
186 unsigned n = num_entries / entries_per_long;
187 unsigned long v = sym;
188 if (sizeof(unsigned long) >= 4)
190 if (sizeof(unsigned long) >= 8) {
191 /* This may produce a compiler warning if an
192 * unsigned long is 32 bits, but this won't be
193 * executed unless an unsigned long is at least
201 decode_table_pos += num_entries;
203 /* Fill in the Huffman decode table entries one 16-bit
204 * integer at a time. */
206 decode_table[decode_table_pos++] = sym;
207 } while (--num_entries);
209 wimlib_assert2(decode_table_pos <= table_num_entries);
210 if (++i == num_used_syms) {
211 wimlib_assert2(decode_table_pos == table_num_entries);
212 /* No codewords were longer than @table_bits, so the
213 * table is now entirely filled with the codewords. */
218 wimlib_assert2(i < num_used_syms);
219 wimlib_assert2(decode_table_pos < table_num_entries);
221 /* Fill in the remaining entries, which correspond to codes longer than
224 * First, zero out the rest of the entries. This is necessary so that
225 * the entries appear as "unallocated" in the next part. */
227 unsigned j = decode_table_pos;
230 } while (++j != table_num_entries);
233 /* Assert that 2**table_bits is at least num_syms. If this wasn't the
234 * case, we wouldn't be able to distinguish pointer entries from symbol
236 wimlib_assert2(table_num_entries >= num_syms);
238 /* The current Huffman codeword */
239 unsigned cur_codeword = decode_table_pos;
241 /* The tree nodes are allocated starting at decode_table[1 <<
242 * table_bits]. Remember that the full size of the table, including the
243 * extra space for the tree nodes, is actually 2**table_bits + 2 *
244 * num_syms slots, while table_num_entries is only 2**table_Bits. */
245 unsigned next_free_tree_slot = table_num_entries;
247 /* Go through every codeword of length greater than @table_bits,
248 * primarily in order of codeword length and secondarily in order of
250 unsigned prev_codeword_len = table_bits;
252 unsigned sym = sorted_syms[i];
253 unsigned codeword_len = lens[sym];
254 unsigned extra_bits = codeword_len - table_bits;
256 cur_codeword <<= (codeword_len - prev_codeword_len);
257 prev_codeword_len = codeword_len;
259 /* index of the current node; find it from the prefix of the
260 * current Huffman codeword. */
261 unsigned node_idx = cur_codeword >> extra_bits;
262 wimlib_assert2(node_idx < table_num_entries);
264 /* Go through each bit of the current Huffman codeword beyond
265 * the prefix of length @table_bits and walk the tree,
266 * allocating any slots that have not yet been allocated. */
269 /* If the current tree node points to nowhere
270 * but we need to follow it, allocate a new node
271 * for it to point to. */
272 if (decode_table[node_idx] == 0) {
273 decode_table[node_idx] = next_free_tree_slot;
274 decode_table[next_free_tree_slot++] = 0;
275 decode_table[next_free_tree_slot++] = 0;
276 wimlib_assert2(next_free_tree_slot <=
277 table_num_entries + 2 * num_syms);
280 /* Set node_idx to left child */
281 node_idx = decode_table[node_idx];
283 /* Is the next bit 0 or 1? If 0, go left (already done).
284 * If 1, go right by incrementing node_idx. */
286 node_idx += (cur_codeword >> extra_bits) & 1;
287 } while (extra_bits != 0);
289 /* node_idx is now the index of the leaf entry into which the
290 * actual symbol will go. */
291 decode_table[node_idx] = sym;
293 /* cur_codeword is always incremented because this is
294 * how canonical Huffman codes are generated (add 1 for
295 * each code, then left shift whenever the code length
298 } while (++i != num_used_syms);
302 /* Reads a Huffman-encoded symbol from the bistream when the number of remaining
303 * bits is less than the maximum codeword length. */
305 read_huffsym_near_end_of_input(struct input_bitstream *istream,
306 const u16 decode_table[],
312 unsigned bitsleft = istream->bitsleft;
317 if (table_bits > bitsleft) {
320 key_bits = bitstream_peek_bits(istream, key_size) <<
321 (table_bits - key_size);
323 key_size = table_bits;
324 bitsleft -= table_bits;
325 key_bits = bitstream_peek_bits(istream, table_bits);
328 sym = decode_table[key_bits];
329 if (sym >= num_syms) {
330 bitstream_remove_bits(istream, key_size);
333 ERROR("Input stream exhausted");
336 key_bits = sym + bitstream_peek_bits(istream, 1);
337 bitstream_remove_bits(istream, 1);
339 } while ((sym = decode_table[key_bits]) >= num_syms);
341 bitstream_remove_bits(istream, lens[sym]);