Introduce ilog2_ceil()
[wimlib] / src / lzx_compress.c
1 /*
2  * lzx_compress.c
3  *
4  * A compressor for the LZX compression format, as used in WIM files.
5  */
6
7 /*
8  * Copyright (C) 2012, 2013, 2014, 2015 Eric Biggers
9  *
10  * This file is free software; you can redistribute it and/or modify it under
11  * the terms of the GNU Lesser General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option) any
13  * later version.
14  *
15  * This file is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this file; if not, see http://www.gnu.org/licenses/.
22  */
23
24
25 /*
26  * This file contains a compressor for the LZX ("Lempel-Ziv eXtended")
27  * compression format, as used in the WIM (Windows IMaging) file format.
28  *
29  * Two different parsing algorithms are implemented: "near-optimal" and "lazy".
30  * "Near-optimal" is significantly slower than "lazy", but results in a better
31  * compression ratio.  The "near-optimal" algorithm is used at the default
32  * compression level.
33  *
34  * This file may need some slight modifications to be used outside of the WIM
35  * format.  In particular, in other situations the LZX block header might be
36  * slightly different, and sliding window support might be required.
37  *
38  * Note: LZX is a compression format derived from DEFLATE, the format used by
39  * zlib and gzip.  Both LZX and DEFLATE use LZ77 matching and Huffman coding.
40  * Certain details are quite similar, such as the method for storing Huffman
41  * codes.  However, the main differences are:
42  *
43  * - LZX preprocesses the data to attempt to make x86 machine code slightly more
44  *   compressible before attempting to compress it further.
45  *
46  * - LZX uses a "main" alphabet which combines literals and matches, with the
47  *   match symbols containing a "length header" (giving all or part of the match
48  *   length) and an "offset slot" (giving, roughly speaking, the order of
49  *   magnitude of the match offset).
50  *
51  * - LZX does not have static Huffman blocks (that is, the kind with preset
52  *   Huffman codes); however it does have two types of dynamic Huffman blocks
53  *   ("verbatim" and "aligned").
54  *
55  * - LZX has a minimum match length of 2 rather than 3.  Length 2 matches can be
56  *   useful, but generally only if the parser is smart about choosing them.
57  *
58  * - In LZX, offset slots 0 through 2 actually represent entries in an LRU queue
59  *   of match offsets.  This is very useful for certain types of files, such as
60  *   binary files that have repeating records.
61  */
62
63 #ifdef HAVE_CONFIG_H
64 #  include "config.h"
65 #endif
66
67 /*
68  * Start a new LZX block (with new Huffman codes) after this many bytes.
69  *
70  * Note: actual block sizes may slightly exceed this value.
71  *
72  * TODO: recursive splitting and cost evaluation might be good for an extremely
73  * high compression mode, but otherwise it is almost always far too slow for how
74  * much it helps.  Perhaps some sort of heuristic would be useful?
75  */
76 #define LZX_DIV_BLOCK_SIZE      32768
77
78 /*
79  * LZX_CACHE_PER_POS is the number of lz_match structures to reserve in the
80  * match cache for each byte position.  This value should be high enough so that
81  * nearly the time, all matches found in a given block can fit in the match
82  * cache.  However, fallback behavior (immediately terminating the block) on
83  * cache overflow is still required.
84  */
85 #define LZX_CACHE_PER_POS       7
86
87 /*
88  * LZX_CACHE_LENGTH is the number of lz_match structures in the match cache,
89  * excluding the extra "overflow" entries.  The per-position multiplier is '1 +
90  * LZX_CACHE_PER_POS' instead of 'LZX_CACHE_PER_POS' because there is an
91  * overhead of one lz_match per position, used to hold the match count at that
92  * position.
93  */
94 #define LZX_CACHE_LENGTH        (LZX_DIV_BLOCK_SIZE * (1 + LZX_CACHE_PER_POS))
95
96 /*
97  * LZX_MAX_MATCHES_PER_POS is an upper bound on the number of matches that can
98  * ever be saved in the match cache for a single position.  Since each match we
99  * save for a single position has a distinct length, we can use the number of
100  * possible match lengths in LZX as this bound.  This bound is guaranteed to be
101  * valid in all cases, although if 'nice_match_length < LZX_MAX_MATCH_LEN', then
102  * it will never actually be reached.
103  */
104 #define LZX_MAX_MATCHES_PER_POS LZX_NUM_LENS
105
106 /*
107  * LZX_BIT_COST is a scaling factor that represents the cost to output one bit.
108  * This makes it possible to consider fractional bit costs.
109  *
110  * Note: this is only useful as a statistical trick for when the true costs are
111  * unknown.  In reality, each token in LZX requires a whole number of bits to
112  * output.
113  */
114 #define LZX_BIT_COST            16
115
116 /*
117  * Should the compressor take into account the costs of aligned offset symbols?
118  */
119 #define LZX_CONSIDER_ALIGNED_COSTS      1
120
121 /*
122  * LZX_MAX_FAST_LEVEL is the maximum compression level at which we use the
123  * faster algorithm.
124  */
125 #define LZX_MAX_FAST_LEVEL      34
126
127 /*
128  * BT_MATCHFINDER_HASH2_ORDER is the log base 2 of the number of entries in the
129  * hash table for finding length 2 matches.  This could be as high as 16, but
130  * using a smaller hash table speeds up compression due to reduced cache
131  * pressure.
132  */
133 #define BT_MATCHFINDER_HASH2_ORDER      12
134
135 /*
136  * These are the compressor-side limits on the codeword lengths for each Huffman
137  * code.  To make outputting bits slightly faster, some of these limits are
138  * lower than the limits defined by the LZX format.  This does not significantly
139  * affect the compression ratio, at least for the block sizes we use.
140  */
141 #define MAIN_CODEWORD_LIMIT     12      /* 64-bit: can buffer 4 main symbols  */
142 #define LENGTH_CODEWORD_LIMIT   12
143 #define ALIGNED_CODEWORD_LIMIT  7
144 #define PRE_CODEWORD_LIMIT      7
145
146 #include "wimlib/compress_common.h"
147 #include "wimlib/compressor_ops.h"
148 #include "wimlib/error.h"
149 #include "wimlib/lz_extend.h"
150 #include "wimlib/lzx_common.h"
151 #include "wimlib/unaligned.h"
152 #include "wimlib/util.h"
153
154 /* Matchfinders with 16-bit positions  */
155 #define mf_pos_t        u16
156 #define MF_SUFFIX       _16
157 #include "wimlib/bt_matchfinder.h"
158 #include "wimlib/hc_matchfinder.h"
159
160 /* Matchfinders with 32-bit positions  */
161 #undef mf_pos_t
162 #undef MF_SUFFIX
163 #define mf_pos_t        u32
164 #define MF_SUFFIX       _32
165 #include "wimlib/bt_matchfinder.h"
166 #include "wimlib/hc_matchfinder.h"
167
168 struct lzx_output_bitstream;
169
170 /* Codewords for the LZX Huffman codes.  */
171 struct lzx_codewords {
172         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
173         u32 len[LZX_LENCODE_NUM_SYMBOLS];
174         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
175 };
176
177 /* Codeword lengths (in bits) for the LZX Huffman codes.
178  * A zero length means the corresponding codeword has zero frequency.  */
179 struct lzx_lens {
180         u8 main[LZX_MAINCODE_MAX_NUM_SYMBOLS + 1];
181         u8 len[LZX_LENCODE_NUM_SYMBOLS + 1];
182         u8 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
183 };
184
185 /* Cost model for near-optimal parsing  */
186 struct lzx_costs {
187
188         /* 'match_cost[offset_slot][len - LZX_MIN_MATCH_LEN]' is the cost for a
189          * length 'len' match that has an offset belonging to 'offset_slot'.  */
190         u32 match_cost[LZX_MAX_OFFSET_SLOTS][LZX_NUM_LENS];
191
192         /* Cost for each symbol in the main code  */
193         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
194
195         /* Cost for each symbol in the length code  */
196         u32 len[LZX_LENCODE_NUM_SYMBOLS];
197
198 #if LZX_CONSIDER_ALIGNED_COSTS
199         /* Cost for each symbol in the aligned code  */
200         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
201 #endif
202 };
203
204 /* Codewords and lengths for the LZX Huffman codes.  */
205 struct lzx_codes {
206         struct lzx_codewords codewords;
207         struct lzx_lens lens;
208 };
209
210 /* Symbol frequency counters for the LZX Huffman codes.  */
211 struct lzx_freqs {
212         u32 main[LZX_MAINCODE_MAX_NUM_SYMBOLS];
213         u32 len[LZX_LENCODE_NUM_SYMBOLS];
214         u32 aligned[LZX_ALIGNEDCODE_NUM_SYMBOLS];
215 };
216
217 /*
218  * Represents a run of literals followed by a match or end-of-block.  This
219  * struct is needed to temporarily store items chosen by the parser, since items
220  * cannot be written until all items for the block have been chosen and the
221  * block's Huffman codes have been computed.
222  */
223 struct lzx_sequence {
224
225         /* The number of literals in the run.  This may be 0.  The literals are
226          * not stored explicitly in this structure; instead, they are read
227          * directly from the uncompressed data.  */
228         u16 litrunlen;
229
230         /* If the next field doesn't indicate end-of-block, then this is the
231          * match length minus LZX_MIN_MATCH_LEN.  */
232         u16 adjusted_length;
233
234         /* If bit 31 is clear, then this field contains the match header in bits
235          * 0-8, and either the match offset plus LZX_OFFSET_ADJUSTMENT or a
236          * recent offset code in bits 9-30.  Otherwise (if bit 31 is set), this
237          * sequence's literal run was the last literal run in the block, so
238          * there is no match that follows it.  */
239         u32 adjusted_offset_and_match_hdr;
240 };
241
242 /*
243  * This structure represents a byte position in the input buffer and a node in
244  * the graph of possible match/literal choices.
245  *
246  * Logically, each incoming edge to this node is labeled with a literal or a
247  * match that can be taken to reach this position from an earlier position; and
248  * each outgoing edge from this node is labeled with a literal or a match that
249  * can be taken to advance from this position to a later position.
250  */
251 struct lzx_optimum_node {
252
253         /* The cost, in bits, of the lowest-cost path that has been found to
254          * reach this position.  This can change as progressively lower cost
255          * paths are found to reach this position.  */
256         u32 cost;
257
258         /*
259          * The match or literal that was taken to reach this position.  This can
260          * change as progressively lower cost paths are found to reach this
261          * position.
262          *
263          * This variable is divided into two bitfields.
264          *
265          * Literals:
266          *      Low bits are 0, high bits are the literal.
267          *
268          * Explicit offset matches:
269          *      Low bits are the match length, high bits are the offset plus 2.
270          *
271          * Repeat offset matches:
272          *      Low bits are the match length, high bits are the queue index.
273          */
274         u32 item;
275 #define OPTIMUM_OFFSET_SHIFT 9
276 #define OPTIMUM_LEN_MASK ((1 << OPTIMUM_OFFSET_SHIFT) - 1)
277 } _aligned_attribute(8);
278
279 /*
280  * Least-recently-used queue for match offsets.
281  *
282  * This is represented as a 64-bit integer for efficiency.  There are three
283  * offsets of 21 bits each.  Bit 64 is garbage.
284  */
285 struct lzx_lru_queue {
286         u64 R;
287 };
288
289 #define LZX_QUEUE64_OFFSET_SHIFT 21
290 #define LZX_QUEUE64_OFFSET_MASK (((u64)1 << LZX_QUEUE64_OFFSET_SHIFT) - 1)
291
292 #define LZX_QUEUE64_R0_SHIFT (0 * LZX_QUEUE64_OFFSET_SHIFT)
293 #define LZX_QUEUE64_R1_SHIFT (1 * LZX_QUEUE64_OFFSET_SHIFT)
294 #define LZX_QUEUE64_R2_SHIFT (2 * LZX_QUEUE64_OFFSET_SHIFT)
295
296 #define LZX_QUEUE64_R0_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R0_SHIFT)
297 #define LZX_QUEUE64_R1_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R1_SHIFT)
298 #define LZX_QUEUE64_R2_MASK (LZX_QUEUE64_OFFSET_MASK << LZX_QUEUE64_R2_SHIFT)
299
300 static inline void
301 lzx_lru_queue_init(struct lzx_lru_queue *queue)
302 {
303         queue->R = ((u64)1 << LZX_QUEUE64_R0_SHIFT) |
304                    ((u64)1 << LZX_QUEUE64_R1_SHIFT) |
305                    ((u64)1 << LZX_QUEUE64_R2_SHIFT);
306 }
307
308 static inline u64
309 lzx_lru_queue_R0(struct lzx_lru_queue queue)
310 {
311         return (queue.R >> LZX_QUEUE64_R0_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
312 }
313
314 static inline u64
315 lzx_lru_queue_R1(struct lzx_lru_queue queue)
316 {
317         return (queue.R >> LZX_QUEUE64_R1_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
318 }
319
320 static inline u64
321 lzx_lru_queue_R2(struct lzx_lru_queue queue)
322 {
323         return (queue.R >> LZX_QUEUE64_R2_SHIFT) & LZX_QUEUE64_OFFSET_MASK;
324 }
325
326 /* Push a match offset onto the front (most recently used) end of the queue.  */
327 static inline struct lzx_lru_queue
328 lzx_lru_queue_push(struct lzx_lru_queue queue, u32 offset)
329 {
330         return (struct lzx_lru_queue) {
331                 .R = (queue.R << LZX_QUEUE64_OFFSET_SHIFT) | offset,
332         };
333 }
334
335 /* Swap a match offset to the front of the queue.  */
336 static inline struct lzx_lru_queue
337 lzx_lru_queue_swap(struct lzx_lru_queue queue, unsigned idx)
338 {
339         if (idx == 0)
340                 return queue;
341
342         if (idx == 1)
343                 return (struct lzx_lru_queue) {
344                         .R = (lzx_lru_queue_R1(queue) << LZX_QUEUE64_R0_SHIFT) |
345                              (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R1_SHIFT) |
346                              (queue.R & LZX_QUEUE64_R2_MASK),
347                 };
348
349         return (struct lzx_lru_queue) {
350                 .R = (lzx_lru_queue_R2(queue) << LZX_QUEUE64_R0_SHIFT) |
351                      (queue.R & LZX_QUEUE64_R1_MASK) |
352                      (lzx_lru_queue_R0(queue) << LZX_QUEUE64_R2_SHIFT),
353         };
354 }
355
356 /* The main LZX compressor structure  */
357 struct lzx_compressor {
358
359         /* The "nice" match length: if a match of this length is found, then
360          * choose it immediately without further consideration.  */
361         unsigned nice_match_length;
362
363         /* The maximum search depth: consider at most this many potential
364          * matches at each position.  */
365         unsigned max_search_depth;
366
367         /* The log base 2 of the LZX window size for LZ match offset encoding
368          * purposes.  This will be >= LZX_MIN_WINDOW_ORDER and <=
369          * LZX_MAX_WINDOW_ORDER.  */
370         unsigned window_order;
371
372         /* The number of symbols in the main alphabet.  This depends on
373          * @window_order, since @window_order determines the maximum possible
374          * offset.  */
375         unsigned num_main_syms;
376
377         /* Number of optimization passes per block  */
378         unsigned num_optim_passes;
379
380         /* The preprocessed buffer of data being compressed  */
381         u8 *in_buffer;
382
383         /* The number of bytes of data to be compressed, which is the number of
384          * bytes of data in @in_buffer that are actually valid.  */
385         size_t in_nbytes;
386
387         /* Pointer to the compress() implementation chosen at allocation time */
388         void (*impl)(struct lzx_compressor *, struct lzx_output_bitstream *);
389
390         /* If true, the compressor need not preserve the input buffer if it
391          * compresses the data successfully.  */
392         bool destructive;
393
394         /* The Huffman symbol frequency counters for the current block.  */
395         struct lzx_freqs freqs;
396
397         /* The Huffman codes for the current and previous blocks.  The one with
398          * index 'codes_index' is for the current block, and the other one is
399          * for the previous block.  */
400         struct lzx_codes codes[2];
401         unsigned codes_index;
402
403         /* The matches and literals that the parser has chosen for the current
404          * block.  The required length of this array is limited by the maximum
405          * number of matches that can ever be chosen for a single block, plus
406          * one for the special entry at the end.  */
407         struct lzx_sequence chosen_sequences[
408                        DIV_ROUND_UP(LZX_DIV_BLOCK_SIZE, LZX_MIN_MATCH_LEN) + 1];
409
410         /* Tables for mapping adjusted offsets to offset slots  */
411
412         /* offset slots [0, 29]  */
413         u8 offset_slot_tab_1[32768];
414
415         /* offset slots [30, 49]  */
416         u8 offset_slot_tab_2[128];
417
418         union {
419                 /* Data for greedy or lazy parsing  */
420                 struct {
421                         /* Hash chains matchfinder (MUST BE LAST!!!)  */
422                         union {
423                                 struct hc_matchfinder_16 hc_mf_16;
424                                 struct hc_matchfinder_32 hc_mf_32;
425                         };
426                 };
427
428                 /* Data for near-optimal parsing  */
429                 struct {
430                         /*
431                          * The graph nodes for the current block.
432                          *
433                          * We need at least 'LZX_DIV_BLOCK_SIZE +
434                          * LZX_MAX_MATCH_LEN - 1' nodes because that is the
435                          * maximum block size that may be used.  Add 1 because
436                          * we need a node to represent end-of-block.
437                          *
438                          * It is possible that nodes past end-of-block are
439                          * accessed during match consideration, but this can
440                          * only occur if the block was truncated at
441                          * LZX_DIV_BLOCK_SIZE.  So the same bound still applies.
442                          * Note that since nodes past the end of the block will
443                          * never actually have an effect on the items that are
444                          * chosen for the block, it makes no difference what
445                          * their costs are initialized to (if anything).
446                          */
447                         struct lzx_optimum_node optimum_nodes[LZX_DIV_BLOCK_SIZE +
448                                                               LZX_MAX_MATCH_LEN - 1 + 1];
449
450                         /* The cost model for the current block  */
451                         struct lzx_costs costs;
452
453                         /*
454                          * Cached matches for the current block.  This array
455                          * contains the matches that were found at each position
456                          * in the block.  Specifically, for each position, there
457                          * is a special 'struct lz_match' whose 'length' field
458                          * contains the number of matches that were found at
459                          * that position; this is followed by the matches
460                          * themselves, if any, sorted by strictly increasing
461                          * length.
462                          *
463                          * Note: in rare cases, there will be a very high number
464                          * of matches in the block and this array will overflow.
465                          * If this happens, we force the end of the current
466                          * block.  LZX_CACHE_LENGTH is the length at which we
467                          * actually check for overflow.  The extra slots beyond
468                          * this are enough to absorb the worst case overflow,
469                          * which occurs if starting at
470                          * &match_cache[LZX_CACHE_LENGTH - 1], we write the
471                          * match count header, then write
472                          * LZX_MAX_MATCHES_PER_POS matches, then skip searching
473                          * for matches at 'LZX_MAX_MATCH_LEN - 1' positions and
474                          * write the match count header for each.
475                          */
476                         struct lz_match match_cache[LZX_CACHE_LENGTH +
477                                                     LZX_MAX_MATCHES_PER_POS +
478                                                     LZX_MAX_MATCH_LEN - 1];
479
480                         /* Binary trees matchfinder (MUST BE LAST!!!)  */
481                         union {
482                                 struct bt_matchfinder_16 bt_mf_16;
483                                 struct bt_matchfinder_32 bt_mf_32;
484                         };
485                 };
486         };
487 };
488
489 /*
490  * Will a matchfinder using 16-bit positions be sufficient for compressing
491  * buffers of up to the specified size?  The limit could be 65536 bytes, but we
492  * also want to optimize out the use of offset_slot_tab_2 in the 16-bit case.
493  * This requires that the limit be no more than the length of offset_slot_tab_1
494  * (currently 32768).
495  */
496 static inline bool
497 lzx_is_16_bit(size_t max_bufsize)
498 {
499         STATIC_ASSERT(ARRAY_LEN(((struct lzx_compressor *)0)->offset_slot_tab_1) == 32768);
500         return max_bufsize <= 32768;
501 }
502
503 /*
504  * The following macros call either the 16-bit or the 32-bit version of a
505  * matchfinder function based on the value of 'is_16_bit', which will be known
506  * at compilation time.
507  */
508
509 #define CALL_HC_MF(is_16_bit, c, funcname, ...)                               \
510         ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->hc_mf_16, ##__VA_ARGS__) : \
511                        CONCAT(funcname, _32)(&(c)->hc_mf_32, ##__VA_ARGS__));
512
513 #define CALL_BT_MF(is_16_bit, c, funcname, ...)                               \
514         ((is_16_bit) ? CONCAT(funcname, _16)(&(c)->bt_mf_16, ##__VA_ARGS__) : \
515                        CONCAT(funcname, _32)(&(c)->bt_mf_32, ##__VA_ARGS__));
516
517 /*
518  * Structure to keep track of the current state of sending bits to the
519  * compressed output buffer.
520  *
521  * The LZX bitstream is encoded as a sequence of 16-bit coding units.
522  */
523 struct lzx_output_bitstream {
524
525         /* Bits that haven't yet been written to the output buffer.  */
526         machine_word_t bitbuf;
527
528         /* Number of bits currently held in @bitbuf.  */
529         u32 bitcount;
530
531         /* Pointer to the start of the output buffer.  */
532         u8 *start;
533
534         /* Pointer to the position in the output buffer at which the next coding
535          * unit should be written.  */
536         u8 *next;
537
538         /* Pointer just past the end of the output buffer, rounded down to a
539          * 2-byte boundary.  */
540         u8 *end;
541 };
542
543 /* Can the specified number of bits always be added to 'bitbuf' after any
544  * pending 16-bit coding units have been flushed?  */
545 #define CAN_BUFFER(n)   ((n) <= WORDBITS - 15)
546
547 /*
548  * Initialize the output bitstream.
549  *
550  * @os
551  *      The output bitstream structure to initialize.
552  * @buffer
553  *      The buffer being written to.
554  * @size
555  *      Size of @buffer, in bytes.
556  */
557 static void
558 lzx_init_output(struct lzx_output_bitstream *os, void *buffer, size_t size)
559 {
560         os->bitbuf = 0;
561         os->bitcount = 0;
562         os->start = buffer;
563         os->next = os->start;
564         os->end = os->start + (size & ~1);
565 }
566
567 /* Add some bits to the bitbuffer variable of the output bitstream.  The caller
568  * must make sure there is enough room.  */
569 static inline void
570 lzx_add_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
571 {
572         os->bitbuf = (os->bitbuf << num_bits) | bits;
573         os->bitcount += num_bits;
574 }
575
576 /* Flush bits from the bitbuffer variable to the output buffer.  'max_num_bits'
577  * specifies the maximum number of bits that may have been added since the last
578  * flush.  */
579 static inline void
580 lzx_flush_bits(struct lzx_output_bitstream *os, unsigned max_num_bits)
581 {
582         /* Masking the number of bits to shift is only needed to avoid undefined
583          * behavior; we don't actually care about the results of bad shifts.  On
584          * x86, the explicit masking generates no extra code.  */
585         const u32 shift_mask = 8 * sizeof(os->bitbuf) - 1;
586
587         if (os->end - os->next < 6)
588                 return;
589         put_unaligned_le16(os->bitbuf >> ((os->bitcount - 16) &
590                                             shift_mask), os->next + 0);
591         if (max_num_bits > 16)
592                 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 32) &
593                                                 shift_mask), os->next + 2);
594         if (max_num_bits > 32)
595                 put_unaligned_le16(os->bitbuf >> ((os->bitcount - 48) &
596                                                 shift_mask), os->next + 4);
597         os->next += (os->bitcount >> 4) << 1;
598         os->bitcount &= 15;
599 }
600
601 /* Add at most 16 bits to the bitbuffer and flush it.  */
602 static inline void
603 lzx_write_bits(struct lzx_output_bitstream *os, u32 bits, unsigned num_bits)
604 {
605         lzx_add_bits(os, bits, num_bits);
606         lzx_flush_bits(os, 16);
607 }
608
609 /*
610  * Flush the last coding unit to the output buffer if needed.  Return the total
611  * number of bytes written to the output buffer, or 0 if an overflow occurred.
612  */
613 static u32
614 lzx_flush_output(struct lzx_output_bitstream *os)
615 {
616         if (os->end - os->next < 6)
617                 return 0;
618
619         if (os->bitcount != 0) {
620                 put_unaligned_le16(os->bitbuf << (16 - os->bitcount), os->next);
621                 os->next += 2;
622         }
623
624         return os->next - os->start;
625 }
626
627 /* Build the main, length, and aligned offset Huffman codes used in LZX.
628  *
629  * This takes as input the frequency tables for each code and produces as output
630  * a set of tables that map symbols to codewords and codeword lengths.  */
631 static void
632 lzx_make_huffman_codes(struct lzx_compressor *c)
633 {
634         const struct lzx_freqs *freqs = &c->freqs;
635         struct lzx_codes *codes = &c->codes[c->codes_index];
636
637         STATIC_ASSERT(MAIN_CODEWORD_LIMIT >= 9 &&
638                       MAIN_CODEWORD_LIMIT <= LZX_MAX_MAIN_CODEWORD_LEN);
639         STATIC_ASSERT(LENGTH_CODEWORD_LIMIT >= 8 &&
640                       LENGTH_CODEWORD_LIMIT <= LZX_MAX_LEN_CODEWORD_LEN);
641         STATIC_ASSERT(ALIGNED_CODEWORD_LIMIT >= LZX_NUM_ALIGNED_OFFSET_BITS &&
642                       ALIGNED_CODEWORD_LIMIT <= LZX_MAX_ALIGNED_CODEWORD_LEN);
643
644         make_canonical_huffman_code(c->num_main_syms,
645                                     MAIN_CODEWORD_LIMIT,
646                                     freqs->main,
647                                     codes->lens.main,
648                                     codes->codewords.main);
649
650         make_canonical_huffman_code(LZX_LENCODE_NUM_SYMBOLS,
651                                     LENGTH_CODEWORD_LIMIT,
652                                     freqs->len,
653                                     codes->lens.len,
654                                     codes->codewords.len);
655
656         make_canonical_huffman_code(LZX_ALIGNEDCODE_NUM_SYMBOLS,
657                                     ALIGNED_CODEWORD_LIMIT,
658                                     freqs->aligned,
659                                     codes->lens.aligned,
660                                     codes->codewords.aligned);
661 }
662
663 /* Reset the symbol frequencies for the LZX Huffman codes.  */
664 static void
665 lzx_reset_symbol_frequencies(struct lzx_compressor *c)
666 {
667         memset(&c->freqs, 0, sizeof(c->freqs));
668 }
669
670 static unsigned
671 lzx_compute_precode_items(const u8 lens[restrict],
672                           const u8 prev_lens[restrict],
673                           u32 precode_freqs[restrict],
674                           unsigned precode_items[restrict])
675 {
676         unsigned *itemptr;
677         unsigned run_start;
678         unsigned run_end;
679         unsigned extra_bits;
680         int delta;
681         u8 len;
682
683         itemptr = precode_items;
684         run_start = 0;
685
686         while (!((len = lens[run_start]) & 0x80)) {
687
688                 /* len = the length being repeated  */
689
690                 /* Find the next run of codeword lengths.  */
691
692                 run_end = run_start + 1;
693
694                 /* Fast case for a single length.  */
695                 if (likely(len != lens[run_end])) {
696                         delta = prev_lens[run_start] - len;
697                         if (delta < 0)
698                                 delta += 17;
699                         precode_freqs[delta]++;
700                         *itemptr++ = delta;
701                         run_start++;
702                         continue;
703                 }
704
705                 /* Extend the run.  */
706                 do {
707                         run_end++;
708                 } while (len == lens[run_end]);
709
710                 if (len == 0) {
711                         /* Run of zeroes.  */
712
713                         /* Symbol 18: RLE 20 to 51 zeroes at a time.  */
714                         while ((run_end - run_start) >= 20) {
715                                 extra_bits = min((run_end - run_start) - 20, 0x1f);
716                                 precode_freqs[18]++;
717                                 *itemptr++ = 18 | (extra_bits << 5);
718                                 run_start += 20 + extra_bits;
719                         }
720
721                         /* Symbol 17: RLE 4 to 19 zeroes at a time.  */
722                         if ((run_end - run_start) >= 4) {
723                                 extra_bits = min((run_end - run_start) - 4, 0xf);
724                                 precode_freqs[17]++;
725                                 *itemptr++ = 17 | (extra_bits << 5);
726                                 run_start += 4 + extra_bits;
727                         }
728                 } else {
729
730                         /* A run of nonzero lengths. */
731
732                         /* Symbol 19: RLE 4 to 5 of any length at a time.  */
733                         while ((run_end - run_start) >= 4) {
734                                 extra_bits = (run_end - run_start) > 4;
735                                 delta = prev_lens[run_start] - len;
736                                 if (delta < 0)
737                                         delta += 17;
738                                 precode_freqs[19]++;
739                                 precode_freqs[delta]++;
740                                 *itemptr++ = 19 | (extra_bits << 5) | (delta << 6);
741                                 run_start += 4 + extra_bits;
742                         }
743                 }
744
745                 /* Output any remaining lengths without RLE.  */
746                 while (run_start != run_end) {
747                         delta = prev_lens[run_start] - len;
748                         if (delta < 0)
749                                 delta += 17;
750                         precode_freqs[delta]++;
751                         *itemptr++ = delta;
752                         run_start++;
753                 }
754         }
755
756         return itemptr - precode_items;
757 }
758
759 /*
760  * Output a Huffman code in the compressed form used in LZX.
761  *
762  * The Huffman code is represented in the output as a logical series of codeword
763  * lengths from which the Huffman code, which must be in canonical form, can be
764  * reconstructed.
765  *
766  * The codeword lengths are themselves compressed using a separate Huffman code,
767  * the "precode", which contains a symbol for each possible codeword length in
768  * the larger code as well as several special symbols to represent repeated
769  * codeword lengths (a form of run-length encoding).  The precode is itself
770  * constructed in canonical form, and its codeword lengths are represented
771  * literally in 20 4-bit fields that immediately precede the compressed codeword
772  * lengths of the larger code.
773  *
774  * Furthermore, the codeword lengths of the larger code are actually represented
775  * as deltas from the codeword lengths of the corresponding code in the previous
776  * block.
777  *
778  * @os:
779  *      Bitstream to which to write the compressed Huffman code.
780  * @lens:
781  *      The codeword lengths, indexed by symbol, in the Huffman code.
782  * @prev_lens:
783  *      The codeword lengths, indexed by symbol, in the corresponding Huffman
784  *      code in the previous block, or all zeroes if this is the first block.
785  * @num_lens:
786  *      The number of symbols in the Huffman code.
787  */
788 static void
789 lzx_write_compressed_code(struct lzx_output_bitstream *os,
790                           const u8 lens[restrict],
791                           const u8 prev_lens[restrict],
792                           unsigned num_lens)
793 {
794         u32 precode_freqs[LZX_PRECODE_NUM_SYMBOLS];
795         u8 precode_lens[LZX_PRECODE_NUM_SYMBOLS];
796         u32 precode_codewords[LZX_PRECODE_NUM_SYMBOLS];
797         unsigned precode_items[num_lens];
798         unsigned num_precode_items;
799         unsigned precode_item;
800         unsigned precode_sym;
801         unsigned i;
802         u8 saved = lens[num_lens];
803         *(u8 *)(lens + num_lens) = 0x80;
804
805         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
806                 precode_freqs[i] = 0;
807
808         /* Compute the "items" (RLE / literal tokens and extra bits) with which
809          * the codeword lengths in the larger code will be output.  */
810         num_precode_items = lzx_compute_precode_items(lens,
811                                                       prev_lens,
812                                                       precode_freqs,
813                                                       precode_items);
814
815         /* Build the precode.  */
816         STATIC_ASSERT(PRE_CODEWORD_LIMIT >= 5 &&
817                       PRE_CODEWORD_LIMIT <= LZX_MAX_PRE_CODEWORD_LEN);
818         make_canonical_huffman_code(LZX_PRECODE_NUM_SYMBOLS,
819                                     PRE_CODEWORD_LIMIT,
820                                     precode_freqs, precode_lens,
821                                     precode_codewords);
822
823         /* Output the lengths of the codewords in the precode.  */
824         for (i = 0; i < LZX_PRECODE_NUM_SYMBOLS; i++)
825                 lzx_write_bits(os, precode_lens[i], LZX_PRECODE_ELEMENT_SIZE);
826
827         /* Output the encoded lengths of the codewords in the larger code.  */
828         for (i = 0; i < num_precode_items; i++) {
829                 precode_item = precode_items[i];
830                 precode_sym = precode_item & 0x1F;
831                 lzx_add_bits(os, precode_codewords[precode_sym],
832                              precode_lens[precode_sym]);
833                 if (precode_sym >= 17) {
834                         if (precode_sym == 17) {
835                                 lzx_add_bits(os, precode_item >> 5, 4);
836                         } else if (precode_sym == 18) {
837                                 lzx_add_bits(os, precode_item >> 5, 5);
838                         } else {
839                                 lzx_add_bits(os, (precode_item >> 5) & 1, 1);
840                                 precode_sym = precode_item >> 6;
841                                 lzx_add_bits(os, precode_codewords[precode_sym],
842                                              precode_lens[precode_sym]);
843                         }
844                 }
845                 STATIC_ASSERT(CAN_BUFFER(2 * PRE_CODEWORD_LIMIT + 1));
846                 lzx_flush_bits(os, 2 * PRE_CODEWORD_LIMIT + 1);
847         }
848
849         *(u8 *)(lens + num_lens) = saved;
850 }
851
852 /*
853  * Write all matches and literal bytes (which were precomputed) in an LZX
854  * compressed block to the output bitstream in the final compressed
855  * representation.
856  *
857  * @os
858  *      The output bitstream.
859  * @block_type
860  *      The chosen type of the LZX compressed block (LZX_BLOCKTYPE_ALIGNED or
861  *      LZX_BLOCKTYPE_VERBATIM).
862  * @block_data
863  *      The uncompressed data of the block.
864  * @sequences
865  *      The matches and literals to output, given as a series of sequences.
866  * @codes
867  *      The main, length, and aligned offset Huffman codes for the current
868  *      LZX compressed block.
869  */
870 static void
871 lzx_write_sequences(struct lzx_output_bitstream *os, int block_type,
872                     const u8 *block_data, const struct lzx_sequence sequences[],
873                     const struct lzx_codes *codes)
874 {
875         const struct lzx_sequence *seq = sequences;
876         u32 ones_if_aligned = 0 - (block_type == LZX_BLOCKTYPE_ALIGNED);
877
878         for (;;) {
879                 /* Output the next sequence.  */
880
881                 unsigned litrunlen = seq->litrunlen;
882                 unsigned match_hdr;
883                 unsigned main_symbol;
884                 unsigned adjusted_length;
885                 u32 adjusted_offset;
886                 unsigned offset_slot;
887                 unsigned num_extra_bits;
888                 u32 extra_bits;
889
890                 /* Output the literal run of the sequence.  */
891
892                 if (litrunlen) {  /* Is the literal run nonempty?  */
893
894                         /* Verify optimization is enabled on 64-bit  */
895                         STATIC_ASSERT(WORDBITS < 64 ||
896                                       CAN_BUFFER(4 * MAIN_CODEWORD_LIMIT));
897
898                         if (CAN_BUFFER(4 * MAIN_CODEWORD_LIMIT)) {
899
900                                 /* 64-bit: write 4 literals at a time.  */
901                                 while (litrunlen >= 4) {
902                                         unsigned lit0 = block_data[0];
903                                         unsigned lit1 = block_data[1];
904                                         unsigned lit2 = block_data[2];
905                                         unsigned lit3 = block_data[3];
906                                         lzx_add_bits(os, codes->codewords.main[lit0],
907                                                      codes->lens.main[lit0]);
908                                         lzx_add_bits(os, codes->codewords.main[lit1],
909                                                      codes->lens.main[lit1]);
910                                         lzx_add_bits(os, codes->codewords.main[lit2],
911                                                      codes->lens.main[lit2]);
912                                         lzx_add_bits(os, codes->codewords.main[lit3],
913                                                      codes->lens.main[lit3]);
914                                         lzx_flush_bits(os, 4 * MAIN_CODEWORD_LIMIT);
915                                         block_data += 4;
916                                         litrunlen -= 4;
917                                 }
918                                 if (litrunlen--) {
919                                         unsigned lit = *block_data++;
920                                         lzx_add_bits(os, codes->codewords.main[lit],
921                                                      codes->lens.main[lit]);
922                                         if (litrunlen--) {
923                                                 unsigned lit = *block_data++;
924                                                 lzx_add_bits(os, codes->codewords.main[lit],
925                                                              codes->lens.main[lit]);
926                                                 if (litrunlen--) {
927                                                         unsigned lit = *block_data++;
928                                                         lzx_add_bits(os, codes->codewords.main[lit],
929                                                                      codes->lens.main[lit]);
930                                                         lzx_flush_bits(os, 3 * MAIN_CODEWORD_LIMIT);
931                                                 } else {
932                                                         lzx_flush_bits(os, 2 * MAIN_CODEWORD_LIMIT);
933                                                 }
934                                         } else {
935                                                 lzx_flush_bits(os, 1 * MAIN_CODEWORD_LIMIT);
936                                         }
937                                 }
938                         } else {
939                                 /* 32-bit: write 1 literal at a time.  */
940                                 do {
941                                         unsigned lit = *block_data++;
942                                         lzx_add_bits(os, codes->codewords.main[lit],
943                                                      codes->lens.main[lit]);
944                                         lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
945                                 } while (--litrunlen);
946                         }
947                 }
948
949                 /* Was this the last literal run?  */
950                 if (seq->adjusted_offset_and_match_hdr & 0x80000000)
951                         return;
952
953                 /* Nope; output the match.  */
954
955                 match_hdr = seq->adjusted_offset_and_match_hdr & 0x1FF;
956                 main_symbol = LZX_NUM_CHARS + match_hdr;
957                 adjusted_length = seq->adjusted_length;
958
959                 block_data += adjusted_length + LZX_MIN_MATCH_LEN;
960
961                 offset_slot = match_hdr / LZX_NUM_LEN_HEADERS;
962                 adjusted_offset = seq->adjusted_offset_and_match_hdr >> 9;
963
964                 num_extra_bits = lzx_extra_offset_bits[offset_slot];
965                 extra_bits = adjusted_offset - lzx_offset_slot_base[offset_slot];
966
967         #define MAX_MATCH_BITS  (MAIN_CODEWORD_LIMIT + LENGTH_CODEWORD_LIMIT + \
968                                  14 + ALIGNED_CODEWORD_LIMIT)
969
970                 /* Verify optimization is enabled on 64-bit  */
971                 STATIC_ASSERT(WORDBITS < 64 || CAN_BUFFER(MAX_MATCH_BITS));
972
973                 /* Output the main symbol for the match.  */
974
975                 lzx_add_bits(os, codes->codewords.main[main_symbol],
976                              codes->lens.main[main_symbol]);
977                 if (!CAN_BUFFER(MAX_MATCH_BITS))
978                         lzx_flush_bits(os, MAIN_CODEWORD_LIMIT);
979
980                 /* If needed, output the length symbol for the match.  */
981
982                 if (adjusted_length >= LZX_NUM_PRIMARY_LENS) {
983                         lzx_add_bits(os, codes->codewords.len[adjusted_length -
984                                                               LZX_NUM_PRIMARY_LENS],
985                                      codes->lens.len[adjusted_length -
986                                                      LZX_NUM_PRIMARY_LENS]);
987                         if (!CAN_BUFFER(MAX_MATCH_BITS))
988                                 lzx_flush_bits(os, LENGTH_CODEWORD_LIMIT);
989                 }
990
991                 /* Output the extra offset bits for the match.  In aligned
992                  * offset blocks, the lowest 3 bits of the adjusted offset are
993                  * Huffman-encoded using the aligned offset code, provided that
994                  * there are at least extra 3 offset bits required.  All other
995                  * extra offset bits are output verbatim.  */
996
997                 if ((adjusted_offset & ones_if_aligned) >= 16) {
998
999                         lzx_add_bits(os, extra_bits >> LZX_NUM_ALIGNED_OFFSET_BITS,
1000                                      num_extra_bits - LZX_NUM_ALIGNED_OFFSET_BITS);
1001                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1002                                 lzx_flush_bits(os, 14);
1003
1004                         lzx_add_bits(os, codes->codewords.aligned[adjusted_offset &
1005                                                                   LZX_ALIGNED_OFFSET_BITMASK],
1006                                      codes->lens.aligned[adjusted_offset &
1007                                                          LZX_ALIGNED_OFFSET_BITMASK]);
1008                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1009                                 lzx_flush_bits(os, ALIGNED_CODEWORD_LIMIT);
1010                 } else {
1011                         STATIC_ASSERT(CAN_BUFFER(17));
1012
1013                         lzx_add_bits(os, extra_bits, num_extra_bits);
1014                         if (!CAN_BUFFER(MAX_MATCH_BITS))
1015                                 lzx_flush_bits(os, 17);
1016                 }
1017
1018                 if (CAN_BUFFER(MAX_MATCH_BITS))
1019                         lzx_flush_bits(os, MAX_MATCH_BITS);
1020
1021                 /* Advance to the next sequence.  */
1022                 seq++;
1023         }
1024 }
1025
1026 static void
1027 lzx_write_compressed_block(const u8 *block_begin,
1028                            int block_type,
1029                            u32 block_size,
1030                            unsigned window_order,
1031                            unsigned num_main_syms,
1032                            const struct lzx_sequence sequences[],
1033                            const struct lzx_codes * codes,
1034                            const struct lzx_lens * prev_lens,
1035                            struct lzx_output_bitstream * os)
1036 {
1037         /* The first three bits indicate the type of block and are one of the
1038          * LZX_BLOCKTYPE_* constants.  */
1039         lzx_write_bits(os, block_type, 3);
1040
1041         /* Output the block size.
1042          *
1043          * The original LZX format seemed to always encode the block size in 3
1044          * bytes.  However, the implementation in WIMGAPI, as used in WIM files,
1045          * uses the first bit to indicate whether the block is the default size
1046          * (32768) or a different size given explicitly by the next 16 bits.
1047          *
1048          * By default, this compressor uses a window size of 32768 and therefore
1049          * follows the WIMGAPI behavior.  However, this compressor also supports
1050          * window sizes greater than 32768 bytes, which do not appear to be
1051          * supported by WIMGAPI.  In such cases, we retain the default size bit
1052          * to mean a size of 32768 bytes but output non-default block size in 24
1053          * bits rather than 16.  The compatibility of this behavior is unknown
1054          * because WIMs created with chunk size greater than 32768 can seemingly
1055          * only be opened by wimlib anyway.  */
1056         if (block_size == LZX_DEFAULT_BLOCK_SIZE) {
1057                 lzx_write_bits(os, 1, 1);
1058         } else {
1059                 lzx_write_bits(os, 0, 1);
1060
1061                 if (window_order >= 16)
1062                         lzx_write_bits(os, block_size >> 16, 8);
1063
1064                 lzx_write_bits(os, block_size & 0xFFFF, 16);
1065         }
1066
1067         /* If it's an aligned offset block, output the aligned offset code.  */
1068         if (block_type == LZX_BLOCKTYPE_ALIGNED) {
1069                 for (int i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1070                         lzx_write_bits(os, codes->lens.aligned[i],
1071                                        LZX_ALIGNEDCODE_ELEMENT_SIZE);
1072                 }
1073         }
1074
1075         /* Output the main code (two parts).  */
1076         lzx_write_compressed_code(os, codes->lens.main,
1077                                   prev_lens->main,
1078                                   LZX_NUM_CHARS);
1079         lzx_write_compressed_code(os, codes->lens.main + LZX_NUM_CHARS,
1080                                   prev_lens->main + LZX_NUM_CHARS,
1081                                   num_main_syms - LZX_NUM_CHARS);
1082
1083         /* Output the length code.  */
1084         lzx_write_compressed_code(os, codes->lens.len,
1085                                   prev_lens->len,
1086                                   LZX_LENCODE_NUM_SYMBOLS);
1087
1088         /* Output the compressed matches and literals.  */
1089         lzx_write_sequences(os, block_type, block_begin, sequences, codes);
1090 }
1091
1092 /* Given the frequencies of symbols in an LZX-compressed block and the
1093  * corresponding Huffman codes, return LZX_BLOCKTYPE_ALIGNED or
1094  * LZX_BLOCKTYPE_VERBATIM if an aligned offset or verbatim block, respectively,
1095  * will take fewer bits to output.  */
1096 static int
1097 lzx_choose_verbatim_or_aligned(const struct lzx_freqs * freqs,
1098                                const struct lzx_codes * codes)
1099 {
1100         u32 aligned_cost = 0;
1101         u32 verbatim_cost = 0;
1102
1103         /* A verbatim block requires 3 bits in each place that an aligned symbol
1104          * would be used in an aligned offset block.  */
1105         for (unsigned i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1106                 verbatim_cost += LZX_NUM_ALIGNED_OFFSET_BITS * freqs->aligned[i];
1107                 aligned_cost += codes->lens.aligned[i] * freqs->aligned[i];
1108         }
1109
1110         /* Account for output of the aligned offset code.  */
1111         aligned_cost += LZX_ALIGNEDCODE_ELEMENT_SIZE * LZX_ALIGNEDCODE_NUM_SYMBOLS;
1112
1113         if (aligned_cost < verbatim_cost)
1114                 return LZX_BLOCKTYPE_ALIGNED;
1115         else
1116                 return LZX_BLOCKTYPE_VERBATIM;
1117 }
1118
1119 /*
1120  * Return the offset slot for the specified adjusted match offset, using the
1121  * compressor's acceleration tables to speed up the mapping.
1122  */
1123 static inline unsigned
1124 lzx_comp_get_offset_slot(struct lzx_compressor *c, u32 adjusted_offset,
1125                          bool is_16_bit)
1126 {
1127         if (is_16_bit || adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1))
1128                 return c->offset_slot_tab_1[adjusted_offset];
1129         return c->offset_slot_tab_2[adjusted_offset >> 14];
1130 }
1131
1132 /*
1133  * Finish an LZX block:
1134  *
1135  * - build the Huffman codes
1136  * - decide whether to output the block as VERBATIM or ALIGNED
1137  * - output the block
1138  * - swap the indices of the current and previous Huffman codes
1139  */
1140 static void
1141 lzx_finish_block(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1142                  const u8 *block_begin, u32 block_size, u32 seq_idx)
1143 {
1144         int block_type;
1145
1146         lzx_make_huffman_codes(c);
1147
1148         block_type = lzx_choose_verbatim_or_aligned(&c->freqs,
1149                                                     &c->codes[c->codes_index]);
1150         lzx_write_compressed_block(block_begin,
1151                                    block_type,
1152                                    block_size,
1153                                    c->window_order,
1154                                    c->num_main_syms,
1155                                    &c->chosen_sequences[seq_idx],
1156                                    &c->codes[c->codes_index],
1157                                    &c->codes[c->codes_index ^ 1].lens,
1158                                    os);
1159         c->codes_index ^= 1;
1160 }
1161
1162 /* Tally the Huffman symbol for a literal and increment the literal run length.
1163  */
1164 static inline void
1165 lzx_record_literal(struct lzx_compressor *c, unsigned literal, u32 *litrunlen_p)
1166 {
1167         c->freqs.main[literal]++;
1168         ++*litrunlen_p;
1169 }
1170
1171 /* Tally the Huffman symbol for a match, save the match data and the length of
1172  * the preceding literal run in the next lzx_sequence, and update the recent
1173  * offsets queue.  */
1174 static inline void
1175 lzx_record_match(struct lzx_compressor *c, unsigned length, u32 offset_data,
1176                  u32 recent_offsets[LZX_NUM_RECENT_OFFSETS], bool is_16_bit,
1177                  u32 *litrunlen_p, struct lzx_sequence **next_seq_p)
1178 {
1179         u32 litrunlen = *litrunlen_p;
1180         struct lzx_sequence *next_seq = *next_seq_p;
1181         unsigned offset_slot;
1182         unsigned v;
1183
1184         v = length - LZX_MIN_MATCH_LEN;
1185
1186         /* Save the literal run length and adjusted length.  */
1187         next_seq->litrunlen = litrunlen;
1188         next_seq->adjusted_length = v;
1189
1190         /* Compute the length header and tally the length symbol if needed  */
1191         if (v >= LZX_NUM_PRIMARY_LENS) {
1192                 c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1193                 v = LZX_NUM_PRIMARY_LENS;
1194         }
1195
1196         /* Compute the offset slot  */
1197         offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1198
1199         /* Compute the match header.  */
1200         v += offset_slot * LZX_NUM_LEN_HEADERS;
1201
1202         /* Save the adjusted offset and match header.  */
1203         next_seq->adjusted_offset_and_match_hdr = (offset_data << 9) | v;
1204
1205         /* Tally the main symbol.  */
1206         c->freqs.main[LZX_NUM_CHARS + v]++;
1207
1208         /* Update the recent offsets queue.  */
1209         if (offset_data < LZX_NUM_RECENT_OFFSETS) {
1210                 /* Repeat offset match  */
1211                 swap(recent_offsets[0], recent_offsets[offset_data]);
1212         } else {
1213                 /* Explicit offset match  */
1214
1215                 /* Tally the aligned offset symbol if needed  */
1216                 if (offset_data >= 16)
1217                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1218
1219                 recent_offsets[2] = recent_offsets[1];
1220                 recent_offsets[1] = recent_offsets[0];
1221                 recent_offsets[0] = offset_data - LZX_OFFSET_ADJUSTMENT;
1222         }
1223
1224         /* Reset the literal run length and advance to the next sequence.  */
1225         *next_seq_p = next_seq + 1;
1226         *litrunlen_p = 0;
1227 }
1228
1229 /* Finish the last lzx_sequence.  The last lzx_sequence is just a literal run;
1230  * there is no match.  This literal run may be empty.  */
1231 static inline void
1232 lzx_finish_sequence(struct lzx_sequence *last_seq, u32 litrunlen)
1233 {
1234         last_seq->litrunlen = litrunlen;
1235
1236         /* Special value to mark last sequence  */
1237         last_seq->adjusted_offset_and_match_hdr = 0x80000000;
1238 }
1239
1240 /*
1241  * Given the minimum-cost path computed through the item graph for the current
1242  * block, walk the path and count how many of each symbol in each Huffman-coded
1243  * alphabet would be required to output the items (matches and literals) along
1244  * the path.
1245  *
1246  * Note that the path will be walked backwards (from the end of the block to the
1247  * beginning of the block), but this doesn't matter because this function only
1248  * computes frequencies.
1249  */
1250 static inline void
1251 lzx_tally_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1252 {
1253         u32 node_idx = block_size;
1254         for (;;) {
1255                 u32 len;
1256                 u32 offset_data;
1257                 unsigned v;
1258                 unsigned offset_slot;
1259
1260                 /* Tally literals until either a match or the beginning of the
1261                  * block is reached.  */
1262                 for (;;) {
1263                         u32 item = c->optimum_nodes[node_idx].item;
1264
1265                         len = item & OPTIMUM_LEN_MASK;
1266                         offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1267
1268                         if (len != 0)  /* Not a literal?  */
1269                                 break;
1270
1271                         /* Tally the main symbol for the literal.  */
1272                         c->freqs.main[offset_data]++;
1273
1274                         if (--node_idx == 0) /* Beginning of block was reached?  */
1275                                 return;
1276                 }
1277
1278                 node_idx -= len;
1279
1280                 /* Tally a match.  */
1281
1282                 /* Tally the aligned offset symbol if needed.  */
1283                 if (offset_data >= 16)
1284                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1285
1286                 /* Tally the length symbol if needed.  */
1287                 v = len - LZX_MIN_MATCH_LEN;;
1288                 if (v >= LZX_NUM_PRIMARY_LENS) {
1289                         c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1290                         v = LZX_NUM_PRIMARY_LENS;
1291                 }
1292
1293                 /* Tally the main symbol.  */
1294                 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1295                 v += offset_slot * LZX_NUM_LEN_HEADERS;
1296                 c->freqs.main[LZX_NUM_CHARS + v]++;
1297
1298                 if (node_idx == 0) /* Beginning of block was reached?  */
1299                         return;
1300         }
1301 }
1302
1303 /*
1304  * Like lzx_tally_item_list(), but this function also generates the list of
1305  * lzx_sequences for the minimum-cost path and writes it to c->chosen_sequences,
1306  * ready to be output to the bitstream after the Huffman codes are computed.
1307  * The lzx_sequences will be written to decreasing memory addresses as the path
1308  * is walked backwards, which means they will end up in the expected
1309  * first-to-last order.  The return value is the index in c->chosen_sequences at
1310  * which the lzx_sequences begin.
1311  */
1312 static inline u32
1313 lzx_record_item_list(struct lzx_compressor *c, u32 block_size, bool is_16_bit)
1314 {
1315         u32 node_idx = block_size;
1316         u32 seq_idx = ARRAY_LEN(c->chosen_sequences) - 1;
1317         u32 lit_start_node;
1318
1319         /* Special value to mark last sequence  */
1320         c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr = 0x80000000;
1321
1322         lit_start_node = node_idx;
1323         for (;;) {
1324                 u32 len;
1325                 u32 offset_data;
1326                 unsigned v;
1327                 unsigned offset_slot;
1328
1329                 /* Record literals until either a match or the beginning of the
1330                  * block is reached.  */
1331                 for (;;) {
1332                         u32 item = c->optimum_nodes[node_idx].item;
1333
1334                         len = item & OPTIMUM_LEN_MASK;
1335                         offset_data = item >> OPTIMUM_OFFSET_SHIFT;
1336
1337                         if (len != 0) /* Not a literal?  */
1338                                 break;
1339
1340                         /* Tally the main symbol for the literal.  */
1341                         c->freqs.main[offset_data]++;
1342
1343                         if (--node_idx == 0) /* Beginning of block was reached?  */
1344                                 goto out;
1345                 }
1346
1347                 /* Save the literal run length for the next sequence (the
1348                  * "previous sequence" when walking backwards).  */
1349                 c->chosen_sequences[seq_idx--].litrunlen = lit_start_node - node_idx;
1350                 node_idx -= len;
1351                 lit_start_node = node_idx;
1352
1353                 /* Record a match.  */
1354
1355                 /* Tally the aligned offset symbol if needed.  */
1356                 if (offset_data >= 16)
1357                         c->freqs.aligned[offset_data & LZX_ALIGNED_OFFSET_BITMASK]++;
1358
1359                 /* Save the adjusted length.  */
1360                 v = len - LZX_MIN_MATCH_LEN;
1361                 c->chosen_sequences[seq_idx].adjusted_length = v;
1362
1363                 /* Tally the length symbol if needed.  */
1364                 if (v >= LZX_NUM_PRIMARY_LENS) {
1365                         c->freqs.len[v - LZX_NUM_PRIMARY_LENS]++;
1366                         v = LZX_NUM_PRIMARY_LENS;
1367                 }
1368
1369                 /* Tally the main symbol.  */
1370                 offset_slot = lzx_comp_get_offset_slot(c, offset_data, is_16_bit);
1371                 v += offset_slot * LZX_NUM_LEN_HEADERS;
1372                 c->freqs.main[LZX_NUM_CHARS + v]++;
1373
1374                 /* Save the adjusted offset and match header.  */
1375                 c->chosen_sequences[seq_idx].adjusted_offset_and_match_hdr =
1376                                 (offset_data << 9) | v;
1377
1378                 if (node_idx == 0) /* Beginning of block was reached?  */
1379                         goto out;
1380         }
1381
1382 out:
1383         /* Save the literal run length for the first sequence.  */
1384         c->chosen_sequences[seq_idx].litrunlen = lit_start_node - node_idx;
1385
1386         /* Return the index in c->chosen_sequences at which the lzx_sequences
1387          * begin.  */
1388         return seq_idx;
1389 }
1390
1391 /*
1392  * Find an inexpensive path through the graph of possible match/literal choices
1393  * for the current block.  The nodes of the graph are
1394  * c->optimum_nodes[0...block_size].  They correspond directly to the bytes in
1395  * the current block, plus one extra node for end-of-block.  The edges of the
1396  * graph are matches and literals.  The goal is to find the minimum cost path
1397  * from 'c->optimum_nodes[0]' to 'c->optimum_nodes[block_size]'.
1398  *
1399  * The algorithm works forwards, starting at 'c->optimum_nodes[0]' and
1400  * proceeding forwards one node at a time.  At each node, a selection of matches
1401  * (len >= 2), as well as the literal byte (len = 1), is considered.  An item of
1402  * length 'len' provides a new path to reach the node 'len' bytes later.  If
1403  * such a path is the lowest cost found so far to reach that later node, then
1404  * that later node is updated with the new path.
1405  *
1406  * Note that although this algorithm is based on minimum cost path search, due
1407  * to various simplifying assumptions the result is not guaranteed to be the
1408  * true minimum cost, or "optimal", path over the graph of all valid LZX
1409  * representations of this block.
1410  *
1411  * Also, note that because of the presence of the recent offsets queue (which is
1412  * a type of adaptive state), the algorithm cannot work backwards and compute
1413  * "cost to end" instead of "cost to beginning".  Furthermore, the way the
1414  * algorithm handles this adaptive state in the "minimum cost" parse is actually
1415  * only an approximation.  It's possible for the globally optimal, minimum cost
1416  * path to contain a prefix, ending at a position, where that path prefix is
1417  * *not* the minimum cost path to that position.  This can happen if such a path
1418  * prefix results in a different adaptive state which results in lower costs
1419  * later.  The algorithm does not solve this problem; it only considers the
1420  * lowest cost to reach each individual position.
1421  */
1422 static inline struct lzx_lru_queue
1423 lzx_find_min_cost_path(struct lzx_compressor * const restrict c,
1424                        const u8 * const restrict block_begin,
1425                        const u32 block_size,
1426                        const struct lzx_lru_queue initial_queue,
1427                        bool is_16_bit)
1428 {
1429         struct lzx_optimum_node *cur_node = c->optimum_nodes;
1430         struct lzx_optimum_node * const end_node = &c->optimum_nodes[block_size];
1431         struct lz_match *cache_ptr = c->match_cache;
1432         const u8 *in_next = block_begin;
1433         const u8 * const block_end = block_begin + block_size;
1434
1435         /* Instead of storing the match offset LRU queues in the
1436          * 'lzx_optimum_node' structures, we save memory (and cache lines) by
1437          * storing them in a smaller array.  This works because the algorithm
1438          * only requires a limited history of the adaptive state.  Once a given
1439          * state is more than LZX_MAX_MATCH_LEN bytes behind the current node,
1440          * it is no longer needed.  */
1441         struct lzx_lru_queue queues[512];
1442
1443         STATIC_ASSERT(ARRAY_LEN(queues) >= LZX_MAX_MATCH_LEN + 1);
1444 #define QUEUE(in) (queues[(uintptr_t)(in) % ARRAY_LEN(queues)])
1445
1446         /* Initially, the cost to reach each node is "infinity".  */
1447         memset(c->optimum_nodes, 0xFF,
1448                (block_size + 1) * sizeof(c->optimum_nodes[0]));
1449
1450         QUEUE(block_begin) = initial_queue;
1451
1452         /* The following loop runs 'block_size' iterations, one per node.  */
1453         do {
1454                 unsigned num_matches;
1455                 unsigned literal;
1456                 u32 cost;
1457
1458                 /*
1459                  * A selection of matches for the block was already saved in
1460                  * memory so that we don't have to run the uncompressed data
1461                  * through the matchfinder on every optimization pass.  However,
1462                  * we still search for repeat offset matches during each
1463                  * optimization pass because we cannot predict the state of the
1464                  * recent offsets queue.  But as a heuristic, we don't bother
1465                  * searching for repeat offset matches if the general-purpose
1466                  * matchfinder failed to find any matches.
1467                  *
1468                  * Note that a match of length n at some offset implies there is
1469                  * also a match of length l for LZX_MIN_MATCH_LEN <= l <= n at
1470                  * that same offset.  In other words, we don't necessarily need
1471                  * to use the full length of a match.  The key heuristic that
1472                  * saves a significicant amount of time is that for each
1473                  * distinct length, we only consider the smallest offset for
1474                  * which that length is available.  This heuristic also applies
1475                  * to repeat offsets, which we order specially: R0 < R1 < R2 <
1476                  * any explicit offset.  Of course, this heuristic may be
1477                  * produce suboptimal results because offset slots in LZX are
1478                  * subject to entropy encoding, but in practice this is a useful
1479                  * heuristic.
1480                  */
1481
1482                 num_matches = cache_ptr->length;
1483                 cache_ptr++;
1484
1485                 if (num_matches) {
1486                         struct lz_match *end_matches = cache_ptr + num_matches;
1487                         unsigned next_len = LZX_MIN_MATCH_LEN;
1488                         unsigned max_len = min(block_end - in_next, LZX_MAX_MATCH_LEN);
1489                         const u8 *matchptr;
1490
1491                         /* Consider R0 match  */
1492                         matchptr = in_next - lzx_lru_queue_R0(QUEUE(in_next));
1493                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1494                                 goto R0_done;
1495                         STATIC_ASSERT(LZX_MIN_MATCH_LEN == 2);
1496                         do {
1497                                 u32 cost = cur_node->cost +
1498                                            c->costs.match_cost[0][
1499                                                         next_len - LZX_MIN_MATCH_LEN];
1500                                 if (cost <= (cur_node + next_len)->cost) {
1501                                         (cur_node + next_len)->cost = cost;
1502                                         (cur_node + next_len)->item =
1503                                                 (0 << OPTIMUM_OFFSET_SHIFT) | next_len;
1504                                 }
1505                                 if (unlikely(++next_len > max_len)) {
1506                                         cache_ptr = end_matches;
1507                                         goto done_matches;
1508                                 }
1509                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1510
1511                 R0_done:
1512
1513                         /* Consider R1 match  */
1514                         matchptr = in_next - lzx_lru_queue_R1(QUEUE(in_next));
1515                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1516                                 goto R1_done;
1517                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1518                                 goto R1_done;
1519                         for (unsigned len = 2; len < next_len - 1; len++)
1520                                 if (matchptr[len] != in_next[len])
1521                                         goto R1_done;
1522                         do {
1523                                 u32 cost = cur_node->cost +
1524                                            c->costs.match_cost[1][
1525                                                         next_len - LZX_MIN_MATCH_LEN];
1526                                 if (cost <= (cur_node + next_len)->cost) {
1527                                         (cur_node + next_len)->cost = cost;
1528                                         (cur_node + next_len)->item =
1529                                                 (1 << OPTIMUM_OFFSET_SHIFT) | next_len;
1530                                 }
1531                                 if (unlikely(++next_len > max_len)) {
1532                                         cache_ptr = end_matches;
1533                                         goto done_matches;
1534                                 }
1535                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1536
1537                 R1_done:
1538
1539                         /* Consider R2 match  */
1540                         matchptr = in_next - lzx_lru_queue_R2(QUEUE(in_next));
1541                         if (load_u16_unaligned(matchptr) != load_u16_unaligned(in_next))
1542                                 goto R2_done;
1543                         if (matchptr[next_len - 1] != in_next[next_len - 1])
1544                                 goto R2_done;
1545                         for (unsigned len = 2; len < next_len - 1; len++)
1546                                 if (matchptr[len] != in_next[len])
1547                                         goto R2_done;
1548                         do {
1549                                 u32 cost = cur_node->cost +
1550                                            c->costs.match_cost[2][
1551                                                         next_len - LZX_MIN_MATCH_LEN];
1552                                 if (cost <= (cur_node + next_len)->cost) {
1553                                         (cur_node + next_len)->cost = cost;
1554                                         (cur_node + next_len)->item =
1555                                                 (2 << OPTIMUM_OFFSET_SHIFT) | next_len;
1556                                 }
1557                                 if (unlikely(++next_len > max_len)) {
1558                                         cache_ptr = end_matches;
1559                                         goto done_matches;
1560                                 }
1561                         } while (in_next[next_len - 1] == matchptr[next_len - 1]);
1562
1563                 R2_done:
1564
1565                         while (next_len > cache_ptr->length)
1566                                 if (++cache_ptr == end_matches)
1567                                         goto done_matches;
1568
1569                         /* Consider explicit offset matches  */
1570                         do {
1571                                 u32 offset = cache_ptr->offset;
1572                                 u32 offset_data = offset + LZX_OFFSET_ADJUSTMENT;
1573                                 unsigned offset_slot = lzx_comp_get_offset_slot(c, offset_data,
1574                                                                                 is_16_bit);
1575                                 u32 base_cost = cur_node->cost;
1576
1577                         #if LZX_CONSIDER_ALIGNED_COSTS
1578                                 if (offset_data >= 16)
1579                                         base_cost += c->costs.aligned[offset_data &
1580                                                                       LZX_ALIGNED_OFFSET_BITMASK];
1581                         #endif
1582
1583                                 do {
1584                                         u32 cost = base_cost +
1585                                                    c->costs.match_cost[offset_slot][
1586                                                                 next_len - LZX_MIN_MATCH_LEN];
1587                                         if (cost < (cur_node + next_len)->cost) {
1588                                                 (cur_node + next_len)->cost = cost;
1589                                                 (cur_node + next_len)->item =
1590                                                         (offset_data << OPTIMUM_OFFSET_SHIFT) | next_len;
1591                                         }
1592                                 } while (++next_len <= cache_ptr->length);
1593                         } while (++cache_ptr != end_matches);
1594                 }
1595
1596         done_matches:
1597
1598                 /* Consider coding a literal.
1599
1600                  * To avoid an extra branch, actually checking the preferability
1601                  * of coding the literal is integrated into the queue update
1602                  * code below.  */
1603                 literal = *in_next++;
1604                 cost = cur_node->cost + c->costs.main[literal];
1605
1606                 /* Advance to the next position.  */
1607                 cur_node++;
1608
1609                 /* The lowest-cost path to the current position is now known.
1610                  * Finalize the recent offsets queue that results from taking
1611                  * this lowest-cost path.  */
1612
1613                 if (cost <= cur_node->cost) {
1614                         /* Literal: queue remains unchanged.  */
1615                         cur_node->cost = cost;
1616                         cur_node->item = (u32)literal << OPTIMUM_OFFSET_SHIFT;
1617                         QUEUE(in_next) = QUEUE(in_next - 1);
1618                 } else {
1619                         /* Match: queue update is needed.  */
1620                         unsigned len = cur_node->item & OPTIMUM_LEN_MASK;
1621                         u32 offset_data = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
1622                         if (offset_data >= LZX_NUM_RECENT_OFFSETS) {
1623                                 /* Explicit offset match: insert offset at front  */
1624                                 QUEUE(in_next) =
1625                                         lzx_lru_queue_push(QUEUE(in_next - len),
1626                                                            offset_data - LZX_OFFSET_ADJUSTMENT);
1627                         } else {
1628                                 /* Repeat offset match: swap offset to front  */
1629                                 QUEUE(in_next) =
1630                                         lzx_lru_queue_swap(QUEUE(in_next - len),
1631                                                            offset_data);
1632                         }
1633                 }
1634         } while (cur_node != end_node);
1635
1636         /* Return the match offset queue at the end of the minimum cost path. */
1637         return QUEUE(block_end);
1638 }
1639
1640 /* Given the costs for the main and length codewords, compute 'match_costs'.  */
1641 static void
1642 lzx_compute_match_costs(struct lzx_compressor *c)
1643 {
1644         unsigned num_offset_slots = (c->num_main_syms - LZX_NUM_CHARS) /
1645                                         LZX_NUM_LEN_HEADERS;
1646         struct lzx_costs *costs = &c->costs;
1647
1648         for (unsigned offset_slot = 0; offset_slot < num_offset_slots; offset_slot++) {
1649
1650                 u32 extra_cost = (u32)lzx_extra_offset_bits[offset_slot] * LZX_BIT_COST;
1651                 unsigned main_symbol = LZX_NUM_CHARS + (offset_slot *
1652                                                         LZX_NUM_LEN_HEADERS);
1653                 unsigned i;
1654
1655         #if LZX_CONSIDER_ALIGNED_COSTS
1656                 if (offset_slot >= 8)
1657                         extra_cost -= LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1658         #endif
1659
1660                 for (i = 0; i < LZX_NUM_PRIMARY_LENS; i++)
1661                         costs->match_cost[offset_slot][i] =
1662                                 costs->main[main_symbol++] + extra_cost;
1663
1664                 extra_cost += costs->main[main_symbol];
1665
1666                 for (; i < LZX_NUM_LENS; i++)
1667                         costs->match_cost[offset_slot][i] =
1668                                 costs->len[i - LZX_NUM_PRIMARY_LENS] + extra_cost;
1669         }
1670 }
1671
1672 /* Set default LZX Huffman symbol costs to bootstrap the iterative optimization
1673  * algorithm.  */
1674 static void
1675 lzx_set_default_costs(struct lzx_compressor *c, const u8 *block, u32 block_size)
1676 {
1677         u32 i;
1678         bool have_byte[256];
1679         unsigned num_used_bytes;
1680
1681         /* The costs below are hard coded to use a scaling factor of 16.  */
1682         STATIC_ASSERT(LZX_BIT_COST == 16);
1683
1684         /*
1685          * Heuristics:
1686          *
1687          * - Use smaller initial costs for literal symbols when the input buffer
1688          *   contains fewer distinct bytes.
1689          *
1690          * - Assume that match symbols are more costly than literal symbols.
1691          *
1692          * - Assume that length symbols for shorter lengths are less costly than
1693          *   length symbols for longer lengths.
1694          */
1695
1696         for (i = 0; i < 256; i++)
1697                 have_byte[i] = false;
1698
1699         for (i = 0; i < block_size; i++)
1700                 have_byte[block[i]] = true;
1701
1702         num_used_bytes = 0;
1703         for (i = 0; i < 256; i++)
1704                 num_used_bytes += have_byte[i];
1705
1706         for (i = 0; i < 256; i++)
1707                 c->costs.main[i] = 140 - (256 - num_used_bytes) / 4;
1708
1709         for (; i < c->num_main_syms; i++)
1710                 c->costs.main[i] = 170;
1711
1712         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++)
1713                 c->costs.len[i] = 103 + (i / 4);
1714
1715 #if LZX_CONSIDER_ALIGNED_COSTS
1716         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++)
1717                 c->costs.aligned[i] = LZX_NUM_ALIGNED_OFFSET_BITS * LZX_BIT_COST;
1718 #endif
1719
1720         lzx_compute_match_costs(c);
1721 }
1722
1723 /* Update the current cost model to reflect the computed Huffman codes.  */
1724 static void
1725 lzx_update_costs(struct lzx_compressor *c)
1726 {
1727         unsigned i;
1728         const struct lzx_lens *lens = &c->codes[c->codes_index].lens;
1729
1730         for (i = 0; i < c->num_main_syms; i++) {
1731                 c->costs.main[i] = (lens->main[i] ? lens->main[i] :
1732                                     MAIN_CODEWORD_LIMIT) * LZX_BIT_COST;
1733         }
1734
1735         for (i = 0; i < LZX_LENCODE_NUM_SYMBOLS; i++) {
1736                 c->costs.len[i] = (lens->len[i] ? lens->len[i] :
1737                                    LENGTH_CODEWORD_LIMIT) * LZX_BIT_COST;
1738         }
1739
1740 #if LZX_CONSIDER_ALIGNED_COSTS
1741         for (i = 0; i < LZX_ALIGNEDCODE_NUM_SYMBOLS; i++) {
1742                 c->costs.aligned[i] = (lens->aligned[i] ? lens->aligned[i] :
1743                                        ALIGNED_CODEWORD_LIMIT) * LZX_BIT_COST;
1744         }
1745 #endif
1746
1747         lzx_compute_match_costs(c);
1748 }
1749
1750 static inline struct lzx_lru_queue
1751 lzx_optimize_and_write_block(struct lzx_compressor * const restrict c,
1752                              struct lzx_output_bitstream * const restrict os,
1753                              const u8 * const restrict block_begin,
1754                              const u32 block_size,
1755                              const struct lzx_lru_queue initial_queue,
1756                              bool is_16_bit)
1757 {
1758         unsigned num_passes_remaining = c->num_optim_passes;
1759         struct lzx_lru_queue new_queue;
1760         u32 seq_idx;
1761
1762         /* The first optimization pass uses a default cost model.  Each
1763          * additional optimization pass uses a cost model derived from the
1764          * Huffman code computed in the previous pass.  */
1765
1766         lzx_set_default_costs(c, block_begin, block_size);
1767         lzx_reset_symbol_frequencies(c);
1768         do {
1769                 new_queue = lzx_find_min_cost_path(c, block_begin, block_size,
1770                                                    initial_queue, is_16_bit);
1771                 if (num_passes_remaining > 1) {
1772                         lzx_tally_item_list(c, block_size, is_16_bit);
1773                         lzx_make_huffman_codes(c);
1774                         lzx_update_costs(c);
1775                         lzx_reset_symbol_frequencies(c);
1776                 }
1777         } while (--num_passes_remaining);
1778
1779         seq_idx = lzx_record_item_list(c, block_size, is_16_bit);
1780         lzx_finish_block(c, os, block_begin, block_size, seq_idx);
1781         return new_queue;
1782 }
1783
1784 /*
1785  * This is the "near-optimal" LZX compressor.
1786  *
1787  * For each block, it performs a relatively thorough graph search to find an
1788  * inexpensive (in terms of compressed size) way to output that block.
1789  *
1790  * Note: there are actually many things this algorithm leaves on the table in
1791  * terms of compression ratio.  So although it may be "near-optimal", it is
1792  * certainly not "optimal".  The goal is not to produce the optimal compression
1793  * ratio, which for LZX is probably impossible within any practical amount of
1794  * time, but rather to produce a compression ratio significantly better than a
1795  * simpler "greedy" or "lazy" parse while still being relatively fast.
1796  */
1797 static inline void
1798 lzx_compress_near_optimal(struct lzx_compressor *c,
1799                           struct lzx_output_bitstream *os,
1800                           bool is_16_bit)
1801 {
1802         const u8 * const in_begin = c->in_buffer;
1803         const u8 *       in_next = in_begin;
1804         const u8 * const in_end  = in_begin + c->in_nbytes;
1805         u32 max_len = LZX_MAX_MATCH_LEN;
1806         u32 nice_len = min(c->nice_match_length, max_len);
1807         u32 next_hashes[2] = {};
1808         struct lzx_lru_queue queue;
1809
1810         CALL_BT_MF(is_16_bit, c, bt_matchfinder_init);
1811         lzx_lru_queue_init(&queue);
1812
1813         do {
1814                 /* Starting a new block  */
1815                 const u8 * const in_block_begin = in_next;
1816                 const u8 * const in_block_end =
1817                         in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
1818
1819                 /* Run the block through the matchfinder and cache the matches. */
1820                 struct lz_match *cache_ptr = c->match_cache;
1821                 do {
1822                         struct lz_match *lz_matchptr;
1823                         u32 best_len;
1824
1825                         /* If approaching the end of the input buffer, adjust
1826                          * 'max_len' and 'nice_len' accordingly.  */
1827                         if (unlikely(max_len > in_end - in_next)) {
1828                                 max_len = in_end - in_next;
1829                                 nice_len = min(max_len, nice_len);
1830                                 if (unlikely(max_len <
1831                                              BT_MATCHFINDER_REQUIRED_NBYTES))
1832                                 {
1833                                         in_next++;
1834                                         cache_ptr->length = 0;
1835                                         cache_ptr++;
1836                                         continue;
1837                                 }
1838                         }
1839
1840                         /* Check for matches.  */
1841                         lz_matchptr = CALL_BT_MF(is_16_bit, c,
1842                                                  bt_matchfinder_get_matches,
1843                                                  in_begin,
1844                                                  in_next - in_begin,
1845                                                  max_len,
1846                                                  nice_len,
1847                                                  c->max_search_depth,
1848                                                  next_hashes,
1849                                                  &best_len,
1850                                                  cache_ptr + 1);
1851                         in_next++;
1852                         cache_ptr->length = lz_matchptr - (cache_ptr + 1);
1853                         cache_ptr = lz_matchptr;
1854
1855                         /*
1856                          * If there was a very long match found, then don't
1857                          * cache any matches for the bytes covered by that
1858                          * match.  This avoids degenerate behavior when
1859                          * compressing highly redundant data, where the number
1860                          * of matches can be very large.
1861                          *
1862                          * This heuristic doesn't actually hurt the compression
1863                          * ratio very much.  If there's a long match, then the
1864                          * data must be highly compressible, so it doesn't
1865                          * matter as much what we do.
1866                          */
1867                         if (best_len >= nice_len) {
1868                                 --best_len;
1869                                 do {
1870                                         if (unlikely(max_len > in_end - in_next)) {
1871                                                 max_len = in_end - in_next;
1872                                                 nice_len = min(max_len, nice_len);
1873                                                 if (unlikely(max_len <
1874                                                              BT_MATCHFINDER_REQUIRED_NBYTES))
1875                                                 {
1876                                                         in_next++;
1877                                                         cache_ptr->length = 0;
1878                                                         cache_ptr++;
1879                                                         continue;
1880                                                 }
1881                                         }
1882                                         CALL_BT_MF(is_16_bit, c,
1883                                                    bt_matchfinder_skip_position,
1884                                                    in_begin,
1885                                                    in_next - in_begin,
1886                                                    nice_len,
1887                                                    c->max_search_depth,
1888                                                    next_hashes);
1889                                         in_next++;
1890                                         cache_ptr->length = 0;
1891                                         cache_ptr++;
1892                                 } while (--best_len);
1893                         }
1894                 } while (in_next < in_block_end &&
1895                          likely(cache_ptr < &c->match_cache[LZX_CACHE_LENGTH]));
1896
1897                 /* We've finished running the block through the matchfinder.
1898                  * Now choose a match/literal sequence and write the block.  */
1899
1900                 queue = lzx_optimize_and_write_block(c, os, in_block_begin,
1901                                                      in_next - in_block_begin,
1902                                                      queue, is_16_bit);
1903         } while (in_next != in_end);
1904 }
1905
1906 static void
1907 lzx_compress_near_optimal_16(struct lzx_compressor *c,
1908                              struct lzx_output_bitstream *os)
1909 {
1910         lzx_compress_near_optimal(c, os, true);
1911 }
1912
1913 static void
1914 lzx_compress_near_optimal_32(struct lzx_compressor *c,
1915                              struct lzx_output_bitstream *os)
1916 {
1917         lzx_compress_near_optimal(c, os, false);
1918 }
1919
1920 /*
1921  * Given a pointer to the current byte sequence and the current list of recent
1922  * match offsets, find the longest repeat offset match.
1923  *
1924  * If no match of at least 2 bytes is found, then return 0.
1925  *
1926  * If a match of at least 2 bytes is found, then return its length and set
1927  * *rep_max_idx_ret to the index of its offset in @queue.
1928 */
1929 static unsigned
1930 lzx_find_longest_repeat_offset_match(const u8 * const in_next,
1931                                      const u32 bytes_remaining,
1932                                      const u32 recent_offsets[LZX_NUM_RECENT_OFFSETS],
1933                                      unsigned *rep_max_idx_ret)
1934 {
1935         STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
1936
1937         const unsigned max_len = min(bytes_remaining, LZX_MAX_MATCH_LEN);
1938         const u16 next_2_bytes = load_u16_unaligned(in_next);
1939         const u8 *matchptr;
1940         unsigned rep_max_len;
1941         unsigned rep_max_idx;
1942         unsigned rep_len;
1943
1944         matchptr = in_next - recent_offsets[0];
1945         if (load_u16_unaligned(matchptr) == next_2_bytes)
1946                 rep_max_len = lz_extend(in_next, matchptr, 2, max_len);
1947         else
1948                 rep_max_len = 0;
1949         rep_max_idx = 0;
1950
1951         matchptr = in_next - recent_offsets[1];
1952         if (load_u16_unaligned(matchptr) == next_2_bytes) {
1953                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1954                 if (rep_len > rep_max_len) {
1955                         rep_max_len = rep_len;
1956                         rep_max_idx = 1;
1957                 }
1958         }
1959
1960         matchptr = in_next - recent_offsets[2];
1961         if (load_u16_unaligned(matchptr) == next_2_bytes) {
1962                 rep_len = lz_extend(in_next, matchptr, 2, max_len);
1963                 if (rep_len > rep_max_len) {
1964                         rep_max_len = rep_len;
1965                         rep_max_idx = 2;
1966                 }
1967         }
1968
1969         *rep_max_idx_ret = rep_max_idx;
1970         return rep_max_len;
1971 }
1972
1973 /* Fast heuristic scoring for lazy parsing: how "good" is this match?  */
1974 static inline unsigned
1975 lzx_explicit_offset_match_score(unsigned len, u32 adjusted_offset)
1976 {
1977         unsigned score = len;
1978
1979         if (adjusted_offset < 4096)
1980                 score++;
1981
1982         if (adjusted_offset < 256)
1983                 score++;
1984
1985         return score;
1986 }
1987
1988 static inline unsigned
1989 lzx_repeat_offset_match_score(unsigned rep_len, unsigned rep_idx)
1990 {
1991         return rep_len + 3;
1992 }
1993
1994 /* This is the "lazy" LZX compressor.  */
1995 static inline void
1996 lzx_compress_lazy(struct lzx_compressor *c, struct lzx_output_bitstream *os,
1997                   bool is_16_bit)
1998 {
1999         const u8 * const in_begin = c->in_buffer;
2000         const u8 *       in_next = in_begin;
2001         const u8 * const in_end  = in_begin + c->in_nbytes;
2002         unsigned max_len = LZX_MAX_MATCH_LEN;
2003         unsigned nice_len = min(c->nice_match_length, max_len);
2004         STATIC_ASSERT(LZX_NUM_RECENT_OFFSETS == 3);
2005         u32 recent_offsets[3] = {1, 1, 1};
2006         u32 next_hashes[2] = {};
2007
2008         CALL_HC_MF(is_16_bit, c, hc_matchfinder_init);
2009
2010         do {
2011                 /* Starting a new block  */
2012
2013                 const u8 * const in_block_begin = in_next;
2014                 const u8 * const in_block_end =
2015                         in_next + min(LZX_DIV_BLOCK_SIZE, in_end - in_next);
2016                 struct lzx_sequence *next_seq = c->chosen_sequences;
2017                 unsigned cur_len;
2018                 u32 cur_offset;
2019                 u32 cur_offset_data;
2020                 unsigned cur_score;
2021                 unsigned next_len;
2022                 u32 next_offset;
2023                 u32 next_offset_data;
2024                 unsigned next_score;
2025                 unsigned rep_max_len;
2026                 unsigned rep_max_idx;
2027                 unsigned rep_score;
2028                 unsigned skip_len;
2029                 u32 litrunlen = 0;
2030
2031                 lzx_reset_symbol_frequencies(c);
2032
2033                 do {
2034                         if (unlikely(max_len > in_end - in_next)) {
2035                                 max_len = in_end - in_next;
2036                                 nice_len = min(max_len, nice_len);
2037                         }
2038
2039                         /* Find the longest match at the current position.  */
2040
2041                         cur_len = CALL_HC_MF(is_16_bit, c,
2042                                              hc_matchfinder_longest_match,
2043                                              in_begin,
2044                                              in_next - in_begin,
2045                                              2,
2046                                              max_len,
2047                                              nice_len,
2048                                              c->max_search_depth,
2049                                              next_hashes,
2050                                              &cur_offset);
2051                         if (cur_len < 3 ||
2052                             (cur_len == 3 &&
2053                              cur_offset >= 8192 - LZX_OFFSET_ADJUSTMENT &&
2054                              cur_offset != recent_offsets[0] &&
2055                              cur_offset != recent_offsets[1] &&
2056                              cur_offset != recent_offsets[2]))
2057                         {
2058                                 /* There was no match found, or the only match found
2059                                  * was a distant length 3 match.  Output a literal.  */
2060                                 lzx_record_literal(c, *in_next++, &litrunlen);
2061                                 continue;
2062                         }
2063
2064                         if (cur_offset == recent_offsets[0]) {
2065                                 in_next++;
2066                                 cur_offset_data = 0;
2067                                 skip_len = cur_len - 1;
2068                                 goto choose_cur_match;
2069                         }
2070
2071                         cur_offset_data = cur_offset + LZX_OFFSET_ADJUSTMENT;
2072                         cur_score = lzx_explicit_offset_match_score(cur_len, cur_offset_data);
2073
2074                         /* Consider a repeat offset match  */
2075                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2076                                                                            in_end - in_next,
2077                                                                            recent_offsets,
2078                                                                            &rep_max_idx);
2079                         in_next++;
2080
2081                         if (rep_max_len >= 3 &&
2082                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2083                                                                        rep_max_idx)) >= cur_score)
2084                         {
2085                                 cur_len = rep_max_len;
2086                                 cur_offset_data = rep_max_idx;
2087                                 skip_len = rep_max_len - 1;
2088                                 goto choose_cur_match;
2089                         }
2090
2091                 have_cur_match:
2092
2093                         /* We have a match at the current position.  */
2094
2095                         /* If we have a very long match, choose it immediately.  */
2096                         if (cur_len >= nice_len) {
2097                                 skip_len = cur_len - 1;
2098                                 goto choose_cur_match;
2099                         }
2100
2101                         /* See if there's a better match at the next position.  */
2102
2103                         if (unlikely(max_len > in_end - in_next)) {
2104                                 max_len = in_end - in_next;
2105                                 nice_len = min(max_len, nice_len);
2106                         }
2107
2108                         next_len = CALL_HC_MF(is_16_bit, c,
2109                                               hc_matchfinder_longest_match,
2110                                               in_begin,
2111                                               in_next - in_begin,
2112                                               cur_len - 2,
2113                                               max_len,
2114                                               nice_len,
2115                                               c->max_search_depth / 2,
2116                                               next_hashes,
2117                                               &next_offset);
2118
2119                         if (next_len <= cur_len - 2) {
2120                                 in_next++;
2121                                 skip_len = cur_len - 2;
2122                                 goto choose_cur_match;
2123                         }
2124
2125                         next_offset_data = next_offset + LZX_OFFSET_ADJUSTMENT;
2126                         next_score = lzx_explicit_offset_match_score(next_len, next_offset_data);
2127
2128                         rep_max_len = lzx_find_longest_repeat_offset_match(in_next,
2129                                                                            in_end - in_next,
2130                                                                            recent_offsets,
2131                                                                            &rep_max_idx);
2132                         in_next++;
2133
2134                         if (rep_max_len >= 3 &&
2135                             (rep_score = lzx_repeat_offset_match_score(rep_max_len,
2136                                                                        rep_max_idx)) >= next_score)
2137                         {
2138
2139                                 if (rep_score > cur_score) {
2140                                         /* The next match is better, and it's a
2141                                          * repeat offset match.  */
2142                                         lzx_record_literal(c, *(in_next - 2),
2143                                                            &litrunlen);
2144                                         cur_len = rep_max_len;
2145                                         cur_offset_data = rep_max_idx;
2146                                         skip_len = cur_len - 1;
2147                                         goto choose_cur_match;
2148                                 }
2149                         } else {
2150                                 if (next_score > cur_score) {
2151                                         /* The next match is better, and it's an
2152                                          * explicit offset match.  */
2153                                         lzx_record_literal(c, *(in_next - 2),
2154                                                            &litrunlen);
2155                                         cur_len = next_len;
2156                                         cur_offset_data = next_offset_data;
2157                                         cur_score = next_score;
2158                                         goto have_cur_match;
2159                                 }
2160                         }
2161
2162                         /* The original match was better.  */
2163                         skip_len = cur_len - 2;
2164
2165                 choose_cur_match:
2166                         lzx_record_match(c, cur_len, cur_offset_data,
2167                                          recent_offsets, is_16_bit,
2168                                          &litrunlen, &next_seq);
2169                         in_next = CALL_HC_MF(is_16_bit, c,
2170                                              hc_matchfinder_skip_positions,
2171                                              in_begin,
2172                                              in_next - in_begin,
2173                                              in_end - in_begin,
2174                                              skip_len,
2175                                              next_hashes);
2176                 } while (in_next < in_block_end);
2177
2178                 lzx_finish_sequence(next_seq, litrunlen);
2179
2180                 lzx_finish_block(c, os, in_block_begin, in_next - in_block_begin, 0);
2181
2182         } while (in_next != in_end);
2183 }
2184
2185 static void
2186 lzx_compress_lazy_16(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2187 {
2188         lzx_compress_lazy(c, os, true);
2189 }
2190
2191 static void
2192 lzx_compress_lazy_32(struct lzx_compressor *c, struct lzx_output_bitstream *os)
2193 {
2194         lzx_compress_lazy(c, os, false);
2195 }
2196
2197 /* Generate the acceleration tables for offset slots.  */
2198 static void
2199 lzx_init_offset_slot_tabs(struct lzx_compressor *c)
2200 {
2201         u32 adjusted_offset = 0;
2202         unsigned slot = 0;
2203
2204         /* slots [0, 29]  */
2205         for (; adjusted_offset < ARRAY_LEN(c->offset_slot_tab_1);
2206              adjusted_offset++)
2207         {
2208                 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2209                         slot++;
2210                 c->offset_slot_tab_1[adjusted_offset] = slot;
2211         }
2212
2213         /* slots [30, 49]  */
2214         for (; adjusted_offset < LZX_MAX_WINDOW_SIZE;
2215              adjusted_offset += (u32)1 << 14)
2216         {
2217                 if (adjusted_offset >= lzx_offset_slot_base[slot + 1])
2218                         slot++;
2219                 c->offset_slot_tab_2[adjusted_offset >> 14] = slot;
2220         }
2221 }
2222
2223 static size_t
2224 lzx_get_compressor_size(size_t max_bufsize, unsigned compression_level)
2225 {
2226         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2227                 if (lzx_is_16_bit(max_bufsize))
2228                         return offsetof(struct lzx_compressor, hc_mf_16) +
2229                                hc_matchfinder_size_16(max_bufsize);
2230                 else
2231                         return offsetof(struct lzx_compressor, hc_mf_32) +
2232                                hc_matchfinder_size_32(max_bufsize);
2233         } else {
2234                 if (lzx_is_16_bit(max_bufsize))
2235                         return offsetof(struct lzx_compressor, bt_mf_16) +
2236                                bt_matchfinder_size_16(max_bufsize);
2237                 else
2238                         return offsetof(struct lzx_compressor, bt_mf_32) +
2239                                bt_matchfinder_size_32(max_bufsize);
2240         }
2241 }
2242
2243 static u64
2244 lzx_get_needed_memory(size_t max_bufsize, unsigned compression_level,
2245                       bool destructive)
2246 {
2247         u64 size = 0;
2248
2249         if (max_bufsize > LZX_MAX_WINDOW_SIZE)
2250                 return 0;
2251
2252         size += lzx_get_compressor_size(max_bufsize, compression_level);
2253         if (!destructive)
2254                 size += max_bufsize; /* in_buffer */
2255         return size;
2256 }
2257
2258 static int
2259 lzx_create_compressor(size_t max_bufsize, unsigned compression_level,
2260                       bool destructive, void **c_ret)
2261 {
2262         unsigned window_order;
2263         struct lzx_compressor *c;
2264
2265         window_order = lzx_get_window_order(max_bufsize);
2266         if (window_order == 0)
2267                 return WIMLIB_ERR_INVALID_PARAM;
2268
2269         c = MALLOC(lzx_get_compressor_size(max_bufsize, compression_level));
2270         if (!c)
2271                 goto oom0;
2272
2273         c->destructive = destructive;
2274
2275         c->num_main_syms = lzx_get_num_main_syms(window_order);
2276         c->window_order = window_order;
2277
2278         if (!c->destructive) {
2279                 c->in_buffer = MALLOC(max_bufsize);
2280                 if (!c->in_buffer)
2281                         goto oom1;
2282         }
2283
2284         if (compression_level <= LZX_MAX_FAST_LEVEL) {
2285
2286                 /* Fast compression: Use lazy parsing.  */
2287
2288                 if (lzx_is_16_bit(max_bufsize))
2289                         c->impl = lzx_compress_lazy_16;
2290                 else
2291                         c->impl = lzx_compress_lazy_32;
2292                 c->max_search_depth = (60 * compression_level) / 20;
2293                 c->nice_match_length = (80 * compression_level) / 20;
2294
2295                 /* lzx_compress_lazy() needs max_search_depth >= 2 because it
2296                  * halves the max_search_depth when attempting a lazy match, and
2297                  * max_search_depth cannot be 0.  */
2298                 if (c->max_search_depth < 2)
2299                         c->max_search_depth = 2;
2300         } else {
2301
2302                 /* Normal / high compression: Use near-optimal parsing.  */
2303
2304                 if (lzx_is_16_bit(max_bufsize))
2305                         c->impl = lzx_compress_near_optimal_16;
2306                 else
2307                         c->impl = lzx_compress_near_optimal_32;
2308
2309                 /* Scale nice_match_length and max_search_depth with the
2310                  * compression level.  */
2311                 c->max_search_depth = (24 * compression_level) / 50;
2312                 c->nice_match_length = (48 * compression_level) / 50;
2313
2314                 /* Set a number of optimization passes appropriate for the
2315                  * compression level.  */
2316
2317                 c->num_optim_passes = 1;
2318
2319                 if (compression_level >= 45)
2320                         c->num_optim_passes++;
2321
2322                 /* Use more optimization passes for higher compression levels.
2323                  * But the more passes there are, the less they help --- so
2324                  * don't add them linearly.  */
2325                 if (compression_level >= 70) {
2326                         c->num_optim_passes++;
2327                         if (compression_level >= 100)
2328                                 c->num_optim_passes++;
2329                         if (compression_level >= 150)
2330                                 c->num_optim_passes++;
2331                         if (compression_level >= 200)
2332                                 c->num_optim_passes++;
2333                         if (compression_level >= 300)
2334                                 c->num_optim_passes++;
2335                 }
2336         }
2337
2338         /* max_search_depth == 0 is invalid.  */
2339         if (c->max_search_depth < 1)
2340                 c->max_search_depth = 1;
2341
2342         if (c->nice_match_length > LZX_MAX_MATCH_LEN)
2343                 c->nice_match_length = LZX_MAX_MATCH_LEN;
2344
2345         lzx_init_offset_slot_tabs(c);
2346         *c_ret = c;
2347         return 0;
2348
2349 oom1:
2350         FREE(c);
2351 oom0:
2352         return WIMLIB_ERR_NOMEM;
2353 }
2354
2355 static size_t
2356 lzx_compress(const void *restrict in, size_t in_nbytes,
2357              void *restrict out, size_t out_nbytes_avail, void *restrict _c)
2358 {
2359         struct lzx_compressor *c = _c;
2360         struct lzx_output_bitstream os;
2361         size_t result;
2362
2363         /* Don't bother trying to compress very small inputs.  */
2364         if (in_nbytes < 100)
2365                 return 0;
2366
2367         /* Copy the input data into the internal buffer and preprocess it.  */
2368         if (c->destructive)
2369                 c->in_buffer = (void *)in;
2370         else
2371                 memcpy(c->in_buffer, in, in_nbytes);
2372         c->in_nbytes = in_nbytes;
2373         lzx_preprocess(c->in_buffer, in_nbytes);
2374
2375         /* Initially, the previous Huffman codeword lengths are all zeroes.  */
2376         c->codes_index = 0;
2377         memset(&c->codes[1].lens, 0, sizeof(struct lzx_lens));
2378
2379         /* Initialize the output bitstream.  */
2380         lzx_init_output(&os, out, out_nbytes_avail);
2381
2382         /* Call the compression level-specific compress() function.  */
2383         (*c->impl)(c, &os);
2384
2385         /* Flush the output bitstream and return the compressed size or 0.  */
2386         result = lzx_flush_output(&os);
2387         if (!result && c->destructive)
2388                 lzx_postprocess(c->in_buffer, c->in_nbytes);
2389         return result;
2390 }
2391
2392 static void
2393 lzx_free_compressor(void *_c)
2394 {
2395         struct lzx_compressor *c = _c;
2396
2397         if (!c->destructive)
2398                 FREE(c->in_buffer);
2399         FREE(c);
2400 }
2401
2402 const struct compressor_ops lzx_compressor_ops = {
2403         .get_needed_memory  = lzx_get_needed_memory,
2404         .create_compressor  = lzx_create_compressor,
2405         .compress           = lzx_compress,
2406         .free_compressor    = lzx_free_compressor,
2407 };