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