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