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-2016 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/>.
30 # include <emmintrin.h>
33 #include "wimlib/decompress_common.h"
35 /* Construct a direct mapping entry in the decode table. */
36 #define MAKE_DIRECT_ENTRY(symbol, length) ((symbol) | ((length) << 11))
39 * make_huffman_decode_table() -
41 * Build a decoding table for a canonical prefix code, or "Huffman code".
43 * This takes as input the length of the codeword for each symbol in the
44 * alphabet and produces as output a table that can be used for fast
45 * decoding of prefix-encoded symbols using read_huffsym().
47 * Strictly speaking, a canonical prefix code might not be a Huffman
48 * code. But this algorithm will work either way; and in fact, since
49 * Huffman codes are defined in terms of symbol frequencies, there is no
50 * way for the decompressor to know whether the code is a true Huffman
51 * code or not until all symbols have been decoded.
53 * Because the prefix code is assumed to be "canonical", it can be
54 * reconstructed directly from the codeword lengths. A prefix code is
55 * canonical if and only if a longer codeword never lexicographically
56 * precedes a shorter codeword, and the lexicographic ordering of
57 * codewords of the same length is the same as the lexicographic ordering
58 * of the corresponding symbols. Consequently, we can sort the symbols
59 * primarily by codeword length and secondarily by symbol value, then
60 * reconstruct the prefix code by generating codewords lexicographically
63 * This function does not, however, generate the prefix code explicitly.
64 * Instead, it directly builds a table for decoding symbols using the
65 * code. The basic idea is this: given the next 'max_codeword_len' bits
66 * in the input, we can look up the decoded symbol by indexing a table
67 * containing 2**max_codeword_len entries. A codeword with length
68 * 'max_codeword_len' will have exactly one entry in this table, whereas
69 * a codeword shorter than 'max_codeword_len' will have multiple entries
70 * in this table. Precisely, a codeword of length n will be represented
71 * by 2**(max_codeword_len - n) entries in this table. The 0-based index
72 * of each such entry will contain the corresponding codeword as a prefix
73 * when zero-padded on the left to 'max_codeword_len' binary digits.
75 * That's the basic idea, but we implement two optimizations regarding
76 * the format of the decode table itself:
78 * - For many compression formats, the maximum codeword length is too
79 * long for it to be efficient to build the full decoding table
80 * whenever a new prefix code is used. Instead, we can build the table
81 * using only 2**table_bits entries, where 'table_bits' is some number
82 * less than or equal to 'max_codeword_len'. Then, only codewords of
83 * length 'table_bits' and shorter can be directly looked up. For
84 * longer codewords, the direct lookup instead produces the root of a
85 * binary tree. Using this tree, the decoder can do traditional
86 * bit-by-bit decoding of the remainder of the codeword. Child nodes
87 * are allocated in extra entries at the end of the table; leaf nodes
88 * contain symbols. Note that the long-codeword case is, in general,
89 * not performance critical, since in Huffman codes the most frequently
90 * used symbols are assigned the shortest codeword lengths.
92 * - When we decode a symbol using a direct lookup of the table, we still
93 * need to know its length so that the bitstream can be advanced by the
94 * appropriate number of bits. The simple solution is to simply retain
95 * the 'lens' array and use the decoded symbol as an index into it.
96 * However, this requires two separate array accesses in the fast path.
97 * The optimization is to store the length directly in the decode
98 * table. We use the bottom 11 bits for the symbol and the top 5 bits
99 * for the length. In addition, to combine this optimization with the
100 * previous one, we introduce a special case where the top 2 bits of
101 * the length are both set if the entry is actually the root of a
105 * The array in which to create the decoding table. This must be
106 * 16-byte aligned and must have a length of at least
107 * ((2**table_bits) + 2 * num_syms) entries. This is permitted to
108 * alias @lens, since all information from @lens is consumed before
109 * anything is written to @decode_table.
112 * The number of symbols in the alphabet; also, the length of the
113 * 'lens' array. Must be less than or equal to
114 * DECODE_TABLE_MAX_SYMBOLS.
117 * The order of the decode table size, as explained above. Must be
118 * less than or equal to DECODE_TABLE_MAX_TABLE_BITS.
121 * An array of length @num_syms, indexable by symbol, that gives the
122 * length of the codeword, in bits, for that symbol. The length can
123 * be 0, which means that the symbol does not have a codeword
124 * assigned. This is permitted to alias @decode_table, since all
125 * information from @lens is consumed before anything is written to
129 * The longest codeword length allowed in the compression format.
130 * All entries in 'lens' must be less than or equal to this value.
131 * This must be less than or equal to DECODE_TABLE_MAX_CODEWORD_LEN.
133 * Returns 0 on success, or -1 if the lengths do not form a valid prefix
137 make_huffman_decode_table(u16 decode_table[const],
138 const unsigned num_syms,
139 const unsigned table_bits,
140 const u8 lens[const],
141 const unsigned max_codeword_len)
143 const unsigned table_num_entries = 1 << table_bits;
144 unsigned offsets[max_codeword_len + 1];
145 unsigned len_counts[max_codeword_len + 1];
146 u16 sorted_syms[num_syms];
148 void *decode_table_ptr;
150 unsigned codeword_len;
151 unsigned decode_table_pos;
153 /* Count how many symbols have each codeword length, including 0. */
154 for (unsigned len = 0; len <= max_codeword_len; len++)
156 for (unsigned sym = 0; sym < num_syms; sym++)
157 len_counts[lens[sym]]++;
159 /* It is already guaranteed that all lengths are <= max_codeword_len,
160 * but it cannot be assumed they form a complete prefix code. A
161 * codeword of length n should require a proportion of the codespace
162 * equaling (1/2)^n. The code is complete if and only if, by this
163 * measure, the codespace is exactly filled by the lengths. */
165 for (unsigned len = 1; len <= max_codeword_len; len++) {
167 remainder -= len_counts[len];
168 if (unlikely(remainder < 0)) {
169 /* The lengths overflow the codespace; that is, the code
170 * is over-subscribed. */
175 if (unlikely(remainder != 0)) {
176 /* The lengths do not fill the codespace; that is, they form an
177 * incomplete code. */
178 if (remainder == (1 << max_codeword_len)) {
179 /* The code is completely empty. This is arguably
180 * invalid, but in fact it is valid in LZX and XPRESS,
181 * so we must allow it. By definition, no symbols can
182 * be decoded with an empty code. Consequently, we
183 * technically don't even need to fill in the decode
184 * table. However, to avoid accessing uninitialized
185 * memory if the algorithm nevertheless attempts to
186 * decode symbols using such a code, we zero out the
188 memset(decode_table, 0,
189 table_num_entries * sizeof(decode_table[0]));
195 /* Sort the symbols primarily by increasing codeword length and
196 * secondarily by increasing symbol value. */
198 /* Initialize 'offsets' so that 'offsets[len]' is the number of
199 * codewords shorter than 'len' bits, including length 0. */
201 for (unsigned len = 0; len < max_codeword_len; len++)
202 offsets[len + 1] = offsets[len] + len_counts[len];
204 /* Use the 'offsets' array to sort the symbols. */
205 for (unsigned sym = 0; sym < num_syms; sym++)
206 sorted_syms[offsets[lens[sym]]++] = sym;
209 * Fill entries for codewords with length <= table_bits
210 * --- that is, those short enough for a direct mapping.
212 * The table will start with entries for the shortest codeword(s), which
213 * have the most entries. From there, the number of entries per
214 * codeword will decrease. As an optimization, we may begin filling
215 * entries with SSE2 vector accesses (8 entries/store), then change to
216 * 'machine_word_t' accesses (2 or 4 entries/store), then change to
217 * 16-bit accesses (1 entry/store).
219 decode_table_ptr = decode_table;
220 sym_idx = offsets[0];
223 /* Fill entries one 128-bit vector (8 entries) at a time. */
224 for (unsigned stores_per_loop = (1 << (table_bits - codeword_len)) /
225 (sizeof(__m128i) / sizeof(decode_table[0]));
226 stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1)
228 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
229 for (; sym_idx < end_sym_idx; sym_idx++) {
230 /* Note: unlike in the machine_word_t version below, the
231 * __m128i type already has __attribute__((may_alias)),
232 * so using it to access the decode table, which is an
233 * array of unsigned shorts, will not violate strict
235 __m128i v = _mm_set1_epi16(
236 MAKE_DIRECT_ENTRY(sorted_syms[sym_idx],
238 unsigned n = stores_per_loop;
240 *(__m128i *)decode_table_ptr = v;
241 decode_table_ptr += sizeof(__m128i);
245 #endif /* __SSE2__ */
247 /* Fill entries one word (2 or 4 entries) at a time. */
248 for (unsigned stores_per_loop = (1 << (table_bits - codeword_len)) /
249 (WORDBYTES / sizeof(decode_table[0]));
250 stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1)
252 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
253 for (; sym_idx < end_sym_idx; sym_idx++) {
255 /* Accessing the array of u16 as u32 or u64 would
256 * violate strict aliasing and would require compiling
257 * the code with -fno-strict-aliasing to guarantee
258 * correctness. To work around this problem, use the
259 * gcc 'may_alias' extension. */
260 typedef machine_word_t _may_alias_attribute aliased_word_t;
263 unsigned n = stores_per_loop;
265 STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
266 v = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
268 v |= v << (WORDBITS == 64 ? 32 : 0);
271 *(aliased_word_t *)decode_table_ptr = v;
272 decode_table_ptr += sizeof(aliased_word_t);
277 /* Fill entries one at a time. */
278 for (unsigned stores_per_loop = (1 << (table_bits - codeword_len));
279 stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1)
281 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
282 for (; sym_idx < end_sym_idx; sym_idx++) {
283 u16 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx],
285 unsigned n = stores_per_loop;
287 *(u16 *)decode_table_ptr = entry;
288 decode_table_ptr += sizeof(u16);
293 /* If we've filled in the entire table, we are done. Otherwise,
294 * there are codewords longer than table_bits for which we must
295 * generate binary trees. */
297 decode_table_pos = (u16 *)decode_table_ptr - decode_table;
298 if (decode_table_pos != table_num_entries) {
300 unsigned next_free_tree_slot;
301 unsigned cur_codeword;
303 /* First, zero out the remaining entries. This is
304 * necessary so that these entries appear as
305 * "unallocated" in the next part. Each of these entries
306 * will eventually be filled with the representation of
307 * the root node of a binary tree. */
308 j = decode_table_pos;
311 } while (++j != table_num_entries);
313 /* We allocate child nodes starting at the end of the
314 * direct lookup table. Note that there should be
315 * 2*num_syms extra entries for this purpose, although
316 * fewer than this may actually be needed. */
317 next_free_tree_slot = table_num_entries;
319 /* Iterate through each codeword with length greater than
320 * 'table_bits', primarily in order of codeword length
321 * and secondarily in order of symbol. */
322 for (cur_codeword = decode_table_pos << 1;
323 codeword_len <= max_codeword_len;
324 codeword_len++, cur_codeword <<= 1)
326 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
327 for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++)
329 /* 'sym' is the symbol represented by the
331 unsigned sym = sorted_syms[sym_idx];
333 unsigned extra_bits = codeword_len - table_bits;
335 unsigned node_idx = cur_codeword >> extra_bits;
337 /* Go through each bit of the current codeword
338 * beyond the prefix of length @table_bits and
339 * walk the appropriate binary tree, allocating
340 * any slots that have not yet been allocated.
342 * Note that the 'pointer' entry to the binary
343 * tree, which is stored in the direct lookup
344 * portion of the table, is represented
345 * identically to other internal (non-leaf)
346 * nodes of the binary tree; it can be thought
347 * of as simply the root of the tree. The
348 * representation of these internal nodes is
349 * simply the index of the left child combined
350 * with the special bits 0xC000 to distinguish
351 * the entry from direct mapping and leaf node
355 /* At least one bit remains in the
356 * codeword, but the current node is an
357 * unallocated leaf. Change it to an
359 if (decode_table[node_idx] == 0) {
360 decode_table[node_idx] =
361 next_free_tree_slot | 0xC000;
362 decode_table[next_free_tree_slot++] = 0;
363 decode_table[next_free_tree_slot++] = 0;
366 /* Go to the left child if the next bit
367 * in the codeword is 0; otherwise go to
368 * the right child. */
369 node_idx = decode_table[node_idx] & 0x3FFF;
371 node_idx += (cur_codeword >> extra_bits) & 1;
372 } while (extra_bits != 0);
374 /* We've traversed the tree using the entire
375 * codeword, and we're now at the entry where
376 * the actual symbol will be stored. This is
377 * distinguished from internal nodes by not
378 * having its high two bits set. */
379 decode_table[node_idx] = sym;