]> wimlib.net Git - wimlib/blob - src/comp.c
7837a4614629f8b33fcde74051f676b76e7d220a
[wimlib] / src / comp.c
1 /*
2  * comp.c
3  *
4  * Functions used for compression.
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 "comp.h"
27 #include <stdlib.h>
28 #include <string.h>
29
30 static inline void flush_bits(struct output_bitstream *ostream)
31 {
32         *(u16*)ostream->bit_output = cpu_to_le16(ostream->bitbuf);
33         ostream->bit_output = ostream->next_bit_output;
34         ostream->next_bit_output = ostream->output;
35         ostream->output += 2;
36         ostream->num_bytes_remaining -= 2;
37 }
38
39 /* Writes @num_bits bits, given by the @num_bits least significant bits of
40  * @bits, to the output @ostream. */
41 int bitstream_put_bits(struct output_bitstream *ostream, output_bitbuf_t bits, 
42                        uint num_bits)
43 {
44         uint rem_bits;
45
46         wimlib_assert(num_bits <= 16);
47         if (num_bits <= ostream->free_bits) {
48                 ostream->bitbuf = (ostream->bitbuf << num_bits) | bits;
49                 ostream->free_bits -= num_bits;
50         } else {
51
52                 if (ostream->num_bytes_remaining + (ostream->output - 
53                                                 ostream->bit_output) < 2)
54                         return 1;
55
56                 /* It is tricky to output the bits correctly.  The correct way
57                  * is to output little-endian 2-byte words, such that the bits
58                  * in the SECOND byte logically precede those in the FIRST byte.
59                  * While the byte order is little-endian, the bit order is
60                  * big-endian; the first bit in a byte is the high-order one.
61                  * Any multi-bit numbers are in bit-big-endian form, so the
62                  * low-order bit of a multi-bit number is the LAST bit to be
63                  * output. */
64                 rem_bits = num_bits - ostream->free_bits;
65                 ostream->bitbuf <<= ostream->free_bits;
66                 ostream->bitbuf |= bits >> rem_bits;
67                 flush_bits(ostream);
68                 ostream->free_bits = 16 - rem_bits;
69                 ostream->bitbuf = bits;
70
71         }
72         return 0;
73 }
74
75 /* Flushes any remaining bits in the output buffer to the output byte stream. */
76 int flush_output_bitstream(struct output_bitstream *ostream)
77 {
78         if (ostream->num_bytes_remaining + (ostream->output - 
79                                         ostream->bit_output) < 2)
80                 return 1;
81         if (ostream->free_bits != 16) {
82                 ostream->bitbuf <<= ostream->free_bits;
83                 flush_bits(ostream);
84         }
85         return 0;
86 }
87
88 /* Initializes an output bit buffer to write its output to the memory location
89  * pointer to by @data. */
90 void init_output_bitstream(struct output_bitstream *ostream, void *data, 
91                            uint num_bytes)
92 {
93         ostream->bitbuf              = 0;
94         ostream->free_bits           = 16;
95         ostream->bit_output          = (u8*)data;
96         ostream->next_bit_output     = (u8*)data + 2;
97         ostream->output              = (u8*)data + 4;
98         ostream->num_bytes_remaining = num_bytes - 4;
99 }
100
101 /* Intermediate (non-leaf) node in a Huffman tree. */
102 typedef struct HuffmanNode {
103         u32 freq;
104         u16 sym;
105         union {
106                 u16 path_len;
107                 u16 height;
108         };
109         struct HuffmanNode *left_child;
110         struct HuffmanNode *right_child;
111 } HuffmanNode;
112
113 /* Leaf node in a Huffman tree.  The fields are in the same order as the
114  * HuffmanNode, so it can be cast to a HuffmanNode.  There are no pointers to
115  * the children in the leaf node. */
116 typedef struct {
117         u32 freq;
118         u16 sym;
119         union {
120                 u16 path_len;
121                 u16 height;
122         };
123 } HuffmanLeafNode;
124
125 /* Comparator function for HuffmanLeafNodes.  Sorts primarily by symbol
126  * frequency and secondarily by symbol value. */
127 static int cmp_leaves_by_freq(const void *__leaf1, const void *__leaf2)
128 {
129         const HuffmanLeafNode *leaf1 = __leaf1;
130         const HuffmanLeafNode *leaf2 = __leaf2;
131
132         int freq_diff = (int)leaf1->freq - (int)leaf2->freq;
133
134         if (freq_diff == 0)
135                 return (int)leaf1->sym - (int)leaf2->sym;
136         else
137                 return freq_diff;
138 }
139
140 /* Comparator function for HuffmanLeafNodes.  Sorts primarily by code length and
141  * secondarily by symbol value. */
142 static int cmp_leaves_by_code_len(const void *__leaf1, const void *__leaf2)
143 {
144         const HuffmanLeafNode *leaf1 = __leaf1;
145         const HuffmanLeafNode *leaf2 = __leaf2;
146
147         int code_len_diff = (int)leaf1->path_len - (int)leaf2->path_len;
148
149         if (code_len_diff == 0)
150                 return (int)leaf1->sym - (int)leaf2->sym;
151         else
152                 return code_len_diff;
153 }
154
155 /* Recursive function to calculate the depth of the leaves in a Huffman tree.
156  * */
157 static void huffman_tree_compute_path_lengths(HuffmanNode *node, u16 cur_len)
158 {
159         if (node->sym == (u16)(-1)) {
160                 /* Intermediate node. */
161                 huffman_tree_compute_path_lengths(node->left_child, cur_len + 1);
162                 huffman_tree_compute_path_lengths(node->right_child, cur_len + 1);
163         } else {
164                 /* Leaf node. */
165                 node->path_len = cur_len;
166         }
167 }
168
169 /* Creates a canonical Huffman code from an array of symbol frequencies. 
170  *
171  * The algorithm used is similar to the well-known algorithm that builds a
172  * Huffman tree using a minheap.  In that algorithm, the leaf nodes are
173  * initialized and inserted into the minheap with the frequency as the key.
174  * Repeatedly, the top two nodes (nodes with the lowest frequency) are taken out
175  * of the heap and made the children of a new node that has a frequency equal to
176  * the sum of the two frequencies of its children.  This new node is inserted
177  * into the heap.  When all the nodes have been removed from the heap, what
178  * remains is the Huffman tree. The Huffman code for a symbol is given by the
179  * path to it in the tree, where each left pointer is mapped to a 0 bit and each
180  * right pointer is mapped to a 1 bit.
181  *
182  * The algorithm used here uses an optimization that removes the need to
183  * actually use a heap.  The leaf nodes are first sorted by frequency, as
184  * opposed to being made into a heap.  Note that this sorting step takes O(n log
185  * n) time vs.  O(n) time for heapifying the array, where n is the number of
186  * symbols.  However, the heapless method is probably faster overall, due to the
187  * time saved later.  In the heapless method, whenever an intermediate node is
188  * created, it is not inserted into the sorted array.  Instead, the intermediate
189  * nodes are kept in a separate array, which is easily kept sorted because every
190  * time an intermediate node is initialized, it will have a frequency at least
191  * as high as that of the previous intermediate node that was initialized.  So
192  * whenever we want the 2 nodes, leaf or intermediate, that have the lowest
193  * frequency, we check the low-frequency ends of both arrays, which is an O(1)
194  * operation.
195  *
196  * The function builds a canonical Huffman code, not just any Huffman code.  A
197  * Huffman code is canonical if the codeword for each symbol numerically
198  * precedes the codeword for all other symbols of the same length that are
199  * numbered higher than the symbol, and additionally, all shorter codewords,
200  * 0-extended, numerically precede longer codewords.  A canonical Huffman code
201  * is useful because it can be reconstructed by only knowing the path lengths in
202  * the tree.  See the make_huffman_decode_table() function to see how to
203  * reconstruct a canonical Huffman code from only the lengths of the codes.
204  *
205  * @num_syms:  The number of symbols in the alphabet.
206  *
207  * @max_codeword_len:  The maximum allowed length of a codeword in the code.
208  *                      Note that if the code being created runs up against
209  *                      this restriction, the code ultimately created will be
210  *                      suboptimal, although there are some advantages for
211  *                      limiting the length of the codewords.
212  *
213  * @freq_tab:  An array of length @num_syms that contains the frequencies
214  *                      of each symbol in the uncompressed data.
215  *
216  * @lens:          An array of length @num_syms into which the lengths of the
217  *                      codewords for each symbol will be written.
218  *
219  * @codewords:     An array of @num_syms short integers into which the
220  *                      codewords for each symbol will be written.  The first 
221  *                      lens[i] bits of codewords[i] will contain the codeword 
222  *                      for symbol i.
223  */
224 void make_canonical_huffman_code(uint num_syms, uint max_codeword_len, 
225                                  const u32 freq_tab[], u8 lens[], 
226                                  u16 codewords[])
227 {
228         /* We require at least 2 possible symbols in the alphabet to produce a
229          * valid Huffman decoding table. It is allowed that fewer than 2 symbols
230          * are actually used, though. */
231         wimlib_assert(num_syms >= 2);
232
233         /* Initialize the lengths and codewords to 0 */
234         memset(lens, 0, num_syms * sizeof(lens[0]));
235         memset(codewords, 0, num_syms * sizeof(codewords[0]));
236
237         /* Calculate how many symbols have non-zero frequency.  These are the
238          * symbols that actually appeared in the input. */
239         uint num_used_symbols = 0;
240         for (uint i = 0; i < num_syms; i++)
241                 if (freq_tab[i] != 0)
242                         num_used_symbols++;
243
244
245         /* It is impossible to make a code for num_used_symbols symbols if there
246          * aren't enough code bits to uniquely represent all of them. */
247         wimlib_assert((1 << max_codeword_len) > num_used_symbols);
248
249         /* Initialize the array of leaf nodes with the symbols and their
250          * frequencies. */
251         HuffmanLeafNode leaves[num_used_symbols];
252         uint leaf_idx = 0;
253         for (uint i = 0; i < num_syms; i++) {
254                 if (freq_tab[i] != 0) {
255                         leaves[leaf_idx].freq = freq_tab[i];
256                         leaves[leaf_idx].sym  = i;
257                         leaves[leaf_idx].height = 0;
258                         leaf_idx++;
259                 }
260         }
261
262         /* Deal with the special cases where num_used_symbols < 2. */
263         if (num_used_symbols < 2) {
264                 if (num_used_symbols == 0) {
265                         /* If num_used_symbols is 0, there are no symbols in the
266                          * input, so it must be empty.  This should be an error,
267                          * but the LZX format expects this case to succeed.  All
268                          * the codeword lengths are simply marked as 0 (which
269                          * was already done.) */
270                 } else {
271                         /* If only one symbol is present, the LZX format
272                          * requires that the Huffman code include two codewords.
273                          * One is not used.  Note that this doesn't make the
274                          * encoded data take up more room anyway, since binary
275                          * data itself has 2 symbols. */
276
277                         uint sym = leaves[0].sym;
278
279                         codewords[0] = 0;
280                         lens[0]      = 1;
281                         if (sym == 0) {
282                                 /* dummy symbol is 1, real symbol is 0 */
283                                 codewords[1] = 1;
284                                 lens[1]      = 1;
285                         } else {
286                                 /* dummy symbol is 0, real symbol is sym */
287                                 codewords[sym] = 1;
288                                 lens[sym]      = 1;
289                         }
290                 }
291                 return;
292         }
293
294         /* Otherwise, there are at least 2 symbols in the input, so we need to
295          * find a real Huffman code. */
296
297
298         /* Declare the array of intermediate nodes.  An intermediate node is not
299          * associated with a symbol. Instead, it represents some binary code
300          * prefix that is shared between at least 2 codewords.  There can be at
301          * most num_used_symbols - 1 intermediate nodes when creating a Huffman
302          * code.  This is because if there were at least num_used_symbols nodes,
303          * the code would be suboptimal because there would be at least one
304          * unnecessary intermediate node.  
305          *
306          * The worst case (greatest number of intermediate nodes) would be if
307          * all the intermediate nodes were chained together.  This results in
308          * num_used_symbols - 1 intermediate nodes.  If num_used_symbols is at
309          * least 17, this configuration would not be allowed because the LZX
310          * format constrains codes to 16 bits or less each.  However, it is
311          * still possible for there to be more than 16 intermediate nodes, as
312          * long as no leaf has a depth of more than 16.  */
313         HuffmanNode inodes[num_used_symbols - 1];
314
315
316         /* Pointer to the leaf node of lowest frequency that hasn't already been
317          * added as the child of some intermediate note. */
318         HuffmanLeafNode *cur_leaf = &leaves[0];
319
320         /* Pointer past the end of the array of leaves. */
321         HuffmanLeafNode *end_leaf = &leaves[num_used_symbols];
322
323         /* Pointer to the intermediate node of lowest frequency. */
324         HuffmanNode     *cur_inode = &inodes[0];
325
326         /* Pointer to the next unallocated intermediate node. */
327         HuffmanNode     *next_inode = &inodes[0];
328
329         /* Only jump back to here if the maximum length of the codewords allowed
330          * by the LZX format (16 bits) is exceeded. */
331 try_building_tree_again:
332
333         /* Sort the leaves from those that correspond to the least frequent
334          * symbol, to those that correspond to the most frequent symbol.  If two
335          * leaves have the same frequency, they are sorted by symbol. */
336         qsort(leaves, num_used_symbols, sizeof(leaves[0]), cmp_leaves_by_freq);
337
338         cur_leaf   = &leaves[0];
339         cur_inode  = &inodes[0];
340         next_inode = &inodes[0];
341
342         /* The following loop takes the two lowest frequency nodes of those
343          * remaining and makes them the children of the next available
344          * intermediate node.  It continues until all the leaf nodes and
345          * intermediate nodes have been used up, or the maximum allowed length
346          * for the codewords is exceeded.  For the latter case, we must adjust
347          * the frequencies to be more equal and then execute this loop again. */
348         while (1) {
349
350                 /* Lowest frequency node. */
351                 HuffmanNode *f1 = NULL; 
352
353                 /* Second lowest frequency node. */
354                 HuffmanNode *f2 = NULL;
355
356                 /* Get the lowest and second lowest frequency nodes from
357                  * the remaining leaves or from the intermediate nodes.
358                  * */
359
360                 if (cur_leaf != end_leaf && (cur_inode == next_inode || 
361                                         cur_leaf->freq <= cur_inode->freq)) {
362                         f1 = (HuffmanNode*)cur_leaf++;
363                 } else if (cur_inode != next_inode) {
364                         f1 = cur_inode++;
365                 }
366
367                 if (cur_leaf != end_leaf && (cur_inode == next_inode || 
368                                         cur_leaf->freq <= cur_inode->freq)) {
369                         f2 = (HuffmanNode*)cur_leaf++;
370                 } else if (cur_inode != next_inode) {
371                         f2 = cur_inode++;
372                 }
373
374                 /* All nodes used up! */
375                 if (f1 == NULL || f2 == NULL)
376                         break;
377
378                 /* next_inode becomes the parent of f1 and f2. */
379
380                 next_inode->freq   = f1->freq + f2->freq;
381                 next_inode->sym    = (u16)(-1); /* Invalid symbol. */
382                 next_inode->left_child   = f1;
383                 next_inode->right_child  = f2;
384
385                 /* We need to keep track of the height so that we can detect if
386                  * the length of a codeword has execeed max_codeword_len.   The
387                  * parent node has a height one higher than the maximum height
388                  * of its children. */
389                 next_inode->height = max(f1->height, f2->height) + 1;
390
391                 /* Check to see if the code length of the leaf farthest away
392                  * from next_inode has exceeded the maximum code length. */
393                 if (next_inode->height > max_codeword_len) {
394                         /* The code lengths can be made more uniform by making
395                          * the frequencies more uniform.  Divide all the
396                          * frequencies by 2, leaving 1 as the minimum frequency.
397                          * If this keeps happening, the symbol frequencies will
398                          * approach equality, which makes their Huffman
399                          * codewords approach the length
400                          * log_2(num_used_symbols).
401                          * */
402                         for (uint i = 0; i < num_used_symbols; i++)
403                                 if (leaves[i].freq > 1)
404                                         leaves[i].freq >>= 1;
405                         goto try_building_tree_again;
406                 } 
407                 next_inode++;
408         }
409
410         /* The Huffman tree is now complete, and its height is no more than
411          * max_codeword_len.  */
412
413         HuffmanNode *root = next_inode - 1;
414         wimlib_assert(root->height <= max_codeword_len);
415
416         /* Compute the path lengths for the leaf nodes. */
417         huffman_tree_compute_path_lengths(root, 0);
418
419         /* Sort the leaf nodes primarily by code length and secondarily by
420          * symbol.  */
421         qsort(leaves, num_used_symbols, sizeof(leaves[0]), cmp_leaves_by_code_len);
422
423         u16 cur_codeword = 0;
424         uint cur_codeword_len = 0;
425         for (uint i = 0; i < num_used_symbols; i++) {
426
427                 /* Each time a codeword becomes one longer, the current codeword
428                  * is left shifted by one place.  This is part of the procedure
429                  * for enumerating the canonical Huffman code.  Additionally,
430                  * whenever a codeword is used, 1 is added to the current
431                  * codeword.  */
432
433                 uint len_diff = leaves[i].path_len - cur_codeword_len;
434                 cur_codeword <<= len_diff;
435                 cur_codeword_len += len_diff;
436
437                 u16 sym = leaves[i].sym;
438                 codewords[sym] = cur_codeword;
439                 lens[sym] = cur_codeword_len;
440
441                 cur_codeword++;
442         }
443 }