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