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