6 * Copyright (C) 2013 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
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)
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
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/.
24 /* This a compressor for the LZMS compression format. More details about this
25 * format can be found in lzms-decompress.c.
27 * This is currently an unsophisticated implementation that is fast but does not
28 * attain the best compression ratios allowed by the format.
36 #include "wimlib/assert.h"
37 #include "wimlib/compiler.h"
38 #include "wimlib/compressor_ops.h"
39 #include "wimlib/compress_common.h"
40 #include "wimlib/endianness.h"
41 #include "wimlib/error.h"
42 #include "wimlib/lz_hash.h"
43 #include "wimlib/lzms.h"
44 #include "wimlib/util.h"
49 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
50 * a series of 16-bit little endian coding units. */
51 struct lzms_output_bitstream {
52 /* Buffer variable containing zero or more bits that have been logically
53 * written to the bitstream but not yet written to memory. This must be
54 * at least as large as the coding unit size. */
57 /* Number of bits in @bitbuf that are valid. */
58 unsigned num_free_bits;
60 /* Pointer to one past the next position in the compressed data buffer
61 * at which to output a 16-bit coding unit. */
64 /* Maximum number of 16-bit coding units that can still be output to
65 * the compressed data buffer. */
66 size_t num_le16_remaining;
68 /* Set to %true if not all coding units could be output due to
69 * insufficient space. */
73 /* Stucture used for range encoding (raw version). */
74 struct lzms_range_encoder_raw {
76 /* A 33-bit variable that holds the low boundary of the current range.
77 * The 33rd bit is needed to catch carries. */
80 /* Size of the current range. */
83 /* Next 16-bit coding unit to output. */
86 /* Number of 16-bit coding units whose output has been delayed due to
87 * possible carrying. The first such coding unit is @cache; all
88 * subsequent such coding units are 0xffff. */
91 /* Pointer to the next position in the compressed data buffer at which
92 * to output a 16-bit coding unit. */
95 /* Maximum number of 16-bit coding units that can still be output to
96 * the compressed data buffer. */
97 size_t num_le16_remaining;
99 /* %true when the very first coding unit has not yet been output. */
102 /* Set to %true if not all coding units could be output due to
103 * insufficient space. */
107 /* Structure used for range encoding. This wraps around `struct
108 * lzms_range_encoder_raw' to use and maintain probability entries. */
109 struct lzms_range_encoder {
110 /* Pointer to the raw range encoder, which has no persistent knowledge
111 * of probabilities. Multiple lzms_range_encoder's share the same
112 * lzms_range_encoder_raw. */
113 struct lzms_range_encoder_raw *rc;
115 /* Bits recently encoded by this range encoder. This are used as in
116 * index into @prob_entries. */
119 /* Bitmask for @state to prevent its value from exceeding the number of
120 * probability entries. */
123 /* Probability entries being used for this range encoder. */
124 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
127 /* Structure used for Huffman encoding, optionally encoding larger "values" as a
128 * Huffman symbol specifying a slot and a slot-dependent number of extra bits.
130 struct lzms_huffman_encoder {
132 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
133 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
135 struct lzms_output_bitstream *os;
137 /* Pointer to the slot base table to use. */
138 const u32 *slot_base_tab;
140 /* Number of symbols that have been written using this code far. Reset
141 * to 0 whenever the code is rebuilt. */
142 u32 num_syms_written;
144 /* When @num_syms_written reaches this number, the Huffman code must be
148 /* Number of symbols in the represented Huffman code. */
151 /* Running totals of symbol frequencies. These are diluted slightly
152 * whenever the code is rebuilt. */
153 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
155 /* The length, in bits, of each symbol in the Huffman code. */
156 u8 lens[LZMS_MAX_NUM_SYMS];
158 /* The codeword of each symbol in the Huffman code. */
159 u16 codewords[LZMS_MAX_NUM_SYMS];
162 /* State of the LZMS compressor. */
163 struct lzms_compressor {
164 /* Pointer to a buffer holding the preprocessed data to compress. */
167 /* Current position in @buffer. */
170 /* Size of the data in @buffer. */
173 /* Temporary array used by lz_analyze_block(); must be at least as long
177 /* Maximum block size this compressor instantiation allows. This is the
178 * allocated size of @window. */
181 /* Raw range encoder which outputs to the beginning of the compressed
182 * data buffer, proceeding forwards. */
183 struct lzms_range_encoder_raw rc;
185 /* Bitstream which outputs to the end of the compressed data buffer,
186 * proceeding backwards. */
187 struct lzms_output_bitstream os;
189 /* Range encoders. */
190 struct lzms_range_encoder main_range_encoder;
191 struct lzms_range_encoder match_range_encoder;
192 struct lzms_range_encoder lz_match_range_encoder;
193 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
194 struct lzms_range_encoder delta_match_range_encoder;
195 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
197 /* Huffman encoders. */
198 struct lzms_huffman_encoder literal_encoder;
199 struct lzms_huffman_encoder lz_offset_encoder;
200 struct lzms_huffman_encoder length_encoder;
201 struct lzms_huffman_encoder delta_power_encoder;
202 struct lzms_huffman_encoder delta_offset_encoder;
204 /* LRU (least-recently-used) queue of LZ match offsets. */
205 u64 recent_lz_offsets[LZMS_NUM_RECENT_OFFSETS + 1];
207 /* LRU (least-recently-used) queue of delta match powers. */
208 u32 recent_delta_powers[LZMS_NUM_RECENT_OFFSETS + 1];
210 /* LRU (least-recently-used) queue of delta match offsets. */
211 u32 recent_delta_offsets[LZMS_NUM_RECENT_OFFSETS + 1];
213 /* These variables are used to delay updates to the LRU queues by one
216 u32 prev_delta_power;
217 u32 prev_delta_offset;
218 u32 upcoming_lz_offset;
219 u32 upcoming_delta_power;
220 u32 upcoming_delta_offset;
222 /* Used for preprocessing. */
223 s32 last_target_usages[65536];
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. */
234 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
235 le16 *out, size_t out_limit)
238 os->num_free_bits = 16;
239 os->out = out + out_limit;
240 os->num_le16_remaining = out_limit;
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. */
247 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
248 u32 bits, unsigned num_bits)
250 bits &= (1U << num_bits) - 1;
252 while (num_bits > os->num_free_bits) {
254 if (unlikely(os->num_le16_remaining == 0)) {
259 unsigned num_fill_bits = os->num_free_bits;
261 os->bitbuf <<= num_fill_bits;
262 os->bitbuf |= bits >> (num_bits - num_fill_bits);
264 *--os->out = cpu_to_le16(os->bitbuf);
265 --os->num_le16_remaining;
267 os->num_free_bits = 16;
268 num_bits -= num_fill_bits;
269 bits &= (1U << num_bits) - 1;
271 os->bitbuf <<= num_bits;
273 os->num_free_bits -= num_bits;
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. */
280 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
282 if (os->num_free_bits != 16)
283 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
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. */
290 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
291 le16 *out, size_t out_limit)
294 rc->range = 0xffffffff;
298 rc->num_le16_remaining = out_limit;
304 * Attempt to flush bits from the range encoder.
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.
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
318 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
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)
325 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
326 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
329 if (rc->num_le16_remaining == 0) {
333 *rc->out++ = cpu_to_le16(rc->cache +
334 (u16)(rc->low >> 32));
335 --rc->num_le16_remaining;
341 } while (--rc->cache_size != 0);
343 rc->cache = (rc->low >> 16) & 0xffff;
346 rc->low = (rc->low & 0xffff) << 16;
350 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
352 if (rc->range <= 0xffff) {
354 lzms_range_encoder_raw_shift_low(rc);
359 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
361 for (unsigned i = 0; i < 4; i++)
362 lzms_range_encoder_raw_shift_low(rc);
366 /* Encode the next bit using the range encoder (raw version).
368 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
370 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
373 lzms_range_encoder_raw_normalize(rc);
375 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
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. */
388 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
390 struct lzms_probability_entry *prob_entry;
393 /* Load the probability entry corresponding to the current state. */
394 prob_entry = &enc->prob_entries[enc->state];
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;
403 else if (prob == LZMS_PROBABILITY_MAX)
404 prob = LZMS_PROBABILITY_MAX - 1;
406 /* Encode the next bit. */
407 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
409 /* Update the state based on the newly encoded bit. */
410 enc->state = ((enc->state << 1) | bit) & enc->mask;
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);
415 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
416 /* Replacing 1 bit with 0 bit; increment the zero count.
418 prob_entry->num_recent_zero_bits++;
421 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
422 /* Replacing 0 bit with 1 bit; decrement the zero count.
424 prob_entry->num_recent_zero_bits--;
427 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
430 /* Encode a symbol using the specified Huffman encoder. */
432 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
434 LZMS_ASSERT(sym < enc->num_syms);
435 if (enc->num_syms_written == enc->rebuild_freq) {
436 /* Adaptive code needs to be rebuilt. */
437 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
438 make_canonical_huffman_code(enc->num_syms,
439 LZMS_MAX_CODEWORD_LEN,
444 /* Dilute the frequencies. */
445 for (unsigned i = 0; i < enc->num_syms; i++) {
446 enc->sym_freqs[i] >>= 1;
447 enc->sym_freqs[i] += 1;
449 enc->num_syms_written = 0;
451 lzms_output_bitstream_put_bits(enc->os,
454 ++enc->num_syms_written;
455 ++enc->sym_freqs[sym];
458 /* Encode a number as a Huffman symbol specifying a slot, plus a number of
459 * slot-dependent extra bits. */
461 lzms_encode_value(struct lzms_huffman_encoder *enc, u32 value)
464 unsigned num_extra_bits;
467 LZMS_ASSERT(enc->slot_base_tab != NULL);
469 slot = lzms_get_slot(value, enc->slot_base_tab, enc->num_syms);
471 /* Get the number of extra bits needed to represent the range of values
472 * that share the slot. */
473 num_extra_bits = bsr32(enc->slot_base_tab[slot + 1] -
474 enc->slot_base_tab[slot]);
476 /* Calculate the extra bits as the offset from the slot base. */
477 extra_bits = value - enc->slot_base_tab[slot];
479 /* Output the slot (Huffman-encoded), then the extra bits (verbatim).
481 lzms_huffman_encode_symbol(enc, slot);
482 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
486 lzms_begin_encode_item(struct lzms_compressor *ctx)
488 ctx->upcoming_delta_offset = 0;
489 ctx->upcoming_lz_offset = 0;
490 ctx->upcoming_delta_power = 0;
494 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
496 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
497 ctx->cur_window_pos += length;
499 /* Update LRU queues */
500 if (ctx->prev_lz_offset != 0) {
501 for (int i = LZMS_NUM_RECENT_OFFSETS - 1; i >= 0; i--)
502 ctx->recent_lz_offsets[i + 1] = ctx->recent_lz_offsets[i];
503 ctx->recent_lz_offsets[0] = ctx->prev_lz_offset;
506 if (ctx->prev_delta_offset != 0) {
507 for (int i = LZMS_NUM_RECENT_OFFSETS - 1; i >= 0; i--) {
508 ctx->recent_delta_powers[i + 1] = ctx->recent_delta_powers[i];
509 ctx->recent_delta_offsets[i + 1] = ctx->recent_delta_offsets[i];
511 ctx->recent_delta_powers[0] = ctx->prev_delta_power;
512 ctx->recent_delta_offsets[0] = ctx->prev_delta_offset;
515 ctx->prev_lz_offset = ctx->upcoming_lz_offset;
516 ctx->prev_delta_offset = ctx->upcoming_delta_offset;
517 ctx->prev_delta_power = ctx->upcoming_delta_power;
520 /* Encode a literal byte. */
522 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
524 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
525 ctx->cur_window_pos, literal, literal);
527 lzms_begin_encode_item(ctx);
529 /* Main bit: 0 = a literal, not a match. */
530 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
532 /* Encode the literal using the current literal Huffman code. */
533 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
535 lzms_end_encode_item(ctx, 1);
538 /* Encode a (length, offset) pair (LZ match). */
540 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
542 int recent_offset_idx;
544 lzms_begin_encode_item(ctx);
546 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
547 ctx->cur_window_pos, length, offset);
549 /* Main bit: 1 = a match, not a literal. */
550 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
552 /* Match bit: 0 = a LZ match, not a delta match. */
553 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
555 /* Determine if the offset can be represented as a recent offset. */
556 for (recent_offset_idx = 0;
557 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
559 if (offset == ctx->recent_lz_offsets[recent_offset_idx])
562 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
563 /* Explicit offset. */
565 /* LZ match bit: 0 = explicit offset, not a repeat offset. */
566 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
568 /* Encode the match offset. */
569 lzms_encode_value(&ctx->lz_offset_encoder, offset);
575 /* LZ match bit: 1 = repeat offset, not an explicit offset. */
576 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
578 /* Encode the recent offset index. A 1 bit is encoded for each
579 * index passed up. This sequence of 1 bits is terminated by a
580 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
581 * bits have been encoded. */
582 for (i = 0; i < recent_offset_idx; i++)
583 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
585 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
586 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
588 /* Initial update of the LZ match offset LRU queue. */
589 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
590 ctx->recent_lz_offsets[i] = ctx->recent_lz_offsets[i + 1];
593 /* Encode the match length. */
594 lzms_encode_value(&ctx->length_encoder, length);
596 /* Save the match offset for later insertion at the front of the LZ
597 * match offset LRU queue. */
598 ctx->upcoming_lz_offset = offset;
600 lzms_end_encode_item(ctx, length);
604 lzms_record_literal(u8 literal, void *_ctx)
606 struct lzms_compressor *ctx = _ctx;
608 lzms_encode_literal(ctx, literal);
612 lzms_record_match(unsigned length, unsigned offset, void *_ctx)
614 struct lzms_compressor *ctx = _ctx;
616 lzms_encode_lz_match(ctx, length, offset);
620 lzms_fast_encode(struct lzms_compressor *ctx)
622 static const struct lz_params lzms_lz_params = {
624 .max_match = UINT_MAX,
625 .max_offset = UINT_MAX,
629 .max_lazy_match = 258,
633 lz_analyze_block(ctx->window,
645 static struct lzms_match
646 lzms_get_best_match(struct lzms_compressor *ctx)
648 struct lzms_match match;
658 lzms_slow_encode(struct lzms_compressor *ctx)
660 struct lzms_match match;
663 while (ctx->cur_window_pos != ctx->window_size) {
664 match = lzms_get_best_match(ctx);
665 if (match.length == 0) {
667 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
670 lzms_encode_lz_match(ctx, match.length, match.offset);
677 lzms_init_range_encoder(struct lzms_range_encoder *enc,
678 struct lzms_range_encoder_raw *rc, u32 num_states)
682 enc->mask = num_states - 1;
683 for (u32 i = 0; i < num_states; i++) {
684 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
685 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
690 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
691 struct lzms_output_bitstream *os,
692 const u32 *slot_base_tab,
694 unsigned rebuild_freq)
697 enc->slot_base_tab = slot_base_tab;
698 enc->num_syms_written = rebuild_freq;
699 enc->rebuild_freq = rebuild_freq;
700 enc->num_syms = num_syms;
701 for (unsigned i = 0; i < num_syms; i++)
702 enc->sym_freqs[i] = 1;
705 /* Initialize the LZMS compressor. */
707 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
708 le16 *cdata, u32 clen16)
710 unsigned num_position_slots;
712 /* Copy the uncompressed data into the @ctx->window buffer. */
713 memcpy(ctx->window, udata, ulen);
714 memset(&ctx->window[ulen], 0, 8);
715 ctx->cur_window_pos = 0;
716 ctx->window_size = ulen;
718 /* Initialize the raw range encoder (writing forwards). */
719 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
721 /* Initialize the output bitstream for Huffman symbols and verbatim bits
722 * (writing backwards). */
723 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
725 /* Initialize position and length slot bases if not done already. */
726 lzms_init_slot_bases();
728 /* Calculate the number of position slots needed for this compressed
730 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
732 LZMS_DEBUG("Using %u position slots", num_position_slots);
734 /* Initialize Huffman encoders for each alphabet used in the compressed
736 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
737 NULL, LZMS_NUM_LITERAL_SYMS,
738 LZMS_LITERAL_CODE_REBUILD_FREQ);
740 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
741 lzms_position_slot_base, num_position_slots,
742 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
744 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
745 lzms_length_slot_base, LZMS_NUM_LEN_SYMS,
746 LZMS_LENGTH_CODE_REBUILD_FREQ);
748 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
749 lzms_position_slot_base, num_position_slots,
750 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
752 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
753 NULL, LZMS_NUM_DELTA_POWER_SYMS,
754 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
756 /* Initialize range encoders, all of which wrap around the same
757 * lzms_range_encoder_raw. */
758 lzms_init_range_encoder(&ctx->main_range_encoder,
759 &ctx->rc, LZMS_NUM_MAIN_STATES);
761 lzms_init_range_encoder(&ctx->match_range_encoder,
762 &ctx->rc, LZMS_NUM_MATCH_STATES);
764 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
765 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
767 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
768 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
769 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
771 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
772 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
774 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
775 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
776 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
778 /* Initialize the LRU queue for recent match offsets. */
779 for (size_t i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++)
780 ctx->recent_lz_offsets[i] = i + 1;
782 for (size_t i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++) {
783 ctx->recent_delta_powers[i] = 0;
784 ctx->recent_delta_offsets[i] = i + 1;
786 ctx->prev_lz_offset = 0;
787 ctx->prev_delta_offset = 0;
788 ctx->prev_delta_power = 0;
789 ctx->upcoming_lz_offset = 0;
790 ctx->upcoming_delta_offset = 0;
791 ctx->upcoming_delta_power = 0;
794 /* Flush the output streams, prepare the final compressed data, and return its
797 * A return value of 0 indicates that the data could not be compressed to fit in
798 * the available space. */
800 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
802 size_t num_forwards_bytes;
803 size_t num_backwards_bytes;
804 size_t compressed_size;
806 /* Flush both the forwards and backwards streams, and make sure they
807 * didn't cross each other and start overwriting each other's data. */
808 if (!lzms_output_bitstream_flush(&ctx->os)) {
809 LZMS_DEBUG("Backwards bitstream overrun.");
813 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
814 LZMS_DEBUG("Forwards bitstream overrun.");
818 if (ctx->rc.out > ctx->os.out) {
819 LZMS_DEBUG("Two bitstreams crossed.");
823 /* Now the compressed buffer contains the data output by the forwards
824 * bitstream, then empty space, then data output by the backwards
825 * bitstream. Move the data output by the forwards bitstream to be
826 * adjacent to the data output by the backwards bitstream, and calculate
827 * the compressed size that this results in. */
828 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
829 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
831 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
833 compressed_size = num_forwards_bytes + num_backwards_bytes;
834 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
835 "compressed_size=%zu",
836 num_forwards_bytes, num_backwards_bytes, compressed_size);
837 LZMS_ASSERT(!(compressed_size & 1));
838 return compressed_size;
842 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
843 void *compressed_data, size_t compressed_size_avail, void *_ctx)
845 struct lzms_compressor *ctx = _ctx;
846 size_t compressed_size;
848 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
849 uncompressed_size, compressed_size_avail);
851 /* Make sure the uncompressed size is compatible with this compressor.
853 if (uncompressed_size > ctx->max_block_size) {
854 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
855 "only supports %u bytes",
856 uncompressed_size, ctx->max_block_size);
860 /* Don't bother compressing extremely small inputs. */
861 if (uncompressed_size < 4)
864 /* Cap the available compressed size to a 32-bit integer, and round it
865 * down to the nearest multiple of 2. */
866 if (compressed_size_avail > UINT32_MAX)
867 compressed_size_avail = UINT32_MAX;
868 if (compressed_size_avail & 1)
869 compressed_size_avail--;
871 /* Initialize the compressor structures. */
872 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
873 compressed_data, compressed_size_avail / 2);
875 /* Preprocess the uncompressed data. */
876 lzms_x86_filter(ctx->window, ctx->window_size,
877 ctx->last_target_usages, false);
879 /* Determine and output a literal/match sequence that decompresses to
880 * the preprocessed data. */
881 lzms_fast_encode(ctx);
883 /* Get and return the compressed data size. */
884 compressed_size = lzms_finalize(ctx, compressed_data,
885 compressed_size_avail);
887 if (compressed_size == 0) {
888 LZMS_DEBUG("Data did not compress to requested size or less.");
892 LZMS_DEBUG("Compressed %zu => %zu bytes",
893 uncompressed_size, compressed_size);
895 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
896 /* Verify that we really get the same thing back when decompressing. */
898 struct wimlib_decompressor *decompressor;
900 LZMS_DEBUG("Verifying LZMS compression.");
902 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
908 ret = wimlib_decompress(compressed_data,
913 wimlib_free_decompressor(decompressor);
916 ERROR("Failed to decompress data we "
917 "compressed using LZMS algorithm");
921 if (memcmp(uncompressed_data, ctx->window,
924 ERROR("Data we compressed using LZMS algorithm "
925 "didn't decompress to original");
930 WARNING("Failed to create decompressor for "
931 "data verification!");
934 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION */
936 return compressed_size;
940 lzms_free_compressor(void *_ctx)
942 struct lzms_compressor *ctx = _ctx;
952 lzms_create_compressor(size_t max_block_size,
953 const struct wimlib_compressor_params_header *params,
956 struct lzms_compressor *ctx;
958 if (max_block_size == 0 || max_block_size >= INT32_MAX) {
959 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
960 return WIMLIB_ERR_INVALID_PARAM;
963 ctx = CALLOC(1, sizeof(struct lzms_compressor));
967 ctx->window = MALLOC(max_block_size + 8);
968 if (ctx->window == NULL)
971 ctx->prev_tab = MALLOC(max_block_size * sizeof(ctx->prev_tab[0]));
972 if (ctx->prev_tab == NULL)
975 ctx->max_block_size = max_block_size;
981 lzms_free_compressor(ctx);
982 return WIMLIB_ERR_NOMEM;
985 const struct compressor_ops lzms_compressor_ops = {
986 .create_compressor = lzms_create_compressor,
987 .compress = lzms_compress,
988 .free_compressor = lzms_free_compressor,