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