]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
6b520ae5f05634eb35d3ab3e36a9c97e5edd20fc
[wimlib] / src / lzx-compress.c
1 /*
2  * lzx-compress.c
3  *
4  * LZX compression routines
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
27 /*
28  * This file contains a compressor for the LZX compression format, as used in
29  * the WIM file format.
30  *
31  * Format
32  * ======
33  *
34  * First, the primary reference for the LZX compression format is the
35  * specification released by Microsoft.
36  *
37  * Second, the comments in lzx-decompress.c provide some more information about
38  * the LZX compression format, including errors in the Microsoft specification.
39  *
40  * Do note that LZX shares many similarities with DEFLATE, the algorithm used by
41  * zlib and gzip.  Both LZX and DEFLATE use LZ77 matching and Huffman coding,
42  * and certain other details are quite similar, such as the method for storing
43  * Huffman codes.  However, some of the main differences are:
44  *
45  * - LZX preprocesses the data to attempt to make x86 machine code slightly more
46  *   compressible before attempting to compress it further.
47  * - LZX uses a "main" alphabet which combines literals and matches, with the
48  *   match symbols containing a "length header" (giving all or part of the match
49  *   length) and a "position slot" (giving, roughly speaking, the order of
50  *   magnitude of the match offset).
51  * - LZX does not have static Huffman blocks; however it does have two types of
52  *   dynamic Huffman blocks ("aligned offset" and "verbatim").
53  * - LZX has a minimum match length of 2 rather than 3.
54  * - In LZX, match offsets 0 through 2 actually represent entries in an LRU
55  *   queue of match offsets.  This is very useful for certain types of files,
56  *   such as binary files that have repeating records.
57  *
58  * Algorithms
59  * ==========
60  *
61  * There are actually two distinct overall algorithms implemented here.  We
62  * shall refer to them as the "slow" algorithm and the "fast" algorithm.  The
63  * "slow" algorithm spends more time compressing to achieve a higher compression
64  * ratio compared to the "fast" algorithm.  More details are presented below.
65  *
66  * Slow algorithm
67  * --------------
68  *
69  * The "slow" algorithm to generate LZX-compressed data is roughly as follows:
70  *
71  * 1. Preprocess the input data to translate the targets of x86 call
72  *    instructions to absolute offsets.
73  *
74  * 2. Build the suffix array and inverse suffix array for the input data.  The
75  *    suffix array contains the indices of all suffixes of the input data,
76  *    sorted lexcographically by the corresponding suffixes.  The "position" of
77  *    a suffix is the index of that suffix in the original string, whereas the
78  *    "rank" of a suffix is the index at which that suffix's position is found
79  *    in the suffix array.
80  *
81  * 3. Build the longest common prefix array corresponding to the suffix array.
82  *
83  * 4. For each suffix, find the highest lower ranked suffix that has a lower
84  *    position, the lowest higher ranked suffix that has a lower position, and
85  *    the length of the common prefix shared between each.   This information is
86  *    later used to link suffix ranks into a doubly-linked list for searching
87  *    the suffix array.
88  *
89  * 5. Set a default cost model for matches/literals.
90  *
91  * 6. Determine the lowest cost sequence of LZ77 matches ((offset, length)
92  *    pairs) and literal bytes to divide the input into.  Raw match-finding is
93  *    done by searching the suffix array using a linked list to avoid
94  *    considering any suffixes that start after the current position.  Each run
95  *    of the match-finder returns the approximate lowest-cost longest match as
96  *    well as any shorter matches that have even lower approximate costs.  Each
97  *    such run also adds the suffix rank of the current position into the linked
98  *    list being used to search the suffix array.  Parsing, or match-choosing,
99  *    is solved as a minimum-cost path problem using a forward "optimal parsing"
100  *    algorithm based on the Deflate encoder from 7-Zip.  This algorithm moves
101  *    forward calculating the minimum cost to reach each byte until either a
102  *    very long match is found or until a position is found at which no matches
103  *    start or overlap.
104  *
105  * 7. Build the Huffman codes needed to output the matches/literals.
106  *
107  * 8. Up to a certain number of iterations, use the resulting Huffman codes to
108  *    refine a cost model and go back to Step #6 to determine an improved
109  *    sequence of matches and literals.
110  *
111  * 9. Output the resulting block using the match/literal sequences and the
112  *    Huffman codes that were computed for the block.
113  *
114  * Note: the algorithm does not yet attempt to split the input into multiple LZX
115  * blocks, instead using a series of blocks of LZX_DIV_BLOCK_SIZE bytes.
116  *
117  * Fast algorithm
118  * --------------
119  *
120  * The fast algorithm (and the only one available in wimlib v1.5.1 and earlier)
121  * spends much less time on the main bottlenecks of the compression process ---
122  * that is, the match finding and match choosing.  Matches are found and chosen
123  * with hash chains using a greedy parse with one position of look-ahead.  No
124  * block splitting is done; only compressing the full input into an aligned
125  * offset block is considered.
126  *
127  * Acknowledgments
128  * ===============
129  *
130  * Acknowledgments to several open-source projects and research papers that made
131  * it possible to implement this code:
132  *
133  * - divsufsort (author: Yuta Mori), for the suffix array construction code,
134  *   located in a separate directory (divsufsort/).
135  *
136  * - "Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its
137  *   Applications" (Kasai et al. 2001), for the LCP array computation.
138  *
139  * - "LPF computation revisited" (Crochemore et al. 2009) for the prev and next
140  *   array computations.
141  *
142  * - 7-Zip (author: Igor Pavlov) for the algorithm for forward optimal parsing
143  *   (match-choosing).
144  *
145  * - zlib (author: Jean-loup Gailly and Mark Adler), for the hash table
146  *   match-finding algorithm (used in lz77.c).
147  *
148  * - lzx-compress (author: Matthew T. Russotto), on which some parts of this
149  *   code were originally based.
150  */
151
152 #ifdef HAVE_CONFIG_H
153 #  include "config.h"
154 #endif
155
156 #include "wimlib.h"
157 #include "wimlib/compressor_ops.h"
158 #include "wimlib/compress_common.h"
159 #include "wimlib/endianness.h"
160 #include "wimlib/error.h"
161 #include "wimlib/lzx.h"
162 #include "wimlib/util.h"
163 #include <pthread.h>
164 #include <math.h>
165 #include <string.h>
166
167 #ifdef ENABLE_LZX_DEBUG
168 #  include "wimlib/decompress_common.h"
169 #endif
170
171 #include "divsufsort/divsufsort.h"
172
173 typedef u32 block_cost_t;
174 #define INFINITE_BLOCK_COST     ((block_cost_t)~0U)
175
176 #define LZX_OPTIM_ARRAY_SIZE    4096
177
178 #define LZX_DIV_BLOCK_SIZE      32768
179
180 #define LZX_MAX_CACHE_PER_POS   10
181
182 /* Codewords for the LZX main, length, and aligned offset Huffman codes  */
183 struct lzx_codewords {
184         u16 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
185         u16 len[LZX_LENCODE_NUM_SYMBOLS];
186         u16 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
187 };
188
189 /* Codeword lengths (in bits) for the LZX main, length, and aligned offset
190  * Huffman codes.
191  *
192  * A 0 length means the codeword has zero frequency.
193  */
194 struct lzx_lens {
195         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
196         u8 len[LZX_LENCODE_NUM_SYMBOLS];
197         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
198 };
199
200 /* Costs for the LZX main, length, and aligned offset Huffman symbols.
201  *
202  * If a codeword has zero frequency, it must still be assigned some nonzero cost
203  * --- generally a high cost, since even if it gets used in the next iteration,
204  * it probably will not be used very times.  */
205 struct lzx_costs {
206         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
207         u8 len[LZX_LENCODE_NUM_SYMBOLS];
208         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
209 };
210
211 /* The LZX main, length, and aligned offset Huffman codes  */
212 struct lzx_codes {
213         struct lzx_codewords codewords;
214         struct lzx_lens lens;
215 };
216
217 /* Tables for tallying symbol frequencies in the three LZX alphabets  */
218 struct lzx_freqs {
219         input_idx_t main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
220         input_idx_t len[LZX_LENCODE_NUM_SYMBOLS];
221         input_idx_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
222 };
223
224 /* LZX intermediate match/literal format  */
225 struct lzx_match {
226         /* Bit     Description
227          *
228          * 31      1 if a match, 0 if a literal.
229          *
230          * 30-25   position slot.  This can be at most 50, so it will fit in 6
231          *         bits.
232          *
233          * 8-24    position footer.  This is the offset of the real formatted
234          *         offset from the position base.  This can be at most 17 bits
235          *         (since lzx_extra_bits[LZX_MAX_POSITION_SLOTS - 1] is 17).
236          *
237          * 0-7     length of match, minus 2.  This can be at most
238          *         (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits.  */
239         u32 data;
240 };
241
242 /* Raw LZ match/literal format: just a length and offset.
243  *
244  * The length is the number of bytes of the match, and the offset is the number
245  * of bytes back in the input the match is from the current position.
246  *
247  * If @len < LZX_MIN_MATCH_LEN, then it's really just a literal byte and @offset is
248  * meaningless.  */
249 struct raw_match {
250         u16 len;
251         input_idx_t offset;
252 };
253
254 /* Specification for an LZX block.  */
255 struct lzx_block_spec {
256
257         /* One of the LZX_BLOCKTYPE_* constants indicating which type of this
258          * block.  */
259         int block_type;
260
261         /* 0-based position in the window at which this block starts.  */
262         input_idx_t window_pos;
263
264         /* The number of bytes of uncompressed data this block represents.  */
265         input_idx_t block_size;
266
267         /* The position in the 'chosen_matches' array in the `struct
268          * lzx_compressor' at which the match/literal specifications for
269          * this block begin.  */
270         input_idx_t chosen_matches_start_pos;
271
272         /* The number of match/literal specifications for this block.  */
273         input_idx_t num_chosen_matches;
274
275         /* Huffman codes for this block.  */
276         struct lzx_codes codes;
277 };
278
279 /*
280  * An array of these structures is used during the match-choosing algorithm.
281  * They correspond to consecutive positions in the window and are used to keep
282  * track of the cost to reach each position, and the match/literal choices that
283  * need to be chosen to reach that position.
284  */
285 struct lzx_optimal {
286         /* The approximate minimum cost, in bits, to reach this position in the
287          * window which has been found so far.  */
288         block_cost_t cost;
289
290         /* The union here is just for clarity, since the fields are used in two
291          * slightly different ways.  Initially, the @prev structure is filled in
292          * first, and links go from later in the window to earlier in the
293          * window.  Later, @next structure is filled in and links go from
294          * earlier in the window to later in the window.  */
295         union {
296                 struct {
297                         /* Position of the start of the match or literal that
298                          * was taken to get to this position in the approximate
299                          * minimum-cost parse.  */
300                         input_idx_t link;
301
302                         /* Offset (as in an LZ (length, offset) pair) of the
303                          * match or literal that was taken to get to this
304                          * position in the approximate minimum-cost parse.  */
305                         input_idx_t match_offset;
306                 } prev;
307                 struct {
308                         /* Position at which the match or literal starting at
309                          * this position ends in the minimum-cost parse.  */
310                         input_idx_t link;
311
312                         /* Offset (as in an LZ (length, offset) pair) of the
313                          * match or literal starting at this position in the
314                          * approximate minimum-cost parse.  */
315                         input_idx_t match_offset;
316                 } next;
317         };
318
319         /* The match offset LRU queue that will exist when the approximate
320          * minimum-cost path to reach this position is taken.  */
321         struct lzx_lru_queue queue;
322 };
323
324 /* Suffix array link  */
325 struct salink {
326         /* Rank of highest ranked suffix that has rank lower than the suffix
327          * corresponding to this structure and either has a lower position
328          * (initially) or has a position lower than the highest position at
329          * which matches have been searched for so far, or -1 if there is no
330          * such suffix.  */
331         input_idx_t prev;
332
333         /* Rank of lowest ranked suffix that has rank greater than the suffix
334          * corresponding to this structure and either has a lower position
335          * (intially) or has a position lower than the highest position at which
336          * matches have been searched for so far, or -1 if there is no such
337          * suffix.  */
338         input_idx_t next;
339
340         /* Length of longest common prefix between the suffix corresponding to
341          * this structure and the suffix with rank @prev, or 0 if @prev is -1.
342          */
343         input_idx_t lcpprev;
344
345         /* Length of longest common prefix between the suffix corresponding to
346          * this structure and the suffix with rank @next, or 0 if @next is -1.
347          */
348         input_idx_t lcpnext;
349 };
350
351 /* State of the LZX compressor.  */
352 struct lzx_compressor {
353
354         /* The parameters that were used to create the compressor.  */
355         struct wimlib_lzx_compressor_params params;
356
357         /* The buffer of data to be compressed.
358          *
359          * 0xe8 byte preprocessing is done directly on the data here before
360          * further compression.
361          *
362          * Note that this compressor does *not* use a real sliding window!!!!
363          * It's not needed in the WIM format, since every chunk is compressed
364          * independently.  This is by design, to allow random access to the
365          * chunks.
366          *
367          * We reserve a few extra bytes to potentially allow reading off the end
368          * of the array in the match-finding code for optimization purposes.
369          */
370         u8 *window;
371
372         /* Number of bytes of data to be compressed, which is the number of
373          * bytes of data in @window that are actually valid.  */
374         input_idx_t window_size;
375
376         /* Allocated size of the @window.  */
377         input_idx_t max_window_size;
378
379         /* Number of symbols in the main alphabet (depends on the
380          * @max_window_size since it determines the maximum allowed offset).  */
381         unsigned num_main_syms;
382
383         /* The current match offset LRU queue.  */
384         struct lzx_lru_queue queue;
385
386         /* Space for the sequences of matches/literals that were chosen for each
387          * block.  */
388         struct lzx_match *chosen_matches;
389
390         /* Information about the LZX blocks the preprocessed input was divided
391          * into.  */
392         struct lzx_block_spec *block_specs;
393
394         /* Number of LZX blocks the input was divided into; a.k.a. the number of
395          * elements of @block_specs that are valid.  */
396         unsigned num_blocks;
397
398         /* This is simply filled in with zeroes and used to avoid special-casing
399          * the output of the first compressed Huffman code, which conceptually
400          * has a delta taken from a code with all symbols having zero-length
401          * codewords.  */
402         struct lzx_codes zero_codes;
403
404         /* The current cost model.  */
405         struct lzx_costs costs;
406
407         /* Fast algorithm only:  Array of hash table links.  */
408         input_idx_t *prev_tab;
409
410         /* Suffix array for window.
411          * This is a mapping from suffix rank to suffix position.  */
412         input_idx_t *SA;
413
414         /* Inverse suffix array for window.
415          * This is a mapping from suffix position to suffix rank.
416          * If 0 <= r < window_size, then ISA[SA[r]] == r.  */
417         input_idx_t *ISA;
418
419         /* Longest common prefix array corresponding to the suffix array SA.
420          * LCP[i] is the length of the longest common prefix between the
421          * suffixes with positions SA[i - 1] and  SA[i].  LCP[0] is undefined.
422          */
423         input_idx_t *LCP;
424
425         /* Suffix array links.
426          *
427          * During a linear scan of the input string to find matches, this array
428          * used to keep track of which rank suffixes in the suffix array appear
429          * before the current position.  Instead of searching in the original
430          * suffix array, scans for matches at a given position traverse a linked
431          * list containing only suffixes that appear before that position.  */
432         struct salink *salink;
433
434         /* Position in window of next match to return.  */
435         input_idx_t match_window_pos;
436
437         /* The match-finder shall ensure the length of matches does not exceed
438          * this position in the input.  */
439         input_idx_t match_window_end;
440
441         /* Matches found by the match-finder are cached in the following array
442          * to achieve a slight speedup when the same matches are needed on
443          * subsequent passes.  This is suboptimal because different matches may
444          * be preferred with different cost models, but seems to be a worthwhile
445          * speedup.  */
446         struct raw_match *cached_matches;
447         unsigned cached_matches_pos;
448         bool matches_cached;
449
450         /* Slow algorithm only: Temporary space used for match-choosing
451          * algorithm.
452          *
453          * The size of this array must be at least LZX_MAX_MATCH_LEN but
454          * otherwise is arbitrary.  More space simply allows the match-choosing
455          * algorithm to potentially find better matches (depending on the input,
456          * as always).  */
457         struct lzx_optimal *optimum;
458
459         /* Slow algorithm only: Variables used by the match-choosing algorithm.
460          *
461          * When matches have been chosen, optimum_cur_idx is set to the position
462          * in the window of the next match/literal to return and optimum_end_idx
463          * is set to the position in the window at the end of the last
464          * match/literal to return.  */
465         u32 optimum_cur_idx;
466         u32 optimum_end_idx;
467 };
468
469 /* Returns the LZX position slot that corresponds to a given match offset,
470  * taking into account the recent offset queue and updating it if the offset is
471  * found in it.  */
472 static unsigned
473 lzx_get_position_slot(unsigned offset, struct lzx_lru_queue *queue)
474 {
475         unsigned position_slot;
476
477         /* See if the offset was recently used.  */
478         for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
479                 if (offset == queue->R[i]) {
480                         /* Found it.  */
481
482                         /* Bring the repeat offset to the front of the
483                          * queue.  Note: this is, in fact, not a real
484                          * LRU queue because repeat matches are simply
485                          * swapped to the front.  */
486                         swap(queue->R[0], queue->R[i]);
487
488                         /* The resulting position slot is simply the first index
489                          * at which the offset was found in the queue.  */
490                         return i;
491                 }
492         }
493
494         /* The offset was not recently used; look up its real position slot.  */
495         position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
496
497         /* Bring the new offset to the front of the queue.  */
498         for (unsigned i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
499                 queue->R[i] = queue->R[i - 1];
500         queue->R[0] = offset;
501
502         return position_slot;
503 }
504
505 /* Build the main, length, and aligned offset Huffman codes used in LZX.
506  *
507  * This takes as input the frequency tables for each code and produces as output
508  * a set of tables that map symbols to codewords and codeword lengths.  */
509 static void
510 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
511                        struct lzx_codes *codes,
512                        unsigned num_main_syms)
513 {
514         make_canonical_huffman_code(num_main_syms,
515                                     LZX_MAX_MAIN_CODEWORD_LEN,
516                                     freqs->main,
517                                     codes->lens.main,
518                                     codes->codewords.main);
519
520         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
521                                     LZX_MAX_LEN_CODEWORD_LEN,
522                                     freqs->len,
523                                     codes->lens.len,
524                                     codes->codewords.len);
525
526         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
527                                     LZX_MAX_ALIGNED_CODEWORD_LEN,
528                                     freqs->aligned,
529                                     codes->lens.aligned,
530                                     codes->codewords.aligned);
531 }
532
533 /*
534  * Output an LZX match.
535  *
536  * @out:         The bitstream to write the match to.
537  * @block_type:  The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
538  * @match:       The match.
539  * @codes:       Pointer to a structure that contains the codewords for the
540  *               main, length, and aligned offset Huffman codes.
541  */
542 static void
543 lzx_write_match(struct output_bitstream *out, int block_type,
544                 struct lzx_match match, const struct lzx_codes *codes)
545 {
546         /* low 8 bits are the match length minus 2 */
547         unsigned match_len_minus_2 = match.data & 0xff;
548         /* Next 17 bits are the position footer */
549         unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
550         /* Next 6 bits are the position slot. */
551         unsigned position_slot = (match.data >> 25) & 0x3f;     /* 6 bits */
552         unsigned len_header;
553         unsigned len_footer;
554         unsigned main_symbol;
555         unsigned num_extra_bits;
556         unsigned verbatim_bits;
557         unsigned aligned_bits;
558
559         /* If the match length is less than MIN_MATCH_LEN (= 2) +
560          * NUM_PRIMARY_LENS (= 7), the length header contains
561          * the match length minus MIN_MATCH_LEN, and there is no
562          * length footer.
563          *
564          * Otherwise, the length header contains
565          * NUM_PRIMARY_LENS, and the length footer contains
566          * the match length minus NUM_PRIMARY_LENS minus
567          * MIN_MATCH_LEN. */
568         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
569                 len_header = match_len_minus_2;
570                 /* No length footer-- mark it with a special
571                  * value. */
572                 len_footer = (unsigned)(-1);
573         } else {
574                 len_header = LZX_NUM_PRIMARY_LENS;
575                 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
576         }
577
578         /* Combine the position slot with the length header into a single symbol
579          * that will be encoded with the main code.
580          *
581          * The actual main symbol is offset by LZX_NUM_CHARS because values
582          * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
583          * match.  */
584         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
585
586         /* Output main symbol. */
587         bitstream_put_bits(out, codes->codewords.main[main_symbol],
588                            codes->lens.main[main_symbol]);
589
590         /* If there is a length footer, output it using the
591          * length Huffman code. */
592         if (len_footer != (unsigned)(-1)) {
593                 bitstream_put_bits(out, codes->codewords.len[len_footer],
594                                    codes->lens.len[len_footer]);
595         }
596
597         num_extra_bits = lzx_get_num_extra_bits(position_slot);
598
599         /* For aligned offset blocks with at least 3 extra bits, output the
600          * verbatim bits literally, then the aligned bits encoded using the
601          * aligned offset code.  Otherwise, only the verbatim bits need to be
602          * output. */
603         if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
604
605                 verbatim_bits = position_footer >> 3;
606                 bitstream_put_bits(out, verbatim_bits,
607                                    num_extra_bits - 3);
608
609                 aligned_bits = (position_footer & 7);
610                 bitstream_put_bits(out,
611                                    codes->codewords.aligned[aligned_bits],
612                                    codes->lens.aligned[aligned_bits]);
613         } else {
614                 /* verbatim bits is the same as the position
615                  * footer, in this case. */
616                 bitstream_put_bits(out, position_footer, num_extra_bits);
617         }
618 }
619
620 static unsigned
621 lzx_build_precode(const u8 lens[restrict],
622                   const u8 prev_lens[restrict],
623                   const unsigned num_syms,
624                   input_idx_t precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
625                   u8 output_syms[restrict num_syms],
626                   u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
627                   u16 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
628                   unsigned *num_additional_bits_ret)
629 {
630         memset(precode_freqs, 0,
631                LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
632
633         /* Since the code word lengths use a form of RLE encoding, the goal here
634          * is to find each run of identical lengths when going through them in
635          * symbol order (including runs of length 1).  For each run, as many
636          * lengths are encoded using RLE as possible, and the rest are output
637          * literally.
638          *
639          * output_syms[] will be filled in with the length symbols that will be
640          * output, including RLE codes, not yet encoded using the precode.
641          *
642          * cur_run_len keeps track of how many code word lengths are in the
643          * current run of identical lengths.  */
644         unsigned output_syms_idx = 0;
645         unsigned cur_run_len = 1;
646         unsigned num_additional_bits = 0;
647         for (unsigned i = 1; i <= num_syms; i++) {
648
649                 if (i != num_syms && lens[i] == lens[i - 1]) {
650                         /* Still in a run--- keep going. */
651                         cur_run_len++;
652                         continue;
653                 }
654
655                 /* Run ended! Check if it is a run of zeroes or a run of
656                  * nonzeroes. */
657
658                 /* The symbol that was repeated in the run--- not to be confused
659                  * with the length *of* the run (cur_run_len) */
660                 unsigned len_in_run = lens[i - 1];
661
662                 if (len_in_run == 0) {
663                         /* A run of 0's.  Encode it in as few length
664                          * codes as we can. */
665
666                         /* The magic length 18 indicates a run of 20 + n zeroes,
667                          * where n is an uncompressed literal 5-bit integer that
668                          * follows the magic length. */
669                         while (cur_run_len >= 20) {
670                                 unsigned additional_bits;
671
672                                 additional_bits = min(cur_run_len - 20, 0x1f);
673                                 num_additional_bits += 5;
674                                 precode_freqs[18]++;
675                                 output_syms[output_syms_idx++] = 18;
676                                 output_syms[output_syms_idx++] = additional_bits;
677                                 cur_run_len -= 20 + additional_bits;
678                         }
679
680                         /* The magic length 17 indicates a run of 4 + n zeroes,
681                          * where n is an uncompressed literal 4-bit integer that
682                          * follows the magic length. */
683                         while (cur_run_len >= 4) {
684                                 unsigned additional_bits;
685
686                                 additional_bits = min(cur_run_len - 4, 0xf);
687                                 num_additional_bits += 4;
688                                 precode_freqs[17]++;
689                                 output_syms[output_syms_idx++] = 17;
690                                 output_syms[output_syms_idx++] = additional_bits;
691                                 cur_run_len -= 4 + additional_bits;
692                         }
693
694                 } else {
695
696                         /* A run of nonzero lengths. */
697
698                         /* The magic length 19 indicates a run of 4 + n
699                          * nonzeroes, where n is a literal bit that follows the
700                          * magic length, and where the value of the lengths in
701                          * the run is given by an extra length symbol, encoded
702                          * with the precode, that follows the literal bit.
703                          *
704                          * The extra length symbol is encoded as a difference
705                          * from the length of the codeword for the first symbol
706                          * in the run in the previous code.
707                          * */
708                         while (cur_run_len >= 4) {
709                                 unsigned additional_bits;
710                                 signed char delta;
711
712                                 additional_bits = (cur_run_len > 4);
713                                 num_additional_bits += 1;
714                                 delta = (signed char)prev_lens[i - cur_run_len] -
715                                         (signed char)len_in_run;
716                                 if (delta < 0)
717                                         delta += 17;
718                                 precode_freqs[19]++;
719                                 precode_freqs[(unsigned char)delta]++;
720                                 output_syms[output_syms_idx++] = 19;
721                                 output_syms[output_syms_idx++] = additional_bits;
722                                 output_syms[output_syms_idx++] = delta;
723                                 cur_run_len -= 4 + additional_bits;
724                         }
725                 }
726
727                 /* Any remaining lengths in the run are outputted without RLE,
728                  * as a difference from the length of that codeword in the
729                  * previous code. */
730                 while (cur_run_len > 0) {
731                         signed char delta;
732
733                         delta = (signed char)prev_lens[i - cur_run_len] -
734                                 (signed char)len_in_run;
735                         if (delta < 0)
736                                 delta += 17;
737
738                         precode_freqs[(unsigned char)delta]++;
739                         output_syms[output_syms_idx++] = delta;
740                         cur_run_len--;
741                 }
742
743                 cur_run_len = 1;
744         }
745
746         /* Build the precode from the frequencies of the length symbols. */
747
748         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
749                                     LZX_MAX_PRE_CODEWORD_LEN,
750                                     precode_freqs, precode_lens,
751                                     precode_codewords);
752
753         *num_additional_bits_ret = num_additional_bits;
754
755         return output_syms_idx;
756 }
757
758 /*
759  * Writes a compressed Huffman code to the output, preceded by the precode for
760  * it.
761  *
762  * The Huffman code is represented in the output as a series of path lengths
763  * from which the canonical Huffman code can be reconstructed.  The path lengths
764  * themselves are compressed using a separate Huffman code, the precode, which
765  * consists of LZX_PRECODE_NUM_SYMBOLS (= 20) symbols that cover all possible
766  * code lengths, plus extra codes for repeated lengths.  The path lengths of the
767  * precode precede the path lengths of the larger code and are uncompressed,
768  * consisting of 20 entries of 4 bits each.
769  *
770  * @out:                Bitstream to write the code to.
771  * @lens:               The code lengths for the Huffman code, indexed by symbol.
772  * @prev_lens:          Code lengths for this Huffman code, indexed by symbol,
773  *                      in the *previous block*, or all zeroes if this is the
774  *                      first block.
775  * @num_syms:           The number of symbols in the code.
776  */
777 static void
778 lzx_write_compressed_code(struct output_bitstream *out,
779                           const u8 lens[restrict],
780                           const u8 prev_lens[restrict],
781                           unsigned num_syms)
782 {
783         input_idx_t precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
784         u8 output_syms[num_syms];
785         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
786         u16 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
787         unsigned i;
788         unsigned num_output_syms;
789         u8 precode_sym;
790         unsigned dummy;
791
792         num_output_syms = lzx_build_precode(lens,
793                                             prev_lens,
794                                             num_syms,
795                                             precode_freqs,
796                                             output_syms,
797                                             precode_lens,
798                                             precode_codewords,
799                                             &dummy);
800
801         /* Write the lengths of the precode codes to the output. */
802         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
803                 bitstream_put_bits(out, precode_lens[i],
804                                    LZX_PRECODE_ELEMENT_SIZE);
805
806         /* Write the length symbols, encoded with the precode, to the output. */
807
808         for (i = 0; i < num_output_syms; ) {
809                 precode_sym = output_syms[i++];
810
811                 bitstream_put_bits(out, precode_codewords[precode_sym],
812                                    precode_lens[precode_sym]);
813                 switch (precode_sym) {
814                 case 17:
815                         bitstream_put_bits(out, output_syms[i++], 4);
816                         break;
817                 case 18:
818                         bitstream_put_bits(out, output_syms[i++], 5);
819                         break;
820                 case 19:
821                         bitstream_put_bits(out, output_syms[i++], 1);
822                         bitstream_put_bits(out,
823                                            precode_codewords[output_syms[i]],
824                                            precode_lens[output_syms[i]]);
825                         i++;
826                         break;
827                 default:
828                         break;
829                 }
830         }
831 }
832
833 /*
834  * Writes all compressed matches and literal bytes in an LZX block to the the
835  * output bitstream.
836  *
837  * @ostream
838  *      The output bitstream.
839  * @block_type
840  *      The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM).
841  * @match_tab
842  *      The array of matches/literals that will be output (length @match_count).
843  * @match_count
844  *      Number of matches/literals to be output.
845  * @codes
846  *      Pointer to a structure that contains the codewords for the main, length,
847  *      and aligned offset Huffman codes.
848  */
849 static void
850 lzx_write_matches_and_literals(struct output_bitstream *ostream,
851                                int block_type,
852                                const struct lzx_match match_tab[],
853                                unsigned match_count,
854                                const struct lzx_codes *codes)
855 {
856         for (unsigned i = 0; i < match_count; i++) {
857                 struct lzx_match match = match_tab[i];
858
859                 /* High bit of the match indicates whether the match is an
860                  * actual match (1) or a literal uncompressed byte (0)  */
861                 if (match.data & 0x80000000) {
862                         /* match */
863                         lzx_write_match(ostream, block_type,
864                                         match, codes);
865                 } else {
866                         /* literal byte */
867                         bitstream_put_bits(ostream,
868                                            codes->codewords.main[match.data],
869                                            codes->lens.main[match.data]);
870                 }
871         }
872 }
873
874 static void
875 lzx_assert_codes_valid(const struct lzx_codes * codes, unsigned num_main_syms)
876 {
877 #ifdef ENABLE_LZX_DEBUG
878         unsigned i;
879
880         for (i = 0; i < num_main_syms; i++)
881                 LZX_ASSERT(codes->lens.main[i] <= LZX_MAX_MAIN_CODEWORD_LEN);
882
883         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
884                 LZX_ASSERT(codes->lens.len[i] <= LZX_MAX_LEN_CODEWORD_LEN);
885
886         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
887                 LZX_ASSERT(codes->lens.aligned[i] <= LZX_MAX_ALIGNED_CODEWORD_LEN);
888
889         const unsigned tablebits = 10;
890         u16 decode_table[(1 << tablebits) +
891                          (2 * max(num_main_syms, LZX_LENCODE_NUM_SYMBOLS))]
892                          _aligned_attribute(DECODE_TABLE_ALIGNMENT);
893         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
894                                                   num_main_syms,
895                                                   min(tablebits, LZX_MAINCODE_TABLEBITS),
896                                                   codes->lens.main,
897                                                   LZX_MAX_MAIN_CODEWORD_LEN));
898         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
899                                                   LZX_LENCODE_NUM_SYMBOLS,
900                                                   min(tablebits, LZX_LENCODE_TABLEBITS),
901                                                   codes->lens.len,
902                                                   LZX_MAX_LEN_CODEWORD_LEN));
903         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
904                                                   LZX_ALIGNEDCODE_NUM_SYMBOLS,
905                                                   min(tablebits, LZX_ALIGNEDCODE_TABLEBITS),
906                                                   codes->lens.aligned,
907                                                   LZX_MAX_ALIGNED_CODEWORD_LEN));
908 #endif /* ENABLE_LZX_DEBUG */
909 }
910
911 /* Write an LZX aligned offset or verbatim block to the output.  */
912 static void
913 lzx_write_compressed_block(int block_type,
914                            unsigned block_size,
915                            unsigned max_window_size,
916                            unsigned num_main_syms,
917                            struct lzx_match * chosen_matches,
918                            unsigned num_chosen_matches,
919                            const struct lzx_codes * codes,
920                            const struct lzx_codes * prev_codes,
921                            struct output_bitstream * ostream)
922 {
923         unsigned i;
924
925         LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
926                    block_type == LZX_BLOCKTYPE_VERBATIM);
927         lzx_assert_codes_valid(codes, num_main_syms);
928
929         /* The first three bits indicate the type of block and are one of the
930          * LZX_BLOCKTYPE_* constants.  */
931         bitstream_put_bits(ostream, block_type, 3);
932
933         /* Output the block size.
934          *
935          * The original LZX format seemed to always encode the block size in 3
936          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
937          * uses the first bit to indicate whether the block is the default size
938          * (32768) or a different size given explicitly by the next 16 bits.
939          *
940          * By default, this compressor uses a window size of 32768 and therefore
941          * follows the WIMGAPI behavior.  However, this compressor also supports
942          * window sizes greater than 32768 bytes, which do not appear to be
943          * supported by WIMGAPI.  In such cases, we retain the default size bit
944          * to mean a size of 32768 bytes but output non-default block size in 24
945          * bits rather than 16.  The compatibility of this behavior is unknown
946          * because WIMs created with chunk size greater than 32768 can seemingly
947          * only be opened by wimlib anyway.  */
948         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
949                 bitstream_put_bits(ostream, 1, 1);
950         } else {
951                 bitstream_put_bits(ostream, 0, 1);
952
953                 if (max_window_size >= 65536)
954                         bitstream_put_bits(ostream, block_size >> 16, 8);
955
956                 bitstream_put_bits(ostream, block_size, 16);
957         }
958
959         /* Write out lengths of the main code. Note that the LZX specification
960          * incorrectly states that the aligned offset code comes after the
961          * length code, but in fact it is the very first code to be written
962          * (before the main code).  */
963         if (block_type == LZX_BLOCKTYPE_ALIGNED)
964                 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
965                         bitstream_put_bits(ostream, codes->lens.aligned[i],
966                                            LZX_ALIGNEDCODE_ELEMENT_SIZE);
967
968         LZX_DEBUG("Writing main code...");
969
970         /* Write the precode and lengths for the first LZX_NUM_CHARS symbols in
971          * the main code, which are the codewords for literal bytes.  */
972         lzx_write_compressed_code(ostream,
973                                   codes->lens.main,
974                                   prev_codes->lens.main,
975                                   LZX_NUM_CHARS);
976
977         /* Write the precode and lengths for the rest of the main code, which
978          * are the codewords for match headers.  */
979         lzx_write_compressed_code(ostream,
980                                   codes->lens.main + LZX_NUM_CHARS,
981                                   prev_codes->lens.main + LZX_NUM_CHARS,
982                                   num_main_syms - LZX_NUM_CHARS);
983
984         LZX_DEBUG("Writing length code...");
985
986         /* Write the precode and lengths for the length code.  */
987         lzx_write_compressed_code(ostream,
988                                   codes->lens.len,
989                                   prev_codes->lens.len,
990                                   LZX_LENCODE_NUM_SYMBOLS);
991
992         LZX_DEBUG("Writing matches and literals...");
993
994         /* Write the actual matches and literals.  */
995         lzx_write_matches_and_literals(ostream, block_type,
996                                        chosen_matches, num_chosen_matches,
997                                        codes);
998
999         LZX_DEBUG("Done writing block.");
1000 }
1001
1002 /* Write out the LZX blocks that were computed.  */
1003 static void
1004 lzx_write_all_blocks(struct lzx_compressor *ctx, struct output_bitstream *ostream)
1005 {
1006
1007         const struct lzx_codes *prev_codes = &ctx->zero_codes;
1008         for (unsigned i = 0; i < ctx->num_blocks; i++) {
1009                 const struct lzx_block_spec *spec = &ctx->block_specs[i];
1010
1011                 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_matches=%u)...",
1012                           i + 1, ctx->num_blocks,
1013                           spec->block_type, spec->block_size,
1014                           spec->num_chosen_matches);
1015
1016                 lzx_write_compressed_block(spec->block_type,
1017                                            spec->block_size,
1018                                            ctx->max_window_size,
1019                                            ctx->num_main_syms,
1020                                            &ctx->chosen_matches[spec->chosen_matches_start_pos],
1021                                            spec->num_chosen_matches,
1022                                            &spec->codes,
1023                                            prev_codes,
1024                                            ostream);
1025
1026                 prev_codes = &spec->codes;
1027         }
1028 }
1029
1030 /* Constructs an LZX match from a literal byte and updates the main code symbol
1031  * frequencies.  */
1032 static u32
1033 lzx_tally_literal(u8 lit, struct lzx_freqs *freqs)
1034 {
1035         freqs->main[lit]++;
1036         return (u32)lit;
1037 }
1038
1039 /* Constructs an LZX match from an offset and a length, and updates the LRU
1040  * queue and the frequency of symbols in the main, length, and aligned offset
1041  * alphabets.  The return value is a 32-bit number that provides the match in an
1042  * intermediate representation documented below.  */
1043 static u32
1044 lzx_tally_match(unsigned match_len, unsigned match_offset,
1045                 struct lzx_freqs *freqs, struct lzx_lru_queue *queue)
1046 {
1047         unsigned position_slot;
1048         unsigned position_footer;
1049         u32 len_header;
1050         unsigned main_symbol;
1051         unsigned len_footer;
1052         unsigned adjusted_match_len;
1053
1054         LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
1055
1056         /* The match offset shall be encoded as a position slot (itself encoded
1057          * as part of the main symbol) and a position footer.  */
1058         position_slot = lzx_get_position_slot(match_offset, queue);
1059         position_footer = (match_offset + LZX_OFFSET_OFFSET) &
1060                                 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
1061
1062         /* The match length shall be encoded as a length header (itself encoded
1063          * as part of the main symbol) and an optional length footer.  */
1064         adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
1065         if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
1066                 /* No length footer needed.  */
1067                 len_header = adjusted_match_len;
1068         } else {
1069                 /* Length footer needed.  It will be encoded using the length
1070                  * code.  */
1071                 len_header = LZX_NUM_PRIMARY_LENS;
1072                 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
1073                 freqs->len[len_footer]++;
1074         }
1075
1076         /* Account for the main symbol.  */
1077         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1078
1079         freqs->main[main_symbol]++;
1080
1081         /* In an aligned offset block, 3 bits of the position footer are output
1082          * as an aligned offset symbol.  Account for this, although we may
1083          * ultimately decide to output the block as verbatim.  */
1084
1085         /* The following check is equivalent to:
1086          *
1087          * if (lzx_extra_bits[position_slot] >= 3)
1088          *
1089          * Note that this correctly excludes position slots that correspond to
1090          * recent offsets.  */
1091         if (position_slot >= 8)
1092                 freqs->aligned[position_footer & 7]++;
1093
1094         /* Pack the position slot, position footer, and match length into an
1095          * intermediate representation.  See `struct lzx_match' for details.
1096          */
1097         LZX_ASSERT(LZX_MAX_POSITION_SLOTS <= 64);
1098         LZX_ASSERT(lzx_get_num_extra_bits(LZX_MAX_POSITION_SLOTS - 1) <= 17);
1099         LZX_ASSERT(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 <= 256);
1100
1101         LZX_ASSERT(position_slot      <= (1U << (31 - 25)) - 1);
1102         LZX_ASSERT(position_footer    <= (1U << (25 -  8)) - 1);
1103         LZX_ASSERT(adjusted_match_len <= (1U << (8  -  0)) - 1);
1104         return 0x80000000 |
1105                 (position_slot << 25) |
1106                 (position_footer << 8) |
1107                 (adjusted_match_len);
1108 }
1109
1110 struct lzx_record_ctx {
1111         struct lzx_freqs freqs;
1112         struct lzx_lru_queue queue;
1113         struct lzx_match *matches;
1114 };
1115
1116 static void
1117 lzx_record_match(unsigned len, unsigned offset, void *_ctx)
1118 {
1119         struct lzx_record_ctx *ctx = _ctx;
1120
1121         (ctx->matches++)->data = lzx_tally_match(len, offset, &ctx->freqs, &ctx->queue);
1122 }
1123
1124 static void
1125 lzx_record_literal(u8 lit, void *_ctx)
1126 {
1127         struct lzx_record_ctx *ctx = _ctx;
1128
1129         (ctx->matches++)->data = lzx_tally_literal(lit, &ctx->freqs);
1130 }
1131
1132 /* Returns the cost, in bits, to output a literal byte using the specified cost
1133  * model.  */
1134 static unsigned
1135 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1136 {
1137         return costs->main[c];
1138 }
1139
1140 /* Given a (length, offset) pair that could be turned into a valid LZX match as
1141  * well as costs for the codewords in the main, length, and aligned Huffman
1142  * codes, return the approximate number of bits it will take to represent this
1143  * match in the compressed output.  Take into account the match offset LRU
1144  * queue and optionally update it.  */
1145 static unsigned
1146 lzx_match_cost(unsigned length, unsigned offset, const struct lzx_costs *costs,
1147                struct lzx_lru_queue *queue)
1148 {
1149         unsigned position_slot;
1150         unsigned len_header, main_symbol;
1151         unsigned cost = 0;
1152
1153         position_slot = lzx_get_position_slot(offset, queue);
1154
1155         len_header = min(length - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1156         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1157
1158         /* Account for main symbol.  */
1159         cost += costs->main[main_symbol];
1160
1161         /* Account for extra position information.  */
1162         unsigned num_extra_bits = lzx_get_num_extra_bits(position_slot);
1163         if (num_extra_bits >= 3) {
1164                 cost += num_extra_bits - 3;
1165                 cost += costs->aligned[(offset + LZX_OFFSET_OFFSET) & 7];
1166         } else {
1167                 cost += num_extra_bits;
1168         }
1169
1170         /* Account for extra length information.  */
1171         if (len_header == LZX_NUM_PRIMARY_LENS)
1172                 cost += costs->len[length - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1173
1174         return cost;
1175
1176 }
1177
1178 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
1179  * Unlike lzx_match_cost() which does a true cost evaluation, this simply
1180  * prioritize matches based on their offset.  */
1181 static block_cost_t
1182 lzx_match_cost_fast(unsigned offset, const struct lzx_lru_queue *queue)
1183 {
1184         /* It seems well worth it to take the time to give priority to recently
1185          * used offsets.  */
1186         for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++)
1187                 if (offset == queue->R[i])
1188                         return i;
1189
1190         BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE >= (block_cost_t)~0U);
1191         return offset;
1192 }
1193
1194 /* Set the cost model @ctx->costs from the Huffman codeword lengths specified in
1195  * @lens.
1196  *
1197  * The cost model and codeword lengths are almost the same thing, but the
1198  * Huffman codewords with length 0 correspond to symbols with zero frequency
1199  * that still need to be assigned actual costs.  The specific values assigned
1200  * are arbitrary, but they should be fairly high (near the maximum codeword
1201  * length) to take into account the fact that uses of these symbols are expected
1202  * to be rare.  */
1203 static void
1204 lzx_set_costs(struct lzx_compressor * ctx, const struct lzx_lens * lens)
1205 {
1206         unsigned i;
1207         unsigned num_main_syms = ctx->num_main_syms;
1208
1209         /* Main code  */
1210         for (i = 0; i < num_main_syms; i++) {
1211                 ctx->costs.main[i] = lens->main[i];
1212                 if (ctx->costs.main[i] == 0)
1213                         ctx->costs.main[i] = ctx->params.alg_params.slow.main_nostat_cost;
1214         }
1215
1216         /* Length code  */
1217         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1218                 ctx->costs.len[i] = lens->len[i];
1219                 if (ctx->costs.len[i] == 0)
1220                         ctx->costs.len[i] = ctx->params.alg_params.slow.len_nostat_cost;
1221         }
1222
1223         /* Aligned offset code  */
1224         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1225                 ctx->costs.aligned[i] = lens->aligned[i];
1226                 if (ctx->costs.aligned[i] == 0)
1227                         ctx->costs.aligned[i] = ctx->params.alg_params.slow.aligned_nostat_cost;
1228         }
1229 }
1230
1231 /* Advance the suffix array match-finder to the next position.  */
1232 static void
1233 lzx_lz_update_salink(input_idx_t i,
1234                      const input_idx_t SA[restrict],
1235                      const input_idx_t ISA[restrict],
1236                      struct salink link[restrict])
1237 {
1238         /* r = Rank of the suffix at the current position.  */
1239         const input_idx_t r = ISA[i];
1240
1241         /* next = rank of LOWEST ranked suffix that is ranked HIGHER than the
1242          * current suffix AND has a LOWER position, or -1 if none exists.  */
1243         const input_idx_t next = link[r].next;
1244
1245         /* prev = rank of HIGHEST ranked suffix that is ranked LOWER than the
1246          * current suffix AND has a LOWER position, or -1 if none exists.  */
1247         const input_idx_t prev = link[r].prev;
1248
1249         /* Link the suffix at the current position into the linked list that
1250          * contains all suffixes in the suffix array that are appear at or
1251          * before the current position, sorted by rank.
1252          *
1253          * Save the values of all fields we overwrite so that rollback is
1254          * possible.  */
1255         if (next != (input_idx_t)~0U) {
1256
1257                 link[next].prev = r;
1258                 link[next].lcpprev = link[r].lcpnext;
1259         }
1260
1261         if (prev != (input_idx_t)~0U) {
1262
1263                 link[prev].next = r;
1264                 link[prev].lcpnext = link[r].lcpprev;
1265         }
1266 }
1267
1268 /*
1269  * Use the suffix array match-finder to retrieve a list of LZ matches at the
1270  * current position.
1271  *
1272  * [in]    @i           Current position in the window.
1273  * [in]    @SA          Suffix array for the window.
1274  * [in]    @ISA         Inverse suffix array for the window.
1275  * [inout] @link        Suffix array links used internally by the match-finder.
1276  * [out]   @matches     The (length, offset) pairs of the resulting matches will
1277  *                              be written here, sorted in decreasing order by
1278  *                              length.  All returned lengths will be unique.
1279  * [in]    @queue       Recently used match offsets, used when evaluating the
1280  *                              cost of matches.
1281  * [in]    @min_match_len       Minimum match length to return.
1282  * [in]    @max_matches_to_consider     Maximum number of matches to consider at
1283  *                                      the position.
1284  * [in]    @max_matches_to_return       Maximum number of matches to return.
1285  *
1286  * The return value is the number of matches found and written to @matches.
1287  */
1288 static unsigned
1289 lzx_lz_get_matches(const input_idx_t i,
1290                    const input_idx_t SA[const restrict],
1291                    const input_idx_t ISA[const restrict],
1292                    struct salink link[const restrict],
1293                    struct raw_match matches[const restrict],
1294                    const struct lzx_lru_queue * const restrict queue,
1295                    const unsigned min_match_len,
1296                    const u32 max_matches_to_consider,
1297                    const u32 max_matches_to_return)
1298 {
1299         /* r = Rank of the suffix at the current position.  */
1300         const input_idx_t r = ISA[i];
1301
1302         /* Prepare for searching the current position.  */
1303         lzx_lz_update_salink(i, SA, ISA, link);
1304
1305         /* L = rank of next suffix to the left;
1306          * R = rank of next suffix to the right;
1307          * lenL = length of match between current position and the suffix with rank L;
1308          * lenR = length of match between current position and the suffix with rank R.
1309          *
1310          * This is left and right relative to the rank of the current suffix.
1311          * Since the suffixes in the suffix array are sorted, the longest
1312          * matches are immediately to the left and right (using the linked list
1313          * to ignore all suffixes that occur later in the window).  The match
1314          * length decreases the farther left and right we go.  We shall keep the
1315          * length on both sides in sync in order to choose the lowest-cost match
1316          * of each length.
1317          */
1318         input_idx_t L = link[r].prev;
1319         input_idx_t R = link[r].next;
1320         input_idx_t lenL = link[r].lcpprev;
1321         input_idx_t lenR = link[r].lcpnext;
1322
1323         /* nmatches = number of matches found so far.  */
1324         unsigned nmatches = 0;
1325
1326         /* best_cost = cost of lowest-cost match found so far.
1327          *
1328          * We keep track of this so that we can ignore shorter matches that do
1329          * not have lower costs than a longer matches already found.
1330          */
1331         block_cost_t best_cost = INFINITE_BLOCK_COST;
1332
1333         /* count_remaining = maximum number of possible matches remaining to be
1334          * considered.  */
1335         u32 count_remaining = max_matches_to_consider;
1336
1337         /* pending = match currently being considered for a specific length.  */
1338         struct raw_match pending;
1339         block_cost_t pending_cost;
1340
1341         while (lenL >= min_match_len || lenR >= min_match_len)
1342         {
1343                 pending.len = lenL;
1344                 pending_cost = INFINITE_BLOCK_COST;
1345                 block_cost_t cost;
1346
1347                 /* Extend left.  */
1348                 if (lenL >= min_match_len && lenL >= lenR) {
1349                         for (;;) {
1350
1351                                 if (--count_remaining == 0)
1352                                         goto out_save_pending;
1353
1354                                 input_idx_t offset = i - SA[L];
1355
1356                                 /* Save match if it has smaller cost.  */
1357                                 cost = lzx_match_cost_fast(offset, queue);
1358                                 if (cost < pending_cost) {
1359                                         pending.offset = offset;
1360                                         pending_cost = cost;
1361                                 }
1362
1363                                 if (link[L].lcpprev < lenL) {
1364                                         /* Match length decreased.  */
1365
1366                                         lenL = link[L].lcpprev;
1367
1368                                         /* Save the pending match unless the
1369                                          * right side still may have matches of
1370                                          * this length to be scanned, or if a
1371                                          * previous (longer) match had lower
1372                                          * cost.  */
1373                                         if (pending.len > lenR) {
1374                                                 if (pending_cost < best_cost) {
1375                                                         best_cost = pending_cost;
1376                                                         matches[nmatches++] = pending;
1377                                                         if (nmatches == max_matches_to_return)
1378                                                                 return nmatches;
1379                                                 }
1380                                                 pending.len = lenL;
1381                                                 pending_cost = INFINITE_BLOCK_COST;
1382                                         }
1383                                         if (lenL < min_match_len || lenL < lenR)
1384                                                 break;
1385                                 }
1386                                 L = link[L].prev;
1387                         }
1388                 }
1389
1390                 pending.len = lenR;
1391
1392                 /* Extend right.  */
1393                 if (lenR >= min_match_len && lenR > lenL) {
1394                         for (;;) {
1395
1396                                 if (--count_remaining == 0)
1397                                         goto out_save_pending;
1398
1399                                 input_idx_t offset = i - SA[R];
1400
1401                                 /* Save match if it has smaller cost.  */
1402                                 cost = lzx_match_cost_fast(offset, queue);
1403                                 if (cost < pending_cost) {
1404                                         pending.offset = offset;
1405                                         pending_cost = cost;
1406                                 }
1407
1408                                 if (link[R].lcpnext < lenR) {
1409                                         /* Match length decreased.  */
1410
1411                                         lenR = link[R].lcpnext;
1412
1413                                         /* Save the pending match unless a
1414                                          * previous (longer) match had lower
1415                                          * cost.  */
1416                                         if (pending_cost < best_cost) {
1417                                                 matches[nmatches++] = pending;
1418                                                 best_cost = pending_cost;
1419                                                 if (nmatches == max_matches_to_return)
1420                                                         return nmatches;
1421                                         }
1422
1423                                         if (lenR < min_match_len || lenR <= lenL)
1424                                                 break;
1425
1426                                         pending.len = lenR;
1427                                         pending_cost = INFINITE_BLOCK_COST;
1428                                 }
1429                                 R = link[R].next;
1430                         }
1431                 }
1432         }
1433         goto out;
1434
1435 out_save_pending:
1436         if (pending_cost != INFINITE_BLOCK_COST)
1437                 matches[nmatches++] = pending;
1438
1439 out:
1440         return nmatches;
1441 }
1442
1443
1444 /* Tell the match-finder to skip the specified number of bytes (@n) in the
1445  * input.  */
1446 static void
1447 lzx_lz_skip_bytes(struct lzx_compressor *ctx, unsigned n)
1448 {
1449         LZX_ASSERT(n <= ctx->match_window_end - ctx->match_window_pos);
1450         if (ctx->matches_cached) {
1451                 ctx->match_window_pos += n;
1452                 while (n--) {
1453                         ctx->cached_matches_pos +=
1454                                 ctx->cached_matches[ctx->cached_matches_pos].len + 1;
1455                 }
1456         } else {
1457                 while (n--) {
1458                         ctx->cached_matches[ctx->cached_matches_pos++].len = 0;
1459                         lzx_lz_update_salink(ctx->match_window_pos++, ctx->SA,
1460                                              ctx->ISA, ctx->salink);
1461                 }
1462         }
1463 }
1464
1465 /* Retrieve a list of matches available at the next position in the input.
1466  *
1467  * The matches are written to ctx->matches in decreasing order of length, and
1468  * the return value is the number of matches found.  */
1469 static unsigned
1470 lzx_lz_get_matches_caching(struct lzx_compressor *ctx,
1471                            const struct lzx_lru_queue *queue,
1472                            struct raw_match **matches_ret)
1473 {
1474         unsigned num_matches;
1475         struct raw_match *matches;
1476
1477         LZX_ASSERT(ctx->match_window_pos <= ctx->match_window_end);
1478
1479         matches = &ctx->cached_matches[ctx->cached_matches_pos + 1];
1480
1481         if (ctx->matches_cached) {
1482                 num_matches = matches[-1].len;
1483         } else {
1484                 unsigned min_match_len = LZX_MIN_MATCH_LEN;
1485                 if (!ctx->params.alg_params.slow.use_len2_matches)
1486                         min_match_len = max(min_match_len, 3);
1487                 const u32 max_search_depth = ctx->params.alg_params.slow.max_search_depth;
1488                 const u32 max_matches_per_pos = ctx->params.alg_params.slow.max_matches_per_pos;
1489
1490                 if (unlikely(max_search_depth == 0 || max_matches_per_pos == 0))
1491                         num_matches = 0;
1492                 else
1493                         num_matches = lzx_lz_get_matches(ctx->match_window_pos,
1494                                                          ctx->SA,
1495                                                          ctx->ISA,
1496                                                          ctx->salink,
1497                                                          matches,
1498                                                          queue,
1499                                                          min_match_len,
1500                                                          max_search_depth,
1501                                                          max_matches_per_pos);
1502                 matches[-1].len = num_matches;
1503         }
1504         ctx->cached_matches_pos += num_matches + 1;
1505         *matches_ret = matches;
1506
1507         /* Cap the length of returned matches to the number of bytes remaining,
1508          * if it is not the whole window.  */
1509         if (ctx->match_window_end < ctx->window_size) {
1510                 unsigned maxlen = ctx->match_window_end - ctx->match_window_pos;
1511                 for (unsigned i = 0; i < num_matches; i++)
1512                         if (matches[i].len > maxlen)
1513                                 matches[i].len = maxlen;
1514         }
1515 #if 0
1516         fprintf(stderr, "Pos %u/%u: %u matches\n",
1517                 ctx->match_window_pos, ctx->match_window_end, num_matches);
1518         for (unsigned i = 0; i < num_matches; i++)
1519                 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
1520 #endif
1521
1522 #ifdef ENABLE_LZX_DEBUG
1523         for (unsigned i = 0; i < num_matches; i++) {
1524                 LZX_ASSERT(matches[i].len >= LZX_MIN_MATCH_LEN);
1525                 LZX_ASSERT(matches[i].len <= LZX_MAX_MATCH_LEN);
1526                 LZX_ASSERT(matches[i].len <= ctx->match_window_end - ctx->match_window_pos);
1527                 LZX_ASSERT(matches[i].offset > 0);
1528                 LZX_ASSERT(matches[i].offset <= ctx->match_window_pos);
1529                 LZX_ASSERT(!memcmp(&ctx->window[ctx->match_window_pos],
1530                                    &ctx->window[ctx->match_window_pos - matches[i].offset],
1531                                    matches[i].len));
1532         }
1533 #endif
1534
1535         ctx->match_window_pos++;
1536         return num_matches;
1537 }
1538
1539 /*
1540  * Reverse the linked list of near-optimal matches so that they can be returned
1541  * in forwards order.
1542  *
1543  * Returns the first match in the list.
1544  */
1545 static struct raw_match
1546 lzx_lz_reverse_near_optimal_match_list(struct lzx_compressor *ctx,
1547                                        unsigned cur_pos)
1548 {
1549         unsigned prev_link, saved_prev_link;
1550         unsigned prev_match_offset, saved_prev_match_offset;
1551
1552         ctx->optimum_end_idx = cur_pos;
1553
1554         saved_prev_link = ctx->optimum[cur_pos].prev.link;
1555         saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
1556
1557         do {
1558                 prev_link = saved_prev_link;
1559                 prev_match_offset = saved_prev_match_offset;
1560
1561                 saved_prev_link = ctx->optimum[prev_link].prev.link;
1562                 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
1563
1564                 ctx->optimum[prev_link].next.link = cur_pos;
1565                 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
1566
1567                 cur_pos = prev_link;
1568         } while (cur_pos != 0);
1569
1570         ctx->optimum_cur_idx = ctx->optimum[0].next.link;
1571
1572         return (struct raw_match)
1573                 { .len = ctx->optimum_cur_idx,
1574                   .offset = ctx->optimum[0].next.match_offset,
1575                 };
1576 }
1577
1578 /*
1579  * lzx_lz_get_near_optimal_match() -
1580  *
1581  * Choose the optimal match or literal to use at the next position in the input.
1582  *
1583  * Unlike a greedy parser that always takes the longest match, or even a
1584  * parser with one match/literal look-ahead like zlib, the algorithm used here
1585  * may look ahead many matches/literals to determine the optimal match/literal to
1586  * output next.  The motivation is that the compression ratio is improved if the
1587  * compressor can do things like use a shorter-than-possible match in order to
1588  * allow a longer match later, and also take into account the Huffman code cost
1589  * model rather than simply assuming that longer is better.
1590  *
1591  * Still, this is not truly an optimal parser because very long matches are
1592  * taken immediately, and the raw match-finder takes some shortcuts.  This is
1593  * done to avoid considering many different alternatives that are unlikely to
1594  * be significantly better.
1595  *
1596  * This algorithm is based on that used in 7-Zip's DEFLATE encoder.
1597  *
1598  * Each call to this function does one of two things:
1599  *
1600  * 1. Build a near-optimal sequence of matches/literals, up to some point, that
1601  *    will be returned by subsequent calls to this function, then return the
1602  *    first one.
1603  *
1604  * OR
1605  *
1606  * 2. Return the next match/literal previously computed by a call to this
1607  *    function;
1608  *
1609  * This function relies on the following state in the compressor context:
1610  *
1611  *      ctx->window          (read-only: preprocessed data being compressed)
1612  *      ctx->cost            (read-only: cost model to use)
1613  *      ctx->optimum         (internal state; leave uninitialized)
1614  *      ctx->optimum_cur_idx (must set to 0 before first call)
1615  *      ctx->optimum_end_idx (must set to 0 before first call)
1616  *
1617  *      Plus any state used by the raw match-finder.
1618  *
1619  * The return value is a (length, offset) pair specifying the match or literal
1620  * chosen.  For literals, the length is less than LZX_MIN_MATCH_LEN and the
1621  * offset is meaningless.
1622  */
1623 static struct raw_match
1624 lzx_lz_get_near_optimal_match(struct lzx_compressor * ctx)
1625 {
1626         unsigned num_possible_matches;
1627         struct raw_match *possible_matches;
1628         struct raw_match match;
1629         unsigned longest_match_len;
1630
1631         if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
1632                 /* Case 2: Return the next match/literal already found.  */
1633                 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
1634                                     ctx->optimum_cur_idx;
1635                 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1636
1637                 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
1638                 return match;
1639         }
1640
1641         /* Case 1:  Compute a new list of matches/literals to return.  */
1642
1643         ctx->optimum_cur_idx = 0;
1644         ctx->optimum_end_idx = 0;
1645
1646         /* Get matches at this position.  */
1647         num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &possible_matches);
1648
1649         /* If no matches found, return literal.  */
1650         if (num_possible_matches == 0)
1651                 return (struct raw_match){ .len = 0 };
1652
1653         /* The matches that were found are sorted in decreasing order by length.
1654          * Get the length of the longest one.  */
1655         longest_match_len = possible_matches[0].len;
1656
1657         /* Greedy heuristic:  if the longest match that was found is greater
1658          * than the number of fast bytes, return it immediately; don't both
1659          * doing more work.  */
1660         if (longest_match_len > ctx->params.alg_params.slow.num_fast_bytes) {
1661                 lzx_lz_skip_bytes(ctx, longest_match_len - 1);
1662                 return possible_matches[0];
1663         }
1664
1665         /* Calculate the cost to reach the next position by outputting a
1666          * literal.  */
1667         ctx->optimum[0].queue = ctx->queue;
1668         ctx->optimum[1].queue = ctx->optimum[0].queue;
1669         ctx->optimum[1].cost = lzx_literal_cost(ctx->window[ctx->match_window_pos],
1670                                                 &ctx->costs);
1671         ctx->optimum[1].prev.link = 0;
1672
1673         /* Calculate the cost to reach any position up to and including that
1674          * reached by the longest match, using the shortest (i.e. closest) match
1675          * that reaches each position.  */
1676         BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1677         for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1678              len <= longest_match_len; len++) {
1679
1680                 LZX_ASSERT(match_idx < num_possible_matches);
1681
1682                 ctx->optimum[len].queue = ctx->optimum[0].queue;
1683                 ctx->optimum[len].prev.link = 0;
1684                 ctx->optimum[len].prev.match_offset = possible_matches[match_idx].offset;
1685                 ctx->optimum[len].cost = lzx_match_cost(len,
1686                                                         possible_matches[match_idx].offset,
1687                                                         &ctx->costs,
1688                                                         &ctx->optimum[len].queue);
1689                 if (len == possible_matches[match_idx].len)
1690                         match_idx--;
1691         }
1692
1693         unsigned cur_pos = 0;
1694
1695         /* len_end: greatest index forward at which costs have been calculated
1696          * so far  */
1697         unsigned len_end = longest_match_len;
1698
1699         for (;;) {
1700                 /* Advance to next position.  */
1701                 cur_pos++;
1702
1703                 if (cur_pos == len_end || cur_pos == LZX_OPTIM_ARRAY_SIZE)
1704                         return lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1705
1706                 /* retrieve the number of matches available at this position  */
1707                 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->optimum[cur_pos].queue,
1708                                                                   &possible_matches);
1709
1710                 unsigned new_len = 0;
1711
1712                 if (num_possible_matches != 0) {
1713                         new_len = possible_matches[0].len;
1714
1715                         /* Greedy heuristic:  if we found a match greater than
1716                          * the number of fast bytes, stop immediately.  */
1717                         if (new_len > ctx->params.alg_params.slow.num_fast_bytes) {
1718
1719                                 /* Build the list of matches to return and get
1720                                  * the first one.  */
1721                                 match = lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1722
1723                                 /* Append the long match to the end of the list.  */
1724                                 ctx->optimum[cur_pos].next.match_offset =
1725                                         possible_matches[0].offset;
1726                                 ctx->optimum[cur_pos].next.link = cur_pos + new_len;
1727                                 ctx->optimum_end_idx = cur_pos + new_len;
1728
1729                                 /* Skip over the remaining bytes of the long match.  */
1730                                 lzx_lz_skip_bytes(ctx, new_len - 1);
1731
1732                                 /* Return first match in the list  */
1733                                 return match;
1734                         }
1735                 }
1736
1737                 /* Consider proceeding with a literal byte.  */
1738                 block_cost_t cur_cost = ctx->optimum[cur_pos].cost;
1739                 block_cost_t cur_plus_literal_cost = cur_cost +
1740                         lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1741                                          &ctx->costs);
1742                 if (cur_plus_literal_cost < ctx->optimum[cur_pos + 1].cost) {
1743                         ctx->optimum[cur_pos + 1].cost = cur_plus_literal_cost;
1744                         ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1745                         ctx->optimum[cur_pos + 1].queue = ctx->optimum[cur_pos].queue;
1746                 }
1747
1748                 if (num_possible_matches == 0)
1749                         continue;
1750
1751                 /* Consider proceeding with a match.  */
1752
1753                 while (len_end < cur_pos + new_len)
1754                         ctx->optimum[++len_end].cost = INFINITE_BLOCK_COST;
1755
1756                 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1757                      len <= new_len; len++) {
1758                         LZX_ASSERT(match_idx < num_possible_matches);
1759                         struct lzx_lru_queue q = ctx->optimum[cur_pos].queue;
1760                         block_cost_t cost = cur_cost + lzx_match_cost(len,
1761                                                                       possible_matches[match_idx].offset,
1762                                                                       &ctx->costs,
1763                                                                       &q);
1764
1765                         if (cost < ctx->optimum[cur_pos + len].cost) {
1766                                 ctx->optimum[cur_pos + len].cost = cost;
1767                                 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1768                                 ctx->optimum[cur_pos + len].prev.match_offset =
1769                                                 possible_matches[match_idx].offset;
1770                                 ctx->optimum[cur_pos + len].queue = q;
1771                         }
1772
1773                         if (len == possible_matches[match_idx].len)
1774                                 match_idx--;
1775                 }
1776         }
1777 }
1778
1779 /*
1780  * Set default symbol costs.
1781  */
1782 static void
1783 lzx_set_default_costs(struct lzx_costs * costs, unsigned num_main_syms)
1784 {
1785         unsigned i;
1786
1787         /* Literal symbols  */
1788         for (i = 0; i < LZX_NUM_CHARS; i++)
1789                 costs->main[i] = 8;
1790
1791         /* Match header symbols  */
1792         for (; i < num_main_syms; i++)
1793                 costs->main[i] = 10;
1794
1795         /* Length symbols  */
1796         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1797                 costs->len[i] = 8;
1798
1799         /* Aligned offset symbols  */
1800         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1801                 costs->aligned[i] = 3;
1802 }
1803
1804 /* Given the frequencies of symbols in a compressed block and the corresponding
1805  * Huffman codes, return LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM if an
1806  * aligned offset or verbatim block, respectively, will take fewer bits to
1807  * output.  */
1808 static int
1809 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1810                                const struct lzx_codes * codes)
1811 {
1812         unsigned aligned_cost = 0;
1813         unsigned verbatim_cost = 0;
1814
1815         /* Verbatim blocks have a constant 3 bits per position footer.  Aligned
1816          * offset blocks have an aligned offset symbol per position footer, plus
1817          * an extra 24 bits to output the lengths necessary to reconstruct the
1818          * aligned offset code itself.  */
1819         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1820                 verbatim_cost += 3 * freqs->aligned[i];
1821                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1822         }
1823         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1824         if (aligned_cost < verbatim_cost)
1825                 return LZX_BLOCKTYPE_ALIGNED;
1826         else
1827                 return LZX_BLOCKTYPE_VERBATIM;
1828 }
1829
1830 /* Find a near-optimal sequence of matches/literals with which to output the
1831  * specified LZX block, then set its type to that which has the minimum cost to
1832  * output.  */
1833 static void
1834 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1835                    unsigned num_passes)
1836 {
1837         const struct lzx_lru_queue orig_queue = ctx->queue;
1838         struct lzx_freqs freqs;
1839
1840         unsigned orig_window_pos = spec->window_pos;
1841         unsigned orig_cached_pos = ctx->cached_matches_pos;
1842
1843         LZX_ASSERT(ctx->match_window_pos == spec->window_pos);
1844
1845         ctx->match_window_end = spec->window_pos + spec->block_size;
1846         spec->chosen_matches_start_pos = spec->window_pos;
1847
1848         LZX_ASSERT(num_passes >= 1);
1849
1850         /* The first optimal parsing pass is done using the cost model already
1851          * set in ctx->costs.  Each later pass is done using a cost model
1852          * computed from the previous pass.  */
1853         for (unsigned pass = 0; pass < num_passes; pass++) {
1854
1855                 ctx->match_window_pos = orig_window_pos;
1856                 ctx->cached_matches_pos = orig_cached_pos;
1857                 ctx->queue = orig_queue;
1858                 spec->num_chosen_matches = 0;
1859                 memset(&freqs, 0, sizeof(freqs));
1860
1861                 for (unsigned i = spec->window_pos; i < spec->window_pos + spec->block_size; ) {
1862                         struct raw_match raw_match;
1863                         struct lzx_match lzx_match;
1864
1865                         raw_match = lzx_lz_get_near_optimal_match(ctx);
1866                         if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1867                                 lzx_match.data = lzx_tally_match(raw_match.len, raw_match.offset,
1868                                                                  &freqs, &ctx->queue);
1869                                 i += raw_match.len;
1870                         } else {
1871                                 lzx_match.data = lzx_tally_literal(ctx->window[i], &freqs);
1872                                 i += 1;
1873                         }
1874                         ctx->chosen_matches[spec->chosen_matches_start_pos +
1875                                             spec->num_chosen_matches++] = lzx_match;
1876                 }
1877
1878                 lzx_make_huffman_codes(&freqs, &spec->codes,
1879                                        ctx->num_main_syms);
1880                 if (pass < num_passes - 1)
1881                         lzx_set_costs(ctx, &spec->codes.lens);
1882                 ctx->matches_cached = true;
1883         }
1884         spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
1885         ctx->matches_cached = false;
1886 }
1887
1888 static void
1889 lzx_optimize_blocks(struct lzx_compressor *ctx)
1890 {
1891         lzx_lru_queue_init(&ctx->queue);
1892         ctx->optimum_cur_idx = 0;
1893         ctx->optimum_end_idx = 0;
1894
1895         const unsigned num_passes = ctx->params.alg_params.slow.num_optim_passes;
1896
1897         for (unsigned i = 0; i < ctx->num_blocks; i++)
1898                 lzx_optimize_block(ctx, &ctx->block_specs[i], num_passes);
1899 }
1900
1901 /* Initialize the suffix array match-finder for the specified input.  */
1902 static void
1903 lzx_lz_init_matchfinder(const u8 T[const restrict],
1904                         const input_idx_t n,
1905                         input_idx_t SA[const restrict],
1906                         input_idx_t ISA[const restrict],
1907                         input_idx_t LCP[const restrict],
1908                         struct salink link[const restrict],
1909                         const unsigned max_match_len)
1910 {
1911         /* Compute SA (Suffix Array).  */
1912
1913         {
1914                 /* ISA and link are used as temporary space.  */
1915                 BUILD_BUG_ON(LZX_MIN_WINDOW_SIZE * sizeof(ISA[0]) < 256 * sizeof(saidx_t));
1916                 BUILD_BUG_ON(LZX_MIN_WINDOW_SIZE * 2 * sizeof(link[0]) < 256 * 256 * sizeof(saidx_t));
1917
1918                 if (sizeof(input_idx_t) == sizeof(saidx_t)) {
1919                         divsufsort(T, SA, n, (saidx_t*)ISA, (saidx_t*)link);
1920                 } else {
1921                         saidx_t sa[n];
1922                         divsufsort(T, sa, n, (saidx_t*)ISA, (saidx_t*)link);
1923                         for (input_idx_t i = 0; i < n; i++)
1924                                 SA[i] = sa[i];
1925                 }
1926         }
1927
1928 #ifdef ENABLE_LZX_DEBUG
1929
1930         LZX_ASSERT(n > 0);
1931
1932         /* Verify suffix array.  */
1933         {
1934                 bool found[n];
1935                 ZERO_ARRAY(found);
1936                 for (input_idx_t r = 0; r < n; r++) {
1937                         input_idx_t i = SA[r];
1938                         LZX_ASSERT(i < n);
1939                         LZX_ASSERT(!found[i]);
1940                         found[i] = true;
1941                 }
1942         }
1943
1944         for (input_idx_t r = 0; r < n - 1; r++) {
1945
1946                 input_idx_t i1 = SA[r];
1947                 input_idx_t i2 = SA[r + 1];
1948
1949                 input_idx_t n1 = n - i1;
1950                 input_idx_t n2 = n - i2;
1951
1952                 LZX_ASSERT(memcmp(&T[i1], &T[i2], min(n1, n2)) <= 0);
1953         }
1954         LZX_DEBUG("Verified SA (len %u)", n);
1955 #endif /* ENABLE_LZX_DEBUG */
1956
1957         /* Compute ISA (Inverse Suffix Array)  */
1958         for (input_idx_t r = 0; r < n; r++)
1959                 ISA[SA[r]] = r;
1960
1961         /* Compute LCP (longest common prefix) array.
1962          *
1963          * Algorithm adapted from Kasai et al. 2001: "Linear-Time
1964          * Longest-Common-Prefix Computation in Suffix Arrays and Its
1965          * Applications".  */
1966         {
1967                 input_idx_t h = 0;
1968                 for (input_idx_t i = 0; i < n; i++) {
1969                         input_idx_t r = ISA[i];
1970                         if (r > 0) {
1971                                 input_idx_t j = SA[r - 1];
1972
1973                                 input_idx_t lim = min(n - i, n - j);
1974
1975                                 while (h < lim && T[i + h] == T[j + h])
1976                                         h++;
1977                                 LCP[r] = h;
1978                                 if (h > 0)
1979                                         h--;
1980                         }
1981                 }
1982         }
1983
1984 #ifdef ENABLE_LZX_DEBUG
1985         /* Verify LCP array.  */
1986         for (input_idx_t r = 0; r < n - 1; r++) {
1987                 LZX_ASSERT(ISA[SA[r]] == r);
1988                 LZX_ASSERT(ISA[SA[r + 1]] == r + 1);
1989
1990                 input_idx_t i1 = SA[r];
1991                 input_idx_t i2 = SA[r + 1];
1992                 input_idx_t lcp = LCP[r + 1];
1993
1994                 input_idx_t n1 = n - i1;
1995                 input_idx_t n2 = n - i2;
1996
1997                 LZX_ASSERT(lcp <= min(n1, n2));
1998
1999                 LZX_ASSERT(memcmp(&T[i1], &T[i2], lcp) == 0);
2000                 if (lcp < min(n1, n2))
2001                         LZX_ASSERT(T[i1 + lcp] != T[i2 + lcp]);
2002         }
2003 #endif /* ENABLE_LZX_DEBUG */
2004
2005         /* Compute salink.next and salink.lcpnext.
2006          *
2007          * Algorithm adapted from Crochemore et al. 2009:
2008          * "LPF computation revisited".
2009          *
2010          * Note: we cap lcpnext to the maximum match length so that the
2011          * match-finder need not worry about it later.  */
2012         link[n - 1].next = (input_idx_t)~0U;
2013         link[n - 1].prev = (input_idx_t)~0U;
2014         link[n - 1].lcpnext = 0;
2015         link[n - 1].lcpprev = 0;
2016         for (input_idx_t r = n - 2; r != (input_idx_t)~0U; r--) {
2017                 input_idx_t t = r + 1;
2018                 input_idx_t l = LCP[t];
2019                 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2020                         l = min(l, link[t].lcpnext);
2021                         t = link[t].next;
2022                 }
2023                 link[r].next = t;
2024                 link[r].lcpnext = min(l, max_match_len);
2025                 LZX_ASSERT(t == (input_idx_t)~0U || l <= n - SA[t]);
2026                 LZX_ASSERT(l <= n - SA[r]);
2027                 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2028         }
2029
2030         /* Compute salink.prev and salink.lcpprev.
2031          *
2032          * Algorithm adapted from Crochemore et al. 2009:
2033          * "LPF computation revisited".
2034          *
2035          * Note: we cap lcpprev to the maximum match length so that the
2036          * match-finder need not worry about it later.  */
2037         link[0].prev = (input_idx_t)~0;
2038         link[0].next = (input_idx_t)~0;
2039         link[0].lcpprev = 0;
2040         link[0].lcpnext = 0;
2041         for (input_idx_t r = 1; r < n; r++) {
2042                 input_idx_t t = r - 1;
2043                 input_idx_t l = LCP[r];
2044                 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2045                         l = min(l, link[t].lcpprev);
2046                         t = link[t].prev;
2047                 }
2048                 link[r].prev = t;
2049                 link[r].lcpprev = min(l, max_match_len);
2050                 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2051                 LZX_ASSERT(l <= n - SA[r]);
2052                 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2053         }
2054 }
2055
2056 /* Prepare the input window into one or more LZX blocks ready to be output.  */
2057 static void
2058 lzx_prepare_blocks(struct lzx_compressor * ctx)
2059 {
2060         /* Initialize the match-finder.  */
2061         lzx_lz_init_matchfinder(ctx->window, ctx->window_size,
2062                                 ctx->SA, ctx->ISA, ctx->LCP, ctx->salink,
2063                                 LZX_MAX_MATCH_LEN);
2064         ctx->cached_matches_pos = 0;
2065         ctx->matches_cached = false;
2066         ctx->match_window_pos = 0;
2067
2068         /* Set up a default cost model.  */
2069         lzx_set_default_costs(&ctx->costs, ctx->num_main_syms);
2070
2071         ctx->num_blocks = DIV_ROUND_UP(ctx->window_size, LZX_DIV_BLOCK_SIZE);
2072         for (unsigned i = 0; i < ctx->num_blocks; i++) {
2073                 unsigned pos = LZX_DIV_BLOCK_SIZE * i;
2074                 ctx->block_specs[i].window_pos = pos;
2075                 ctx->block_specs[i].block_size = min(ctx->window_size - pos, LZX_DIV_BLOCK_SIZE);
2076         }
2077
2078         /* Determine sequence of matches/literals to output for each block.  */
2079         lzx_optimize_blocks(ctx);
2080 }
2081
2082 /*
2083  * This is the fast version of lzx_prepare_blocks().  This version "quickly"
2084  * prepares a single compressed block containing the entire input.  See the
2085  * description of the "Fast algorithm" at the beginning of this file for more
2086  * information.
2087  *
2088  * Input ---  the preprocessed data:
2089  *
2090  *      ctx->window[]
2091  *      ctx->window_size
2092  *
2093  * Output --- the block specification and the corresponding match/literal data:
2094  *
2095  *      ctx->block_specs[]
2096  *      ctx->num_blocks
2097  *      ctx->chosen_matches[]
2098  */
2099 static void
2100 lzx_prepare_block_fast(struct lzx_compressor * ctx)
2101 {
2102         struct lzx_record_ctx record_ctx;
2103         struct lzx_block_spec *spec;
2104
2105         /* Parameters to hash chain LZ match finder
2106          * (lazy with 1 match lookahead)  */
2107         static const struct lz_params lzx_lz_params = {
2108                 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
2109                  * aren't worth choosing when using greedy or lazy parsing.  */
2110                 .min_match      = 3,
2111                 .max_match      = LZX_MAX_MATCH_LEN,
2112                 .max_offset     = LZX_MAX_WINDOW_SIZE,
2113                 .good_match     = LZX_MAX_MATCH_LEN,
2114                 .nice_match     = LZX_MAX_MATCH_LEN,
2115                 .max_chain_len  = LZX_MAX_MATCH_LEN,
2116                 .max_lazy_match = LZX_MAX_MATCH_LEN,
2117                 .too_far        = 4096,
2118         };
2119
2120         /* Initialize symbol frequencies and match offset LRU queue.  */
2121         memset(&record_ctx.freqs, 0, sizeof(struct lzx_freqs));
2122         lzx_lru_queue_init(&record_ctx.queue);
2123         record_ctx.matches = ctx->chosen_matches;
2124
2125         /* Determine series of matches/literals to output.  */
2126         lz_analyze_block(ctx->window,
2127                          ctx->window_size,
2128                          lzx_record_match,
2129                          lzx_record_literal,
2130                          &record_ctx,
2131                          &lzx_lz_params,
2132                          ctx->prev_tab);
2133
2134         /* Set up block specification.  */
2135         spec = &ctx->block_specs[0];
2136         spec->block_type = LZX_BLOCKTYPE_ALIGNED;
2137         spec->window_pos = 0;
2138         spec->block_size = ctx->window_size;
2139         spec->num_chosen_matches = (record_ctx.matches - ctx->chosen_matches);
2140         spec->chosen_matches_start_pos = 0;
2141         lzx_make_huffman_codes(&record_ctx.freqs, &spec->codes,
2142                                ctx->num_main_syms);
2143         ctx->num_blocks = 1;
2144 }
2145
2146 static void
2147 do_call_insn_translation(u32 *call_insn_target, int input_pos,
2148                          s32 file_size)
2149 {
2150         s32 abs_offset;
2151         s32 rel_offset;
2152
2153         rel_offset = le32_to_cpu(*call_insn_target);
2154         if (rel_offset >= -input_pos && rel_offset < file_size) {
2155                 if (rel_offset < file_size - input_pos) {
2156                         /* "good translation" */
2157                         abs_offset = rel_offset + input_pos;
2158                 } else {
2159                         /* "compensating translation" */
2160                         abs_offset = rel_offset - file_size;
2161                 }
2162                 *call_insn_target = cpu_to_le32(abs_offset);
2163         }
2164 }
2165
2166 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
2167  * See the comment above that function for more information.  */
2168 static void
2169 do_call_insn_preprocessing(u8 data[], int size)
2170 {
2171         for (int i = 0; i < size - 10; i++) {
2172                 if (data[i] == 0xe8) {
2173                         do_call_insn_translation((u32*)&data[i + 1], i,
2174                                                  LZX_WIM_MAGIC_FILESIZE);
2175                         i += 4;
2176                 }
2177         }
2178 }
2179
2180 static size_t
2181 lzx_compress(const void *uncompressed_data, size_t uncompressed_size,
2182              void *compressed_data, size_t compressed_size_avail, void *_ctx)
2183 {
2184         struct lzx_compressor *ctx = _ctx;
2185         struct output_bitstream ostream;
2186         size_t compressed_size;
2187
2188         if (uncompressed_size < 100) {
2189                 LZX_DEBUG("Too small to bother compressing.");
2190                 return 0;
2191         }
2192
2193         if (uncompressed_size > ctx->max_window_size) {
2194                 LZX_DEBUG("Can't compress %zu bytes using window of %u bytes!",
2195                           uncompressed_size, ctx->max_window_size);
2196                 return 0;
2197         }
2198
2199         LZX_DEBUG("Attempting to compress %zu bytes...",
2200                   uncompressed_size);
2201
2202         /* The input data must be preprocessed.  To avoid changing the original
2203          * input, copy it to a temporary buffer.  */
2204         memcpy(ctx->window, uncompressed_data, uncompressed_size);
2205         ctx->window_size = uncompressed_size;
2206
2207         /* This line is unnecessary; it just avoids inconsequential accesses of
2208          * uninitialized memory that would show up in memory-checking tools such
2209          * as valgrind.  */
2210         memset(&ctx->window[ctx->window_size], 0, 12);
2211
2212         LZX_DEBUG("Preprocessing data...");
2213
2214         /* Before doing any actual compression, do the call instruction (0xe8
2215          * byte) translation on the uncompressed data.  */
2216         do_call_insn_preprocessing(ctx->window, ctx->window_size);
2217
2218         LZX_DEBUG("Preparing blocks...");
2219
2220         /* Prepare the compressed data.  */
2221         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
2222                 lzx_prepare_block_fast(ctx);
2223         else
2224                 lzx_prepare_blocks(ctx);
2225
2226         LZX_DEBUG("Writing compressed blocks...");
2227
2228         /* Generate the compressed data.  */
2229         init_output_bitstream(&ostream, compressed_data, compressed_size_avail);
2230         lzx_write_all_blocks(ctx, &ostream);
2231
2232         LZX_DEBUG("Flushing bitstream...");
2233         compressed_size = flush_output_bitstream(&ostream);
2234         if (compressed_size == ~(input_idx_t)0) {
2235                 LZX_DEBUG("Data did not compress to %zu bytes or less!",
2236                           compressed_size_avail);
2237                 return 0;
2238         }
2239
2240         LZX_DEBUG("Done: compressed %zu => %zu bytes.",
2241                   uncompressed_size, compressed_size);
2242
2243         /* Verify that we really get the same thing back when decompressing.
2244          * Although this could be disabled by default in all cases, it only
2245          * takes around 2-3% of the running time of the slow algorithm to do the
2246          * verification.  */
2247         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
2248         #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
2249             || 1
2250         #endif
2251             )
2252         {
2253                 struct wimlib_decompressor *decompressor;
2254
2255                 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZX,
2256                                                     ctx->max_window_size,
2257                                                     NULL,
2258                                                     &decompressor))
2259                 {
2260                         int ret;
2261                         ret = wimlib_decompress(compressed_data,
2262                                                 compressed_size,
2263                                                 ctx->window,
2264                                                 uncompressed_size,
2265                                                 decompressor);
2266                         wimlib_free_decompressor(decompressor);
2267
2268                         if (ret) {
2269                                 ERROR("Failed to decompress data we "
2270                                       "compressed using LZX algorithm");
2271                                 wimlib_assert(0);
2272                                 return 0;
2273                         }
2274                         if (memcmp(uncompressed_data, ctx->window, uncompressed_size)) {
2275                                 ERROR("Data we compressed using LZX algorithm "
2276                                       "didn't decompress to original");
2277                                 wimlib_assert(0);
2278                                 return 0;
2279                         }
2280                 } else {
2281                         WARNING("Failed to create decompressor for "
2282                                 "data verification!");
2283                 }
2284         }
2285         return compressed_size;
2286 }
2287
2288 static bool
2289 lzx_params_valid(const struct wimlib_lzx_compressor_params *params)
2290 {
2291         /* Validate parameters.  */
2292         if (params->hdr.size != sizeof(struct wimlib_lzx_compressor_params)) {
2293                 LZX_DEBUG("Invalid parameter structure size!");
2294                 return false;
2295         }
2296
2297         if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
2298             params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
2299         {
2300                 LZX_DEBUG("Invalid algorithm.");
2301                 return false;
2302         }
2303
2304         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2305                 if (params->alg_params.slow.num_optim_passes < 1)
2306                 {
2307                         LZX_DEBUG("Invalid number of optimization passes!");
2308                         return false;
2309                 }
2310
2311                 if (params->alg_params.slow.main_nostat_cost < 1 ||
2312                     params->alg_params.slow.main_nostat_cost > 16)
2313                 {
2314                         LZX_DEBUG("Invalid main_nostat_cost!");
2315                         return false;
2316                 }
2317
2318                 if (params->alg_params.slow.len_nostat_cost < 1 ||
2319                     params->alg_params.slow.len_nostat_cost > 16)
2320                 {
2321                         LZX_DEBUG("Invalid len_nostat_cost!");
2322                         return false;
2323                 }
2324
2325                 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
2326                     params->alg_params.slow.aligned_nostat_cost > 8)
2327                 {
2328                         LZX_DEBUG("Invalid aligned_nostat_cost!");
2329                         return false;
2330                 }
2331         }
2332         return true;
2333 }
2334
2335 static void
2336 lzx_free_compressor(void *_ctx)
2337 {
2338         struct lzx_compressor *ctx = _ctx;
2339
2340         if (ctx) {
2341                 FREE(ctx->chosen_matches);
2342                 FREE(ctx->cached_matches);
2343                 FREE(ctx->optimum);
2344                 FREE(ctx->salink);
2345                 FREE(ctx->SA);
2346                 FREE(ctx->block_specs);
2347                 FREE(ctx->prev_tab);
2348                 FREE(ctx->window);
2349                 FREE(ctx);
2350         }
2351 }
2352
2353 static int
2354 lzx_create_compressor(size_t window_size,
2355                       const struct wimlib_compressor_params_header *_params,
2356                       void **ctx_ret)
2357 {
2358         const struct wimlib_lzx_compressor_params *params =
2359                 (const struct wimlib_lzx_compressor_params*)_params;
2360         struct lzx_compressor *ctx;
2361
2362         LZX_DEBUG("Allocating LZX context...");
2363
2364         if (!lzx_window_size_valid(window_size))
2365                 return WIMLIB_ERR_INVALID_PARAM;
2366
2367         static const struct wimlib_lzx_compressor_params fast_default = {
2368                 .hdr = {
2369                         .size = sizeof(struct wimlib_lzx_compressor_params),
2370                 },
2371                 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
2372                 .use_defaults = 0,
2373                 .alg_params = {
2374                         .fast = {
2375                         },
2376                 },
2377         };
2378         static const struct wimlib_lzx_compressor_params slow_default = {
2379                 .hdr = {
2380                         .size = sizeof(struct wimlib_lzx_compressor_params),
2381                 },
2382                 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
2383                 .use_defaults = 0,
2384                 .alg_params = {
2385                         .slow = {
2386                                 .use_len2_matches = 1,
2387                                 .num_fast_bytes = 32,
2388                                 .num_optim_passes = 2,
2389                                 .max_search_depth = 50,
2390                                 .max_matches_per_pos = 3,
2391                                 .main_nostat_cost = 15,
2392                                 .len_nostat_cost = 15,
2393                                 .aligned_nostat_cost = 7,
2394                         },
2395                 },
2396         };
2397
2398         if (params) {
2399                 if (!lzx_params_valid(params))
2400                         return WIMLIB_ERR_INVALID_PARAM;
2401         } else {
2402                 LZX_DEBUG("Using default algorithm and parameters.");
2403                 params = &slow_default;
2404         }
2405
2406         if (params->use_defaults) {
2407                 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2408                         params = &slow_default;
2409                 else
2410                         params = &fast_default;
2411         }
2412
2413         LZX_DEBUG("Allocating memory.");
2414
2415         ctx = CALLOC(1, sizeof(struct lzx_compressor));
2416         if (ctx == NULL)
2417                 goto oom;
2418
2419         ctx->num_main_syms = lzx_get_num_main_syms(window_size);
2420         ctx->max_window_size = window_size;
2421         ctx->window = MALLOC(window_size + 12);
2422         if (ctx->window == NULL)
2423                 goto oom;
2424
2425         if (params->algorithm == WIMLIB_LZX_ALGORITHM_FAST) {
2426                 ctx->prev_tab = MALLOC(window_size * sizeof(ctx->prev_tab[0]));
2427                 if (ctx->prev_tab == NULL)
2428                         goto oom;
2429         }
2430
2431         size_t block_specs_length = DIV_ROUND_UP(window_size, LZX_DIV_BLOCK_SIZE);
2432         ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
2433         if (ctx->block_specs == NULL)
2434                 goto oom;
2435
2436         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2437                 ctx->SA = MALLOC(3U * window_size * sizeof(ctx->SA[0]));
2438                 if (ctx->SA == NULL)
2439                         goto oom;
2440                 ctx->ISA = ctx->SA + window_size;
2441                 ctx->LCP = ctx->ISA + window_size;
2442
2443                 ctx->salink = MALLOC(window_size * sizeof(ctx->salink[0]));
2444                 if (ctx->salink == NULL)
2445                         goto oom;
2446         }
2447
2448         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2449                 ctx->optimum = MALLOC((LZX_OPTIM_ARRAY_SIZE + LZX_MAX_MATCH_LEN) *
2450                                        sizeof(ctx->optimum[0]));
2451                 if (ctx->optimum == NULL)
2452                         goto oom;
2453         }
2454
2455         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2456                 u32 cache_per_pos;
2457
2458                 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
2459                 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
2460                         cache_per_pos = LZX_MAX_CACHE_PER_POS;
2461
2462                 ctx->cached_matches = MALLOC(window_size * (cache_per_pos + 1) *
2463                                              sizeof(ctx->cached_matches[0]));
2464                 if (ctx->cached_matches == NULL)
2465                         goto oom;
2466         }
2467
2468         ctx->chosen_matches = MALLOC(window_size * sizeof(ctx->chosen_matches[0]));
2469         if (ctx->chosen_matches == NULL)
2470                 goto oom;
2471
2472         memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_compressor_params));
2473         memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
2474
2475         LZX_DEBUG("Successfully allocated new LZX context.");
2476
2477         *ctx_ret = ctx;
2478         return 0;
2479
2480 oom:
2481         lzx_free_compressor(ctx);
2482         return WIMLIB_ERR_NOMEM;
2483 }
2484
2485 const struct compressor_ops lzx_compressor_ops = {
2486         .create_compressor  = lzx_create_compressor,
2487         .compress           = lzx_compress,
2488         .free_compressor    = lzx_free_compressor,
2489 };