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