4 * Code for decompression shared among multiple compression formats.
6 * The following copying information applies to this specific source code file:
8 * Written in 2012-2015 by Eric Biggers <ebiggers3@gmail.com>
10 * To the extent possible under law, the author(s) have dedicated all copyright
11 * and related and neighboring rights to this software to the public domain
12 * worldwide via the Creative Commons Zero 1.0 Universal Public Domain
13 * Dedication (the "CC0").
15 * This software is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the CC0 for more details.
19 * You should have received a copy of the CC0 along with this software; if not
20 * see <http://creativecommons.org/publicdomain/zero/1.0/>.
27 #include "wimlib/decompress_common.h"
36 # define USE_SSE2_FILL
37 # include <emmintrin.h>
41 /* Construct a direct mapping entry in the lookup table. */
42 #define MAKE_DIRECT_ENTRY(symbol, length) ((symbol) | ((length) << 11))
45 * make_huffman_decode_table() -
47 * Build a decoding table for a canonical prefix code, or "Huffman code".
49 * This takes as input the length of the codeword for each symbol in the
50 * alphabet and produces as output a table that can be used for fast
51 * decoding of prefix-encoded symbols using read_huffsym().
53 * Strictly speaking, a canonical prefix code might not be a Huffman
54 * code. But this algorithm will work either way; and in fact, since
55 * Huffman codes are defined in terms of symbol frequencies, there is no
56 * way for the decompressor to know whether the code is a true Huffman
57 * code or not until all symbols have been decoded.
59 * Because the prefix code is assumed to be "canonical", it can be
60 * reconstructed directly from the codeword lengths. A prefix code is
61 * canonical if and only if a longer codeword never lexicographically
62 * precedes a shorter codeword, and the lexicographic ordering of
63 * codewords of the same length is the same as the lexicographic ordering
64 * of the corresponding symbols. Consequently, we can sort the symbols
65 * primarily by codeword length and secondarily by symbol value, then
66 * reconstruct the prefix code by generating codewords lexicographically
69 * This function does not, however, generate the prefix code explicitly.
70 * Instead, it directly builds a table for decoding symbols using the
71 * code. The basic idea is this: given the next 'max_codeword_len' bits
72 * in the input, we can look up the decoded symbol by indexing a table
73 * containing 2**max_codeword_len entries. A codeword with length
74 * 'max_codeword_len' will have exactly one entry in this table, whereas
75 * a codeword shorter than 'max_codeword_len' will have multiple entries
76 * in this table. Precisely, a codeword of length n will be represented
77 * by 2**(max_codeword_len - n) entries in this table. The 0-based index
78 * of each such entry will contain the corresponding codeword as a prefix
79 * when zero-padded on the left to 'max_codeword_len' binary digits.
81 * That's the basic idea, but we implement two optimizations regarding
82 * the format of the decode table itself:
84 * - For many compression formats, the maximum codeword length is too
85 * long for it to be efficient to build the full decoding table
86 * whenever a new prefix code is used. Instead, we can build the table
87 * using only 2**table_bits entries, where 'table_bits' is some number
88 * less than or equal to 'max_codeword_len'. Then, only codewords of
89 * length 'table_bits' and shorter can be directly looked up. For
90 * longer codewords, the direct lookup instead produces the root of a
91 * binary tree. Using this tree, the decoder can do traditional
92 * bit-by-bit decoding of the remainder of the codeword. Child nodes
93 * are allocated in extra entries at the end of the table; leaf nodes
94 * contain symbols. Note that the long-codeword case is, in general,
95 * not performance critical, since in Huffman codes the most frequently
96 * used symbols are assigned the shortest codeword lengths.
98 * - When we decode a symbol using a direct lookup of the table, we still
99 * need to know its length so that the bitstream can be advanced by the
100 * appropriate number of bits. The simple solution is to simply retain
101 * the 'lens' array and use the decoded symbol as an index into it.
102 * However, this requires two separate array accesses in the fast path.
103 * The optimization is to store the length directly in the decode
104 * table. We use the bottom 11 bits for the symbol and the top 5 bits
105 * for the length. In addition, to combine this optimization with the
106 * previous one, we introduce a special case where the top 2 bits of
107 * the length are both set if the entry is actually the root of a
111 * The array in which to create the decoding table. This must be
112 * 16-byte aligned and must have a length of at least
113 * ((2**table_bits) + 2 * num_syms) entries. This is permitted to
114 * alias @lens, since all information from @lens is consumed before
115 * anything is written to @decode_table.
118 * The number of symbols in the alphabet; also, the length of the
119 * 'lens' array. Must be less than or equal to
120 * DECODE_TABLE_MAX_SYMBOLS.
123 * The order of the decode table size, as explained above. Must be
124 * less than or equal to DECODE_TABLE_MAX_TABLE_BITS.
127 * An array of length @num_syms, indexable by symbol, that gives the
128 * length of the codeword, in bits, for that symbol. The length can
129 * be 0, which means that the symbol does not have a codeword
130 * assigned. This is permitted to alias @decode_table, since all
131 * information from @lens is consumed before anything is written to
135 * The longest codeword length allowed in the compression format.
136 * All entries in 'lens' must be less than or equal to this value.
137 * This must be less than or equal to DECODE_TABLE_MAX_CODEWORD_LEN.
139 * Returns 0 on success, or -1 if the lengths do not form a valid prefix
143 make_huffman_decode_table(u16 decode_table[const],
144 const unsigned num_syms,
145 const unsigned table_bits,
146 const u8 lens[const],
147 const unsigned max_codeword_len)
149 const unsigned table_num_entries = 1 << table_bits;
150 unsigned len_counts[max_codeword_len + 1];
151 u16 sorted_syms[num_syms];
153 void *decode_table_ptr;
155 unsigned codeword_len;
156 unsigned stores_per_loop;
157 unsigned decode_table_pos;
160 const unsigned entries_per_word = WORDBYTES / sizeof(decode_table[0]);
164 const unsigned entries_per_xmm = sizeof(__m128i) / sizeof(decode_table[0]);
167 /* Count how many symbols have each possible codeword length.
168 * Note that a length of 0 indicates the corresponding symbol is not
169 * used in the code and therefore does not have a codeword. */
170 for (unsigned len = 0; len <= max_codeword_len; len++)
172 for (unsigned sym = 0; sym < num_syms; sym++)
173 len_counts[lens[sym]]++;
175 /* We can assume all lengths are <= max_codeword_len, but we
176 * cannot assume they form a valid prefix code. A codeword of
177 * length n should require a proportion of the codespace equaling
178 * (1/2)^n. The code is valid if and only if the codespace is
179 * exactly filled by the lengths, by this measure. */
181 for (unsigned len = 1; len <= max_codeword_len; len++) {
183 left -= len_counts[len];
184 if (unlikely(left < 0)) {
185 /* The lengths overflow the codespace; that is, the code
186 * is over-subscribed. */
191 if (unlikely(left != 0)) {
192 /* The lengths do not fill the codespace; that is, they form an
194 if (left == (1 << max_codeword_len)) {
195 /* The code is completely empty. This is arguably
196 * invalid, but in fact it is valid in LZX and XPRESS,
197 * so we must allow it. By definition, no symbols can
198 * be decoded with an empty code. Consequently, we
199 * technically don't even need to fill in the decode
200 * table. However, to avoid accessing uninitialized
201 * memory if the algorithm nevertheless attempts to
202 * decode symbols using such a code, we zero out the
204 memset(decode_table, 0,
205 table_num_entries * sizeof(decode_table[0]));
211 /* Sort the symbols primarily by length and secondarily by symbol order.
214 unsigned offsets[max_codeword_len + 1];
216 /* Initialize 'offsets' so that offsets[len] for 1 <= len <=
217 * max_codeword_len is the number of codewords shorter than
220 for (unsigned len = 1; len < max_codeword_len; len++)
221 offsets[len + 1] = offsets[len] + len_counts[len];
223 /* Use the 'offsets' array to sort the symbols.
224 * Note that we do not include symbols that are not used in the
225 * code. Consequently, fewer than 'num_syms' entries in
226 * 'sorted_syms' may be filled. */
227 for (unsigned sym = 0; sym < num_syms; sym++)
229 sorted_syms[offsets[lens[sym]]++] = sym;
232 /* Fill entries for codewords with length <= table_bits
233 * --- that is, those short enough for a direct mapping.
235 * The table will start with entries for the shortest codeword(s), which
236 * have the most entries. From there, the number of entries per
237 * codeword will decrease. As an optimization, we may begin filling
238 * entries with SSE2 vector accesses (8 entries/store), then change to
239 * 'machine_word_t' accesses (2 or 4 entries/store), then change to
240 * 16-bit accesses (1 entry/store). */
241 decode_table_ptr = decode_table;
245 /* Fill the entries one 128-bit vector at a time.
246 * This is 8 entries per store. */
247 stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_xmm;
248 for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
249 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
250 for (; sym_idx < end_sym_idx; sym_idx++) {
251 /* Note: unlike in the machine_word_t version below, the
252 * __m128i type already has __attribute__((may_alias)),
253 * so using it to access the decode table, which is an
254 * array of unsigned shorts, will not violate strict
261 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
263 v = _mm_set1_epi16(entry);
264 p = (__m128i*)decode_table_ptr;
269 decode_table_ptr = p;
272 #endif /* USE_SSE2_FILL */
275 /* Fill the entries one machine word at a time.
276 * On 32-bit systems this is 2 entries per store, while on 64-bit
277 * systems this is 4 entries per store. */
278 stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_word;
279 for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
280 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
281 for (; sym_idx < end_sym_idx; sym_idx++) {
283 /* Accessing the array of u16 as u32 or u64 would
284 * violate strict aliasing and would require compiling
285 * the code with -fno-strict-aliasing to guarantee
286 * correctness. To work around this problem, use the
287 * gcc 'may_alias' extension. */
288 typedef machine_word_t _may_alias_attribute aliased_word_t;
294 STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
296 v = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
298 v |= v << (WORDBITS == 64 ? 32 : 0);
300 p = (aliased_word_t *)decode_table_ptr;
306 decode_table_ptr = p;
309 #endif /* USE_WORD_FILL */
311 /* Fill the entries one 16-bit integer at a time. */
312 stores_per_loop = (1 << (table_bits - codeword_len));
313 for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
314 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
315 for (; sym_idx < end_sym_idx; sym_idx++) {
320 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
322 p = (u16*)decode_table_ptr;
329 decode_table_ptr = p;
333 /* If we've filled in the entire table, we are done. Otherwise,
334 * there are codewords longer than table_bits for which we must
335 * generate binary trees. */
337 decode_table_pos = (u16*)decode_table_ptr - decode_table;
338 if (decode_table_pos != table_num_entries) {
340 unsigned next_free_tree_slot;
341 unsigned cur_codeword;
343 /* First, zero out the remaining entries. This is
344 * necessary so that these entries appear as
345 * "unallocated" in the next part. Each of these entries
346 * will eventually be filled with the representation of
347 * the root node of a binary tree. */
348 j = decode_table_pos;
351 } while (++j != table_num_entries);
353 /* We allocate child nodes starting at the end of the
354 * direct lookup table. Note that there should be
355 * 2*num_syms extra entries for this purpose, although
356 * fewer than this may actually be needed. */
357 next_free_tree_slot = table_num_entries;
359 /* Iterate through each codeword with length greater than
360 * 'table_bits', primarily in order of codeword length
361 * and secondarily in order of symbol. */
362 for (cur_codeword = decode_table_pos << 1;
363 codeword_len <= max_codeword_len;
364 codeword_len++, cur_codeword <<= 1)
366 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
367 for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++)
369 /* 'sym' is the symbol represented by the
371 unsigned sym = sorted_syms[sym_idx];
373 unsigned extra_bits = codeword_len - table_bits;
375 unsigned node_idx = cur_codeword >> extra_bits;
377 /* Go through each bit of the current codeword
378 * beyond the prefix of length @table_bits and
379 * walk the appropriate binary tree, allocating
380 * any slots that have not yet been allocated.
382 * Note that the 'pointer' entry to the binary
383 * tree, which is stored in the direct lookup
384 * portion of the table, is represented
385 * identically to other internal (non-leaf)
386 * nodes of the binary tree; it can be thought
387 * of as simply the root of the tree. The
388 * representation of these internal nodes is
389 * simply the index of the left child combined
390 * with the special bits 0xC000 to distinguish
391 * the entry from direct mapping and leaf node
395 /* At least one bit remains in the
396 * codeword, but the current node is an
397 * unallocated leaf. Change it to an
399 if (decode_table[node_idx] == 0) {
400 decode_table[node_idx] =
401 next_free_tree_slot | 0xC000;
402 decode_table[next_free_tree_slot++] = 0;
403 decode_table[next_free_tree_slot++] = 0;
406 /* Go to the left child if the next bit
407 * in the codeword is 0; otherwise go to
408 * the right child. */
409 node_idx = decode_table[node_idx] & 0x3FFF;
411 node_idx += (cur_codeword >> extra_bits) & 1;
412 } while (extra_bits != 0);
414 /* We've traversed the tree using the entire
415 * codeword, and we're now at the entry where
416 * the actual symbol will be stored. This is
417 * distinguished from internal nodes by not
418 * having its high two bits set. */
419 decode_table[node_idx] = sym;