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