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