]> wimlib.net Git - wimlib/blob - src/lzx-compress.c
lzx-compress.c: Fix for lazy parsing and multiple blocks
[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.
30  *
31  * Two different parsing algorithms are implemented: "near-optimal" and "lazy".
32  * "Near-optimal" is significantly slower than "lazy", but results in a better
33  * compression ratio.  The "near-optimal" algorithm is used at the default
34  * compression level.
35  *
36  * This file may need some slight modifications to be used outside of the WIM
37  * format.  In particular, in other situations the LZX block header might be
38  * slightly different, and a sliding window rather than a fixed-size window
39  * might be required.
40  *
41  * Note: LZX is a compression format derived from DEFLATE, the format used by
42  * zlib and gzip.  Both LZX and DEFLATE use LZ77 matching and Huffman coding.
43  * Certain details are quite similar, such as the method for storing Huffman
44  * codes.  However, the main differences are:
45  *
46  * - LZX preprocesses the data to attempt to make x86 machine code slightly more
47  *   compressible before attempting to compress it further.
48  *
49  * - LZX uses a "main" alphabet which combines literals and matches, with the
50  *   match symbols containing a "length header" (giving all or part of the match
51  *   length) and an "offset slot" (giving, roughly speaking, the order of
52  *   magnitude of the match offset).
53  *
54  * - LZX does not have static Huffman blocks (that is, the kind with preset
55  *   Huffman codes); however it does have two types of dynamic Huffman blocks
56  *   ("verbatim" and "aligned").
57  *
58  * - LZX has a minimum match length of 2 rather than 3.  Length 2 matches can be
59  *   useful, but generally only if the parser is smart about choosing them.
60  *
61  * - In LZX, offset slots 0 through 2 actually represent entries in an LRU queue
62  *   of match offsets.  This is very useful for certain types of files, such as
63  *   binary files that have repeating records.
64  */
65
66 #ifdef HAVE_CONFIG_H
67 #  include "config.h"
68 #endif
69
70 #include "wimlib/compress_common.h"
71 #include "wimlib/compressor_ops.h"
72 #include "wimlib/endianness.h"
73 #include "wimlib/error.h"
74 #include "wimlib/lz_mf.h"
75 #include "wimlib/lz_repsearch.h"
76 #include "wimlib/lzx.h"
77 #include "wimlib/util.h"
78
79 #include <string.h>
80 #include <limits.h>
81
82 #define LZX_OPTIM_ARRAY_LENGTH  4096
83
84 #define LZX_DIV_BLOCK_SIZE      32768
85
86 #define LZX_CACHE_PER_POS       8
87
88 #define LZX_MAX_MATCHES_PER_POS (LZX_MAX_MATCH_LEN - LZX_MIN_MATCH_LEN + 1)
89
90 #define LZX_CACHE_LEN (LZX_DIV_BLOCK_SIZE * (LZX_CACHE_PER_POS + 1))
91
92 struct lzx_compressor;
93
94 /* Codewords for the LZX Huffman codes.  */
95 struct lzx_codewords {
96         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
97         u32 len[LZX_LENCODE_NUM_SYMBOLS];
98         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
99 };
100
101 /* Codeword lengths (in bits) for the LZX Huffman codes.
102  * A zero length means the corresponding codeword has zero frequency.  */
103 struct lzx_lens {
104         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
105         u8 len[LZX_LENCODE_NUM_SYMBOLS];
106         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
107 };
108
109 /* Estimated cost, in bits, to output each symbol in the LZX Huffman codes.  */
110 struct lzx_costs {
111         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
112         u8 len[LZX_LENCODE_NUM_SYMBOLS];
113         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
114 };
115
116 /* Codewords and lengths for the LZX Huffman codes.  */
117 struct lzx_codes {
118         struct lzx_codewords codewords;
119         struct lzx_lens lens;
120 };
121
122 /* Symbol frequency counters for the LZX Huffman codes.  */
123 struct lzx_freqs {
124         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
125         u32 len[LZX_LENCODE_NUM_SYMBOLS];
126         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
127 };
128
129 /* Intermediate LZX match/literal format  */
130 struct lzx_item {
131
132         /* Bits 0  -  9: Main symbol
133          * Bits 10 - 17: Length symbol
134          * Bits 18 - 22: Number of extra offset bits
135          * Bits 23+    : Extra offset bits  */
136         u64 data;
137 };
138
139 /* Internal compression parameters  */
140 struct lzx_compressor_params {
141         u32 (*choose_items_for_block)(struct lzx_compressor *, u32, u32);
142         u32 num_optim_passes;
143         enum lz_mf_algo mf_algo;
144         u32 min_match_length;
145         u32 nice_match_length;
146         u32 max_search_depth;
147 };
148
149 /*
150  * Match chooser position data:
151  *
152  * An array of these structures is used during the near-optimal match-choosing
153  * algorithm.  They correspond to consecutive positions in the window and are
154  * used to keep track of the cost to reach each position, and the match/literal
155  * choices that need to be chosen to reach that position.
156  */
157 struct lzx_mc_pos_data {
158
159         /* The cost, in bits, of the lowest-cost path that has been found to
160          * reach this position.  This can change as progressively lower cost
161          * paths are found to reach this position.  */
162         u32 cost;
163 #define MC_INFINITE_COST UINT32_MAX
164
165         /* The match or literal that was taken to reach this position.  This can
166          * change as progressively lower cost paths are found to reach this
167          * position.
168          *
169          * This variable is divided into two bitfields.
170          *
171          * Literals:
172          *      Low bits are 1, high bits are the literal.
173          *
174          * Explicit offset matches:
175          *      Low bits are the match length, high bits are the offset plus 2.
176          *
177          * Repeat offset matches:
178          *      Low bits are the match length, high bits are the queue index.
179          */
180         u32 mc_item_data;
181 #define MC_OFFSET_SHIFT 9
182 #define MC_LEN_MASK ((1 << MC_OFFSET_SHIFT) - 1)
183
184         /* The state of the LZX recent match offsets queue at this position.
185          * This is filled in lazily, only after the minimum-cost path to this
186          * position is found.
187          *
188          * Note: the way we handle this adaptive state in the "minimum-cost"
189          * parse is actually only an approximation.  It's possible for the
190          * globally optimal, minimum cost path to contain a prefix, ending at a
191          * position, where that path prefix is *not* the minimum cost path to
192          * that position.  This can happen if such a path prefix results in a
193          * different adaptive state which results in lower costs later.  We do
194          * not solve this problem; we only consider the lowest cost to reach
195          * each position, which seems to be an acceptable approximation.  */
196         struct lzx_lru_queue queue _aligned_attribute(16);
197
198 } _aligned_attribute(16);
199
200 /* State of the LZX compressor  */
201 struct lzx_compressor {
202
203         /* Internal compression parameters  */
204         struct lzx_compressor_params params;
205
206         /* The preprocessed buffer of data being compressed  */
207         u8 *cur_window;
208
209         /* Number of bytes of data to be compressed, which is the number of
210          * bytes of data in @cur_window that are actually valid.  */
211         u32 cur_window_size;
212
213         /* log2 order of the LZX window size for LZ match offset encoding
214          * purposes.  Will be >= LZX_MIN_WINDOW_ORDER and <=
215          * LZX_MAX_WINDOW_ORDER.
216          *
217          * Note: 1 << @window_order is normally equal to @max_window_size,
218          * a.k.a. the allocated size of @cur_window, but it will be greater than
219          * @max_window_size in the event that the compressor was created with a
220          * non-power-of-2 block size.  (See lzx_get_window_order().)  */
221         unsigned window_order;
222
223         /* Number of symbols in the main alphabet.  This depends on
224          * @window_order, since @window_order determines the maximum possible
225          * offset.  It does not, however, depend on the *actual* size of the
226          * current data buffer being processed, which might be less than 1 <<
227          * @window_order.  */
228         unsigned num_main_syms;
229
230         /* Lempel-Ziv match-finder  */
231         struct lz_mf *mf;
232
233         /* Match-finder wrapper functions and data for near-optimal parsing.
234          *
235          * When doing more than one match-choosing pass over the data, matches
236          * found by the match-finder are cached to achieve a slight speedup when
237          * the same matches are needed on subsequent passes.  This is suboptimal
238          * because different matches may be preferred with different cost
239          * models, but it is a very worthwhile speedup.  */
240         unsigned (*get_matches_func)(struct lzx_compressor *, const struct lz_match **);
241         void (*skip_bytes_func)(struct lzx_compressor *, unsigned n);
242         u32 match_window_pos;
243         u32 match_window_end;
244         struct lz_match *cached_matches;
245         struct lz_match *cache_ptr;
246         struct lz_match *cache_limit;
247
248         /* Position data for near-optimal parsing.  */
249         struct lzx_mc_pos_data optimum[LZX_OPTIM_ARRAY_LENGTH + LZX_MAX_MATCH_LEN];
250
251         /* The cost model currently being used for near-optimal parsing.  */
252         struct lzx_costs costs;
253
254         /* The current match offset LRU queue.  */
255         struct lzx_lru_queue queue;
256
257         /* Frequency counters for the current block.  */
258         struct lzx_freqs freqs;
259
260         /* The Huffman codes for the current and previous blocks.  */
261         struct lzx_codes codes[2];
262
263         /* Which 'struct lzx_codes' is being used for the current block.  The
264          * other was used for the previous block (if this isn't the first
265          * block).  */
266         unsigned int codes_index;
267
268         /* Dummy lengths that are always 0.  */
269         struct lzx_lens zero_lens;
270
271         /* Matches/literals that were chosen for the current block.  */
272         struct lzx_item chosen_items[LZX_DIV_BLOCK_SIZE];
273
274         /* Table mapping match offset => offset slot for small offsets  */
275 #define LZX_NUM_FAST_OFFSETS 32768
276         u8 offset_slot_fast[LZX_NUM_FAST_OFFSETS];
277 };
278
279 /*
280  * Structure to keep track of the current state of sending bits to the
281  * compressed output buffer.
282  *
283  * The LZX bitstream is encoded as a sequence of 16-bit coding units.
284  */
285 struct lzx_output_bitstream {
286
287         /* Bits that haven't yet been written to the output buffer.  */
288         u32 bitbuf;
289
290         /* Number of bits currently held in @bitbuf.  */
291         u32 bitcount;
292
293         /* Pointer to the start of the output buffer.  */
294         le16 *start;
295
296         /* Pointer to the position in the output buffer at which the next coding
297          * unit should be written.  */
298         le16 *next;
299
300         /* Pointer past the end of the output buffer.  */
301         le16 *end;
302 };
303
304 /*
305  * Initialize the output bitstream.
306  *
307  * @os
308  *      The output bitstream structure to initialize.
309  * @buffer
310  *      The buffer being written to.
311  * @size
312  *      Size of @buffer, in bytes.
313  */
314 static void
315 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, u32 size)
316 {
317         os->bitbuf = 0;
318         os->bitcount = 0;
319         os->start = buffer;
320         os->next = os->start;
321         os->end = os->start + size / sizeof(le16);
322 }
323
324 /*
325  * Write some bits to the output bitstream.
326  *
327  * The bits are given by the low-order @num_bits bits of @bits.  Higher-order
328  * bits in @bits cannot be set.  At most 17 bits can be written at once.
329  *
330  * @max_num_bits is a compile-time constant that specifies the maximum number of
331  * bits that can ever be written at the call site.  Currently, it is used to
332  * optimize away the conditional code for writing a second 16-bit coding unit
333  * when writing fewer than 17 bits.
334  *
335  * If the output buffer space is exhausted, then the bits will be ignored, and
336  * lzx_flush_output() will return 0 when it gets called.
337  */
338 static inline void
339 lzx_write_varbits(struct lzx_output_bitstream *os,
340                   const u32 bits, const unsigned int num_bits,
341                   const unsigned int max_num_bits)
342 {
343         /* This code is optimized for LZX, which never needs to write more than
344          * 17 bits at once.  */
345         LZX_ASSERT(num_bits <= 17);
346         LZX_ASSERT(num_bits <= max_num_bits);
347         LZX_ASSERT(os->bitcount <= 15);
348
349         /* Add the bits to the bit buffer variable.  @bitcount will be at most
350          * 15, so there will be just enough space for the maximum possible
351          * @num_bits of 17.  */
352         os->bitcount += num_bits;
353         os->bitbuf = (os->bitbuf << num_bits) | bits;
354
355         /* Check whether any coding units need to be written.  */
356         if (os->bitcount >= 16) {
357
358                 os->bitcount -= 16;
359
360                 /* Write a coding unit, unless it would overflow the buffer.  */
361                 if (os->next != os->end)
362                         *os->next++ = cpu_to_le16(os->bitbuf >> os->bitcount);
363
364                 /* If writing 17 bits, a second coding unit might need to be
365                  * written.  But because 'max_num_bits' is a compile-time
366                  * constant, the compiler will optimize away this code at most
367                  * call sites.  */
368                 if (max_num_bits == 17 && os->bitcount == 16) {
369                         if (os->next != os->end)
370                                 *os->next++ = cpu_to_le16(os->bitbuf);
371                         os->bitcount = 0;
372                 }
373         }
374 }
375
376 /* Use when @num_bits is a compile-time constant.  Otherwise use
377  * lzx_write_varbits().  */
378 static inline void
379 lzx_write_bits(struct lzx_output_bitstream *os,
380                const u32 bits, const unsigned int num_bits)
381 {
382         lzx_write_varbits(os, bits, num_bits, num_bits);
383 }
384
385 /*
386  * Flush the last coding unit to the output buffer if needed.  Return the total
387  * number of bytes written to the output buffer, or 0 if an overflow occurred.
388  */
389 static u32
390 lzx_flush_output(struct lzx_output_bitstream *os)
391 {
392         if (os->next == os->end)
393                 return 0;
394
395         if (os->bitcount != 0)
396                 *os->next++ = cpu_to_le16(os->bitbuf << (16 - os->bitcount));
397
398         return (const u8 *)os->next - (const u8 *)os->start;
399 }
400
401 /* Build the main, length, and aligned offset Huffman codes used in LZX.
402  *
403  * This takes as input the frequency tables for each code and produces as output
404  * a set of tables that map symbols to codewords and codeword lengths.  */
405 static void
406 lzx_make_huffman_codes(const struct lzx_freqs *freqs, struct lzx_codes *codes,
407                        unsigned num_main_syms)
408 {
409         make_canonical_huffman_code(num_main_syms,
410                                     LZX_MAX_MAIN_CODEWORD_LEN,
411                                     freqs->main,
412                                     codes->lens.main,
413                                     codes->codewords.main);
414
415         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
416                                     LZX_MAX_LEN_CODEWORD_LEN,
417                                     freqs->len,
418                                     codes->lens.len,
419                                     codes->codewords.len);
420
421         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
422                                     LZX_MAX_ALIGNED_CODEWORD_LEN,
423                                     freqs->aligned,
424                                     codes->lens.aligned,
425                                     codes->codewords.aligned);
426 }
427
428 static unsigned
429 lzx_compute_precode_items(const u8 lens[restrict],
430                           const u8 prev_lens[restrict],
431                           const unsigned num_lens,
432                           u32 precode_freqs[restrict],
433                           unsigned precode_items[restrict])
434 {
435         unsigned *itemptr;
436         unsigned run_start;
437         unsigned run_end;
438         unsigned extra_bits;
439         int delta;
440         u8 len;
441
442         itemptr = precode_items;
443         run_start = 0;
444         do {
445                 /* Find the next run of codeword lengths.  */
446
447                 /* len = the length being repeated  */
448                 len = lens[run_start];
449
450                 run_end = run_start + 1;
451
452                 /* Fast case for a single length.  */
453                 if (likely(run_end == num_lens || len != lens[run_end])) {
454                         delta = prev_lens[run_start] - len;
455                         if (delta < 0)
456                                 delta += 17;
457                         precode_freqs[delta]++;
458                         *itemptr++ = delta;
459                         run_start++;
460                         continue;
461                 }
462
463                 /* Extend the run.  */
464                 do {
465                         run_end++;
466                 } while (run_end != num_lens && len == lens[run_end]);
467
468                 if (len == 0) {
469                         /* Run of zeroes.  */
470
471                         /* Symbol 18: RLE 20 to 51 zeroes at a time.  */
472                         while ((run_end - run_start) >= 20) {
473                                 extra_bits = min((run_end - run_start) - 20, 0x1f);
474                                 precode_freqs[18]++;
475                                 *itemptr++ = 18 | (extra_bits << 5);
476                                 run_start += 20 + extra_bits;
477                         }
478
479                         /* Symbol 17: RLE 4 to 19 zeroes at a time.  */
480                         if ((run_end - run_start) >= 4) {
481                                 extra_bits = min((run_end - run_start) - 4, 0xf);
482                                 precode_freqs[17]++;
483                                 *itemptr++ = 17 | (extra_bits << 5);
484                                 run_start += 4 + extra_bits;
485                         }
486                 } else {
487
488                         /* A run of nonzero lengths. */
489
490                         /* Symbol 19: RLE 4 to 5 of any length at a time.  */
491                         while ((run_end - run_start) >= 4) {
492                                 extra_bits = (run_end - run_start) > 4;
493                                 delta = prev_lens[run_start] - len;
494                                 if (delta < 0)
495                                         delta += 17;
496                                 precode_freqs[19]++;
497                                 precode_freqs[delta]++;
498                                 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
499                                 run_start += 4 + extra_bits;
500                         }
501                 }
502
503                 /* Output any remaining lengths without RLE.  */
504                 while (run_start != run_end) {
505                         delta = prev_lens[run_start] - len;
506                         if (delta < 0)
507                                 delta += 17;
508                         precode_freqs[delta]++;
509                         *itemptr++ = delta;
510                         run_start++;
511                 }
512         } while (run_start != num_lens);
513
514         return itemptr - precode_items;
515 }
516
517 /*
518  * Output a Huffman code in the compressed form used in LZX.
519  *
520  * The Huffman code is represented in the output as a logical series of codeword
521  * lengths from which the Huffman code, which must be in canonical form, can be
522  * reconstructed.
523  *
524  * The codeword lengths are themselves compressed using a separate Huffman code,
525  * the "precode", which contains a symbol for each possible codeword length in
526  * the larger code as well as several special symbols to represent repeated
527  * codeword lengths (a form of run-length encoding).  The precode is itself
528  * constructed in canonical form, and its codeword lengths are represented
529  * literally in 20 4-bit fields that immediately precede the compressed codeword
530  * lengths of the larger code.
531  *
532  * Furthermore, the codeword lengths of the larger code are actually represented
533  * as deltas from the codeword lengths of the corresponding code in the previous
534  * block.
535  *
536  * @os:
537  *      Bitstream to which to write the compressed Huffman code.
538  * @lens:
539  *      The codeword lengths, indexed by symbol, in the Huffman code.
540  * @prev_lens:
541  *      The codeword lengths, indexed by symbol, in the corresponding Huffman
542  *      code in the previous block, or all zeroes if this is the first block.
543  * @num_lens:
544  *      The number of symbols in the Huffman code.
545  */
546 static void
547 lzx_write_compressed_code(struct lzx_output_bitstream *os,
548                           const u8 lens[restrict],
549                           const u8 prev_lens[restrict],
550                           unsigned num_lens)
551 {
552         u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
553         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
554         u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
555         unsigned precode_items[num_lens];
556         unsigned num_precode_items;
557         unsigned precode_item;
558         unsigned precode_sym;
559         unsigned i;
560
561         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
562                 precode_freqs[i] = 0;
563
564         /* Compute the "items" (RLE / literal tokens and extra bits) with which
565          * the codeword lengths in the larger code will be output.  */
566         num_precode_items = lzx_compute_precode_items(lens,
567                                                       prev_lens,
568                                                       num_lens,
569                                                       precode_freqs,
570                                                       precode_items);
571
572         /* Build the precode.  */
573         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
574                                     LZX_MAX_PRE_CODEWORD_LEN,
575                                     precode_freqs, precode_lens,
576                                     precode_codewords);
577
578         /* Output the lengths of the codewords in the precode.  */
579         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
580                 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
581
582         /* Output the encoded lengths of the codewords in the larger code.  */
583         for (i = 0; i < num_precode_items; i++) {
584                 precode_item = precode_items[i];
585                 precode_sym = precode_item & 0x1F;
586                 lzx_write_varbits(os, precode_codewords[precode_sym],
587                                   precode_lens[precode_sym],
588                                   LZX_MAX_PRE_CODEWORD_LEN);
589                 if (precode_sym >= 17) {
590                         if (precode_sym == 17) {
591                                 lzx_write_bits(os, precode_item >> 5, 4);
592                         } else if (precode_sym == 18) {
593                                 lzx_write_bits(os, precode_item >> 5, 5);
594                         } else {
595                                 lzx_write_bits(os, (precode_item >> 5) & 1, 1);
596                                 precode_sym = precode_item >> 6;
597                                 lzx_write_varbits(os, precode_codewords[precode_sym],
598                                                   precode_lens[precode_sym],
599                                                   LZX_MAX_PRE_CODEWORD_LEN);
600                         }
601                 }
602         }
603 }
604
605 /* Output a match or literal.  */
606 static inline void
607 lzx_write_item(struct lzx_output_bitstream *os, struct lzx_item item,
608                unsigned ones_if_aligned, const struct lzx_codes *codes)
609 {
610         u64 data = item.data;
611         unsigned main_symbol;
612         unsigned len_symbol;
613         unsigned num_extra_bits;
614         u32 extra_bits;
615
616         main_symbol = data & 0x3FF;
617
618         lzx_write_varbits(os, codes->codewords.main[main_symbol],
619                           codes->lens.main[main_symbol],
620                           LZX_MAX_MAIN_CODEWORD_LEN);
621
622         if (main_symbol < LZX_NUM_CHARS)  /* Literal?  */
623                 return;
624
625         len_symbol = (data >> 10) & 0xFF;
626
627         if (len_symbol != LZX_LENCODE_NUM_SYMBOLS) {
628                 lzx_write_varbits(os, codes->codewords.len[len_symbol],
629                                   codes->lens.len[len_symbol],
630                                   LZX_MAX_LEN_CODEWORD_LEN);
631         }
632
633         num_extra_bits = (data >> 18) & 0x1F;
634         if (num_extra_bits == 0)  /* Small offset or repeat offset match?  */
635                 return;
636
637         extra_bits = data >> 23;
638
639         /*if (block_type == LZX_BLOCKTYPE_ALIGNED && num_extra_bits >= 3) {*/
640         if ((num_extra_bits & ones_if_aligned) >= 3) {
641
642                 /* Aligned offset blocks: The low 3 bits of the extra offset
643                  * bits are Huffman-encoded using the aligned offset code.  The
644                  * remaining bits are output literally.  */
645
646                 lzx_write_varbits(os, extra_bits >> 3, num_extra_bits - 3, 14);
647
648                 lzx_write_varbits(os, codes->codewords.aligned[extra_bits & 7],
649                                   codes->lens.aligned[extra_bits & 7],
650                                   LZX_MAX_ALIGNED_CODEWORD_LEN);
651         } else {
652                 /* Verbatim blocks, or fewer than 3 extra bits:  All extra
653                  * offset bits are output literally.  */
654                 lzx_write_varbits(os, extra_bits, num_extra_bits, 17);
655         }
656 }
657
658 /*
659  * Write all matches and literal bytes (which were precomputed) in an LZX
660  * compressed block to the output bitstream in the final compressed
661  * representation.
662  *
663  * @os
664  *      The output bitstream.
665  * @block_type
666  *      The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
667  *      LZX_BLOCKTYPE_VERBATIM).
668  * @items
669  *      The array of matches/literals to output.
670  * @num_items
671  *      Number of matches/literals to output (length of @items).
672  * @codes
673  *      The main, length, and aligned offset Huffman codes for the current
674  *      LZX compressed block.
675  */
676 static void
677 lzx_write_items(struct lzx_output_bitstream *os, int block_type,
678                 const struct lzx_item items[], u32 num_items,
679                 const struct lzx_codes *codes)
680 {
681         unsigned ones_if_aligned = 0U - (block_type == LZX_BLOCKTYPE_ALIGNED);
682
683         for (u32 i = 0; i < num_items; i++)
684                 lzx_write_item(os, items[i], ones_if_aligned, codes);
685 }
686
687 /* Write an LZX aligned offset or verbatim block to the output bitstream.  */
688 static void
689 lzx_write_compressed_block(int block_type,
690                            u32 block_size,
691                            unsigned window_order,
692                            unsigned num_main_syms,
693                            struct lzx_item * chosen_items,
694                            u32 num_chosen_items,
695                            const struct lzx_codes * codes,
696                            const struct lzx_lens * prev_lens,
697                            struct lzx_output_bitstream * os)
698 {
699         LZX_ASSERT(block_type == LZX_BLOCKTYPE_ALIGNED ||
700                    block_type == LZX_BLOCKTYPE_VERBATIM);
701
702         /* The first three bits indicate the type of block and are one of the
703          * LZX_BLOCKTYPE_* constants.  */
704         lzx_write_bits(os, block_type, 3);
705
706         /* Output the block size.
707          *
708          * The original LZX format seemed to always encode the block size in 3
709          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
710          * uses the first bit to indicate whether the block is the default size
711          * (32768) or a different size given explicitly by the next 16 bits.
712          *
713          * By default, this compressor uses a window size of 32768 and therefore
714          * follows the WIMGAPI behavior.  However, this compressor also supports
715          * window sizes greater than 32768 bytes, which do not appear to be
716          * supported by WIMGAPI.  In such cases, we retain the default size bit
717          * to mean a size of 32768 bytes but output non-default block size in 24
718          * bits rather than 16.  The compatibility of this behavior is unknown
719          * because WIMs created with chunk size greater than 32768 can seemingly
720          * only be opened by wimlib anyway.  */
721         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
722                 lzx_write_bits(os, 1, 1);
723         } else {
724                 lzx_write_bits(os, 0, 1);
725
726                 if (window_order >= 16)
727                         lzx_write_bits(os, block_size >> 16, 8);
728
729                 lzx_write_bits(os, block_size & 0xFFFF, 16);
730         }
731
732         /* If it's an aligned offset block, output the aligned offset code.  */
733         if (block_type == LZX_BLOCKTYPE_ALIGNED) {
734                 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
735                         lzx_write_bits(os, codes->lens.aligned[i],
736                                        LZX_ALIGNEDCODE_ELEMENT_SIZE);
737                 }
738         }
739
740         /* Output the main code (two parts).  */
741         lzx_write_compressed_code(os, codes->lens.main,
742                                   prev_lens->main,
743                                   LZX_NUM_CHARS);
744         lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
745                                   prev_lens->main + LZX_NUM_CHARS,
746                                   num_main_syms - LZX_NUM_CHARS);
747
748         /* Output the length code.  */
749         lzx_write_compressed_code(os, codes->lens.len,
750                                   prev_lens->len,
751                                   LZX_LENCODE_NUM_SYMBOLS);
752
753         /* Output the compressed matches and literals.  */
754         lzx_write_items(os, block_type, chosen_items, num_chosen_items, codes);
755 }
756
757 /* Don't allow matches to span the end of an LZX block.  */
758 static inline unsigned
759 maybe_truncate_matches(struct lz_match matches[], unsigned num_matches,
760                        struct lzx_compressor *c)
761 {
762         if (c->match_window_end < c->cur_window_size && num_matches != 0) {
763                 u32 limit = c->match_window_end - c->match_window_pos;
764
765                 if (limit >= LZX_MIN_MATCH_LEN) {
766
767                         unsigned i = num_matches - 1;
768                         do {
769                                 if (matches[i].len >= limit) {
770                                         matches[i].len = limit;
771
772                                         /* Truncation might produce multiple
773                                          * matches with length 'limit'.  Keep at
774                                          * most 1.  */
775                                         num_matches = i + 1;
776                                 }
777                         } while (i--);
778                 } else {
779                         num_matches = 0;
780                 }
781         }
782         return num_matches;
783 }
784
785 static unsigned
786 lzx_get_matches_fillcache_singleblock(struct lzx_compressor *c,
787                                       const struct lz_match **matches_ret)
788 {
789         struct lz_match *cache_ptr;
790         struct lz_match *matches;
791         unsigned num_matches;
792
793         cache_ptr = c->cache_ptr;
794         matches = cache_ptr + 1;
795         if (likely(cache_ptr <= c->cache_limit)) {
796                 num_matches = lz_mf_get_matches(c->mf, matches);
797                 cache_ptr->len = num_matches;
798                 c->cache_ptr = matches + num_matches;
799         } else {
800                 num_matches = 0;
801         }
802         c->match_window_pos++;
803         *matches_ret = matches;
804         return num_matches;
805 }
806
807 static unsigned
808 lzx_get_matches_fillcache_multiblock(struct lzx_compressor *c,
809                                      const struct lz_match **matches_ret)
810 {
811         struct lz_match *cache_ptr;
812         struct lz_match *matches;
813         unsigned num_matches;
814
815         cache_ptr = c->cache_ptr;
816         matches = cache_ptr + 1;
817         if (likely(cache_ptr <= c->cache_limit)) {
818                 num_matches = lz_mf_get_matches(c->mf, matches);
819                 num_matches = maybe_truncate_matches(matches, num_matches, c);
820                 cache_ptr->len = num_matches;
821                 c->cache_ptr = matches + num_matches;
822         } else {
823                 num_matches = 0;
824         }
825         c->match_window_pos++;
826         *matches_ret = matches;
827         return num_matches;
828 }
829
830 static unsigned
831 lzx_get_matches_usecache(struct lzx_compressor *c,
832                          const struct lz_match **matches_ret)
833 {
834         struct lz_match *cache_ptr;
835         struct lz_match *matches;
836         unsigned num_matches;
837
838         cache_ptr = c->cache_ptr;
839         matches = cache_ptr + 1;
840         if (cache_ptr <= c->cache_limit) {
841                 num_matches = cache_ptr->len;
842                 c->cache_ptr = matches + num_matches;
843         } else {
844                 num_matches = 0;
845         }
846         c->match_window_pos++;
847         *matches_ret = matches;
848         return num_matches;
849 }
850
851 static unsigned
852 lzx_get_matches_usecache_nocheck(struct lzx_compressor *c,
853                                  const struct lz_match **matches_ret)
854 {
855         struct lz_match *cache_ptr;
856         struct lz_match *matches;
857         unsigned num_matches;
858
859         cache_ptr = c->cache_ptr;
860         matches = cache_ptr + 1;
861         num_matches = cache_ptr->len;
862         c->cache_ptr = matches + num_matches;
863         c->match_window_pos++;
864         *matches_ret = matches;
865         return num_matches;
866 }
867
868 static unsigned
869 lzx_get_matches_nocache_singleblock(struct lzx_compressor *c,
870                                     const struct lz_match **matches_ret)
871 {
872         struct lz_match *matches;
873         unsigned num_matches;
874
875         matches = c->cache_ptr;
876         num_matches = lz_mf_get_matches(c->mf, matches);
877         c->match_window_pos++;
878         *matches_ret = matches;
879         return num_matches;
880 }
881
882 static unsigned
883 lzx_get_matches_nocache_multiblock(struct lzx_compressor *c,
884                                    const struct lz_match **matches_ret)
885 {
886         struct lz_match *matches;
887         unsigned num_matches;
888
889         matches = c->cache_ptr;
890         num_matches = lz_mf_get_matches(c->mf, matches);
891         num_matches = maybe_truncate_matches(matches, num_matches, c);
892         c->match_window_pos++;
893         *matches_ret = matches;
894         return num_matches;
895 }
896
897 /*
898  * Find matches at the next position in the window.
899  *
900  * This uses a wrapper function around the underlying match-finder.
901  *
902  * Returns the number of matches found and sets *matches_ret to point to the
903  * matches array.  The matches will be sorted by strictly increasing length and
904  * offset.
905  */
906 static inline unsigned
907 lzx_get_matches(struct lzx_compressor *c,
908                 const struct lz_match **matches_ret)
909 {
910         return (*c->get_matches_func)(c, matches_ret);
911 }
912
913 static void
914 lzx_skip_bytes_fillcache(struct lzx_compressor *c, unsigned n)
915 {
916         struct lz_match *cache_ptr;
917
918         cache_ptr = c->cache_ptr;
919         c->match_window_pos += n;
920         lz_mf_skip_positions(c->mf, n);
921         if (cache_ptr <= c->cache_limit) {
922                 do {
923                         cache_ptr->len = 0;
924                         cache_ptr += 1;
925                 } while (--n && cache_ptr <= c->cache_limit);
926         }
927         c->cache_ptr = cache_ptr;
928 }
929
930 static void
931 lzx_skip_bytes_usecache(struct lzx_compressor *c, unsigned n)
932 {
933         struct lz_match *cache_ptr;
934
935         cache_ptr = c->cache_ptr;
936         c->match_window_pos += n;
937         if (cache_ptr <= c->cache_limit) {
938                 do {
939                         cache_ptr += 1 + cache_ptr->len;
940                 } while (--n && cache_ptr <= c->cache_limit);
941         }
942         c->cache_ptr = cache_ptr;
943 }
944
945 static void
946 lzx_skip_bytes_usecache_nocheck(struct lzx_compressor *c, unsigned n)
947 {
948         struct lz_match *cache_ptr;
949
950         cache_ptr = c->cache_ptr;
951         c->match_window_pos += n;
952         do {
953                 cache_ptr += 1 + cache_ptr->len;
954         } while (--n);
955         c->cache_ptr = cache_ptr;
956 }
957
958 static void
959 lzx_skip_bytes_nocache(struct lzx_compressor *c, unsigned n)
960 {
961         c->match_window_pos += n;
962         lz_mf_skip_positions(c->mf, n);
963 }
964
965 /*
966  * Skip the specified number of positions in the window (don't search for
967  * matches at them).
968  *
969  * This uses a wrapper function around the underlying match-finder.
970  */
971 static inline void
972 lzx_skip_bytes(struct lzx_compressor *c, unsigned n)
973 {
974         return (*c->skip_bytes_func)(c, n);
975 }
976
977 /* Tally, and optionally record, the specified literal byte.  */
978 static inline void
979 lzx_declare_literal(struct lzx_compressor *c, unsigned literal,
980                     struct lzx_item **next_chosen_item)
981 {
982         unsigned main_symbol = literal;
983
984         c->freqs.main[main_symbol]++;
985
986         if (next_chosen_item) {
987                 *(*next_chosen_item)++ = (struct lzx_item) {
988                         .data = main_symbol,
989                 };
990         }
991 }
992
993 /* Tally, and optionally record, the specified repeat offset match.  */
994 static inline void
995 lzx_declare_repeat_offset_match(struct lzx_compressor *c,
996                                 unsigned len, unsigned rep_index,
997                                 struct lzx_item **next_chosen_item)
998 {
999         unsigned len_header;
1000         unsigned main_symbol;
1001         unsigned len_symbol;
1002
1003         if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1004                 len_header = len - LZX_MIN_MATCH_LEN;
1005                 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1006         } else {
1007                 len_header = LZX_NUM_PRIMARY_LENS;
1008                 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1009                 c->freqs.len[len_symbol]++;
1010         }
1011
1012         main_symbol = LZX_NUM_CHARS + ((rep_index << 3) | len_header);
1013
1014         c->freqs.main[main_symbol]++;
1015
1016         if (next_chosen_item) {
1017                 *(*next_chosen_item)++ = (struct lzx_item) {
1018                         .data = (u64)main_symbol | ((u64)len_symbol << 10),
1019                 };
1020         }
1021 }
1022
1023 /* Tally, and optionally record, the specified explicit offset match.  */
1024 static inline void
1025 lzx_declare_explicit_offset_match(struct lzx_compressor *c, unsigned len, u32 offset,
1026                                   struct lzx_item **next_chosen_item)
1027 {
1028         unsigned len_header;
1029         unsigned main_symbol;
1030         unsigned len_symbol;
1031         unsigned offset_slot;
1032         unsigned num_extra_bits;
1033         u32 extra_bits;
1034
1035         if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1036                 len_header = len - LZX_MIN_MATCH_LEN;
1037                 len_symbol = LZX_LENCODE_NUM_SYMBOLS;
1038         } else {
1039                 len_header = LZX_NUM_PRIMARY_LENS;
1040                 len_symbol = len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS;
1041                 c->freqs.len[len_symbol]++;
1042         }
1043
1044         offset_slot = lzx_get_offset_slot_raw(offset + LZX_OFFSET_OFFSET);
1045
1046         main_symbol = LZX_NUM_CHARS + ((offset_slot << 3) | len_header);
1047
1048         c->freqs.main[main_symbol]++;
1049
1050         if (offset_slot >= 8)
1051                 c->freqs.aligned[(offset + LZX_OFFSET_OFFSET) & 7]++;
1052
1053         if (next_chosen_item) {
1054
1055                 num_extra_bits = lzx_extra_offset_bits[offset_slot];
1056
1057                 extra_bits = (offset + LZX_OFFSET_OFFSET) -
1058                              lzx_offset_slot_base[offset_slot];
1059
1060                 *(*next_chosen_item)++ = (struct lzx_item) {
1061                         .data = (u64)main_symbol |
1062                                 ((u64)len_symbol << 10) |
1063                                 ((u64)num_extra_bits << 18) |
1064                                 ((u64)extra_bits << 23),
1065                 };
1066         }
1067 }
1068
1069 /* Tally, and optionally record, the specified match or literal.  */
1070 static inline void
1071 lzx_declare_item(struct lzx_compressor *c, u32 mc_item_data,
1072                  struct lzx_item **next_chosen_item)
1073 {
1074         u32 len = mc_item_data & MC_LEN_MASK;
1075         u32 offset_data = mc_item_data >> MC_OFFSET_SHIFT;
1076
1077         if (len == 1)
1078                 lzx_declare_literal(c, offset_data, next_chosen_item);
1079         else if (offset_data < LZX_NUM_RECENT_OFFSETS)
1080                 lzx_declare_repeat_offset_match(c, len, offset_data,
1081                                                 next_chosen_item);
1082         else
1083                 lzx_declare_explicit_offset_match(c, len,
1084                                                   offset_data - LZX_OFFSET_OFFSET,
1085                                                   next_chosen_item);
1086 }
1087
1088 static inline void
1089 lzx_record_item_list(struct lzx_compressor *c,
1090                      struct lzx_mc_pos_data *cur_optimum_ptr,
1091                      struct lzx_item **next_chosen_item)
1092 {
1093         struct lzx_mc_pos_data *end_optimum_ptr;
1094         u32 saved_item;
1095         u32 item;
1096
1097         /* The list is currently in reverse order (last item to first item).
1098          * Reverse it.  */
1099         end_optimum_ptr = cur_optimum_ptr;
1100         saved_item = cur_optimum_ptr->mc_item_data;
1101         do {
1102                 item = saved_item;
1103                 cur_optimum_ptr -= item & MC_LEN_MASK;
1104                 saved_item = cur_optimum_ptr->mc_item_data;
1105                 cur_optimum_ptr->mc_item_data = item;
1106         } while (cur_optimum_ptr != c->optimum);
1107
1108         /* Walk the list of items from beginning to end, tallying and recording
1109          * each item.  */
1110         do {
1111                 lzx_declare_item(c, cur_optimum_ptr->mc_item_data, next_chosen_item);
1112                 cur_optimum_ptr += (cur_optimum_ptr->mc_item_data) & MC_LEN_MASK;
1113         } while (cur_optimum_ptr != end_optimum_ptr);
1114 }
1115
1116 static inline void
1117 lzx_tally_item_list(struct lzx_compressor *c, struct lzx_mc_pos_data *cur_optimum_ptr)
1118 {
1119         /* Since we're just tallying the items, we don't need to reverse the
1120          * list.  Processing the items in reverse order is fine.  */
1121         do {
1122                 lzx_declare_item(c, cur_optimum_ptr->mc_item_data, NULL);
1123                 cur_optimum_ptr -= (cur_optimum_ptr->mc_item_data & MC_LEN_MASK);
1124         } while (cur_optimum_ptr != c->optimum);
1125 }
1126
1127 /* Tally, and optionally (if next_chosen_item != NULL) record, in order, all
1128  * items in the current list of items found by the match-chooser.  */
1129 static void
1130 lzx_declare_item_list(struct lzx_compressor *c, struct lzx_mc_pos_data *cur_optimum_ptr,
1131                       struct lzx_item **next_chosen_item)
1132 {
1133         if (next_chosen_item)
1134                 lzx_record_item_list(c, cur_optimum_ptr, next_chosen_item);
1135         else
1136                 lzx_tally_item_list(c, cur_optimum_ptr);
1137 }
1138
1139 /* Set the cost model @c->costs from the Huffman codeword lengths specified in
1140  * @lens.
1141  *
1142  * The cost model and codeword lengths are almost the same thing, but the
1143  * Huffman codewords with length 0 correspond to symbols with zero frequency
1144  * that still need to be assigned actual costs.  The specific values assigned
1145  * are arbitrary, but they should be fairly high (near the maximum codeword
1146  * length) to take into account the fact that uses of these symbols are expected
1147  * to be rare.  */
1148 static void
1149 lzx_set_costs(struct lzx_compressor *c, const struct lzx_lens * lens)
1150 {
1151         unsigned i;
1152
1153         /* Main code  */
1154         for (i = 0; i < c->num_main_syms; i++)
1155                 c->costs.main[i] = lens->main[i] ? lens->main[i] : 15;
1156
1157         /* Length code  */
1158         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1159                 c->costs.len[i] = lens->len[i] ? lens->len[i] : 15;
1160
1161         /* Aligned offset code  */
1162         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1163                 c->costs.aligned[i] = lens->aligned[i] ? lens->aligned[i] : 7;
1164 }
1165
1166 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1167  * algorithm.  */
1168 static void
1169 lzx_set_default_costs(struct lzx_costs * costs, unsigned num_main_syms)
1170 {
1171         unsigned i;
1172
1173         /* Main code (part 1): Literal symbols  */
1174         for (i = 0; i < LZX_NUM_CHARS; i++)
1175                 costs->main[i] = 8;
1176
1177         /* Main code (part 2): Match header symbols  */
1178         for (; i < num_main_syms; i++)
1179                 costs->main[i] = 10;
1180
1181         /* Length code  */
1182         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1183                 costs->len[i] = 8;
1184
1185         /* Aligned offset code  */
1186         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1187                 costs->aligned[i] = 3;
1188 }
1189
1190 /* Return the cost, in bits, to output a literal byte using the specified cost
1191  * model.  */
1192 static inline u32
1193 lzx_literal_cost(unsigned literal, const struct lzx_costs * costs)
1194 {
1195         return costs->main[literal];
1196 }
1197
1198 /* Return the cost, in bits, to output a match of the specified length and
1199  * offset slot using the specified cost model.  Does not take into account
1200  * extra offset bits.  */
1201 static inline u32
1202 lzx_match_cost_raw(unsigned len, unsigned offset_slot,
1203                    const struct lzx_costs *costs)
1204 {
1205         u32 cost;
1206         unsigned len_header;
1207         unsigned main_symbol;
1208
1209         if (len - LZX_MIN_MATCH_LEN < LZX_NUM_PRIMARY_LENS) {
1210                 len_header = len - LZX_MIN_MATCH_LEN ;
1211                 cost = 0;
1212         } else {
1213                 len_header = LZX_NUM_PRIMARY_LENS;
1214
1215                 /* Account for length symbol.  */
1216                 cost = costs->len[len - LZX_MIN_MATCH_LEN - LZX_NUM_PRIMARY_LENS];
1217         }
1218
1219         /* Account for main symbol.  */
1220         main_symbol = LZX_NUM_CHARS + ((offset_slot << 3) | len_header);
1221         cost += costs->main[main_symbol];
1222
1223         return cost;
1224 }
1225
1226 /* Equivalent to lzx_match_cost_raw(), but assumes the length is small enough
1227  * that it doesn't require a length symbol.  */
1228 static inline u32
1229 lzx_match_cost_raw_smalllen(unsigned len, unsigned offset_slot,
1230                             const struct lzx_costs *costs)
1231 {
1232         LZX_ASSERT(len < LZX_MIN_MATCH_LEN + LZX_NUM_PRIMARY_LENS);
1233         return costs->main[LZX_NUM_CHARS +
1234                            ((offset_slot << 3) | (len - LZX_MIN_MATCH_LEN))];
1235 }
1236
1237 /*
1238  * Consider coding the match at repeat offset index @rep_idx.  Consider each
1239  * length from the minimum (2) to the full match length (@rep_len).
1240  */
1241 static inline void
1242 lzx_consider_repeat_offset_match(struct lzx_compressor *c,
1243                                  struct lzx_mc_pos_data *cur_optimum_ptr,
1244                                  unsigned rep_len, unsigned rep_idx)
1245 {
1246         u32 base_cost = cur_optimum_ptr->cost;
1247         u32 cost;
1248         unsigned len;
1249
1250 #if 1   /* Optimized version */
1251
1252         if (rep_len < LZX_MIN_MATCH_LEN + LZX_NUM_PRIMARY_LENS) {
1253                 /* All lengths being considered are small.  */
1254                 len = 2;
1255                 do {
1256                         cost = base_cost +
1257                                lzx_match_cost_raw_smalllen(len, rep_idx, &c->costs);
1258                         if (cost < (cur_optimum_ptr + len)->cost) {
1259                                 (cur_optimum_ptr + len)->mc_item_data =
1260                                         (rep_idx << MC_OFFSET_SHIFT) | len;
1261                                 (cur_optimum_ptr + len)->cost = cost;
1262                         }
1263                 } while (++len <= rep_len);
1264         } else {
1265                 /* Some lengths being considered are small, and some are big.
1266                  * Start with the optimized loop for small lengths, then switch
1267                  * to the optimized loop for big lengths.  */
1268                 len = 2;
1269                 do {
1270                         cost = base_cost +
1271                                lzx_match_cost_raw_smalllen(len, rep_idx, &c->costs);
1272                         if (cost < (cur_optimum_ptr + len)->cost) {
1273                                 (cur_optimum_ptr + len)->mc_item_data =
1274                                         (rep_idx << MC_OFFSET_SHIFT) | len;
1275                                 (cur_optimum_ptr + len)->cost = cost;
1276                         }
1277                 } while (++len < LZX_MIN_MATCH_LEN + LZX_NUM_PRIMARY_LENS);
1278
1279                 /* The main symbol is now fixed.  */
1280                 base_cost += c->costs.main[LZX_NUM_CHARS +
1281                                            ((rep_idx << 3) | LZX_NUM_PRIMARY_LENS)];
1282                 do {
1283                         cost = base_cost +
1284                                c->costs.len[len - LZX_MIN_MATCH_LEN -
1285                                             LZX_NUM_PRIMARY_LENS];
1286                         if (cost < (cur_optimum_ptr + len)->cost) {
1287                                 (cur_optimum_ptr + len)->mc_item_data =
1288                                         (rep_idx << MC_OFFSET_SHIFT) | len;
1289                                 (cur_optimum_ptr + len)->cost = cost;
1290                         }
1291                 } while (++len <= rep_len);
1292         }
1293
1294 #else   /* Unoptimized version  */
1295
1296         len = 2;
1297         do {
1298                 cost = base_cost +
1299                        lzx_match_cost_raw(len, rep_idx, &c->costs);
1300                 if (cost < (cur_optimum_ptr + len)->cost) {
1301                         (cur_optimum_ptr + len)->mc_item_data =
1302                                 (rep_idx << MC_OFFSET_SHIFT) | len;
1303                         (cur_optimum_ptr + len)->cost = cost;
1304                 }
1305         } while (++len <= rep_len);
1306 #endif
1307 }
1308
1309 /*
1310  * Consider coding each match in @matches as an explicit offset match.
1311  *
1312  * @matches must be sorted by strictly increasing length and strictly
1313  * increasing offset.  This is guaranteed by the match-finder.
1314  *
1315  * We consider each length from the minimum (2) to the longest
1316  * (matches[num_matches - 1].len).  For each length, we consider only
1317  * the smallest offset for which that length is available.  Although
1318  * this is not guaranteed to be optimal due to the possibility of a
1319  * larger offset costing less than a smaller offset to code, this is a
1320  * very useful heuristic.
1321  */
1322 static inline void
1323 lzx_consider_explicit_offset_matches(struct lzx_compressor *c,
1324                                      struct lzx_mc_pos_data *cur_optimum_ptr,
1325                                      const struct lz_match matches[],
1326                                      unsigned num_matches)
1327 {
1328         LZX_ASSERT(num_matches > 0);
1329
1330         unsigned i;
1331         unsigned len;
1332         unsigned offset_slot;
1333         u32 position_cost;
1334         u32 cost;
1335         u32 offset_data;
1336
1337
1338 #if 1   /* Optimized version */
1339
1340         if (matches[num_matches - 1].offset < LZX_NUM_FAST_OFFSETS) {
1341
1342                 /*
1343                  * Offset is small; the offset slot can be looked up directly in
1344                  * c->offset_slot_fast.
1345                  *
1346                  * Additional optimizations:
1347                  *
1348                  * - Since the offset is small, it falls in the exponential part
1349                  *   of the offset slot bases and the number of extra offset
1350                  *   bits can be calculated directly as (offset_slot >> 1) - 1.
1351                  *
1352                  * - Just consider the number of extra offset bits; don't
1353                  *   account for the aligned offset code.  Usually this has
1354                  *   almost no effect on the compression ratio.
1355                  *
1356                  * - Start out in a loop optimized for small lengths.  When the
1357                  *   length becomes high enough that a length symbol will be
1358                  *   needed, jump into a loop optimized for big lengths.
1359                  */
1360
1361                 LZX_ASSERT(offset_slot <= 37); /* for extra bits formula  */
1362
1363                 len = 2;
1364                 i = 0;
1365                 do {
1366                         offset_slot = c->offset_slot_fast[matches[i].offset];
1367                         position_cost = cur_optimum_ptr->cost +
1368                                         ((offset_slot >> 1) - 1);
1369                         offset_data = matches[i].offset + LZX_OFFSET_OFFSET;
1370                         do {
1371                                 if (len >= LZX_MIN_MATCH_LEN + LZX_NUM_PRIMARY_LENS)
1372                                         goto biglen;
1373                                 cost = position_cost +
1374                                        lzx_match_cost_raw_smalllen(len, offset_slot,
1375                                                                    &c->costs);
1376                                 if (cost < (cur_optimum_ptr + len)->cost) {
1377                                         (cur_optimum_ptr + len)->cost = cost;
1378                                         (cur_optimum_ptr + len)->mc_item_data =
1379                                                 (offset_data << MC_OFFSET_SHIFT) | len;
1380                                 }
1381                         } while (++len <= matches[i].len);
1382                 } while (++i != num_matches);
1383
1384                 return;
1385
1386                 do {
1387                         offset_slot = c->offset_slot_fast[matches[i].offset];
1388         biglen:
1389                         position_cost = cur_optimum_ptr->cost +
1390                                         ((offset_slot >> 1) - 1) +
1391                                         c->costs.main[LZX_NUM_CHARS +
1392                                                       ((offset_slot << 3) |
1393                                                        LZX_NUM_PRIMARY_LENS)];
1394                         offset_data = matches[i].offset + LZX_OFFSET_OFFSET;
1395                         do {
1396                                 cost = position_cost +
1397                                        c->costs.len[len - LZX_MIN_MATCH_LEN -
1398                                                     LZX_NUM_PRIMARY_LENS];
1399                                 if (cost < (cur_optimum_ptr + len)->cost) {
1400                                         (cur_optimum_ptr + len)->cost = cost;
1401                                         (cur_optimum_ptr + len)->mc_item_data =
1402                                                 (offset_data << MC_OFFSET_SHIFT) | len;
1403                                 }
1404                         } while (++len <= matches[i].len);
1405                 } while (++i != num_matches);
1406         } else {
1407                 len = 2;
1408                 i = 0;
1409                 do {
1410                         offset_data = matches[i].offset + LZX_OFFSET_OFFSET;
1411                         offset_slot = lzx_get_offset_slot_raw(offset_data);
1412                         position_cost = cur_optimum_ptr->cost +
1413                                         lzx_extra_offset_bits[offset_slot];
1414                         do {
1415                                 cost = position_cost +
1416                                        lzx_match_cost_raw(len, offset_slot, &c->costs);
1417                                 if (cost < (cur_optimum_ptr + len)->cost) {
1418                                         (cur_optimum_ptr + len)->cost = cost;
1419                                         (cur_optimum_ptr + len)->mc_item_data =
1420                                                 (offset_data << MC_OFFSET_SHIFT) | len;
1421                                 }
1422                         } while (++len <= matches[i].len);
1423                 } while (++i != num_matches);
1424         }
1425
1426 #else   /* Unoptimized version */
1427
1428         unsigned num_extra_bits;
1429
1430         len = 2;
1431         i = 0;
1432         do {
1433                 offset_data = matches[i].offset + LZX_OFFSET_OFFSET;
1434                 position_cost = cur_optimum_ptr->cost;
1435                 offset_slot = lzx_get_offset_slot_raw(offset_data);
1436                 num_extra_bits = lzx_extra_offset_bits[offset_slot];
1437                 if (num_extra_bits >= 3) {
1438                         position_cost += num_extra_bits - 3;
1439                         position_cost += c->costs.aligned[offset_data & 7];
1440                 } else {
1441                         position_cost += num_extra_bits;
1442                 }
1443                 do {
1444                         cost = position_cost +
1445                                lzx_match_cost_raw(len, offset_slot, &c->costs);
1446                         if (cost < (cur_optimum_ptr + len)->cost) {
1447                                 (cur_optimum_ptr + len)->cost = cost;
1448                                 (cur_optimum_ptr + len)->mc_item_data =
1449                                         (offset_data << MC_OFFSET_SHIFT) | len;
1450                         }
1451                 } while (++len <= matches[i].len);
1452         } while (++i != num_matches);
1453 #endif
1454 }
1455
1456 /*
1457  * Search for repeat offset matches with the current position.
1458  */
1459 static inline unsigned
1460 lzx_repsearch(const u8 * const strptr, const u32 bytes_remaining,
1461               const struct lzx_lru_queue *queue, unsigned *rep_max_idx_ret)
1462 {
1463         BUILD_BUG_ON(LZX_NUM_RECENT_OFFSETS != 3);
1464         return lz_repsearch3(strptr, min(bytes_remaining, LZX_MAX_MATCH_LEN),
1465                              queue->R, rep_max_idx_ret);
1466 }
1467
1468 /*
1469  * The main near-optimal parsing routine.
1470  *
1471  * Briefly, the algorithm does an approximate minimum-cost path search to find a
1472  * "near-optimal" sequence of matches and literals to output, based on the
1473  * current cost model.  The algorithm steps forward, position by position (byte
1474  * by byte), and updates the minimum cost path to reach each later position that
1475  * can be reached using a match or literal from the current position.  This is
1476  * essentially Dijkstra's algorithm in disguise: the graph nodes are positions,
1477  * the graph edges are possible matches/literals to code, and the cost of each
1478  * edge is the estimated number of bits that will be required to output the
1479  * corresponding match or literal.  But one difference is that we actually
1480  * compute the lowest-cost path in pieces, where each piece is terminated when
1481  * there are no choices to be made.
1482  *
1483  * This function will run this algorithm on the portion of the window from
1484  * &c->cur_window[c->match_window_pos] to &c->cur_window[c->match_window_end].
1485  *
1486  * On entry, c->queue must be the current state of the match offset LRU queue,
1487  * and c->costs must be the current cost model to use for Huffman symbols.
1488  *
1489  * On exit, c->queue will be the state that the LRU queue would be in if the
1490  * chosen items were to be coded.
1491  *
1492  * If next_chosen_item != NULL, then all items chosen will be recorded (saved in
1493  * the chosen_items array).  Otherwise, all items chosen will only be tallied
1494  * (symbol frequencies tallied in c->freqs).
1495  */
1496 static void
1497 lzx_optim_pass(struct lzx_compressor *c, struct lzx_item **next_chosen_item)
1498 {
1499         const u8 *block_end;
1500         struct lzx_lru_queue *begin_queue;
1501         const u8 *window_ptr;
1502         struct lzx_mc_pos_data *cur_optimum_ptr;
1503         struct lzx_mc_pos_data *end_optimum_ptr;
1504         const struct lz_match *matches;
1505         unsigned num_matches;
1506         unsigned longest_len;
1507         unsigned rep_max_len;
1508         unsigned rep_max_idx;
1509         unsigned literal;
1510         unsigned len;
1511         u32 cost;
1512         u32 offset_data;
1513
1514         block_end = &c->cur_window[c->match_window_end];
1515         begin_queue = &c->queue;
1516 begin:
1517         /* Start building a new list of items, which will correspond to the next
1518          * piece of the overall minimum-cost path.
1519          *
1520          * *begin_queue is the current state of the match offset LRU queue.  */
1521
1522         window_ptr = &c->cur_window[c->match_window_pos];
1523
1524         if (window_ptr == block_end) {
1525                 c->queue = *begin_queue;
1526                 return;
1527         }
1528
1529         cur_optimum_ptr = c->optimum;
1530         cur_optimum_ptr->cost = 0;
1531         cur_optimum_ptr->queue = *begin_queue;
1532
1533         end_optimum_ptr = cur_optimum_ptr;
1534
1535         /* The following loop runs once for each per byte in the window, except
1536          * in a couple shortcut cases.  */
1537         for (;;) {
1538
1539                 /* Find explicit offset matches with the current position.  */
1540                 num_matches = lzx_get_matches(c, &matches);
1541
1542                 if (num_matches) {
1543                         /*
1544                          * Find the longest repeat offset match with the current
1545                          * position.
1546                          *
1547                          * Heuristics:
1548                          *
1549                          * - Only search for repeat offset matches if the
1550                          *   match-finder already found at least one match.
1551                          *
1552                          * - Only consider the longest repeat offset match.  It
1553                          *   seems to be rare for the optimal parse to include a
1554                          *   repeat offset match that doesn't have the longest
1555                          *   length (allowing for the possibility that not all
1556                          *   of that length is actually used).
1557                          */
1558                         rep_max_len = lzx_repsearch(window_ptr,
1559                                                     block_end - window_ptr,
1560                                                     &cur_optimum_ptr->queue,
1561                                                     &rep_max_idx);
1562
1563                         if (rep_max_len) {
1564                                 /* If there's a very long repeat offset match,
1565                                  * choose it immediately.  */
1566                                 if (rep_max_len >= c->params.nice_match_length) {
1567
1568                                         swap(cur_optimum_ptr->queue.R[0],
1569                                              cur_optimum_ptr->queue.R[rep_max_idx]);
1570                                         begin_queue = &cur_optimum_ptr->queue;
1571
1572                                         cur_optimum_ptr += rep_max_len;
1573                                         cur_optimum_ptr->mc_item_data =
1574                                                 (rep_max_idx << MC_OFFSET_SHIFT) |
1575                                                 rep_max_len;
1576
1577                                         lzx_skip_bytes(c, rep_max_len - 1);
1578                                         break;
1579                                 }
1580
1581                                 /* If reaching any positions for the first time,
1582                                  * initialize their costs to "infinity".  */
1583                                 while (end_optimum_ptr < cur_optimum_ptr + rep_max_len)
1584                                         (++end_optimum_ptr)->cost = MC_INFINITE_COST;
1585
1586                                 /* Consider coding a repeat offset match.  */
1587                                 lzx_consider_repeat_offset_match(c,
1588                                                                  cur_optimum_ptr,
1589                                                                  rep_max_len,
1590                                                                  rep_max_idx);
1591                         }
1592
1593                         longest_len = matches[num_matches - 1].len;
1594
1595                         /* If there's a very long explicit offset match, choose
1596                          * it immediately.  */
1597                         if (longest_len >= c->params.nice_match_length) {
1598
1599                                 cur_optimum_ptr->queue.R[2] =
1600                                         cur_optimum_ptr->queue.R[1];
1601                                 cur_optimum_ptr->queue.R[1] =
1602                                         cur_optimum_ptr->queue.R[0];
1603                                 cur_optimum_ptr->queue.R[0] =
1604                                         matches[num_matches - 1].offset;
1605                                 begin_queue = &cur_optimum_ptr->queue;
1606
1607                                 offset_data = matches[num_matches - 1].offset +
1608                                               LZX_OFFSET_OFFSET;
1609                                 cur_optimum_ptr += longest_len;
1610                                 cur_optimum_ptr->mc_item_data =
1611                                         (offset_data << MC_OFFSET_SHIFT) |
1612                                         longest_len;
1613
1614                                 lzx_skip_bytes(c, longest_len - 1);
1615                                 break;
1616                         }
1617
1618                         /* If reaching any positions for the first time,
1619                          * initialize their costs to "infinity".  */
1620                         while (end_optimum_ptr < cur_optimum_ptr + longest_len)
1621                                 (++end_optimum_ptr)->cost = MC_INFINITE_COST;
1622
1623                         /* Consider coding an explicit offset match.  */
1624                         lzx_consider_explicit_offset_matches(c, cur_optimum_ptr,
1625                                                              matches, num_matches);
1626                 } else {
1627                         /* No matches found.  The only choice at this position
1628                          * is to code a literal.  */
1629
1630                         if (end_optimum_ptr == cur_optimum_ptr) {
1631                         #if 1
1632                                 /* Optimization for single literals.  */
1633                                 if (likely(cur_optimum_ptr == c->optimum)) {
1634                                         lzx_declare_literal(c, *window_ptr++,
1635                                                             next_chosen_item);
1636                                         if (window_ptr == block_end) {
1637                                                 c->queue = cur_optimum_ptr->queue;
1638                                                 return;
1639                                         }
1640                                         continue;
1641                                 }
1642                         #endif
1643                                 (++end_optimum_ptr)->cost = MC_INFINITE_COST;
1644                         }
1645                 }
1646
1647                 /* Consider coding a literal.
1648
1649                  * To avoid an extra unpredictable brench, actually checking the
1650                  * preferability of coding a literal is integrated into the
1651                  * queue update code below.  */
1652                 literal = *window_ptr++;
1653                 cost = cur_optimum_ptr->cost + lzx_literal_cost(literal, &c->costs);
1654
1655                 /* Advance to the next position.  */
1656                 cur_optimum_ptr++;
1657
1658                 /* The lowest-cost path to the current position is now known.
1659                  * Finalize the recent offsets queue that results from taking
1660                  * this lowest-cost path.  */
1661
1662                 if (cost < cur_optimum_ptr->cost) {
1663                         /* Literal: queue remains unchanged.  */
1664                         cur_optimum_ptr->cost = cost;
1665                         cur_optimum_ptr->mc_item_data = (literal << MC_OFFSET_SHIFT) | 1;
1666                         cur_optimum_ptr->queue = (cur_optimum_ptr - 1)->queue;
1667                 } else {
1668                         /* Match: queue update is needed.  */
1669                         len = cur_optimum_ptr->mc_item_data & MC_LEN_MASK;
1670                         offset_data = cur_optimum_ptr->mc_item_data >> MC_OFFSET_SHIFT;
1671                         if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1672                                 /* Explicit offset match: offset is inserted at front  */
1673                                 cur_optimum_ptr->queue.R[0] = offset_data - LZX_OFFSET_OFFSET;
1674                                 cur_optimum_ptr->queue.R[1] = (cur_optimum_ptr - len)->queue.R[0];
1675                                 cur_optimum_ptr->queue.R[2] = (cur_optimum_ptr - len)->queue.R[1];
1676                         } else {
1677                                 /* Repeat offset match: offset is swapped to front  */
1678                                 cur_optimum_ptr->queue = (cur_optimum_ptr - len)->queue;
1679                                 swap(cur_optimum_ptr->queue.R[0],
1680                                      cur_optimum_ptr->queue.R[offset_data]);
1681                         }
1682                 }
1683
1684                 /*
1685                  * This loop will terminate when either of the following
1686                  * conditions is true:
1687                  *
1688                  * (1) cur_optimum_ptr == end_optimum_ptr
1689                  *
1690                  *      There are no paths that extend beyond the current
1691                  *      position.  In this case, any path to a later position
1692                  *      must pass through the current position, so we can go
1693                  *      ahead and choose the list of items that led to this
1694                  *      position.
1695                  *
1696                  * (2) cur_optimum_ptr == &c->optimum[LZX_OPTIM_ARRAY_LENGTH]
1697                  *
1698                  *      This bounds the number of times the algorithm can step
1699                  *      forward before it is guaranteed to start choosing items.
1700                  *      This limits the memory usage.  But
1701                  *      LZX_OPTIM_ARRAY_LENGTH is high enough that on most
1702                  *      inputs this limit is never reached.
1703                  *
1704                  * Note: no check for end-of-block is needed because
1705                  * end-of-block will trigger condition (1).
1706                  */
1707                 if (cur_optimum_ptr == end_optimum_ptr ||
1708                     cur_optimum_ptr == &c->optimum[LZX_OPTIM_ARRAY_LENGTH])
1709                 {
1710                         begin_queue = &cur_optimum_ptr->queue;
1711                         break;
1712                 }
1713         }
1714
1715         /* Choose the current list of items that constitute the minimum-cost
1716          * path to the current position.  */
1717         lzx_declare_item_list(c, cur_optimum_ptr, next_chosen_item);
1718         goto begin;
1719 }
1720
1721 /* Fast heuristic scoring for lazy parsing: how "good" is this match?  */
1722 static inline unsigned
1723 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1724 {
1725         unsigned score = len;
1726
1727         if (adjusted_offset < 2048)
1728                 score++;
1729
1730         if (adjusted_offset < 1024)
1731                 score++;
1732
1733         return score;
1734 }
1735
1736 static inline unsigned
1737 lzx_repeat_offset_match_score(unsigned len, unsigned slot)
1738 {
1739         return len + 3;
1740 }
1741
1742 /* Lazy parsing  */
1743 static u32
1744 lzx_choose_lazy_items_for_block(struct lzx_compressor *c,
1745                                 u32 block_start_pos, u32 block_size)
1746 {
1747         const u8 *window_ptr;
1748         const u8 *block_end;
1749         struct lz_mf *mf;
1750         struct lz_match *matches;
1751         unsigned num_matches;
1752         unsigned cur_len;
1753         u32 cur_offset_data;
1754         unsigned cur_score;
1755         unsigned rep_max_len;
1756         unsigned rep_max_idx;
1757         unsigned rep_score;
1758         unsigned prev_len;
1759         unsigned prev_score;
1760         u32 prev_offset_data;
1761         unsigned skip_len;
1762         struct lzx_item *next_chosen_item;
1763
1764         window_ptr = &c->cur_window[block_start_pos];
1765         block_end = window_ptr + block_size;
1766         matches = c->cached_matches;
1767         mf = c->mf;
1768         next_chosen_item = c->chosen_items;
1769
1770         prev_len = 0;
1771         prev_offset_data = 0;
1772         prev_score = 0;
1773
1774         while (window_ptr != block_end) {
1775
1776                 /* Find explicit offset matches with the current position.  */
1777                 num_matches = lz_mf_get_matches(mf, matches);
1778                 window_ptr++;
1779
1780                 if (num_matches == 0 ||
1781                     (matches[num_matches - 1].len == 3 &&
1782                      matches[num_matches - 1].offset >= 8192 - LZX_OFFSET_OFFSET &&
1783                      matches[num_matches - 1].offset != c->queue.R[0] &&
1784                      matches[num_matches - 1].offset != c->queue.R[1] &&
1785                      matches[num_matches - 1].offset != c->queue.R[2]))
1786                 {
1787                         /* No match found, or the only match found was a distant
1788                          * length 3 match.  Output the previous match if there
1789                          * is one; otherwise output a literal.  */
1790
1791                 no_match_found:
1792
1793                         if (prev_len) {
1794                                 skip_len = prev_len - 2;
1795                                 goto output_prev_match;
1796                         } else {
1797                                 lzx_declare_literal(c, *(window_ptr - 1),
1798                                                     &next_chosen_item);
1799                                 continue;
1800                         }
1801                 }
1802
1803                 /* Find the longest repeat offset match with the current
1804                  * position.  */
1805                 if (likely(block_end - (window_ptr - 1) >= 2)) {
1806                         rep_max_len = lzx_repsearch((window_ptr - 1),
1807                                                     block_end - (window_ptr - 1),
1808                                                     &c->queue, &rep_max_idx);
1809                 } else {
1810                         rep_max_len = 0;
1811                 }
1812
1813                 cur_len = matches[num_matches - 1].len;
1814                 cur_offset_data = matches[num_matches - 1].offset + LZX_OFFSET_OFFSET;
1815                 cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
1816
1817                 /* Select the better of the explicit and repeat offset matches.  */
1818                 if (rep_max_len >= 3 &&
1819                     (rep_score = lzx_repeat_offset_match_score(rep_max_len,
1820                                                                rep_max_idx)) >= cur_score)
1821                 {
1822                         cur_len = rep_max_len;
1823                         cur_offset_data = rep_max_idx;
1824                         cur_score = rep_score;
1825                 }
1826
1827                 if (unlikely(cur_len > block_end - (window_ptr - 1))) {
1828                         /* Nearing end of block.  */
1829                         cur_len = block_end - (window_ptr - 1);
1830                         if (cur_len < 3)
1831                                 goto no_match_found;
1832                 }
1833
1834                 if (prev_len == 0 || cur_score > prev_score) {
1835                         /* No previous match, or the current match is better
1836                          * than the previous match.
1837                          *
1838                          * If there's a previous match, then output a literal in
1839                          * its place.
1840                          *
1841                          * In both cases, if the current match is very long,
1842                          * then output it immediately.  Otherwise, attempt a
1843                          * lazy match by waiting to see if there's a better
1844                          * match at the next position.  */
1845
1846                         if (prev_len)
1847                                 lzx_declare_literal(c, *(window_ptr - 2), &next_chosen_item);
1848
1849                         prev_len = cur_len;
1850                         prev_offset_data = cur_offset_data;
1851                         prev_score = cur_score;
1852
1853                         if (prev_len >= c->params.nice_match_length) {
1854                                 skip_len = prev_len - 1;
1855                                 goto output_prev_match;
1856                         }
1857                         continue;
1858                 }
1859
1860                 /* Current match is not better than the previous match, so
1861                  * output the previous match.  */
1862
1863                 skip_len = prev_len - 2;
1864
1865         output_prev_match:
1866                 if (prev_offset_data < LZX_NUM_RECENT_OFFSETS) {
1867                         lzx_declare_repeat_offset_match(c, prev_len,
1868                                                         prev_offset_data,
1869                                                         &next_chosen_item);
1870                         swap(c->queue.R[0], c->queue.R[prev_offset_data]);
1871                 } else {
1872                         lzx_declare_explicit_offset_match(c, prev_len,
1873                                                           prev_offset_data - LZX_OFFSET_OFFSET,
1874                                                           &next_chosen_item);
1875                         c->queue.R[2] = c->queue.R[1];
1876                         c->queue.R[1] = c->queue.R[0];
1877                         c->queue.R[0] = prev_offset_data - LZX_OFFSET_OFFSET;
1878                 }
1879                 lz_mf_skip_positions(mf, skip_len);
1880                 window_ptr += skip_len;
1881                 prev_len = 0;
1882         }
1883
1884         return next_chosen_item - c->chosen_items;
1885 }
1886
1887 /* Given the frequencies of symbols in an LZX-compressed block and the
1888  * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1889  * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1890  * will take fewer bits to output.  */
1891 static int
1892 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1893                                const struct lzx_codes * codes)
1894 {
1895         unsigned aligned_cost = 0;
1896         unsigned verbatim_cost = 0;
1897
1898         /* A verbatim block require 3 bits in each place that an aligned symbol
1899          * was used.  */
1900         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1901                 verbatim_cost += 3 * freqs->aligned[i];
1902                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1903         }
1904
1905         /* Account for output of the aligned offset code.  */
1906         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1907
1908         if (aligned_cost < verbatim_cost)
1909                 return LZX_BLOCKTYPE_ALIGNED;
1910         else
1911                 return LZX_BLOCKTYPE_VERBATIM;
1912 }
1913
1914 /* Near-optimal parsing  */
1915 static u32
1916 lzx_choose_near_optimal_items_for_block(struct lzx_compressor *c,
1917                                         u32 block_start_pos, u32 block_size)
1918 {
1919         u32 num_passes_remaining = c->params.num_optim_passes;
1920         struct lzx_lru_queue orig_queue;
1921         struct lzx_item *next_chosen_item;
1922         struct lzx_item **next_chosen_item_ptr;
1923
1924         /* Choose appropriate match-finder wrapper functions.  */
1925         if (num_passes_remaining > 1) {
1926                 if (block_size == c->cur_window_size)
1927                         c->get_matches_func = lzx_get_matches_fillcache_singleblock;
1928                 else
1929                         c->get_matches_func = lzx_get_matches_fillcache_multiblock;
1930                 c->skip_bytes_func = lzx_skip_bytes_fillcache;
1931         } else {
1932                 if (block_size == c->cur_window_size)
1933                         c->get_matches_func = lzx_get_matches_nocache_singleblock;
1934                 else
1935                         c->get_matches_func = lzx_get_matches_nocache_multiblock;
1936                 c->skip_bytes_func = lzx_skip_bytes_nocache;
1937         }
1938
1939         /* No matches will extend beyond the end of the block.  */
1940         c->match_window_end = block_start_pos + block_size;
1941
1942         /* The first optimization pass will use a default cost model.  Each
1943          * additional optimization pass will use a cost model computed from the
1944          * previous pass.
1945          *
1946          * To improve performance we only generate the array containing the
1947          * matches and literals in intermediate form on the final pass.  For
1948          * earlier passes, tallying symbol frequencies is sufficient.  */
1949         lzx_set_default_costs(&c->costs, c->num_main_syms);
1950
1951         next_chosen_item_ptr = NULL;
1952         orig_queue = c->queue;
1953         do {
1954                 /* Reset the match-finder wrapper.  */
1955                 c->match_window_pos = block_start_pos;
1956                 c->cache_ptr = c->cached_matches;
1957
1958                 if (num_passes_remaining == 1) {
1959                         /* Last pass: actually generate the items.  */
1960                         next_chosen_item = c->chosen_items;
1961                         next_chosen_item_ptr = &next_chosen_item;
1962                 }
1963
1964                 /* Choose the items.  */
1965                 lzx_optim_pass(c, next_chosen_item_ptr);
1966
1967                 if (num_passes_remaining > 1) {
1968                         /* This isn't the last pass.  */
1969
1970                         /* Make the Huffman codes from the symbol frequencies.  */
1971                         lzx_make_huffman_codes(&c->freqs, &c->codes[c->codes_index],
1972                                                c->num_main_syms);
1973
1974                         /* Update symbol costs.  */
1975                         lzx_set_costs(c, &c->codes[c->codes_index].lens);
1976
1977                         /* Reset symbol frequencies.  */
1978                         memset(&c->freqs, 0, sizeof(c->freqs));
1979
1980                         /* Reset the match offset LRU queue to what it was at
1981                          * the beginning of the block.  */
1982                         c->queue = orig_queue;
1983
1984                         /* Choose appopriate match-finder wrapper functions.  */
1985                         if (c->cache_ptr <= c->cache_limit) {
1986                                 c->get_matches_func = lzx_get_matches_usecache_nocheck;
1987                                 c->skip_bytes_func = lzx_skip_bytes_usecache_nocheck;
1988                         } else {
1989                                 c->get_matches_func = lzx_get_matches_usecache;
1990                                 c->skip_bytes_func = lzx_skip_bytes_usecache;
1991                         }
1992                 }
1993         } while (--num_passes_remaining);
1994
1995         /* Return the number of items chosen.  */
1996         return next_chosen_item - c->chosen_items;
1997 }
1998
1999 /*
2000  * Choose the matches/literals with which to output the block of data beginning
2001  * at '&c->cur_window[block_start_pos]' and extending for 'block_size' bytes.
2002  *
2003  * The frequences of the Huffman symbols in the block will be tallied in
2004  * 'c->freqs'.
2005  *
2006  * 'c->queue' must specify the state of the queue at the beginning of this block.
2007  * This function will update it to the state of the queue at the end of this
2008  * block.
2009  *
2010  * Returns the number of matches/literals that were chosen and written to
2011  * 'c->chosen_items' in the 'struct lzx_item' intermediate representation.
2012  */
2013 static u32
2014 lzx_choose_items_for_block(struct lzx_compressor *c,
2015                            u32 block_start_pos, u32 block_size)
2016 {
2017         return (*c->params.choose_items_for_block)(c, block_start_pos, block_size);
2018 }
2019
2020 /* Initialize c->offset_slot_fast.  */
2021 static void
2022 lzx_init_offset_slot_fast(struct lzx_compressor *c)
2023 {
2024         u8 slot = 0;
2025
2026         for (u32 offset = 0; offset < LZX_NUM_FAST_OFFSETS; offset++) {
2027
2028                 while (offset + LZX_OFFSET_OFFSET >= lzx_offset_slot_base[slot + 1])
2029                         slot++;
2030
2031                 c->offset_slot_fast[offset] = slot;
2032         }
2033 }
2034
2035 /* Set internal compression parameters for the specified compression level and
2036  * maximum window size.  */
2037 static void
2038 lzx_build_params(unsigned int compression_level, u32 max_window_size,
2039                  struct lzx_compressor_params *lzx_params)
2040 {
2041         if (compression_level < 25) {
2042
2043                 /* Fast compression: Use lazy parsing.  */
2044
2045                 lzx_params->choose_items_for_block = lzx_choose_lazy_items_for_block;
2046                 lzx_params->num_optim_passes = 1;
2047
2048                 /* When lazy parsing, the hash chain match-finding algorithm is
2049                  * fastest unless the window is too large.
2050                  *
2051                  * TODO: something like hash arrays would actually be better
2052                  * than binary trees on large windows.  */
2053                 if (max_window_size <= 262144)
2054                         lzx_params->mf_algo = LZ_MF_HASH_CHAINS;
2055                 else
2056                         lzx_params->mf_algo = LZ_MF_BINARY_TREES;
2057
2058                 /* When lazy parsing, don't bother with length 2 matches.  */
2059                 lzx_params->min_match_length = 3;
2060
2061                 /* Scale nice_match_length and max_search_depth with the
2062                  * compression level.  */
2063                 lzx_params->nice_match_length = 25 + compression_level * 2;
2064                 lzx_params->max_search_depth = 25 + compression_level;
2065         } else {
2066
2067                 /* Normal / high compression: Use near-optimal parsing.  */
2068
2069                 lzx_params->choose_items_for_block = lzx_choose_near_optimal_items_for_block;
2070
2071                 /* Set a number of optimization passes appropriate for the
2072                  * compression level.  */
2073
2074                 lzx_params->num_optim_passes = 1;
2075
2076                 if (compression_level >= 40)
2077                         lzx_params->num_optim_passes++;
2078
2079                 /* Use more optimization passes for higher compression levels.
2080                  * But the more passes there are, the less they help --- so
2081                  * don't add them linearly.  */
2082                 if (compression_level >= 70) {
2083                         lzx_params->num_optim_passes++;
2084                         if (compression_level >= 100)
2085                                 lzx_params->num_optim_passes++;
2086                         if (compression_level >= 150)
2087                                 lzx_params->num_optim_passes++;
2088                         if (compression_level >= 200)
2089                                 lzx_params->num_optim_passes++;
2090                         if (compression_level >= 300)
2091                                 lzx_params->num_optim_passes++;
2092                 }
2093
2094                 /* When doing near-optimal parsing, the hash chain match-finding
2095                  * algorithm is good if the window size is small and we're only
2096                  * doing one optimization pass.  Otherwise, the binary tree
2097                  * algorithm is the way to go.  */
2098                 if (max_window_size <= 32768 && lzx_params->num_optim_passes == 1)
2099                         lzx_params->mf_algo = LZ_MF_HASH_CHAINS;
2100                 else
2101                         lzx_params->mf_algo = LZ_MF_BINARY_TREES;
2102
2103                 /* When doing near-optimal parsing, allow length 2 matches if
2104                  * the compression level is sufficiently high.  */
2105                 if (compression_level >= 45)
2106                         lzx_params->min_match_length = 2;
2107                 else
2108                         lzx_params->min_match_length = 3;
2109
2110                 /* Scale nice_match_length and max_search_depth with the
2111                  * compression level.  */
2112                 lzx_params->nice_match_length = min(((u64)compression_level * 32) / 50,
2113                                                     LZX_MAX_MATCH_LEN);
2114                 lzx_params->max_search_depth = min(((u64)compression_level * 50) / 50,
2115                                                    LZX_MAX_MATCH_LEN);
2116         }
2117 }
2118
2119 /* Given the internal compression parameters and maximum window size, build the
2120  * Lempel-Ziv match-finder parameters.  */
2121 static void
2122 lzx_build_mf_params(const struct lzx_compressor_params *lzx_params,
2123                     u32 max_window_size, struct lz_mf_params *mf_params)
2124 {
2125         memset(mf_params, 0, sizeof(*mf_params));
2126
2127         mf_params->algorithm = lzx_params->mf_algo;
2128         mf_params->max_window_size = max_window_size;
2129         mf_params->min_match_len = lzx_params->min_match_length;
2130         mf_params->max_match_len = LZX_MAX_MATCH_LEN;
2131         mf_params->max_search_depth = lzx_params->max_search_depth;
2132         mf_params->nice_match_len = lzx_params->nice_match_length;
2133 }
2134
2135 static void
2136 lzx_free_compressor(void *_c);
2137
2138 static u64
2139 lzx_get_needed_memory(size_t max_block_size, unsigned int compression_level)
2140 {
2141         struct lzx_compressor_params params;
2142         u64 size = 0;
2143         unsigned window_order;
2144         u32 max_window_size;
2145
2146         window_order = lzx_get_window_order(max_block_size);
2147         if (window_order == 0)
2148                 return 0;
2149         max_window_size = max_block_size;
2150
2151         lzx_build_params(compression_level, max_window_size, &params);
2152
2153         size += sizeof(struct lzx_compressor);
2154
2155         /* cur_window */
2156         size += max_window_size;
2157
2158         /* mf */
2159         size += lz_mf_get_needed_memory(params.mf_algo, max_window_size);
2160
2161         /* cached_matches */
2162         if (params.num_optim_passes > 1)
2163                 size += LZX_CACHE_LEN * sizeof(struct lz_match);
2164         else
2165                 size += LZX_MAX_MATCHES_PER_POS * sizeof(struct lz_match);
2166         return size;
2167 }
2168
2169 static int
2170 lzx_create_compressor(size_t max_block_size, unsigned int compression_level,
2171                       void **c_ret)
2172 {
2173         struct lzx_compressor *c;
2174         struct lzx_compressor_params params;
2175         struct lz_mf_params mf_params;
2176         unsigned window_order;
2177         u32 max_window_size;
2178
2179         window_order = lzx_get_window_order(max_block_size);
2180         if (window_order == 0)
2181                 return WIMLIB_ERR_INVALID_PARAM;
2182         max_window_size = max_block_size;
2183
2184         lzx_build_params(compression_level, max_window_size, &params);
2185         lzx_build_mf_params(&params, max_window_size, &mf_params);
2186         if (!lz_mf_params_valid(&mf_params))
2187                 return WIMLIB_ERR_INVALID_PARAM;
2188
2189         c = CALLOC(1, sizeof(struct lzx_compressor));
2190         if (!c)
2191                 goto oom;
2192
2193         c->params = params;
2194         c->num_main_syms = lzx_get_num_main_syms(window_order);
2195         c->window_order = window_order;
2196
2197         /* The window is allocated as 16-byte aligned to speed up memcpy() and
2198          * enable lzx_e8_filter() optimization on x86_64.  */
2199         c->cur_window = ALIGNED_MALLOC(max_window_size, 16);
2200         if (!c->cur_window)
2201                 goto oom;
2202
2203         c->mf = lz_mf_alloc(&mf_params);
2204         if (!c->mf)
2205                 goto oom;
2206
2207         if (params.num_optim_passes > 1) {
2208                 c->cached_matches = MALLOC(LZX_CACHE_LEN *
2209                                            sizeof(struct lz_match));
2210                 if (!c->cached_matches)
2211                         goto oom;
2212                 c->cache_limit = c->cached_matches + LZX_CACHE_LEN -
2213                                  (LZX_MAX_MATCHES_PER_POS + 1);
2214         } else {
2215                 c->cached_matches = MALLOC(LZX_MAX_MATCHES_PER_POS *
2216                                            sizeof(struct lz_match));
2217                 if (!c->cached_matches)
2218                         goto oom;
2219         }
2220
2221         lzx_init_offset_slot_fast(c);
2222
2223         *c_ret = c;
2224         return 0;
2225
2226 oom:
2227         lzx_free_compressor(c);
2228         return WIMLIB_ERR_NOMEM;
2229 }
2230
2231 static size_t
2232 lzx_compress(const void *uncompressed_data, size_t uncompressed_size,
2233              void *compressed_data, size_t compressed_size_avail, void *_c)
2234 {
2235         struct lzx_compressor *c = _c;
2236         struct lzx_output_bitstream os;
2237         u32 num_chosen_items;
2238         const struct lzx_lens *prev_lens;
2239         u32 block_start_pos;
2240         u32 block_size;
2241         int block_type;
2242
2243         /* Don't bother compressing very small inputs.  */
2244         if (uncompressed_size < 100)
2245                 return 0;
2246
2247         /* The input data must be preprocessed.  To avoid changing the original
2248          * input data, copy it to a temporary buffer.  */
2249         memcpy(c->cur_window, uncompressed_data, uncompressed_size);
2250         c->cur_window_size = uncompressed_size;
2251
2252         /* Preprocess the data.  */
2253         lzx_do_e8_preprocessing(c->cur_window, c->cur_window_size);
2254
2255         /* Load the window into the match-finder.  */
2256         lz_mf_load_window(c->mf, c->cur_window, c->cur_window_size);
2257
2258         /* Initialize the match offset LRU queue.  */
2259         lzx_lru_queue_init(&c->queue);
2260
2261         /* Initialize the output bitstream.  */
2262         lzx_init_output(&os, compressed_data, compressed_size_avail);
2263
2264         /* Compress the data block by block.
2265          *
2266          * TODO: The compression ratio could be slightly improved by performing
2267          * data-dependent block splitting instead of using fixed-size blocks.
2268          * Doing so well is a computationally hard problem, however.  */
2269         block_start_pos = 0;
2270         c->codes_index = 0;
2271         prev_lens = &c->zero_lens;
2272         do {
2273                 /* Compute the block size.  */
2274                 block_size = min(LZX_DIV_BLOCK_SIZE,
2275                                  uncompressed_size - block_start_pos);
2276
2277                 /* Reset symbol frequencies.  */
2278                 memset(&c->freqs, 0, sizeof(c->freqs));
2279
2280                 /* Prepare the matches/literals for the block.  */
2281                 num_chosen_items = lzx_choose_items_for_block(c,
2282                                                               block_start_pos,
2283                                                               block_size);
2284
2285                 /* Make the Huffman codes from the symbol frequencies.  */
2286                 lzx_make_huffman_codes(&c->freqs, &c->codes[c->codes_index],
2287                                        c->num_main_syms);
2288
2289                 /* Choose the best block type.
2290                  *
2291                  * Note: we currently don't consider uncompressed blocks.  */
2292                 block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
2293                                                             &c->codes[c->codes_index]);
2294
2295                 /* Write the compressed block to the output buffer.  */
2296                 lzx_write_compressed_block(block_type,
2297                                            block_size,
2298                                            c->window_order,
2299                                            c->num_main_syms,
2300                                            c->chosen_items,
2301                                            num_chosen_items,
2302                                            &c->codes[c->codes_index],
2303                                            prev_lens,
2304                                            &os);
2305
2306                 /* The current codeword lengths become the previous lengths.  */
2307                 prev_lens = &c->codes[c->codes_index].lens;
2308                 c->codes_index ^= 1;
2309
2310                 block_start_pos += block_size;
2311
2312         } while (block_start_pos != uncompressed_size);
2313
2314         return lzx_flush_output(&os);
2315 }
2316
2317 static void
2318 lzx_free_compressor(void *_c)
2319 {
2320         struct lzx_compressor *c = _c;
2321
2322         if (c) {
2323                 ALIGNED_FREE(c->cur_window);
2324                 lz_mf_free(c->mf);
2325                 FREE(c->cached_matches);
2326                 FREE(c);
2327         }
2328 }
2329
2330 const struct compressor_ops lzx_compressor_ops = {
2331         .get_needed_memory  = lzx_get_needed_memory,
2332         .create_compressor  = lzx_create_compressor,
2333         .compress           = lzx_compress,
2334         .free_compressor    = lzx_free_compressor,
2335 };