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