]> wimlib.net Git - wimlib/blob - src/decomp.c
Clean up file headers
[wimlib] / src / decomp.c
1 /*
2  * decomp.c
3  *
4  * Functions used for decompression.
5  */
6
7 /*
8  * Copyright (C) 2012 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU Lesser General Public License as published by the Free
14  * Software Foundation; either version 2.1 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #include "decomp.h"
27 #include <string.h>
28
29 /* Reads @n bytes from the bitstream @stream into the location pointed to by @dest.
30  * The bitstream must be 16-bit aligned. */
31 int bitstream_read_bytes(struct input_bitstream *stream, size_t n, void *dest)
32 {
33         /* Precondition:  The bitstream is 16-byte aligned. */
34         wimlib_assert(stream->bitsleft % 16 == 0);
35
36         u8 *p = dest;
37
38         /* Get the bytes currently in the buffer variable. */
39         while (stream->bitsleft != 0) {
40                 if (n-- == 0)
41                         return 0;
42                 *p++ = bitstream_peek_bits(stream, 8);
43                 bitstream_remove_bits(stream, 8);
44         }
45
46         /* Get the rest directly from the pointer to the data.  Of course, it's
47          * necessary to check there are really n bytes available. */
48         if (n > stream->data_bytes_left) {
49                 ERROR("Unexpected end of input when "
50                                 "reading %zu bytes from bitstream "
51                                 "(only have %u bytes left)\n", n,
52                                 stream->data_bytes_left);
53                 return 1;
54         }
55         memcpy(p, stream->data, n);
56         stream->data += n;
57         stream->data_bytes_left -= n;
58
59         /* It's possible to copy an odd number of bytes and leave the stream in
60          * an inconsistent state. Fix it by reading the next byte, if it is
61          * there. */
62         if ((n & 1) && stream->data_bytes_left != 0) {
63                 stream->bitsleft = 8;
64                 stream->data_bytes_left--;
65                 stream->bitbuf |= (input_bitbuf_t)(*stream->data) << 
66                                         (sizeof(input_bitbuf_t) * 8 - 8);
67                 stream->data++;
68         }
69         return 0;
70 }
71
72 /* Aligns the bitstream on a 16-bit boundary.
73  *
74  * Note: M$'s idea of "alignment" means that for some reason, a 16-bit word
75  * should be skipped over if the buffer happens to already be aligned on such a
76  * boundary.  This only applies for realigning the stream after the blocktype
77  * and length fields of an uncompressed block, however; it does not apply when
78  * realigning the stream after the end of the uncompressed block.
79  */
80 int align_input_bitstream(struct input_bitstream *stream, 
81                           bool skip_word_if_aligned)
82 {
83         int ret;
84         if (stream->bitsleft % 16 != 0) {
85                 bitstream_remove_bits(stream, stream->bitsleft % 16);
86         } else if (skip_word_if_aligned) {
87                 if (stream->bitsleft == 0) {
88                         ret = bitstream_ensure_bits(stream, 16);
89                         if (ret != 0) {
90                                 ERROR("Unexpected end of input when "
91                                                 "aligning bitstream!\n");
92                                 return ret;
93                         }
94                 }
95                 bitstream_remove_bits(stream, 16);
96         }
97         return 0;
98 }
99
100 /* 
101  * Builds a fast huffman decoding table from a canonical huffman code lengths
102  * table.  Based on code written by David Tritscher.
103  *
104  * @decode_table:       The array in which to create the fast huffman decoding
105  *                              table.  It must have a length of at least
106  *                              (2**num_bits) + 2 * num_syms to guarantee
107  *                              that there is enough space.
108  *
109  * @num_syms:   Total number of symbols in the Huffman tree.
110  *
111  * @num_bits:   Any symbols with a code length of num_bits or less can be
112  *                      decoded in one lookup of the table.  2**num_bits
113  *                      must be greater than or equal to @num_syms if there are 
114  *                      any Huffman codes longer than @num_bits.
115  *
116  * @lens:       An array of length @num_syms, indexable by symbol, that
117  *                      gives the length of that symbol.  Because the Huffman
118  *                      tree is in canonical form, it can be reconstructed by
119  *                      only knowing the length of the code for each symbol.
120  *
121  * @make_codeword_len:  An integer that gives the longest possible codeword
122  *                      length.
123  *
124  * Returns 0 on success; returns 1 if the length values do not correspond to a
125  * valid Huffman tree, or if there are codes of length greater than @num_bits
126  * but 2**num_bits < num_syms.
127  *
128  * What exactly is the format of the fast Huffman decoding table?  The first 
129  * (1 << num_bits) entries of the table are indexed by chunks of the input of
130  * size @num_bits.  If the next Huffman code in the input happens to have a
131  * length of exactly @num_bits, the symbol is simply read directly from the
132  * decoding table.  Alternatively, if the next Huffman code has length _less
133  * than_ @num_bits, the symbol is also read directly from the decode table; this
134  * is possible because every entry in the table that is indexed by an integer
135  * that has the shorter code as a binary prefix is filled in with the
136  * appropriate symbol.  If a code has length n <= num_bits, it will have
137  * 2**(num_bits - n) possible suffixes, and thus that many entries in the
138  * decoding table.
139  *
140  * It's a bit more complicated if the next Huffman code has length of more than
141  * @num_bits.  The table entry indexed by the first @num_bits of that code
142  * cannot give the appropriate symbol directly, because that entry is guaranteed
143  * to be referenced by the Huffman codes for multiple symbols.  And while the
144  * LZX compression format does not allow codes longer than 16 bits, a table of
145  * size (2 ** 16) = 65536 entries would be too slow to create.
146  *
147  * There are several different ways to make it possible to look up the symbols
148  * for codes longer than @num_bits.  A common way is to make the entries for the
149  * prefixes of length @num_bits of those entries be pointers to additional
150  * decoding tables that are indexed by some number of additional bits of the
151  * code symbol.  The technique used here is a bit simpler, however.  We just
152  * store the needed subtrees of the Huffman tree in the decoding table after the
153  * lookup entries, beginning at index (2**num_bits).  Real pointers are
154  * replaced by indices into the decoding table, and we distinguish symbol
155  * entries from pointers by the fact that values less than @num_syms must be
156  * symbol values.
157  */
158 int make_huffman_decode_table(u16 decode_table[],  uint num_syms, 
159                               uint num_bits, const u8 lens[], 
160                               uint max_code_len)
161 {
162         /* Number of entries in the decode table. */
163         u32 table_num_entries = 1 << num_bits;
164
165         /* Current position in the decode table. */
166         u32 decode_table_pos = 0;
167
168         /* Fill entries for codes short enough for a direct mapping.  Here we
169          * are taking advantage of the ordering of the codes, since they are for
170          * a canonical Huffman tree.  It must be the case that all the codes of
171          * some length @code_length, zero-extended or one-extended, numerically
172          * precede all the codes of length @code_length + 1.  Furthermore, if we
173          * have 2 symbols A and B, such that A is listed before B in the lens
174          * array, and both symbols have the same code length, then we know that
175          * the code for A numerically precedes the code for B.
176          * */
177         for (uint code_len = 1; code_len <= num_bits; code_len++) {
178
179                 /* Number of entries that a code of length @code_length would
180                  * need.  */
181                 u32 code_num_entries = 1 << (num_bits - code_len);
182
183
184                 /* For each symbol of length @code_len, fill in its entries in
185                  * the decode table. */
186                 for (uint sym = 0; sym < num_syms; sym++) {
187
188                         if (lens[sym] != code_len)
189                                 continue;
190
191
192                         /* Check for table overrun.  This can only happen if the
193                          * given lengths do not correspond to a valid Huffman
194                          * tree.  */
195                         if (decode_table_pos >= table_num_entries) {
196                                 ERROR("Huffman decoding table overrun: "
197                                                 "pos = %u, num_entries = %u\n",
198                                                 decode_table_pos, 
199                                                 table_num_entries);
200                                 return 1;
201                         }
202
203                         /* Fill all possible lookups of this symbol with
204                          * the symbol itself. */
205                         for (uint i = 0; i < code_num_entries; i++)
206                                 decode_table[decode_table_pos + i] = sym;
207
208                         /* Increment the position in the decode table by
209                          * the number of entries that were just filled
210                          * in. */
211                         decode_table_pos += code_num_entries;
212                 }
213         }
214
215         /* If all entries of the decode table have been filled in, there are no
216          * codes longer than num_bits, so we are done filling in the decode
217          * table. */
218         if (decode_table_pos == table_num_entries)
219                 return 0;
220
221         /* Otherwise, fill in the remaining entries, which correspond to codes longer
222          * than @num_bits. */
223
224
225         /* First, zero out the rest of the entries; this is necessary so
226          * that the entries appear as "unallocated" in the next part.  */
227         for (uint i = decode_table_pos; i < table_num_entries; i++)
228                 decode_table[i] = 0;
229
230         /* Assert that 2**num_bits is at least num_syms.  If this wasn't the
231          * case, we wouldn't be able to distinguish pointer entries from symbol
232          * entries. */
233         wimlib_assert((1 << num_bits) >= num_syms);
234
235
236         /* The current Huffman code.  */
237         uint current_code = decode_table_pos;
238
239         /* The tree nodes are allocated starting at
240          * decode_table[table_num_entries].  Remember that the full size of the
241          * table, including the extra space for the tree nodes, is actually
242          * 2**num_bits + 2 * num_syms slots, while table_num_entries is only
243          * 2**num_bits. */
244         uint next_free_tree_slot = table_num_entries;
245
246         /* Go through every codeword of length greater than @num_bits.  Note:
247          * the LZX format guarantees that the codeword length can be at most 16
248          * bits. */
249         for (uint code_len = num_bits + 1; code_len <= max_code_len; 
250                                                         code_len++) 
251         {
252                 current_code <<= 1;
253                 for (uint sym = 0; sym < num_syms; sym++) {
254                         if (lens[sym] != code_len)
255                                 continue;
256
257
258                         /* i is the index of the current node; find it from the
259                          * prefix of the current Huffman code. */
260                         uint i = current_code >> (code_len - num_bits);
261
262                         if (i >= (1 << num_bits)) {
263                                 ERROR("Invalid canonical Huffman code!\n");
264                                 return 1;
265                         }
266
267                         /* Go through each bit of the current Huffman code
268                          * beyond the prefix of length num_bits and walk the
269                          * tree, "allocating" slots that have not yet been
270                          * allocated. */
271                         for (int bit_num = num_bits + 1; bit_num <= code_len; bit_num++) {
272
273                                 /* If the current tree node points to nowhere
274                                  * but we need to follow it, allocate a new node
275                                  * for it to point to. */
276                                 if (decode_table[i] == 0) {
277                                         decode_table[i] = next_free_tree_slot;
278                                         decode_table[next_free_tree_slot++] = 0;
279                                         decode_table[next_free_tree_slot++] = 0;
280                                 }
281
282                                 i = decode_table[i];
283
284                                 /* Is the next bit 0 or 1? If 0, go left;
285                                  * otherwise, go right (by incrementing i by 1) */
286                                 int bit_pos = code_len - bit_num;
287
288                                 int bit = (current_code & (1 << bit_pos)) >> 
289                                                                 bit_pos;
290                                 i += bit;
291                         }
292
293                         /* i is now the index of the leaf entry into which the
294                          * actual symbol will go. */
295                         decode_table[i] = sym;
296
297                         /* Increment decode_table_pos only if the prefix of the
298                          * Huffman code changes. */
299                         if (current_code >> (code_len - num_bits) != 
300                                         (current_code + 1) >> (code_len - num_bits))
301                                 decode_table_pos++;
302
303                         /* current_code is always incremented because this is
304                          * how canonical Huffman codes are generated (add 1 for
305                          * each code, then left shift whenever the code length
306                          * increases) */
307                         current_code++;
308                 }
309         }
310
311
312         /* If the lengths really represented a valid Huffman tree, all
313          * @table_num_entries in the table will have been filled.  However, it
314          * is also possible that the tree is completely empty (as noted
315          * earlier) with all 0 lengths, and this is expected to succeed. */
316
317         if (decode_table_pos != table_num_entries) {
318
319                 for (uint i = 0; i < num_syms; i++) {
320                         if (lens[i] != 0) {
321                                 ERROR("Lengths do not form a valid "
322                                                 "canonical Huffman tree "
323                                                 "(only filled %u of %u decode "
324                                                 "table slots)!\n", decode_table_pos, 
325                                                 table_num_entries);
326                                 return 1;
327                         }
328                 }
329         }
330         return 0;
331 }
332
333 /* Reads a Huffman-encoded symbol when it is known there are less than
334  * MAX_CODE_LEN bits remaining in the bitstream. */
335 static int read_huffsym_near_end_of_input(struct input_bitstream *istream, 
336                                           const u16 decode_table[], 
337                                           const u8 lens[], 
338                                           uint num_syms, 
339                                           uint table_bits, 
340                                           uint *n)
341 {
342         uint bitsleft = istream->bitsleft;
343         uint key_size;
344         u16 sym;
345         u16 key_bits;
346
347         if (table_bits > bitsleft) {
348                 key_size = bitsleft;
349                 bitsleft = 0;
350                 key_bits = bitstream_peek_bits(istream, key_size) << 
351                                                 (table_bits - key_size);
352         } else {
353                 key_size = table_bits;
354                 bitsleft -= table_bits;
355                 key_bits = bitstream_peek_bits(istream, table_bits);
356         }
357
358         sym = decode_table[key_bits];
359         if (sym >= num_syms) {
360                 bitstream_remove_bits(istream, key_size);
361                 do {
362                         if (bitsleft == 0) {
363                                 ERROR("Input stream exhausted!\n");
364                                 return 1;
365                         }
366                         key_bits = sym + bitstream_peek_bits(istream, 1);
367                         bitstream_remove_bits(istream, 1);
368                         bitsleft--;
369                 } while ((sym = decode_table[key_bits]) >= num_syms);
370         } else {
371                 bitstream_remove_bits(istream, lens[sym]);
372         }
373         *n = sym;
374         return 0;
375 }
376
377 /* 
378  * Reads a Huffman-encoded symbol from a bitstream.
379  *
380  * This function may be called hundreds of millions of times when extracting a
381  * large WIM file.  I'm not sure it could be made much faster that it is,
382  * especially since there isn't enough time to make a big table that allows
383  * decoding multiple symbols per lookup.  But if extracting files to a hard
384  * disk, the IO will be the bottleneck anyway.
385  *
386  * @buf:        The input buffer from which the symbol will be read.
387  * @decode_table:       The fast Huffman decoding table for the Huffman tree.
388  * @lengths:            The table that gives the length of the code for each
389  *                              symbol.
390  * @num_symbols:        The number of symbols in the Huffman code.
391  * @table_bits:         Huffman codes this length or less can be looked up 
392  *                              directory in the decode_table, as the
393  *                              decode_table contains 2**table_bits entries.
394  */
395 int read_huffsym(struct input_bitstream *stream, 
396              const u16 decode_table[], 
397              const u8 lengths[], 
398              unsigned num_symbols, 
399              unsigned table_bits, 
400              uint *n, 
401              unsigned max_codeword_len)
402 {
403         /* In the most common case, there are at least max_codeword_len bits
404          * remaining in the stream. */
405         if (bitstream_ensure_bits(stream, max_codeword_len) == 0) {
406
407                 /* Use the next table_bits of the input as an index into the
408                  * decode_table. */
409                 u16 key_bits = bitstream_peek_bits(stream, table_bits);
410
411                 u16 sym = decode_table[key_bits];
412
413                 /* If the entry in the decode table is not a valid symbol, it is
414                  * the offset of the root of its Huffman subtree. */
415                 if (sym >= num_symbols) {
416                         bitstream_remove_bits(stream, table_bits);
417                         do {
418                                 key_bits = sym + bitstream_peek_bits(stream, 1);
419                                 bitstream_remove_bits(stream, 1);
420
421                                 wimlib_assert(key_bits < num_symbols * 2 + 
422                                                         (1 << table_bits));
423                         } while ((sym = decode_table[key_bits]) >= num_symbols);
424                 } else {
425                         wimlib_assert(lengths[sym] <= table_bits);
426                         bitstream_remove_bits(stream, lengths[sym]);
427                 }
428                 *n = sym;
429                 return 0;
430         } else {
431                 /* Otherwise, we must be careful to use only the bits that are
432                  * actually remaining.  Don't inline this part since it is very
433                  * rarely used. */
434                 return read_huffsym_near_end_of_input(stream, decode_table, lengths,
435                                         num_symbols, table_bits, n);
436         }
437 }