]> wimlib.net Git - wimlib/blob - src/decompress_common.c
lzx-compress.c: Rename lzx_record_ctx.matches
[wimlib] / src / decompress_common.c
1 /*
2  * decompress_common.c
3  *
4  * Code for decompression shared among multiple compression formats.
5  *
6  * Author:  Eric Biggers
7  * Year:    2012 - 2014
8  *
9  * The author dedicates this file to the public domain.
10  * You can do whatever you want with this file.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 #  include "config.h"
15 #endif
16
17 #include "wimlib/decompress_common.h"
18 #include "wimlib/error.h"
19 #include "wimlib/util.h" /* for BUILD_BUG_ON()  */
20
21 #include <string.h>
22
23 #ifdef __GNUC__
24 #  ifdef __SSE2__
25 #    define USE_SSE2_FILL
26 #    include <emmintrin.h>
27 #  else
28 #    define USE_LONG_FILL
29 #  endif
30 #endif
31
32 /* Construct a direct mapping entry in the lookup table.  */
33 #define MAKE_DIRECT_ENTRY(symbol, length) ((symbol) | ((length) << 11))
34
35 /*
36  * make_huffman_decode_table() -
37  *
38  * Build a decoding table for a canonical prefix code, or "Huffman code".
39  *
40  * This takes as input the length of the codeword for each symbol in the
41  * alphabet and produces as output a table that can be used for fast
42  * decoding of prefix-encoded symbols using read_huffsym().
43  *
44  * Strictly speaking, a canonical prefix code might not be a Huffman
45  * code.  But this algorithm will work either way; and in fact, since
46  * Huffman codes are defined in terms of symbol frequencies, there is no
47  * way for the decompressor to know whether the code is a true Huffman
48  * code or not until all symbols have been decoded.
49  *
50  * Because the prefix code is assumed to be "canonical", it can be
51  * reconstructed directly from the codeword lengths.  A prefix code is
52  * canonical if and only if a longer codeword never lexicographically
53  * precedes a shorter codeword, and the lexicographic ordering of
54  * codewords of the same length is the same as the lexicographic ordering
55  * of the corresponding symbols.  Consequently, we can sort the symbols
56  * primarily by codeword length and secondarily by symbol value, then
57  * reconstruct the prefix code by generating codewords lexicographically
58  * in that order.
59  *
60  * This function does not, however, generate the prefix code explicitly.
61  * Instead, it directly builds a table for decoding symbols using the
62  * code.  The basic idea is this: given the next 'max_codeword_len' bits
63  * in the input, we can look up the decoded symbol by indexing a table
64  * containing 2**max_codeword_len entries.  A codeword with length
65  * 'max_codeword_len' will have exactly one entry in this table, whereas
66  * a codeword shorter than 'max_codeword_len' will have multiple entries
67  * in this table.  Precisely, a codeword of length n will be represented
68  * by 2**(max_codeword_len - n) entries in this table.  The 0-based index
69  * of each such entry will contain the corresponding codeword as a prefix
70  * when zero-padded on the left to 'max_codeword_len' binary digits.
71  *
72  * That's the basic idea, but we implement two optimizations regarding
73  * the format of the decode table itself:
74  *
75  * - For many compression formats, the maximum codeword length is too
76  *   long for it to be efficient to build the full decoding table
77  *   whenever a new prefix code is used.  Instead, we can build the table
78  *   using only 2**table_bits entries, where 'table_bits' is some number
79  *   less than or equal to 'max_codeword_len'.  Then, only codewords of
80  *   length 'table_bits' and shorter can be directly looked up.  For
81  *   longer codewords, the direct lookup instead produces the root of a
82  *   binary tree.  Using this tree, the decoder can do traditional
83  *   bit-by-bit decoding of the remainder of the codeword.  Child nodes
84  *   are allocated in extra entries at the end of the table; leaf nodes
85  *   contain symbols.  Note that the long-codeword case is, in general,
86  *   not performance critical, since in Huffman codes the most frequently
87  *   used symbols are assigned the shortest codeword lengths.
88  *
89  * - When we decode a symbol using a direct lookup of the table, we still
90  *   need to know its length so that the bitstream can be advanced by the
91  *   appropriate number of bits.  The simple solution is to simply retain
92  *   the 'lens' array and use the decoded symbol as an index into it.
93  *   However, this requires two separate array accesses in the fast path.
94  *   The optimization is to store the length directly in the decode
95  *   table.  We use the bottom 11 bits for the symbol and the top 5 bits
96  *   for the length.  In addition, to combine this optimization with the
97  *   previous one, we introduce a special case where the top 2 bits of
98  *   the length are both set if the entry is actually the root of a
99  *   binary tree.
100  *
101  * @decode_table:
102  *      The array in which to create the decoding table.
103  *      This must be 16-byte aligned and must have a length of at least
104  *      ((2**table_bits) + 2 * num_syms) entries.
105  *
106  * @num_syms:
107  *      The number of symbols in the alphabet; also, the length of the
108  *      'lens' array.  Must be less than or equal to
109  *      DECODE_TABLE_MAX_SYMBOLS.
110  *
111  * @table_bits:
112  *      The order of the decode table size, as explained above.  Must be
113  *      less than or equal to DECODE_TABLE_MAX_TABLE_BITS.
114  *
115  * @lens:
116  *      An array of length @num_syms, indexable by symbol, that gives the
117  *      length of the codeword, in bits, for that symbol.  The length can
118  *      be 0, which means that the symbol does not have a codeword
119  *      assigned.
120  *
121  * @max_codeword_len:
122  *      The longest codeword length allowed in the compression format.
123  *      All entries in 'lens' must be less than or equal to this value.
124  *      This must be less than or equal to DECODE_TABLE_MAX_CODEWORD_LEN.
125  *
126  * Returns 0 on success, or -1 if the lengths do not form a valid prefix
127  * code.
128  */
129 int
130 make_huffman_decode_table(u16 decode_table[const restrict],
131                           const unsigned num_syms,
132                           const unsigned table_bits,
133                           const u8 lens[const restrict],
134                           const unsigned max_codeword_len)
135 {
136         const unsigned table_num_entries = 1 << table_bits;
137         unsigned len_counts[max_codeword_len + 1];
138         u16 sorted_syms[num_syms];
139         int left;
140         void *decode_table_ptr;
141         unsigned sym_idx;
142         unsigned codeword_len;
143         unsigned stores_per_loop;
144         unsigned decode_table_pos;
145
146 #ifdef USE_LONG_FILL
147         const unsigned entries_per_long = sizeof(unsigned long) / sizeof(decode_table[0]);
148 #endif
149
150 #ifdef USE_SSE2_FILL
151         const unsigned entries_per_xmm = sizeof(__m128i) / sizeof(decode_table[0]);
152 #endif
153
154         /* Check parameters if assertions are enabled.  */
155         wimlib_assert2((uintptr_t)decode_table % DECODE_TABLE_ALIGNMENT == 0);
156         wimlib_assert2(num_syms <= DECODE_TABLE_MAX_SYMBOLS);
157         wimlib_assert2(table_bits <= DECODE_TABLE_MAX_TABLE_BITS);
158         wimlib_assert2(max_codeword_len <= DECODE_TABLE_MAX_CODEWORD_LEN);
159         for (unsigned sym = 0; sym < num_syms; sym++)
160                 wimlib_assert2(lens[sym] <= max_codeword_len);
161
162         /* Count how many symbols have each possible codeword length.
163          * Note that a length of 0 indicates the corresponding symbol is not
164          * used in the code and therefore does not have a codeword.  */
165         for (unsigned len = 0; len <= max_codeword_len; len++)
166                 len_counts[len] = 0;
167         for (unsigned sym = 0; sym < num_syms; sym++)
168                 len_counts[lens[sym]]++;
169
170         /* We can assume all lengths are <= max_codeword_len, but we
171          * cannot assume they form a valid prefix code.  A codeword of
172          * length n should require a proportion of the codespace equaling
173          * (1/2)^n.  The code is valid if and only if the codespace is
174          * exactly filled by the lengths, by this measure.  */
175         left = 1;
176         for (unsigned len = 1; len <= max_codeword_len; len++) {
177                 left <<= 1;
178                 left -= len_counts[len];
179                 if (unlikely(left < 0)) {
180                         /* The lengths overflow the codespace; that is, the code
181                          * is over-subscribed.  */
182                         DEBUG("Invalid prefix code (over-subscribed)");
183                         return -1;
184                 }
185         }
186
187         if (unlikely(left != 0)) {
188                 /* The lengths do not fill the codespace; that is, they form an
189                  * incomplete set.  */
190                 if (left == (1 << max_codeword_len)) {
191                         /* The code is completely empty.  This is arguably
192                          * invalid, but in fact it is valid in LZX and XPRESS,
193                          * so we must allow it.  By definition, no symbols can
194                          * be decoded with an empty code.  Consequently, we
195                          * technically don't even need to fill in the decode
196                          * table.  However, to avoid accessing uninitialized
197                          * memory if the algorithm nevertheless attempts to
198                          * decode symbols using such a code, we zero out the
199                          * decode table.  */
200                         memset(decode_table, 0,
201                                table_num_entries * sizeof(decode_table[0]));
202                         return 0;
203                 }
204                 DEBUG("Invalid prefix code (incomplete set)");
205                 return -1;
206         }
207
208         /* Sort the symbols primarily by length and secondarily by symbol order.
209          */
210         {
211                 unsigned offsets[max_codeword_len + 1];
212
213                 /* Initialize 'offsets' so that offsets[len] for 1 <= len <=
214                  * max_codeword_len is the number of codewords shorter than
215                  * 'len' bits.  */
216                 offsets[1] = 0;
217                 for (unsigned len = 1; len < max_codeword_len; len++)
218                         offsets[len + 1] = offsets[len] + len_counts[len];
219
220                 /* Use the 'offsets' array to sort the symbols.
221                  * Note that we do not include symbols that are not used in the
222                  * code.  Consequently, fewer than 'num_syms' entries in
223                  * 'sorted_syms' may be filled.  */
224                 for (unsigned sym = 0; sym < num_syms; sym++)
225                         if (lens[sym] != 0)
226                                 sorted_syms[offsets[lens[sym]]++] = sym;
227         }
228
229         /* Fill entries for codewords with length <= table_bits
230          * --- that is, those short enough for a direct mapping.
231          *
232          * The table will start with entries for the shortest codeword(s), which
233          * have the most entries.  From there, the number of entries per
234          * codeword will decrease.  As an optimization, we may begin filling
235          * entries with SSE2 vector accesses (8 entries/store), then change to
236          * 'unsigned long' accesses (2 or 4 entries/store), then change to
237          * 16-bit accesses (1 entry/store).  */
238         decode_table_ptr = decode_table;
239         sym_idx = 0;
240         codeword_len = 1;
241 #ifdef USE_SSE2_FILL
242         /* Fill the entries one 128-bit vector at a time.
243          * This is 8 entries per store.  */
244         stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_xmm;
245         for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
246                 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
247                 for (; sym_idx < end_sym_idx; sym_idx++) {
248                         /* Note: unlike in the 'long' version below, the __m128i
249                          * type already has __attribute__((may_alias)), so using
250                          * it to access the decode table, which is an array of
251                          * unsigned shorts, will not violate strict aliasing.
252                          */
253                         u16 entry;
254                         __m128i v;
255                         __m128i *p;
256                         unsigned n;
257
258                         entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
259
260                         v = _mm_set1_epi16(entry);
261                         p = (__m128i*)decode_table_ptr;
262                         n = stores_per_loop;
263                         do {
264                                 *p++ = v;
265                         } while (--n);
266                         decode_table_ptr = p;
267                 }
268         }
269 #endif /* USE_SSE2_FILL */
270
271 #ifdef USE_LONG_FILL
272         /* Fill the entries one 'unsigned long' at a time.
273          * On 32-bit systems this is 2 entries per store, while on 64-bit
274          * systems this is 4 entries per store.  */
275         stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_long;
276         for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
277                 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
278                 for (; sym_idx < end_sym_idx; sym_idx++) {
279
280                         /* Accessing the array of unsigned shorts as unsigned
281                          * longs would violate strict aliasing and would require
282                          * compiling the code with -fno-strict-aliasing to
283                          * guarantee correctness.  To work around this problem,
284                          * use the gcc 'may_alias' extension to define a special
285                          * unsigned long type that may alias any other in-memory
286                          * variable.  */
287                         typedef unsigned long __attribute__((may_alias)) aliased_long_t;
288
289                         unsigned long v;
290                         aliased_long_t *p;
291                         unsigned n;
292
293                         BUILD_BUG_ON(sizeof(unsigned long) != 4 &&
294                                      sizeof(unsigned long) != 8);
295
296                         v = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
297                         v |= v << 16;
298                         if (sizeof(unsigned long) == 8) {
299                                 /* This may produce a compiler warning if an
300                                  * 'unsigned long' is 32 bits, but this won't be
301                                  * executed unless an 'unsigned long' is at
302                                  * least 64 bits anyway.  */
303                                 v |= v << 32;
304                         }
305
306                         p = (aliased_long_t *)decode_table_ptr;
307                         n = stores_per_loop;
308
309                         do {
310                                 *p++ = v;
311                         } while (--n);
312                         decode_table_ptr = p;
313                 }
314         }
315 #endif /* USE_LONG_FILL */
316
317         /* Fill the entries one 16-bit integer at a time.  */
318         stores_per_loop = (1 << (table_bits - codeword_len));
319         for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
320                 unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
321                 for (; sym_idx < end_sym_idx; sym_idx++) {
322                         u16 entry;
323                         u16 *p;
324                         unsigned n;
325
326                         entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
327
328                         p = (u16*)decode_table_ptr;
329                         n = stores_per_loop;
330
331                         do {
332                                 *p++ = entry;
333                         } while (--n);
334
335                         decode_table_ptr = p;
336                 }
337         }
338
339         /* If we've filled in the entire table, we are done.  Otherwise,
340          * there are codewords longer than table_bits for which we must
341          * generate binary trees.  */
342
343         decode_table_pos = (u16*)decode_table_ptr - decode_table;
344         if (decode_table_pos != table_num_entries) {
345                 unsigned j;
346                 unsigned next_free_tree_slot;
347                 unsigned cur_codeword;
348
349                 /* First, zero out the remaining entries.  This is
350                  * necessary so that these entries appear as
351                  * "unallocated" in the next part.  Each of these entries
352                  * will eventually be filled with the representation of
353                  * the root node of a binary tree.  */
354                 j = decode_table_pos;
355                 do {
356                         decode_table[j] = 0;
357                 } while (++j != table_num_entries);
358
359                 /* We allocate child nodes starting at the end of the
360                  * direct lookup table.  Note that there should be
361                  * 2*num_syms extra entries for this purpose, although
362                  * fewer than this may actually be needed.  */
363                 next_free_tree_slot = table_num_entries;
364
365                 /* Iterate through each codeword with length greater than
366                  * 'table_bits', primarily in order of codeword length
367                  * and secondarily in order of symbol.  */
368                 for (cur_codeword = decode_table_pos << 1;
369                      codeword_len <= max_codeword_len;
370                      codeword_len++, cur_codeword <<= 1)
371                 {
372                         unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
373                         for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++)
374                         {
375                                 /* 'sym' is the symbol represented by the
376                                  * codeword.  */
377                                 unsigned sym = sorted_syms[sym_idx];
378
379                                 unsigned extra_bits = codeword_len - table_bits;
380
381                                 unsigned node_idx = cur_codeword >> extra_bits;
382
383                                 /* Go through each bit of the current codeword
384                                  * beyond the prefix of length @table_bits and
385                                  * walk the appropriate binary tree, allocating
386                                  * any slots that have not yet been allocated.
387                                  *
388                                  * Note that the 'pointer' entry to the binary
389                                  * tree, which is stored in the direct lookup
390                                  * portion of the table, is represented
391                                  * identically to other internal (non-leaf)
392                                  * nodes of the binary tree; it can be thought
393                                  * of as simply the root of the tree.  The
394                                  * representation of these internal nodes is
395                                  * simply the index of the left child combined
396                                  * with the special bits 0xC000 to distingush
397                                  * the entry from direct mapping and leaf node
398                                  * entries.  */
399                                 do {
400
401                                         /* At least one bit remains in the
402                                          * codeword, but the current node is an
403                                          * unallocated leaf.  Change it to an
404                                          * internal node.  */
405                                         if (decode_table[node_idx] == 0) {
406                                                 decode_table[node_idx] =
407                                                         next_free_tree_slot | 0xC000;
408                                                 decode_table[next_free_tree_slot++] = 0;
409                                                 decode_table[next_free_tree_slot++] = 0;
410                                         }
411
412                                         /* Go to the left child if the next bit
413                                          * in the codeword is 0; otherwise go to
414                                          * the right child.  */
415                                         node_idx = decode_table[node_idx] & 0x3FFF;
416                                         --extra_bits;
417                                         node_idx += (cur_codeword >> extra_bits) & 1;
418                                 } while (extra_bits != 0);
419
420                                 /* We've traversed the tree using the entire
421                                  * codeword, and we're now at the entry where
422                                  * the actual symbol will be stored.  This is
423                                  * distinguished from internal nodes by not
424                                  * having its high two bits set.  */
425                                 decode_table[node_idx] = sym;
426                         }
427                 }
428         }
429         return 0;
430 }