]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
00d448603c07f9f9aece71f15fd3165655252323
[wimlib] / src / lzx-compress.c
1 /*
2  * lzx-compress.c
3  *
4  * LZX compression routines
5  */
6
7 /*
8  * Copyright (C) 2012, 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26
27 /*
28  * This file contains a compressor for the LZX compression format, as used in
29  * the WIM file format.
30  *
31  * Format
32  * ======
33  *
34  * First, the primary reference for the LZX compression format is the
35  * specification released by Microsoft.
36  *
37  * Second, the comments in lzx-decompress.c provide some more information about
38  * the LZX compression format, including errors in the Microsoft specification.
39  *
40  * Do note that LZX shares many similarities with DEFLATE, the algorithm used by
41  * zlib and gzip.  Both LZX and DEFLATE use LZ77 matching and Huffman coding,
42  * and certain other details are quite similar, such as the method for storing
43  * Huffman codes.  However, some of the main differences are:
44  *
45  * - LZX preprocesses the data to attempt to make x86 machine code slightly more
46  *   compressible before attempting to compress it further.
47  * - LZX uses a "main" alphabet which combines literals and matches, with the
48  *   match symbols containing a "length header" (giving all or part of the match
49  *   length) and a "position slot" (giving, roughly speaking, the order of
50  *   magnitude of the match offset).
51  * - LZX does not have static Huffman blocks; however it does have two types of
52  *   dynamic Huffman blocks ("aligned offset" and "verbatim").
53  * - LZX has a minimum match length of 2 rather than 3.
54  * - In LZX, match offsets 0 through 2 actually represent entries in an LRU
55  *   queue of match offsets.  This is very useful for certain types of files,
56  *   such as binary files that have repeating records.
57  *
58  * Algorithms
59  * ==========
60  *
61  * There are actually two distinct overall algorithms implemented here.  We
62  * shall refer to them as the "slow" algorithm and the "fast" algorithm.  The
63  * "slow" algorithm spends more time compressing to achieve a higher compression
64  * ratio compared to the "fast" algorithm.  More details are presented below.
65  *
66  * Slow algorithm
67  * --------------
68  *
69  * The "slow" algorithm to generate LZX-compressed data is roughly as follows:
70  *
71  * 1. Preprocess the input data to translate the targets of x86 call
72  *    instructions to absolute offsets.
73  *
74  * 2. Build the suffix array and inverse suffix array for the input data.  The
75  *    suffix array contains the indices of all suffixes of the input data,
76  *    sorted lexcographically by the corresponding suffixes.  The "position" of
77  *    a suffix is the index of that suffix in the original string, whereas the
78  *    "rank" of a suffix is the index at which that suffix's position is found
79  *    in the suffix array.
80  *
81  * 3. Build the longest common prefix array corresponding to the suffix array.
82  *
83  * 4. For each suffix, find the highest lower ranked suffix that has a lower
84  *    position, the lowest higher ranked suffix that has a lower position, and
85  *    the length of the common prefix shared between each.   This information is
86  *    later used to link suffix ranks into a doubly-linked list for searching
87  *    the suffix array.
88  *
89  * 5. Set a default cost model for matches/literals.
90  *
91  * 6. Determine the lowest cost sequence of LZ77 matches ((offset, length)
92  *    pairs) and literal bytes to divide the input into.  Raw match-finding is
93  *    done by searching the suffix array using a linked list to avoid
94  *    considering any suffixes that start after the current position.  Each run
95  *    of the match-finder returns the approximate lowest-cost longest match as
96  *    well as any shorter matches that have even lower approximate costs.  Each
97  *    such run also adds the suffix rank of the current position into the linked
98  *    list being used to search the suffix array.  Parsing, or match-choosing,
99  *    is solved as a minimum-cost path problem using a forward "optimal parsing"
100  *    algorithm based on the Deflate encoder from 7-Zip.  This algorithm moves
101  *    forward calculating the minimum cost to reach each byte until either a
102  *    very long match is found or until a position is found at which no matches
103  *    start or overlap.
104  *
105  * 7. Build the Huffman codes needed to output the matches/literals.
106  *
107  * 8. Up to a certain number of iterations, use the resulting Huffman codes to
108  *    refine a cost model and go back to Step #6 to determine an improved
109  *    sequence of matches and literals.
110  *
111  * 9. Output the resulting block using the match/literal sequences and the
112  *    Huffman codes that were computed for the block.
113  *
114  * Note: the algorithm does not yet attempt to split the input into multiple LZX
115  * blocks, instead using a series of blocks of LZX_DIV_BLOCK_SIZE bytes.
116  *
117  * Fast algorithm
118  * --------------
119  *
120  * The fast algorithm (and the only one available in wimlib v1.5.1 and earlier)
121  * spends much less time on the main bottlenecks of the compression process ---
122  * that is, the match finding and match choosing.  Matches are found and chosen
123  * with hash chains using a greedy parse with one position of look-ahead.  No
124  * block splitting is done; only compressing the full input into an aligned
125  * offset block is considered.
126  *
127  * Acknowledgments
128  * ===============
129  *
130  * Acknowledgments to several open-source projects and research papers that made
131  * it possible to implement this code:
132  *
133  * - divsufsort (author: Yuta Mori), for the suffix array construction code,
134  *   located in a separate directory (divsufsort/).
135  *
136  * - "Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its
137  *   Applications" (Kasai et al. 2001), for the LCP array computation.
138  *
139  * - "LPF computation revisited" (Crochemore et al. 2009) for the prev and next
140  *   array computations.
141  *
142  * - 7-Zip (author: Igor Pavlov) for the algorithm for forward optimal parsing
143  *   (match-choosing).
144  *
145  * - zlib (author: Jean-loup Gailly and Mark Adler), for the hash table
146  *   match-finding algorithm (used in lz77.c).
147  *
148  * - lzx-compress (author: Matthew T. Russotto), on which some parts of this
149  *   code were originally based.
150  */
151
152 #ifdef HAVE_CONFIG_H
153 #  include "config.h"
154 #endif
155
156 #include "wimlib.h"
157 #include "wimlib/compressor_ops.h"
158 #include "wimlib/compress_common.h"
159 #include "wimlib/endianness.h"
160 #include "wimlib/error.h"
161 #include "wimlib/lz_hash.h"
162 #include "wimlib/lz_sarray.h"
163 #include "wimlib/lzx.h"
164 #include "wimlib/util.h"
165 #include <string.h>
166
167 #ifdef ENABLE_LZX_DEBUG
168 #  include "wimlib/decompress_common.h"
169 #endif
170
171 typedef u32 block_cost_t;
172 #define INFINITE_BLOCK_COST     (~(block_cost_t)0)
173
174 #define LZX_OPTIM_ARRAY_SIZE    4096
175
176 #define LZX_DIV_BLOCK_SIZE      32768
177
178 #define LZX_MAX_CACHE_PER_POS   10
179
180 /* Codewords for the LZX main, length, and aligned offset Huffman codes  */
181 struct lzx_codewords {
182         u16 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
183         u16 len[LZX_LENCODE_NUM_SYMBOLS];
184         u16 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
185 };
186
187 /* Codeword lengths (in bits) for the LZX main, length, and aligned offset
188  * Huffman codes.
189  *
190  * A 0 length means the codeword has zero frequency.
191  */
192 struct lzx_lens {
193         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
194         u8 len[LZX_LENCODE_NUM_SYMBOLS];
195         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
196 };
197
198 /* Costs for the LZX main, length, and aligned offset Huffman symbols.
199  *
200  * If a codeword has zero frequency, it must still be assigned some nonzero cost
201  * --- generally a high cost, since even if it gets used in the next iteration,
202  * it probably will not be used very times.  */
203 struct lzx_costs {
204         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
205         u8 len[LZX_LENCODE_NUM_SYMBOLS];
206         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
207 };
208
209 /* The LZX main, length, and aligned offset Huffman codes  */
210 struct lzx_codes {
211         struct lzx_codewords codewords;
212         struct lzx_lens lens;
213 };
214
215 /* Tables for tallying symbol frequencies in the three LZX alphabets  */
216 struct lzx_freqs {
217         input_idx_t main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
218         input_idx_t len[LZX_LENCODE_NUM_SYMBOLS];
219         input_idx_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
220 };
221
222 /* LZX intermediate match/literal format  */
223 struct lzx_match {
224         /* Bit     Description
225          *
226          * 31      1 if a match, 0 if a literal.
227          *
228          * 30-25   position slot.  This can be at most 50, so it will fit in 6
229          *         bits.
230          *
231          * 8-24    position footer.  This is the offset of the real formatted
232          *         offset from the position base.  This can be at most 17 bits
233          *         (since lzx_extra_bits[LZX_MAX_POSITION_SLOTS - 1] is 17).
234          *
235          * 0-7     length of match, minus 2.  This can be at most
236          *         (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits.  */
237         u32 data;
238 };
239
240 /* Specification for an LZX block.  */
241 struct lzx_block_spec {
242
243         /* One of the LZX_BLOCKTYPE_* constants indicating which type of this
244          * block.  */
245         int block_type;
246
247         /* 0-based position in the window at which this block starts.  */
248         input_idx_t window_pos;
249
250         /* The number of bytes of uncompressed data this block represents.  */
251         input_idx_t block_size;
252
253         /* The position in the 'chosen_matches' array in the `struct
254          * lzx_compressor' at which the match/literal specifications for
255          * this block begin.  */
256         input_idx_t chosen_matches_start_pos;
257
258         /* The number of match/literal specifications for this block.  */
259         input_idx_t num_chosen_matches;
260
261         /* Huffman codes for this block.  */
262         struct lzx_codes codes;
263 };
264
265 /* Include template for the match-choosing algorithm.  */
266 #define LZ_COMPRESSOR           struct lzx_compressor
267 #define LZ_ADAPTIVE_STATE       struct lzx_lru_queue
268 struct lzx_compressor;
269 #include "wimlib/lz_optimal.h"
270
271 /* State of the LZX compressor.  */
272 struct lzx_compressor {
273
274         /* The parameters that were used to create the compressor.  */
275         struct wimlib_lzx_compressor_params params;
276
277         /* The buffer of data to be compressed.
278          *
279          * 0xe8 byte preprocessing is done directly on the data here before
280          * further compression.
281          *
282          * Note that this compressor does *not* use a real sliding window!!!!
283          * It's not needed in the WIM format, since every chunk is compressed
284          * independently.  This is by design, to allow random access to the
285          * chunks.
286          *
287          * We reserve a few extra bytes to potentially allow reading off the end
288          * of the array in the match-finding code for optimization purposes.
289          */
290         u8 *window;
291
292         /* Number of bytes of data to be compressed, which is the number of
293          * bytes of data in @window that are actually valid.  */
294         input_idx_t window_size;
295
296         /* Allocated size of the @window.  */
297         input_idx_t max_window_size;
298
299         /* Number of symbols in the main alphabet (depends on the
300          * @max_window_size since it determines the maximum allowed offset).  */
301         unsigned num_main_syms;
302
303         /* The current match offset LRU queue.  */
304         struct lzx_lru_queue queue;
305
306         /* Space for the sequences of matches/literals that were chosen for each
307          * block.  */
308         struct lzx_match *chosen_matches;
309
310         /* Information about the LZX blocks the preprocessed input was divided
311          * into.  */
312         struct lzx_block_spec *block_specs;
313
314         /* Number of LZX blocks the input was divided into; a.k.a. the number of
315          * elements of @block_specs that are valid.  */
316         unsigned num_blocks;
317
318         /* This is simply filled in with zeroes and used to avoid special-casing
319          * the output of the first compressed Huffman code, which conceptually
320          * has a delta taken from a code with all symbols having zero-length
321          * codewords.  */
322         struct lzx_codes zero_codes;
323
324         /* The current cost model.  */
325         struct lzx_costs costs;
326
327         /* Fast algorithm only:  Array of hash table links.  */
328         input_idx_t *prev_tab;
329
330         /* Slow algorithm only: Suffix array match-finder.  */
331         struct lz_sarray lz_sarray;
332
333         /* Position in window of next match to return.  */
334         input_idx_t match_window_pos;
335
336         /* The match-finder shall ensure the length of matches does not exceed
337          * this position in the input.  */
338         input_idx_t match_window_end;
339
340         /* Matches found by the match-finder are cached in the following array
341          * to achieve a slight speedup when the same matches are needed on
342          * subsequent passes.  This is suboptimal because different matches may
343          * be preferred with different cost models, but seems to be a worthwhile
344          * speedup.  */
345         struct raw_match *cached_matches;
346         unsigned cached_matches_pos;
347         bool matches_cached;
348
349         /* Match chooser.  */
350         struct lz_match_chooser mc;
351 };
352
353 /* Returns the LZX position slot that corresponds to a given match offset,
354  * taking into account the recent offset queue and updating it if the offset is
355  * found in it.  */
356 static unsigned
357 lzx_get_position_slot(unsigned offset, struct lzx_lru_queue *queue)
358 {
359         unsigned position_slot;
360
361         /* See if the offset was recently used.  */
362         for (unsigned i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
363                 if (offset == queue->R[i]) {
364                         /* Found it.  */
365
366                         /* Bring the repeat offset to the front of the
367                          * queue.  Note: this is, in fact, not a real
368                          * LRU queue because repeat matches are simply
369                          * swapped to the front.  */
370                         swap(queue->R[0], queue->R[i]);
371
372                         /* The resulting position slot is simply the first index
373                          * at which the offset was found in the queue.  */
374                         return i;
375                 }
376         }
377
378         /* The offset was not recently used; look up its real position slot.  */
379         position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
380
381         /* Bring the new offset to the front of the queue.  */
382         for (unsigned i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
383                 queue->R[i] = queue->R[i - 1];
384         queue->R[0] = offset;
385
386         return position_slot;
387 }
388
389 /* Build the main, length, and aligned offset Huffman codes used in LZX.
390  *
391  * This takes as input the frequency tables for each code and produces as output
392  * a set of tables that map symbols to codewords and codeword lengths.  */
393 static void
394 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
395                        struct lzx_codes *codes,
396                        unsigned num_main_syms)
397 {
398         make_canonical_huffman_code(num_main_syms,
399                                     LZX_MAX_MAIN_CODEWORD_LEN,
400                                     freqs->main,
401                                     codes->lens.main,
402                                     codes->codewords.main);
403
404         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
405                                     LZX_MAX_LEN_CODEWORD_LEN,
406                                     freqs->len,
407                                     codes->lens.len,
408                                     codes->codewords.len);
409
410         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
411                                     LZX_MAX_ALIGNED_CODEWORD_LEN,
412                                     freqs->aligned,
413                                     codes->lens.aligned,
414                                     codes->codewords.aligned);
415 }
416
417 /*
418  * Output an LZX match.
419  *
420  * @out:         The bitstream to write the match to.
421  * @block_type:  The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM)
422  * @match:       The match.
423  * @codes:       Pointer to a structure that contains the codewords for the
424  *               main, length, and aligned offset Huffman codes.
425  */
426 static void
427 lzx_write_match(struct output_bitstream *out, int block_type,
428                 struct lzx_match match, const struct lzx_codes *codes)
429 {
430         /* low 8 bits are the match length minus 2 */
431         unsigned match_len_minus_2 = match.data & 0xff;
432         /* Next 17 bits are the position footer */
433         unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
434         /* Next 6 bits are the position slot. */
435         unsigned position_slot = (match.data >> 25) & 0x3f;     /* 6 bits */
436         unsigned len_header;
437         unsigned len_footer;
438         unsigned main_symbol;
439         unsigned num_extra_bits;
440         unsigned verbatim_bits;
441         unsigned aligned_bits;
442
443         /* If the match length is less than MIN_MATCH_LEN (= 2) +
444          * NUM_PRIMARY_LENS (= 7), the length header contains
445          * the match length minus MIN_MATCH_LEN, and there is no
446          * length footer.
447          *
448          * Otherwise, the length header contains
449          * NUM_PRIMARY_LENS, and the length footer contains
450          * the match length minus NUM_PRIMARY_LENS minus
451          * MIN_MATCH_LEN. */
452         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
453                 len_header = match_len_minus_2;
454                 /* No length footer-- mark it with a special
455                  * value. */
456                 len_footer = (unsigned)(-1);
457         } else {
458                 len_header = LZX_NUM_PRIMARY_LENS;
459                 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
460         }
461
462         /* Combine the position slot with the length header into a single symbol
463          * that will be encoded with the main code.
464          *
465          * The actual main symbol is offset by LZX_NUM_CHARS because values
466          * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
467          * match.  */
468         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
469
470         /* Output main symbol. */
471         bitstream_put_bits(out, codes->codewords.main[main_symbol],
472                            codes->lens.main[main_symbol]);
473
474         /* If there is a length footer, output it using the
475          * length Huffman code. */
476         if (len_footer != (unsigned)(-1)) {
477                 bitstream_put_bits(out, codes->codewords.len[len_footer],
478                                    codes->lens.len[len_footer]);
479         }
480
481         num_extra_bits = lzx_get_num_extra_bits(position_slot);
482
483         /* For aligned offset blocks with at least 3 extra bits, output the
484          * verbatim bits literally, then the aligned bits encoded using the
485          * aligned offset code.  Otherwise, only the verbatim bits need to be
486          * output. */
487         if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
488
489                 verbatim_bits = position_footer >> 3;
490                 bitstream_put_bits(out, verbatim_bits,
491                                    num_extra_bits - 3);
492
493                 aligned_bits = (position_footer & 7);
494                 bitstream_put_bits(out,
495                                    codes->codewords.aligned[aligned_bits],
496                                    codes->lens.aligned[aligned_bits]);
497         } else {
498                 /* verbatim bits is the same as the position
499                  * footer, in this case. */
500                 bitstream_put_bits(out, position_footer, num_extra_bits);
501         }
502 }
503
504 static unsigned
505 lzx_build_precode(const u8 lens[restrict],
506                   const u8 prev_lens[restrict],
507                   const unsigned num_syms,
508                   input_idx_t precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
509                   u8 output_syms[restrict num_syms],
510                   u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
511                   u16 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
512                   unsigned *num_additional_bits_ret)
513 {
514         memset(precode_freqs, 0,
515                LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
516
517         /* Since the code word lengths use a form of RLE encoding, the goal here
518          * is to find each run of identical lengths when going through them in
519          * symbol order (including runs of length 1).  For each run, as many
520          * lengths are encoded using RLE as possible, and the rest are output
521          * literally.
522          *
523          * output_syms[] will be filled in with the length symbols that will be
524          * output, including RLE codes, not yet encoded using the precode.
525          *
526          * cur_run_len keeps track of how many code word lengths are in the
527          * current run of identical lengths.  */
528         unsigned output_syms_idx = 0;
529         unsigned cur_run_len = 1;
530         unsigned num_additional_bits = 0;
531         for (unsigned i = 1; i <= num_syms; i++) {
532
533                 if (i != num_syms && lens[i] == lens[i - 1]) {
534                         /* Still in a run--- keep going. */
535                         cur_run_len++;
536                         continue;
537                 }
538
539                 /* Run ended! Check if it is a run of zeroes or a run of
540                  * nonzeroes. */
541
542                 /* The symbol that was repeated in the run--- not to be confused
543                  * with the length *of* the run (cur_run_len) */
544                 unsigned len_in_run = lens[i - 1];
545
546                 if (len_in_run == 0) {
547                         /* A run of 0's.  Encode it in as few length
548                          * codes as we can. */
549
550                         /* The magic length 18 indicates a run of 20 + n zeroes,
551                          * where n is an uncompressed literal 5-bit integer that
552                          * follows the magic length. */
553                         while (cur_run_len >= 20) {
554                                 unsigned additional_bits;
555
556                                 additional_bits = min(cur_run_len - 20, 0x1f);
557                                 num_additional_bits += 5;
558                                 precode_freqs[18]++;
559                                 output_syms[output_syms_idx++] = 18;
560                                 output_syms[output_syms_idx++] = additional_bits;
561                                 cur_run_len -= 20 + additional_bits;
562                         }
563
564                         /* The magic length 17 indicates a run of 4 + n zeroes,
565                          * where n is an uncompressed literal 4-bit integer that
566                          * follows the magic length. */
567                         while (cur_run_len >= 4) {
568                                 unsigned additional_bits;
569
570                                 additional_bits = min(cur_run_len - 4, 0xf);
571                                 num_additional_bits += 4;
572                                 precode_freqs[17]++;
573                                 output_syms[output_syms_idx++] = 17;
574                                 output_syms[output_syms_idx++] = additional_bits;
575                                 cur_run_len -= 4 + additional_bits;
576                         }
577
578                 } else {
579
580                         /* A run of nonzero lengths. */
581
582                         /* The magic length 19 indicates a run of 4 + n
583                          * nonzeroes, where n is a literal bit that follows the
584                          * magic length, and where the value of the lengths in
585                          * the run is given by an extra length symbol, encoded
586                          * with the precode, that follows the literal bit.
587                          *
588                          * The extra length symbol is encoded as a difference
589                          * from the length of the codeword for the first symbol
590                          * in the run in the previous code.
591                          * */
592                         while (cur_run_len >= 4) {
593                                 unsigned additional_bits;
594                                 signed char delta;
595
596                                 additional_bits = (cur_run_len > 4);
597                                 num_additional_bits += 1;
598                                 delta = (signed char)prev_lens[i - cur_run_len] -
599                                         (signed char)len_in_run;
600                                 if (delta < 0)
601                                         delta += 17;
602                                 precode_freqs[19]++;
603                                 precode_freqs[(unsigned char)delta]++;
604                                 output_syms[output_syms_idx++] = 19;
605                                 output_syms[output_syms_idx++] = additional_bits;
606                                 output_syms[output_syms_idx++] = delta;
607                                 cur_run_len -= 4 + additional_bits;
608                         }
609                 }
610
611                 /* Any remaining lengths in the run are outputted without RLE,
612                  * as a difference from the length of that codeword in the
613                  * previous code. */
614                 while (cur_run_len > 0) {
615                         signed char delta;
616
617                         delta = (signed char)prev_lens[i - cur_run_len] -
618                                 (signed char)len_in_run;
619                         if (delta < 0)
620                                 delta += 17;
621
622                         precode_freqs[(unsigned char)delta]++;
623                         output_syms[output_syms_idx++] = delta;
624                         cur_run_len--;
625                 }
626
627                 cur_run_len = 1;
628         }
629
630         /* Build the precode from the frequencies of the length symbols. */
631
632         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
633                                     LZX_MAX_PRE_CODEWORD_LEN,
634                                     precode_freqs, precode_lens,
635                                     precode_codewords);
636
637         *num_additional_bits_ret = num_additional_bits;
638
639         return output_syms_idx;
640 }
641
642 /*
643  * Writes a compressed Huffman code to the output, preceded by the precode for
644  * it.
645  *
646  * The Huffman code is represented in the output as a series of path lengths
647  * from which the canonical Huffman code can be reconstructed.  The path lengths
648  * themselves are compressed using a separate Huffman code, the precode, which
649  * consists of LZX_PRECODE_NUM_SYMBOLS (= 20) symbols that cover all possible
650  * code lengths, plus extra codes for repeated lengths.  The path lengths of the
651  * precode precede the path lengths of the larger code and are uncompressed,
652  * consisting of 20 entries of 4 bits each.
653  *
654  * @out:                Bitstream to write the code to.
655  * @lens:               The code lengths for the Huffman code, indexed by symbol.
656  * @prev_lens:          Code lengths for this Huffman code, indexed by symbol,
657  *                      in the *previous block*, or all zeroes if this is the
658  *                      first block.
659  * @num_syms:           The number of symbols in the code.
660  */
661 static void
662 lzx_write_compressed_code(struct output_bitstream *out,
663                           const u8 lens[restrict],
664                           const u8 prev_lens[restrict],
665                           unsigned num_syms)
666 {
667         input_idx_t precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
668         u8 output_syms[num_syms];
669         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
670         u16 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
671         unsigned i;
672         unsigned num_output_syms;
673         u8 precode_sym;
674         unsigned dummy;
675
676         num_output_syms = lzx_build_precode(lens,
677                                             prev_lens,
678                                             num_syms,
679                                             precode_freqs,
680                                             output_syms,
681                                             precode_lens,
682                                             precode_codewords,
683                                             &dummy);
684
685         /* Write the lengths of the precode codes to the output. */
686         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
687                 bitstream_put_bits(out, precode_lens[i],
688                                    LZX_PRECODE_ELEMENT_SIZE);
689
690         /* Write the length symbols, encoded with the precode, to the output. */
691
692         for (i = 0; i < num_output_syms; ) {
693                 precode_sym = output_syms[i++];
694
695                 bitstream_put_bits(out, precode_codewords[precode_sym],
696                                    precode_lens[precode_sym]);
697                 switch (precode_sym) {
698                 case 17:
699                         bitstream_put_bits(out, output_syms[i++], 4);
700                         break;
701                 case 18:
702                         bitstream_put_bits(out, output_syms[i++], 5);
703                         break;
704                 case 19:
705                         bitstream_put_bits(out, output_syms[i++], 1);
706                         bitstream_put_bits(out,
707                                            precode_codewords[output_syms[i]],
708                                            precode_lens[output_syms[i]]);
709                         i++;
710                         break;
711                 default:
712                         break;
713                 }
714         }
715 }
716
717 /*
718  * Writes all compressed matches and literal bytes in an LZX block to the the
719  * output bitstream.
720  *
721  * @ostream
722  *      The output bitstream.
723  * @block_type
724  *      The type of the block (LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM).
725  * @match_tab
726  *      The array of matches/literals that will be output (length @match_count).
727  * @match_count
728  *      Number of matches/literals to be output.
729  * @codes
730  *      Pointer to a structure that contains the codewords for the main, length,
731  *      and aligned offset Huffman codes.
732  */
733 static void
734 lzx_write_matches_and_literals(struct output_bitstream *ostream,
735                                int block_type,
736                                const struct lzx_match match_tab[],
737                                unsigned match_count,
738                                const struct lzx_codes *codes)
739 {
740         for (unsigned i = 0; i < match_count; i++) {
741                 struct lzx_match match = match_tab[i];
742
743                 /* High bit of the match indicates whether the match is an
744                  * actual match (1) or a literal uncompressed byte (0)  */
745                 if (match.data & 0x80000000) {
746                         /* match */
747                         lzx_write_match(ostream, block_type,
748                                         match, codes);
749                 } else {
750                         /* literal byte */
751                         bitstream_put_bits(ostream,
752                                            codes->codewords.main[match.data],
753                                            codes->lens.main[match.data]);
754                 }
755         }
756 }
757
758 static void
759 lzx_assert_codes_valid(const struct lzx_codes * codes, unsigned num_main_syms)
760 {
761 #ifdef ENABLE_LZX_DEBUG
762         unsigned i;
763
764         for (i = 0; i < num_main_syms; i++)
765                 LZX_ASSERT(codes->lens.main[i] <= LZX_MAX_MAIN_CODEWORD_LEN);
766
767         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
768                 LZX_ASSERT(codes->lens.len[i] <= LZX_MAX_LEN_CODEWORD_LEN);
769
770         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
771                 LZX_ASSERT(codes->lens.aligned[i] <= LZX_MAX_ALIGNED_CODEWORD_LEN);
772
773         const unsigned tablebits = 10;
774         u16 decode_table[(1 << tablebits) +
775                          (2 * max(num_main_syms, LZX_LENCODE_NUM_SYMBOLS))]
776                          _aligned_attribute(DECODE_TABLE_ALIGNMENT);
777         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
778                                                   num_main_syms,
779                                                   min(tablebits, LZX_MAINCODE_TABLEBITS),
780                                                   codes->lens.main,
781                                                   LZX_MAX_MAIN_CODEWORD_LEN));
782         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
783                                                   LZX_LENCODE_NUM_SYMBOLS,
784                                                   min(tablebits, LZX_LENCODE_TABLEBITS),
785                                                   codes->lens.len,
786                                                   LZX_MAX_LEN_CODEWORD_LEN));
787         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
788                                                   LZX_ALIGNEDCODE_NUM_SYMBOLS,
789                                                   min(tablebits, LZX_ALIGNEDCODE_TABLEBITS),
790                                                   codes->lens.aligned,
791                                                   LZX_MAX_ALIGNED_CODEWORD_LEN));
792 #endif /* ENABLE_LZX_DEBUG */
793 }
794
795 /* Write an LZX aligned offset or verbatim block to the output.  */
796 static void
797 lzx_write_compressed_block(int block_type,
798                            unsigned block_size,
799                            unsigned max_window_size,
800                            unsigned num_main_syms,
801                            struct lzx_match * chosen_matches,
802                            unsigned num_chosen_matches,
803                            const struct lzx_codes * codes,
804                            const struct lzx_codes * prev_codes,
805                            struct output_bitstream * ostream)
806 {
807         unsigned i;
808
809         LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
810                    block_type == LZX_BLOCKTYPE_VERBATIM);
811         lzx_assert_codes_valid(codes, num_main_syms);
812
813         /* The first three bits indicate the type of block and are one of the
814          * LZX_BLOCKTYPE_* constants.  */
815         bitstream_put_bits(ostream, block_type, 3);
816
817         /* Output the block size.
818          *
819          * The original LZX format seemed to always encode the block size in 3
820          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
821          * uses the first bit to indicate whether the block is the default size
822          * (32768) or a different size given explicitly by the next 16 bits.
823          *
824          * By default, this compressor uses a window size of 32768 and therefore
825          * follows the WIMGAPI behavior.  However, this compressor also supports
826          * window sizes greater than 32768 bytes, which do not appear to be
827          * supported by WIMGAPI.  In such cases, we retain the default size bit
828          * to mean a size of 32768 bytes but output non-default block size in 24
829          * bits rather than 16.  The compatibility of this behavior is unknown
830          * because WIMs created with chunk size greater than 32768 can seemingly
831          * only be opened by wimlib anyway.  */
832         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
833                 bitstream_put_bits(ostream, 1, 1);
834         } else {
835                 bitstream_put_bits(ostream, 0, 1);
836
837                 if (max_window_size >= 65536)
838                         bitstream_put_bits(ostream, block_size >> 16, 8);
839
840                 bitstream_put_bits(ostream, block_size, 16);
841         }
842
843         /* Write out lengths of the main code. Note that the LZX specification
844          * incorrectly states that the aligned offset code comes after the
845          * length code, but in fact it is the very first code to be written
846          * (before the main code).  */
847         if (block_type == LZX_BLOCKTYPE_ALIGNED)
848                 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
849                         bitstream_put_bits(ostream, codes->lens.aligned[i],
850                                            LZX_ALIGNEDCODE_ELEMENT_SIZE);
851
852         LZX_DEBUG("Writing main code...");
853
854         /* Write the precode and lengths for the first LZX_NUM_CHARS symbols in
855          * the main code, which are the codewords for literal bytes.  */
856         lzx_write_compressed_code(ostream,
857                                   codes->lens.main,
858                                   prev_codes->lens.main,
859                                   LZX_NUM_CHARS);
860
861         /* Write the precode and lengths for the rest of the main code, which
862          * are the codewords for match headers.  */
863         lzx_write_compressed_code(ostream,
864                                   codes->lens.main + LZX_NUM_CHARS,
865                                   prev_codes->lens.main + LZX_NUM_CHARS,
866                                   num_main_syms - LZX_NUM_CHARS);
867
868         LZX_DEBUG("Writing length code...");
869
870         /* Write the precode and lengths for the length code.  */
871         lzx_write_compressed_code(ostream,
872                                   codes->lens.len,
873                                   prev_codes->lens.len,
874                                   LZX_LENCODE_NUM_SYMBOLS);
875
876         LZX_DEBUG("Writing matches and literals...");
877
878         /* Write the actual matches and literals.  */
879         lzx_write_matches_and_literals(ostream, block_type,
880                                        chosen_matches, num_chosen_matches,
881                                        codes);
882
883         LZX_DEBUG("Done writing block.");
884 }
885
886 /* Write out the LZX blocks that were computed.  */
887 static void
888 lzx_write_all_blocks(struct lzx_compressor *ctx, struct output_bitstream *ostream)
889 {
890
891         const struct lzx_codes *prev_codes = &ctx->zero_codes;
892         for (unsigned i = 0; i < ctx->num_blocks; i++) {
893                 const struct lzx_block_spec *spec = &ctx->block_specs[i];
894
895                 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_matches=%u)...",
896                           i + 1, ctx->num_blocks,
897                           spec->block_type, spec->block_size,
898                           spec->num_chosen_matches);
899
900                 lzx_write_compressed_block(spec->block_type,
901                                            spec->block_size,
902                                            ctx->max_window_size,
903                                            ctx->num_main_syms,
904                                            &ctx->chosen_matches[spec->chosen_matches_start_pos],
905                                            spec->num_chosen_matches,
906                                            &spec->codes,
907                                            prev_codes,
908                                            ostream);
909
910                 prev_codes = &spec->codes;
911         }
912 }
913
914 /* Constructs an LZX match from a literal byte and updates the main code symbol
915  * frequencies.  */
916 static u32
917 lzx_tally_literal(u8 lit, struct lzx_freqs *freqs)
918 {
919         freqs->main[lit]++;
920         return (u32)lit;
921 }
922
923 /* Constructs an LZX match from an offset and a length, and updates the LRU
924  * queue and the frequency of symbols in the main, length, and aligned offset
925  * alphabets.  The return value is a 32-bit number that provides the match in an
926  * intermediate representation documented below.  */
927 static u32
928 lzx_tally_match(unsigned match_len, unsigned match_offset,
929                 struct lzx_freqs *freqs, struct lzx_lru_queue *queue)
930 {
931         unsigned position_slot;
932         unsigned position_footer;
933         u32 len_header;
934         unsigned main_symbol;
935         unsigned len_footer;
936         unsigned adjusted_match_len;
937
938         LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
939
940         /* The match offset shall be encoded as a position slot (itself encoded
941          * as part of the main symbol) and a position footer.  */
942         position_slot = lzx_get_position_slot(match_offset, queue);
943         position_footer = (match_offset + LZX_OFFSET_OFFSET) &
944                                 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
945
946         /* The match length shall be encoded as a length header (itself encoded
947          * as part of the main symbol) and an optional length footer.  */
948         adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
949         if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
950                 /* No length footer needed.  */
951                 len_header = adjusted_match_len;
952         } else {
953                 /* Length footer needed.  It will be encoded using the length
954                  * code.  */
955                 len_header = LZX_NUM_PRIMARY_LENS;
956                 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
957                 freqs->len[len_footer]++;
958         }
959
960         /* Account for the main symbol.  */
961         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
962
963         freqs->main[main_symbol]++;
964
965         /* In an aligned offset block, 3 bits of the position footer are output
966          * as an aligned offset symbol.  Account for this, although we may
967          * ultimately decide to output the block as verbatim.  */
968
969         /* The following check is equivalent to:
970          *
971          * if (lzx_extra_bits[position_slot] >= 3)
972          *
973          * Note that this correctly excludes position slots that correspond to
974          * recent offsets.  */
975         if (position_slot >= 8)
976                 freqs->aligned[position_footer & 7]++;
977
978         /* Pack the position slot, position footer, and match length into an
979          * intermediate representation.  See `struct lzx_match' for details.
980          */
981         LZX_ASSERT(LZX_MAX_POSITION_SLOTS <= 64);
982         LZX_ASSERT(lzx_get_num_extra_bits(LZX_MAX_POSITION_SLOTS - 1) <= 17);
983         LZX_ASSERT(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 <= 256);
984
985         LZX_ASSERT(position_slot      <= (1U << (31 - 25)) - 1);
986         LZX_ASSERT(position_footer    <= (1U << (25 -  8)) - 1);
987         LZX_ASSERT(adjusted_match_len <= (1U << (8  -  0)) - 1);
988         return 0x80000000 |
989                 (position_slot << 25) |
990                 (position_footer << 8) |
991                 (adjusted_match_len);
992 }
993
994 struct lzx_record_ctx {
995         struct lzx_freqs freqs;
996         struct lzx_lru_queue queue;
997         struct lzx_match *matches;
998 };
999
1000 static void
1001 lzx_record_match(unsigned len, unsigned offset, void *_ctx)
1002 {
1003         struct lzx_record_ctx *ctx = _ctx;
1004
1005         (ctx->matches++)->data = lzx_tally_match(len, offset, &ctx->freqs, &ctx->queue);
1006 }
1007
1008 static void
1009 lzx_record_literal(u8 lit, void *_ctx)
1010 {
1011         struct lzx_record_ctx *ctx = _ctx;
1012
1013         (ctx->matches++)->data = lzx_tally_literal(lit, &ctx->freqs);
1014 }
1015
1016 /* Returns the cost, in bits, to output a literal byte using the specified cost
1017  * model.  */
1018 static unsigned
1019 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1020 {
1021         return costs->main[c];
1022 }
1023
1024 /* Given a (length, offset) pair that could be turned into a valid LZX match as
1025  * well as costs for the codewords in the main, length, and aligned Huffman
1026  * codes, return the approximate number of bits it will take to represent this
1027  * match in the compressed output.  Take into account the match offset LRU
1028  * queue and optionally update it.  */
1029 static unsigned
1030 lzx_match_cost(unsigned length, unsigned offset, const struct lzx_costs *costs,
1031                struct lzx_lru_queue *queue)
1032 {
1033         unsigned position_slot;
1034         unsigned len_header, main_symbol;
1035         unsigned cost = 0;
1036
1037         position_slot = lzx_get_position_slot(offset, queue);
1038
1039         len_header = min(length - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1040         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1041
1042         /* Account for main symbol.  */
1043         cost += costs->main[main_symbol];
1044
1045         /* Account for extra position information.  */
1046         unsigned num_extra_bits = lzx_get_num_extra_bits(position_slot);
1047         if (num_extra_bits >= 3) {
1048                 cost += num_extra_bits - 3;
1049                 cost += costs->aligned[(offset + LZX_OFFSET_OFFSET) & 7];
1050         } else {
1051                 cost += num_extra_bits;
1052         }
1053
1054         /* Account for extra length information.  */
1055         if (len_header == LZX_NUM_PRIMARY_LENS)
1056                 cost += costs->len[length - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1057
1058         return cost;
1059
1060 }
1061
1062 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
1063  * Unlike lzx_match_cost() which does a true cost evaluation, this simply
1064  * prioritize matches based on their offset.  */
1065 static input_idx_t
1066 lzx_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_queue)
1067 {
1068         const struct lzx_lru_queue *queue = _queue;
1069
1070         /* It seems well worth it to take the time to give priority to recently
1071          * used offsets.  */
1072         for (input_idx_t i = 0; i < LZX_NUM_RECENT_OFFSETS; i++)
1073                 if (offset == queue->R[i])
1074                         return i;
1075
1076         return offset;
1077 }
1078
1079 /* Set the cost model @ctx->costs from the Huffman codeword lengths specified in
1080  * @lens.
1081  *
1082  * The cost model and codeword lengths are almost the same thing, but the
1083  * Huffman codewords with length 0 correspond to symbols with zero frequency
1084  * that still need to be assigned actual costs.  The specific values assigned
1085  * are arbitrary, but they should be fairly high (near the maximum codeword
1086  * length) to take into account the fact that uses of these symbols are expected
1087  * to be rare.  */
1088 static void
1089 lzx_set_costs(struct lzx_compressor * ctx, const struct lzx_lens * lens)
1090 {
1091         unsigned i;
1092         unsigned num_main_syms = ctx->num_main_syms;
1093
1094         /* Main code  */
1095         for (i = 0; i < num_main_syms; i++) {
1096                 ctx->costs.main[i] = lens->main[i];
1097                 if (ctx->costs.main[i] == 0)
1098                         ctx->costs.main[i] = ctx->params.alg_params.slow.main_nostat_cost;
1099         }
1100
1101         /* Length code  */
1102         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1103                 ctx->costs.len[i] = lens->len[i];
1104                 if (ctx->costs.len[i] == 0)
1105                         ctx->costs.len[i] = ctx->params.alg_params.slow.len_nostat_cost;
1106         }
1107
1108         /* Aligned offset code  */
1109         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1110                 ctx->costs.aligned[i] = lens->aligned[i];
1111                 if (ctx->costs.aligned[i] == 0)
1112                         ctx->costs.aligned[i] = ctx->params.alg_params.slow.aligned_nostat_cost;
1113         }
1114 }
1115
1116 /* Tell the match-finder to skip the specified number of bytes (@n) in the
1117  * input.  */
1118 static void
1119 lzx_lz_skip_bytes(struct lzx_compressor *ctx, input_idx_t n)
1120 {
1121         LZX_ASSERT(n <= ctx->match_window_end - ctx->match_window_pos);
1122         if (ctx->matches_cached) {
1123                 ctx->match_window_pos += n;
1124                 while (n--) {
1125                         ctx->cached_matches_pos +=
1126                                 ctx->cached_matches[ctx->cached_matches_pos].len + 1;
1127                 }
1128         } else {
1129                 while (n--) {
1130                         ctx->cached_matches[ctx->cached_matches_pos++].len = 0;
1131                         lz_sarray_skip_position(&ctx->lz_sarray);
1132                         ctx->match_window_pos++;
1133                 }
1134                 LZX_ASSERT(lz_sarray_get_pos(&ctx->lz_sarray) == ctx->match_window_pos);
1135         }
1136 }
1137
1138 /* Retrieve a list of matches available at the next position in the input.
1139  *
1140  * The matches are written to ctx->matches in decreasing order of length, and
1141  * the return value is the number of matches found.  */
1142 static u32
1143 lzx_lz_get_matches_caching(struct lzx_compressor *ctx,
1144                            const struct lzx_lru_queue *queue,
1145                            struct raw_match **matches_ret)
1146 {
1147         u32 num_matches;
1148         struct raw_match *matches;
1149
1150         LZX_ASSERT(ctx->match_window_pos <= ctx->match_window_end);
1151
1152         matches = &ctx->cached_matches[ctx->cached_matches_pos + 1];
1153
1154         if (ctx->matches_cached) {
1155                 num_matches = matches[-1].len;
1156         } else {
1157                 LZX_ASSERT(lz_sarray_get_pos(&ctx->lz_sarray) == ctx->match_window_pos);
1158                 num_matches = lz_sarray_get_matches(&ctx->lz_sarray,
1159                                                     matches,
1160                                                     lzx_match_cost_fast,
1161                                                     queue);
1162                 matches[-1].len = num_matches;
1163         }
1164         ctx->cached_matches_pos += num_matches + 1;
1165         *matches_ret = matches;
1166
1167         /* Cap the length of returned matches to the number of bytes remaining,
1168          * if it is not the whole window.  */
1169         if (ctx->match_window_end < ctx->window_size) {
1170                 unsigned maxlen = ctx->match_window_end - ctx->match_window_pos;
1171                 for (u32 i = 0; i < num_matches; i++)
1172                         if (matches[i].len > maxlen)
1173                                 matches[i].len = maxlen;
1174         }
1175 #if 0
1176         fprintf(stderr, "Pos %u/%u: %u matches\n",
1177                 ctx->match_window_pos, ctx->match_window_end, num_matches);
1178         for (unsigned i = 0; i < num_matches; i++)
1179                 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
1180 #endif
1181
1182 #ifdef ENABLE_LZX_DEBUG
1183         for (u32 i = 0; i < num_matches; i++) {
1184                 LZX_ASSERT(matches[i].len >= LZX_MIN_MATCH_LEN);
1185                 LZX_ASSERT(matches[i].len <= LZX_MAX_MATCH_LEN);
1186                 LZX_ASSERT(matches[i].len <= ctx->match_window_end - ctx->match_window_pos);
1187                 LZX_ASSERT(matches[i].offset > 0);
1188                 LZX_ASSERT(matches[i].offset <= ctx->match_window_pos);
1189                 LZX_ASSERT(!memcmp(&ctx->window[ctx->match_window_pos],
1190                                    &ctx->window[ctx->match_window_pos - matches[i].offset],
1191                                    matches[i].len));
1192         }
1193 #endif
1194
1195         ctx->match_window_pos++;
1196         return num_matches;
1197 }
1198
1199 static u32
1200 lzx_get_prev_literal_cost(struct lzx_compressor *ctx,
1201                           struct lzx_lru_queue *queue)
1202 {
1203         return lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1204                                 &ctx->costs);
1205 }
1206
1207 static u32
1208 lzx_get_match_cost(struct lzx_compressor *ctx,
1209                    struct lzx_lru_queue *queue,
1210                    input_idx_t length, input_idx_t offset)
1211 {
1212         return lzx_match_cost(length, offset, &ctx->costs, queue);
1213 }
1214
1215 static struct raw_match
1216 lzx_lz_get_near_optimal_match(struct lzx_compressor *ctx)
1217 {
1218         return lz_get_near_optimal_match(&ctx->mc,
1219                                          lzx_lz_get_matches_caching,
1220                                          lzx_lz_skip_bytes,
1221                                          lzx_get_prev_literal_cost,
1222                                          lzx_get_match_cost,
1223                                          ctx,
1224                                          &ctx->queue);
1225 }
1226
1227 /*
1228  * Set default symbol costs.
1229  */
1230 static void
1231 lzx_set_default_costs(struct lzx_costs * costs, unsigned num_main_syms)
1232 {
1233         unsigned i;
1234
1235         /* Literal symbols  */
1236         for (i = 0; i < LZX_NUM_CHARS; i++)
1237                 costs->main[i] = 8;
1238
1239         /* Match header symbols  */
1240         for (; i < num_main_syms; i++)
1241                 costs->main[i] = 10;
1242
1243         /* Length symbols  */
1244         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1245                 costs->len[i] = 8;
1246
1247         /* Aligned offset symbols  */
1248         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1249                 costs->aligned[i] = 3;
1250 }
1251
1252 /* Given the frequencies of symbols in a compressed block and the corresponding
1253  * Huffman codes, return LZX_BLOCKTYPE_ALIGNED or LZX_BLOCKTYPE_VERBATIM if an
1254  * aligned offset or verbatim block, respectively, will take fewer bits to
1255  * output.  */
1256 static int
1257 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1258                                const struct lzx_codes * codes)
1259 {
1260         unsigned aligned_cost = 0;
1261         unsigned verbatim_cost = 0;
1262
1263         /* Verbatim blocks have a constant 3 bits per position footer.  Aligned
1264          * offset blocks have an aligned offset symbol per position footer, plus
1265          * an extra 24 bits to output the lengths necessary to reconstruct the
1266          * aligned offset code itself.  */
1267         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1268                 verbatim_cost += 3 * freqs->aligned[i];
1269                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1270         }
1271         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1272         if (aligned_cost < verbatim_cost)
1273                 return LZX_BLOCKTYPE_ALIGNED;
1274         else
1275                 return LZX_BLOCKTYPE_VERBATIM;
1276 }
1277
1278 /* Find a near-optimal sequence of matches/literals with which to output the
1279  * specified LZX block, then set its type to that which has the minimum cost to
1280  * output.  */
1281 static void
1282 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1283                    unsigned num_passes)
1284 {
1285         const struct lzx_lru_queue orig_queue = ctx->queue;
1286         struct lzx_freqs freqs;
1287
1288         unsigned orig_window_pos = spec->window_pos;
1289         unsigned orig_cached_pos = ctx->cached_matches_pos;
1290
1291         LZX_ASSERT(ctx->match_window_pos == spec->window_pos);
1292
1293         ctx->match_window_end = spec->window_pos + spec->block_size;
1294         spec->chosen_matches_start_pos = spec->window_pos;
1295
1296         LZX_ASSERT(num_passes >= 1);
1297
1298         /* The first optimal parsing pass is done using the cost model already
1299          * set in ctx->costs.  Each later pass is done using a cost model
1300          * computed from the previous pass.  */
1301         for (unsigned pass = 0; pass < num_passes; pass++) {
1302
1303                 ctx->match_window_pos = orig_window_pos;
1304                 ctx->cached_matches_pos = orig_cached_pos;
1305                 ctx->queue = orig_queue;
1306                 spec->num_chosen_matches = 0;
1307                 memset(&freqs, 0, sizeof(freqs));
1308
1309                 for (unsigned i = spec->window_pos; i < spec->window_pos + spec->block_size; ) {
1310                         struct raw_match raw_match;
1311                         struct lzx_match lzx_match;
1312
1313                         raw_match = lzx_lz_get_near_optimal_match(ctx);
1314                         if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1315                                 if (unlikely(raw_match.len == LZX_MIN_MATCH_LEN &&
1316                                              raw_match.offset == ctx->max_window_size -
1317                                                                  LZX_MIN_MATCH_LEN))
1318                                 {
1319                                         /* Degenerate case where the parser
1320                                          * generated the minimum match length
1321                                          * with the maximum offset.  There
1322                                          * aren't actually enough position slots
1323                                          * to represent this offset, as noted in
1324                                          * the comments in
1325                                          * lzx_get_num_main_syms(), so we cannot
1326                                          * allow it.  Use literals instead.
1327                                          *
1328                                          * Note that this case only occurs if
1329                                          * the match-finder can generate matches
1330                                          * to the very start of the window.  The
1331                                          * suffix array match-finder can,
1332                                          * although typical hash chain and
1333                                          * binary tree match-finders use 0 as a
1334                                          * null value and therefore cannot
1335                                          * generate such matches.  */
1336                                         BUILD_BUG_ON(LZX_MIN_MATCH_LEN != 2);
1337                                         lzx_match.data = lzx_tally_literal(ctx->window[i],
1338                                                                            &freqs);
1339                                         i += 1;
1340                                         ctx->chosen_matches[spec->chosen_matches_start_pos +
1341                                                             spec->num_chosen_matches++]
1342                                                             = lzx_match;
1343                                         lzx_match.data = lzx_tally_literal(ctx->window[i],
1344                                                                            &freqs);
1345                                         i += 1;
1346                                 } else {
1347                                         lzx_match.data = lzx_tally_match(raw_match.len,
1348                                                                          raw_match.offset,
1349                                                                          &freqs,
1350                                                                          &ctx->queue);
1351                                         i += raw_match.len;
1352                                 }
1353                         } else {
1354                                 lzx_match.data = lzx_tally_literal(ctx->window[i], &freqs);
1355                                 i += 1;
1356                         }
1357                         ctx->chosen_matches[spec->chosen_matches_start_pos +
1358                                             spec->num_chosen_matches++] = lzx_match;
1359                 }
1360
1361                 lzx_make_huffman_codes(&freqs, &spec->codes,
1362                                        ctx->num_main_syms);
1363                 if (pass < num_passes - 1)
1364                         lzx_set_costs(ctx, &spec->codes.lens);
1365                 ctx->matches_cached = true;
1366         }
1367         spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
1368         ctx->matches_cached = false;
1369 }
1370
1371 static void
1372 lzx_optimize_blocks(struct lzx_compressor *ctx)
1373 {
1374         lzx_lru_queue_init(&ctx->queue);
1375         lz_match_chooser_begin(&ctx->mc);
1376
1377         const unsigned num_passes = ctx->params.alg_params.slow.num_optim_passes;
1378
1379         for (unsigned i = 0; i < ctx->num_blocks; i++)
1380                 lzx_optimize_block(ctx, &ctx->block_specs[i], num_passes);
1381 }
1382
1383 /* Prepare the input window into one or more LZX blocks ready to be output.  */
1384 static void
1385 lzx_prepare_blocks(struct lzx_compressor * ctx)
1386 {
1387         /* Initialize the match-finder.  */
1388         lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
1389         ctx->cached_matches_pos = 0;
1390         ctx->matches_cached = false;
1391         ctx->match_window_pos = 0;
1392
1393         /* Set up a default cost model.  */
1394         lzx_set_default_costs(&ctx->costs, ctx->num_main_syms);
1395
1396         ctx->num_blocks = DIV_ROUND_UP(ctx->window_size, LZX_DIV_BLOCK_SIZE);
1397         for (unsigned i = 0; i < ctx->num_blocks; i++) {
1398                 unsigned pos = LZX_DIV_BLOCK_SIZE * i;
1399                 ctx->block_specs[i].window_pos = pos;
1400                 ctx->block_specs[i].block_size = min(ctx->window_size - pos, LZX_DIV_BLOCK_SIZE);
1401         }
1402
1403         /* Determine sequence of matches/literals to output for each block.  */
1404         lzx_optimize_blocks(ctx);
1405 }
1406
1407 /*
1408  * This is the fast version of lzx_prepare_blocks().  This version "quickly"
1409  * prepares a single compressed block containing the entire input.  See the
1410  * description of the "Fast algorithm" at the beginning of this file for more
1411  * information.
1412  *
1413  * Input ---  the preprocessed data:
1414  *
1415  *      ctx->window[]
1416  *      ctx->window_size
1417  *
1418  * Output --- the block specification and the corresponding match/literal data:
1419  *
1420  *      ctx->block_specs[]
1421  *      ctx->num_blocks
1422  *      ctx->chosen_matches[]
1423  */
1424 static void
1425 lzx_prepare_block_fast(struct lzx_compressor * ctx)
1426 {
1427         struct lzx_record_ctx record_ctx;
1428         struct lzx_block_spec *spec;
1429
1430         /* Parameters to hash chain LZ match finder
1431          * (lazy with 1 match lookahead)  */
1432         static const struct lz_params lzx_lz_params = {
1433                 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
1434                  * aren't worth choosing when using greedy or lazy parsing.  */
1435                 .min_match      = 3,
1436                 .max_match      = LZX_MAX_MATCH_LEN,
1437                 .max_offset     = LZX_MAX_WINDOW_SIZE,
1438                 .good_match     = LZX_MAX_MATCH_LEN,
1439                 .nice_match     = LZX_MAX_MATCH_LEN,
1440                 .max_chain_len  = LZX_MAX_MATCH_LEN,
1441                 .max_lazy_match = LZX_MAX_MATCH_LEN,
1442                 .too_far        = 4096,
1443         };
1444
1445         /* Initialize symbol frequencies and match offset LRU queue.  */
1446         memset(&record_ctx.freqs, 0, sizeof(struct lzx_freqs));
1447         lzx_lru_queue_init(&record_ctx.queue);
1448         record_ctx.matches = ctx->chosen_matches;
1449
1450         /* Determine series of matches/literals to output.  */
1451         lz_analyze_block(ctx->window,
1452                          ctx->window_size,
1453                          lzx_record_match,
1454                          lzx_record_literal,
1455                          &record_ctx,
1456                          &lzx_lz_params,
1457                          ctx->prev_tab);
1458
1459         /* Set up block specification.  */
1460         spec = &ctx->block_specs[0];
1461         spec->block_type = LZX_BLOCKTYPE_ALIGNED;
1462         spec->window_pos = 0;
1463         spec->block_size = ctx->window_size;
1464         spec->num_chosen_matches = (record_ctx.matches - ctx->chosen_matches);
1465         spec->chosen_matches_start_pos = 0;
1466         lzx_make_huffman_codes(&record_ctx.freqs, &spec->codes,
1467                                ctx->num_main_syms);
1468         ctx->num_blocks = 1;
1469 }
1470
1471 static void
1472 do_call_insn_translation(u32 *call_insn_target, int input_pos,
1473                          s32 file_size)
1474 {
1475         s32 abs_offset;
1476         s32 rel_offset;
1477
1478         rel_offset = le32_to_cpu(*call_insn_target);
1479         if (rel_offset >= -input_pos && rel_offset < file_size) {
1480                 if (rel_offset < file_size - input_pos) {
1481                         /* "good translation" */
1482                         abs_offset = rel_offset + input_pos;
1483                 } else {
1484                         /* "compensating translation" */
1485                         abs_offset = rel_offset - file_size;
1486                 }
1487                 *call_insn_target = cpu_to_le32(abs_offset);
1488         }
1489 }
1490
1491 /* This is the reverse of undo_call_insn_preprocessing() in lzx-decompress.c.
1492  * See the comment above that function for more information.  */
1493 static void
1494 do_call_insn_preprocessing(u8 data[], int size)
1495 {
1496         for (int i = 0; i < size - 10; i++) {
1497                 if (data[i] == 0xe8) {
1498                         do_call_insn_translation((u32*)&data[i + 1], i,
1499                                                  LZX_WIM_MAGIC_FILESIZE);
1500                         i += 4;
1501                 }
1502         }
1503 }
1504
1505 static size_t
1506 lzx_compress(const void *uncompressed_data, size_t uncompressed_size,
1507              void *compressed_data, size_t compressed_size_avail, void *_ctx)
1508 {
1509         struct lzx_compressor *ctx = _ctx;
1510         struct output_bitstream ostream;
1511         size_t compressed_size;
1512
1513         if (uncompressed_size < 100) {
1514                 LZX_DEBUG("Too small to bother compressing.");
1515                 return 0;
1516         }
1517
1518         if (uncompressed_size > ctx->max_window_size) {
1519                 LZX_DEBUG("Can't compress %zu bytes using window of %u bytes!",
1520                           uncompressed_size, ctx->max_window_size);
1521                 return 0;
1522         }
1523
1524         LZX_DEBUG("Attempting to compress %zu bytes...",
1525                   uncompressed_size);
1526
1527         /* The input data must be preprocessed.  To avoid changing the original
1528          * input, copy it to a temporary buffer.  */
1529         memcpy(ctx->window, uncompressed_data, uncompressed_size);
1530         ctx->window_size = uncompressed_size;
1531
1532         /* This line is unnecessary; it just avoids inconsequential accesses of
1533          * uninitialized memory that would show up in memory-checking tools such
1534          * as valgrind.  */
1535         memset(&ctx->window[ctx->window_size], 0, 12);
1536
1537         LZX_DEBUG("Preprocessing data...");
1538
1539         /* Before doing any actual compression, do the call instruction (0xe8
1540          * byte) translation on the uncompressed data.  */
1541         do_call_insn_preprocessing(ctx->window, ctx->window_size);
1542
1543         LZX_DEBUG("Preparing blocks...");
1544
1545         /* Prepare the compressed data.  */
1546         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
1547                 lzx_prepare_block_fast(ctx);
1548         else
1549                 lzx_prepare_blocks(ctx);
1550
1551         LZX_DEBUG("Writing compressed blocks...");
1552
1553         /* Generate the compressed data.  */
1554         init_output_bitstream(&ostream, compressed_data, compressed_size_avail);
1555         lzx_write_all_blocks(ctx, &ostream);
1556
1557         LZX_DEBUG("Flushing bitstream...");
1558         compressed_size = flush_output_bitstream(&ostream);
1559         if (compressed_size == ~(input_idx_t)0) {
1560                 LZX_DEBUG("Data did not compress to %zu bytes or less!",
1561                           compressed_size_avail);
1562                 return 0;
1563         }
1564
1565         LZX_DEBUG("Done: compressed %zu => %zu bytes.",
1566                   uncompressed_size, compressed_size);
1567
1568         /* Verify that we really get the same thing back when decompressing.
1569          * Although this could be disabled by default in all cases, it only
1570          * takes around 2-3% of the running time of the slow algorithm to do the
1571          * verification.  */
1572         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
1573         #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
1574             || 1
1575         #endif
1576             )
1577         {
1578                 struct wimlib_decompressor *decompressor;
1579
1580                 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZX,
1581                                                     ctx->max_window_size,
1582                                                     NULL,
1583                                                     &decompressor))
1584                 {
1585                         int ret;
1586                         ret = wimlib_decompress(compressed_data,
1587                                                 compressed_size,
1588                                                 ctx->window,
1589                                                 uncompressed_size,
1590                                                 decompressor);
1591                         wimlib_free_decompressor(decompressor);
1592
1593                         if (ret) {
1594                                 ERROR("Failed to decompress data we "
1595                                       "compressed using LZX algorithm");
1596                                 wimlib_assert(0);
1597                                 return 0;
1598                         }
1599                         if (memcmp(uncompressed_data, ctx->window, uncompressed_size)) {
1600                                 ERROR("Data we compressed using LZX algorithm "
1601                                       "didn't decompress to original");
1602                                 wimlib_assert(0);
1603                                 return 0;
1604                         }
1605                 } else {
1606                         WARNING("Failed to create decompressor for "
1607                                 "data verification!");
1608                 }
1609         }
1610         return compressed_size;
1611 }
1612
1613 static void
1614 lzx_free_compressor(void *_ctx)
1615 {
1616         struct lzx_compressor *ctx = _ctx;
1617
1618         if (ctx) {
1619                 FREE(ctx->chosen_matches);
1620                 FREE(ctx->cached_matches);
1621                 lz_match_chooser_destroy(&ctx->mc);
1622                 lz_sarray_destroy(&ctx->lz_sarray);
1623                 FREE(ctx->block_specs);
1624                 FREE(ctx->prev_tab);
1625                 FREE(ctx->window);
1626                 FREE(ctx);
1627         }
1628 }
1629
1630 static const struct wimlib_lzx_compressor_params lzx_fast_default = {
1631         .hdr = {
1632                 .size = sizeof(struct wimlib_lzx_compressor_params),
1633         },
1634         .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
1635         .use_defaults = 0,
1636         .alg_params = {
1637                 .fast = {
1638                 },
1639         },
1640 };
1641 static const struct wimlib_lzx_compressor_params lzx_slow_default = {
1642         .hdr = {
1643                 .size = sizeof(struct wimlib_lzx_compressor_params),
1644         },
1645         .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
1646         .use_defaults = 0,
1647         .alg_params = {
1648                 .slow = {
1649                         .use_len2_matches = 1,
1650                         .nice_match_length = 32,
1651                         .num_optim_passes = 2,
1652                         .max_search_depth = 50,
1653                         .max_matches_per_pos = 3,
1654                         .main_nostat_cost = 15,
1655                         .len_nostat_cost = 15,
1656                         .aligned_nostat_cost = 7,
1657                 },
1658         },
1659 };
1660
1661 static const struct wimlib_lzx_compressor_params *
1662 lzx_get_params(const struct wimlib_compressor_params_header *_params)
1663 {
1664         const struct wimlib_lzx_compressor_params *params =
1665                 (const struct wimlib_lzx_compressor_params*)_params;
1666
1667         if (params == NULL) {
1668                 LZX_DEBUG("Using default algorithm and parameters.");
1669                 params = &lzx_slow_default;
1670         } else {
1671                 if (params->use_defaults) {
1672                         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
1673                                 params = &lzx_slow_default;
1674                         else
1675                                 params = &lzx_fast_default;
1676                 }
1677         }
1678         return params;
1679 }
1680
1681 static int
1682 lzx_create_compressor(size_t window_size,
1683                       const struct wimlib_compressor_params_header *_params,
1684                       void **ctx_ret)
1685 {
1686         const struct wimlib_lzx_compressor_params *params = lzx_get_params(_params);
1687         struct lzx_compressor *ctx;
1688
1689         LZX_DEBUG("Allocating LZX context...");
1690
1691         if (!lzx_window_size_valid(window_size))
1692                 return WIMLIB_ERR_INVALID_PARAM;
1693
1694         LZX_DEBUG("Allocating memory.");
1695
1696         ctx = CALLOC(1, sizeof(struct lzx_compressor));
1697         if (ctx == NULL)
1698                 goto oom;
1699
1700         ctx->num_main_syms = lzx_get_num_main_syms(window_size);
1701         ctx->max_window_size = window_size;
1702         ctx->window = MALLOC(window_size + 12);
1703         if (ctx->window == NULL)
1704                 goto oom;
1705
1706         if (params->algorithm == WIMLIB_LZX_ALGORITHM_FAST) {
1707                 ctx->prev_tab = MALLOC(window_size * sizeof(ctx->prev_tab[0]));
1708                 if (ctx->prev_tab == NULL)
1709                         goto oom;
1710         }
1711
1712         size_t block_specs_length = DIV_ROUND_UP(window_size, LZX_DIV_BLOCK_SIZE);
1713         ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
1714         if (ctx->block_specs == NULL)
1715                 goto oom;
1716
1717         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
1718                 unsigned min_match_len = LZX_MIN_MATCH_LEN;
1719                 if (!params->alg_params.slow.use_len2_matches)
1720                         min_match_len = max(min_match_len, 3);
1721
1722                 if (!lz_sarray_init(&ctx->lz_sarray,
1723                                     window_size,
1724                                     min_match_len,
1725                                     LZX_MAX_MATCH_LEN,
1726                                     params->alg_params.slow.max_search_depth,
1727                                     params->alg_params.slow.max_matches_per_pos))
1728                         goto oom;
1729         }
1730
1731         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
1732                 if (!lz_match_chooser_init(&ctx->mc,
1733                                            LZX_OPTIM_ARRAY_SIZE,
1734                                            params->alg_params.slow.nice_match_length,
1735                                            LZX_MAX_MATCH_LEN))
1736                         goto oom;
1737         }
1738
1739         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
1740                 u32 cache_per_pos;
1741
1742                 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
1743                 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
1744                         cache_per_pos = LZX_MAX_CACHE_PER_POS;
1745
1746                 ctx->cached_matches = MALLOC(window_size * (cache_per_pos + 1) *
1747                                              sizeof(ctx->cached_matches[0]));
1748                 if (ctx->cached_matches == NULL)
1749                         goto oom;
1750         }
1751
1752         ctx->chosen_matches = MALLOC(window_size * sizeof(ctx->chosen_matches[0]));
1753         if (ctx->chosen_matches == NULL)
1754                 goto oom;
1755
1756         memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_compressor_params));
1757         memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
1758
1759         LZX_DEBUG("Successfully allocated new LZX context.");
1760
1761         *ctx_ret = ctx;
1762         return 0;
1763
1764 oom:
1765         lzx_free_compressor(ctx);
1766         return WIMLIB_ERR_NOMEM;
1767 }
1768
1769 static u64
1770 lzx_get_needed_memory(size_t max_block_size,
1771                       const struct wimlib_compressor_params_header *_params)
1772 {
1773         const struct wimlib_lzx_compressor_params *params = lzx_get_params(_params);
1774
1775         u64 size = 0;
1776
1777         size += sizeof(struct lzx_compressor);
1778
1779         size += max_block_size + 12;
1780
1781         size += DIV_ROUND_UP(max_block_size, LZX_DIV_BLOCK_SIZE) *
1782                 sizeof(((struct lzx_compressor*)0)->block_specs[0]);
1783
1784         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
1785                 size += max_block_size * sizeof(((struct lzx_compressor*)0)->chosen_matches[0]);
1786                 size += lz_sarray_get_needed_memory(max_block_size);
1787                 size += lz_match_chooser_get_needed_memory(LZX_OPTIM_ARRAY_SIZE,
1788                                                            params->alg_params.slow.nice_match_length,
1789                                                            LZX_MAX_MATCH_LEN);
1790                 u32 cache_per_pos;
1791
1792                 cache_per_pos = params->alg_params.slow.max_matches_per_pos;
1793                 if (cache_per_pos > LZX_MAX_CACHE_PER_POS)
1794                         cache_per_pos = LZX_MAX_CACHE_PER_POS;
1795
1796                 size += max_block_size * (cache_per_pos + 1) *
1797                         sizeof(((struct lzx_compressor*)0)->cached_matches[0]);
1798         } else {
1799                 size += max_block_size * sizeof(((struct lzx_compressor*)0)->prev_tab[0]);
1800         }
1801         return size;
1802 }
1803
1804 static bool
1805 lzx_params_valid(const struct wimlib_compressor_params_header *_params)
1806 {
1807         const struct wimlib_lzx_compressor_params *params =
1808                 (const struct wimlib_lzx_compressor_params*)_params;
1809
1810         if (params->hdr.size != sizeof(struct wimlib_lzx_compressor_params)) {
1811                 LZX_DEBUG("Invalid parameter structure size!");
1812                 return false;
1813         }
1814
1815         if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
1816             params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
1817         {
1818                 LZX_DEBUG("Invalid algorithm.");
1819                 return false;
1820         }
1821
1822         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW &&
1823             !params->use_defaults)
1824         {
1825                 if (params->alg_params.slow.num_optim_passes < 1)
1826                 {
1827                         LZX_DEBUG("Invalid number of optimization passes!");
1828                         return false;
1829                 }
1830
1831                 if (params->alg_params.slow.main_nostat_cost < 1 ||
1832                     params->alg_params.slow.main_nostat_cost > 16)
1833                 {
1834                         LZX_DEBUG("Invalid main_nostat_cost!");
1835                         return false;
1836                 }
1837
1838                 if (params->alg_params.slow.len_nostat_cost < 1 ||
1839                     params->alg_params.slow.len_nostat_cost > 16)
1840                 {
1841                         LZX_DEBUG("Invalid len_nostat_cost!");
1842                         return false;
1843                 }
1844
1845                 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
1846                     params->alg_params.slow.aligned_nostat_cost > 8)
1847                 {
1848                         LZX_DEBUG("Invalid aligned_nostat_cost!");
1849                         return false;
1850                 }
1851         }
1852         return true;
1853 }
1854
1855
1856 const struct compressor_ops lzx_compressor_ops = {
1857         .params_valid       = lzx_params_valid,
1858         .get_needed_memory  = lzx_get_needed_memory,
1859         .create_compressor  = lzx_create_compressor,
1860         .compress           = lzx_compress,
1861         .free_compressor    = lzx_free_compressor,
1862 };