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