]> wimlib.net Git - wimlib/blob - src/lzms-compress.c
lzms-compress.c: Remove unused constant
[wimlib] / src / lzms-compress.c
1 /*
2  * lzms-compress.c
3  */
4
5 /*
6  * Copyright (C) 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 /* This a compressor for the LZMS compression format.  More details about this
25  * format can be found in lzms-decompress.c.
26  *
27  * NOTE: this compressor currently does not code any delta matches.
28  */
29
30 #ifdef HAVE_CONFIG_H
31 #  include "config.h"
32 #endif
33
34 #include "wimlib.h"
35 #include "wimlib/compiler.h"
36 #include "wimlib/compressor_ops.h"
37 #include "wimlib/compress_common.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/lz_sarray.h"
41 #include "wimlib/lzms.h"
42 #include "wimlib/util.h"
43
44 #include <string.h>
45 #include <limits.h>
46 #include <pthread.h>
47
48 struct lzms_compressor;
49 struct lzms_adaptive_state {
50         struct lzms_lz_lru_queues lru;
51         u8 main_state;
52         u8 match_state;
53         u8 lz_match_state;
54         u8 lz_repeat_match_state[LZMS_NUM_RECENT_OFFSETS - 1];
55 };
56 #define LZ_ADAPTIVE_STATE struct lzms_adaptive_state
57 #define LZ_COMPRESSOR     struct lzms_compressor
58 #include "wimlib/lz_optimal.h"
59
60 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
61  * a series of 16-bit little endian coding units.  */
62 struct lzms_output_bitstream {
63         /* Buffer variable containing zero or more bits that have been logically
64          * written to the bitstream but not yet written to memory.  This must be
65          * at least as large as the coding unit size.  */
66         u16 bitbuf;
67
68         /* Number of bits in @bitbuf that are valid.  */
69         unsigned num_free_bits;
70
71         /* Pointer to one past the next position in the compressed data buffer
72          * at which to output a 16-bit coding unit.  */
73         le16 *out;
74
75         /* Maximum number of 16-bit coding units that can still be output to
76          * the compressed data buffer.  */
77         size_t num_le16_remaining;
78
79         /* Set to %true if not all coding units could be output due to
80          * insufficient space.  */
81         bool overrun;
82 };
83
84 /* Stucture used for range encoding (raw version).  */
85 struct lzms_range_encoder_raw {
86
87         /* A 33-bit variable that holds the low boundary of the current range.
88          * The 33rd bit is needed to catch carries.  */
89         u64 low;
90
91         /* Size of the current range.  */
92         u32 range;
93
94         /* Next 16-bit coding unit to output.  */
95         u16 cache;
96
97         /* Number of 16-bit coding units whose output has been delayed due to
98          * possible carrying.  The first such coding unit is @cache; all
99          * subsequent such coding units are 0xffff.  */
100         u32 cache_size;
101
102         /* Pointer to the next position in the compressed data buffer at which
103          * to output a 16-bit coding unit.  */
104         le16 *out;
105
106         /* Maximum number of 16-bit coding units that can still be output to
107          * the compressed data buffer.  */
108         size_t num_le16_remaining;
109
110         /* %true when the very first coding unit has not yet been output.  */
111         bool first;
112
113         /* Set to %true if not all coding units could be output due to
114          * insufficient space.  */
115         bool overrun;
116 };
117
118 /* Structure used for range encoding.  This wraps around `struct
119  * lzms_range_encoder_raw' to use and maintain probability entries.  */
120 struct lzms_range_encoder {
121         /* Pointer to the raw range encoder, which has no persistent knowledge
122          * of probabilities.  Multiple lzms_range_encoder's share the same
123          * lzms_range_encoder_raw.  */
124         struct lzms_range_encoder_raw *rc;
125
126         /* Bits recently encoded by this range encoder.  This are used as in
127          * index into @prob_entries.  */
128         u32 state;
129
130         /* Bitmask for @state to prevent its value from exceeding the number of
131          * probability entries.  */
132         u32 mask;
133
134         /* Probability entries being used for this range encoder.  */
135         struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
136 };
137
138 /* Structure used for Huffman encoding.  */
139 struct lzms_huffman_encoder {
140
141         /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
142          * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
143          */
144         struct lzms_output_bitstream *os;
145
146         /* Number of symbols that have been written using this code far.  Reset
147          * to 0 whenever the code is rebuilt.  */
148         u32 num_syms_written;
149
150         /* When @num_syms_written reaches this number, the Huffman code must be
151          * rebuilt.  */
152         u32 rebuild_freq;
153
154         /* Number of symbols in the represented Huffman code.  */
155         unsigned num_syms;
156
157         /* Running totals of symbol frequencies.  These are diluted slightly
158          * whenever the code is rebuilt.  */
159         u32 sym_freqs[LZMS_MAX_NUM_SYMS];
160
161         /* The length, in bits, of each symbol in the Huffman code.  */
162         u8 lens[LZMS_MAX_NUM_SYMS];
163
164         /* The codeword of each symbol in the Huffman code.  */
165         u16 codewords[LZMS_MAX_NUM_SYMS];
166 };
167
168 /* State of the LZMS compressor.  */
169 struct lzms_compressor {
170         /* Pointer to a buffer holding the preprocessed data to compress.  */
171         u8 *window;
172
173         /* Current position in @buffer.  */
174         u32 cur_window_pos;
175
176         /* Size of the data in @buffer.  */
177         u32 window_size;
178
179         /* Suffix array match-finder.  */
180         struct lz_sarray lz_sarray;
181
182         /* Temporary space to store found matches.  */
183         struct raw_match *matches;
184
185         /* Match-chooser.  */
186         struct lz_match_chooser mc;
187
188         /* Maximum block size this compressor instantiation allows.  This is the
189          * allocated size of @window.  */
190         u32 max_block_size;
191
192         /* Raw range encoder which outputs to the beginning of the compressed
193          * data buffer, proceeding forwards.  */
194         struct lzms_range_encoder_raw rc;
195
196         /* Bitstream which outputs to the end of the compressed data buffer,
197          * proceeding backwards.  */
198         struct lzms_output_bitstream os;
199
200         /* Range encoders.  */
201         struct lzms_range_encoder main_range_encoder;
202         struct lzms_range_encoder match_range_encoder;
203         struct lzms_range_encoder lz_match_range_encoder;
204         struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
205         struct lzms_range_encoder delta_match_range_encoder;
206         struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
207
208         /* Huffman encoders.  */
209         struct lzms_huffman_encoder literal_encoder;
210         struct lzms_huffman_encoder lz_offset_encoder;
211         struct lzms_huffman_encoder length_encoder;
212         struct lzms_huffman_encoder delta_power_encoder;
213         struct lzms_huffman_encoder delta_offset_encoder;
214
215         /* LRU (least-recently-used) queues for match information.  */
216         struct lzms_lru_queues lru;
217
218         /* Used for preprocessing.  */
219         s32 last_target_usages[65536];
220 };
221
222 /* Initialize the output bitstream @os to write forwards to the specified
223  * compressed data buffer @out that is @out_limit 16-bit integers long.  */
224 static void
225 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
226                            le16 *out, size_t out_limit)
227 {
228         os->bitbuf = 0;
229         os->num_free_bits = 16;
230         os->out = out + out_limit;
231         os->num_le16_remaining = out_limit;
232         os->overrun = false;
233 }
234
235 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
236  * from high-order to low-order), to the output bitstream @os.  */
237 static void
238 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
239                                u32 bits, unsigned num_bits)
240 {
241         bits &= (1U << num_bits) - 1;
242
243         while (num_bits > os->num_free_bits) {
244
245                 if (unlikely(os->num_le16_remaining == 0)) {
246                         os->overrun = true;
247                         return;
248                 }
249
250                 unsigned num_fill_bits = os->num_free_bits;
251
252                 os->bitbuf <<= num_fill_bits;
253                 os->bitbuf |= bits >> (num_bits - num_fill_bits);
254
255                 *--os->out = cpu_to_le16(os->bitbuf);
256                 --os->num_le16_remaining;
257
258                 os->num_free_bits = 16;
259                 num_bits -= num_fill_bits;
260                 bits &= (1U << num_bits) - 1;
261         }
262         os->bitbuf <<= num_bits;
263         os->bitbuf |= bits;
264         os->num_free_bits -= num_bits;
265 }
266
267 /* Flush the output bitstream, ensuring that all bits written to it have been
268  * written to memory.  Returns %true if all bits were output successfully, or
269  * %false if an overrun occurred.  */
270 static bool
271 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
272 {
273         if (os->num_free_bits != 16)
274                 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
275         return !os->overrun;
276 }
277
278 /* Initialize the range encoder @rc to write forwards to the specified
279  * compressed data buffer @out that is @out_limit 16-bit integers long.  */
280 static void
281 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
282                             le16 *out, size_t out_limit)
283 {
284         rc->low = 0;
285         rc->range = 0xffffffff;
286         rc->cache = 0;
287         rc->cache_size = 1;
288         rc->out = out;
289         rc->num_le16_remaining = out_limit;
290         rc->first = true;
291         rc->overrun = false;
292 }
293
294 /*
295  * Attempt to flush bits from the range encoder.
296  *
297  * Note: this is based on the public domain code for LZMA written by Igor
298  * Pavlov.  The only differences in this function are that in LZMS the bits must
299  * be output in 16-bit coding units instead of 8-bit coding units, and that in
300  * LZMS the first coding unit is not ignored by the decompressor, so the encoder
301  * cannot output a dummy value to that position.
302  *
303  * The basic idea is that we're writing bits from @rc->low to the output.
304  * However, due to carrying, the writing of coding units with value 0xffff, as
305  * well as one prior coding unit, must be delayed until it is determined whether
306  * a carry is needed.
307  */
308 static void
309 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
310 {
311         LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
312                    rc->low, rc->cache, rc->cache_size);
313         if ((u32)(rc->low) < 0xffff0000 ||
314             (u32)(rc->low >> 32) != 0)
315         {
316                 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
317                  * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1).  */
318                 do {
319                         if (!rc->first) {
320                                 if (rc->num_le16_remaining == 0) {
321                                         rc->overrun = true;
322                                         return;
323                                 }
324                                 *rc->out++ = cpu_to_le16(rc->cache +
325                                                          (u16)(rc->low >> 32));
326                                 --rc->num_le16_remaining;
327                         } else {
328                                 rc->first = false;
329                         }
330
331                         rc->cache = 0xffff;
332                 } while (--rc->cache_size != 0);
333
334                 rc->cache = (rc->low >> 16) & 0xffff;
335         }
336         ++rc->cache_size;
337         rc->low = (rc->low & 0xffff) << 16;
338 }
339
340 static void
341 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
342 {
343         if (rc->range <= 0xffff) {
344                 rc->range <<= 16;
345                 lzms_range_encoder_raw_shift_low(rc);
346         }
347 }
348
349 static bool
350 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
351 {
352         for (unsigned i = 0; i < 4; i++)
353                 lzms_range_encoder_raw_shift_low(rc);
354         return !rc->overrun;
355 }
356
357 /* Encode the next bit using the range encoder (raw version).
358  *
359  * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0.  */
360 static void
361 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
362                                   u32 prob)
363 {
364         lzms_range_encoder_raw_normalize(rc);
365
366         u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
367         if (bit == 0) {
368                 rc->range = bound;
369         } else {
370                 rc->low += bound;
371                 rc->range -= bound;
372         }
373 }
374
375 /* Encode a bit using the specified range encoder. This wraps around
376  * lzms_range_encoder_raw_encode_bit() to handle using and updating the
377  * appropriate probability table.  */
378 static void
379 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
380 {
381         struct lzms_probability_entry *prob_entry;
382         u32 prob;
383
384         /* Load the probability entry corresponding to the current state.  */
385         prob_entry = &enc->prob_entries[enc->state];
386
387         /* Treat the number of zero bits in the most recently encoded
388          * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
389          * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0.  However,
390          * don't allow 0% or 100% probabilities.  */
391         prob = prob_entry->num_recent_zero_bits;
392         if (prob == 0)
393                 prob = 1;
394         else if (prob == LZMS_PROBABILITY_MAX)
395                 prob = LZMS_PROBABILITY_MAX - 1;
396
397         /* Encode the next bit.  */
398         lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
399
400         /* Update the state based on the newly encoded bit.  */
401         enc->state = ((enc->state << 1) | bit) & enc->mask;
402
403         /* Update the recent bits, including the cached count of 0's.  */
404         BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
405         if (bit == 0) {
406                 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
407                         /* Replacing 1 bit with 0 bit; increment the zero count.
408                          */
409                         prob_entry->num_recent_zero_bits++;
410                 }
411         } else {
412                 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
413                         /* Replacing 0 bit with 1 bit; decrement the zero count.
414                          */
415                         prob_entry->num_recent_zero_bits--;
416                 }
417         }
418         prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
419 }
420
421 /* Encode a symbol using the specified Huffman encoder.  */
422 static void
423 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
424 {
425         LZMS_ASSERT(sym < enc->num_syms);
426         lzms_output_bitstream_put_bits(enc->os,
427                                        enc->codewords[sym],
428                                        enc->lens[sym]);
429         ++enc->sym_freqs[sym];
430         if (++enc->num_syms_written == enc->rebuild_freq) {
431                 /* Adaptive code needs to be rebuilt.  */
432                 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
433                 make_canonical_huffman_code(enc->num_syms,
434                                             LZMS_MAX_CODEWORD_LEN,
435                                             enc->sym_freqs,
436                                             enc->lens,
437                                             enc->codewords);
438
439                 /* Dilute the frequencies.  */
440                 for (unsigned i = 0; i < enc->num_syms; i++) {
441                         enc->sym_freqs[i] >>= 1;
442                         enc->sym_freqs[i] += 1;
443                 }
444                 enc->num_syms_written = 0;
445         }
446 }
447
448 static void
449 lzms_encode_length(struct lzms_huffman_encoder *enc, u32 length)
450 {
451         unsigned slot;
452         unsigned num_extra_bits;
453         u32 extra_bits;
454
455         slot = lzms_get_length_slot(length);
456
457         num_extra_bits = lzms_extra_length_bits[slot];
458
459         extra_bits = length - lzms_length_slot_base[slot];
460
461         lzms_huffman_encode_symbol(enc, slot);
462         lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
463 }
464
465 static void
466 lzms_encode_offset(struct lzms_huffman_encoder *enc, u32 offset)
467 {
468         unsigned slot;
469         unsigned num_extra_bits;
470         u32 extra_bits;
471
472         slot = lzms_get_position_slot(offset);
473
474         num_extra_bits = lzms_extra_position_bits[slot];
475
476         extra_bits = offset - lzms_position_slot_base[slot];
477
478         lzms_huffman_encode_symbol(enc, slot);
479         lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
480 }
481
482 static void
483 lzms_begin_encode_item(struct lzms_compressor *ctx)
484 {
485         ctx->lru.lz.upcoming_offset = 0;
486         ctx->lru.delta.upcoming_offset = 0;
487         ctx->lru.delta.upcoming_power = 0;
488 }
489
490 static void
491 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
492 {
493         LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
494         ctx->cur_window_pos += length;
495         lzms_update_lru_queues(&ctx->lru);
496 }
497
498 /* Encode a literal byte.  */
499 static void
500 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
501 {
502         LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
503                    ctx->cur_window_pos, literal, literal);
504
505         lzms_begin_encode_item(ctx);
506
507         /* Main bit: 0 = a literal, not a match.  */
508         lzms_range_encode_bit(&ctx->main_range_encoder, 0);
509
510         /* Encode the literal using the current literal Huffman code.  */
511         lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
512
513         lzms_end_encode_item(ctx, 1);
514 }
515
516 /* Encode a (length, offset) pair (LZ match).  */
517 static void
518 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
519 {
520         int recent_offset_idx;
521
522         LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
523                    ctx->cur_window_pos, length, offset);
524
525         LZMS_ASSERT(length <= ctx->window_size - ctx->cur_window_pos);
526         LZMS_ASSERT(offset <= ctx->cur_window_pos);
527         LZMS_ASSERT(!memcmp(&ctx->window[ctx->cur_window_pos],
528                             &ctx->window[ctx->cur_window_pos - offset],
529                             length));
530
531         lzms_begin_encode_item(ctx);
532
533         /* Main bit: 1 = a match, not a literal.  */
534         lzms_range_encode_bit(&ctx->main_range_encoder, 1);
535
536         /* Match bit: 0 = a LZ match, not a delta match.  */
537         lzms_range_encode_bit(&ctx->match_range_encoder, 0);
538
539         /* Determine if the offset can be represented as a recent offset.  */
540         for (recent_offset_idx = 0;
541              recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
542              recent_offset_idx++)
543                 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
544                         break;
545
546         if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
547                 /* Explicit offset.  */
548
549                 /* LZ match bit: 0 = explicit offset, not a recent offset.  */
550                 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
551
552                 /* Encode the match offset.  */
553                 lzms_encode_offset(&ctx->lz_offset_encoder, offset);
554         } else {
555                 int i;
556
557                 /* Recent offset.  */
558
559                 /* LZ match bit: 1 = recent offset, not an explicit offset.  */
560                 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
561
562                 /* Encode the recent offset index.  A 1 bit is encoded for each
563                  * index passed up.  This sequence of 1 bits is terminated by a
564                  * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
565                  * bits have been encoded.  */
566                 for (i = 0; i < recent_offset_idx; i++)
567                         lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
568
569                 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
570                         lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
571
572                 /* Initial update of the LZ match offset LRU queue.  */
573                 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
574                         ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
575         }
576
577         /* Encode the match length.  */
578         lzms_encode_length(&ctx->length_encoder, length);
579
580         /* Save the match offset for later insertion at the front of the LZ
581          * match offset LRU queue.  */
582         ctx->lru.lz.upcoming_offset = offset;
583
584         lzms_end_encode_item(ctx, length);
585 }
586
587 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
588  * Unlike lzms_get_lz_match_cost(), which does a true cost evaluation, this
589  * simply prioritize matches based on their offset.  */
590 static input_idx_t
591 lzms_lz_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_lru)
592 {
593         const struct lzms_lz_lru_queues *lru = _lru;
594
595         for (input_idx_t i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++)
596                 if (offset == lru->recent_offsets[i])
597                         return i;
598
599         return offset;
600 }
601
602 #define LZMS_COST_SHIFT 5
603
604 /*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
605
606 static u32
607 lzms_rc_costs[LZMS_PROBABILITY_MAX + 1];
608
609 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
610 #  include <math.h>
611 #endif
612
613 static void
614 lzms_do_init_rc_costs(void)
615 {
616         /* Fill in a table that maps range coding probabilities needed to code a
617          * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
618          * handle fractional costs) needed to code that bit X.
619          *
620          * Consider the range of the range decoder.  To eliminate exactly half
621          * the range (logical probability of 0.5), we need exactly 1 bit.  For
622          * lower probabilities we need more bits and for higher probabilities we
623          * need fewer bits.  In general, a logical probability of N will
624          * eliminate the proportion 1 - N of the range; this information takes
625          * log2(1 / N) bits to encode.
626          *
627          * The below loop is simply calculating this number of bits for each
628          * possible probability allowed by the LZMS compression format, but
629          * without using real numbers.  To handle fractional probabilities, each
630          * cost is multiplied by (1 << LZMS_COST_SHIFT).  These techniques are
631          * based on those used by LZMA.
632          *
633          * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
634          * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
635          * 63 / 64.
636          */
637         for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
638                 u32 prob = i;
639
640                 if (prob == 0)
641                         prob = 1;
642                 else if (prob == LZMS_PROBABILITY_MAX)
643                         prob = LZMS_PROBABILITY_MAX - 1;
644
645         #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
646                 lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
647                                         (1 << LZMS_COST_SHIFT);
648         #else
649                 u32 w = prob;
650                 u32 bit_count = 0;
651                 for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
652                         w *= w;
653                         bit_count <<= 1;
654                         while (w >= (1U << 16)) {
655                                 w >>= 1;
656                                 ++bit_count;
657                         }
658                 }
659                 lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
660                                    (15 + bit_count);
661         #endif
662         }
663 }
664
665 static void
666 lzms_init_rc_costs(void)
667 {
668         static bool done = false;
669         static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
670
671         if (unlikely(!done)) {
672                 pthread_mutex_lock(&mutex);
673                 if (!done) {
674                         lzms_do_init_rc_costs();
675                         done = true;
676                 }
677                 pthread_mutex_unlock(&mutex);
678         }
679 }
680
681 /*
682  * Return the cost to range-encode the specified bit when in the specified
683  * state.
684  *
685  * @enc         The range encoder to use.
686  * @cur_state   Current state, which indicates the probability entry to choose.
687  *              Updated by this function.
688  * @bit         The bit to encode (0 or 1).
689  */
690 static u32
691 lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 *cur_state, int bit)
692 {
693         u32 prob_zero;
694         u32 prob_correct;
695
696         prob_zero = enc->prob_entries[*cur_state & enc->mask].num_recent_zero_bits;
697
698         *cur_state = (*cur_state << 1) | bit;
699
700         if (bit == 0)
701                 prob_correct = prob_zero;
702         else
703                 prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
704
705         return lzms_rc_costs[prob_correct];
706 }
707
708 static u32
709 lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, u32 sym)
710 {
711         return enc->lens[sym] << LZMS_COST_SHIFT;
712 }
713
714 static u32
715 lzms_offset_cost(const struct lzms_huffman_encoder *enc, u32 offset)
716 {
717         u32 slot;
718         u32 num_extra_bits;
719         u32 cost = 0;
720
721         slot = lzms_get_position_slot(offset);
722
723         cost += lzms_huffman_symbol_cost(enc, slot);
724
725         num_extra_bits = lzms_extra_position_bits[slot];
726
727         cost += num_extra_bits << LZMS_COST_SHIFT;
728
729         return cost;
730 }
731
732 static u32
733 lzms_length_cost(const struct lzms_huffman_encoder *enc, u32 length)
734 {
735         u32 slot;
736         u32 num_extra_bits;
737         u32 cost = 0;
738
739         slot = lzms_get_length_slot(length);
740
741         cost += lzms_huffman_symbol_cost(enc, slot);
742
743         num_extra_bits = lzms_extra_length_bits[slot];
744
745         cost += num_extra_bits << LZMS_COST_SHIFT;
746
747         return cost;
748 }
749
750 static u32
751 lzms_get_matches(struct lzms_compressor *ctx,
752                  const struct lzms_adaptive_state *state,
753                  struct raw_match **matches_ret)
754 {
755         *matches_ret = ctx->matches;
756         return lz_sarray_get_matches(&ctx->lz_sarray,
757                                      ctx->matches,
758                                      lzms_lz_match_cost_fast,
759                                      &state->lru);
760 }
761
762 static void
763 lzms_skip_bytes(struct lzms_compressor *ctx, input_idx_t n)
764 {
765         while (n--)
766                 lz_sarray_skip_position(&ctx->lz_sarray);
767 }
768
769 static u32
770 lzms_get_prev_literal_cost(struct lzms_compressor *ctx,
771                            struct lzms_adaptive_state *state)
772 {
773         u8 literal = ctx->window[lz_sarray_get_pos(&ctx->lz_sarray) - 1];
774         u32 cost = 0;
775
776         state->lru.upcoming_offset = 0;
777         lzms_update_lz_lru_queues(&state->lru);
778
779         cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
780                                  &state->main_state, 0);
781
782         cost += lzms_huffman_symbol_cost(&ctx->literal_encoder, literal);
783
784         return cost;
785 }
786
787 static u32
788 lzms_get_lz_match_cost(struct lzms_compressor *ctx,
789                        struct lzms_adaptive_state *state,
790                        input_idx_t length, input_idx_t offset)
791 {
792         u32 cost = 0;
793         int recent_offset_idx;
794
795         cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
796                                  &state->main_state, 1);
797         cost += lzms_rc_bit_cost(&ctx->match_range_encoder,
798                                  &state->match_state, 0);
799
800         for (recent_offset_idx = 0;
801              recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
802              recent_offset_idx++)
803                 if (offset == state->lru.recent_offsets[recent_offset_idx])
804                         break;
805
806         if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
807                 /* Explicit offset.  */
808                 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
809                                          &state->lz_match_state, 0);
810
811                 cost += lzms_offset_cost(&ctx->lz_offset_encoder, offset);
812         } else {
813                 int i;
814
815                 /* Recent offset.  */
816                 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
817                                          &state->lz_match_state, 1);
818
819                 for (i = 0; i < recent_offset_idx; i++)
820                         cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
821                                                  &state->lz_repeat_match_state[i], 0);
822
823                 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
824                         cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
825                                                  &state->lz_repeat_match_state[i], 1);
826
827
828                 /* Initial update of the LZ match offset LRU queue.  */
829                 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
830                         state->lru.recent_offsets[i] = state->lru.recent_offsets[i + 1];
831         }
832
833         cost += lzms_length_cost(&ctx->length_encoder, length);
834
835         state->lru.upcoming_offset = offset;
836         lzms_update_lz_lru_queues(&state->lru);
837
838         return cost;
839 }
840
841 static struct raw_match
842 lzms_get_near_optimal_match(struct lzms_compressor *ctx)
843 {
844         struct lzms_adaptive_state initial_state;
845
846         initial_state.lru = ctx->lru.lz;
847         initial_state.main_state = ctx->main_range_encoder.state;
848         initial_state.match_state = ctx->match_range_encoder.state;
849         initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
850         for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
851                 initial_state.lz_repeat_match_state[i] =
852                         ctx->lz_repeat_match_range_encoders[i].state;
853         return lz_get_near_optimal_match(&ctx->mc,
854                                          lzms_get_matches,
855                                          lzms_skip_bytes,
856                                          lzms_get_prev_literal_cost,
857                                          lzms_get_lz_match_cost,
858                                          ctx,
859                                          &initial_state);
860 }
861
862 /*
863  * The main loop for the LZMS compressor.
864  *
865  * Notes:
866  *
867  * - This uses near-optimal LZ parsing backed by a suffix-array match-finder.
868  *   More details can be found in the corresponding files (lz_optimal.h,
869  *   lz_sarray.{h,c}).
870  *
871  * - This does not output any delta matches.  It would take a specialized
872  *   algorithm to find them, then more code in lz_optimal.h and here to handle
873  *   evaluating and outputting them.
874  *
875  * - The costs of literals and matches are estimated using the range encoder
876  *   states and the semi-adaptive Huffman codes.  Except for range encoding
877  *   states, costs are assumed to be constant throughout a single run of the
878  *   parsing algorithm, which can parse up to @optim_array_length (from the
879  *   `struct wimlib_lzms_compressor_params') bytes of data.  This introduces a
880  *   source of inaccuracy because the probabilities and Huffman codes can change
881  *   over this part of the data.
882  */
883 static void
884 lzms_encode(struct lzms_compressor *ctx)
885 {
886         struct raw_match match;
887
888         /* Load window into suffix array match-finder.  */
889         lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
890
891         /* Reset the match-chooser.  */
892         lz_match_chooser_begin(&ctx->mc);
893
894         while (ctx->cur_window_pos != ctx->window_size) {
895                 match = lzms_get_near_optimal_match(ctx);
896                 if (match.len <= 1)
897                         lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
898                 else
899                         lzms_encode_lz_match(ctx, match.len, match.offset);
900         }
901 }
902
903 static void
904 lzms_init_range_encoder(struct lzms_range_encoder *enc,
905                         struct lzms_range_encoder_raw *rc, u32 num_states)
906 {
907         enc->rc = rc;
908         enc->state = 0;
909         enc->mask = num_states - 1;
910         for (u32 i = 0; i < num_states; i++) {
911                 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
912                 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
913         }
914 }
915
916 static void
917 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
918                           struct lzms_output_bitstream *os,
919                           unsigned num_syms,
920                           unsigned rebuild_freq)
921 {
922         enc->os = os;
923         enc->num_syms_written = 0;
924         enc->rebuild_freq = rebuild_freq;
925         enc->num_syms = num_syms;
926         for (unsigned i = 0; i < num_syms; i++)
927                 enc->sym_freqs[i] = 1;
928
929         make_canonical_huffman_code(enc->num_syms,
930                                     LZMS_MAX_CODEWORD_LEN,
931                                     enc->sym_freqs,
932                                     enc->lens,
933                                     enc->codewords);
934 }
935
936 /* Initialize the LZMS compressor.  */
937 static void
938 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
939                      le16 *cdata, u32 clen16)
940 {
941         unsigned num_position_slots;
942
943         /* Copy the uncompressed data into the @ctx->window buffer.  */
944         memcpy(ctx->window, udata, ulen);
945         ctx->cur_window_pos = 0;
946         ctx->window_size = ulen;
947
948         /* Initialize the raw range encoder (writing forwards).  */
949         lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
950
951         /* Initialize the output bitstream for Huffman symbols and verbatim bits
952          * (writing backwards).  */
953         lzms_output_bitstream_init(&ctx->os, cdata, clen16);
954
955         /* Calculate the number of position slots needed for this compressed
956          * block.  */
957         num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
958
959         LZMS_DEBUG("Using %u position slots", num_position_slots);
960
961         /* Initialize Huffman encoders for each alphabet used in the compressed
962          * representation.  */
963         lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
964                                   LZMS_NUM_LITERAL_SYMS,
965                                   LZMS_LITERAL_CODE_REBUILD_FREQ);
966
967         lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
968                                   num_position_slots,
969                                   LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
970
971         lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
972                                   LZMS_NUM_LEN_SYMS,
973                                   LZMS_LENGTH_CODE_REBUILD_FREQ);
974
975         lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
976                                   num_position_slots,
977                                   LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
978
979         lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
980                                   LZMS_NUM_DELTA_POWER_SYMS,
981                                   LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
982
983         /* Initialize range encoders, all of which wrap around the same
984          * lzms_range_encoder_raw.  */
985         lzms_init_range_encoder(&ctx->main_range_encoder,
986                                 &ctx->rc, LZMS_NUM_MAIN_STATES);
987
988         lzms_init_range_encoder(&ctx->match_range_encoder,
989                                 &ctx->rc, LZMS_NUM_MATCH_STATES);
990
991         lzms_init_range_encoder(&ctx->lz_match_range_encoder,
992                                 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
993
994         for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
995                 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
996                                         &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
997
998         lzms_init_range_encoder(&ctx->delta_match_range_encoder,
999                                 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
1000
1001         for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
1002                 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
1003                                         &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1004
1005         /* Initialize LRU match information.  */
1006         lzms_init_lru_queues(&ctx->lru);
1007 }
1008
1009 /* Flush the output streams, prepare the final compressed data, and return its
1010  * size in bytes.
1011  *
1012  * A return value of 0 indicates that the data could not be compressed to fit in
1013  * the available space.  */
1014 static size_t
1015 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
1016 {
1017         size_t num_forwards_bytes;
1018         size_t num_backwards_bytes;
1019         size_t compressed_size;
1020
1021         /* Flush both the forwards and backwards streams, and make sure they
1022          * didn't cross each other and start overwriting each other's data.  */
1023         if (!lzms_output_bitstream_flush(&ctx->os)) {
1024                 LZMS_DEBUG("Backwards bitstream overrun.");
1025                 return 0;
1026         }
1027
1028         if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
1029                 LZMS_DEBUG("Forwards bitstream overrun.");
1030                 return 0;
1031         }
1032
1033         if (ctx->rc.out > ctx->os.out) {
1034                 LZMS_DEBUG("Two bitstreams crossed.");
1035                 return 0;
1036         }
1037
1038         /* Now the compressed buffer contains the data output by the forwards
1039          * bitstream, then empty space, then data output by the backwards
1040          * bitstream.  Move the data output by the backwards bitstream to be
1041          * adjacent to the data output by the forward bitstream, and calculate
1042          * the compressed size that this results in.  */
1043         num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
1044         num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
1045
1046         memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
1047
1048         compressed_size = num_forwards_bytes + num_backwards_bytes;
1049         LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
1050                    "compressed_size=%zu",
1051                    num_forwards_bytes, num_backwards_bytes, compressed_size);
1052         LZMS_ASSERT(compressed_size % 2 == 0);
1053         return compressed_size;
1054 }
1055
1056 static size_t
1057 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
1058               void *compressed_data, size_t compressed_size_avail, void *_ctx)
1059 {
1060         struct lzms_compressor *ctx = _ctx;
1061         size_t compressed_size;
1062
1063         LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
1064                    uncompressed_size, compressed_size_avail);
1065
1066         /* Make sure the uncompressed size is compatible with this compressor.
1067          */
1068         if (uncompressed_size > ctx->max_block_size) {
1069                 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
1070                            "only supports %u bytes",
1071                            uncompressed_size, ctx->max_block_size);
1072                 return 0;
1073         }
1074
1075         /* Don't bother compressing extremely small inputs.  */
1076         if (uncompressed_size < 4) {
1077                 LZMS_DEBUG("Input too small to bother compressing.");
1078                 return 0;
1079         }
1080
1081         /* Cap the available compressed size to a 32-bit integer and round it
1082          * down to the nearest multiple of 2.  */
1083         if (compressed_size_avail > UINT32_MAX)
1084                 compressed_size_avail = UINT32_MAX;
1085         if (compressed_size_avail & 1)
1086                 compressed_size_avail--;
1087
1088         /* Initialize the compressor structures.  */
1089         lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
1090                              compressed_data, compressed_size_avail / 2);
1091
1092         /* Preprocess the uncompressed data.  */
1093         lzms_x86_filter(ctx->window, ctx->window_size,
1094                         ctx->last_target_usages, false);
1095
1096         /* Compute and encode a literal/match sequence that decompresses to the
1097          * preprocessed data.  */
1098         lzms_encode(ctx);
1099
1100         /* Get and return the compressed data size.  */
1101         compressed_size = lzms_finalize(ctx, compressed_data,
1102                                         compressed_size_avail);
1103
1104         if (compressed_size == 0) {
1105                 LZMS_DEBUG("Data did not compress to requested size or less.");
1106                 return 0;
1107         }
1108
1109         LZMS_DEBUG("Compressed %zu => %zu bytes",
1110                    uncompressed_size, compressed_size);
1111
1112 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
1113         /* Verify that we really get the same thing back when decompressing.  */
1114         {
1115                 struct wimlib_decompressor *decompressor;
1116
1117                 LZMS_DEBUG("Verifying LZMS compression.");
1118
1119                 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
1120                                                     ctx->max_block_size,
1121                                                     NULL,
1122                                                     &decompressor))
1123                 {
1124                         int ret;
1125                         ret = wimlib_decompress(compressed_data,
1126                                                 compressed_size,
1127                                                 ctx->window,
1128                                                 uncompressed_size,
1129                                                 decompressor);
1130                         wimlib_free_decompressor(decompressor);
1131
1132                         if (ret) {
1133                                 ERROR("Failed to decompress data we "
1134                                       "compressed using LZMS algorithm");
1135                                 wimlib_assert(0);
1136                                 return 0;
1137                         }
1138                         if (memcmp(uncompressed_data, ctx->window,
1139                                    uncompressed_size))
1140                         {
1141                                 ERROR("Data we compressed using LZMS algorithm "
1142                                       "didn't decompress to original");
1143                                 wimlib_assert(0);
1144                                 return 0;
1145                         }
1146                 } else {
1147                         WARNING("Failed to create decompressor for "
1148                                 "data verification!");
1149                 }
1150         }
1151 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION  */
1152
1153         return compressed_size;
1154 }
1155
1156 static void
1157 lzms_free_compressor(void *_ctx)
1158 {
1159         struct lzms_compressor *ctx = _ctx;
1160
1161         if (ctx) {
1162                 FREE(ctx->window);
1163                 FREE(ctx->matches);
1164                 lz_sarray_destroy(&ctx->lz_sarray);
1165                 lz_match_chooser_destroy(&ctx->mc);
1166                 FREE(ctx);
1167         }
1168 }
1169
1170 static const struct wimlib_lzms_compressor_params lzms_default = {
1171         .hdr = sizeof(struct wimlib_lzms_compressor_params),
1172         .min_match_length = 2,
1173         .max_match_length = UINT32_MAX,
1174         .nice_match_length = 32,
1175         .max_search_depth = 50,
1176         .max_matches_per_pos = 3,
1177         .optim_array_length = 1024,
1178 };
1179
1180 static const struct wimlib_lzms_compressor_params *
1181 lzms_get_params(const struct wimlib_compressor_params_header *_params)
1182 {
1183         const struct wimlib_lzms_compressor_params *params =
1184                 (const struct wimlib_lzms_compressor_params*)_params;
1185
1186         if (params == NULL)
1187                 params = &lzms_default;
1188
1189         return params;
1190 }
1191
1192 static int
1193 lzms_create_compressor(size_t max_block_size,
1194                        const struct wimlib_compressor_params_header *_params,
1195                        void **ctx_ret)
1196 {
1197         struct lzms_compressor *ctx;
1198         const struct wimlib_lzms_compressor_params *params = lzms_get_params(_params);
1199
1200         if (max_block_size == 0 || max_block_size >= INT32_MAX) {
1201                 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
1202                 return WIMLIB_ERR_INVALID_PARAM;
1203         }
1204
1205         ctx = CALLOC(1, sizeof(struct lzms_compressor));
1206         if (ctx == NULL)
1207                 goto oom;
1208
1209         ctx->window = MALLOC(max_block_size);
1210         if (ctx->window == NULL)
1211                 goto oom;
1212
1213         ctx->matches = MALLOC(min(params->max_match_length -
1214                                         params->min_match_length + 1,
1215                                   params->max_matches_per_pos) *
1216                                 sizeof(ctx->matches[0]));
1217         if (ctx->matches == NULL)
1218                 goto oom;
1219
1220         if (!lz_sarray_init(&ctx->lz_sarray, max_block_size,
1221                             params->min_match_length,
1222                             params->max_match_length,
1223                             params->max_search_depth,
1224                             params->max_matches_per_pos))
1225                 goto oom;
1226
1227         if (!lz_match_chooser_init(&ctx->mc,
1228                                    params->optim_array_length,
1229                                    params->nice_match_length,
1230                                    params->max_match_length))
1231                 goto oom;
1232
1233         /* Initialize position and length slot data if not done already.  */
1234         lzms_init_slots();
1235
1236         /* Initialize range encoding cost table if not done already.  */
1237         lzms_init_rc_costs();
1238
1239         ctx->max_block_size = max_block_size;
1240
1241         *ctx_ret = ctx;
1242         return 0;
1243
1244 oom:
1245         lzms_free_compressor(ctx);
1246         return WIMLIB_ERR_NOMEM;
1247 }
1248
1249 static u64
1250 lzms_get_needed_memory(size_t max_block_size,
1251                        const struct wimlib_compressor_params_header *_params)
1252 {
1253         const struct wimlib_lzms_compressor_params *params = lzms_get_params(_params);
1254
1255         u64 size = 0;
1256
1257         size += max_block_size;
1258         size += sizeof(struct lzms_compressor);
1259         size += lz_sarray_get_needed_memory(max_block_size);
1260         size += lz_match_chooser_get_needed_memory(params->optim_array_length,
1261                                                    params->nice_match_length,
1262                                                    params->max_match_length);
1263         size += min(params->max_match_length -
1264                     params->min_match_length + 1,
1265                     params->max_matches_per_pos) *
1266                 sizeof(((struct lzms_compressor*)0)->matches[0]);
1267         return size;
1268 }
1269
1270 static bool
1271 lzms_params_valid(const struct wimlib_compressor_params_header *_params)
1272 {
1273         const struct wimlib_lzms_compressor_params *params =
1274                 (const struct wimlib_lzms_compressor_params*)_params;
1275
1276         if (params->hdr.size != sizeof(*params) ||
1277             params->max_match_length < params->min_match_length ||
1278             params->min_match_length < 2 ||
1279             params->optim_array_length == 0 ||
1280             min(params->max_match_length, params->nice_match_length) > 65536)
1281                 return false;
1282
1283         return true;
1284 }
1285
1286 const struct compressor_ops lzms_compressor_ops = {
1287         .params_valid       = lzms_params_valid,
1288         .get_needed_memory  = lzms_get_needed_memory,
1289         .create_compressor  = lzms_create_compressor,
1290         .compress           = lzms_compress,
1291         .free_compressor    = lzms_free_compressor,
1292 };