]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
lzx-compress.c: Don't compute match/literal array before actually needed
[wimlib] / src / lzx-compress.c
1 /*
2  * lzx-compress.c
3  */
4
5 /*
6  * Copyright (C) 2012, 2013, 2014 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24
25 /*
26  * This file contains a compressor for the LZX ("Lempel-Ziv eXtended"?)
27  * compression format, as used in the WIM (Windows IMaging) file format.  This
28  * code may need some slight modifications to be used outside of the WIM format.
29  * In particular, in other situations the LZX block header might be slightly
30  * different, and a sliding window rather than a fixed-size window might be
31  * required.
32  *
33  * ----------------------------------------------------------------------------
34  *
35  *                               Format Overview
36  *
37  * The primary reference for LZX is the specification released by Microsoft.
38  * However, the comments in lzx-decompress.c provide more information about LZX
39  * and note some errors in the Microsoft specification.
40  *
41  * LZX shares many similarities with DEFLATE, the format used by zlib and gzip.
42  * Both LZX and DEFLATE use LZ77 matching and Huffman coding.  Certain details
43  * are quite similar, such as the method for storing Huffman codes.  However,
44  * the main differences are:
45  *
46  * - LZX preprocesses the data to attempt to make x86 machine code slightly more
47  *   compressible before attempting to compress it further.
48  *
49  * - LZX uses a "main" alphabet which combines literals and matches, with the
50  *   match symbols containing a "length header" (giving all or part of the match
51  *   length) and a "position slot" (giving, roughly speaking, the order of
52  *   magnitude of the match offset).
53  *
54  * - LZX does not have static Huffman blocks (that is, the kind with preset
55  *   Huffman codes); however it does have two types of dynamic Huffman blocks
56  *   ("verbatim" and "aligned").
57  *
58  * - LZX has a minimum match length of 2 rather than 3.
59  *
60  * - In LZX, match offsets 0 through 2 actually represent entries in an LRU
61  *   queue of match offsets.  This is very useful for certain types of files,
62  *   such as binary files that have repeating records.
63  *
64  * ----------------------------------------------------------------------------
65  *
66  *                            Algorithmic Overview
67  *
68  * At a high level, any implementation of LZX compression must operate as
69  * follows:
70  *
71  * 1. Preprocess the input data to translate the targets of 32-bit x86 call
72  *    instructions to absolute offsets.  (Actually, this is required for WIM,
73  *    but might not be in other places LZX is used.)
74  *
75  * 2. Find a sequence of LZ77-style matches and literal bytes that expands to
76  *    the preprocessed data.
77  *
78  * 3. Divide the match/literal sequence into one or more LZX blocks, each of
79  *    which may be "uncompressed", "verbatim", or "aligned".
80  *
81  * 4. Output each LZX block.
82  *
83  * Step (1) is fairly straightforward.  It requires looking for 0xe8 bytes in
84  * the input data and performing a translation on the 4 bytes following each
85  * one.
86  *
87  * Step (4) is complicated, but it is mostly determined by the LZX format.  The
88  * only real choice we have is what algorithm to use to build the length-limited
89  * canonical Huffman codes.  See lzx_write_all_blocks() for details.
90  *
91  * That leaves steps (2) and (3) as where all the hard stuff happens.  Focusing
92  * on step (2), we need to do LZ77-style parsing on the input data, or "window",
93  * to divide it into a sequence of matches and literals.  Each position in the
94  * window might have multiple matches associated with it, and we need to choose
95  * which one, if any, to actually use.  Therefore, the problem can really be
96  * divided into two areas of concern: (a) finding matches at a given position,
97  * which we shall call "match-finding", and (b) choosing whether to use a
98  * match or a literal at a given position, and if using a match, which one (if
99  * there is more than one available).  We shall call this "match-choosing".  We
100  * first consider match-finding, then match-choosing.
101  *
102  * ----------------------------------------------------------------------------
103  *
104  *                               Match-finding
105  *
106  * Given a position in the window, we want to find LZ77-style "matches" with
107  * that position at previous positions in the window.  With LZX, the minimum
108  * match length is 2 and the maximum match length is 257.  The only restriction
109  * on offsets is that LZX does not allow the last 2 bytes of the window to match
110  * the the beginning of the window.
111  *
112  * Depending on how good a compression ratio we want (see the "Match-choosing"
113  * section), we may want to find: (a) all matches, or (b) just the longest
114  * match, or (c) just some "promising" matches that we are able to find quickly,
115  * or (d) just the longest match that we're able to find quickly.  Below we
116  * introduce the match-finding methods that the code currently uses or has
117  * previously used:
118  *
119  * - Hash chains.  Maintain a table that maps hash codes, computed from
120  *   fixed-length byte sequences, to linked lists containing previous window
121  *   positions.  To search for matches, compute the hash for the current
122  *   position in the window and search the appropriate hash chain.  When
123  *   advancing to the next position, prepend the current position to the
124  *   appropriate hash list.  This is a good approach for producing matches with
125  *   stategy (d) and is useful for fast compression.  Therefore, we provide an
126  *   option to use this method for LZX compression.  See lz_hash.c for the
127  *   implementation.
128  *
129  * - Binary trees.  Similar to hash chains, but each hash bucket contains a
130  *   binary tree of previous window positions rather than a linked list.  This
131  *   is a good approach for producing matches with stategy (c) and is useful for
132  *   achieving a good compression ratio.  Therefore, we provide an option to use
133  *   this method; see lz_bt.c for the implementation.
134  *
135  * - Suffix arrays.  This code previously used this method to produce matches
136  *   with stategy (c), but I've dropped it because it was slower than the binary
137  *   trees approach, used more memory, and did not improve the compression ratio
138  *   enough to compensate.  Download wimlib v1.6.2 if you want the code.
139  *   However, the suffix array method was basically as follows.  Build the
140  *   suffix array for the entire window.  The suffix array contains each
141  *   possible window position, sorted by the lexicographic order of the strings
142  *   that begin at those positions.  Find the matches at a given position by
143  *   searching the suffix array outwards, in both directions, from the suffix
144  *   array slot for that position.  This produces the longest matches first, but
145  *   "matches" that actually occur at later positions in the window must be
146  *   skipped.  To do this skipping, use an auxiliary array with dynamically
147  *   constructed linked lists.  Also, use the inverse suffix array to quickly
148  *   find the suffix array slot for a given position without doing a binary
149  *   search.
150  *
151  * ----------------------------------------------------------------------------
152  *
153  *                               Match-choosing
154  *
155  * Usually, choosing the longest match is best because it encodes the most data
156  * in that one item.  However, sometimes the longest match is not optimal
157  * because (a) choosing a long match now might prevent using an even longer
158  * match later, or (b) more generally, what we actually care about is the number
159  * of bits it will ultimately take to output each match or literal, which is
160  * actually dependent on the entropy encoding using by the underlying
161  * compression format.  Consequently, a longer match usually, but not always,
162  * takes fewer bits to encode than multiple shorter matches or literals that
163  * cover the same data.
164  *
165  * This problem of choosing the truly best match/literal sequence is probably
166  * impossible to solve efficiently when combined with entropy encoding.  If we
167  * knew how many bits it takes to output each match/literal, then we could
168  * choose the optimal sequence using shortest-path search a la Dijkstra's
169  * algorithm.  However, with entropy encoding, the chosen match/literal sequence
170  * affects its own encoding.  Therefore, we can't know how many bits it will
171  * take to actually output any one match or literal until we have actually
172  * chosen the full sequence of matches and literals.
173  *
174  * Notwithstanding the entropy encoding problem, we also aren't guaranteed to
175  * choose the optimal match/literal sequence unless the match-finder (see
176  * section "Match-finder") provides the match-chooser with all possible matches
177  * at each position.  However, this is not computationally efficient.  For
178  * example, there might be many matches of the same length, and usually (but not
179  * always) the best choice is the one with the smallest offset.  So in practice,
180  * it's fine to only consider the smallest offset for a given match length at a
181  * given position.  (Actually, for LZX, it's also worth considering repeat
182  * offsets.)
183  *
184  * In addition, as mentioned earlier, in LZX we have the choice of using
185  * multiple blocks, each of which resets the Huffman codes.  This expands the
186  * search space even further.  Therefore, to simplify the problem, we currently
187  * we don't attempt to actually choose the LZX blocks based on the data.
188  * Instead, we just divide the data into fixed-size blocks of LZX_DIV_BLOCK_SIZE
189  * bytes each, and always use verbatim or aligned blocks (never uncompressed).
190  * A previous version of this code recursively split the input data into
191  * equal-sized blocks, up to a maximum depth, and chose the lowest-cost block
192  * divisions.  However, this made compression much slower and did not actually
193  * help very much.  It remains an open question whether a sufficiently fast and
194  * useful block-splitting algorithm is possible for LZX.  Essentially the same
195  * problem also applies to DEFLATE.  The Microsoft LZX compressor seemingly does
196  * do block splitting, although I don't know how fast or useful it is,
197  * specifically.
198  *
199  * Now, back to the entropy encoding problem.  The "solution" is to use an
200  * iterative approach to compute a good, but not necessarily optimal,
201  * match/literal sequence.  Start with a fixed assignment of symbol costs and
202  * choose an "optimal" match/literal sequence based on those costs, using
203  * shortest-path seach a la Dijkstra's algorithm.  Then, for each iteration of
204  * the optimization, update the costs based on the entropy encoding of the
205  * current match/literal sequence, then choose a new match/literal sequence
206  * based on the updated costs.  Usually, the actual cost to output the current
207  * match/literal sequence will decrease in each iteration until it converges on
208  * a fixed point.  This result may not be the truly optimal match/literal
209  * sequence, but it usually is much better than one chosen by doing a "greedy"
210  * parse where we always chooe the longest match.
211  *
212  * An alternative to both greedy parsing and iterative, near-optimal parsing is
213  * "lazy" parsing.  Briefly, "lazy" parsing considers just the longest match at
214  * each position, but it waits to choose that match until it has also examined
215  * the next position.  This is actually a useful approach; it's used by zlib,
216  * for example.  Therefore, for fast compression we combine lazy parsing with
217  * the hash chain max-finder.  For normal/high compression we combine
218  * near-optimal parsing with the binary tree match-finder.
219  *
220  * Anyway, if you've read through this comment, you hopefully should have a
221  * better idea of why things are done in a certain way in this LZX compressor,
222  * as well as in other compressors for LZ77-based formats (including third-party
223  * ones).  In my opinion, the phrase "compression algorithm" is often mis-used
224  * in place of "compression format",  since there can be many different
225  * algorithms that all generate compressed data in the same format.  The
226  * challenge is to design an algorithm that is efficient but still gives a good
227  * compression ratio.
228  */
229
230 #ifdef HAVE_CONFIG_H
231 #  include "config.h"
232 #endif
233
234 #include "wimlib.h"
235 #include "wimlib/compressor_ops.h"
236 #include "wimlib/compress_common.h"
237 #include "wimlib/endianness.h"
238 #include "wimlib/error.h"
239 #include "wimlib/lz.h"
240 #include "wimlib/lz_hash.h"
241 #include "wimlib/lz_bt.h"
242 #include "wimlib/lzx.h"
243 #include "wimlib/util.h"
244 #include <string.h>
245
246 #ifdef ENABLE_LZX_DEBUG
247 #  include "wimlib/decompress_common.h"
248 #endif
249
250 #define LZX_OPTIM_ARRAY_SIZE    4096
251
252 #define LZX_DIV_BLOCK_SIZE      32768
253
254 #define LZX_CACHE_PER_POS       8
255
256 #define LZX_CACHE_LEN (LZX_DIV_BLOCK_SIZE * (LZX_CACHE_PER_POS + 1))
257 #define LZX_CACHE_SIZE (LZX_CACHE_LEN * sizeof(struct raw_match))
258 #define LZX_MAX_MATCHES_PER_POS (LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1)
259
260 /* Codewords for the LZX main, length, and aligned offset Huffman codes  */
261 struct lzx_codewords {
262         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
263         u32 len[LZX_LENCODE_NUM_SYMBOLS];
264         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
265 };
266
267 /* Codeword lengths (in bits) for the LZX main, length, and aligned offset
268  * Huffman codes.
269  *
270  * A 0 length means the codeword has zero frequency.
271  */
272 struct lzx_lens {
273         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
274         u8 len[LZX_LENCODE_NUM_SYMBOLS];
275         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
276 };
277
278 /* Costs for the LZX main, length, and aligned offset Huffman symbols.
279  *
280  * If a codeword has zero frequency, it must still be assigned some nonzero cost
281  * --- generally a high cost, since even if it gets used in the next iteration,
282  * it probably will not be used very times.  */
283 struct lzx_costs {
284         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
285         u8 len[LZX_LENCODE_NUM_SYMBOLS];
286         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
287 };
288
289 /* The LZX main, length, and aligned offset Huffman codes  */
290 struct lzx_codes {
291         struct lzx_codewords codewords;
292         struct lzx_lens lens;
293 };
294
295 /* Tables for tallying symbol frequencies in the three LZX alphabets  */
296 struct lzx_freqs {
297         input_idx_t main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
298         input_idx_t len[LZX_LENCODE_NUM_SYMBOLS];
299         input_idx_t aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
300 };
301
302 /* LZX intermediate match/literal format  */
303 struct lzx_match {
304         /* Bit     Description
305          *
306          * 31      1 if a match, 0 if a literal.
307          *
308          * 30-25   position slot.  This can be at most 50, so it will fit in 6
309          *         bits.
310          *
311          * 8-24    position footer.  This is the offset of the real formatted
312          *         offset from the position base.  This can be at most 17 bits
313          *         (since lzx_extra_bits[LZX_MAX_POSITION_SLOTS - 1] is 17).
314          *
315          * 0-7     length of match, minus 2.  This can be at most
316          *         (LZX_MAX_MATCH_LEN - 2) == 255, so it will fit in 8 bits.  */
317         u32 data;
318 };
319
320 /* Specification for an LZX block.  */
321 struct lzx_block_spec {
322
323         /* One of the LZX_BLOCKTYPE_* constants indicating which type of this
324          * block.  */
325         int block_type;
326
327         /* 0-based position in the window at which this block starts.  */
328         input_idx_t window_pos;
329
330         /* The number of bytes of uncompressed data this block represents.  */
331         input_idx_t block_size;
332
333         /* The match/literal sequence for this block.  */
334         struct lzx_match *chosen_matches;
335
336         /* The length of the @chosen_matches sequence.  */
337         input_idx_t num_chosen_matches;
338
339         /* Huffman codes for this block.  */
340         struct lzx_codes codes;
341 };
342
343 /* State of the LZX compressor.  */
344 struct lzx_compressor {
345
346         /* The parameters that were used to create the compressor.  */
347         struct wimlib_lzx_compressor_params params;
348
349         /* The buffer of data to be compressed.
350          *
351          * 0xe8 byte preprocessing is done directly on the data here before
352          * further compression.
353          *
354          * Note that this compressor does *not* use a real sliding window!!!!
355          * It's not needed in the WIM format, since every chunk is compressed
356          * independently.  This is by design, to allow random access to the
357          * chunks.
358          *
359          * We reserve a few extra bytes to potentially allow reading off the end
360          * of the array in the match-finding code for optimization purposes
361          * (currently only needed for the hash chain match-finder).  */
362         u8 *window;
363
364         /* Number of bytes of data to be compressed, which is the number of
365          * bytes of data in @window that are actually valid.  */
366         input_idx_t window_size;
367
368         /* Allocated size of the @window.  */
369         input_idx_t max_window_size;
370
371         /* Number of symbols in the main alphabet (depends on the
372          * @max_window_size since it determines the maximum allowed offset).  */
373         unsigned num_main_syms;
374
375         /* The current match offset LRU queue.  */
376         struct lzx_lru_queue queue;
377
378         /* Space for the sequences of matches/literals that were chosen for each
379          * block.  */
380         struct lzx_match *chosen_matches;
381
382         /* Information about the LZX blocks the preprocessed input was divided
383          * into.  */
384         struct lzx_block_spec *block_specs;
385
386         /* Number of LZX blocks the input was divided into; a.k.a. the number of
387          * elements of @block_specs that are valid.  */
388         unsigned num_blocks;
389
390         /* This is simply filled in with zeroes and used to avoid special-casing
391          * the output of the first compressed Huffman code, which conceptually
392          * has a delta taken from a code with all symbols having zero-length
393          * codewords.  */
394         struct lzx_codes zero_codes;
395
396         /* The current cost model.  */
397         struct lzx_costs costs;
398
399         /* Fast algorithm only:  Array of hash table links.  */
400         input_idx_t *prev_tab;
401
402         /* Slow algorithm only: Binary tree match-finder.  */
403         struct lz_bt mf;
404
405         /* Position in window of next match to return.  */
406         input_idx_t match_window_pos;
407
408         /* The end-of-block position.  We can't allow any matches to span this
409          * position.  */
410         input_idx_t match_window_end;
411
412         /* Matches found by the match-finder are cached in the following array
413          * to achieve a slight speedup when the same matches are needed on
414          * subsequent passes.  This is suboptimal because different matches may
415          * be preferred with different cost models, but seems to be a worthwhile
416          * speedup.  */
417         struct raw_match *cached_matches;
418         struct raw_match *cache_ptr;
419         bool matches_cached;
420         struct raw_match *cache_limit;
421
422         /* Match-chooser state.
423          * When matches have been chosen, optimum_cur_idx is set to the position
424          * in the window of the next match/literal to return and optimum_end_idx
425          * is set to the position in the window at the end of the last
426          * match/literal to return.  */
427         struct lzx_mc_pos_data *optimum;
428         unsigned optimum_cur_idx;
429         unsigned optimum_end_idx;
430 };
431
432 /*
433  * Match chooser position data:
434  *
435  * An array of these structures is used during the match-choosing algorithm.
436  * They correspond to consecutive positions in the window and are used to keep
437  * track of the cost to reach each position, and the match/literal choices that
438  * need to be chosen to reach that position.
439  */
440 struct lzx_mc_pos_data {
441         /* The approximate minimum cost, in bits, to reach this position in the
442          * window which has been found so far.  */
443         u32 cost;
444 #define MC_INFINITE_COST ((u32)~0UL)
445
446         /* The union here is just for clarity, since the fields are used in two
447          * slightly different ways.  Initially, the @prev structure is filled in
448          * first, and links go from later in the window to earlier in the
449          * window.  Later, @next structure is filled in and links go from
450          * earlier in the window to later in the window.  */
451         union {
452                 struct {
453                         /* Position of the start of the match or literal that
454                          * was taken to get to this position in the approximate
455                          * minimum-cost parse.  */
456                         input_idx_t link;
457
458                         /* Offset (as in an LZ (length, offset) pair) of the
459                          * match or literal that was taken to get to this
460                          * position in the approximate minimum-cost parse.  */
461                         input_idx_t match_offset;
462                 } prev;
463                 struct {
464                         /* Position at which the match or literal starting at
465                          * this position ends in the minimum-cost parse.  */
466                         input_idx_t link;
467
468                         /* Offset (as in an LZ (length, offset) pair) of the
469                          * match or literal starting at this position in the
470                          * approximate minimum-cost parse.  */
471                         input_idx_t match_offset;
472                 } next;
473         };
474
475         /* Adaptive state that exists after an approximate minimum-cost path to
476          * reach this position is taken.  */
477         struct lzx_lru_queue queue;
478 };
479
480 /* Returns the LZX position slot that corresponds to a given match offset,
481  * taking into account the recent offset queue and updating it if the offset is
482  * found in it.  */
483 static unsigned
484 lzx_get_position_slot(u32 offset, struct lzx_lru_queue *queue)
485 {
486         unsigned position_slot;
487
488         /* See if the offset was recently used.  */
489         for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
490                 if (offset == queue->R[i]) {
491                         /* Found it.  */
492
493                         /* Bring the repeat offset to the front of the
494                          * queue.  Note: this is, in fact, not a real
495                          * LRU queue because repeat matches are simply
496                          * swapped to the front.  */
497                         swap(queue->R[0], queue->R[i]);
498
499                         /* The resulting position slot is simply the first index
500                          * at which the offset was found in the queue.  */
501                         return i;
502                 }
503         }
504
505         /* The offset was not recently used; look up its real position slot.  */
506         position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
507
508         /* Bring the new offset to the front of the queue.  */
509         for (int i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
510                 queue->R[i] = queue->R[i - 1];
511         queue->R[0] = offset;
512
513         return position_slot;
514 }
515
516 /* Build the main, length, and aligned offset Huffman codes used in LZX.
517  *
518  * This takes as input the frequency tables for each code and produces as output
519  * a set of tables that map symbols to codewords and codeword lengths.  */
520 static void
521 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
522                        struct lzx_codes *codes,
523                        unsigned num_main_syms)
524 {
525         make_canonical_huffman_code(num_main_syms,
526                                     LZX_MAX_MAIN_CODEWORD_LEN,
527                                     freqs->main,
528                                     codes->lens.main,
529                                     codes->codewords.main);
530
531         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
532                                     LZX_MAX_LEN_CODEWORD_LEN,
533                                     freqs->len,
534                                     codes->lens.len,
535                                     codes->codewords.len);
536
537         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
538                                     LZX_MAX_ALIGNED_CODEWORD_LEN,
539                                     freqs->aligned,
540                                     codes->lens.aligned,
541                                     codes->codewords.aligned);
542 }
543
544 /*
545  * Output a precomputed LZX match.
546  *
547  * @out:
548  *      The bitstream to which to write the match.
549  * @block_type:
550  *      The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or
551  *      LZX_BLOCKTYPE_VERBATIM)
552  * @match:
553  *      The match, as a (length, offset) pair.
554  * @codes:
555  *      Pointer to a structure that contains the codewords for the main, length,
556  *      and aligned offset Huffman codes for the current LZX compressed block.
557  */
558 static void
559 lzx_write_match(struct output_bitstream *out, int block_type,
560                 struct lzx_match match, const struct lzx_codes *codes)
561 {
562         /* low 8 bits are the match length minus 2 */
563         unsigned match_len_minus_2 = match.data & 0xff;
564         /* Next 17 bits are the position footer */
565         unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
566         /* Next 6 bits are the position slot. */
567         unsigned position_slot = (match.data >> 25) & 0x3f;     /* 6 bits */
568         unsigned len_header;
569         unsigned len_footer;
570         unsigned main_symbol;
571         unsigned num_extra_bits;
572         unsigned verbatim_bits;
573         unsigned aligned_bits;
574
575         /* If the match length is less than MIN_MATCH_LEN (= 2) +
576          * NUM_PRIMARY_LENS (= 7), the length header contains
577          * the match length minus MIN_MATCH_LEN, and there is no
578          * length footer.
579          *
580          * Otherwise, the length header contains
581          * NUM_PRIMARY_LENS, and the length footer contains
582          * the match length minus NUM_PRIMARY_LENS minus
583          * MIN_MATCH_LEN. */
584         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
585                 len_header = match_len_minus_2;
586         } else {
587                 len_header = LZX_NUM_PRIMARY_LENS;
588                 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
589         }
590
591         /* Combine the position slot with the length header into a single symbol
592          * that will be encoded with the main code.
593          *
594          * The actual main symbol is offset by LZX_NUM_CHARS because values
595          * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
596          * match.  */
597         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
598
599         /* Output main symbol. */
600         bitstream_put_bits(out, codes->codewords.main[main_symbol],
601                            codes->lens.main[main_symbol]);
602
603         /* If there is a length footer, output it using the
604          * length Huffman code. */
605         if (len_header == LZX_NUM_PRIMARY_LENS)
606                 bitstream_put_bits(out, codes->codewords.len[len_footer],
607                                    codes->lens.len[len_footer]);
608
609         num_extra_bits = lzx_get_num_extra_bits(position_slot);
610
611         /* For aligned offset blocks with at least 3 extra bits, output the
612          * verbatim bits literally, then the aligned bits encoded using the
613          * aligned offset code.  Otherwise, only the verbatim bits need to be
614          * output. */
615         if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
616
617                 verbatim_bits = position_footer >> 3;
618                 bitstream_put_bits(out, verbatim_bits,
619                                    num_extra_bits - 3);
620
621                 aligned_bits = (position_footer & 7);
622                 bitstream_put_bits(out,
623                                    codes->codewords.aligned[aligned_bits],
624                                    codes->lens.aligned[aligned_bits]);
625         } else {
626                 /* verbatim bits is the same as the position
627                  * footer, in this case. */
628                 bitstream_put_bits(out, position_footer, num_extra_bits);
629         }
630 }
631
632 /* Output an LZX literal (encoded with the main Huffman code).  */
633 static void
634 lzx_write_literal(struct output_bitstream *out, u8 literal,
635                   const struct lzx_codes *codes)
636 {
637         bitstream_put_bits(out,
638                            codes->codewords.main[literal],
639                            codes->lens.main[literal]);
640 }
641
642 static unsigned
643 lzx_build_precode(const u8 lens[restrict],
644                   const u8 prev_lens[restrict],
645                   const unsigned num_syms,
646                   input_idx_t precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
647                   u8 output_syms[restrict num_syms],
648                   u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
649                   u32 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
650                   unsigned *num_additional_bits_ret)
651 {
652         memset(precode_freqs, 0,
653                LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
654
655         /* Since the code word lengths use a form of RLE encoding, the goal here
656          * is to find each run of identical lengths when going through them in
657          * symbol order (including runs of length 1).  For each run, as many
658          * lengths are encoded using RLE as possible, and the rest are output
659          * literally.
660          *
661          * output_syms[] will be filled in with the length symbols that will be
662          * output, including RLE codes, not yet encoded using the precode.
663          *
664          * cur_run_len keeps track of how many code word lengths are in the
665          * current run of identical lengths.  */
666         unsigned output_syms_idx = 0;
667         unsigned cur_run_len = 1;
668         unsigned num_additional_bits = 0;
669         for (unsigned i = 1; i <= num_syms; i++) {
670
671                 if (i != num_syms && lens[i] == lens[i - 1]) {
672                         /* Still in a run--- keep going. */
673                         cur_run_len++;
674                         continue;
675                 }
676
677                 /* Run ended! Check if it is a run of zeroes or a run of
678                  * nonzeroes. */
679
680                 /* The symbol that was repeated in the run--- not to be confused
681                  * with the length *of* the run (cur_run_len) */
682                 unsigned len_in_run = lens[i - 1];
683
684                 if (len_in_run == 0) {
685                         /* A run of 0's.  Encode it in as few length
686                          * codes as we can. */
687
688                         /* The magic length 18 indicates a run of 20 + n zeroes,
689                          * where n is an uncompressed literal 5-bit integer that
690                          * follows the magic length. */
691                         while (cur_run_len >= 20) {
692                                 unsigned additional_bits;
693
694                                 additional_bits = min(cur_run_len - 20, 0x1f);
695                                 num_additional_bits += 5;
696                                 precode_freqs[18]++;
697                                 output_syms[output_syms_idx++] = 18;
698                                 output_syms[output_syms_idx++] = additional_bits;
699                                 cur_run_len -= 20 + additional_bits;
700                         }
701
702                         /* The magic length 17 indicates a run of 4 + n zeroes,
703                          * where n is an uncompressed literal 4-bit integer that
704                          * follows the magic length. */
705                         while (cur_run_len >= 4) {
706                                 unsigned additional_bits;
707
708                                 additional_bits = min(cur_run_len - 4, 0xf);
709                                 num_additional_bits += 4;
710                                 precode_freqs[17]++;
711                                 output_syms[output_syms_idx++] = 17;
712                                 output_syms[output_syms_idx++] = additional_bits;
713                                 cur_run_len -= 4 + additional_bits;
714                         }
715
716                 } else {
717
718                         /* A run of nonzero lengths. */
719
720                         /* The magic length 19 indicates a run of 4 + n
721                          * nonzeroes, where n is a literal bit that follows the
722                          * magic length, and where the value of the lengths in
723                          * the run is given by an extra length symbol, encoded
724                          * with the precode, that follows the literal bit.
725                          *
726                          * The extra length symbol is encoded as a difference
727                          * from the length of the codeword for the first symbol
728                          * in the run in the previous code.
729                          * */
730                         while (cur_run_len >= 4) {
731                                 unsigned additional_bits;
732                                 signed char delta;
733
734                                 additional_bits = (cur_run_len > 4);
735                                 num_additional_bits += 1;
736                                 delta = (signed char)prev_lens[i - cur_run_len] -
737                                         (signed char)len_in_run;
738                                 if (delta < 0)
739                                         delta += 17;
740                                 precode_freqs[19]++;
741                                 precode_freqs[(unsigned char)delta]++;
742                                 output_syms[output_syms_idx++] = 19;
743                                 output_syms[output_syms_idx++] = additional_bits;
744                                 output_syms[output_syms_idx++] = delta;
745                                 cur_run_len -= 4 + additional_bits;
746                         }
747                 }
748
749                 /* Any remaining lengths in the run are outputted without RLE,
750                  * as a difference from the length of that codeword in the
751                  * previous code. */
752                 while (cur_run_len > 0) {
753                         signed char delta;
754
755                         delta = (signed char)prev_lens[i - cur_run_len] -
756                                 (signed char)len_in_run;
757                         if (delta < 0)
758                                 delta += 17;
759
760                         precode_freqs[(unsigned char)delta]++;
761                         output_syms[output_syms_idx++] = delta;
762                         cur_run_len--;
763                 }
764
765                 cur_run_len = 1;
766         }
767
768         /* Build the precode from the frequencies of the length symbols. */
769
770         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
771                                     LZX_MAX_PRE_CODEWORD_LEN,
772                                     precode_freqs, precode_lens,
773                                     precode_codewords);
774
775         *num_additional_bits_ret = num_additional_bits;
776
777         return output_syms_idx;
778 }
779
780 /*
781  * Output a Huffman code in the compressed form used in LZX.
782  *
783  * The Huffman code is represented in the output as a logical series of codeword
784  * lengths from which the Huffman code, which must be in canonical form, can be
785  * reconstructed.
786  *
787  * The codeword lengths are themselves compressed using a separate Huffman code,
788  * the "precode", which contains a symbol for each possible codeword length in
789  * the larger code as well as several special symbols to represent repeated
790  * codeword lengths (a form of run-length encoding).  The precode is itself
791  * constructed in canonical form, and its codeword lengths are represented
792  * literally in 20 4-bit fields that immediately precede the compressed codeword
793  * lengths of the larger code.
794  *
795  * Furthermore, the codeword lengths of the larger code are actually represented
796  * as deltas from the codeword lengths of the corresponding code in the previous
797  * block.
798  *
799  * @out:
800  *      Bitstream to which to write the compressed Huffman code.
801  * @lens:
802  *      The codeword lengths, indexed by symbol, in the Huffman code.
803  * @prev_lens:
804  *      The codeword lengths, indexed by symbol, in the corresponding Huffman
805  *      code in the previous block, or all zeroes if this is the first block.
806  * @num_syms:
807  *      The number of symbols in the Huffman code.
808  */
809 static void
810 lzx_write_compressed_code(struct output_bitstream *out,
811                           const u8 lens[restrict],
812                           const u8 prev_lens[restrict],
813                           unsigned num_syms)
814 {
815         input_idx_t precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
816         u8 output_syms[num_syms];
817         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
818         u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
819         unsigned i;
820         unsigned num_output_syms;
821         u8 precode_sym;
822         unsigned dummy;
823
824         num_output_syms = lzx_build_precode(lens,
825                                             prev_lens,
826                                             num_syms,
827                                             precode_freqs,
828                                             output_syms,
829                                             precode_lens,
830                                             precode_codewords,
831                                             &dummy);
832
833         /* Write the lengths of the precode codes to the output. */
834         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
835                 bitstream_put_bits(out, precode_lens[i],
836                                    LZX_PRECODE_ELEMENT_SIZE);
837
838         /* Write the length symbols, encoded with the precode, to the output. */
839
840         for (i = 0; i < num_output_syms; ) {
841                 precode_sym = output_syms[i++];
842
843                 bitstream_put_bits(out, precode_codewords[precode_sym],
844                                    precode_lens[precode_sym]);
845                 switch (precode_sym) {
846                 case 17:
847                         bitstream_put_bits(out, output_syms[i++], 4);
848                         break;
849                 case 18:
850                         bitstream_put_bits(out, output_syms[i++], 5);
851                         break;
852                 case 19:
853                         bitstream_put_bits(out, output_syms[i++], 1);
854                         bitstream_put_bits(out,
855                                            precode_codewords[output_syms[i]],
856                                            precode_lens[output_syms[i]]);
857                         i++;
858                         break;
859                 default:
860                         break;
861                 }
862         }
863 }
864
865 /*
866  * Write all matches and literal bytes (which were precomputed) in an LZX
867  * compressed block to the output bitstream in the final compressed
868  * representation.
869  *
870  * @ostream
871  *      The output bitstream.
872  * @block_type
873  *      The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
874  *      LZX_BLOCKTYPE_VERBATIM).
875  * @match_tab
876  *      The array of matches/literals to output.
877  * @match_count
878  *      Number of matches/literals to output (length of @match_tab).
879  * @codes
880  *      The main, length, and aligned offset Huffman codes for the current
881  *      LZX compressed block.
882  */
883 static void
884 lzx_write_matches_and_literals(struct output_bitstream *ostream,
885                                int block_type,
886                                const struct lzx_match match_tab[],
887                                unsigned match_count,
888                                const struct lzx_codes *codes)
889 {
890         for (unsigned i = 0; i < match_count; i++) {
891                 struct lzx_match match = match_tab[i];
892
893                 /* The high bit of the 32-bit intermediate representation
894                  * indicates whether the item is an actual LZ-style match (1) or
895                  * a literal byte (0).  */
896                 if (match.data & 0x80000000)
897                         lzx_write_match(ostream, block_type, match, codes);
898                 else
899                         lzx_write_literal(ostream, match.data, codes);
900         }
901 }
902
903 static void
904 lzx_assert_codes_valid(const struct lzx_codes * codes, unsigned num_main_syms)
905 {
906 #ifdef ENABLE_LZX_DEBUG
907         unsigned i;
908
909         for (i = 0; i < num_main_syms; i++)
910                 LZX_ASSERT(codes->lens.main[i] <= LZX_MAX_MAIN_CODEWORD_LEN);
911
912         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
913                 LZX_ASSERT(codes->lens.len[i] <= LZX_MAX_LEN_CODEWORD_LEN);
914
915         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
916                 LZX_ASSERT(codes->lens.aligned[i] <= LZX_MAX_ALIGNED_CODEWORD_LEN);
917
918         const unsigned tablebits = 10;
919         u16 decode_table[(1 << tablebits) +
920                          (2 * max(num_main_syms, LZX_LENCODE_NUM_SYMBOLS))]
921                          _aligned_attribute(DECODE_TABLE_ALIGNMENT);
922         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
923                                                   num_main_syms,
924                                                   min(tablebits, LZX_MAINCODE_TABLEBITS),
925                                                   codes->lens.main,
926                                                   LZX_MAX_MAIN_CODEWORD_LEN));
927         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
928                                                   LZX_LENCODE_NUM_SYMBOLS,
929                                                   min(tablebits, LZX_LENCODE_TABLEBITS),
930                                                   codes->lens.len,
931                                                   LZX_MAX_LEN_CODEWORD_LEN));
932         LZX_ASSERT(0 == make_huffman_decode_table(decode_table,
933                                                   LZX_ALIGNEDCODE_NUM_SYMBOLS,
934                                                   min(tablebits, LZX_ALIGNEDCODE_TABLEBITS),
935                                                   codes->lens.aligned,
936                                                   LZX_MAX_ALIGNED_CODEWORD_LEN));
937 #endif /* ENABLE_LZX_DEBUG */
938 }
939
940 /* Write an LZX aligned offset or verbatim block to the output.  */
941 static void
942 lzx_write_compressed_block(int block_type,
943                            unsigned block_size,
944                            unsigned max_window_size,
945                            unsigned num_main_syms,
946                            struct lzx_match * chosen_matches,
947                            unsigned num_chosen_matches,
948                            const struct lzx_codes * codes,
949                            const struct lzx_codes * prev_codes,
950                            struct output_bitstream * ostream)
951 {
952         unsigned i;
953
954         LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
955                    block_type == LZX_BLOCKTYPE_VERBATIM);
956         lzx_assert_codes_valid(codes, num_main_syms);
957
958         /* The first three bits indicate the type of block and are one of the
959          * LZX_BLOCKTYPE_* constants.  */
960         bitstream_put_bits(ostream, block_type, 3);
961
962         /* Output the block size.
963          *
964          * The original LZX format seemed to always encode the block size in 3
965          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
966          * uses the first bit to indicate whether the block is the default size
967          * (32768) or a different size given explicitly by the next 16 bits.
968          *
969          * By default, this compressor uses a window size of 32768 and therefore
970          * follows the WIMGAPI behavior.  However, this compressor also supports
971          * window sizes greater than 32768 bytes, which do not appear to be
972          * supported by WIMGAPI.  In such cases, we retain the default size bit
973          * to mean a size of 32768 bytes but output non-default block size in 24
974          * bits rather than 16.  The compatibility of this behavior is unknown
975          * because WIMs created with chunk size greater than 32768 can seemingly
976          * only be opened by wimlib anyway.  */
977         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
978                 bitstream_put_bits(ostream, 1, 1);
979         } else {
980                 bitstream_put_bits(ostream, 0, 1);
981
982                 if (max_window_size >= 65536)
983                         bitstream_put_bits(ostream, block_size >> 16, 8);
984
985                 bitstream_put_bits(ostream, block_size, 16);
986         }
987
988         /* Write out lengths of the main code. Note that the LZX specification
989          * incorrectly states that the aligned offset code comes after the
990          * length code, but in fact it is the very first code to be written
991          * (before the main code).  */
992         if (block_type == LZX_BLOCKTYPE_ALIGNED)
993                 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
994                         bitstream_put_bits(ostream, codes->lens.aligned[i],
995                                            LZX_ALIGNEDCODE_ELEMENT_SIZE);
996
997         LZX_DEBUG("Writing main code...");
998
999         /* Write the precode and lengths for the first LZX_NUM_CHARS symbols in
1000          * the main code, which are the codewords for literal bytes.  */
1001         lzx_write_compressed_code(ostream,
1002                                   codes->lens.main,
1003                                   prev_codes->lens.main,
1004                                   LZX_NUM_CHARS);
1005
1006         /* Write the precode and lengths for the rest of the main code, which
1007          * are the codewords for match headers.  */
1008         lzx_write_compressed_code(ostream,
1009                                   codes->lens.main + LZX_NUM_CHARS,
1010                                   prev_codes->lens.main + LZX_NUM_CHARS,
1011                                   num_main_syms - LZX_NUM_CHARS);
1012
1013         LZX_DEBUG("Writing length code...");
1014
1015         /* Write the precode and lengths for the length code.  */
1016         lzx_write_compressed_code(ostream,
1017                                   codes->lens.len,
1018                                   prev_codes->lens.len,
1019                                   LZX_LENCODE_NUM_SYMBOLS);
1020
1021         LZX_DEBUG("Writing matches and literals...");
1022
1023         /* Write the actual matches and literals.  */
1024         lzx_write_matches_and_literals(ostream, block_type,
1025                                        chosen_matches, num_chosen_matches,
1026                                        codes);
1027
1028         LZX_DEBUG("Done writing block.");
1029 }
1030
1031 /* Write out the LZX blocks that were computed.  */
1032 static void
1033 lzx_write_all_blocks(struct lzx_compressor *ctx, struct output_bitstream *ostream)
1034 {
1035
1036         const struct lzx_codes *prev_codes = &ctx->zero_codes;
1037         for (unsigned i = 0; i < ctx->num_blocks; i++) {
1038                 const struct lzx_block_spec *spec = &ctx->block_specs[i];
1039
1040                 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_matches=%u)...",
1041                           i + 1, ctx->num_blocks,
1042                           spec->block_type, spec->block_size,
1043                           spec->num_chosen_matches);
1044
1045                 lzx_write_compressed_block(spec->block_type,
1046                                            spec->block_size,
1047                                            ctx->max_window_size,
1048                                            ctx->num_main_syms,
1049                                            spec->chosen_matches,
1050                                            spec->num_chosen_matches,
1051                                            &spec->codes,
1052                                            prev_codes,
1053                                            ostream);
1054
1055                 prev_codes = &spec->codes;
1056         }
1057 }
1058
1059 /* Constructs an LZX match from a literal byte and updates the main code symbol
1060  * frequencies.  */
1061 static inline u32
1062 lzx_tally_literal(u8 lit, struct lzx_freqs *freqs)
1063 {
1064         freqs->main[lit]++;
1065         return (u32)lit;
1066 }
1067
1068 /* Constructs an LZX match from an offset and a length, and updates the LRU
1069  * queue and the frequency of symbols in the main, length, and aligned offset
1070  * alphabets.  The return value is a 32-bit number that provides the match in an
1071  * intermediate representation documented below.  */
1072 static inline u32
1073 lzx_tally_match(unsigned match_len, u32 match_offset,
1074                 struct lzx_freqs *freqs, struct lzx_lru_queue *queue)
1075 {
1076         unsigned position_slot;
1077         unsigned position_footer;
1078         u32 len_header;
1079         unsigned main_symbol;
1080         unsigned len_footer;
1081         unsigned adjusted_match_len;
1082
1083         LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
1084
1085         /* The match offset shall be encoded as a position slot (itself encoded
1086          * as part of the main symbol) and a position footer.  */
1087         position_slot = lzx_get_position_slot(match_offset, queue);
1088         position_footer = (match_offset + LZX_OFFSET_OFFSET) &
1089                                 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
1090
1091         /* The match length shall be encoded as a length header (itself encoded
1092          * as part of the main symbol) and an optional length footer.  */
1093         adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
1094         if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
1095                 /* No length footer needed.  */
1096                 len_header = adjusted_match_len;
1097         } else {
1098                 /* Length footer needed.  It will be encoded using the length
1099                  * code.  */
1100                 len_header = LZX_NUM_PRIMARY_LENS;
1101                 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
1102                 freqs->len[len_footer]++;
1103         }
1104
1105         /* Account for the main symbol.  */
1106         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1107
1108         freqs->main[main_symbol]++;
1109
1110         /* In an aligned offset block, 3 bits of the position footer are output
1111          * as an aligned offset symbol.  Account for this, although we may
1112          * ultimately decide to output the block as verbatim.  */
1113
1114         /* The following check is equivalent to:
1115          *
1116          * if (lzx_extra_bits[position_slot] >= 3)
1117          *
1118          * Note that this correctly excludes position slots that correspond to
1119          * recent offsets.  */
1120         if (position_slot >= 8)
1121                 freqs->aligned[position_footer & 7]++;
1122
1123         /* Pack the position slot, position footer, and match length into an
1124          * intermediate representation.  See `struct lzx_match' for details.
1125          */
1126         LZX_ASSERT(LZX_MAX_POSITION_SLOTS <= 64);
1127         LZX_ASSERT(lzx_get_num_extra_bits(LZX_MAX_POSITION_SLOTS - 1) <= 17);
1128         LZX_ASSERT(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 <= 256);
1129
1130         LZX_ASSERT(position_slot      <= (1U << (31 - 25)) - 1);
1131         LZX_ASSERT(position_footer    <= (1U << (25 -  8)) - 1);
1132         LZX_ASSERT(adjusted_match_len <= (1U << (8  -  0)) - 1);
1133         return 0x80000000 |
1134                 (position_slot << 25) |
1135                 (position_footer << 8) |
1136                 (adjusted_match_len);
1137 }
1138
1139 struct lzx_record_ctx {
1140         struct lzx_freqs freqs;
1141         struct lzx_lru_queue queue;
1142         struct lzx_match *matches;
1143 };
1144
1145 static void
1146 lzx_record_match(unsigned len, unsigned offset, void *_ctx)
1147 {
1148         struct lzx_record_ctx *ctx = _ctx;
1149
1150         (ctx->matches++)->data = lzx_tally_match(len, offset, &ctx->freqs, &ctx->queue);
1151 }
1152
1153 static void
1154 lzx_record_literal(u8 lit, void *_ctx)
1155 {
1156         struct lzx_record_ctx *ctx = _ctx;
1157
1158         (ctx->matches++)->data = lzx_tally_literal(lit, &ctx->freqs);
1159 }
1160
1161 /* Returns the cost, in bits, to output a literal byte using the specified cost
1162  * model.  */
1163 static u32
1164 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1165 {
1166         return costs->main[c];
1167 }
1168
1169 /* Given a (length, offset) pair that could be turned into a valid LZX match as
1170  * well as costs for the codewords in the main, length, and aligned Huffman
1171  * codes, return the approximate number of bits it will take to represent this
1172  * match in the compressed output.  Take into account the match offset LRU
1173  * queue and also updates it.  */
1174 static u32
1175 lzx_match_cost(unsigned length, u32 offset, const struct lzx_costs *costs,
1176                struct lzx_lru_queue *queue)
1177 {
1178         unsigned position_slot;
1179         unsigned len_header, main_symbol;
1180         unsigned num_extra_bits;
1181         u32 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         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 /* Set the cost model @ctx->costs from the Huffman codeword lengths specified in
1209  * @lens.
1210  *
1211  * The cost model and codeword lengths are almost the same thing, but the
1212  * Huffman codewords with length 0 correspond to symbols with zero frequency
1213  * that still need to be assigned actual costs.  The specific values assigned
1214  * are arbitrary, but they should be fairly high (near the maximum codeword
1215  * length) to take into account the fact that uses of these symbols are expected
1216  * to be rare.  */
1217 static void
1218 lzx_set_costs(struct lzx_compressor * ctx, const struct lzx_lens * lens)
1219 {
1220         unsigned i;
1221         unsigned num_main_syms = ctx->num_main_syms;
1222
1223         /* Main code  */
1224         for (i = 0; i < num_main_syms; i++) {
1225                 ctx->costs.main[i] = lens->main[i];
1226                 if (ctx->costs.main[i] == 0)
1227                         ctx->costs.main[i] = ctx->params.alg_params.slow.main_nostat_cost;
1228         }
1229
1230         /* Length code  */
1231         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1232                 ctx->costs.len[i] = lens->len[i];
1233                 if (ctx->costs.len[i] == 0)
1234                         ctx->costs.len[i] = ctx->params.alg_params.slow.len_nostat_cost;
1235         }
1236
1237         /* Aligned offset code  */
1238         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1239                 ctx->costs.aligned[i] = lens->aligned[i];
1240                 if (ctx->costs.aligned[i] == 0)
1241                         ctx->costs.aligned[i] = ctx->params.alg_params.slow.aligned_nostat_cost;
1242         }
1243 }
1244
1245 /* Retrieve a list of matches available at the next position in the input.
1246  *
1247  * A pointer to the matches array is written into @matches_ret, and the return
1248  * value is the number of matches found.  */
1249 static unsigned
1250 lzx_get_matches(struct lzx_compressor *ctx,
1251                 const struct raw_match **matches_ret)
1252 {
1253         struct raw_match *cache_ptr;
1254         struct raw_match *matches;
1255         unsigned num_matches;
1256
1257         LZX_ASSERT(ctx->match_window_pos < ctx->match_window_end);
1258
1259         cache_ptr = ctx->cache_ptr;
1260         matches = cache_ptr + 1;
1261         if (likely(cache_ptr <= ctx->cache_limit)) {
1262                 if (ctx->matches_cached) {
1263                         num_matches = cache_ptr->len;
1264                 } else {
1265                         num_matches = lz_bt_get_matches(&ctx->mf, matches);
1266                         cache_ptr->len = num_matches;
1267                 }
1268         } else {
1269                 num_matches = 0;
1270         }
1271
1272         /* Don't allow matches to span the end of an LZX block.  */
1273         if (ctx->match_window_end < ctx->window_size && num_matches != 0) {
1274                 unsigned limit = ctx->match_window_end - ctx->match_window_pos;
1275
1276                 if (limit >= LZX_MIN_MATCH_LEN) {
1277
1278                         unsigned i = num_matches - 1;
1279                         do {
1280                                 if (matches[i].len >= limit) {
1281                                         matches[i].len = limit;
1282
1283                                         /* Truncation might produce multiple
1284                                          * matches with length 'limit'.  Keep at
1285                                          * most 1.  */
1286                                         num_matches = i + 1;
1287                                 }
1288                         } while (i--);
1289                 } else {
1290                         num_matches = 0;
1291                 }
1292                 cache_ptr->len = num_matches;
1293         }
1294
1295 #if 0
1296         fprintf(stderr, "Pos %u/%u: %u matches\n",
1297                 ctx->match_window_pos, ctx->window_size, num_matches);
1298         for (unsigned i = 0; i < num_matches; i++)
1299                 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
1300 #endif
1301
1302 #ifdef ENABLE_LZX_DEBUG
1303         for (unsigned i = 0; i < num_matches; i++) {
1304                 LZX_ASSERT(matches[i].len >= LZX_MIN_MATCH_LEN);
1305                 LZX_ASSERT(matches[i].len <= LZX_MAX_MATCH_LEN);
1306                 LZX_ASSERT(matches[i].len <= ctx->match_window_end - ctx->match_window_pos);
1307                 LZX_ASSERT(matches[i].offset > 0);
1308                 LZX_ASSERT(matches[i].offset <= ctx->match_window_pos);
1309                 LZX_ASSERT(!memcmp(&ctx->window[ctx->match_window_pos],
1310                                    &ctx->window[ctx->match_window_pos - matches[i].offset],
1311                                    matches[i].len));
1312                 if (i) {
1313                         LZX_ASSERT(matches[i].len > matches[i - 1].len);
1314                         LZX_ASSERT(matches[i].offset > matches[i - 1].offset);
1315                 }
1316         }
1317 #endif
1318         ctx->match_window_pos++;
1319         ctx->cache_ptr = matches + num_matches;
1320         *matches_ret = matches;
1321         return num_matches;
1322 }
1323
1324 static void
1325 lzx_skip_bytes(struct lzx_compressor *ctx, unsigned n)
1326 {
1327         struct raw_match *cache_ptr;
1328
1329         LZX_ASSERT(n <= ctx->match_window_end - ctx->match_window_pos);
1330
1331         cache_ptr = ctx->cache_ptr;
1332         ctx->match_window_pos += n;
1333         if (ctx->matches_cached) {
1334                 while (n-- && cache_ptr <= ctx->cache_limit)
1335                         cache_ptr += 1 + cache_ptr->len;
1336         } else {
1337                 lz_bt_skip_positions(&ctx->mf, n);
1338                 while (n-- && cache_ptr <= ctx->cache_limit) {
1339                         cache_ptr->len = 0;
1340                         cache_ptr += 1;
1341                 }
1342         }
1343         ctx->cache_ptr = cache_ptr;
1344 }
1345
1346 /*
1347  * Reverse the linked list of near-optimal matches so that they can be returned
1348  * in forwards order.
1349  *
1350  * Returns the first match in the list.
1351  */
1352 static struct raw_match
1353 lzx_match_chooser_reverse_list(struct lzx_compressor *ctx, unsigned cur_pos)
1354 {
1355         unsigned prev_link, saved_prev_link;
1356         unsigned prev_match_offset, saved_prev_match_offset;
1357
1358         ctx->optimum_end_idx = cur_pos;
1359
1360         saved_prev_link = ctx->optimum[cur_pos].prev.link;
1361         saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
1362
1363         do {
1364                 prev_link = saved_prev_link;
1365                 prev_match_offset = saved_prev_match_offset;
1366
1367                 saved_prev_link = ctx->optimum[prev_link].prev.link;
1368                 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
1369
1370                 ctx->optimum[prev_link].next.link = cur_pos;
1371                 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
1372
1373                 cur_pos = prev_link;
1374         } while (cur_pos != 0);
1375
1376         ctx->optimum_cur_idx = ctx->optimum[0].next.link;
1377
1378         return (struct raw_match)
1379                 { .len = ctx->optimum_cur_idx,
1380                   .offset = ctx->optimum[0].next.match_offset,
1381                 };
1382 }
1383
1384 /*
1385  * lzx_get_near_optimal_match() -
1386  *
1387  * Choose an approximately optimal match or literal to use at the next position
1388  * in the string, or "window", being LZ-encoded.
1389  *
1390  * This is based on algorithms used in 7-Zip, including the DEFLATE encoder
1391  * and the LZMA encoder, written by Igor Pavlov.
1392  *
1393  * Unlike a greedy parser that always takes the longest match, or even a "lazy"
1394  * parser with one match/literal look-ahead like zlib, the algorithm used here
1395  * may look ahead many matches/literals to determine the approximately optimal
1396  * match/literal to code next.  The motivation is that the compression ratio is
1397  * improved if the compressor can do things like use a shorter-than-possible
1398  * match in order to allow a longer match later, and also take into account the
1399  * estimated real cost of coding each match/literal based on the underlying
1400  * entropy encoding.
1401  *
1402  * Still, this is not a true optimal parser for several reasons:
1403  *
1404  * - Real compression formats use entropy encoding of the literal/match
1405  *   sequence, so the real cost of coding each match or literal is unknown until
1406  *   the parse is fully determined.  It can be approximated based on iterative
1407  *   parses, but the end result is not guaranteed to be globally optimal.
1408  *
1409  * - Very long matches are chosen immediately.  This is because locations with
1410  *   long matches are likely to have many possible alternatives that would cause
1411  *   slow optimal parsing, but also such locations are already highly
1412  *   compressible so it is not too harmful to just grab the longest match.
1413  *
1414  * - Not all possible matches at each location are considered because the
1415  *   underlying match-finder limits the number and type of matches produced at
1416  *   each position.  For example, for a given match length it's usually not
1417  *   worth it to only consider matches other than the lowest-offset match,
1418  *   except in the case of a repeat offset.
1419  *
1420  * - Although we take into account the adaptive state (in LZX, the recent offset
1421  *   queue), coding decisions made with respect to the adaptive state will be
1422  *   locally optimal but will not necessarily be globally optimal.  This is
1423  *   because the algorithm only keeps the least-costly path to get to a given
1424  *   location and does not take into account that a slightly more costly path
1425  *   could result in a different adaptive state that ultimately results in a
1426  *   lower global cost.
1427  *
1428  * - The array space used by this function is bounded, so in degenerate cases it
1429  *   is forced to start returning matches/literals before the algorithm has
1430  *   really finished.
1431  *
1432  * Each call to this function does one of two things:
1433  *
1434  * 1. Build a sequence of near-optimal matches/literals, up to some point, that
1435  *    will be returned by subsequent calls to this function, then return the
1436  *    first one.
1437  *
1438  * OR
1439  *
1440  * 2. Return the next match/literal previously computed by a call to this
1441  *    function.
1442  *
1443  * The return value is a (length, offset) pair specifying the match or literal
1444  * chosen.  For literals, the length is 0 or 1 and the offset is meaningless.
1445  */
1446 static struct raw_match
1447 lzx_get_near_optimal_match(struct lzx_compressor *ctx)
1448 {
1449         unsigned num_matches;
1450         const struct raw_match *matches;
1451         struct raw_match match;
1452         unsigned longest_len;
1453         unsigned longest_rep_len;
1454         u32 longest_rep_offset;
1455         unsigned cur_pos;
1456         unsigned end_pos;
1457
1458         if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
1459                 /* Case 2: Return the next match/literal already found.  */
1460                 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
1461                                     ctx->optimum_cur_idx;
1462                 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
1463
1464                 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
1465                 return match;
1466         }
1467
1468         /* Case 1:  Compute a new list of matches/literals to return.  */
1469
1470         ctx->optimum_cur_idx = 0;
1471         ctx->optimum_end_idx = 0;
1472
1473         /* Search for matches at recent offsets.  Only keep the one with the
1474          * longest match length.  */
1475         longest_rep_len = LZX_MIN_MATCH_LEN - 1;
1476         if (ctx->match_window_pos >= 1) {
1477                 unsigned limit = min(LZX_MAX_MATCH_LEN,
1478                                      ctx->match_window_end - ctx->match_window_pos);
1479                 for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
1480                         u32 offset = ctx->queue.R[i];
1481                         const u8 *strptr = &ctx->window[ctx->match_window_pos];
1482                         const u8 *matchptr = strptr - offset;
1483                         unsigned len = 0;
1484                         while (len < limit && strptr[len] == matchptr[len])
1485                                 len++;
1486                         if (len > longest_rep_len) {
1487                                 longest_rep_len = len;
1488                                 longest_rep_offset = offset;
1489                         }
1490                 }
1491         }
1492
1493         /* If there's a long match with a recent offset, take it.  */
1494         if (longest_rep_len >= ctx->params.alg_params.slow.nice_match_length) {
1495                 lzx_skip_bytes(ctx, longest_rep_len);
1496                 return (struct raw_match) {
1497                         .len = longest_rep_len,
1498                         .offset = longest_rep_offset,
1499                 };
1500         }
1501
1502         /* Search other matches.  */
1503         num_matches = lzx_get_matches(ctx, &matches);
1504
1505         /* If there's a long match, take it.  */
1506         if (num_matches) {
1507                 longest_len = matches[num_matches - 1].len;
1508                 if (longest_len >= ctx->params.alg_params.slow.nice_match_length) {
1509                         lzx_skip_bytes(ctx, longest_len - 1);
1510                         return matches[num_matches - 1];
1511                 }
1512         } else {
1513                 longest_len = 1;
1514         }
1515
1516         /* Calculate the cost to reach the next position by coding a literal.
1517          */
1518         ctx->optimum[1].queue = ctx->queue;
1519         ctx->optimum[1].cost = lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1520                                                 &ctx->costs);
1521         ctx->optimum[1].prev.link = 0;
1522
1523         /* Calculate the cost to reach any position up to and including that
1524          * reached by the longest match.
1525          *
1526          * Note: We consider only the lowest-offset match that reaches each
1527          * position.
1528          *
1529          * Note: Some of the cost calculation stays the same for each offset,
1530          * regardless of how many lengths it gets used for.  Therefore, to
1531          * improve performance, we hand-code the cost calculation instead of
1532          * calling lzx_match_cost() to do a from-scratch cost evaluation at each
1533          * length.  */
1534         for (unsigned i = 0, len = 2; i < num_matches; i++) {
1535                 u32 offset;
1536                 struct lzx_lru_queue queue;
1537                 u32 position_cost;
1538                 unsigned position_slot;
1539                 unsigned num_extra_bits;
1540
1541                 offset = matches[i].offset;
1542                 queue = ctx->queue;
1543                 position_cost = 0;
1544
1545                 position_slot = lzx_get_position_slot(offset, &queue);
1546                 num_extra_bits = lzx_get_num_extra_bits(position_slot);
1547                 if (num_extra_bits >= 3) {
1548                         position_cost += num_extra_bits - 3;
1549                         position_cost += ctx->costs.aligned[(offset + LZX_OFFSET_OFFSET) & 7];
1550                 } else {
1551                         position_cost += num_extra_bits;
1552                 }
1553
1554                 do {
1555                         unsigned len_header;
1556                         unsigned main_symbol;
1557                         u32 cost;
1558
1559                         cost = position_cost;
1560
1561                         len_header = min(len - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1562                         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1563                         cost += ctx->costs.main[main_symbol];
1564                         if (len_header == LZX_NUM_PRIMARY_LENS)
1565                                 cost += ctx->costs.len[len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1566
1567                         ctx->optimum[len].queue = queue;
1568                         ctx->optimum[len].prev.link = 0;
1569                         ctx->optimum[len].prev.match_offset = offset;
1570                         ctx->optimum[len].cost = cost;
1571                 } while (++len <= matches[i].len);
1572         }
1573         end_pos = longest_len;
1574
1575         if (longest_rep_len >= LZX_MIN_MATCH_LEN) {
1576                 struct lzx_lru_queue queue;
1577                 u32 cost;
1578
1579                 while (end_pos < longest_rep_len)
1580                         ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1581
1582                 queue = ctx->queue;
1583                 cost = lzx_match_cost(longest_rep_len, longest_rep_offset,
1584                                       &ctx->costs, &queue);
1585                 if (cost <= ctx->optimum[longest_rep_len].cost) {
1586                         ctx->optimum[longest_rep_len].queue = queue;
1587                         ctx->optimum[longest_rep_len].prev.link = 0;
1588                         ctx->optimum[longest_rep_len].prev.match_offset = longest_rep_offset;
1589                         ctx->optimum[longest_rep_len].cost = cost;
1590                 }
1591         }
1592
1593         /* Step forward, calculating the estimated minimum cost to reach each
1594          * position.  The algorithm may find multiple paths to reach each
1595          * position; only the lowest-cost path is saved.
1596          *
1597          * The progress of the parse is tracked in the @ctx->optimum array, which
1598          * for each position contains the minimum cost to reach that position,
1599          * the index of the start of the match/literal taken to reach that
1600          * position through the minimum-cost path, the offset of the match taken
1601          * (not relevant for literals), and the adaptive state that will exist
1602          * at that position after the minimum-cost path is taken.  The @cur_pos
1603          * variable stores the position at which the algorithm is currently
1604          * considering coding choices, and the @end_pos variable stores the
1605          * greatest position at which the costs of coding choices have been
1606          * saved.  (Actually, the algorithm guarantees that all positions up to
1607          * and including @end_pos are reachable by at least one path.)
1608          *
1609          * The loop terminates when any one of the following conditions occurs:
1610          *
1611          * 1. A match with length greater than or equal to @nice_match_length is
1612          *    found.  When this occurs, the algorithm chooses this match
1613          *    unconditionally, and consequently the near-optimal match/literal
1614          *    sequence up to and including that match is fully determined and it
1615          *    can begin returning the match/literal list.
1616          *
1617          * 2. @cur_pos reaches a position not overlapped by a preceding match.
1618          *    In such cases, the near-optimal match/literal sequence up to
1619          *    @cur_pos is fully determined and it can begin returning the
1620          *    match/literal list.
1621          *
1622          * 3. Failing either of the above in a degenerate case, the loop
1623          *    terminates when space in the @ctx->optimum array is exhausted.
1624          *    This terminates the algorithm and forces it to start returning
1625          *    matches/literals even though they may not be globally optimal.
1626          *
1627          * Upon loop termination, a nonempty list of matches/literals will have
1628          * been produced and stored in the @optimum array.  These
1629          * matches/literals are linked in reverse order, so the last thing this
1630          * function does is reverse this list and return the first
1631          * match/literal, leaving the rest to be returned immediately by
1632          * subsequent calls to this function.
1633          */
1634         cur_pos = 0;
1635         for (;;) {
1636                 u32 cost;
1637
1638                 /* Advance to next position.  */
1639                 cur_pos++;
1640
1641                 /* Check termination conditions (2) and (3) noted above.  */
1642                 if (cur_pos == end_pos || cur_pos == LZX_OPTIM_ARRAY_SIZE)
1643                         return lzx_match_chooser_reverse_list(ctx, cur_pos);
1644
1645                 /* Search for matches at recent offsets.  */
1646                 longest_rep_len = LZX_MIN_MATCH_LEN - 1;
1647                 unsigned limit = min(LZX_MAX_MATCH_LEN,
1648                                      ctx->match_window_end - ctx->match_window_pos);
1649                 for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
1650                         u32 offset = ctx->optimum[cur_pos].queue.R[i];
1651                         const u8 *strptr = &ctx->window[ctx->match_window_pos];
1652                         const u8 *matchptr = strptr - offset;
1653                         unsigned len = 0;
1654                         while (len < limit && strptr[len] == matchptr[len])
1655                                 len++;
1656                         if (len > longest_rep_len) {
1657                                 longest_rep_len = len;
1658                                 longest_rep_offset = offset;
1659                         }
1660                 }
1661
1662                 /* If we found a long match at a recent offset, choose it
1663                  * immediately.  */
1664                 if (longest_rep_len >= ctx->params.alg_params.slow.nice_match_length) {
1665                         /* Build the list of matches to return and get
1666                          * the first one.  */
1667                         match = lzx_match_chooser_reverse_list(ctx, cur_pos);
1668
1669                         /* Append the long match to the end of the list.  */
1670                         ctx->optimum[cur_pos].next.match_offset = longest_rep_offset;
1671                         ctx->optimum[cur_pos].next.link = cur_pos + longest_rep_len;
1672                         ctx->optimum_end_idx = cur_pos + longest_rep_len;
1673
1674                         /* Skip over the remaining bytes of the long match.  */
1675                         lzx_skip_bytes(ctx, longest_rep_len);
1676
1677                         /* Return first match in the list.  */
1678                         return match;
1679                 }
1680
1681                 /* Search other matches.  */
1682                 num_matches = lzx_get_matches(ctx, &matches);
1683
1684                 /* If there's a long match, take it.  */
1685                 if (num_matches) {
1686                         longest_len = matches[num_matches - 1].len;
1687                         if (longest_len >= ctx->params.alg_params.slow.nice_match_length) {
1688                                 /* Build the list of matches to return and get
1689                                  * the first one.  */
1690                                 match = lzx_match_chooser_reverse_list(ctx, cur_pos);
1691
1692                                 /* Append the long match to the end of the list.  */
1693                                 ctx->optimum[cur_pos].next.match_offset =
1694                                         matches[num_matches - 1].offset;
1695                                 ctx->optimum[cur_pos].next.link = cur_pos + longest_len;
1696                                 ctx->optimum_end_idx = cur_pos + longest_len;
1697
1698                                 /* Skip over the remaining bytes of the long match.  */
1699                                 lzx_skip_bytes(ctx, longest_len - 1);
1700
1701                                 /* Return first match in the list.  */
1702                                 return match;
1703                         }
1704                 } else {
1705                         longest_len = 1;
1706                 }
1707
1708                 while (end_pos < cur_pos + longest_len)
1709                         ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1710
1711                 /* Consider coding a literal.  */
1712                 cost = ctx->optimum[cur_pos].cost +
1713                         lzx_literal_cost(ctx->window[ctx->match_window_pos - 1],
1714                                          &ctx->costs);
1715                 if (cost < ctx->optimum[cur_pos + 1].cost) {
1716                         ctx->optimum[cur_pos + 1].queue = ctx->optimum[cur_pos].queue;
1717                         ctx->optimum[cur_pos + 1].cost = cost;
1718                         ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1719                 }
1720
1721                 /* Consider coding a match.
1722                  *
1723                  * The hard-coded cost calculation is done for the same reason
1724                  * stated in the comment for the similar loop earlier.
1725                  * Actually, it is *this* one that has the biggest effect on
1726                  * performance; overall LZX compression is > 10% faster with
1727                  * this code compared to calling lzx_match_cost() with each
1728                  * length.  */
1729                 for (unsigned i = 0, len = 2; i < num_matches; i++) {
1730                         u32 offset;
1731                         struct lzx_lru_queue queue;
1732                         u32 position_cost;
1733                         unsigned position_slot;
1734                         unsigned num_extra_bits;
1735
1736                         offset = matches[i].offset;
1737                         queue = ctx->optimum[cur_pos].queue;
1738                         position_cost = ctx->optimum[cur_pos].cost;
1739
1740                         position_slot = lzx_get_position_slot(offset, &queue);
1741                         num_extra_bits = lzx_get_num_extra_bits(position_slot);
1742                         if (num_extra_bits >= 3) {
1743                                 position_cost += num_extra_bits - 3;
1744                                 position_cost += ctx->costs.aligned[
1745                                                 (offset + LZX_OFFSET_OFFSET) & 7];
1746                         } else {
1747                                 position_cost += num_extra_bits;
1748                         }
1749
1750                         do {
1751                                 unsigned len_header;
1752                                 unsigned main_symbol;
1753                                 u32 cost;
1754
1755                                 cost = position_cost;
1756
1757                                 len_header = min(len - LZX_MIN_MATCH_LEN,
1758                                                  LZX_NUM_PRIMARY_LENS);
1759                                 main_symbol = ((position_slot << 3) | len_header) +
1760                                                 LZX_NUM_CHARS;
1761                                 cost += ctx->costs.main[main_symbol];
1762                                 if (len_header == LZX_NUM_PRIMARY_LENS) {
1763                                         cost += ctx->costs.len[len -
1764                                                         LZX_MIN_MATCH_LEN -
1765                                                         LZX_NUM_PRIMARY_LENS];
1766                                 }
1767                                 if (cost < ctx->optimum[cur_pos + len].cost) {
1768                                         ctx->optimum[cur_pos + len].queue = queue;
1769                                         ctx->optimum[cur_pos + len].prev.link = cur_pos;
1770                                         ctx->optimum[cur_pos + len].prev.match_offset = offset;
1771                                         ctx->optimum[cur_pos + len].cost = cost;
1772                                 }
1773                         } while (++len <= matches[i].len);
1774                 }
1775
1776                 if (longest_rep_len >= LZX_MIN_MATCH_LEN) {
1777                         struct lzx_lru_queue queue;
1778
1779                         while (end_pos < cur_pos + longest_rep_len)
1780                                 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1781
1782                         queue = ctx->optimum[cur_pos].queue;
1783
1784                         cost = ctx->optimum[cur_pos].cost +
1785                                 lzx_match_cost(longest_rep_len, longest_rep_offset,
1786                                                &ctx->costs, &queue);
1787                         if (cost <= ctx->optimum[cur_pos + longest_rep_len].cost) {
1788                                 ctx->optimum[cur_pos + longest_rep_len].queue =
1789                                         queue;
1790                                 ctx->optimum[cur_pos + longest_rep_len].prev.link =
1791                                         cur_pos;
1792                                 ctx->optimum[cur_pos + longest_rep_len].prev.match_offset =
1793                                         longest_rep_offset;
1794                                 ctx->optimum[cur_pos + longest_rep_len].cost =
1795                                         cost;
1796                         }
1797                 }
1798         }
1799 }
1800
1801 /* Set default symbol costs for the LZX Huffman codes.  */
1802 static void
1803 lzx_set_default_costs(struct lzx_costs * costs, unsigned num_main_syms)
1804 {
1805         unsigned i;
1806
1807         /* Main code (part 1): Literal symbols  */
1808         for (i = 0; i < LZX_NUM_CHARS; i++)
1809                 costs->main[i] = 8;
1810
1811         /* Main code (part 2): Match header symbols  */
1812         for (; i < num_main_syms; i++)
1813                 costs->main[i] = 10;
1814
1815         /* Length code  */
1816         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1817                 costs->len[i] = 8;
1818
1819         /* Aligned offset code  */
1820         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1821                 costs->aligned[i] = 3;
1822 }
1823
1824 /* Given the frequencies of symbols in an LZX-compressed block and the
1825  * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1826  * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1827  * will take fewer bits to output.  */
1828 static int
1829 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1830                                const struct lzx_codes * codes)
1831 {
1832         unsigned aligned_cost = 0;
1833         unsigned verbatim_cost = 0;
1834
1835         /* Verbatim blocks have a constant 3 bits per position footer.  Aligned
1836          * offset blocks have an aligned offset symbol per position footer, plus
1837          * an extra 24 bits per block to output the lengths necessary to
1838          * reconstruct the aligned offset code itself.  */
1839         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1840                 verbatim_cost += 3 * freqs->aligned[i];
1841                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1842         }
1843         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1844         if (aligned_cost < verbatim_cost)
1845                 return LZX_BLOCKTYPE_ALIGNED;
1846         else
1847                 return LZX_BLOCKTYPE_VERBATIM;
1848 }
1849
1850 /* Find a near-optimal sequence of matches/literals with which to output the
1851  * specified LZX block, then set the block's type to that which has the minimum
1852  * cost to output (either verbatim or aligned).  */
1853 static void
1854 lzx_optimize_block(struct lzx_compressor *ctx, struct lzx_block_spec *spec,
1855                    unsigned num_passes)
1856 {
1857         const struct lzx_lru_queue orig_queue = ctx->queue;
1858         unsigned num_passes_remaining = num_passes;
1859         struct lzx_freqs freqs;
1860         const u8 *window_ptr;
1861         const u8 *window_end;
1862         struct lzx_match *next_chosen_match;
1863         struct raw_match raw_match;
1864         struct lzx_match lzx_match;
1865
1866         LZX_ASSERT(num_passes >= 1);
1867         LZX_ASSERT(lz_bt_get_position(&ctx->mf) == spec->window_pos);
1868
1869         ctx->match_window_end = spec->window_pos + spec->block_size;
1870         ctx->matches_cached = false;
1871
1872         /* The first optimal parsing pass is done using the cost model already
1873          * set in ctx->costs.  Each later pass is done using a cost model
1874          * computed from the previous pass.
1875          *
1876          * To improve performance we only generate the array containing the
1877          * matches and literals in intermediate form on the final pass.  */
1878
1879         while (--num_passes_remaining) {
1880                 ctx->match_window_pos = spec->window_pos;
1881                 ctx->cache_ptr = ctx->cached_matches;
1882                 memset(&freqs, 0, sizeof(freqs));
1883                 window_ptr = &ctx->window[spec->window_pos];
1884                 window_end = window_ptr + spec->block_size;
1885
1886                 while (window_ptr != window_end) {
1887
1888                         raw_match = lzx_get_near_optimal_match(ctx);
1889
1890                         LZX_ASSERT(!(raw_match.len == LZX_MIN_MATCH_LEN &&
1891                                      raw_match.offset == ctx->max_window_size -
1892                                                          LZX_MIN_MATCH_LEN));
1893                         if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1894                                 lzx_tally_match(raw_match.len, raw_match.offset,
1895                                                 &freqs, &ctx->queue);
1896                                 window_ptr += raw_match.len;
1897                         } else {
1898                                 lzx_tally_literal(*window_ptr, &freqs);
1899                                 window_ptr += 1;
1900                         }
1901                 }
1902                 lzx_make_huffman_codes(&freqs, &spec->codes, ctx->num_main_syms);
1903                 lzx_set_costs(ctx, &spec->codes.lens);
1904                 ctx->queue = orig_queue;
1905                 ctx->matches_cached = true;
1906         }
1907
1908         ctx->match_window_pos = spec->window_pos;
1909         ctx->cache_ptr = ctx->cached_matches;
1910         memset(&freqs, 0, sizeof(freqs));
1911         window_ptr = &ctx->window[spec->window_pos];
1912         window_end = window_ptr + spec->block_size;
1913
1914         spec->chosen_matches = &ctx->chosen_matches[spec->window_pos];
1915         next_chosen_match = spec->chosen_matches;
1916
1917         while (window_ptr != window_end) {
1918                 raw_match = lzx_get_near_optimal_match(ctx);
1919
1920                 LZX_ASSERT(!(raw_match.len == LZX_MIN_MATCH_LEN &&
1921                              raw_match.offset == ctx->max_window_size -
1922                                                  LZX_MIN_MATCH_LEN));
1923                 if (raw_match.len >= LZX_MIN_MATCH_LEN) {
1924                         lzx_match.data = lzx_tally_match(raw_match.len,
1925                                                          raw_match.offset,
1926                                                          &freqs, &ctx->queue);
1927                         window_ptr += raw_match.len;
1928                 } else {
1929                         lzx_match.data = lzx_tally_literal(*window_ptr, &freqs);
1930                         window_ptr += 1;
1931                 }
1932                 *next_chosen_match++ = lzx_match;
1933         }
1934         spec->num_chosen_matches = next_chosen_match - spec->chosen_matches;
1935         lzx_make_huffman_codes(&freqs, &spec->codes, ctx->num_main_syms);
1936         spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
1937 }
1938
1939 /* Prepare the input window into one or more LZX blocks ready to be output.  */
1940 static void
1941 lzx_prepare_blocks(struct lzx_compressor * ctx)
1942 {
1943         /* Set up a default cost model.  */
1944         lzx_set_default_costs(&ctx->costs, ctx->num_main_syms);
1945
1946         /* Set up the block specifications.
1947          * TODO: The compression ratio could be slightly improved by performing
1948          * data-dependent block splitting instead of using fixed-size blocks.
1949          * Doing so well is a computationally hard problem, however.  */
1950         ctx->num_blocks = DIV_ROUND_UP(ctx->window_size, LZX_DIV_BLOCK_SIZE);
1951         for (unsigned i = 0; i < ctx->num_blocks; i++) {
1952                 unsigned pos = LZX_DIV_BLOCK_SIZE * i;
1953                 ctx->block_specs[i].window_pos = pos;
1954                 ctx->block_specs[i].block_size = min(ctx->window_size - pos,
1955                                                      LZX_DIV_BLOCK_SIZE);
1956         }
1957
1958         /* Load the window into the match-finder.  */
1959         lz_bt_load_window(&ctx->mf, ctx->window, ctx->window_size);
1960
1961         /* Determine sequence of matches/literals to output for each block.  */
1962         lzx_lru_queue_init(&ctx->queue);
1963         ctx->optimum_cur_idx = 0;
1964         ctx->optimum_end_idx = 0;
1965         for (unsigned i = 0; i < ctx->num_blocks; i++) {
1966                 lzx_optimize_block(ctx, &ctx->block_specs[i],
1967                                    ctx->params.alg_params.slow.num_optim_passes);
1968         }
1969 }
1970
1971 /*
1972  * This is the fast version of lzx_prepare_blocks().  This version "quickly"
1973  * prepares a single compressed block containing the entire input.  See the
1974  * description of the "Fast algorithm" at the beginning of this file for more
1975  * information.
1976  *
1977  * Input ---  the preprocessed data:
1978  *
1979  *      ctx->window[]
1980  *      ctx->window_size
1981  *
1982  * Output --- the block specification and the corresponding match/literal data:
1983  *
1984  *      ctx->block_specs[]
1985  *      ctx->num_blocks
1986  *      ctx->chosen_matches[]
1987  */
1988 static void
1989 lzx_prepare_block_fast(struct lzx_compressor * ctx)
1990 {
1991         struct lzx_record_ctx record_ctx;
1992         struct lzx_block_spec *spec;
1993
1994         /* Parameters to hash chain LZ match finder
1995          * (lazy with 1 match lookahead)  */
1996         static const struct lz_params lzx_lz_params = {
1997                 /* Although LZX_MIN_MATCH_LEN == 2, length 2 matches typically
1998                  * aren't worth choosing when using greedy or lazy parsing.  */
1999                 .min_match      = 3,
2000                 .max_match      = LZX_MAX_MATCH_LEN,
2001                 .max_offset     = LZX_MAX_WINDOW_SIZE,
2002                 .good_match     = LZX_MAX_MATCH_LEN,
2003                 .nice_match     = LZX_MAX_MATCH_LEN,
2004                 .max_chain_len  = LZX_MAX_MATCH_LEN,
2005                 .max_lazy_match = LZX_MAX_MATCH_LEN,
2006                 .too_far        = 4096,
2007         };
2008
2009         /* Initialize symbol frequencies and match offset LRU queue.  */
2010         memset(&record_ctx.freqs, 0, sizeof(struct lzx_freqs));
2011         lzx_lru_queue_init(&record_ctx.queue);
2012         record_ctx.matches = ctx->chosen_matches;
2013
2014         /* Determine series of matches/literals to output.  */
2015         lz_analyze_block(ctx->window,
2016                          ctx->window_size,
2017                          lzx_record_match,
2018                          lzx_record_literal,
2019                          &record_ctx,
2020                          &lzx_lz_params,
2021                          ctx->prev_tab);
2022
2023         /* Set up block specification.  */
2024         spec = &ctx->block_specs[0];
2025         spec->block_type = LZX_BLOCKTYPE_ALIGNED;
2026         spec->window_pos = 0;
2027         spec->block_size = ctx->window_size;
2028         spec->num_chosen_matches = (record_ctx.matches - ctx->chosen_matches);
2029         spec->chosen_matches = ctx->chosen_matches;
2030         lzx_make_huffman_codes(&record_ctx.freqs, &spec->codes,
2031                                ctx->num_main_syms);
2032         ctx->num_blocks = 1;
2033 }
2034
2035 static size_t
2036 lzx_compress(const void *uncompressed_data, size_t uncompressed_size,
2037              void *compressed_data, size_t compressed_size_avail, void *_ctx)
2038 {
2039         struct lzx_compressor *ctx = _ctx;
2040         struct output_bitstream ostream;
2041         size_t compressed_size;
2042
2043         if (uncompressed_size < 100) {
2044                 LZX_DEBUG("Too small to bother compressing.");
2045                 return 0;
2046         }
2047
2048         if (uncompressed_size > ctx->max_window_size) {
2049                 LZX_DEBUG("Can't compress %zu bytes using window of %u bytes!",
2050                           uncompressed_size, ctx->max_window_size);
2051                 return 0;
2052         }
2053
2054         LZX_DEBUG("Attempting to compress %zu bytes...",
2055                   uncompressed_size);
2056
2057         /* The input data must be preprocessed.  To avoid changing the original
2058          * input, copy it to a temporary buffer.  */
2059         memcpy(ctx->window, uncompressed_data, uncompressed_size);
2060         ctx->window_size = uncompressed_size;
2061
2062         /* This line is unnecessary; it just avoids inconsequential accesses of
2063          * uninitialized memory that would show up in memory-checking tools such
2064          * as valgrind.  */
2065         memset(&ctx->window[ctx->window_size], 0, 12);
2066
2067         LZX_DEBUG("Preprocessing data...");
2068
2069         /* Before doing any actual compression, do the call instruction (0xe8
2070          * byte) translation on the uncompressed data.  */
2071         lzx_do_e8_preprocessing(ctx->window, ctx->window_size);
2072
2073         LZX_DEBUG("Preparing blocks...");
2074
2075         /* Prepare the compressed data.  */
2076         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_FAST)
2077                 lzx_prepare_block_fast(ctx);
2078         else
2079                 lzx_prepare_blocks(ctx);
2080
2081         LZX_DEBUG("Writing compressed blocks...");
2082
2083         /* Generate the compressed data.  */
2084         init_output_bitstream(&ostream, compressed_data, compressed_size_avail);
2085         lzx_write_all_blocks(ctx, &ostream);
2086
2087         LZX_DEBUG("Flushing bitstream...");
2088         compressed_size = flush_output_bitstream(&ostream);
2089         if (compressed_size == ~(input_idx_t)0) {
2090                 LZX_DEBUG("Data did not compress to %zu bytes or less!",
2091                           compressed_size_avail);
2092                 return 0;
2093         }
2094
2095         LZX_DEBUG("Done: compressed %zu => %zu bytes.",
2096                   uncompressed_size, compressed_size);
2097
2098         /* Verify that we really get the same thing back when decompressing.
2099          * Although this could be disabled by default in all cases, it only
2100          * takes around 2-3% of the running time of the slow algorithm to do the
2101          * verification.  */
2102         if (ctx->params.algorithm == WIMLIB_LZX_ALGORITHM_SLOW
2103         #if defined(ENABLE_LZX_DEBUG) || defined(ENABLE_VERIFY_COMPRESSION)
2104             || 1
2105         #endif
2106             )
2107         {
2108                 struct wimlib_decompressor *decompressor;
2109
2110                 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZX,
2111                                                     ctx->max_window_size,
2112                                                     NULL,
2113                                                     &decompressor))
2114                 {
2115                         int ret;
2116                         ret = wimlib_decompress(compressed_data,
2117                                                 compressed_size,
2118                                                 ctx->window,
2119                                                 uncompressed_size,
2120                                                 decompressor);
2121                         wimlib_free_decompressor(decompressor);
2122
2123                         if (ret) {
2124                                 ERROR("Failed to decompress data we "
2125                                       "compressed using LZX algorithm");
2126                                 wimlib_assert(0);
2127                                 return 0;
2128                         }
2129                         if (memcmp(uncompressed_data, ctx->window, uncompressed_size)) {
2130                                 ERROR("Data we compressed using LZX algorithm "
2131                                       "didn't decompress to original");
2132                                 wimlib_assert(0);
2133                                 return 0;
2134                         }
2135                 } else {
2136                         WARNING("Failed to create decompressor for "
2137                                 "data verification!");
2138                 }
2139         }
2140         return compressed_size;
2141 }
2142
2143 static void
2144 lzx_free_compressor(void *_ctx)
2145 {
2146         struct lzx_compressor *ctx = _ctx;
2147
2148         if (ctx) {
2149                 FREE(ctx->chosen_matches);
2150                 FREE(ctx->cached_matches);
2151                 FREE(ctx->optimum);
2152                 lz_bt_destroy(&ctx->mf);
2153                 FREE(ctx->block_specs);
2154                 FREE(ctx->prev_tab);
2155                 FREE(ctx->window);
2156                 FREE(ctx);
2157         }
2158 }
2159
2160 static const struct wimlib_lzx_compressor_params lzx_fast_default = {
2161         .hdr = {
2162                 .size = sizeof(struct wimlib_lzx_compressor_params),
2163         },
2164         .algorithm = WIMLIB_LZX_ALGORITHM_FAST,
2165         .use_defaults = 0,
2166         .alg_params = {
2167                 .fast = {
2168                 },
2169         },
2170 };
2171 static const struct wimlib_lzx_compressor_params lzx_slow_default = {
2172         .hdr = {
2173                 .size = sizeof(struct wimlib_lzx_compressor_params),
2174         },
2175         .algorithm = WIMLIB_LZX_ALGORITHM_SLOW,
2176         .use_defaults = 0,
2177         .alg_params = {
2178                 .slow = {
2179                         .use_len2_matches = 1,
2180                         .nice_match_length = 32,
2181                         .num_optim_passes = 2,
2182                         .max_search_depth = 50,
2183                         .main_nostat_cost = 15,
2184                         .len_nostat_cost = 15,
2185                         .aligned_nostat_cost = 7,
2186                 },
2187         },
2188 };
2189
2190 static const struct wimlib_lzx_compressor_params *
2191 lzx_get_params(const struct wimlib_compressor_params_header *_params)
2192 {
2193         const struct wimlib_lzx_compressor_params *params =
2194                 (const struct wimlib_lzx_compressor_params*)_params;
2195
2196         if (params == NULL) {
2197                 LZX_DEBUG("Using default algorithm and parameters.");
2198                 params = &lzx_slow_default;
2199         } else {
2200                 if (params->use_defaults) {
2201                         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW)
2202                                 params = &lzx_slow_default;
2203                         else
2204                                 params = &lzx_fast_default;
2205                 }
2206         }
2207         return params;
2208 }
2209
2210 static int
2211 lzx_create_compressor(size_t window_size,
2212                       const struct wimlib_compressor_params_header *_params,
2213                       void **ctx_ret)
2214 {
2215         const struct wimlib_lzx_compressor_params *params = lzx_get_params(_params);
2216         struct lzx_compressor *ctx;
2217
2218         LZX_DEBUG("Allocating LZX context...");
2219
2220         if (!lzx_window_size_valid(window_size))
2221                 return WIMLIB_ERR_INVALID_PARAM;
2222
2223         LZX_DEBUG("Allocating memory.");
2224
2225         ctx = CALLOC(1, sizeof(struct lzx_compressor));
2226         if (ctx == NULL)
2227                 goto oom;
2228
2229         ctx->num_main_syms = lzx_get_num_main_syms(window_size);
2230         ctx->max_window_size = window_size;
2231         ctx->window = MALLOC(window_size + 12);
2232         if (ctx->window == NULL)
2233                 goto oom;
2234
2235         if (params->algorithm == WIMLIB_LZX_ALGORITHM_FAST) {
2236                 ctx->prev_tab = MALLOC(window_size * sizeof(ctx->prev_tab[0]));
2237                 if (ctx->prev_tab == NULL)
2238                         goto oom;
2239         }
2240
2241         size_t block_specs_length = DIV_ROUND_UP(window_size, LZX_DIV_BLOCK_SIZE);
2242         ctx->block_specs = MALLOC(block_specs_length * sizeof(ctx->block_specs[0]));
2243         if (ctx->block_specs == NULL)
2244                 goto oom;
2245
2246         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2247                 unsigned min_match_len = LZX_MIN_MATCH_LEN;
2248                 if (!params->alg_params.slow.use_len2_matches)
2249                         min_match_len = max(min_match_len, 3);
2250
2251                 if (!lz_bt_init(&ctx->mf,
2252                                 window_size,
2253                                 min_match_len,
2254                                 LZX_MAX_MATCH_LEN,
2255                                 params->alg_params.slow.nice_match_length,
2256                                 params->alg_params.slow.max_search_depth))
2257                         goto oom;
2258         }
2259
2260         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2261                 ctx->optimum = MALLOC((LZX_OPTIM_ARRAY_SIZE +
2262                                        min(params->alg_params.slow.nice_match_length,
2263                                            LZX_MAX_MATCH_LEN)) *
2264                                                 sizeof(ctx->optimum[0]));
2265                 if (!ctx->optimum)
2266                         goto oom;
2267         }
2268
2269         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2270                 ctx->cached_matches = MALLOC(LZX_CACHE_SIZE);
2271                 if (ctx->cached_matches == NULL)
2272                         goto oom;
2273                 ctx->cache_limit = ctx->cached_matches +
2274                                    LZX_CACHE_LEN - (LZX_MAX_MATCHES_PER_POS + 1);
2275         }
2276
2277         ctx->chosen_matches = MALLOC(window_size * sizeof(ctx->chosen_matches[0]));
2278         if (ctx->chosen_matches == NULL)
2279                 goto oom;
2280
2281         memcpy(&ctx->params, params, sizeof(struct wimlib_lzx_compressor_params));
2282         memset(&ctx->zero_codes, 0, sizeof(ctx->zero_codes));
2283
2284         LZX_DEBUG("Successfully allocated new LZX context.");
2285
2286         *ctx_ret = ctx;
2287         return 0;
2288
2289 oom:
2290         lzx_free_compressor(ctx);
2291         return WIMLIB_ERR_NOMEM;
2292 }
2293
2294 static u64
2295 lzx_get_needed_memory(size_t max_block_size,
2296                       const struct wimlib_compressor_params_header *_params)
2297 {
2298         const struct wimlib_lzx_compressor_params *params = lzx_get_params(_params);
2299
2300         u64 size = 0;
2301
2302         size += sizeof(struct lzx_compressor);
2303
2304         size += max_block_size + 12;
2305
2306         size += DIV_ROUND_UP(max_block_size, LZX_DIV_BLOCK_SIZE) *
2307                 sizeof(((struct lzx_compressor*)0)->block_specs[0]);
2308
2309         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW) {
2310                 size += max_block_size * sizeof(((struct lzx_compressor*)0)->chosen_matches[0]);
2311                 size += lz_bt_get_needed_memory(max_block_size);
2312                 size += (LZX_OPTIM_ARRAY_SIZE +
2313                          min(params->alg_params.slow.nice_match_length,
2314                              LZX_MAX_MATCH_LEN)) *
2315                                 sizeof(((struct lzx_compressor *)0)->optimum[0]);
2316                 size += LZX_CACHE_SIZE;
2317         } else {
2318                 size += max_block_size * sizeof(((struct lzx_compressor*)0)->prev_tab[0]);
2319         }
2320         return size;
2321 }
2322
2323 static bool
2324 lzx_params_valid(const struct wimlib_compressor_params_header *_params)
2325 {
2326         const struct wimlib_lzx_compressor_params *params =
2327                 (const struct wimlib_lzx_compressor_params*)_params;
2328
2329         if (params->hdr.size != sizeof(struct wimlib_lzx_compressor_params)) {
2330                 LZX_DEBUG("Invalid parameter structure size!");
2331                 return false;
2332         }
2333
2334         if (params->algorithm != WIMLIB_LZX_ALGORITHM_SLOW &&
2335             params->algorithm != WIMLIB_LZX_ALGORITHM_FAST)
2336         {
2337                 LZX_DEBUG("Invalid algorithm.");
2338                 return false;
2339         }
2340
2341         if (params->algorithm == WIMLIB_LZX_ALGORITHM_SLOW &&
2342             !params->use_defaults)
2343         {
2344                 if (params->alg_params.slow.num_optim_passes < 1)
2345                 {
2346                         LZX_DEBUG("Invalid number of optimization passes!");
2347                         return false;
2348                 }
2349
2350                 if (params->alg_params.slow.main_nostat_cost < 1 ||
2351                     params->alg_params.slow.main_nostat_cost > 16)
2352                 {
2353                         LZX_DEBUG("Invalid main_nostat_cost!");
2354                         return false;
2355                 }
2356
2357                 if (params->alg_params.slow.len_nostat_cost < 1 ||
2358                     params->alg_params.slow.len_nostat_cost > 16)
2359                 {
2360                         LZX_DEBUG("Invalid len_nostat_cost!");
2361                         return false;
2362                 }
2363
2364                 if (params->alg_params.slow.aligned_nostat_cost < 1 ||
2365                     params->alg_params.slow.aligned_nostat_cost > 8)
2366                 {
2367                         LZX_DEBUG("Invalid aligned_nostat_cost!");
2368                         return false;
2369                 }
2370         }
2371         return true;
2372 }
2373
2374 const struct compressor_ops lzx_compressor_ops = {
2375         .params_valid       = lzx_params_valid,
2376         .get_needed_memory  = lzx_get_needed_memory,
2377         .create_compressor  = lzx_create_compressor,
2378         .compress           = lzx_compress,
2379         .free_compressor    = lzx_free_compressor,
2380 };