]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
Merge LZX compressor updates
[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 #if 0
1626 static struct raw_match
1627 lzx_lz_get_greedy_match(struct lzx_compressor * ctx)
1628 {
1629         struct raw_match *matches;
1630
1631         if (!lzx_lz_get_matches_caching(ctx, &ctx->queue, &matches))
1632                 return (struct raw_match) {.len = 0};
1633
1634         lzx_lz_skip_bytes(ctx, matches[0].len - 1);
1635         return matches[0];
1636 }
1637 #endif
1638
1639 #if 0
1640 static struct raw_match
1641 lzx_lz_get_lazy_match(struct lzx_compressor * ctx)
1642 {
1643         unsigned num_matches;
1644         struct raw_match *matches;
1645         struct raw_match prev_match;
1646         struct lzx_lru_queue queue;
1647
1648         if (ctx->optimum_cur_idx != ctx->optimum_end_idx)
1649                 goto retopt;
1650
1651         /* Check for matches at first position.  */
1652         num_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &matches);
1653
1654         /* Return literal if no matches were found.  */
1655         if (num_matches == 0)
1656                 return (struct raw_match) { .len = 0 };
1657
1658         /* Immediately choose match if longer than threshold.  */
1659         if (matches[0].len > ctx->params.alg_params.slow.num_fast_bytes)
1660                 goto savecur;
1661
1662         ctx->optimum_cur_idx = ctx->optimum_end_idx = 0;
1663         for (;;) {
1664                 prev_match = matches[0];
1665
1666                 /* Check for matches at next position.  */
1667                 num_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &matches);
1668
1669                 /* Choose previous match if there is not a match at this
1670                  * position.  */
1671                 if (num_matches == 0)
1672                         goto saveprev;
1673
1674                 /* Choose previous match the longest match at the next position
1675                  * is the same place, just one character shifted over.  */
1676                 if (matches[0].offset == prev_match.offset ||
1677                     matches[0].len < prev_match.len)
1678                         goto saveprev;
1679
1680                 struct lzx_lru_queue q1 = ctx->queue, q2 = ctx->queue;
1681                 double lazycost = lzx_literal_cost(ctx->window[ctx->match_window_pos - 2],
1682                                                      &ctx->costs) +
1683                                     lzx_match_cost(matches[0].len, matches[0].offset,
1684                                                    &ctx->costs, &q1);
1685                 double greedycost = lzx_match_cost(prev_match.len, prev_match.offset,
1686                                                      &ctx->costs, &q2);
1687                 lazycost *= (double)prev_match.len / (1 + matches[0].len);
1688
1689                 /* Choose previous match if greedy cost was lower.  */
1690                 if (greedycost <= lazycost)
1691                         goto saveprev;
1692
1693                 /* Choose literal at the previous position.  */
1694                 ctx->optimum[ctx->optimum_end_idx++].next.link = 0;
1695
1696
1697                 /* Immediately choose match if longer than threshold.  */
1698                 if (matches[0].len > ctx->params.alg_params.slow.num_fast_bytes)
1699                         goto savecur;
1700         }
1701
1702 savecur:
1703         lzx_lz_skip_bytes(ctx, 1);
1704         prev_match = matches[0];
1705
1706 saveprev:
1707         lzx_lz_skip_bytes(ctx, prev_match.len - 2);
1708         ctx->optimum[ctx->optimum_end_idx].next.link = prev_match.len;
1709         ctx->optimum[ctx->optimum_end_idx].next.match_offset = prev_match.offset;
1710         ctx->optimum_end_idx++;
1711 retopt:
1712         prev_match.len = ctx->optimum[ctx->optimum_cur_idx].next.link;
1713         prev_match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1714         ctx->optimum_cur_idx++;
1715         return prev_match;
1716 }
1717 #endif
1718
1719
1720 /*
1721  * lzx_lz_get_near_optimal_match() -
1722  *
1723  * Choose the optimal match or literal to use at the next position in the input.
1724  *
1725  * Unlike a greedy parser that always takes the longest match, or even a
1726  * parser with one match/literal look-ahead like zlib, the algorithm used here
1727  * may look ahead many matches/literals to determine the optimal match/literal to
1728  * output next.  The motivation is that the compression ratio is improved if the
1729  * compressor can do things like use a shorter-than-possible match in order to
1730  * allow a longer match later, and also take into account the Huffman code cost
1731  * model rather than simply assuming that longer is better.
1732  *
1733  * Still, this is not truly an optimal parser because very long matches are
1734  * taken immediately.  This is done to avoid considering many different
1735  * alternatives that are unlikely to significantly be better.
1736  *
1737  * This algorithm is based on that used in 7-Zip's DEFLATE encoder.
1738  *
1739  * Each call to this function does one of two things:
1740  *
1741  * 1. Build a near-optimal sequence of matches/literals, up to some point, that
1742  *    will be returned by subsequent calls to this function, then return the
1743  *    first one.
1744  *
1745  * OR
1746  *
1747  * 2. Return the next match/literal previously computed by a call to this
1748  *    function;
1749  *
1750  * This function relies on the following state in the compressor context:
1751  *
1752  *      ctx->window          (read-only: preprocessed data being compressed)
1753  *      ctx->cost            (read-only: cost model to use)
1754  *      ctx->optimum         (internal state; leave uninitialized)
1755  *      ctx->optimum_cur_idx (must set to 0 before first call)
1756  *      ctx->optimum_end_idx (must set to 0 before first call)
1757  *      ctx->SA              (must be built before first call)
1758  *      ctx->ISA             (must be built before first call)
1759  *      ctx->salink          (must be built before first call)
1760  *      ctx->match_window_pos (must initialize to position of next match to
1761  *                             return; subsequent calls return subsequent
1762  *                             matches)
1763  *      ctx->match_window_end (must initialize to limit of match-finding region;
1764  *                             subsequent calls use the same limit)
1765  *
1766  * The return value is a (length, offset) pair specifying the match or literal
1767  * chosen.  For literals, the length is less than LZX_MIN_MATCH_LEN and the
1768  * offset is meaningless.
1769  */
1770 static struct raw_match
1771 lzx_lz_get_near_optimal_match(struct lzx_compressor * ctx)
1772 {
1773         unsigned num_possible_matches;
1774         struct raw_match *possible_matches;
1775         struct raw_match match;
1776         unsigned longest_match_len;
1777
1778         if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
1779                 /* Case 2: Return the next match/literal already found.  */
1780                 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
1781                                     ctx->optimum_cur_idx;
1782                 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1783
1784                 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
1785                 return match;
1786         }
1787
1788         /* Case 1:  Compute a new list of matches/literals to return.  */
1789
1790         ctx->optimum_cur_idx = 0;
1791         ctx->optimum_end_idx = 0;
1792
1793         /* Get matches at this position.  */
1794         num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->queue, &possible_matches);
1795
1796         /* If no matches found, return literal.  */
1797         if (num_possible_matches == 0)
1798                 return (struct raw_match){ .len = 0 };
1799
1800         /* The matches that were found are sorted in decreasing order by length.
1801          * Get the length of the longest one.  */
1802         longest_match_len = possible_matches[0].len;
1803
1804         /* Greedy heuristic:  if the longest match that was found is greater
1805          * than the number of fast bytes, return it immediately; don't both
1806          * doing more work.  */
1807         if (longest_match_len > ctx->params.alg_params.slow.num_fast_bytes) {
1808                 lzx_lz_skip_bytes(ctx, longest_match_len - 1);
1809                 return possible_matches[0];
1810         }
1811
1812         /* Calculate the cost to reach the next position by outputting a
1813          * literal.  */
1814         ctx->optimum[0].queue = ctx->queue;
1815         ctx->optimum[1].queue = ctx->optimum[0].queue;
1816         ctx->optimum[1].cost = lzx_literal_cost(ctx->window[ctx->match_window_pos],
1817                                                 &ctx->costs);
1818         ctx->optimum[1].prev.link = 0;
1819
1820         /* Calculate the cost to reach any position up to and including that
1821          * reached by the longest match, using the shortest (i.e. closest) match
1822          * that reaches each position.  */
1823         BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1824         for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1825              len <= longest_match_len; len++) {
1826
1827                 LZX_ASSERT(match_idx < num_possible_matches);
1828
1829                 ctx->optimum[len].queue = ctx->optimum[0].queue;
1830                 ctx->optimum[len].prev.link = 0;
1831                 ctx->optimum[len].prev.match_offset = possible_matches[match_idx].offset;
1832                 ctx->optimum[len].cost = lzx_match_cost(len,
1833                                                         possible_matches[match_idx].offset,
1834                                                         &ctx->costs,
1835                                                         &ctx->optimum[len].queue);
1836                 if (len == possible_matches[match_idx].len)
1837                         match_idx--;
1838         }
1839
1840         unsigned cur_pos = 0;
1841
1842         /* len_end: greatest index forward at which costs have been calculated
1843          * so far  */
1844         unsigned len_end = longest_match_len;
1845
1846         for (;;) {
1847                 /* Advance to next position.  */
1848                 cur_pos++;
1849
1850                 if (cur_pos == len_end || cur_pos == LZX_OPTIM_ARRAY_SIZE)
1851                         return lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1852
1853                 /* retrieve the number of matches available at this position  */
1854                 num_possible_matches = lzx_lz_get_matches_caching(ctx, &ctx->optimum[cur_pos].queue,
1855                                                                   &possible_matches);
1856
1857                 unsigned new_len = 0;
1858
1859                 if (num_possible_matches != 0) {
1860                         new_len = possible_matches[0].len;
1861
1862                         /* Greedy heuristic:  if we found a match greater than
1863                          * the number of fast bytes, stop immediately.  */
1864                         if (new_len > ctx->params.alg_params.slow.num_fast_bytes) {
1865
1866                                 /* Build the list of matches to return and get
1867                                  * the first one.  */
1868                                 match = lzx_lz_reverse_near_optimal_match_list(ctx, cur_pos);
1869
1870                                 /* Append the long match to the end of the list.  */
1871                                 ctx->optimum[cur_pos].next.match_offset =
1872                                         possible_matches[0].offset;
1873                                 ctx->optimum[cur_pos].next.link = cur_pos + new_len;
1874                                 ctx->optimum_end_idx = cur_pos + new_len;
1875
1876                                 /* Skip over the remaining bytes of the long match.  */
1877                                 lzx_lz_skip_bytes(ctx, new_len - 1);
1878
1879                                 /* Return first match in the list  */
1880                                 return match;
1881                         }
1882                 }
1883
1884                 /* Consider proceeding with a literal byte.  */
1885                 block_cost_t cur_cost = ctx->optimum[cur_pos].cost;
1886                 block_cost_t cur_plus_literal_cost = cur_cost +
1887                         lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1888                                          &ctx->costs);
1889                 if (cur_plus_literal_cost < ctx->optimum[cur_pos + 1].cost) {
1890                         ctx->optimum[cur_pos + 1].cost = cur_plus_literal_cost;
1891                         ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1892                         ctx->optimum[cur_pos + 1].queue = ctx->optimum[cur_pos].queue;
1893                 }
1894
1895                 if (num_possible_matches == 0)
1896                         continue;
1897
1898                 /* Consider proceeding with a match.  */
1899
1900                 while (len_end < cur_pos + new_len)
1901                         ctx->optimum[++len_end].cost = INFINITE_BLOCK_COST;
1902
1903                 for (unsigned len = LZX_MIN_MATCH_LEN, match_idx = num_possible_matches - 1;
1904                      len <= new_len; len++) {
1905                         LZX_ASSERT(match_idx < num_possible_matches);
1906                         struct lzx_lru_queue q = ctx->optimum[cur_pos].queue;
1907                         block_cost_t cost = cur_cost + lzx_match_cost(len,
1908                                                                       possible_matches[match_idx].offset,
1909                                                                       &ctx->costs,
1910                                                                       &q);
1911
1912                         if (cost < ctx->optimum[cur_pos + len].cost) {
1913                                 ctx->optimum[cur_pos + len].cost = cost;
1914                                 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1915                                 ctx->optimum[cur_pos + len].prev.match_offset =
1916                                                 possible_matches[match_idx].offset;
1917                                 ctx->optimum[cur_pos + len].queue = q;
1918                         }
1919
1920                         if (len == possible_matches[match_idx].len)
1921                                 match_idx--;
1922                 }
1923         }
1924 }
1925
1926 /*
1927  * Set default symbol costs.
1928  */
1929 static void
1930 lzx_set_default_costs(struct lzx_costs * costs)
1931 {
1932         unsigned i;
1933
1934         /* Literal symbols  */
1935         for (i = 0; i < LZX_NUM_CHARS; i++)
1936                 costs->main[i] = 8;
1937
1938         /* Match header symbols  */
1939         for (; i < LZX_MAINCODE_NUM_SYMBOLS; i++)
1940                 costs->main[i] = 10;
1941
1942         /* Length symbols  */
1943         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1944                 costs->len[i] = 8;
1945
1946         /* Aligned offset symbols  */
1947         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1948                 costs->aligned[i] = 3;
1949 }
1950
1951 /* Given the frequencies of symbols in a compressed block and the corresponding
1952  * Huffman codes, return LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM if an
1953  * aligned offset or verbatim block, respectively, will take fewer bits to
1954  * output.  */
1955 static int
1956 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1957                                const struct lzx_codes * codes)
1958 {
1959         unsigned aligned_cost = 0;
1960         unsigned verbatim_cost = 0;
1961
1962         /* Verbatim blocks have a constant 3 bits per position footer.  Aligned
1963          * offset blocks have an aligned offset symbol per position footer, plus
1964          * an extra 24 bits to output the lengths necessary to reconstruct the
1965          * aligned offset code itself.  */
1966         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1967                 verbatim_cost += 3 * freqs->aligned[i];
1968                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1969         }
1970         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1971         if (aligned_cost < verbatim_cost)
1972                 return LZX_BLOCKTYPE_ALIGNED;
1973         else
1974                 return LZX_BLOCKTYPE_VERBATIM;
1975 }
1976
1977 /* Find a near-optimal sequence of matches/literals with which to output the
1978  * specified LZX block, and set its type to that which has the minimum cost to
1979  * output.  */
1980 static void
1981 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1982                    unsigned num_passes)
1983 {
1984         struct lzx_lru_queue orig_queue = ctx->queue;
1985         struct lzx_freqs freqs;
1986
1987         ctx->match_window_end = spec->window_pos + spec->block_size;
1988         spec->chosen_matches_start_pos = spec->window_pos;
1989
1990         LZX_ASSERT(num_passes >= 1);
1991
1992         /* The first optimal parsing pass is done using the cost model already
1993          * set in ctx->costs.  Each later pass is done using a cost model
1994          * computed from the previous pass.  */
1995         for (unsigned pass = 0; pass < num_passes; pass++) {
1996
1997                 lzx_lz_rewind_matchfinder(ctx, spec->window_pos);
1998                 ctx->queue = orig_queue;
1999                 spec->num_chosen_matches = 0;
2000                 memset(&freqs, 0, sizeof(freqs));
2001
2002                 for (unsigned i = spec->window_pos; i < spec->window_pos + spec->block_size; ) {
2003                         struct raw_match raw_match;
2004                         struct lzx_match lzx_match;
2005
2006                         raw_match = lzx_lz_get_near_optimal_match(ctx);
2007                         if (raw_match.len >= LZX_MIN_MATCH_LEN) {
2008                                 lzx_match.data = lzx_record_match(raw_match.offset, raw_match.len,
2009                                                                   &freqs, &ctx->queue);
2010                                 i += raw_match.len;
2011                         } else {
2012                                 lzx_match.data = lzx_record_literal(ctx->window[i], &freqs);
2013                                 i += 1;
2014                         }
2015                         ctx->chosen_matches[spec->chosen_matches_start_pos +
2016                                             spec->num_chosen_matches++] = lzx_match;
2017                 }
2018
2019                 lzx_make_huffman_codes(&freqs, &spec->codes);
2020                 if (pass < num_passes - 1)
2021                         lzx_set_costs(ctx, &spec->codes.lens);
2022         }
2023         spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
2024 }
2025
2026 static void
2027 lzx_optimize_blocks(struct lzx_compressor *ctx)
2028 {
2029         lzx_lru_queue_init(&ctx->queue);
2030         ctx->optimum_cur_idx = 0;
2031         ctx->optimum_end_idx = 0;
2032
2033         const unsigned num_passes = ctx->params.alg_params.slow.num_optim_passes;
2034
2035         for (unsigned i = 0; i < ctx->num_blocks; i++)
2036                 lzx_optimize_block(ctx, &ctx->block_specs[i], num_passes);
2037 }
2038
2039 static bool entropy_val_tab_inited = false;
2040 static double entropy_val_tab[LZX_MAX_WINDOW_SIZE];
2041 static pthread_mutex_t entropy_val_tab_mutex = PTHREAD_MUTEX_INITIALIZER;
2042
2043 static double entropy_val(unsigned count)
2044 {
2045         /*return count * log(count);*/
2046         return entropy_val_tab[count];
2047 }
2048
2049 /* Split a LZX block into several if it is advantageous to do so.
2050  *
2051  * TODO:  This doesn't work very well yet.  Should optimal parsing be done
2052  * before or after splitting?  */
2053 static void
2054 lzx_block_split(const u32 matches[restrict],
2055                 const input_idx_t n,
2056                 const double epsilon,
2057                 const unsigned max_num_blocks,
2058                 const unsigned min_block_len,
2059                 struct lzx_block_spec block_specs[restrict],
2060                 unsigned * const restrict num_blocks_ret)
2061 {
2062         const double block_overhead = 1500;
2063
2064         if (!entropy_val_tab_inited) {
2065                 pthread_mutex_lock(&entropy_val_tab_mutex);
2066                 if (!entropy_val_tab_inited) {
2067                         entropy_val_tab[0] = 0;
2068                         for (input_idx_t i = 1; i < LZX_MAX_WINDOW_SIZE; i++)
2069                                 entropy_val_tab[i] = i * log2(i);
2070                         entropy_val_tab_inited = true;
2071                 }
2072                 pthread_mutex_unlock(&entropy_val_tab_mutex);
2073         }
2074
2075         u16 main_syms[n];
2076         u8 len_syms[n];
2077         u8 aligned_syms[n];
2078         input_idx_t orig_input_indices[n + 1];
2079
2080         LZX_ASSERT(epsilon >= 0);
2081         LZX_ASSERT(max_num_blocks >= 1);
2082
2083         /* For convenience, extract the main, length, and aligned symbols from
2084          * the matches.  Every position will have a main symbol, but not every
2085          * position will have a length and aligned symbol.  Special values
2086          * larger than the valid symbols are used to indicate the absense of a
2087          * symbol. */
2088         orig_input_indices[0] = 0;
2089         for (input_idx_t i = 0, orig_input_idx = 0; i < n; i++) {
2090                 u32 match = matches[i];
2091                 u16 main_sym;
2092                 u8 len_sym = LZX_LENCODE_NUM_SYMBOLS;
2093                 u8 aligned_sym = LZX_ALIGNEDCODE_NUM_SYMBOLS;
2094                 if (match & 0x80000000) {
2095                         unsigned match_len_minus_2 = match & 0xff;
2096                         unsigned position_footer = (match >> 8) & 0x1ffff;
2097                         unsigned position_slot = (match >> 25) & 0x3f;
2098                         unsigned len_header;
2099
2100                         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
2101                                 len_header = match_len_minus_2;
2102                         } else {
2103                                 len_header = LZX_NUM_PRIMARY_LENS;
2104                                 len_sym = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
2105                         }
2106                         main_sym = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
2107                         if (position_slot >= 8)
2108                                 aligned_sym = position_footer & 7;
2109                         orig_input_idx += match_len_minus_2 + 2;
2110                 } else {
2111                         main_sym = match;
2112                         orig_input_idx++;
2113                 }
2114                 main_syms[i] = main_sym;
2115                 len_syms[i] = len_sym;
2116                 aligned_syms[i] = aligned_sym;
2117                 orig_input_indices[i + 1] = orig_input_idx;
2118         }
2119
2120         /* Compute the number of sliding windows that will be used for the
2121          * entropy calculations. */
2122         int num_windows = 0;
2123         unsigned window_len;
2124         {
2125                 double e = min_block_len;
2126                 do {
2127                         window_len = e;
2128                         num_windows++;
2129                         e *= epsilon + 1;
2130                 } while (window_len < n);
2131         }
2132
2133         /* Compute the length of each sliding window. */
2134         unsigned window_lens[num_windows];
2135         {
2136                 double e = min_block_len;
2137                 unsigned window_idx = 0;
2138                 do {
2139                         window_len = e;
2140                         window_lens[window_idx++] = min(window_len, n);
2141                         e *= epsilon + 1;
2142                 } while (window_len < n);
2143         }
2144
2145         /* Best estimated compression size, in bits, found so far for the input
2146          * matches up to each position. */
2147         unsigned shortest_paths[n + 1];
2148
2149         /* Pointers to follow to get the sequence of blocks that represents the
2150          * shortest path (in terms of estimated compressed size) up to each
2151          * position in the input matches. */
2152         input_idx_t back_ptrs[n + 1];
2153
2154         for (input_idx_t i = 0; i < n + 1; i++) {
2155                 shortest_paths[i] = ~0U;
2156                 back_ptrs[i] = 0;
2157         }
2158         shortest_paths[0] = 0;
2159
2160         {
2161                 /* Initialize the per-window symbol and entropy counters */
2162                 input_idx_t mainsym_ctrs[num_windows][LZX_MAINCODE_NUM_SYMBOLS];
2163                 input_idx_t lensym_ctrs[num_windows][LZX_LENCODE_NUM_SYMBOLS + 1];
2164                 input_idx_t alignedsym_ctrs[num_windows][LZX_ALIGNEDCODE_NUM_SYMBOLS + 1];
2165                 ZERO_ARRAY(mainsym_ctrs);
2166                 ZERO_ARRAY(lensym_ctrs);
2167                 ZERO_ARRAY(alignedsym_ctrs);
2168
2169                 {
2170                         int start_win_idx = 0;
2171                         for (input_idx_t i = 0; i < n; i++) {
2172                                 while (i >= window_lens[start_win_idx])
2173                                         start_win_idx++;
2174                                 for (int j = start_win_idx; j < num_windows; j++) {
2175                                         mainsym_ctrs[j][main_syms[i]]++;
2176                                         lensym_ctrs[j][len_syms[i]]++;
2177                                         alignedsym_ctrs[j][aligned_syms[i]]++;
2178                                 }
2179                         }
2180                 }
2181
2182                 double entropy_ctrs[num_windows];
2183                 for (int i = 0; i < num_windows; i++) {
2184                         entropy_ctrs[i] = 0;
2185                         for (unsigned j = 0; j < LZX_MAINCODE_NUM_SYMBOLS; j++)
2186                                 entropy_ctrs[i] += entropy_val(mainsym_ctrs[i][j]);
2187                         for (unsigned j = 0; j < LZX_LENCODE_NUM_SYMBOLS; j++)
2188                                 entropy_ctrs[i] += entropy_val(lensym_ctrs[i][j]);
2189                         for (unsigned j = 0; j < LZX_ALIGNEDCODE_NUM_SYMBOLS; j++)
2190                                 entropy_ctrs[i] += entropy_val(alignedsym_ctrs[i][j]);
2191                 }
2192
2193                 /* Slide the windows along the input and compute the shortest
2194                  * path to each position in the matches. */
2195                 int end_window_idx = (int)num_windows - 1;
2196                 for (input_idx_t i = 0; i < n; i++) {
2197                         for (int j = 0; j <= end_window_idx; j++) {
2198                                 if (shortest_paths[i] == ~0U)
2199                                         continue;
2200                                 unsigned num_mainsyms = window_lens[j];
2201                                 unsigned num_lensyms = window_lens[j] -
2202                                                        lensym_ctrs[j][LZX_LENCODE_NUM_SYMBOLS];
2203                                 unsigned num_alignedsyms = window_lens[j] -
2204                                                            alignedsym_ctrs[j][LZX_ALIGNEDCODE_NUM_SYMBOLS];
2205                                 unsigned entropy = entropy_val(num_mainsyms) +
2206                                                    entropy_val(num_lensyms) +
2207                                                    entropy_val(num_alignedsyms) -
2208                                                    entropy_ctrs[j];
2209                                 unsigned est_csize = entropy + block_overhead;
2210
2211                                 unsigned end_idx = i + window_lens[j];
2212                                 if (est_csize + shortest_paths[i] < shortest_paths[end_idx]) {
2213                                         shortest_paths[end_idx] = est_csize + shortest_paths[i];
2214                                         back_ptrs[end_idx] = i;
2215                                 }
2216                         }
2217                         /* Remove left symbol from windows */
2218                         for (int j = 0; j <= end_window_idx; j++) {
2219                                 input_idx_t orig_maincnt = mainsym_ctrs[j][main_syms[i]]--;
2220                                 entropy_ctrs[j] -= entropy_val(orig_maincnt);
2221                                 entropy_ctrs[j] += entropy_val(orig_maincnt - 1);
2222
2223                                 input_idx_t orig_lencnt =
2224                                                 lensym_ctrs[j][len_syms[i]]--;
2225                                 if (len_syms[i] != LZX_LENCODE_NUM_SYMBOLS) {
2226                                         entropy_ctrs[j] -= entropy_val(orig_lencnt);
2227                                         entropy_ctrs[j] += entropy_val(orig_lencnt - 1);
2228                                 }
2229
2230                                 input_idx_t orig_alignedcnt =
2231                                                 alignedsym_ctrs[j][aligned_syms[i]]--;
2232                                 if (aligned_syms[i] != LZX_ALIGNEDCODE_NUM_SYMBOLS) {
2233                                         entropy_ctrs[j] -= entropy_val(orig_alignedcnt);
2234                                         entropy_ctrs[j] += entropy_val(orig_alignedcnt - 1);
2235                                 }
2236                         }
2237
2238                         /* Calculate index of longest window remaining */
2239                         while (end_window_idx >= 0 && window_lens[end_window_idx] >= n - i)
2240                                 end_window_idx--;
2241
2242                         /* Append right symbol to windows */
2243                         for (int j = 0; j <= end_window_idx; j++) {
2244                                 input_idx_t orig_maincnt = mainsym_ctrs[j][
2245                                                                 main_syms[i + window_lens[j]]]++;
2246                                 entropy_ctrs[j] -= entropy_val(orig_maincnt);
2247                                 entropy_ctrs[j] += entropy_val(orig_maincnt + 1);
2248
2249                                 input_idx_t orig_lencnt =
2250                                         lensym_ctrs[j][len_syms[i + window_lens[j]]]++;
2251                                 if (len_syms[i + window_lens[j]] != LZX_LENCODE_NUM_SYMBOLS) {
2252                                         entropy_ctrs[j] -= entropy_val(orig_lencnt);
2253                                         entropy_ctrs[j] += entropy_val(orig_lencnt + 1);
2254                                 }
2255
2256                                 input_idx_t orig_alignedcnt =
2257                                         alignedsym_ctrs[j][aligned_syms[i + window_lens[j]]]++;
2258                                 if (aligned_syms[i + window_lens[j]] != LZX_ALIGNEDCODE_NUM_SYMBOLS) {
2259                                         entropy_ctrs[j] -= entropy_val(orig_alignedcnt);
2260                                         entropy_ctrs[j] += entropy_val(orig_alignedcnt + 1);
2261                                 }
2262                         }
2263                 }
2264         }
2265
2266 #if 0
2267         /* If no cost was computed for the first block (due to it being shorter
2268          * than all the windows), merge it with the second block. */
2269         for (input_idx_t i = n; i != 0; i = back_ptrs[i])
2270                 if (back_ptrs[i] != 0 && shortest_paths[back_ptrs[i]] == ~0U)
2271                         back_ptrs[i] = 0;
2272 #endif
2273
2274         /* Calculate number of blocks */
2275         input_idx_t num_blocks = 0;
2276         for (input_idx_t i = n; i != 0; i = back_ptrs[i])
2277                 num_blocks++;
2278
2279         while (num_blocks > max_num_blocks) {
2280                 LZX_DEBUG("Joining blocks to bring total under max_num_blucks=%u",
2281                           max_num_blocks);
2282                 back_ptrs[n] = back_ptrs[back_ptrs[n]];
2283                 num_blocks--;
2284         }
2285
2286         LZX_ASSERT(num_blocks != 0);
2287
2288         /* fill in the 'struct lzx_block_spec' for each block */
2289         for (input_idx_t i = n, j = num_blocks - 1; i != 0; i = back_ptrs[i], j--) {
2290
2291                 block_specs[j].chosen_matches_start_pos = back_ptrs[i];
2292                 block_specs[j].num_chosen_matches = i - back_ptrs[i];
2293                 block_specs[j].window_pos = orig_input_indices[back_ptrs[i]];
2294                 block_specs[j].block_size = orig_input_indices[i] -
2295                                             orig_input_indices[back_ptrs[i]];
2296                 /*block_specs[j].est_csize = (shortest_paths[i] -*/
2297                                            /*shortest_paths[back_ptrs[i]]) / 8;*/
2298
2299                 LZX_DEBUG("block match_indices [%u, %u) est_csize %u bits\n",
2300                           back_ptrs[i], i,
2301                           shortest_paths[i] - shortest_paths[back_ptrs[i]]);
2302
2303                 struct lzx_freqs freqs = {};
2304
2305                 for (input_idx_t k = back_ptrs[i]; k < i; k++) {
2306                         freqs.main[main_syms[k]]++;
2307                         if (len_syms[k] != LZX_LENCODE_NUM_SYMBOLS)
2308                                 freqs.len[len_syms[k]]++;
2309                         if (aligned_syms[k] != LZX_LENCODE_NUM_SYMBOLS)
2310                                 freqs.aligned[aligned_syms[k]]++;
2311                 }
2312                 lzx_make_huffman_codes(&freqs, &block_specs[j].codes);
2313
2314                 block_specs[j].block_type = lzx_choose_verbatim_or_aligned(&freqs,
2315                                                                            &block_specs[j].codes);
2316         }
2317         *num_blocks_ret = num_blocks;
2318 }
2319
2320
2321 /* Initialize the suffix array match-finder for the specified input.  */
2322 static void
2323 lzx_lz_init_matchfinder(const u8 T[const restrict],
2324                         const input_idx_t n,
2325                         input_idx_t SA[const restrict],
2326                         input_idx_t ISA[const restrict],
2327                         input_idx_t LCP[const restrict],
2328                         struct salink link[const restrict],
2329                         const unsigned max_match_len)
2330 {
2331         /* Compute SA (Suffix Array).  */
2332
2333         {
2334                 saidx_t sa[n];
2335                 /* ISA and link are used as temporary space.  */
2336                 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE * sizeof(ISA[0]) < 256 * sizeof(saidx_t));
2337                 BUILD_BUG_ON(LZX_MAX_WINDOW_SIZE * 2 * sizeof(link[0]) < 256 * 256 * sizeof(saidx_t));
2338                 divsufsort(T, sa, n, (saidx_t*)ISA, (saidx_t*)link);
2339                 for (input_idx_t i = 0; i < n; i++)
2340                         SA[i] = sa[i];
2341         }
2342
2343 #ifdef ENABLE_LZX_DEBUG
2344
2345         LZX_ASSERT(n > 0);
2346
2347         /* Verify suffix array.  */
2348         {
2349                 bool found[n];
2350                 ZERO_ARRAY(found);
2351                 for (input_idx_t r = 0; r < n; r++) {
2352                         input_idx_t i = SA[r];
2353                         LZX_ASSERT(i < n);
2354                         LZX_ASSERT(!found[i]);
2355                         found[i] = true;
2356                 }
2357         }
2358
2359         for (input_idx_t r = 0; r < n - 1; r++) {
2360
2361                 input_idx_t i1 = SA[r];
2362                 input_idx_t i2 = SA[r + 1];
2363
2364                 input_idx_t n1 = n - i1;
2365                 input_idx_t n2 = n - i2;
2366
2367                 LZX_ASSERT(memcmp(&T[i1], &T[i2], min(n1, n2)) <= 0);
2368         }
2369         LZX_DEBUG("Verified SA (len %u)", n);
2370 #endif /* ENABLE_LZX_DEBUG */
2371
2372         /* Compute ISA (Inverse Suffix Array)  */
2373         for (input_idx_t r = 0; r < n; r++)
2374                 ISA[SA[r]] = r;
2375
2376         /* Compute LCP (longest common prefix) array.
2377          *
2378          * Algorithm adapted from Kasai et al. 2001: "Linear-Time
2379          * Longest-Common-Prefix Computation in Suffix Arrays and Its
2380          * Applications".  */
2381         {
2382                 input_idx_t h = 0;
2383                 for (input_idx_t i = 0; i < n; i++) {
2384                         input_idx_t r = ISA[i];
2385                         if (r > 0) {
2386                                 input_idx_t j = SA[r - 1];
2387
2388                                 input_idx_t lim = min(n - i, n - j);
2389
2390                                 while (h < lim && T[i + h] == T[j + h])
2391                                         h++;
2392                                 LCP[r] = h;
2393                                 if (h > 0)
2394                                         h--;
2395                         }
2396                 }
2397         }
2398
2399 #ifdef ENABLE_LZX_DEBUG
2400         /* Verify LCP array.  */
2401         for (input_idx_t r = 0; r < n - 1; r++) {
2402                 LZX_ASSERT(ISA[SA[r]] == r);
2403                 LZX_ASSERT(ISA[SA[r + 1]] == r + 1);
2404
2405                 input_idx_t i1 = SA[r];
2406                 input_idx_t i2 = SA[r + 1];
2407                 input_idx_t lcp = LCP[r + 1];
2408
2409                 input_idx_t n1 = n - i1;
2410                 input_idx_t n2 = n - i2;
2411
2412                 LZX_ASSERT(lcp <= min(n1, n2));
2413
2414                 LZX_ASSERT(memcmp(&T[i1], &T[i2], lcp) == 0);
2415                 if (lcp < min(n1, n2))
2416                         LZX_ASSERT(T[i1 + lcp] != T[i2 + lcp]);
2417         }
2418 #endif /* ENABLE_LZX_DEBUG */
2419
2420         /* Compute salink.next and salink.lcpnext.
2421          *
2422          * Algorithm adapted from Crochemore et al. 2009:
2423          * "LPF computation revisited".
2424          *
2425          * Note: we cap lcpnext to the maximum match length so that the
2426          * match-finder need not worry about it later.  */
2427         link[n - 1].next = (input_idx_t)~0U;
2428         link[n - 1].prev = (input_idx_t)~0U;
2429         link[n - 1].lcpnext = 0;
2430         link[n - 1].lcpprev = 0;
2431         for (input_idx_t r = n - 2; r != (input_idx_t)~0U; r--) {
2432                 input_idx_t t = r + 1;
2433                 input_idx_t l = LCP[t];
2434                 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2435                         l = min(l, link[t].lcpnext);
2436                         t = link[t].next;
2437                 }
2438                 link[r].next = t;
2439                 link[r].lcpnext = min(l, max_match_len);
2440                 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2441                 LZX_ASSERT(l <= n - SA[r]);
2442                 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2443         }
2444
2445         /* Compute salink.prev and salink.lcpprev.
2446          *
2447          * Algorithm adapted from Crochemore et al. 2009:
2448          * "LPF computation revisited".
2449          *
2450          * Note: we cap lcpprev to the maximum match length so that the
2451          * match-finder need not worry about it later.  */
2452         link[0].prev = (input_idx_t)~0;
2453         link[0].next = (input_idx_t)~0;
2454         link[0].lcpprev = 0;
2455         link[0].lcpnext = 0;
2456         for (input_idx_t r = 1; r < n; r++) {
2457                 input_idx_t t = r - 1;
2458                 input_idx_t l = LCP[r];
2459                 while (t != (input_idx_t)~0 && SA[t] > SA[r]) {
2460                         l = min(l, link[t].lcpprev);
2461                         t = link[t].prev;
2462                 }
2463                 link[r].prev = t;
2464                 link[r].lcpprev = min(l, max_match_len);
2465                 LZX_ASSERT(t == (input_idx_t)~0 || l <= n - SA[t]);
2466                 LZX_ASSERT(l <= n - SA[r]);
2467                 LZX_ASSERT(memcmp(&T[SA[r]], &T[SA[t]], l) == 0);
2468         }
2469 }
2470
2471 /* Prepare the input window into one or more LZX blocks ready to be output.  */
2472 static void
2473 lzx_prepare_blocks(struct lzx_compressor * ctx)
2474 {
2475         /* Initialize the match-finder.  */
2476         lzx_lz_init_matchfinder(ctx->window, ctx->window_size,
2477                                 ctx->SA, ctx->ISA, ctx->LCP, ctx->salink,
2478                                 LZX_MAX_MATCH_LEN);
2479         ctx->cached_matches_pos = 0;
2480         ctx->matches_cached = false;
2481         ctx->match_window_pos = 0;
2482
2483         /* Set up a default cost model.  */
2484         lzx_set_default_costs(&ctx->costs);
2485
2486         /* Initially assume that the entire input will be one LZX block.  */
2487         ctx->block_specs[0].block_type = LZX_BLOCKTYPE_ALIGNED;
2488         ctx->block_specs[0].window_pos = 0;
2489         ctx->block_specs[0].block_size = ctx->window_size;
2490         ctx->num_blocks = 1;
2491
2492         /* Perform near-optimal LZ parsing.  */
2493         lzx_optimize_blocks(ctx);
2494
2495         /* Possibly divide up the LZX block.  */
2496         const unsigned max_num_blocks = 1U << ctx->params.alg_params.slow.num_split_passes;
2497         if (max_num_blocks > 1) {
2498                 const double epsilon = 0.2;
2499                 const unsigned min_block_len = 500;
2500
2501                 lzx_block_split((const u32*)ctx->chosen_matches,
2502                                 ctx->block_specs[0].num_chosen_matches,
2503                                 epsilon, max_num_blocks, min_block_len,
2504                                 ctx->block_specs, &ctx->num_blocks);
2505         }
2506 }
2507
2508 /*
2509  * This is the fast version of lzx_prepare_blocks().  This version "quickly"
2510  * prepares a single compressed block containing the entire input.  See the
2511  * description of the "Fast algorithm" at the beginning of this file for more
2512  * information.
2513  *
2514  * Input ---  the preprocessed data:
2515  *
2516  *      ctx->window[]
2517  *      ctx->window_size
2518  *
2519  * Working space:
2520  *      ctx->queue
2521  *
2522  * Output --- the block specification and the corresponding match/literal data:
2523  *
2524  *      ctx->block_specs[]
2525  *      ctx->num_blocks
2526  *      ctx->chosen_matches[]
2527  */
2528 static void
2529 lzx_prepare_block_fast(struct lzx_compressor * ctx)
2530 {
2531         unsigned num_matches;
2532         struct lzx_freqs freqs;
2533         struct lzx_block_spec *spec;
2534
2535         /* Parameters to hash chain LZ match finder
2536          * (lazy with 1 match lookahead)  */
2537         static const struct lz_params lzx_lz_params = {
2538                 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
2539                  * aren't worth choosing when using greedy or lazy parsing.  */
2540                 .min_match      = 3,
2541                 .max_match      = LZX_MAX_MATCH_LEN,
2542                 .good_match     = LZX_MAX_MATCH_LEN,
2543                 .nice_match     = LZX_MAX_MATCH_LEN,
2544                 .max_chain_len  = LZX_MAX_MATCH_LEN,
2545                 .max_lazy_match = LZX_MAX_MATCH_LEN,
2546                 .too_far        = 4096,
2547         };
2548
2549         /* Initialize symbol frequencies and match offset LRU queue.  */
2550         memset(&freqs, 0, sizeof(struct lzx_freqs));
2551         lzx_lru_queue_init(&ctx->queue);
2552
2553         /* Determine series of matches/literals to output.  */
2554         num_matches = lz_analyze_block(ctx->window,
2555                                        ctx->window_size,
2556                                        (u32*)ctx->chosen_matches,
2557                                        lzx_record_match,
2558                                        lzx_record_literal,
2559                                        &freqs,
2560                                        &ctx->queue,
2561                                        &freqs,
2562                                        &lzx_lz_params);
2563
2564
2565         /* Set up block specification.  */
2566         spec = &ctx->block_specs[0];
2567         spec->block_type = LZX_BLOCKTYPE_ALIGNED;
2568         spec->window_pos = 0;
2569         spec->block_size = ctx->window_size;
2570         spec->num_chosen_matches = num_matches;
2571         spec->chosen_matches_start_pos = 0;
2572         lzx_make_huffman_codes(&freqs, &spec->codes);
2573         ctx->num_blocks = 1;
2574 }
2575
2576 static void
2577 do_call_insn_translation(u32 *call_insn_target, int input_pos,
2578                          s32 file_size)
2579 {
2580         s32 abs_offset;
2581         s32 rel_offset;
2582
2583         rel_offset = le32_to_cpu(*call_insn_target);
2584         if (rel_offset >= -input_pos && rel_offset < file_size) {
2585                 if (rel_offset < file_size - input_pos) {
2586                         /* "good translation" */
2587                         abs_offset = rel_offset + input_pos;
2588                 } else {
2589                         /* "compensating translation" */
2590                         abs_offset = rel_offset - file_size;
2591                 }
2592                 *call_insn_target = cpu_to_le32(abs_offset);
2593         }
2594 }
2595
2596 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
2597  * See the comment above that function for more information.  */
2598 static void
2599 do_call_insn_preprocessing(u8 data[], int size)
2600 {
2601         for (int i = 0; i < size - 10; i++) {
2602                 if (data[i] == 0xe8) {
2603                         do_call_insn_translation((u32*)&data[i + 1], i,
2604                                                  LZX_WIM_MAGIC_FILESIZE);
2605                         i += 4;
2606                 }
2607         }
2608 }
2609
2610 /* API function documented in wimlib.h  */
2611 WIMLIBAPI unsigned
2612 wimlib_lzx_compress2(const void                 * const restrict uncompressed_data,
2613                      unsigned                     const          uncompressed_len,
2614                      void                       * const restrict compressed_data,
2615                      struct wimlib_lzx_context  * const restrict lzx_ctx)
2616 {
2617         struct lzx_compressor *ctx = (struct lzx_compressor*)lzx_ctx;
2618         struct output_bitstream ostream;
2619         unsigned compressed_len;
2620
2621         if (uncompressed_len < 100) {
2622                 LZX_DEBUG("Too small to bother compressing.");
2623                 return 0;
2624         }
2625
2626         if (uncompressed_len > 32768) {
2627                 LZX_DEBUG("Only up to 32768 bytes of uncompressed data are supported.");
2628                 return 0;
2629         }
2630
2631         wimlib_assert(lzx_ctx != NULL);
2632
2633         LZX_DEBUG("Attempting to compress %u bytes...", uncompressed_len);
2634
2635         /* The input data must be preprocessed.  To avoid changing the original
2636          * input, copy it to a temporary buffer.  */
2637         memcpy(ctx->window, uncompressed_data, uncompressed_len);
2638         ctx->window_size = uncompressed_len;
2639
2640         /* This line is unnecessary; it just avoids inconsequential accesses of
2641          * uninitialized memory that would show up in memory-checking tools such
2642          * as valgrind.  */
2643         memset(&ctx->window[ctx->window_size], 0, 12);
2644
2645         LZX_DEBUG("Preprocessing data...");
2646
2647         /* Before doing any actual compression, do the call instruction (0xe8
2648          * byte) translation on the uncompressed data.  */
2649         do_call_insn_preprocessing(ctx->window, ctx->window_size);
2650
2651         LZX_DEBUG("Preparing blocks...");
2652
2653         /* Prepare the compressed data.  */
2654         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
2655                 lzx_prepare_block_fast(ctx);
2656         else
2657                 lzx_prepare_blocks(ctx);
2658
2659         LZX_DEBUG("Writing compressed blocks...");
2660
2661         /* Generate the compressed data.  */
2662         init_output_bitstream(&ostream, compressed_data, ctx->window_size - 1);
2663         lzx_write_all_blocks(ctx, &ostream);
2664
2665         LZX_DEBUG("Flushing bitstream...");
2666         if (flush_output_bitstream(&ostream)) {
2667                 /* If the bitstream cannot be flushed, then the output space was
2668                  * exhausted.  */
2669                 LZX_DEBUG("Data did not compress to less than original length!");
2670                 return 0;
2671         }
2672
2673         /* Compute the length of the compressed data.  */
2674         compressed_len = ostream.bit_output - (u8*)compressed_data;
2675
2676         LZX_DEBUG("Done: compressed %u => %u bytes.",
2677                   uncompressed_len, compressed_len);
2678
2679         /* Verify that we really get the same thing back when decompressing.
2680          * TODO: Disable this check by default on the slow algorithm.  */
2681         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
2682         #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
2683             || 1
2684         #endif
2685             )
2686         {
2687                 u8 buf[uncompressed_len];
2688                 int ret;
2689
2690                 ret = wimlib_lzx_decompress(compressed_data, compressed_len,
2691                                             buf, uncompressed_len);
2692                 if (ret) {
2693                         ERROR("Failed to decompress data we "
2694                               "compressed using LZX algorithm");
2695                         wimlib_assert(0);
2696                         return 0;
2697                 }
2698
2699                 if (memcmp(uncompressed_data, buf, uncompressed_len)) {
2700                         ERROR("Data we compressed using LZX algorithm "
2701                               "didn't decompress to original");
2702                         wimlib_assert(0);
2703                         return 0;
2704                 }
2705         }
2706         return compressed_len;
2707 }
2708
2709 static bool
2710 lzx_params_compatible(const struct wimlib_lzx_params *oldparams,
2711                       const struct wimlib_lzx_params *newparams)
2712 {
2713         return 0 == memcmp(oldparams, newparams, sizeof(struct wimlib_lzx_params));
2714 }
2715
2716 static struct wimlib_lzx_params lzx_user_default_params;
2717 static struct wimlib_lzx_params *lzx_user_default_params_ptr;
2718
2719 static bool
2720 lzx_params_valid(const struct wimlib_lzx_params *params)
2721 {
2722         /* Validate parameters.  */
2723         if (params->size_of_this != sizeof(struct wimlib_lzx_params)) {
2724                 LZX_DEBUG("Invalid parameter structure size!");
2725                 return false;
2726         }
2727
2728         if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
2729             params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
2730         {
2731                 LZX_DEBUG("Invalid algorithm.");
2732                 return false;
2733         }
2734
2735         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2736                 if (params->alg_params.slow.num_optim_passes < 1)
2737                 {
2738                         LZX_DEBUG("Invalid number of optimization passes!");
2739                         return false;
2740                 }
2741
2742                 if (params->alg_params.slow.main_nostat_cost < 1 ||
2743                     params->alg_params.slow.main_nostat_cost > 16)
2744                 {
2745                         LZX_DEBUG("Invalid main_nostat_cost!");
2746                         return false;
2747                 }
2748
2749                 if (params->alg_params.slow.len_nostat_cost < 1 ||
2750                     params->alg_params.slow.len_nostat_cost > 16)
2751                 {
2752                         LZX_DEBUG("Invalid len_nostat_cost!");
2753                         return false;
2754                 }
2755
2756                 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
2757                     params->alg_params.slow.aligned_nostat_cost > 8)
2758                 {
2759                         LZX_DEBUG("Invalid aligned_nostat_cost!");
2760                         return false;
2761                 }
2762
2763                 if (params->alg_params.slow.num_split_passes > 31) {
2764                         LZX_DEBUG("Invalid num_split_passes!");
2765                         return false;
2766                 }
2767         }
2768         return true;
2769 }
2770
2771 WIMLIBAPI int
2772 wimlib_lzx_set_default_params(const struct wimlib_lzx_params * params)
2773 {
2774         if (params) {
2775                 if (!lzx_params_valid(params))
2776                         return WIMLIB_ERR_INVALID_PARAM;
2777                 lzx_user_default_params = *params;
2778                 lzx_user_default_params_ptr = &lzx_user_default_params;
2779         } else {
2780                 lzx_user_default_params_ptr = NULL;
2781         }
2782         return 0;
2783 }
2784
2785 /* API function documented in wimlib.h  */
2786 WIMLIBAPI int
2787 wimlib_lzx_alloc_context(const struct wimlib_lzx_params *params,
2788                          struct wimlib_lzx_context **ctx_pp)
2789 {
2790
2791         LZX_DEBUG("Allocating LZX context...");
2792
2793         struct lzx_compressor *ctx;
2794
2795         static const struct wimlib_lzx_params fast_default = {
2796                 .size_of_this = sizeof(struct wimlib_lzx_params),
2797                 .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
2798                 .use_defaults = 0,
2799                 .alg_params = {
2800                         .fast = {
2801                         },
2802                 },
2803         };
2804         static const struct wimlib_lzx_params slow_default = {
2805                 .size_of_this = sizeof(struct wimlib_lzx_params),
2806                 .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
2807                 .use_defaults = 0,
2808                 .alg_params = {
2809                         .slow = {
2810                                 .use_len2_matches = 1,
2811                                 .num_fast_bytes = 32,
2812                                 .num_optim_passes = 2,
2813                                 .num_split_passes = 0,
2814                                 .max_search_depth = 50,
2815                                 .max_matches_per_pos = 3,
2816                                 .main_nostat_cost = 15,
2817                                 .len_nostat_cost = 15,
2818                                 .aligned_nostat_cost = 7,
2819                         },
2820                 },
2821         };
2822
2823         if (params) {
2824                 if (!lzx_params_valid(params))
2825                         return WIMLIB_ERR_INVALID_PARAM;
2826         } else {
2827                 LZX_DEBUG("Using default algorithm and parameters.");
2828                 if (lzx_user_default_params_ptr)
2829                         params = lzx_user_default_params_ptr;
2830                 else
2831                         params = &slow_default;
2832         }
2833
2834         if (params->use_defaults) {
2835                 if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2836                         params = &slow_default;
2837                 else
2838                         params = &fast_default;
2839         }
2840
2841         if (ctx_pp) {
2842                 ctx = *(struct lzx_compressor**)ctx_pp;
2843
2844                 if (ctx && lzx_params_compatible(&ctx->params, params))
2845                         return 0;
2846         } else {
2847                 LZX_DEBUG("Check parameters only.");
2848                 return 0;
2849         }
2850
2851         LZX_DEBUG("Allocating memory.");
2852
2853         ctx = MALLOC(sizeof(struct lzx_compressor));
2854         if (ctx == NULL)
2855                 goto err;
2856
2857         size_t block_specs_length;
2858
2859         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2860                 block_specs_length = 1U << params->alg_params.slow.num_split_passes;
2861         else
2862                 block_specs_length = 1U;
2863         ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
2864         if (ctx->block_specs == NULL)
2865                 goto err_free_ctx;
2866
2867         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2868                 ctx->SA = MALLOC(3U * LZX_MAX_WINDOW_SIZE * sizeof(ctx->SA[0]));
2869                 if (ctx->SA == NULL)
2870                         goto err_free_block_specs;
2871                 ctx->ISA = ctx->SA + LZX_MAX_WINDOW_SIZE;
2872                 ctx->LCP = ctx->ISA + LZX_MAX_WINDOW_SIZE;
2873                 ctx->salink = MALLOC(LZX_MAX_WINDOW_SIZE * sizeof(ctx->salink[0]));
2874                 if (ctx->salink == NULL)
2875                         goto err_free_SA;
2876         } else {
2877                 ctx->SA = NULL;
2878                 ctx->ISA = NULL;
2879                 ctx->LCP = NULL;
2880                 ctx->salink = NULL;
2881         }
2882
2883         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2884                 ctx->optimum = MALLOC((LZX_OPTIM_ARRAY_SIZE + LZX_MAX_MATCH_LEN) *
2885                                        sizeof(ctx->optimum[0]));
2886                 if (ctx->optimum == NULL)
2887                         goto err_free_salink;
2888         } else {
2889                 ctx->optimum = NULL;
2890         }
2891
2892         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2893                 uint32_t cache_per_pos;
2894
2895                 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
2896                 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
2897                         cache_per_pos = LZX_MAX_CACHE_PER_POS;
2898
2899                 ctx->cached_matches = MALLOC(LZX_MAX_WINDOW_SIZE * (cache_per_pos + 1) *
2900                                              sizeof(ctx->cached_matches[0]));
2901                 if (ctx->cached_matches == NULL)
2902                         goto err_free_optimum;
2903         } else {
2904                 ctx->cached_matches = NULL;
2905         }
2906
2907         ctx->chosen_matches = MALLOC(LZX_MAX_WINDOW_SIZE *
2908                                      sizeof(ctx->chosen_matches[0]));
2909         if (ctx->chosen_matches == NULL)
2910                 goto err_free_cached_matches;
2911
2912         memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_params));
2913         memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
2914
2915         LZX_DEBUG("Successfully allocated new LZX context.");
2916
2917         wimlib_lzx_free_context(*ctx_pp);
2918         *ctx_pp = (struct wimlib_lzx_context*)ctx;
2919         return 0;
2920
2921 err_free_cached_matches:
2922         FREE(ctx->cached_matches);
2923 err_free_optimum:
2924         FREE(ctx->optimum);
2925 err_free_salink:
2926         FREE(ctx->salink);
2927 err_free_SA:
2928         FREE(ctx->SA);
2929 err_free_block_specs:
2930         FREE(ctx->block_specs);
2931 err_free_ctx:
2932         FREE(ctx);
2933 err:
2934         LZX_DEBUG("Ran out of memory.");
2935         return WIMLIB_ERR_NOMEM;
2936 }
2937
2938 /* API function documented in wimlib.h  */
2939 WIMLIBAPI void
2940 wimlib_lzx_free_context(struct wimlib_lzx_context *_ctx)
2941 {
2942         struct lzx_compressor *ctx = (struct lzx_compressor*)_ctx;
2943
2944         if (ctx) {
2945                 FREE(ctx->cached_matches);
2946                 FREE(ctx->chosen_matches);
2947                 FREE(ctx->optimum);
2948                 FREE(ctx->SA);
2949                 FREE(ctx->salink);
2950                 FREE(ctx->block_specs);
2951                 FREE(ctx);
2952         }
2953 }
2954
2955 /* API function documented in wimlib.h  */
2956 WIMLIBAPI unsigned
2957 wimlib_lzx_compress(const void * const restrict uncompressed_data,
2958                     unsigned     const          uncompressed_len,
2959                     void       * const restrict compressed_data)
2960 {
2961         int ret;
2962         struct wimlib_lzx_context *ctx = NULL;
2963         unsigned compressed_len;
2964
2965         ret = wimlib_lzx_alloc_context(NULL, &ctx);
2966         if (ret) {
2967                 wimlib_assert(ret != WIMLIB_ERR_INVALID_PARAM);
2968                 WARNING("Couldn't allocate LZX compression context: %"TS"",
2969                         wimlib_get_error_string(ret));
2970                 return 0;
2971         }
2972
2973         compressed_len = wimlib_lzx_compress2(uncompressed_data,
2974                                               uncompressed_len,
2975                                               compressed_data,
2976                                               ctx);
2977
2978         wimlib_lzx_free_context(ctx);
2979
2980         return compressed_len;
2981 }