]> wimlib.net Git - wimlib/blob - src/decompress.c
Rewrite make_huffman_decode_table()
[wimlib] / src / decompress.c
1 /*
2  * decompress.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 General Public License as published by the Free
14  * Software Foundation; either version 3 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 General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #include "decompress.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_assert2(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 reading %zu bytes from "
50                       "bitstream (only have %u bytes left)",
51                       n, stream->data_bytes_left);
52                 return 1;
53         }
54         memcpy(p, stream->data, n);
55         stream->data += n;
56         stream->data_bytes_left -= n;
57
58         /* It's possible to copy an odd number of bytes and leave the stream in
59          * an inconsistent state. Fix it by reading the next byte, if it is
60          * there. */
61         if ((n & 1) && stream->data_bytes_left != 0) {
62                 stream->bitsleft = 8;
63                 stream->data_bytes_left--;
64                 stream->bitbuf |= (input_bitbuf_t)(*stream->data) <<
65                                         (sizeof(input_bitbuf_t) * 8 - 8);
66                 stream->data++;
67         }
68         return 0;
69 }
70
71 /*
72  * Builds a fast huffman decoding table from an array that gives the length of
73  * the codeword for each symbol in the alphabet.  Originally based on code
74  * written by David Tritscher (taken the original LZX decompression code); also
75  * heavily modified to add some optimizations used in the zlib code, as well as
76  * more comments.
77  *
78  * @decode_table:       The array in which to create the fast huffman decoding
79  *                      table.  It must have a length of at least
80  *                      (2**table_bits) + 2 * num_syms to guarantee
81  *                      that there is enough space.
82  *
83  * @num_syms:           Total number of symbols in the Huffman tree.
84  *
85  * @table_bits:         Any symbols with a code length of table_bits or less can
86  *                      be decoded in one lookup of the table.  2**table_bits
87  *                      must be greater than or equal to @num_syms if there are
88  *                      any Huffman codes longer than @table_bits.
89  *
90  * @lens:               An array of length @num_syms, indexable by symbol, that
91  *                      gives the length of the Huffman codeward for that
92  *                      symbol.  Because the Huffman tree is in canonical form,
93  *                      it can be reconstructed by only knowing the length of
94  *                      the codeword for each symbol.  It is assumed, but not
95  *                      checked, that every length is less than
96  *                      @max_codeword_len.
97  *
98  * @max_codeword_len:   The longest codeword length allowed in the compression
99  *                      format.
100  *
101  * Returns 0 on success; returns -1 if the length values do not correspond to a
102  * valid Huffman tree.
103  *
104  * The format of the Huffamn decoding table is as follows.  The first (1 <<
105  * table_bits) entries of the table are indexed by chunks of the input of size
106  * @table_bits.  If the next Huffman codeword in the input happens to have a
107  * length of exactly @table_bits, the symbol is simply read directly from the
108  * decoding table.  Alternatively, if the next Huffman codeword has length _less
109  * than_ @table_bits, the symbol is also read directly from the decode table;
110  * this is possible because every entry in the table that is indexed by an
111  * integer that has the shorter codeword as a binary prefix is filled in with
112  * the appropriate symbol.  If a codeword has length n <= table_bits, it will
113  * have 2**(table_bits - n) possible suffixes, and thus that many entries in the
114  * decoding table.
115  *
116  * It's a bit more complicated if the next Huffman codeword has length of more
117  * than @table_bits.  The table entry indexed by the first @table_bits of that
118  * codeword cannot give the appropriate symbol directly, because that entry is
119  * guaranteed to be referenced by the Huffman codewords of multiple symbols.
120  * And while the LZX compression format does not allow codes longer than 16
121  * bits, a table of size (2 ** 16) = 65536 entries would be too slow to create.
122  *
123  * There are several different ways to make it possible to look up the symbols
124  * for codewords longer than @table_bits.  One way is to make the entries for
125  * the prefixes of length @table_bits of those entries be pointers to additional
126  * decoding tables that are indexed by some number of additional bits of the
127  * codeword.  The technique used here is a bit simpler, however: just store the
128  * needed subtrees of the Huffman tree in the decoding table after the lookup
129  * entries, beginning at index (2**table_bits).  Real pointers are replaced by
130  * indices into the decoding table, and symbol entries are distinguished from
131  * pointers by the fact that values less than @num_syms must be symbol values.
132  */
133 int make_huffman_decode_table(u16 decode_table[],  unsigned num_syms,
134                               unsigned table_bits, const u8 lens[],
135                               unsigned max_codeword_len)
136 {
137         unsigned len_counts[max_codeword_len + 1];
138         u16 sorted_syms[num_syms];
139         unsigned offsets[max_codeword_len + 1];
140         const unsigned table_num_entries = 1 << table_bits;
141
142         /* accumulate lengths for codes */
143         for (unsigned i = 0; i <= max_codeword_len; i++)
144                 len_counts[i] = 0;
145
146         for (unsigned sym = 0; sym < num_syms; sym++) {
147                 wimlib_assert2(lens[sym] <= max_codeword_len);
148                 len_counts[lens[sym]]++;
149         }
150
151         /* check for an over-subscribed or incomplete set of lengths */
152         int left = 1;
153         for (unsigned len = 1; len <= max_codeword_len; len++) {
154                 left <<= 1;
155                 left -= len_counts[len];
156                 if (left < 0) { /* over-subscribed */
157                         ERROR("Invalid Huffman code (over-subscribed)");
158                         return -1;
159                 }
160         }
161         if (left != 0) /* incomplete set */{
162                 if (left == 1 << max_codeword_len) {
163                         /* Empty code--- okay in XPRESS and LZX */
164                         memset(decode_table, 0,
165                                table_num_entries * sizeof(decode_table[0]));
166                         return 0;
167                 } else {
168                         ERROR("Invalid Huffman code (incomplete set)");
169                         return -1;
170                 }
171         }
172
173         /* Generate offsets into symbol table for each length for sorting */
174         offsets[1] = 0;
175         for (unsigned len = 1; len < max_codeword_len; len++)
176                 offsets[len + 1] = offsets[len] + len_counts[len];
177
178         /* Sort symbols primarily by length and secondarily by symbol order.
179          * This is basically a count-sort over the codeword lengths.
180          * In the process, calculate the number of symbols that have nonzero
181          * length and are therefore used in the symbol stream. */
182         unsigned num_used_syms = 0;
183         for (unsigned sym = 0; sym < num_syms; sym++) {
184                 if (lens[sym] != 0) {
185                         sorted_syms[offsets[lens[sym]]++] = sym;
186                         num_used_syms++;
187                 }
188         }
189
190         /* Fill entries for codewords short enough for a direct mapping.  We can
191          * take advantage of the ordering of the codewords, since the Huffman
192          * code is canonical.  It must be the case that all the codewords of
193          * some length L numerically precede all the codewords of length L + 1.
194          * Furthermore, if we have 2 symbols A and B with the same codeword
195          * length but symbol A is sorted before symbol B, then then we know that
196          * the codeword for A numerically precedes the codeword for B. */
197         unsigned decode_table_pos = 0;
198         unsigned i = 0;
199
200         wimlib_assert2(num_used_syms != 0);
201         while (1) {
202                 unsigned sym = sorted_syms[i];
203                 unsigned codeword_len = lens[sym];
204                 if (codeword_len > table_bits)
205                         break;
206
207                 unsigned num_entries = 1 << (table_bits - codeword_len);
208                 if (num_entries >=
209                         (sizeof(unsigned long) / sizeof(decode_table[0])))
210                 {
211                         wimlib_assert2(decode_table_pos % 4 == 0);
212                         BUILD_BUG_ON(sizeof(unsigned long) != 4 &&
213                                      sizeof(unsigned long) != 8);
214
215                         unsigned long *p = (unsigned long *)&decode_table[decode_table_pos];
216                         unsigned long n = num_entries /
217                                                 (sizeof(unsigned long) /
218                                                         sizeof(decode_table[0]));
219                         unsigned long v = sym;
220                         if (sizeof(unsigned long) >= 4)
221                                 v |= v << 16;
222                         if (sizeof(unsigned long) >= 8)
223                                 v |= v << 32;
224                         do {
225                                 *p++ = v;
226                         } while (--n);
227
228                         decode_table_pos += num_entries;
229                 } else {
230                         do {
231                                 decode_table[decode_table_pos++] = sym;
232                         } while (--num_entries);
233                 }
234                 wimlib_assert2(decode_table_pos <= table_num_entries);
235                 if (++i == num_used_syms) {
236                         wimlib_assert2(decode_table_pos == table_num_entries);
237                         /* No codewords were longer than @table_bits, so the
238                          * table is now entirely filled with the codewords. */
239                         return 0;
240                 }
241         }
242
243         wimlib_assert2(i < num_used_syms);
244         wimlib_assert2(decode_table_pos < table_num_entries);
245
246         /* Fill in the remaining entries, which correspond to codes longer than
247          * @table_bits.
248          *
249          * First, zero out the rest of the entries.  This is necessary so that
250          * the entries appear as "unallocated" in the next part. */
251         {
252                 unsigned j = decode_table_pos;
253                 do {
254                         decode_table[j] = 0;
255                 } while (++j != table_num_entries);
256         }
257
258         /* Assert that 2**table_bits is at least num_syms.  If this wasn't the
259          * case, we wouldn't be able to distinguish pointer entries from symbol
260          * entries. */
261         wimlib_assert2(table_num_entries >= num_syms);
262
263         /* The current Huffman codeword  */
264         unsigned cur_codeword = decode_table_pos;
265
266         /* The tree nodes are allocated starting at decode_table[1 <<
267          * table_bits].  Remember that the full size of the table, including the
268          * extra space for the tree nodes, is actually 2**table_bits + 2 *
269          * num_syms slots, while table_num_entries is only 2**table_Bits. */
270         unsigned next_free_tree_slot = table_num_entries;
271
272         /* Go through every codeword of length greater than @table_bits,
273          * primarily in order of codeword length and secondarily in order of
274          * symbol. */
275         unsigned prev_codeword_len = table_bits;
276         do {
277                 unsigned sym = sorted_syms[i];
278                 unsigned codeword_len = lens[sym];
279                 unsigned extra_bits = codeword_len - table_bits;
280                 unsigned extra_mask;
281
282                 cur_codeword <<= (codeword_len - prev_codeword_len);
283                 prev_codeword_len = codeword_len;
284
285                 /* index of the current node; find it from the prefix of the
286                  * current Huffman codeword. */
287                 unsigned node_idx = cur_codeword >> extra_bits;
288                 wimlib_assert2(node_idx < table_num_entries);
289
290                 /* Go through each bit of the current Huffman codeword beyond
291                  * the prefix of length @table_bits and walk the tree,
292                  * allocating any slots that have not yet been allocated. */
293                 do {
294
295                         /* If the current tree node points to nowhere
296                          * but we need to follow it, allocate a new node
297                          * for it to point to. */
298                         if (decode_table[node_idx] == 0) {
299                                 decode_table[node_idx] = next_free_tree_slot;
300                                 decode_table[next_free_tree_slot++] = 0;
301                                 decode_table[next_free_tree_slot++] = 0;
302                                 wimlib_assert2(next_free_tree_slot <=
303                                                table_num_entries + 2 * num_syms);
304                         }
305
306                         /* Set node_idx to left child */
307                         node_idx = decode_table[node_idx];
308
309                         /* Is the next bit 0 or 1? If 0, go left (already done).
310                          * If 1, go right by incrementing node_idx. */
311                         --extra_bits;
312                         node_idx += (cur_codeword >> extra_bits) & 1;
313                 } while (extra_bits != 0);
314
315                 /* node_idx is now the index of the leaf entry into which the
316                  * actual symbol will go. */
317                 decode_table[node_idx] = sym;
318
319                 /* cur_codeword is always incremented because this is
320                  * how canonical Huffman codes are generated (add 1 for
321                  * each code, then left shift whenever the code length
322                  * increases) */
323                 cur_codeword++;
324         } while (++i != num_used_syms);
325         return 0;
326 }
327
328 /* Reads a Huffman-encoded symbol when it is known there are less than
329  * MAX_CODE_LEN bits remaining in the bitstream. */
330 int read_huffsym_near_end_of_input(struct input_bitstream *istream,
331                                    const u16 decode_table[],
332                                    const u8 lens[],
333                                    unsigned num_syms,
334                                    unsigned table_bits,
335                                    unsigned *n)
336 {
337         unsigned bitsleft = istream->bitsleft;
338         unsigned key_size;
339         u16 sym;
340         u16 key_bits;
341
342         if (table_bits > bitsleft) {
343                 key_size = bitsleft;
344                 bitsleft = 0;
345                 key_bits = bitstream_peek_bits(istream, key_size) <<
346                                                 (table_bits - key_size);
347         } else {
348                 key_size = table_bits;
349                 bitsleft -= table_bits;
350                 key_bits = bitstream_peek_bits(istream, table_bits);
351         }
352
353         sym = decode_table[key_bits];
354         if (sym >= num_syms) {
355                 bitstream_remove_bits(istream, key_size);
356                 do {
357                         if (bitsleft == 0) {
358                                 ERROR("Input stream exhausted");
359                                 return 1;
360                         }
361                         key_bits = sym + bitstream_peek_bits(istream, 1);
362                         bitstream_remove_bits(istream, 1);
363                         bitsleft--;
364                 } while ((sym = decode_table[key_bits]) >= num_syms);
365         } else {
366                 bitstream_remove_bits(istream, lens[sym]);
367         }
368         *n = sym;
369         return 0;
370 }