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