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