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