4 * Code for decompression shared among multiple compression formats.
9 * The author dedicates this file to the public domain.
10 * You can do whatever you want with this file.
17 #include "wimlib/decompress_common.h"
18 #include "wimlib/util.h" /* for BUILD_BUG_ON() */
24 # define USE_SSE2_FILL
25 # include <emmintrin.h>
27 # define USE_LONG_FILL
31 /* Construct a direct mapping entry in the lookup table. */
32 #define MAKE_DIRECT_ENTRY(symbol, length) ((symbol) | ((length) << 11))
35 * make_huffman_decode_table() -
37 * Build a decoding table for a canonical prefix code, or "Huffman code".
39 * This takes as input the length of the codeword for each symbol in the
40 * alphabet and produces as output a table that can be used for fast
41 * decoding of prefix-encoded symbols using read_huffsym().
43 * Strictly speaking, a canonical prefix code might not be a Huffman
44 * code. But this algorithm will work either way; and in fact, since
45 * Huffman codes are defined in terms of symbol frequencies, there is no
46 * way for the decompressor to know whether the code is a true Huffman
47 * code or not until all symbols have been decoded.
49 * Because the prefix code is assumed to be "canonical", it can be
50 * reconstructed directly from the codeword lengths. A prefix code is
51 * canonical if and only if a longer codeword never lexicographically
52 * precedes a shorter codeword, and the lexicographic ordering of
53 * codewords of the same length is the same as the lexicographic ordering
54 * of the corresponding symbols. Consequently, we can sort the symbols
55 * primarily by codeword length and secondarily by symbol value, then
56 * reconstruct the prefix code by generating codewords lexicographically
59 * This function does not, however, generate the prefix code explicitly.
60 * Instead, it directly builds a table for decoding symbols using the
61 * code. The basic idea is this: given the next 'max_codeword_len' bits
62 * in the input, we can look up the decoded symbol by indexing a table
63 * containing 2**max_codeword_len entries. A codeword with length
64 * 'max_codeword_len' will have exactly one entry in this table, whereas
65 * a codeword shorter than 'max_codeword_len' will have multiple entries
66 * in this table. Precisely, a codeword of length n will be represented
67 * by 2**(max_codeword_len - n) entries in this table. The 0-based index
68 * of each such entry will contain the corresponding codeword as a prefix
69 * when zero-padded on the left to 'max_codeword_len' binary digits.
71 * That's the basic idea, but we implement two optimizations regarding
72 * the format of the decode table itself:
74 * - For many compression formats, the maximum codeword length is too
75 * long for it to be efficient to build the full decoding table
76 * whenever a new prefix code is used. Instead, we can build the table
77 * using only 2**table_bits entries, where 'table_bits' is some number
78 * less than or equal to 'max_codeword_len'. Then, only codewords of
79 * length 'table_bits' and shorter can be directly looked up. For
80 * longer codewords, the direct lookup instead produces the root of a
81 * binary tree. Using this tree, the decoder can do traditional
82 * bit-by-bit decoding of the remainder of the codeword. Child nodes
83 * are allocated in extra entries at the end of the table; leaf nodes
84 * contain symbols. Note that the long-codeword case is, in general,
85 * not performance critical, since in Huffman codes the most frequently
86 * used symbols are assigned the shortest codeword lengths.
88 * - When we decode a symbol using a direct lookup of the table, we still
89 * need to know its length so that the bitstream can be advanced by the
90 * appropriate number of bits. The simple solution is to simply retain
91 * the 'lens' array and use the decoded symbol as an index into it.
92 * However, this requires two separate array accesses in the fast path.
93 * The optimization is to store the length directly in the decode
94 * table. We use the bottom 11 bits for the symbol and the top 5 bits
95 * for the length. In addition, to combine this optimization with the
96 * previous one, we introduce a special case where the top 2 bits of
97 * the length are both set if the entry is actually the root of a
101 * The array in which to create the decoding table.
102 * This must be 16-byte aligned and must have a length of at least
103 * ((2**table_bits) + 2 * num_syms) entries.
106 * The number of symbols in the alphabet; also, the length of the
107 * 'lens' array. Must be less than or equal to
108 * DECODE_TABLE_MAX_SYMBOLS.
111 * The order of the decode table size, as explained above. Must be
112 * less than or equal to DECODE_TABLE_MAX_TABLE_BITS.
115 * An array of length @num_syms, indexable by symbol, that gives the
116 * length of the codeword, in bits, for that symbol. The length can
117 * be 0, which means that the symbol does not have a codeword
121 * The longest codeword length allowed in the compression format.
122 * All entries in 'lens' must be less than or equal to this value.
123 * This must be less than or equal to DECODE_TABLE_MAX_CODEWORD_LEN.
125 * Returns 0 on success, or -1 if the lengths do not form a valid prefix
129 make_huffman_decode_table(u16 decode_table[const restrict],
130 const unsigned num_syms,
131 const unsigned table_bits,
132 const u8 lens[const restrict],
133 const unsigned max_codeword_len)
135 const unsigned table_num_entries = 1 << table_bits;
136 unsigned len_counts[max_codeword_len + 1];
137 u16 sorted_syms[num_syms];
139 void *decode_table_ptr;
141 unsigned codeword_len;
142 unsigned stores_per_loop;
143 unsigned decode_table_pos;
146 const unsigned entries_per_long = sizeof(unsigned long) / sizeof(decode_table[0]);
150 const unsigned entries_per_xmm = sizeof(__m128i) / sizeof(decode_table[0]);
153 /* Check parameters if assertions are enabled. */
154 wimlib_assert2((uintptr_t)decode_table % DECODE_TABLE_ALIGNMENT == 0);
155 wimlib_assert2(num_syms <= DECODE_TABLE_MAX_SYMBOLS);
156 wimlib_assert2(table_bits <= DECODE_TABLE_MAX_TABLE_BITS);
157 wimlib_assert2(max_codeword_len <= DECODE_TABLE_MAX_CODEWORD_LEN);
158 for (unsigned sym = 0; sym < num_syms; sym++)
159 wimlib_assert2(lens[sym] <= max_codeword_len);
161 /* Count how many symbols have each possible codeword length.
162 * Note that a length of 0 indicates the corresponding symbol is not
163 * used in the code and therefore does not have a codeword. */
164 for (unsigned len = 0; len <= max_codeword_len; len++)
166 for (unsigned sym = 0; sym < num_syms; sym++)
167 len_counts[lens[sym]]++;
169 /* We can assume all lengths are <= max_codeword_len, but we
170 * cannot assume they form a valid prefix code. A codeword of
171 * length n should require a proportion of the codespace equaling
172 * (1/2)^n. The code is valid if and only if the codespace is
173 * exactly filled by the lengths, by this measure. */
175 for (unsigned len = 1; len <= max_codeword_len; len++) {
177 left -= len_counts[len];
178 if (unlikely(left < 0)) {
179 /* The lengths overflow the codespace; that is, the code
180 * is over-subscribed. */
185 if (unlikely(left != 0)) {
186 /* The lengths do not fill the codespace; that is, they form an
188 if (left == (1 << max_codeword_len)) {
189 /* The code is completely empty. This is arguably
190 * invalid, but in fact it is valid in LZX and XPRESS,
191 * so we must allow it. By definition, no symbols can
192 * be decoded with an empty code. Consequently, we
193 * technically don't even need to fill in the decode
194 * table. However, to avoid accessing uninitialized
195 * memory if the algorithm nevertheless attempts to
196 * decode symbols using such a code, we zero out the
198 memset(decode_table, 0,
199 table_num_entries * sizeof(decode_table[0]));
205 /* Sort the symbols primarily by length and secondarily by symbol order.
208 unsigned offsets[max_codeword_len + 1];
210 /* Initialize 'offsets' so that offsets[len] for 1 <= len <=
211 * max_codeword_len is the number of codewords shorter than
214 for (unsigned len = 1; len < max_codeword_len; len++)
215 offsets[len + 1] = offsets[len] + len_counts[len];
217 /* Use the 'offsets' array to sort the symbols.
218 * Note that we do not include symbols that are not used in the
219 * code. Consequently, fewer than 'num_syms' entries in
220 * 'sorted_syms' may be filled. */
221 for (unsigned sym = 0; sym < num_syms; sym++)
223 sorted_syms[offsets[lens[sym]]++] = sym;
226 /* Fill entries for codewords with length <= table_bits
227 * --- that is, those short enough for a direct mapping.
229 * The table will start with entries for the shortest codeword(s), which
230 * have the most entries. From there, the number of entries per
231 * codeword will decrease. As an optimization, we may begin filling
232 * entries with SSE2 vector accesses (8 entries/store), then change to
233 * 'unsigned long' accesses (2 or 4 entries/store), then change to
234 * 16-bit accesses (1 entry/store). */
235 decode_table_ptr = decode_table;
239 /* Fill the entries one 128-bit vector at a time.
240 * This is 8 entries per store. */
241 stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_xmm;
242 for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
243 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
244 for (; sym_idx < end_sym_idx; sym_idx++) {
245 /* Note: unlike in the 'long' version below, the __m128i
246 * type already has __attribute__((may_alias)), so using
247 * it to access the decode table, which is an array of
248 * unsigned shorts, will not violate strict aliasing.
255 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
257 v = _mm_set1_epi16(entry);
258 p = (__m128i*)decode_table_ptr;
263 decode_table_ptr = p;
266 #endif /* USE_SSE2_FILL */
269 /* Fill the entries one 'unsigned long' at a time.
270 * On 32-bit systems this is 2 entries per store, while on 64-bit
271 * systems this is 4 entries per store. */
272 stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_long;
273 for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
274 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
275 for (; sym_idx < end_sym_idx; sym_idx++) {
277 /* Accessing the array of unsigned shorts as unsigned
278 * longs would violate strict aliasing and would require
279 * compiling the code with -fno-strict-aliasing to
280 * guarantee correctness. To work around this problem,
281 * use the gcc 'may_alias' extension to define a special
282 * unsigned long type that may alias any other in-memory
284 typedef unsigned long __attribute__((may_alias)) aliased_long_t;
290 BUILD_BUG_ON(sizeof(unsigned long) != 4 &&
291 sizeof(unsigned long) != 8);
293 v = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
295 v |= v << (sizeof(unsigned long) == 8 ? 32 : 0);
297 p = (aliased_long_t *)decode_table_ptr;
303 decode_table_ptr = p;
306 #endif /* USE_LONG_FILL */
308 /* Fill the entries one 16-bit integer at a time. */
309 stores_per_loop = (1 << (table_bits - codeword_len));
310 for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
311 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
312 for (; sym_idx < end_sym_idx; sym_idx++) {
317 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
319 p = (u16*)decode_table_ptr;
326 decode_table_ptr = p;
330 /* If we've filled in the entire table, we are done. Otherwise,
331 * there are codewords longer than table_bits for which we must
332 * generate binary trees. */
334 decode_table_pos = (u16*)decode_table_ptr - decode_table;
335 if (decode_table_pos != table_num_entries) {
337 unsigned next_free_tree_slot;
338 unsigned cur_codeword;
340 /* First, zero out the remaining entries. This is
341 * necessary so that these entries appear as
342 * "unallocated" in the next part. Each of these entries
343 * will eventually be filled with the representation of
344 * the root node of a binary tree. */
345 j = decode_table_pos;
348 } while (++j != table_num_entries);
350 /* We allocate child nodes starting at the end of the
351 * direct lookup table. Note that there should be
352 * 2*num_syms extra entries for this purpose, although
353 * fewer than this may actually be needed. */
354 next_free_tree_slot = table_num_entries;
356 /* Iterate through each codeword with length greater than
357 * 'table_bits', primarily in order of codeword length
358 * and secondarily in order of symbol. */
359 for (cur_codeword = decode_table_pos << 1;
360 codeword_len <= max_codeword_len;
361 codeword_len++, cur_codeword <<= 1)
363 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
364 for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++)
366 /* 'sym' is the symbol represented by the
368 unsigned sym = sorted_syms[sym_idx];
370 unsigned extra_bits = codeword_len - table_bits;
372 unsigned node_idx = cur_codeword >> extra_bits;
374 /* Go through each bit of the current codeword
375 * beyond the prefix of length @table_bits and
376 * walk the appropriate binary tree, allocating
377 * any slots that have not yet been allocated.
379 * Note that the 'pointer' entry to the binary
380 * tree, which is stored in the direct lookup
381 * portion of the table, is represented
382 * identically to other internal (non-leaf)
383 * nodes of the binary tree; it can be thought
384 * of as simply the root of the tree. The
385 * representation of these internal nodes is
386 * simply the index of the left child combined
387 * with the special bits 0xC000 to distingush
388 * the entry from direct mapping and leaf node
392 /* At least one bit remains in the
393 * codeword, but the current node is an
394 * unallocated leaf. Change it to an
396 if (decode_table[node_idx] == 0) {
397 decode_table[node_idx] =
398 next_free_tree_slot | 0xC000;
399 decode_table[next_free_tree_slot++] = 0;
400 decode_table[next_free_tree_slot++] = 0;
403 /* Go to the left child if the next bit
404 * in the codeword is 0; otherwise go to
405 * the right child. */
406 node_idx = decode_table[node_idx] & 0x3FFF;
408 node_idx += (cur_codeword >> extra_bits) & 1;
409 } while (extra_bits != 0);
411 /* We've traversed the tree using the entire
412 * codeword, and we're now at the entry where
413 * the actual symbol will be stored. This is
414 * distinguished from internal nodes by not
415 * having its high two bits set. */
416 decode_table[node_idx] = sym;