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