]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
unix_capture.c: Include <limits.h> for PATH_MAX
[wimlib] / src / lzx-compress.c
1 /*
2  * lzx-compress.c
3  *
4  * LZX compression routines, originally based on code written by Matthew T.
5  * Russotto (liblzxcomp), but heavily modified.
6  */
7
8 /*
9  * Copyright (C) 2002 Matthew T. Russotto
10  * Copyright (C) 2012, 2013 Eric Biggers
11  *
12  * This file is part of wimlib, a library for working with WIM files.
13  *
14  * wimlib is free software; you can redistribute it and/or modify it under the
15  * terms of the GNU General Public License as published by the Free
16  * Software Foundation; either version 3 of the License, or (at your option)
17  * any later version.
18  *
19  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
20  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21  * A PARTICULAR PURPOSE. See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with wimlib; if not, see http://www.gnu.org/licenses/.
26  */
27
28
29 /*
30  * This file provides wimlib_lzx_compress(), a function to compress an in-memory
31  * buffer of data using LZX compression, as used in the WIM file format.
32  *
33  * Please see the comments in lzx-decompress.c for more information about this
34  * compression format.
35  *
36  * One thing to keep in mind is that there is no sliding window, since the
37  * window is always the entirety of a WIM chunk, which is at most WIM_CHUNK_SIZE
38  * ( = 32768) bytes.
39  *
40  * The basic compression algorithm used here should be familiar if you are
41  * familiar with Huffman trees and with other LZ77 and Huffman-based formats
42  * such as DEFLATE.  Otherwise it can be quite tricky to understand.  Basically
43  * it is the following:
44  *
45  * - Preprocess the input data (LZX-specific)
46  * - Go through the input data and determine matches.  This part is based on
47  *       code from zlib, and a hash table of 3-character strings is used to
48  *       accelerate the process of finding matches.
49  * - Build the Huffman trees based on the frequencies of symbols determined
50  *       while recording matches.
51  * - Output the block header, including the Huffman trees; then output the
52  *       compressed stream of matches and literal characters.
53  *
54  * It is possible for a WIM chunk to include multiple LZX blocks, since for some
55  * input data this will produce a better compression ratio (especially since
56  * each block can include new Huffman codes).  However, producing multiple LZX
57  * blocks from one input chunk is not yet implemented.
58  */
59
60 #include "wimlib.h"
61 #include "lzx.h"
62 #include "compress.h"
63 #include <stdlib.h>
64 #include <string.h>
65
66
67 /* Structure to contain the Huffman codes for the main, length, and aligned
68  * offset trees. */
69 struct lzx_codes {
70         u16 main_codewords[LZX_MAINTREE_NUM_SYMBOLS];
71         u8  main_lens[LZX_MAINTREE_NUM_SYMBOLS];
72
73         u16 len_codewords[LZX_LENTREE_NUM_SYMBOLS];
74         u8  len_lens[LZX_LENTREE_NUM_SYMBOLS];
75
76         u16 aligned_codewords[LZX_ALIGNEDTREE_NUM_SYMBOLS];
77         u8  aligned_lens[LZX_ALIGNEDTREE_NUM_SYMBOLS];
78 };
79
80 struct lzx_freq_tables {
81         freq_t main_freq_table[LZX_MAINTREE_NUM_SYMBOLS];
82         freq_t len_freq_table[LZX_LENTREE_NUM_SYMBOLS];
83         freq_t aligned_freq_table[LZX_ALIGNEDTREE_NUM_SYMBOLS];
84 };
85
86 /* Returns the LZX position slot that corresponds to a given formatted offset.
87  *
88  * Logically, this returns the smallest i such that
89  * formatted_offset >= lzx_position_base[i].
90  *
91  * The actual implementation below takes advantage of the regularity of the
92  * numbers in the lzx_position_base array to calculate the slot directly from
93  * the formatted offset without actually looking at the array.
94  */
95 static inline unsigned
96 lzx_get_position_slot(unsigned formatted_offset)
97 {
98 #if 0
99         /*
100          * Slots 36-49 (formatted_offset >= 262144) can be found by
101          * (formatted_offset/131072) + 34 == (formatted_offset >> 17) + 34;
102          * however, this check for formatted_offset >= 262144 is commented out
103          * because WIM chunks cannot be that large.
104          */
105         if (formatted_offset >= 262144) {
106                 return (formatted_offset >> 17) + 34;
107         } else
108 #endif
109         {
110                 /* Note: this part here only works if:
111                  *
112                  *    2 <= formatted_offset < 655360
113                  *
114                  * It is < 655360 because the frequency of the position bases
115                  * increases starting at the 655360 entry, and it is >= 2
116                  * because the below calculation fails if the most significant
117                  * bit is lower than the 2's place. */
118                 wimlib_assert(formatted_offset >= 2 && formatted_offset < 655360);
119                 unsigned mssb_idx = bsr32(formatted_offset);
120                 return (mssb_idx << 1) |
121                         ((formatted_offset >> (mssb_idx - 1)) & 1);
122         }
123 }
124
125 static u32
126 lzx_record_literal(u8 literal, void *__main_freq_tab)
127 {
128         freq_t *main_freq_tab = __main_freq_tab;
129         main_freq_tab[literal]++;
130         return literal;
131 }
132
133 /* Constructs a match from an offset and a length, and updates the LRU queue and
134  * the frequency of symbols in the main, length, and aligned offset alphabets.
135  * The return value is a 32-bit number that provides the match in an
136  * intermediate representation documented below. */
137 static u32
138 lzx_record_match(unsigned match_offset, unsigned match_len,
139                  void *__freq_tabs, void *__queue)
140 {
141         struct lzx_freq_tables *freq_tabs = __freq_tabs;
142         struct lru_queue *queue = __queue;
143         unsigned position_slot;
144         unsigned position_footer = 0;
145         u32 match;
146         u32 len_header;
147         u32 len_pos_header;
148         unsigned len_footer;
149         unsigned adjusted_match_len;
150
151         wimlib_assert(match_len >= LZX_MIN_MATCH && match_len <= LZX_MAX_MATCH);
152         wimlib_assert(match_offset != 0);
153
154         /* If possible, encode this offset as a repeated offset. */
155         if (match_offset == queue->R0) {
156                 position_slot = 0;
157         } else if (match_offset == queue->R1) {
158                 swap(queue->R0, queue->R1);
159                 position_slot = 1;
160         } else if (match_offset == queue->R2) {
161                 swap(queue->R0, queue->R2);
162                 position_slot = 2;
163         } else {
164                 /* Not a repeated offset. */
165
166                 /* offsets of 0, 1, and 2 are reserved for the repeated offset
167                  * codes, so non-repeated offsets must be encoded as 3+.  The
168                  * minimum offset is 1, so encode the offsets offset by 2. */
169                 unsigned formatted_offset = match_offset + LZX_MIN_MATCH;
170
171                 queue->R2 = queue->R1;
172                 queue->R1 = queue->R0;
173                 queue->R0 = match_offset;
174
175                 /* The (now-formatted) offset will actually be encoded as a
176                  * small position slot number that maps to a certain hard-coded
177                  * offset (position base), followed by a number of extra bits---
178                  * the position footer--- that are added to the position base to
179                  * get the original formatted offset. */
180
181                 position_slot = lzx_get_position_slot(formatted_offset);
182                 position_footer = formatted_offset &
183                                   ((1 << lzx_get_num_extra_bits(position_slot)) - 1);
184         }
185
186         adjusted_match_len = match_len - LZX_MIN_MATCH;
187
188         /* Pack the position slot, position footer, and match length into an
189          * intermediate representation.
190          *
191          * bits    description
192          * ----    -----------------------------------------------------------
193          *
194          * 31      1 if a match, 0 if a literal.
195          *
196          * 30-25   position slot.  This can be at most 50, so it will fit in 6
197          *         bits.
198          *
199          * 8-24    position footer.  This is the offset of the real formatted
200          *         offset from the position base.  This can be at most 17 bits
201          *         (since lzx_extra_bits[LZX_NUM_POSITION_SLOTS - 1] is 17).
202          *
203          * 0-7     length of match, offset by 2.  This can be at most
204          *         (LZX_MAX_MATCH - 2) == 255, so it will fit in 8 bits.  */
205         match = 0x80000000 |
206                 (position_slot << 25) |
207                 (position_footer << 8) |
208                 (adjusted_match_len);
209
210         /* The match length must be at least 2, so let the adjusted match length
211          * be the match length minus 2.
212          *
213          * If it is less than 7, the adjusted match length is encoded as a 3-bit
214          * number offset by 2.  Otherwise, the 3-bit length header is all 1's
215          * and the actual adjusted length is given as a symbol encoded with the
216          * length tree, offset by 7.
217          */
218         if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
219                 len_header = adjusted_match_len;
220         } else {
221                 len_header = LZX_NUM_PRIMARY_LENS;
222                 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
223                 freq_tabs->len_freq_table[len_footer]++;
224         }
225         len_pos_header = (position_slot << 3) | len_header;
226
227         wimlib_assert(len_pos_header < LZX_MAINTREE_NUM_SYMBOLS - LZX_NUM_CHARS);
228
229         freq_tabs->main_freq_table[len_pos_header + LZX_NUM_CHARS]++;
230
231         /* Equivalent to:
232          * if (lzx_extra_bits[position_slot] >= 3) */
233         if (position_slot >= 8)
234                 freq_tabs->aligned_freq_table[position_footer & 7]++;
235
236         return match;
237 }
238
239 /*
240  * Writes a compressed literal match to the output.
241  *
242  * @out:         The output bitstream.
243  * @block_type:  The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
244  * @match:       The match, encoded as a 32-bit number.
245  * @codes:      Pointer to a structure that contains the codewords for the
246  *                      main, length, and aligned offset Huffman codes.
247  */
248 static int
249 lzx_write_match(struct output_bitstream *out, int block_type,
250                 u32 match, const struct lzx_codes *codes)
251 {
252         /* low 8 bits are the match length minus 2 */
253         unsigned match_len_minus_2 = match & 0xff;
254         /* Next 17 bits are the position footer */
255         unsigned position_footer = (match >> 8) & 0x1ffff;      /* 17 bits */
256         /* Next 6 bits are the position slot. */
257         unsigned position_slot = (match >> 25) & 0x3f;  /* 6 bits */
258         unsigned len_header;
259         unsigned len_footer;
260         unsigned len_pos_header;
261         unsigned main_symbol;
262         unsigned num_extra_bits;
263         unsigned verbatim_bits;
264         unsigned aligned_bits;
265         int ret;
266
267         /* If the match length is less than MIN_MATCH (= 2) +
268          * NUM_PRIMARY_LENS (= 7), the length header contains
269          * the match length minus MIN_MATCH, and there is no
270          * length footer.
271          *
272          * Otherwise, the length header contains
273          * NUM_PRIMARY_LENS, and the length footer contains
274          * the match length minus NUM_PRIMARY_LENS minus
275          * MIN_MATCH. */
276         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
277                 len_header = match_len_minus_2;
278                 /* No length footer-- mark it with a special
279                  * value. */
280                 len_footer = (unsigned)(-1);
281         } else {
282                 len_header = LZX_NUM_PRIMARY_LENS;
283                 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
284         }
285
286         /* Combine the position slot with the length header into
287          * a single symbol that will be encoded with the main
288          * tree. */
289         len_pos_header = (position_slot << 3) | len_header;
290
291         /* The actual main symbol is offset by LZX_NUM_CHARS because
292          * values under LZX_NUM_CHARS are used to indicate a literal
293          * byte rather than a match. */
294         main_symbol = len_pos_header + LZX_NUM_CHARS;
295
296         /* Output main symbol. */
297         ret = bitstream_put_bits(out, codes->main_codewords[main_symbol],
298                                  codes->main_lens[main_symbol]);
299         if (ret != 0)
300                 return ret;
301
302         /* If there is a length footer, output it using the
303          * length Huffman code. */
304         if (len_footer != (unsigned)(-1)) {
305                 ret = bitstream_put_bits(out, codes->len_codewords[len_footer],
306                                          codes->len_lens[len_footer]);
307                 if (ret != 0)
308                         return ret;
309         }
310
311         wimlib_assert(position_slot < LZX_NUM_POSITION_SLOTS);
312
313         num_extra_bits = lzx_get_num_extra_bits(position_slot);
314
315         /* For aligned offset blocks with at least 3 extra bits, output the
316          * verbatim bits literally, then the aligned bits encoded using the
317          * aligned offset tree.  Otherwise, only the verbatim bits need to be
318          * output. */
319         if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
320
321                 verbatim_bits = position_footer >> 3;
322                 ret = bitstream_put_bits(out, verbatim_bits,
323                                          num_extra_bits - 3);
324                 if (ret != 0)
325                         return ret;
326
327                 aligned_bits = (position_footer & 7);
328                 ret = bitstream_put_bits(out,
329                                          codes->aligned_codewords[aligned_bits],
330                                          codes->aligned_lens[aligned_bits]);
331                 if (ret != 0)
332                         return ret;
333         } else {
334                 /* verbatim bits is the same as the position
335                  * footer, in this case. */
336                 ret = bitstream_put_bits(out, position_footer, num_extra_bits);
337                 if (ret != 0)
338                         return ret;
339         }
340         return 0;
341 }
342
343 /*
344  * Writes all compressed literals in a block, both matches and literal bytes, to
345  * the output bitstream.
346  *
347  * @out:         The output bitstream.
348  * @block_type:  The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
349  * @match_tab[]:   The array of matches that will be output.  It has length
350  *                      of @num_compressed_literals.
351  * @num_compressed_literals:  Number of compressed literals to be output.
352  * @codes:      Pointer to a structure that contains the codewords for the
353  *                      main, length, and aligned offset Huffman codes.
354  */
355 static int
356 lzx_write_compressed_literals(struct output_bitstream *ostream,
357                               int block_type,
358                               const u32 match_tab[],
359                               unsigned  num_compressed_literals,
360                               const struct lzx_codes *codes)
361 {
362         unsigned i;
363         u32 match;
364         int ret;
365
366         for (i = 0; i < num_compressed_literals; i++) {
367                 match = match_tab[i];
368
369                 /* High bit of the match indicates whether the match is an
370                  * actual match (1) or a literal uncompressed byte (0) */
371                 if (match & 0x80000000) {
372                         /* match */
373                         ret = lzx_write_match(ostream, block_type, match,
374                                               codes);
375                         if (ret != 0)
376                                 return ret;
377                 } else {
378                         /* literal byte */
379                         wimlib_assert(match < LZX_NUM_CHARS);
380                         ret = bitstream_put_bits(ostream,
381                                                  codes->main_codewords[match],
382                                                  codes->main_lens[match]);
383                         if (ret != 0)
384                                 return ret;
385                 }
386         }
387         return 0;
388 }
389
390 /*
391  * Writes a compressed Huffman tree to the output, preceded by the pretree for
392  * it.
393  *
394  * The Huffman tree is represented in the output as a series of path lengths
395  * from which the canonical Huffman code can be reconstructed.  The path lengths
396  * themselves are compressed using a separate Huffman code, the pretree, which
397  * consists of LZX_PRETREE_NUM_SYMBOLS (= 20) symbols that cover all possible code
398  * lengths, plus extra codes for repeated lengths.  The path lengths of the
399  * pretree precede the path lengths of the larger code and are uncompressed,
400  * consisting of 20 entries of 4 bits each.
401  *
402  * @out:        The bitstream for the compressed output.
403  * @lens:       The code lengths for the Huffman tree, indexed by symbol.
404  * @num_symbols:        The number of symbols in the code.
405  */
406 static int
407 lzx_write_compressed_tree(struct output_bitstream *out,
408                           const u8 lens[], unsigned num_symbols)
409 {
410         /* Frequencies of the length symbols, including the RLE symbols (NOT the
411          * actual lengths themselves). */
412         freq_t pretree_freqs[LZX_PRETREE_NUM_SYMBOLS];
413         u8 pretree_lens[LZX_PRETREE_NUM_SYMBOLS];
414         u16 pretree_codewords[LZX_PRETREE_NUM_SYMBOLS];
415         u8 output_syms[num_symbols * 2];
416         unsigned output_syms_idx;
417         unsigned cur_run_len;
418         unsigned i;
419         unsigned len_in_run;
420         unsigned additional_bits;
421         char delta;
422         u8 pretree_sym;
423
424         ZERO_ARRAY(pretree_freqs);
425
426         /* Since the code word lengths use a form of RLE encoding, the goal here
427          * is to find each run of identical lengths when going through them in
428          * symbol order (including runs of length 1).  For each run, as many
429          * lengths are encoded using RLE as possible, and the rest are output
430          * literally.
431          *
432          * output_syms[] will be filled in with the length symbols that will be
433          * output, including RLE codes, not yet encoded using the pre-tree.
434          *
435          * cur_run_len keeps track of how many code word lengths are in the
436          * current run of identical lengths.
437          */
438         output_syms_idx = 0;
439         cur_run_len = 1;
440         for (i = 1; i <= num_symbols; i++) {
441
442                 if (i != num_symbols && lens[i] == lens[i - 1]) {
443                         /* Still in a run--- keep going. */
444                         cur_run_len++;
445                         continue;
446                 }
447
448                 /* Run ended! Check if it is a run of zeroes or a run of
449                  * nonzeroes. */
450
451                 /* The symbol that was repeated in the run--- not to be confused
452                  * with the length *of* the run (cur_run_len) */
453                 len_in_run = lens[i - 1];
454
455                 if (len_in_run == 0) {
456                         /* A run of 0's.  Encode it in as few length
457                          * codes as we can. */
458
459                         /* The magic length 18 indicates a run of 20 + n zeroes,
460                          * where n is an uncompressed literal 5-bit integer that
461                          * follows the magic length. */
462                         while (cur_run_len >= 20) {
463
464                                 additional_bits = min(cur_run_len - 20, 0x1f);
465                                 pretree_freqs[18]++;
466                                 output_syms[output_syms_idx++] = 18;
467                                 output_syms[output_syms_idx++] = additional_bits;
468                                 cur_run_len -= 20 + additional_bits;
469                         }
470
471                         /* The magic length 17 indicates a run of 4 + n zeroes,
472                          * where n is an uncompressed literal 4-bit integer that
473                          * follows the magic length. */
474                         while (cur_run_len >= 4) {
475                                 additional_bits = min(cur_run_len - 4, 0xf);
476                                 pretree_freqs[17]++;
477                                 output_syms[output_syms_idx++] = 17;
478                                 output_syms[output_syms_idx++] = additional_bits;
479                                 cur_run_len -= 4 + additional_bits;
480                         }
481
482                 } else {
483
484                         /* A run of nonzero lengths. */
485
486                         /* The magic length 19 indicates a run of 4 + n
487                          * nonzeroes, where n is a literal bit that follows the
488                          * magic length, and where the value of the lengths in
489                          * the run is given by an extra length symbol, encoded
490                          * with the pretree, that follows the literal bit.
491                          *
492                          * The extra length symbol is encoded as a difference
493                          * from the length of the codeword for the first symbol
494                          * in the run in the previous tree.
495                          * */
496                         while (cur_run_len >= 4) {
497                                 additional_bits = (cur_run_len > 4);
498                                 delta = -(char)len_in_run;
499                                 if (delta < 0)
500                                         delta += 17;
501                                 pretree_freqs[19]++;
502                                 pretree_freqs[(unsigned char)delta]++;
503                                 output_syms[output_syms_idx++] = 19;
504                                 output_syms[output_syms_idx++] = additional_bits;
505                                 output_syms[output_syms_idx++] = delta;
506                                 cur_run_len -= 4 + additional_bits;
507                         }
508                 }
509
510                 /* Any remaining lengths in the run are outputted without RLE,
511                  * as a difference from the length of that codeword in the
512                  * previous tree. */
513                 while (cur_run_len--) {
514                         delta = -(char)len_in_run;
515                         if (delta < 0)
516                                 delta += 17;
517
518                         pretree_freqs[(unsigned char)delta]++;
519                         output_syms[output_syms_idx++] = delta;
520                 }
521
522                 cur_run_len = 1;
523         }
524
525         wimlib_assert(output_syms_idx < ARRAY_LEN(output_syms));
526
527         /* Build the pretree from the frequencies of the length symbols. */
528
529         make_canonical_huffman_code(LZX_PRETREE_NUM_SYMBOLS,
530                                     LZX_MAX_CODEWORD_LEN,
531                                     pretree_freqs, pretree_lens,
532                                     pretree_codewords);
533
534         /* Write the lengths of the pretree codes to the output. */
535         for (i = 0; i < LZX_PRETREE_NUM_SYMBOLS; i++)
536                 bitstream_put_bits(out, pretree_lens[i],
537                                    LZX_PRETREE_ELEMENT_SIZE);
538
539         /* Write the length symbols, encoded with the pretree, to the output. */
540
541         i = 0;
542         while (i < output_syms_idx) {
543                 pretree_sym = output_syms[i++];
544
545                 bitstream_put_bits(out, pretree_codewords[pretree_sym],
546                                    pretree_lens[pretree_sym]);
547                 switch (pretree_sym) {
548                 case 17:
549                         bitstream_put_bits(out, output_syms[i++], 4);
550                         break;
551                 case 18:
552                         bitstream_put_bits(out, output_syms[i++], 5);
553                         break;
554                 case 19:
555                         bitstream_put_bits(out, output_syms[i++], 1);
556                         bitstream_put_bits(out,
557                                            pretree_codewords[output_syms[i]],
558                                            pretree_lens[output_syms[i]]);
559                         i++;
560                         break;
561                 default:
562                         break;
563                 }
564         }
565         return 0;
566 }
567
568 /* Builds the canonical Huffman code for the main tree, the length tree, and the
569  * aligned offset tree. */
570 static void
571 lzx_make_huffman_codes(const struct lzx_freq_tables *freq_tabs,
572                        struct lzx_codes *codes)
573 {
574         make_canonical_huffman_code(LZX_MAINTREE_NUM_SYMBOLS,
575                                         LZX_MAX_CODEWORD_LEN,
576                                         freq_tabs->main_freq_table,
577                                         codes->main_lens,
578                                         codes->main_codewords);
579
580         make_canonical_huffman_code(LZX_LENTREE_NUM_SYMBOLS,
581                                         LZX_MAX_CODEWORD_LEN,
582                                         freq_tabs->len_freq_table,
583                                         codes->len_lens,
584                                         codes->len_codewords);
585
586         make_canonical_huffman_code(LZX_ALIGNEDTREE_NUM_SYMBOLS, 8,
587                                         freq_tabs->aligned_freq_table,
588                                         codes->aligned_lens,
589                                         codes->aligned_codewords);
590 }
591
592 static void
593 do_call_insn_translation(u32 *call_insn_target, int input_pos,
594                          int32_t file_size)
595 {
596         int32_t abs_offset;
597         int32_t rel_offset;
598
599         rel_offset = le32_to_cpu(*call_insn_target);
600         if (rel_offset >= -input_pos && rel_offset < file_size) {
601                 if (rel_offset < file_size - input_pos) {
602                         /* "good translation" */
603                         abs_offset = rel_offset + input_pos;
604                 } else {
605                         /* "compensating translation" */
606                         abs_offset = rel_offset - file_size;
607                 }
608                 *call_insn_target = cpu_to_le32(abs_offset);
609         }
610 }
611
612 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
613  * See the comment above that function for more information. */
614 static void
615 do_call_insn_preprocessing(u8 uncompressed_data[], int uncompressed_data_len)
616 {
617         for (int i = 0; i < uncompressed_data_len - 10; i++) {
618                 if (uncompressed_data[i] == 0xe8) {
619                         do_call_insn_translation((u32*)&uncompressed_data[i + 1],
620                                                  i,
621                                                  LZX_WIM_MAGIC_FILESIZE);
622                         i += 4;
623                 }
624         }
625 }
626
627
628 static const struct lz_params lzx_lz_params = {
629
630          /* LZX_MIN_MATCH == 2, but 2-character matches are rarely useful; the
631           * minimum match for compression is set to 3 instead. */
632         .min_match      = 3,
633
634         .max_match      = LZX_MAX_MATCH,
635         .good_match     = LZX_MAX_MATCH,
636         .nice_match     = LZX_MAX_MATCH,
637         .max_chain_len  = LZX_MAX_MATCH,
638         .max_lazy_match = LZX_MAX_MATCH,
639         .too_far        = 4096,
640 };
641
642 /* Documented in wimlib.h */
643 WIMLIBAPI unsigned
644 wimlib_lzx_compress(const void *__uncompressed_data, unsigned uncompressed_len,
645                     void *compressed_data)
646 {
647         struct output_bitstream ostream;
648         u8 uncompressed_data[uncompressed_len + 8];
649         struct lzx_freq_tables freq_tabs;
650         struct lzx_codes codes;
651         u32 match_tab[uncompressed_len];
652         struct lru_queue queue;
653         unsigned num_matches;
654         unsigned compressed_len;
655         unsigned i;
656         int ret;
657         int block_type = LZX_BLOCKTYPE_ALIGNED;
658
659         wimlib_assert(uncompressed_len <= 32768);
660
661         if (uncompressed_len < 100)
662                 return 0;
663
664         memset(&freq_tabs, 0, sizeof(freq_tabs));
665         queue.R0 = 1;
666         queue.R1 = 1;
667         queue.R2 = 1;
668
669         /* The input data must be preprocessed. To avoid changing the original
670          * input, copy it to a temporary buffer. */
671         memcpy(uncompressed_data, __uncompressed_data, uncompressed_len);
672         memset(uncompressed_data + uncompressed_len, 0, 8);
673
674         /* Before doing any actual compression, do the call instruction (0xe8
675          * byte) translation on the uncompressed data. */
676         do_call_insn_preprocessing(uncompressed_data, uncompressed_len);
677
678         /* Determine the sequence of matches and literals that will be output,
679          * and in the process, keep counts of the number of times each symbol
680          * will be output, so that the Huffman trees can be made. */
681
682         num_matches = lz_analyze_block(uncompressed_data, uncompressed_len,
683                                        match_tab, lzx_record_match,
684                                        lzx_record_literal, &freq_tabs,
685                                        &queue, freq_tabs.main_freq_table,
686                                        &lzx_lz_params);
687
688         lzx_make_huffman_codes(&freq_tabs, &codes);
689
690         /* Initialize the output bitstream. */
691         init_output_bitstream(&ostream, compressed_data, uncompressed_len - 1);
692
693         /* The first three bits tell us what kind of block it is, and are one
694          * of the LZX_BLOCKTYPE_* values.  */
695         bitstream_put_bits(&ostream, block_type, 3);
696
697         /* The next bit indicates whether the block size is the default (32768),
698          * indicated by a 1 bit, or whether the block size is given by the next
699          * 16 bits, indicated by a 0 bit. */
700         if (uncompressed_len == 32768) {
701                 bitstream_put_bits(&ostream, 1, 1);
702         } else {
703                 bitstream_put_bits(&ostream, 0, 1);
704                 bitstream_put_bits(&ostream, uncompressed_len, 16);
705         }
706
707         /* Write out the aligned offset tree. Note that M$ lies and says that
708          * the aligned offset tree comes after the length tree, but that is
709          * wrong; it actually is before the main tree.  */
710         if (block_type == LZX_BLOCKTYPE_ALIGNED)
711                 for (i = 0; i < LZX_ALIGNEDTREE_NUM_SYMBOLS; i++)
712                         bitstream_put_bits(&ostream, codes.aligned_lens[i],
713                                            LZX_ALIGNEDTREE_ELEMENT_SIZE);
714
715         /* Write the pre-tree and lengths for the first LZX_NUM_CHARS symbols in the
716          * main tree. */
717         ret = lzx_write_compressed_tree(&ostream, codes.main_lens,
718                                         LZX_NUM_CHARS);
719         if (ret)
720                 return 0;
721
722         /* Write the pre-tree and symbols for the rest of the main tree. */
723         ret = lzx_write_compressed_tree(&ostream, codes.main_lens +
724                                         LZX_NUM_CHARS,
725                                         LZX_MAINTREE_NUM_SYMBOLS -
726                                                 LZX_NUM_CHARS);
727         if (ret)
728                 return 0;
729
730         /* Write the pre-tree and symbols for the length tree. */
731         ret = lzx_write_compressed_tree(&ostream, codes.len_lens,
732                                         LZX_LENTREE_NUM_SYMBOLS);
733         if (ret)
734                 return 0;
735
736         /* Write the compressed literals. */
737         ret = lzx_write_compressed_literals(&ostream, block_type,
738                                             match_tab, num_matches, &codes);
739         if (ret)
740                 return 0;
741
742         ret = flush_output_bitstream(&ostream);
743         if (ret)
744                 return 0;
745
746         compressed_len = ostream.bit_output - (u8*)compressed_data;
747
748 #ifdef ENABLE_VERIFY_COMPRESSION
749         /* Verify that we really get the same thing back when decompressing. */
750         {
751                 u8 buf[uncompressed_len];
752                 ret = wimlib_lzx_decompress(compressed_data, compressed_len,
753                                             buf, uncompressed_len);
754                 if (ret != 0) {
755                         ERROR("lzx_compress(): Failed to decompress data we compressed");
756                         abort();
757                 }
758
759                 for (i = 0; i < uncompressed_len; i++) {
760                         if (buf[i] != *((u8*)__uncompressed_data + i)) {
761                                 ERROR("lzx_compress(): Data we compressed didn't "
762                                       "decompress to the original data (difference at "
763                                       "byte %u of %u)", i + 1, uncompressed_len);
764                                 abort();
765                         }
766                 }
767         }
768 #endif
769         return compressed_len;
770 }