]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
lzx-compress.c: Don't update recent offset queue unnecessarily
[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         struct lzx_lru_queue queue;
444 };
445
446 /* Returns the LZX position slot that corresponds to a given match offset,
447  * taking into account the recent offset queue and updating it if the offset is
448  * found in it.  */
449 static unsigned
450 lzx_get_position_slot(u32 offset, struct lzx_lru_queue *queue)
451 {
452         unsigned position_slot;
453
454         /* See if the offset was recently used.  */
455         for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
456                 if (offset == queue->R[i]) {
457                         /* Found it.  */
458
459                         /* Bring the repeat offset to the front of the
460                          * queue.  Note: this is, in fact, not a real
461                          * LRU queue because repeat matches are simply
462                          * swapped to the front.  */
463                         swap(queue->R[0], queue->R[i]);
464
465                         /* The resulting position slot is simply the first index
466                          * at which the offset was found in the queue.  */
467                         return i;
468                 }
469         }
470
471         /* The offset was not recently used; look up its real position slot.  */
472         position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
473
474         /* Bring the new offset to the front of the queue.  */
475         for (int i = LZX_NUM_RECENT_OFFSETS - 1; i > 0; i--)
476                 queue->R[i] = queue->R[i - 1];
477         queue->R[0] = offset;
478
479         return position_slot;
480 }
481
482 /* Build the main, length, and aligned offset Huffman codes used in LZX.
483  *
484  * This takes as input the frequency tables for each code and produces as output
485  * a set of tables that map symbols to codewords and codeword lengths.  */
486 static void
487 lzx_make_huffman_codes(const struct lzx_freqs *freqs,
488                        struct lzx_codes *codes,
489                        unsigned num_main_syms)
490 {
491         make_canonical_huffman_code(num_main_syms,
492                                     LZX_MAX_MAIN_CODEWORD_LEN,
493                                     freqs->main,
494                                     codes->lens.main,
495                                     codes->codewords.main);
496
497         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
498                                     LZX_MAX_LEN_CODEWORD_LEN,
499                                     freqs->len,
500                                     codes->lens.len,
501                                     codes->codewords.len);
502
503         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
504                                     LZX_MAX_ALIGNED_CODEWORD_LEN,
505                                     freqs->aligned,
506                                     codes->lens.aligned,
507                                     codes->codewords.aligned);
508 }
509
510 /*
511  * Output a precomputed LZX match.
512  *
513  * @out:
514  *      The bitstream to which to write the match.
515  * @block_type:
516  *      The type of the LZX block (LZX_BLOCKTYPE_ALIGNED or
517  *      LZX_BLOCKTYPE_VERBATIM)
518  * @match:
519  *      The match data.
520  * @codes:
521  *      Pointer to a structure that contains the codewords for the main, length,
522  *      and aligned offset Huffman codes for the current LZX compressed block.
523  */
524 static void
525 lzx_write_match(struct output_bitstream *out, int block_type,
526                 struct lzx_item match, const struct lzx_codes *codes)
527 {
528         /* low 8 bits are the match length minus 2 */
529         unsigned match_len_minus_2 = match.data & 0xff;
530         /* Next 17 bits are the position footer */
531         unsigned position_footer = (match.data >> 8) & 0x1ffff; /* 17 bits */
532         /* Next 6 bits are the position slot. */
533         unsigned position_slot = (match.data >> 25) & 0x3f;     /* 6 bits */
534         unsigned len_header;
535         unsigned len_footer;
536         unsigned main_symbol;
537         unsigned num_extra_bits;
538         unsigned verbatim_bits;
539         unsigned aligned_bits;
540
541         /* If the match length is less than MIN_MATCH_LEN (= 2) +
542          * NUM_PRIMARY_LENS (= 7), the length header contains
543          * the match length minus MIN_MATCH_LEN, and there is no
544          * length footer.
545          *
546          * Otherwise, the length header contains
547          * NUM_PRIMARY_LENS, and the length footer contains
548          * the match length minus NUM_PRIMARY_LENS minus
549          * MIN_MATCH_LEN. */
550         if (match_len_minus_2 < LZX_NUM_PRIMARY_LENS) {
551                 len_header = match_len_minus_2;
552         } else {
553                 len_header = LZX_NUM_PRIMARY_LENS;
554                 len_footer = match_len_minus_2 - LZX_NUM_PRIMARY_LENS;
555         }
556
557         /* Combine the position slot with the length header into a single symbol
558          * that will be encoded with the main code.
559          *
560          * The actual main symbol is offset by LZX_NUM_CHARS because values
561          * under LZX_NUM_CHARS are used to indicate a literal byte rather than a
562          * match.  */
563         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
564
565         /* Output main symbol. */
566         bitstream_put_bits(out, codes->codewords.main[main_symbol],
567                            codes->lens.main[main_symbol]);
568
569         /* If there is a length footer, output it using the
570          * length Huffman code. */
571         if (len_header == LZX_NUM_PRIMARY_LENS)
572                 bitstream_put_bits(out, codes->codewords.len[len_footer],
573                                    codes->lens.len[len_footer]);
574
575         num_extra_bits = lzx_get_num_extra_bits(position_slot);
576
577         /* For aligned offset blocks with at least 3 extra bits, output the
578          * verbatim bits literally, then the aligned bits encoded using the
579          * aligned offset code.  Otherwise, only the verbatim bits need to be
580          * output. */
581         if ((block_type == LZX_BLOCKTYPE_ALIGNED) && (num_extra_bits >= 3)) {
582
583                 verbatim_bits = position_footer >> 3;
584                 bitstream_put_bits(out, verbatim_bits,
585                                    num_extra_bits - 3);
586
587                 aligned_bits = (position_footer & 7);
588                 bitstream_put_bits(out,
589                                    codes->codewords.aligned[aligned_bits],
590                                    codes->lens.aligned[aligned_bits]);
591         } else {
592                 /* verbatim bits is the same as the position
593                  * footer, in this case. */
594                 bitstream_put_bits(out, position_footer, num_extra_bits);
595         }
596 }
597
598 /* Output an LZX literal (encoded with the main Huffman code).  */
599 static void
600 lzx_write_literal(struct output_bitstream *out, u8 literal,
601                   const struct lzx_codes *codes)
602 {
603         bitstream_put_bits(out,
604                            codes->codewords.main[literal],
605                            codes->lens.main[literal]);
606 }
607
608 static unsigned
609 lzx_build_precode(const u8 lens[restrict],
610                   const u8 prev_lens[restrict],
611                   const unsigned num_syms,
612                   u32 precode_freqs[restrict LZX_PRECODE_NUM_SYMBOLS],
613                   u8 output_syms[restrict num_syms],
614                   u8 precode_lens[restrict LZX_PRECODE_NUM_SYMBOLS],
615                   u32 precode_codewords[restrict LZX_PRECODE_NUM_SYMBOLS],
616                   unsigned *num_additional_bits_ret)
617 {
618         memset(precode_freqs, 0,
619                LZX_PRECODE_NUM_SYMBOLS * sizeof(precode_freqs[0]));
620
621         /* Since the code word lengths use a form of RLE encoding, the goal here
622          * is to find each run of identical lengths when going through them in
623          * symbol order (including runs of length 1).  For each run, as many
624          * lengths are encoded using RLE as possible, and the rest are output
625          * literally.
626          *
627          * output_syms[] will be filled in with the length symbols that will be
628          * output, including RLE codes, not yet encoded using the precode.
629          *
630          * cur_run_len keeps track of how many code word lengths are in the
631          * current run of identical lengths.  */
632         unsigned output_syms_idx = 0;
633         unsigned cur_run_len = 1;
634         unsigned num_additional_bits = 0;
635         for (unsigned i = 1; i <= num_syms; i++) {
636
637                 if (i != num_syms && lens[i] == lens[i - 1]) {
638                         /* Still in a run--- keep going. */
639                         cur_run_len++;
640                         continue;
641                 }
642
643                 /* Run ended! Check if it is a run of zeroes or a run of
644                  * nonzeroes. */
645
646                 /* The symbol that was repeated in the run--- not to be confused
647                  * with the length *of* the run (cur_run_len) */
648                 unsigned len_in_run = lens[i - 1];
649
650                 if (len_in_run == 0) {
651                         /* A run of 0's.  Encode it in as few length
652                          * codes as we can. */
653
654                         /* The magic length 18 indicates a run of 20 + n zeroes,
655                          * where n is an uncompressed literal 5-bit integer that
656                          * follows the magic length. */
657                         while (cur_run_len >= 20) {
658                                 unsigned additional_bits;
659
660                                 additional_bits = min(cur_run_len - 20, 0x1f);
661                                 num_additional_bits += 5;
662                                 precode_freqs[18]++;
663                                 output_syms[output_syms_idx++] = 18;
664                                 output_syms[output_syms_idx++] = additional_bits;
665                                 cur_run_len -= 20 + additional_bits;
666                         }
667
668                         /* The magic length 17 indicates a run of 4 + n zeroes,
669                          * where n is an uncompressed literal 4-bit integer that
670                          * follows the magic length. */
671                         while (cur_run_len >= 4) {
672                                 unsigned additional_bits;
673
674                                 additional_bits = min(cur_run_len - 4, 0xf);
675                                 num_additional_bits += 4;
676                                 precode_freqs[17]++;
677                                 output_syms[output_syms_idx++] = 17;
678                                 output_syms[output_syms_idx++] = additional_bits;
679                                 cur_run_len -= 4 + additional_bits;
680                         }
681
682                 } else {
683
684                         /* A run of nonzero lengths. */
685
686                         /* The magic length 19 indicates a run of 4 + n
687                          * nonzeroes, where n is a literal bit that follows the
688                          * magic length, and where the value of the lengths in
689                          * the run is given by an extra length symbol, encoded
690                          * with the precode, that follows the literal bit.
691                          *
692                          * The extra length symbol is encoded as a difference
693                          * from the length of the codeword for the first symbol
694                          * in the run in the previous code.
695                          * */
696                         while (cur_run_len >= 4) {
697                                 unsigned additional_bits;
698                                 signed char delta;
699
700                                 additional_bits = (cur_run_len > 4);
701                                 num_additional_bits += 1;
702                                 delta = (signed char)prev_lens[i - cur_run_len] -
703                                         (signed char)len_in_run;
704                                 if (delta < 0)
705                                         delta += 17;
706                                 precode_freqs[19]++;
707                                 precode_freqs[(unsigned char)delta]++;
708                                 output_syms[output_syms_idx++] = 19;
709                                 output_syms[output_syms_idx++] = additional_bits;
710                                 output_syms[output_syms_idx++] = delta;
711                                 cur_run_len -= 4 + additional_bits;
712                         }
713                 }
714
715                 /* Any remaining lengths in the run are outputted without RLE,
716                  * as a difference from the length of that codeword in the
717                  * previous code. */
718                 while (cur_run_len > 0) {
719                         signed char delta;
720
721                         delta = (signed char)prev_lens[i - cur_run_len] -
722                                 (signed char)len_in_run;
723                         if (delta < 0)
724                                 delta += 17;
725
726                         precode_freqs[(unsigned char)delta]++;
727                         output_syms[output_syms_idx++] = delta;
728                         cur_run_len--;
729                 }
730
731                 cur_run_len = 1;
732         }
733
734         /* Build the precode from the frequencies of the length symbols. */
735
736         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
737                                     LZX_MAX_PRE_CODEWORD_LEN,
738                                     precode_freqs, precode_lens,
739                                     precode_codewords);
740
741         *num_additional_bits_ret = num_additional_bits;
742
743         return output_syms_idx;
744 }
745
746 /*
747  * Output a Huffman code in the compressed form used in LZX.
748  *
749  * The Huffman code is represented in the output as a logical series of codeword
750  * lengths from which the Huffman code, which must be in canonical form, can be
751  * reconstructed.
752  *
753  * The codeword lengths are themselves compressed using a separate Huffman code,
754  * the "precode", which contains a symbol for each possible codeword length in
755  * the larger code as well as several special symbols to represent repeated
756  * codeword lengths (a form of run-length encoding).  The precode is itself
757  * constructed in canonical form, and its codeword lengths are represented
758  * literally in 20 4-bit fields that immediately precede the compressed codeword
759  * lengths of the larger code.
760  *
761  * Furthermore, the codeword lengths of the larger code are actually represented
762  * as deltas from the codeword lengths of the corresponding code in the previous
763  * block.
764  *
765  * @out:
766  *      Bitstream to which to write the compressed Huffman code.
767  * @lens:
768  *      The codeword lengths, indexed by symbol, in the Huffman code.
769  * @prev_lens:
770  *      The codeword lengths, indexed by symbol, in the corresponding Huffman
771  *      code in the previous block, or all zeroes if this is the first block.
772  * @num_syms:
773  *      The number of symbols in the Huffman code.
774  */
775 static void
776 lzx_write_compressed_code(struct output_bitstream *out,
777                           const u8 lens[restrict],
778                           const u8 prev_lens[restrict],
779                           unsigned num_syms)
780 {
781         u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
782         u8 output_syms[num_syms];
783         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
784         u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
785         unsigned i;
786         unsigned num_output_syms;
787         u8 precode_sym;
788         unsigned dummy;
789
790         num_output_syms = lzx_build_precode(lens,
791                                             prev_lens,
792                                             num_syms,
793                                             precode_freqs,
794                                             output_syms,
795                                             precode_lens,
796                                             precode_codewords,
797                                             &dummy);
798
799         /* Write the lengths of the precode codes to the output. */
800         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
801                 bitstream_put_bits(out, precode_lens[i],
802                                    LZX_PRECODE_ELEMENT_SIZE);
803
804         /* Write the length symbols, encoded with the precode, to the output. */
805
806         for (i = 0; i < num_output_syms; ) {
807                 precode_sym = output_syms[i++];
808
809                 bitstream_put_bits(out, precode_codewords[precode_sym],
810                                    precode_lens[precode_sym]);
811                 switch (precode_sym) {
812                 case 17:
813                         bitstream_put_bits(out, output_syms[i++], 4);
814                         break;
815                 case 18:
816                         bitstream_put_bits(out, output_syms[i++], 5);
817                         break;
818                 case 19:
819                         bitstream_put_bits(out, output_syms[i++], 1);
820                         bitstream_put_bits(out,
821                                            precode_codewords[output_syms[i]],
822                                            precode_lens[output_syms[i]]);
823                         i++;
824                         break;
825                 default:
826                         break;
827                 }
828         }
829 }
830
831 /*
832  * Write all matches and literal bytes (which were precomputed) in an LZX
833  * compressed block to the output bitstream in the final compressed
834  * representation.
835  *
836  * @ostream
837  *      The output bitstream.
838  * @block_type
839  *      The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
840  *      LZX_BLOCKTYPE_VERBATIM).
841  * @items
842  *      The array of matches/literals to output.
843  * @num_items
844  *      Number of matches/literals to output (length of @items).
845  * @codes
846  *      The main, length, and aligned offset Huffman codes for the current
847  *      LZX compressed block.
848  */
849 static void
850 lzx_write_items(struct output_bitstream *ostream, int block_type,
851                 const struct lzx_item items[], u32 num_items,
852                 const struct lzx_codes *codes)
853 {
854         for (u32 i = 0; i < num_items; i++) {
855                 /* The high bit of the 32-bit intermediate representation
856                  * indicates whether the item is an actual LZ-style match (1) or
857                  * a literal byte (0).  */
858                 if (items[i].data & 0x80000000)
859                         lzx_write_match(ostream, block_type, items[i], codes);
860                 else
861                         lzx_write_literal(ostream, items[i].data, codes);
862         }
863 }
864
865 /* Write an LZX aligned offset or verbatim block to the output.  */
866 static void
867 lzx_write_compressed_block(int block_type,
868                            unsigned block_size,
869                            unsigned max_window_size,
870                            unsigned num_main_syms,
871                            struct lzx_item * chosen_items,
872                            unsigned num_chosen_items,
873                            const struct lzx_codes * codes,
874                            const struct lzx_codes * prev_codes,
875                            struct output_bitstream * ostream)
876 {
877         unsigned i;
878
879         LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
880                    block_type == LZX_BLOCKTYPE_VERBATIM);
881
882         /* The first three bits indicate the type of block and are one of the
883          * LZX_BLOCKTYPE_* constants.  */
884         bitstream_put_bits(ostream, block_type, 3);
885
886         /* Output the block size.
887          *
888          * The original LZX format seemed to always encode the block size in 3
889          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
890          * uses the first bit to indicate whether the block is the default size
891          * (32768) or a different size given explicitly by the next 16 bits.
892          *
893          * By default, this compressor uses a window size of 32768 and therefore
894          * follows the WIMGAPI behavior.  However, this compressor also supports
895          * window sizes greater than 32768 bytes, which do not appear to be
896          * supported by WIMGAPI.  In such cases, we retain the default size bit
897          * to mean a size of 32768 bytes but output non-default block size in 24
898          * bits rather than 16.  The compatibility of this behavior is unknown
899          * because WIMs created with chunk size greater than 32768 can seemingly
900          * only be opened by wimlib anyway.  */
901         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
902                 bitstream_put_bits(ostream, 1, 1);
903         } else {
904                 bitstream_put_bits(ostream, 0, 1);
905
906                 if (max_window_size >= 65536)
907                         bitstream_put_bits(ostream, block_size >> 16, 8);
908
909                 bitstream_put_bits(ostream, block_size, 16);
910         }
911
912         /* Write out lengths of the main code. Note that the LZX specification
913          * incorrectly states that the aligned offset code comes after the
914          * length code, but in fact it is the very first code to be written
915          * (before the main code).  */
916         if (block_type == LZX_BLOCKTYPE_ALIGNED)
917                 for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
918                         bitstream_put_bits(ostream, codes->lens.aligned[i],
919                                            LZX_ALIGNEDCODE_ELEMENT_SIZE);
920
921         /* Write the precode and lengths for the first LZX_NUM_CHARS symbols in
922          * the main code, which are the codewords for literal bytes.  */
923         lzx_write_compressed_code(ostream,
924                                   codes->lens.main,
925                                   prev_codes->lens.main,
926                                   LZX_NUM_CHARS);
927
928         /* Write the precode and lengths for the rest of the main code, which
929          * are the codewords for match headers.  */
930         lzx_write_compressed_code(ostream,
931                                   codes->lens.main + LZX_NUM_CHARS,
932                                   prev_codes->lens.main + LZX_NUM_CHARS,
933                                   num_main_syms - LZX_NUM_CHARS);
934
935         /* Write the precode and lengths for the length code.  */
936         lzx_write_compressed_code(ostream,
937                                   codes->lens.len,
938                                   prev_codes->lens.len,
939                                   LZX_LENCODE_NUM_SYMBOLS);
940
941         /* Write the actual matches and literals.  */
942         lzx_write_items(ostream, block_type,
943                         chosen_items, num_chosen_items, codes);
944 }
945
946 /* Write out the LZX blocks that were computed.  */
947 static void
948 lzx_write_all_blocks(struct lzx_compressor *c, struct output_bitstream *ostream)
949 {
950
951         const struct lzx_codes *prev_codes = &c->zero_codes;
952         for (unsigned i = 0; i < c->num_blocks; i++) {
953                 const struct lzx_block_spec *spec = &c->block_specs[i];
954
955                 LZX_DEBUG("Writing block %u/%u (type=%d, size=%u, num_chosen_items=%u)...",
956                           i + 1, c->num_blocks,
957                           spec->block_type, spec->block_size,
958                           spec->num_chosen_items);
959
960                 lzx_write_compressed_block(spec->block_type,
961                                            spec->block_size,
962                                            c->max_window_size,
963                                            c->num_main_syms,
964                                            spec->chosen_items,
965                                            spec->num_chosen_items,
966                                            &spec->codes,
967                                            prev_codes,
968                                            ostream);
969
970                 prev_codes = &spec->codes;
971         }
972 }
973
974 /* Constructs an LZX match from a literal byte and updates the main code symbol
975  * frequencies.  */
976 static inline u32
977 lzx_tally_literal(u8 lit, struct lzx_freqs *freqs)
978 {
979         freqs->main[lit]++;
980         return (u32)lit;
981 }
982
983 /* Constructs an LZX match from an offset and a length, and updates the LRU
984  * queue and the frequency of symbols in the main, length, and aligned offset
985  * alphabets.  The return value is a 32-bit number that provides the match in an
986  * intermediate representation documented below.  */
987 static inline u32
988 lzx_tally_match(unsigned match_len, u32 match_offset,
989                 struct lzx_freqs *freqs, struct lzx_lru_queue *queue)
990 {
991         unsigned position_slot;
992         unsigned position_footer;
993         u32 len_header;
994         unsigned main_symbol;
995         unsigned len_footer;
996         unsigned adjusted_match_len;
997
998         LZX_ASSERT(match_len >= LZX_MIN_MATCH_LEN && match_len <= LZX_MAX_MATCH_LEN);
999
1000         /* The match offset shall be encoded as a position slot (itself encoded
1001          * as part of the main symbol) and a position footer.  */
1002         position_slot = lzx_get_position_slot(match_offset, queue);
1003         position_footer = (match_offset + LZX_OFFSET_OFFSET) &
1004                                 ((1U << lzx_get_num_extra_bits(position_slot)) - 1);
1005
1006         /* The match length shall be encoded as a length header (itself encoded
1007          * as part of the main symbol) and an optional length footer.  */
1008         adjusted_match_len = match_len - LZX_MIN_MATCH_LEN;
1009         if (adjusted_match_len < LZX_NUM_PRIMARY_LENS) {
1010                 /* No length footer needed.  */
1011                 len_header = adjusted_match_len;
1012         } else {
1013                 /* Length footer needed.  It will be encoded using the length
1014                  * code.  */
1015                 len_header = LZX_NUM_PRIMARY_LENS;
1016                 len_footer = adjusted_match_len - LZX_NUM_PRIMARY_LENS;
1017                 freqs->len[len_footer]++;
1018         }
1019
1020         /* Account for the main symbol.  */
1021         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1022
1023         freqs->main[main_symbol]++;
1024
1025         /* In an aligned offset block, 3 bits of the position footer are output
1026          * as an aligned offset symbol.  Account for this, although we may
1027          * ultimately decide to output the block as verbatim.  */
1028
1029         /* The following check is equivalent to:
1030          *
1031          * if (lzx_extra_bits[position_slot] >= 3)
1032          *
1033          * Note that this correctly excludes position slots that correspond to
1034          * recent offsets.  */
1035         if (position_slot >= 8)
1036                 freqs->aligned[position_footer & 7]++;
1037
1038         /* Pack the position slot, position footer, and match length into an
1039          * intermediate representation.  See `struct lzx_item' for details.
1040          */
1041         LZX_ASSERT(LZX_MAX_POSITION_SLOTS <= 64);
1042         LZX_ASSERT(lzx_get_num_extra_bits(LZX_MAX_POSITION_SLOTS - 1) <= 17);
1043         LZX_ASSERT(LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1 <= 256);
1044
1045         LZX_ASSERT(position_slot      <= (1U << (31 - 25)) - 1);
1046         LZX_ASSERT(position_footer    <= (1U << (25 -  8)) - 1);
1047         LZX_ASSERT(adjusted_match_len <= (1U << (8  -  0)) - 1);
1048         return 0x80000000 |
1049                 (position_slot << 25) |
1050                 (position_footer << 8) |
1051                 (adjusted_match_len);
1052 }
1053
1054 /* Returns the cost, in bits, to output a literal byte using the specified cost
1055  * model.  */
1056 static u32
1057 lzx_literal_cost(u8 c, const struct lzx_costs * costs)
1058 {
1059         return costs->main[c];
1060 }
1061
1062 /* Returns the cost, in bits, to output a repeat offset match of the specified
1063  * length and position slot (repeat index) using the specified cost model.  */
1064 static u32
1065 lzx_repmatch_cost(u32 len, unsigned position_slot, const struct lzx_costs *costs)
1066 {
1067         unsigned len_header, main_symbol;
1068         u32 cost = 0;
1069
1070         len_header = min(len - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1071         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1072
1073         /* Account for main symbol.  */
1074         cost += costs->main[main_symbol];
1075
1076         /* Account for extra length information.  */
1077         if (len_header == LZX_NUM_PRIMARY_LENS)
1078                 cost += costs->len[len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1079
1080         return cost;
1081 }
1082
1083 /* Set the cost model @c->costs from the Huffman codeword lengths specified in
1084  * @lens.
1085  *
1086  * The cost model and codeword lengths are almost the same thing, but the
1087  * Huffman codewords with length 0 correspond to symbols with zero frequency
1088  * that still need to be assigned actual costs.  The specific values assigned
1089  * are arbitrary, but they should be fairly high (near the maximum codeword
1090  * length) to take into account the fact that uses of these symbols are expected
1091  * to be rare.  */
1092 static void
1093 lzx_set_costs(struct lzx_compressor *c, const struct lzx_lens * lens,
1094               unsigned nostat)
1095 {
1096         unsigned i;
1097
1098         /* Main code  */
1099         for (i = 0; i < c->num_main_syms; i++)
1100                 c->costs.main[i] = lens->main[i] ? lens->main[i] : nostat;
1101
1102         /* Length code  */
1103         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1104                 c->costs.len[i] = lens->len[i] ? lens->len[i] : nostat;
1105
1106         /* Aligned offset code  */
1107         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1108                 c->costs.aligned[i] = lens->aligned[i] ? lens->aligned[i] : nostat / 2;
1109 }
1110
1111 /* Don't allow matches to span the end of an LZX block.  */
1112 static inline u32
1113 maybe_truncate_matches(struct lz_match matches[], u32 num_matches,
1114                        struct lzx_compressor *c)
1115 {
1116         if (c->match_window_end < c->cur_window_size && num_matches != 0) {
1117                 u32 limit = c->match_window_end - c->match_window_pos;
1118
1119                 if (limit >= LZX_MIN_MATCH_LEN) {
1120
1121                         u32 i = num_matches - 1;
1122                         do {
1123                                 if (matches[i].len >= limit) {
1124                                         matches[i].len = limit;
1125
1126                                         /* Truncation might produce multiple
1127                                          * matches with length 'limit'.  Keep at
1128                                          * most 1.  */
1129                                         num_matches = i + 1;
1130                                 }
1131                         } while (i--);
1132                 } else {
1133                         num_matches = 0;
1134                 }
1135         }
1136         return num_matches;
1137 }
1138
1139 static unsigned
1140 lzx_get_matches_fillcache_singleblock(struct lzx_compressor *c,
1141                                       const struct lz_match **matches_ret)
1142 {
1143         struct lz_match *cache_ptr;
1144         struct lz_match *matches;
1145         unsigned num_matches;
1146
1147         cache_ptr = c->cache_ptr;
1148         matches = cache_ptr + 1;
1149         if (likely(cache_ptr <= c->cache_limit)) {
1150                 num_matches = lz_mf_get_matches(c->mf, matches);
1151                 cache_ptr->len = num_matches;
1152                 c->cache_ptr = matches + num_matches;
1153         } else {
1154                 num_matches = 0;
1155         }
1156         c->match_window_pos++;
1157         *matches_ret = matches;
1158         return num_matches;
1159 }
1160
1161 static unsigned
1162 lzx_get_matches_fillcache_multiblock(struct lzx_compressor *c,
1163                                      const struct lz_match **matches_ret)
1164 {
1165         struct lz_match *cache_ptr;
1166         struct lz_match *matches;
1167         unsigned num_matches;
1168
1169         cache_ptr = c->cache_ptr;
1170         matches = cache_ptr + 1;
1171         if (likely(cache_ptr <= c->cache_limit)) {
1172                 num_matches = lz_mf_get_matches(c->mf, matches);
1173                 num_matches = maybe_truncate_matches(matches, num_matches, c);
1174                 cache_ptr->len = num_matches;
1175                 c->cache_ptr = matches + num_matches;
1176         } else {
1177                 num_matches = 0;
1178         }
1179         c->match_window_pos++;
1180         *matches_ret = matches;
1181         return num_matches;
1182 }
1183
1184 static unsigned
1185 lzx_get_matches_usecache(struct lzx_compressor *c,
1186                          const struct lz_match **matches_ret)
1187 {
1188         struct lz_match *cache_ptr;
1189         struct lz_match *matches;
1190         unsigned num_matches;
1191
1192         cache_ptr = c->cache_ptr;
1193         matches = cache_ptr + 1;
1194         if (cache_ptr <= c->cache_limit) {
1195                 num_matches = cache_ptr->len;
1196                 c->cache_ptr = matches + num_matches;
1197         } else {
1198                 num_matches = 0;
1199         }
1200         c->match_window_pos++;
1201         *matches_ret = matches;
1202         return num_matches;
1203 }
1204
1205 static unsigned
1206 lzx_get_matches_usecache_nocheck(struct lzx_compressor *c,
1207                                  const struct lz_match **matches_ret)
1208 {
1209         struct lz_match *cache_ptr;
1210         struct lz_match *matches;
1211         unsigned num_matches;
1212
1213         cache_ptr = c->cache_ptr;
1214         matches = cache_ptr + 1;
1215         num_matches = cache_ptr->len;
1216         c->cache_ptr = matches + num_matches;
1217         c->match_window_pos++;
1218         *matches_ret = matches;
1219         return num_matches;
1220 }
1221
1222 static unsigned
1223 lzx_get_matches_nocache_singleblock(struct lzx_compressor *c,
1224                                     const struct lz_match **matches_ret)
1225 {
1226         struct lz_match *matches;
1227         unsigned num_matches;
1228
1229         matches = c->cache_ptr;
1230         num_matches = lz_mf_get_matches(c->mf, matches);
1231         c->match_window_pos++;
1232         *matches_ret = matches;
1233         return num_matches;
1234 }
1235
1236 static unsigned
1237 lzx_get_matches_nocache_multiblock(struct lzx_compressor *c,
1238                                    const struct lz_match **matches_ret)
1239 {
1240         struct lz_match *matches;
1241         unsigned num_matches;
1242
1243         matches = c->cache_ptr;
1244         num_matches = lz_mf_get_matches(c->mf, matches);
1245         num_matches = maybe_truncate_matches(matches, num_matches, c);
1246         c->match_window_pos++;
1247         *matches_ret = matches;
1248         return num_matches;
1249 }
1250
1251 /*
1252  * Find matches at the next position in the window.
1253  *
1254  * Returns the number of matches found and sets *matches_ret to point to the
1255  * matches array.  The matches will be sorted by strictly increasing length and
1256  * offset.
1257  */
1258 static inline unsigned
1259 lzx_get_matches(struct lzx_compressor *c,
1260                 const struct lz_match **matches_ret)
1261 {
1262         return (*c->get_matches_func)(c, matches_ret);
1263 }
1264
1265 static void
1266 lzx_skip_bytes_fillcache(struct lzx_compressor *c, unsigned n)
1267 {
1268         struct lz_match *cache_ptr;
1269
1270         cache_ptr = c->cache_ptr;
1271         c->match_window_pos += n;
1272         lz_mf_skip_positions(c->mf, n);
1273         if (cache_ptr <= c->cache_limit) {
1274                 do {
1275                         cache_ptr->len = 0;
1276                         cache_ptr += 1;
1277                 } while (--n && cache_ptr <= c->cache_limit);
1278         }
1279         c->cache_ptr = cache_ptr;
1280 }
1281
1282 static void
1283 lzx_skip_bytes_usecache(struct lzx_compressor *c, unsigned n)
1284 {
1285         struct lz_match *cache_ptr;
1286
1287         cache_ptr = c->cache_ptr;
1288         c->match_window_pos += n;
1289         if (cache_ptr <= c->cache_limit) {
1290                 do {
1291                         cache_ptr += 1 + cache_ptr->len;
1292                 } while (--n && cache_ptr <= c->cache_limit);
1293         }
1294         c->cache_ptr = cache_ptr;
1295 }
1296
1297 static void
1298 lzx_skip_bytes_usecache_nocheck(struct lzx_compressor *c, unsigned n)
1299 {
1300         struct lz_match *cache_ptr;
1301
1302         cache_ptr = c->cache_ptr;
1303         c->match_window_pos += n;
1304         do {
1305                 cache_ptr += 1 + cache_ptr->len;
1306         } while (--n);
1307         c->cache_ptr = cache_ptr;
1308 }
1309
1310 static void
1311 lzx_skip_bytes_nocache(struct lzx_compressor *c, unsigned n)
1312 {
1313         c->match_window_pos += n;
1314         lz_mf_skip_positions(c->mf, n);
1315 }
1316
1317 /*
1318  * Skip the specified number of positions in the window (don't search for
1319  * matches at them).
1320  */
1321 static inline void
1322 lzx_skip_bytes(struct lzx_compressor *c, unsigned n)
1323 {
1324         return (*c->skip_bytes_func)(c, n);
1325 }
1326
1327 /*
1328  * Reverse the linked list of near-optimal matches so that they can be returned
1329  * in forwards order.
1330  *
1331  * Returns the first match in the list.
1332  */
1333 static struct lz_match
1334 lzx_match_chooser_reverse_list(struct lzx_compressor *c, unsigned cur_pos)
1335 {
1336         unsigned prev_link, saved_prev_link;
1337         unsigned prev_match_offset, saved_prev_match_offset;
1338
1339         c->optimum_end_idx = cur_pos;
1340
1341         saved_prev_link = c->optimum[cur_pos].prev.link;
1342         saved_prev_match_offset = c->optimum[cur_pos].prev.match_offset;
1343
1344         do {
1345                 prev_link = saved_prev_link;
1346                 prev_match_offset = saved_prev_match_offset;
1347
1348                 saved_prev_link = c->optimum[prev_link].prev.link;
1349                 saved_prev_match_offset = c->optimum[prev_link].prev.match_offset;
1350
1351                 c->optimum[prev_link].next.link = cur_pos;
1352                 c->optimum[prev_link].next.match_offset = prev_match_offset;
1353
1354                 cur_pos = prev_link;
1355         } while (cur_pos != 0);
1356
1357         c->optimum_cur_idx = c->optimum[0].next.link;
1358
1359         return (struct lz_match)
1360                 { .len = c->optimum_cur_idx,
1361                   .offset = c->optimum[0].next.match_offset,
1362                 };
1363 }
1364
1365 /*
1366  * lzx_choose_near_optimal_match() -
1367  *
1368  * Choose an approximately optimal match or literal to use at the next position
1369  * in the string, or "window", being LZ-encoded.
1370  *
1371  * This is based on algorithms used in 7-Zip, including the DEFLATE encoder
1372  * and the LZMA encoder, written by Igor Pavlov.
1373  *
1374  * Unlike a greedy parser that always takes the longest match, or even a "lazy"
1375  * parser with one match/literal look-ahead like zlib, the algorithm used here
1376  * may look ahead many matches/literals to determine the approximately optimal
1377  * match/literal to code next.  The motivation is that the compression ratio is
1378  * improved if the compressor can do things like use a shorter-than-possible
1379  * match in order to allow a longer match later, and also take into account the
1380  * estimated real cost of coding each match/literal based on the underlying
1381  * entropy encoding.
1382  *
1383  * Still, this is not a true optimal parser for several reasons:
1384  *
1385  * - Real compression formats use entropy encoding of the literal/match
1386  *   sequence, so the real cost of coding each match or literal is unknown until
1387  *   the parse is fully determined.  It can be approximated based on iterative
1388  *   parses, but the end result is not guaranteed to be globally optimal.
1389  *
1390  * - Very long matches are chosen immediately.  This is because locations with
1391  *   long matches are likely to have many possible alternatives that would cause
1392  *   slow optimal parsing, but also such locations are already highly
1393  *   compressible so it is not too harmful to just grab the longest match.
1394  *
1395  * - Not all possible matches at each location are considered because the
1396  *   underlying match-finder limits the number and type of matches produced at
1397  *   each position.  For example, for a given match length it's usually not
1398  *   worth it to only consider matches other than the lowest-offset match,
1399  *   except in the case of a repeat offset.
1400  *
1401  * - Although we take into account the adaptive state (in LZX, the recent offset
1402  *   queue), coding decisions made with respect to the adaptive state will be
1403  *   locally optimal but will not necessarily be globally optimal.  This is
1404  *   because the algorithm only keeps the least-costly path to get to a given
1405  *   location and does not take into account that a slightly more costly path
1406  *   could result in a different adaptive state that ultimately results in a
1407  *   lower global cost.
1408  *
1409  * - The array space used by this function is bounded, so in degenerate cases it
1410  *   is forced to start returning matches/literals before the algorithm has
1411  *   really finished.
1412  *
1413  * Each call to this function does one of two things:
1414  *
1415  * 1. Build a sequence of near-optimal matches/literals, up to some point, that
1416  *    will be returned by subsequent calls to this function, then return the
1417  *    first one.
1418  *
1419  * OR
1420  *
1421  * 2. Return the next match/literal previously computed by a call to this
1422  *    function.
1423  *
1424  * The return value is a (length, offset) pair specifying the match or literal
1425  * chosen.  For literals, the length is 0 or 1 and the offset is meaningless.
1426  */
1427 static struct lz_match
1428 lzx_choose_near_optimal_item(struct lzx_compressor *c)
1429 {
1430         unsigned num_matches;
1431         const struct lz_match *matches;
1432         struct lz_match match;
1433         u32 longest_len;
1434         u32 longest_rep_len;
1435         unsigned longest_rep_slot;
1436         unsigned cur_pos;
1437         unsigned end_pos;
1438         struct lzx_mc_pos_data *optimum = c->optimum;
1439
1440         if (c->optimum_cur_idx != c->optimum_end_idx) {
1441                 /* Case 2: Return the next match/literal already found.  */
1442                 match.len = optimum[c->optimum_cur_idx].next.link -
1443                                     c->optimum_cur_idx;
1444                 match.offset = optimum[c->optimum_cur_idx].next.match_offset;
1445
1446                 c->optimum_cur_idx = optimum[c->optimum_cur_idx].next.link;
1447                 return match;
1448         }
1449
1450         /* Case 1:  Compute a new list of matches/literals to return.  */
1451
1452         c->optimum_cur_idx = 0;
1453         c->optimum_end_idx = 0;
1454
1455         /* Search for matches at recent offsets.  Only keep the one with the
1456          * longest match length.  */
1457         longest_rep_len = LZX_MIN_MATCH_LEN - 1;
1458         if (c->match_window_pos >= 1) {
1459                 unsigned limit = min(LZX_MAX_MATCH_LEN,
1460                                      c->match_window_end - c->match_window_pos);
1461                 for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
1462                         u32 offset = c->queue.R[i];
1463                         const u8 *strptr = &c->cur_window[c->match_window_pos];
1464                         const u8 *matchptr = strptr - offset;
1465                         unsigned len = 0;
1466                         while (len < limit && strptr[len] == matchptr[len])
1467                                 len++;
1468                         if (len > longest_rep_len) {
1469                                 longest_rep_len = len;
1470                                 longest_rep_slot = i;
1471                         }
1472                 }
1473         }
1474
1475         /* If there's a long match with a recent offset, take it.  */
1476         if (longest_rep_len >= c->params.nice_match_length) {
1477                 lzx_skip_bytes(c, longest_rep_len);
1478                 return (struct lz_match) {
1479                         .len = longest_rep_len,
1480                         .offset = c->queue.R[longest_rep_slot],
1481                 };
1482         }
1483
1484         /* Search other matches.  */
1485         num_matches = lzx_get_matches(c, &matches);
1486
1487         /* If there's a long match, take it.  */
1488         if (num_matches) {
1489                 longest_len = matches[num_matches - 1].len;
1490                 if (longest_len >= c->params.nice_match_length) {
1491                         lzx_skip_bytes(c, longest_len - 1);
1492                         return matches[num_matches - 1];
1493                 }
1494         } else {
1495                 longest_len = 1;
1496         }
1497
1498         /* Calculate the cost to reach the next position by coding a literal.
1499          */
1500         optimum[1].queue = c->queue;
1501         optimum[1].cost = lzx_literal_cost(c->cur_window[c->match_window_pos - 1],
1502                                               &c->costs);
1503         optimum[1].prev.link = 0;
1504
1505         /* Calculate the cost to reach any position up to and including that
1506          * reached by the longest match.
1507          *
1508          * Note: We consider only the lowest-offset match that reaches each
1509          * position.
1510          *
1511          * Note: Some of the cost calculation stays the same for each offset,
1512          * regardless of how many lengths it gets used for.  Therefore, to
1513          * improve performance, we hand-code the cost calculation instead of
1514          * calling lzx_match_cost() to do a from-scratch cost evaluation at each
1515          * length.  */
1516         for (unsigned i = 0, len = 2; i < num_matches; i++) {
1517                 u32 offset;
1518                 struct lzx_lru_queue queue;
1519                 u32 position_cost;
1520                 unsigned position_slot;
1521                 unsigned num_extra_bits;
1522
1523                 offset = matches[i].offset;
1524                 queue = c->queue;
1525                 position_cost = 0;
1526
1527                 position_slot = lzx_get_position_slot(offset, &queue);
1528                 num_extra_bits = lzx_get_num_extra_bits(position_slot);
1529                 if (num_extra_bits >= 3) {
1530                         position_cost += num_extra_bits - 3;
1531                         position_cost += c->costs.aligned[(offset + LZX_OFFSET_OFFSET) & 7];
1532                 } else {
1533                         position_cost += num_extra_bits;
1534                 }
1535
1536                 do {
1537                         unsigned len_header;
1538                         unsigned main_symbol;
1539                         u32 cost;
1540
1541                         cost = position_cost;
1542
1543                         len_header = min(len - LZX_MIN_MATCH_LEN, LZX_NUM_PRIMARY_LENS);
1544                         main_symbol = ((position_slot << 3) | len_header) + LZX_NUM_CHARS;
1545                         cost += c->costs.main[main_symbol];
1546                         if (len_header == LZX_NUM_PRIMARY_LENS)
1547                                 cost += c->costs.len[len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1548
1549                         optimum[len].queue = queue;
1550                         optimum[len].prev.link = 0;
1551                         optimum[len].prev.match_offset = offset;
1552                         optimum[len].cost = cost;
1553                 } while (++len <= matches[i].len);
1554         }
1555         end_pos = longest_len;
1556
1557         if (longest_rep_len >= LZX_MIN_MATCH_LEN) {
1558                 u32 cost;
1559
1560                 while (end_pos < longest_rep_len)
1561                         optimum[++end_pos].cost = MC_INFINITE_COST;
1562
1563                 cost = lzx_repmatch_cost(longest_rep_len, longest_rep_slot,
1564                                          &c->costs);
1565                 if (cost <= optimum[longest_rep_len].cost) {
1566                         optimum[longest_rep_len].queue = c->queue;
1567                         swap(optimum[longest_rep_len].queue.R[0],
1568                              optimum[longest_rep_len].queue.R[longest_rep_slot]);
1569                         optimum[longest_rep_len].prev.link = 0;
1570                         optimum[longest_rep_len].prev.match_offset =
1571                                 optimum[longest_rep_len].queue.R[0];
1572                         optimum[longest_rep_len].cost = cost;
1573                 }
1574         }
1575
1576         /* Step forward, calculating the estimated minimum cost to reach each
1577          * position.  The algorithm may find multiple paths to reach each
1578          * position; only the lowest-cost path is saved.
1579          *
1580          * The progress of the parse is tracked in the @optimum array, which
1581          * for each position contains the minimum cost to reach that position,
1582          * the index of the start of the match/literal taken to reach that
1583          * position through the minimum-cost path, the offset of the match taken
1584          * (not relevant for literals), and the adaptive state that will exist
1585          * at that position after the minimum-cost path is taken.  The @cur_pos
1586          * variable stores the position at which the algorithm is currently
1587          * considering coding choices, and the @end_pos variable stores the
1588          * greatest position at which the costs of coding choices have been
1589          * saved.  (Actually, the algorithm guarantees that all positions up to
1590          * and including @end_pos are reachable by at least one path.)
1591          *
1592          * The loop terminates when any one of the following conditions occurs:
1593          *
1594          * 1. A match with length greater than or equal to @nice_match_length is
1595          *    found.  When this occurs, the algorithm chooses this match
1596          *    unconditionally, and consequently the near-optimal match/literal
1597          *    sequence up to and including that match is fully determined and it
1598          *    can begin returning the match/literal list.
1599          *
1600          * 2. @cur_pos reaches a position not overlapped by a preceding match.
1601          *    In such cases, the near-optimal match/literal sequence up to
1602          *    @cur_pos is fully determined and it can begin returning the
1603          *    match/literal list.
1604          *
1605          * 3. Failing either of the above in a degenerate case, the loop
1606          *    terminates when space in the @optimum array is exhausted.
1607          *    This terminates the algorithm and forces it to start returning
1608          *    matches/literals even though they may not be globally optimal.
1609          *
1610          * Upon loop termination, a nonempty list of matches/literals will have
1611          * been produced and stored in the @optimum array.  These
1612          * matches/literals are linked in reverse order, so the last thing this
1613          * function does is reverse this list and return the first
1614          * match/literal, leaving the rest to be returned immediately by
1615          * subsequent calls to this function.
1616          */
1617         cur_pos = 0;
1618         for (;;) {
1619                 u32 cost;
1620
1621                 /* Advance to next position.  */
1622                 cur_pos++;
1623
1624                 /* Check termination conditions (2) and (3) noted above.  */
1625                 if (cur_pos == end_pos || cur_pos == LZX_OPTIM_ARRAY_LENGTH)
1626                         return lzx_match_chooser_reverse_list(c, cur_pos);
1627
1628                 /* Search for matches at recent offsets.  */
1629                 longest_rep_len = LZX_MIN_MATCH_LEN - 1;
1630                 unsigned limit = min(LZX_MAX_MATCH_LEN,
1631                                      c->match_window_end - c->match_window_pos);
1632                 for (int i = 0; i < LZX_NUM_RECENT_OFFSETS; i++) {
1633                         u32 offset = optimum[cur_pos].queue.R[i];
1634                         const u8 *strptr = &c->cur_window[c->match_window_pos];
1635                         const u8 *matchptr = strptr - offset;
1636                         unsigned len = 0;
1637                         while (len < limit && strptr[len] == matchptr[len])
1638                                 len++;
1639                         if (len > longest_rep_len) {
1640                                 longest_rep_len = len;
1641                                 longest_rep_slot = i;
1642                         }
1643                 }
1644
1645                 /* If we found a long match at a recent offset, choose it
1646                  * immediately.  */
1647                 if (longest_rep_len >= c->params.nice_match_length) {
1648                         /* Build the list of matches to return and get
1649                          * the first one.  */
1650                         match = lzx_match_chooser_reverse_list(c, cur_pos);
1651
1652                         /* Append the long match to the end of the list.  */
1653                         optimum[cur_pos].next.match_offset =
1654                                 optimum[cur_pos].queue.R[longest_rep_slot];
1655                         optimum[cur_pos].next.link = cur_pos + longest_rep_len;
1656                         c->optimum_end_idx = cur_pos + longest_rep_len;
1657
1658                         /* Skip over the remaining bytes of the long match.  */
1659                         lzx_skip_bytes(c, longest_rep_len);
1660
1661                         /* Return first match in the list.  */
1662                         return match;
1663                 }
1664
1665                 /* Search other matches.  */
1666                 num_matches = lzx_get_matches(c, &matches);
1667
1668                 /* If there's a long match, take it.  */
1669                 if (num_matches) {
1670                         longest_len = matches[num_matches - 1].len;
1671                         if (longest_len >= c->params.nice_match_length) {
1672                                 /* Build the list of matches to return and get
1673                                  * the first one.  */
1674                                 match = lzx_match_chooser_reverse_list(c, cur_pos);
1675
1676                                 /* Append the long match to the end of the list.  */
1677                                 optimum[cur_pos].next.match_offset =
1678                                         matches[num_matches - 1].offset;
1679                                 optimum[cur_pos].next.link = cur_pos + longest_len;
1680                                 c->optimum_end_idx = cur_pos + longest_len;
1681
1682                                 /* Skip over the remaining bytes of the long match.  */
1683                                 lzx_skip_bytes(c, longest_len - 1);
1684
1685                                 /* Return first match in the list.  */
1686                                 return match;
1687                         }
1688                 } else {
1689                         longest_len = 1;
1690                 }
1691
1692                 while (end_pos < cur_pos + longest_len)
1693                         optimum[++end_pos].cost = MC_INFINITE_COST;
1694
1695                 /* Consider coding a literal.  */
1696                 cost = optimum[cur_pos].cost +
1697                         lzx_literal_cost(c->cur_window[c->match_window_pos - 1],
1698                                          &c->costs);
1699                 if (cost < optimum[cur_pos + 1].cost) {
1700                         optimum[cur_pos + 1].queue = optimum[cur_pos].queue;
1701                         optimum[cur_pos + 1].cost = cost;
1702                         optimum[cur_pos + 1].prev.link = cur_pos;
1703                 }
1704
1705                 /* Consider coding a match.
1706                  *
1707                  * The hard-coded cost calculation is done for the same reason
1708                  * stated in the comment for the similar loop earlier.
1709                  * Actually, it is *this* one that has the biggest effect on
1710                  * performance; overall LZX compression is > 10% faster with
1711                  * this code compared to calling lzx_match_cost() with each
1712                  * length.  */
1713                 for (unsigned i = 0, len = 2; i < num_matches; i++) {
1714                         u32 offset;
1715                         u32 position_cost;
1716                         unsigned position_slot;
1717                         unsigned num_extra_bits;
1718
1719                         offset = matches[i].offset;
1720                         position_cost = optimum[cur_pos].cost;
1721
1722                         for (position_slot = 0; position_slot < LZX_NUM_RECENT_OFFSETS; position_slot++)
1723                                 if (offset == optimum[cur_pos].queue.R[position_slot])
1724                                         goto have_position_cost;
1725
1726                         position_slot = lzx_get_position_slot_raw(offset + LZX_OFFSET_OFFSET);
1727
1728                         num_extra_bits = lzx_get_num_extra_bits(position_slot);
1729                         if (num_extra_bits >= 3) {
1730                                 position_cost += num_extra_bits - 3;
1731                                 position_cost += c->costs.aligned[
1732                                                 (offset + LZX_OFFSET_OFFSET) & 7];
1733                         } else {
1734                                 position_cost += num_extra_bits;
1735                         }
1736
1737                 have_position_cost:
1738
1739                         do {
1740                                 unsigned len_header;
1741                                 unsigned main_symbol;
1742                                 u32 cost;
1743
1744                                 cost = position_cost;
1745
1746                                 len_header = min(len - LZX_MIN_MATCH_LEN,
1747                                                  LZX_NUM_PRIMARY_LENS);
1748                                 main_symbol = ((position_slot << 3) | len_header) +
1749                                                 LZX_NUM_CHARS;
1750                                 cost += c->costs.main[main_symbol];
1751                                 if (len_header == LZX_NUM_PRIMARY_LENS) {
1752                                         cost += c->costs.len[len -
1753                                                         LZX_MIN_MATCH_LEN -
1754                                                         LZX_NUM_PRIMARY_LENS];
1755                                 }
1756                                 if (cost < optimum[cur_pos + len].cost) {
1757
1758                                         if (position_slot < LZX_NUM_RECENT_OFFSETS) {
1759                                                 optimum[cur_pos + len].queue = optimum[cur_pos].queue;
1760                                                 swap(optimum[cur_pos + len].queue.R[0],
1761                                                      optimum[cur_pos + len].queue.R[position_slot]);
1762                                         } else {
1763                                                 optimum[cur_pos + len].queue.R[0] = offset;
1764                                                 optimum[cur_pos + len].queue.R[1] = optimum[cur_pos].queue.R[0];
1765                                                 optimum[cur_pos + len].queue.R[2] = optimum[cur_pos].queue.R[1];
1766                                         }
1767                                         optimum[cur_pos + len].prev.link = cur_pos;
1768                                         optimum[cur_pos + len].prev.match_offset = offset;
1769                                         optimum[cur_pos + len].cost = cost;
1770                                 }
1771                         } while (++len <= matches[i].len);
1772                 }
1773
1774                 if (longest_rep_len >= LZX_MIN_MATCH_LEN) {
1775
1776                         while (end_pos < cur_pos + longest_rep_len)
1777                                 optimum[++end_pos].cost = MC_INFINITE_COST;
1778
1779                         cost = optimum[cur_pos].cost +
1780                                 lzx_repmatch_cost(longest_rep_len, longest_rep_slot,
1781                                                   &c->costs);
1782                         if (cost <= optimum[cur_pos + longest_rep_len].cost) {
1783                                 optimum[cur_pos + longest_rep_len].queue =
1784                                         optimum[cur_pos].queue;
1785                                 swap(optimum[cur_pos + longest_rep_len].queue.R[0],
1786                                      optimum[cur_pos + longest_rep_len].queue.R[longest_rep_slot]);
1787                                 optimum[cur_pos + longest_rep_len].prev.link =
1788                                         cur_pos;
1789                                 optimum[cur_pos + longest_rep_len].prev.match_offset =
1790                                         optimum[cur_pos + longest_rep_len].queue.R[0];
1791                                 optimum[cur_pos + longest_rep_len].cost =
1792                                         cost;
1793                         }
1794                 }
1795         }
1796 }
1797
1798 static struct lz_match
1799 lzx_choose_lazy_item(struct lzx_compressor *c)
1800 {
1801         const struct lz_match *matches;
1802         struct lz_match cur_match;
1803         struct lz_match next_match;
1804         u32 num_matches;
1805
1806         if (c->prev_match.len) {
1807                 cur_match = c->prev_match;
1808                 c->prev_match.len = 0;
1809         } else {
1810                 num_matches = lzx_get_matches(c, &matches);
1811                 if (num_matches == 0 ||
1812                     (matches[num_matches - 1].len <= 3 &&
1813                      (matches[num_matches - 1].len <= 2 ||
1814                       matches[num_matches - 1].offset > 4096)))
1815                 {
1816                         return (struct lz_match) { };
1817                 }
1818
1819                 cur_match = matches[num_matches - 1];
1820         }
1821
1822         if (cur_match.len >= c->params.nice_match_length) {
1823                 lzx_skip_bytes(c, cur_match.len - 1);
1824                 return cur_match;
1825         }
1826
1827         num_matches = lzx_get_matches(c, &matches);
1828         if (num_matches == 0 ||
1829             (matches[num_matches - 1].len <= 3 &&
1830              (matches[num_matches - 1].len <= 2 ||
1831               matches[num_matches - 1].offset > 4096)))
1832         {
1833                 lzx_skip_bytes(c, cur_match.len - 2);
1834                 return cur_match;
1835         }
1836
1837         next_match = matches[num_matches - 1];
1838
1839         if (next_match.len <= cur_match.len) {
1840                 lzx_skip_bytes(c, cur_match.len - 2);
1841                 return cur_match;
1842         } else {
1843                 c->prev_match = next_match;
1844                 return (struct lz_match) { };
1845         }
1846 }
1847
1848 /*
1849  * Return the next match or literal to use, delegating to the currently selected
1850  * match-choosing algorithm.
1851  *
1852  * If the length of the returned 'struct lz_match' is less than
1853  * LZX_MIN_MATCH_LEN, then it is really a literal.
1854  */
1855 static inline struct lz_match
1856 lzx_choose_item(struct lzx_compressor *c)
1857 {
1858         return (*c->params.choose_item_func)(c);
1859 }
1860
1861 /* Set default symbol costs for the LZX Huffman codes.  */
1862 static void
1863 lzx_set_default_costs(struct lzx_costs * costs, unsigned num_main_syms)
1864 {
1865         unsigned i;
1866
1867         /* Main code (part 1): Literal symbols  */
1868         for (i = 0; i < LZX_NUM_CHARS; i++)
1869                 costs->main[i] = 8;
1870
1871         /* Main code (part 2): Match header symbols  */
1872         for (; i < num_main_syms; i++)
1873                 costs->main[i] = 10;
1874
1875         /* Length code  */
1876         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1877                 costs->len[i] = 8;
1878
1879         /* Aligned offset code  */
1880         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1881                 costs->aligned[i] = 3;
1882 }
1883
1884 /* Given the frequencies of symbols in an LZX-compressed block and the
1885  * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1886  * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1887  * will take fewer bits to output.  */
1888 static int
1889 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1890                                const struct lzx_codes * codes)
1891 {
1892         unsigned aligned_cost = 0;
1893         unsigned verbatim_cost = 0;
1894
1895         /* Verbatim blocks have a constant 3 bits per position footer.  Aligned
1896          * offset blocks have an aligned offset symbol per position footer, plus
1897          * an extra 24 bits per block to output the lengths necessary to
1898          * reconstruct the aligned offset code itself.  */
1899         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1900                 verbatim_cost += 3 * freqs->aligned[i];
1901                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1902         }
1903         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1904         if (aligned_cost < verbatim_cost)
1905                 return LZX_BLOCKTYPE_ALIGNED;
1906         else
1907                 return LZX_BLOCKTYPE_VERBATIM;
1908 }
1909
1910 /* Find a sequence of matches/literals with which to output the specified LZX
1911  * block, then set the block's type to that which has the minimum cost to output
1912  * (either verbatim or aligned).  */
1913 static void
1914 lzx_choose_items_for_block(struct lzx_compressor *c, struct lzx_block_spec *spec)
1915 {
1916         const struct lzx_lru_queue orig_queue = c->queue;
1917         u32 num_passes_remaining = c->params.num_optim_passes;
1918         struct lzx_freqs freqs;
1919         const u8 *window_ptr;
1920         const u8 *window_end;
1921         struct lzx_item *next_chosen_item;
1922         struct lz_match lz_match;
1923         struct lzx_item lzx_item;
1924
1925         LZX_ASSERT(num_passes >= 1);
1926         LZX_ASSERT(lz_mf_get_position(c->mf) == spec->window_pos);
1927
1928         c->match_window_end = spec->window_pos + spec->block_size;
1929
1930         if (c->params.num_optim_passes > 1) {
1931                 if (spec->block_size == c->cur_window_size)
1932                         c->get_matches_func = lzx_get_matches_fillcache_singleblock;
1933                 else
1934                         c->get_matches_func = lzx_get_matches_fillcache_multiblock;
1935                 c->skip_bytes_func = lzx_skip_bytes_fillcache;
1936         } else {
1937                 if (spec->block_size == c->cur_window_size)
1938                         c->get_matches_func = lzx_get_matches_nocache_singleblock;
1939                 else
1940                         c->get_matches_func = lzx_get_matches_nocache_multiblock;
1941                 c->skip_bytes_func = lzx_skip_bytes_nocache;
1942         }
1943
1944         /* The first optimal parsing pass is done using the cost model already
1945          * set in c->costs.  Each later pass is done using a cost model
1946          * computed from the previous pass.
1947          *
1948          * To improve performance we only generate the array containing the
1949          * matches and literals in intermediate form on the final pass.  */
1950
1951         while (--num_passes_remaining) {
1952                 c->match_window_pos = spec->window_pos;
1953                 c->cache_ptr = c->cached_matches;
1954                 memset(&freqs, 0, sizeof(freqs));
1955                 window_ptr = &c->cur_window[spec->window_pos];
1956                 window_end = window_ptr + spec->block_size;
1957
1958                 while (window_ptr != window_end) {
1959
1960                         lz_match = lzx_choose_item(c);
1961
1962                         LZX_ASSERT(!(lz_match.len == LZX_MIN_MATCH_LEN &&
1963                                      lz_match.offset == c->max_window_size -
1964                                                          LZX_MIN_MATCH_LEN));
1965                         if (lz_match.len >= LZX_MIN_MATCH_LEN) {
1966                                 lzx_tally_match(lz_match.len, lz_match.offset,
1967                                                 &freqs, &c->queue);
1968                                 window_ptr += lz_match.len;
1969                         } else {
1970                                 lzx_tally_literal(*window_ptr, &freqs);
1971                                 window_ptr += 1;
1972                         }
1973                 }
1974                 lzx_make_huffman_codes(&freqs, &spec->codes, c->num_main_syms);
1975                 lzx_set_costs(c, &spec->codes.lens, 15);
1976                 c->queue = orig_queue;
1977                 if (c->cache_ptr <= c->cache_limit) {
1978                         c->get_matches_func = lzx_get_matches_usecache_nocheck;
1979                         c->skip_bytes_func = lzx_skip_bytes_usecache_nocheck;
1980                 } else {
1981                         c->get_matches_func = lzx_get_matches_usecache;
1982                         c->skip_bytes_func = lzx_skip_bytes_usecache;
1983                 }
1984         }
1985
1986         c->match_window_pos = spec->window_pos;
1987         c->cache_ptr = c->cached_matches;
1988         memset(&freqs, 0, sizeof(freqs));
1989         window_ptr = &c->cur_window[spec->window_pos];
1990         window_end = window_ptr + spec->block_size;
1991
1992         spec->chosen_items = &c->chosen_items[spec->window_pos];
1993         next_chosen_item = spec->chosen_items;
1994
1995         unsigned unseen_cost = 9;
1996         while (window_ptr != window_end) {
1997
1998                 lz_match = lzx_choose_item(c);
1999
2000                 LZX_ASSERT(!(lz_match.len == LZX_MIN_MATCH_LEN &&
2001                              lz_match.offset == c->max_window_size -
2002                                                  LZX_MIN_MATCH_LEN));
2003                 if (lz_match.len >= LZX_MIN_MATCH_LEN) {
2004                         lzx_item.data = lzx_tally_match(lz_match.len,
2005                                                          lz_match.offset,
2006                                                          &freqs, &c->queue);
2007                         window_ptr += lz_match.len;
2008                 } else {
2009                         lzx_item.data = lzx_tally_literal(*window_ptr, &freqs);
2010                         window_ptr += 1;
2011                 }
2012                 *next_chosen_item++ = lzx_item;
2013
2014                 /* When doing one-pass "near-optimal" parsing, update the cost
2015                  * model occassionally.  */
2016                 if (unlikely((next_chosen_item - spec->chosen_items) % 2048 == 0) &&
2017                     c->params.choose_item_func == lzx_choose_near_optimal_item &&
2018                     c->params.num_optim_passes == 1)
2019                 {
2020                         lzx_make_huffman_codes(&freqs, &spec->codes, c->num_main_syms);
2021                         lzx_set_costs(c, &spec->codes.lens, unseen_cost);
2022                         if (unseen_cost < 15)
2023                                 unseen_cost++;
2024                 }
2025         }
2026         spec->num_chosen_items = next_chosen_item - spec->chosen_items;
2027         lzx_make_huffman_codes(&freqs, &spec->codes, c->num_main_syms);
2028         spec->block_type = lzx_choose_verbatim_or_aligned(&freqs, &spec->codes);
2029 }
2030
2031 /* Prepare the input window into one or more LZX blocks ready to be output.  */
2032 static void
2033 lzx_prepare_blocks(struct lzx_compressor *c)
2034 {
2035         /* Set up a default cost model.  */
2036         if (c->params.choose_item_func == lzx_choose_near_optimal_item)
2037                 lzx_set_default_costs(&c->costs, c->num_main_syms);
2038
2039         /* Set up the block specifications.
2040          * TODO: The compression ratio could be slightly improved by performing
2041          * data-dependent block splitting instead of using fixed-size blocks.
2042          * Doing so well is a computationally hard problem, however.  */
2043         c->num_blocks = DIV_ROUND_UP(c->cur_window_size, LZX_DIV_BLOCK_SIZE);
2044         for (unsigned i = 0; i < c->num_blocks; i++) {
2045                 u32 pos = LZX_DIV_BLOCK_SIZE * i;
2046                 c->block_specs[i].window_pos = pos;
2047                 c->block_specs[i].block_size = min(c->cur_window_size - pos,
2048                                                    LZX_DIV_BLOCK_SIZE);
2049         }
2050
2051         /* Load the window into the match-finder.  */
2052         lz_mf_load_window(c->mf, c->cur_window, c->cur_window_size);
2053
2054         /* Determine sequence of matches/literals to output for each block.  */
2055         lzx_lru_queue_init(&c->queue);
2056         c->optimum_cur_idx = 0;
2057         c->optimum_end_idx = 0;
2058         c->prev_match.len = 0;
2059         for (unsigned i = 0; i < c->num_blocks; i++)
2060                 lzx_choose_items_for_block(c, &c->block_specs[i]);
2061 }
2062
2063 static void
2064 lzx_build_params(unsigned int compression_level,
2065                  u32 max_window_size,
2066                  struct lzx_compressor_params *lzx_params)
2067 {
2068         if (compression_level < 25) {
2069                 lzx_params->choose_item_func = lzx_choose_lazy_item;
2070                 lzx_params->num_optim_passes  = 1;
2071                 if (max_window_size <= 262144)
2072                         lzx_params->mf_algo = LZ_MF_HASH_CHAINS;
2073                 else
2074                         lzx_params->mf_algo = LZ_MF_BINARY_TREES;
2075                 lzx_params->min_match_length  = 3;
2076                 lzx_params->nice_match_length = 25 + compression_level * 2;
2077                 lzx_params->max_search_depth  = 25 + compression_level;
2078         } else {
2079                 lzx_params->choose_item_func = lzx_choose_near_optimal_item;
2080                 lzx_params->num_optim_passes  = compression_level / 20;
2081                 if (max_window_size <= 32768 && lzx_params->num_optim_passes == 1)
2082                         lzx_params->mf_algo = LZ_MF_HASH_CHAINS;
2083                 else
2084                         lzx_params->mf_algo = LZ_MF_BINARY_TREES;
2085                 lzx_params->min_match_length  = (compression_level >= 45) ? 2 : 3;
2086                 lzx_params->nice_match_length = min(((u64)compression_level * 32) / 50,
2087                                                     LZX_MAX_MATCH_LEN);
2088                 lzx_params->max_search_depth  = min(((u64)compression_level * 50) / 50,
2089                                                     LZX_MAX_MATCH_LEN);
2090         }
2091 }
2092
2093 static void
2094 lzx_build_mf_params(const struct lzx_compressor_params *lzx_params,
2095                     u32 max_window_size, struct lz_mf_params *mf_params)
2096 {
2097         memset(mf_params, 0, sizeof(*mf_params));
2098
2099         mf_params->algorithm = lzx_params->mf_algo;
2100         mf_params->max_window_size = max_window_size;
2101         mf_params->min_match_len = lzx_params->min_match_length;
2102         mf_params->max_match_len = LZX_MAX_MATCH_LEN;
2103         mf_params->max_search_depth = lzx_params->max_search_depth;
2104         mf_params->nice_match_len = lzx_params->nice_match_length;
2105 }
2106
2107 static void
2108 lzx_free_compressor(void *_c);
2109
2110 static u64
2111 lzx_get_needed_memory(size_t max_window_size, unsigned int compression_level)
2112 {
2113         struct lzx_compressor_params params;
2114         u64 size = 0;
2115
2116         if (!lzx_window_size_valid(max_window_size))
2117                 return 0;
2118
2119         lzx_build_params(compression_level, max_window_size, &params);
2120
2121         size += sizeof(struct lzx_compressor);
2122
2123         size += max_window_size;
2124
2125         size += DIV_ROUND_UP(max_window_size, LZX_DIV_BLOCK_SIZE) *
2126                 sizeof(struct lzx_block_spec);
2127
2128         size += max_window_size * sizeof(struct lzx_item);
2129
2130         size += lz_mf_get_needed_memory(params.mf_algo, max_window_size);
2131         if (params.choose_item_func == lzx_choose_near_optimal_item) {
2132                 size += (LZX_OPTIM_ARRAY_LENGTH + params.nice_match_length) *
2133                         sizeof(struct lzx_mc_pos_data);
2134         }
2135         if (params.num_optim_passes > 1)
2136                 size += LZX_CACHE_LEN * sizeof(struct lz_match);
2137         else
2138                 size += LZX_MAX_MATCHES_PER_POS * sizeof(struct lz_match);
2139         return size;
2140 }
2141
2142 static int
2143 lzx_create_compressor(size_t max_window_size, unsigned int compression_level,
2144                       void **c_ret)
2145 {
2146         struct lzx_compressor *c;
2147         struct lzx_compressor_params params;
2148         struct lz_mf_params mf_params;
2149
2150         if (!lzx_window_size_valid(max_window_size))
2151                 return WIMLIB_ERR_INVALID_PARAM;
2152
2153         lzx_build_params(compression_level, max_window_size, &params);
2154         lzx_build_mf_params(&params, max_window_size, &mf_params);
2155         if (!lz_mf_params_valid(&mf_params))
2156                 return WIMLIB_ERR_INVALID_PARAM;
2157
2158         c = CALLOC(1, sizeof(struct lzx_compressor));
2159         if (!c)
2160                 goto oom;
2161
2162         c->params = params;
2163         c->num_main_syms = lzx_get_num_main_syms(max_window_size);
2164         c->max_window_size = max_window_size;
2165
2166         c->cur_window = ALIGNED_MALLOC(max_window_size, 16);
2167         if (!c->cur_window)
2168                 goto oom;
2169
2170         c->block_specs = MALLOC(DIV_ROUND_UP(max_window_size,
2171                                              LZX_DIV_BLOCK_SIZE) *
2172                                 sizeof(struct lzx_block_spec));
2173         if (!c->block_specs)
2174                 goto oom;
2175
2176         c->chosen_items = MALLOC(max_window_size * sizeof(struct lzx_item));
2177         if (!c->chosen_items)
2178                 goto oom;
2179
2180         c->mf = lz_mf_alloc(&mf_params);
2181         if (!c->mf)
2182                 goto oom;
2183
2184         if (params.choose_item_func == lzx_choose_near_optimal_item) {
2185                 c->optimum = MALLOC((LZX_OPTIM_ARRAY_LENGTH +
2186                                      params.nice_match_length) *
2187                                     sizeof(struct lzx_mc_pos_data));
2188                 if (!c->optimum)
2189                         goto oom;
2190         }
2191
2192         if (params.num_optim_passes > 1) {
2193                 c->cached_matches = MALLOC(LZX_CACHE_LEN *
2194                                            sizeof(struct lz_match));
2195                 if (!c->cached_matches)
2196                         goto oom;
2197                 c->cache_limit = c->cached_matches + LZX_CACHE_LEN -
2198                                  (LZX_MAX_MATCHES_PER_POS + 1);
2199         } else {
2200                 c->cached_matches = MALLOC(LZX_MAX_MATCHES_PER_POS *
2201                                            sizeof(struct lz_match));
2202                 if (!c->cached_matches)
2203                         goto oom;
2204         }
2205
2206         *c_ret = c;
2207         return 0;
2208
2209 oom:
2210         lzx_free_compressor(c);
2211         return WIMLIB_ERR_NOMEM;
2212 }
2213
2214 static size_t
2215 lzx_compress(const void *uncompressed_data, size_t uncompressed_size,
2216              void *compressed_data, size_t compressed_size_avail, void *_c)
2217 {
2218         struct lzx_compressor *c = _c;
2219         struct output_bitstream ostream;
2220         size_t compressed_size;
2221
2222         if (uncompressed_size < 100) {
2223                 LZX_DEBUG("Too small to bother compressing.");
2224                 return 0;
2225         }
2226
2227         LZX_DEBUG("Attempting to compress %zu bytes...",
2228                   uncompressed_size);
2229
2230         /* The input data must be preprocessed.  To avoid changing the original
2231          * input, copy it to a temporary buffer.  */
2232         memcpy(c->cur_window, uncompressed_data, uncompressed_size);
2233         c->cur_window_size = uncompressed_size;
2234
2235         /* Before doing any actual compression, do the call instruction (0xe8
2236          * byte) translation on the uncompressed data.  */
2237         lzx_do_e8_preprocessing(c->cur_window, c->cur_window_size);
2238
2239         /* Prepare the compressed data.  */
2240         lzx_prepare_blocks(c);
2241
2242         /* Generate the compressed data.  */
2243         init_output_bitstream(&ostream, compressed_data, compressed_size_avail);
2244         lzx_write_all_blocks(c, &ostream);
2245
2246         compressed_size = flush_output_bitstream(&ostream);
2247         if (compressed_size == (u32)~0UL) {
2248                 LZX_DEBUG("Data did not compress to %zu bytes or less!",
2249                           compressed_size_avail);
2250                 return 0;
2251         }
2252
2253         LZX_DEBUG("Done: compressed %zu => %zu bytes.",
2254                   uncompressed_size, compressed_size);
2255
2256         return compressed_size;
2257 }
2258
2259 static void
2260 lzx_free_compressor(void *_c)
2261 {
2262         struct lzx_compressor *c = _c;
2263
2264         if (c) {
2265                 ALIGNED_FREE(c->cur_window);
2266                 FREE(c->block_specs);
2267                 FREE(c->chosen_items);
2268                 lz_mf_free(c->mf);
2269                 FREE(c->optimum);
2270                 FREE(c->cached_matches);
2271                 FREE(c);
2272         }
2273 }
2274
2275 const struct compressor_ops lzx_compressor_ops = {
2276         .get_needed_memory  = lzx_get_needed_memory,
2277         .create_compressor  = lzx_create_compressor,
2278         .compress           = lzx_compress,
2279         .free_compressor    = lzx_free_compressor,
2280 };