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;
152 /* Count how many symbols have each codeword length, including 0. */
153 for (unsigned len = 0; len <= max_codeword_len; len++)
155 for (unsigned sym = 0; sym < num_syms; sym++)
156 len_counts[lens[sym]]++;
158 /* It is already guaranteed that all lengths are <= max_codeword_len,
159 * but it cannot be assumed they form a complete prefix code. A
160 * codeword of length n should require a proportion of the codespace
161 * equaling (1/2)^n. The code is complete if and only if, by this
162 * measure, the codespace is exactly filled by the lengths. */
164 for (unsigned len = 1; len <= max_codeword_len; len++) {
166 remainder -= len_counts[len];
167 if (unlikely(remainder < 0)) {
168 /* The lengths overflow the codespace; that is, the code
169 * is over-subscribed. */
174 if (unlikely(remainder != 0)) {
175 /* The lengths do not fill the codespace; that is, they form an
176 * incomplete code. */
177 if (remainder == (1 << max_codeword_len)) {
178 /* The code is completely empty. This is arguably
179 * invalid, but in fact it is valid in LZX and XPRESS,
180 * so we must allow it. By definition, no symbols can
181 * be decoded with an empty code. Consequently, we
182 * technically don't even need to fill in the decode
183 * table. However, to avoid accessing uninitialized
184 * memory if the algorithm nevertheless attempts to
185 * decode symbols using such a code, we zero out the
187 memset(decode_table, 0,
188 table_num_entries * sizeof(decode_table[0]));
194 /* Sort the symbols primarily by increasing codeword length and
195 * secondarily by increasing symbol value. */
197 /* Initialize 'offsets' so that 'offsets[len]' is the number of
198 * codewords shorter than 'len' bits, including length 0. */
200 for (unsigned len = 0; len < max_codeword_len; len++)
201 offsets[len + 1] = offsets[len] + len_counts[len];
203 /* Use the 'offsets' array to sort the symbols. */
204 for (unsigned sym = 0; sym < num_syms; sym++)
205 sorted_syms[offsets[lens[sym]]++] = sym;
208 * Fill entries for codewords with length <= table_bits
209 * --- that is, those short enough for a direct mapping.
211 * The table will start with entries for the shortest codeword(s), which
212 * have the most entries. From there, the number of entries per
213 * codeword will decrease. As an optimization, we may begin filling
214 * entries with SSE2 vector accesses (8 entries/store), then change to
215 * 'machine_word_t' accesses (2 or 4 entries/store), then change to
216 * 16-bit accesses (1 entry/store).
218 decode_table_ptr = decode_table;
219 sym_idx = offsets[0];
222 /* Fill entries one 128-bit vector (8 entries) at a time. */
223 for (unsigned stores_per_loop = (1 << (table_bits - codeword_len)) /
224 (sizeof(__m128i) / sizeof(decode_table[0]));
225 stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1)
227 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
228 for (; sym_idx < end_sym_idx; sym_idx++) {
229 /* Note: unlike in the machine_word_t version below, the
230 * __m128i type already has __attribute__((may_alias)),
231 * so using it to access the decode table, which is an
232 * array of unsigned shorts, will not violate strict
234 __m128i v = _mm_set1_epi16(
235 MAKE_DIRECT_ENTRY(sorted_syms[sym_idx],
237 unsigned n = stores_per_loop;
239 *(__m128i *)decode_table_ptr = v;
240 decode_table_ptr += sizeof(__m128i);
244 #endif /* __SSE2__ */
246 /* Fill entries one word (2 or 4 entries) at a time. */
247 for (unsigned stores_per_loop = (1 << (table_bits - codeword_len)) /
248 (WORDBYTES / sizeof(decode_table[0]));
249 stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1)
251 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
252 for (; sym_idx < end_sym_idx; sym_idx++) {
254 /* Accessing the array of u16 as u32 or u64 would
255 * violate strict aliasing and would require compiling
256 * the code with -fno-strict-aliasing to guarantee
257 * correctness. To work around this problem, use the
258 * gcc 'may_alias' extension. */
259 typedef machine_word_t _may_alias_attribute aliased_word_t;
262 unsigned n = stores_per_loop;
264 STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
265 v = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
267 v |= v << (WORDBITS == 64 ? 32 : 0);
270 *(aliased_word_t *)decode_table_ptr = v;
271 decode_table_ptr += sizeof(aliased_word_t);
276 /* Fill entries one at a time. */
277 for (unsigned stores_per_loop = (1 << (table_bits - codeword_len));
278 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++) {
282 u16 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx],
284 unsigned n = stores_per_loop;
286 *(u16 *)decode_table_ptr = entry;
287 decode_table_ptr += sizeof(u16);
292 unsigned codeword = ((u16 *)decode_table_ptr - decode_table) << 1;
293 unsigned cur_subtable_pos = table_num_entries;
294 unsigned cur_subtable_bits = table_bits;
295 unsigned cur_subtable_prefix = -1;
297 /* Fill in the remaining entries if any. These entries will require
299 while (sym_idx < num_syms) {
301 while (len_counts[codeword_len] == 0) {
306 unsigned prefix = codeword >> (codeword_len - table_bits);
308 /* Start a new subtable if the first 'table_bits' bits of the
309 * codeword don't match the prefix for the previous subtable, or
310 * if this will be the first subtable. */
311 if (prefix != cur_subtable_prefix) {
313 cur_subtable_prefix = prefix;
315 /* Calculate the subtable length. If the codeword
316 * length exceeds 'table_bits' by n, the subtable needs
317 * at least 2**n entries. But it may need more; if
318 * there are fewer than 2**n codewords of length
319 * 'table_bits + n' remaining, then n will need to be
320 * incremented to bring in longer codewords until the
321 * subtable can be filled completely. Note that it
322 * always will, eventually, be possible to fill the
323 * subtable, since the only case where we may have an
324 * incomplete code is a single codeword of length 1,
325 * and that never requires any subtables. */
326 cur_subtable_bits = codeword_len - table_bits;
327 remainder = (s32)1 << cur_subtable_bits;
329 remainder -= len_counts[table_bits +
337 /* Create the entry that points from the main table to
338 * the subtable. This entry contains the index of the
339 * start of the subtable and the number of bits with
340 * which the subtable is indexed (the log base 2 of the
341 * number of entries it contains). */
342 decode_table[cur_subtable_prefix] =
343 0x8000 | (cur_subtable_bits << 12) |
344 (cur_subtable_pos - table_num_entries);
347 u16 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx],
348 codeword_len - table_bits);
349 unsigned n = 1 << (cur_subtable_bits - (codeword_len - table_bits));
352 decode_table[cur_subtable_pos++] = entry;
355 /* Advance to the next symbol. This will either increase the
356 * codeword length, or keep the same codeword length but
357 * increase the symbol value. Note: since we are using
358 * bit-reversed codewords, we don't need to explicitly append
359 * zeroes to the codeword when the codeword length increases. */
361 len_counts[codeword_len]--;