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/lz_sarray.h"
44 #include "wimlib/lzms.h"
45 #include "wimlib/util.h"
50 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
51 * a series of 16-bit little endian coding units. */
52 struct lzms_output_bitstream {
53 /* Buffer variable containing zero or more bits that have been logically
54 * written to the bitstream but not yet written to memory. This must be
55 * at least as large as the coding unit size. */
58 /* Number of bits in @bitbuf that are valid. */
59 unsigned num_free_bits;
61 /* Pointer to one past the next position in the compressed data buffer
62 * at which to output a 16-bit coding unit. */
65 /* Maximum number of 16-bit coding units that can still be output to
66 * the compressed data buffer. */
67 size_t num_le16_remaining;
69 /* Set to %true if not all coding units could be output due to
70 * insufficient space. */
74 /* Stucture used for range encoding (raw version). */
75 struct lzms_range_encoder_raw {
77 /* A 33-bit variable that holds the low boundary of the current range.
78 * The 33rd bit is needed to catch carries. */
81 /* Size of the current range. */
84 /* Next 16-bit coding unit to output. */
87 /* Number of 16-bit coding units whose output has been delayed due to
88 * possible carrying. The first such coding unit is @cache; all
89 * subsequent such coding units are 0xffff. */
92 /* Pointer to the next position in the compressed data buffer at which
93 * to output a 16-bit coding unit. */
96 /* Maximum number of 16-bit coding units that can still be output to
97 * the compressed data buffer. */
98 size_t num_le16_remaining;
100 /* %true when the very first coding unit has not yet been output. */
103 /* Set to %true if not all coding units could be output due to
104 * insufficient space. */
108 /* Structure used for range encoding. This wraps around `struct
109 * lzms_range_encoder_raw' to use and maintain probability entries. */
110 struct lzms_range_encoder {
111 /* Pointer to the raw range encoder, which has no persistent knowledge
112 * of probabilities. Multiple lzms_range_encoder's share the same
113 * lzms_range_encoder_raw. */
114 struct lzms_range_encoder_raw *rc;
116 /* Bits recently encoded by this range encoder. This are used as in
117 * index into @prob_entries. */
120 /* Bitmask for @state to prevent its value from exceeding the number of
121 * probability entries. */
124 /* Probability entries being used for this range encoder. */
125 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
128 /* Structure used for Huffman encoding, optionally encoding larger "values" as a
129 * Huffman symbol specifying a slot and a slot-dependent number of extra bits.
131 struct lzms_huffman_encoder {
133 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
134 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
136 struct lzms_output_bitstream *os;
138 /* Pointer to the slot base table to use. */
139 const u32 *slot_base_tab;
141 /* Number of symbols that have been written using this code far. Reset
142 * to 0 whenever the code is rebuilt. */
143 u32 num_syms_written;
145 /* When @num_syms_written reaches this number, the Huffman code must be
149 /* Number of symbols in the represented Huffman code. */
152 /* Running totals of symbol frequencies. These are diluted slightly
153 * whenever the code is rebuilt. */
154 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
156 /* The length, in bits, of each symbol in the Huffman code. */
157 u8 lens[LZMS_MAX_NUM_SYMS];
159 /* The codeword of each symbol in the Huffman code. */
160 u16 codewords[LZMS_MAX_NUM_SYMS];
163 /* State of the LZMS compressor. */
164 struct lzms_compressor {
165 /* Pointer to a buffer holding the preprocessed data to compress. */
168 /* Current position in @buffer. */
171 /* Size of the data in @buffer. */
174 /* Temporary array used by lz_analyze_block(); must be at least as long
178 /* Suffix array match-finder. */
179 struct lz_sarray lz_sarray;
181 /* Maximum block size this compressor instantiation allows. This is the
182 * allocated size of @window. */
185 /* Raw range encoder which outputs to the beginning of the compressed
186 * data buffer, proceeding forwards. */
187 struct lzms_range_encoder_raw rc;
189 /* Bitstream which outputs to the end of the compressed data buffer,
190 * proceeding backwards. */
191 struct lzms_output_bitstream os;
193 /* Range encoders. */
194 struct lzms_range_encoder main_range_encoder;
195 struct lzms_range_encoder match_range_encoder;
196 struct lzms_range_encoder lz_match_range_encoder;
197 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
198 struct lzms_range_encoder delta_match_range_encoder;
199 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
201 /* Huffman encoders. */
202 struct lzms_huffman_encoder literal_encoder;
203 struct lzms_huffman_encoder lz_offset_encoder;
204 struct lzms_huffman_encoder length_encoder;
205 struct lzms_huffman_encoder delta_power_encoder;
206 struct lzms_huffman_encoder delta_offset_encoder;
208 /* LRU (least-recently-used) queues for match information. */
209 struct lzms_lru_queues lru;
211 /* Used for preprocessing. */
212 s32 last_target_usages[65536];
215 /* Initialize the output bitstream @os to write forwards to the specified
216 * compressed data buffer @out that is @out_limit 16-bit integers long. */
218 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
219 le16 *out, size_t out_limit)
222 os->num_free_bits = 16;
223 os->out = out + out_limit;
224 os->num_le16_remaining = out_limit;
228 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
229 * from high-order to low-order), to the output bitstream @os. */
231 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
232 u32 bits, unsigned num_bits)
234 bits &= (1U << num_bits) - 1;
236 while (num_bits > os->num_free_bits) {
238 if (unlikely(os->num_le16_remaining == 0)) {
243 unsigned num_fill_bits = os->num_free_bits;
245 os->bitbuf <<= num_fill_bits;
246 os->bitbuf |= bits >> (num_bits - num_fill_bits);
248 *--os->out = cpu_to_le16(os->bitbuf);
249 --os->num_le16_remaining;
251 os->num_free_bits = 16;
252 num_bits -= num_fill_bits;
253 bits &= (1U << num_bits) - 1;
255 os->bitbuf <<= num_bits;
257 os->num_free_bits -= num_bits;
260 /* Flush the output bitstream, ensuring that all bits written to it have been
261 * written to memory. Returns %true if all bits were output successfully, or
262 * %false if an overrun occurred. */
264 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
266 if (os->num_free_bits != 16)
267 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
271 /* Initialize the range encoder @rc to write forwards to the specified
272 * compressed data buffer @out that is @out_limit 16-bit integers long. */
274 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
275 le16 *out, size_t out_limit)
278 rc->range = 0xffffffff;
282 rc->num_le16_remaining = out_limit;
288 * Attempt to flush bits from the range encoder.
290 * Note: this is based on the public domain code for LZMA written by Igor
291 * Pavlov. The only differences in this function are that in LZMS the bits must
292 * be output in 16-bit coding units instead of 8-bit coding units, and that in
293 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
294 * cannot output a dummy value to that position.
296 * The basic idea is that we're writing bits from @rc->low to the output.
297 * However, due to carrying, the writing of coding units with value 0xffff, as
298 * well as one prior coding unit, must be delayed until it is determined whether
302 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
304 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
305 rc->low, rc->cache, rc->cache_size);
306 if ((u32)(rc->low) < 0xffff0000 ||
307 (u32)(rc->low >> 32) != 0)
309 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
310 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
313 if (rc->num_le16_remaining == 0) {
317 *rc->out++ = cpu_to_le16(rc->cache +
318 (u16)(rc->low >> 32));
319 --rc->num_le16_remaining;
325 } while (--rc->cache_size != 0);
327 rc->cache = (rc->low >> 16) & 0xffff;
330 rc->low = (rc->low & 0xffff) << 16;
334 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
336 if (rc->range <= 0xffff) {
338 lzms_range_encoder_raw_shift_low(rc);
343 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
345 for (unsigned i = 0; i < 4; i++)
346 lzms_range_encoder_raw_shift_low(rc);
350 /* Encode the next bit using the range encoder (raw version).
352 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
354 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
357 lzms_range_encoder_raw_normalize(rc);
359 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
368 /* Encode a bit using the specified range encoder. This wraps around
369 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
370 * appropriate probability table. */
372 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
374 struct lzms_probability_entry *prob_entry;
377 /* Load the probability entry corresponding to the current state. */
378 prob_entry = &enc->prob_entries[enc->state];
380 /* Treat the number of zero bits in the most recently encoded
381 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
382 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
383 * don't allow 0% or 100% probabilities. */
384 prob = prob_entry->num_recent_zero_bits;
387 else if (prob == LZMS_PROBABILITY_MAX)
388 prob = LZMS_PROBABILITY_MAX - 1;
390 /* Encode the next bit. */
391 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
393 /* Update the state based on the newly encoded bit. */
394 enc->state = ((enc->state << 1) | bit) & enc->mask;
396 /* Update the recent bits, including the cached count of 0's. */
397 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
399 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
400 /* Replacing 1 bit with 0 bit; increment the zero count.
402 prob_entry->num_recent_zero_bits++;
405 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
406 /* Replacing 0 bit with 1 bit; decrement the zero count.
408 prob_entry->num_recent_zero_bits--;
411 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
414 /* Encode a symbol using the specified Huffman encoder. */
416 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
418 LZMS_ASSERT(sym < enc->num_syms);
419 if (enc->num_syms_written == enc->rebuild_freq) {
420 /* Adaptive code needs to be rebuilt. */
421 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
422 make_canonical_huffman_code(enc->num_syms,
423 LZMS_MAX_CODEWORD_LEN,
428 /* Dilute the frequencies. */
429 for (unsigned i = 0; i < enc->num_syms; i++) {
430 enc->sym_freqs[i] >>= 1;
431 enc->sym_freqs[i] += 1;
433 enc->num_syms_written = 0;
435 lzms_output_bitstream_put_bits(enc->os,
438 ++enc->num_syms_written;
439 ++enc->sym_freqs[sym];
442 /* Encode a number as a Huffman symbol specifying a slot, plus a number of
443 * slot-dependent extra bits. */
445 lzms_encode_value(struct lzms_huffman_encoder *enc, u32 value)
448 unsigned num_extra_bits;
451 LZMS_ASSERT(enc->slot_base_tab != NULL);
453 slot = lzms_get_slot(value, enc->slot_base_tab, enc->num_syms);
455 /* Get the number of extra bits needed to represent the range of values
456 * that share the slot. */
457 num_extra_bits = bsr32(enc->slot_base_tab[slot + 1] -
458 enc->slot_base_tab[slot]);
460 /* Calculate the extra bits as the offset from the slot base. */
461 extra_bits = value - enc->slot_base_tab[slot];
463 /* Output the slot (Huffman-encoded), then the extra bits (verbatim).
465 lzms_huffman_encode_symbol(enc, slot);
466 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
470 lzms_begin_encode_item(struct lzms_compressor *ctx)
472 ctx->lru.lz.upcoming_offset = 0;
473 ctx->lru.delta.upcoming_offset = 0;
474 ctx->lru.delta.upcoming_power = 0;
478 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
480 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
481 ctx->cur_window_pos += length;
482 lzms_update_lru_queues(&ctx->lru);
485 /* Encode a literal byte. */
487 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
489 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
490 ctx->cur_window_pos, literal, literal);
492 lzms_begin_encode_item(ctx);
494 /* Main bit: 0 = a literal, not a match. */
495 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
497 /* Encode the literal using the current literal Huffman code. */
498 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
500 lzms_end_encode_item(ctx, 1);
503 /* Encode a (length, offset) pair (LZ match). */
505 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
507 int recent_offset_idx;
509 lzms_begin_encode_item(ctx);
511 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
512 ctx->cur_window_pos, length, offset);
514 /* Main bit: 1 = a match, not a literal. */
515 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
517 /* Match bit: 0 = a LZ match, not a delta match. */
518 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
520 /* Determine if the offset can be represented as a recent offset. */
521 for (recent_offset_idx = 0;
522 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
524 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
527 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
528 /* Explicit offset. */
530 /* LZ match bit: 0 = explicit offset, not a repeat offset. */
531 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
533 /* Encode the match offset. */
534 lzms_encode_value(&ctx->lz_offset_encoder, offset);
540 /* LZ match bit: 1 = repeat offset, not an explicit offset. */
541 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
543 /* Encode the recent offset index. A 1 bit is encoded for each
544 * index passed up. This sequence of 1 bits is terminated by a
545 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
546 * bits have been encoded. */
547 for (i = 0; i < recent_offset_idx; i++)
548 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
550 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
551 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
553 /* Initial update of the LZ match offset LRU queue. */
554 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
555 ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
558 /* Encode the match length. */
559 lzms_encode_value(&ctx->length_encoder, length);
561 /* Save the match offset for later insertion at the front of the LZ
562 * match offset LRU queue. */
563 ctx->lru.lz.upcoming_offset = offset;
565 lzms_end_encode_item(ctx, length);
569 lzms_record_literal(u8 literal, void *_ctx)
571 struct lzms_compressor *ctx = _ctx;
573 lzms_encode_literal(ctx, literal);
577 lzms_record_match(unsigned length, unsigned offset, void *_ctx)
579 struct lzms_compressor *ctx = _ctx;
581 lzms_encode_lz_match(ctx, length, offset);
585 lzms_fast_encode(struct lzms_compressor *ctx)
587 static const struct lz_params lzms_lz_params = {
589 .max_match = UINT_MAX,
590 .max_offset = UINT_MAX,
594 .max_lazy_match = 258,
598 lz_analyze_block(ctx->window,
608 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
609 * Unlike lzms_match_cost() which does a true cost evaluation, this simply
610 * prioritize matches based on their offset. */
612 lzms_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_lru)
614 const struct lzms_lz_lru_queues *lru = _lru;
617 /* It seems well worth it to take the time to give priority to recently
619 for (input_idx_t i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++)
620 if (offset == lru->recent_offsets[i])
627 lzms_lz_skip_bytes(struct lzms_compressor *ctx, u32 n)
630 lz_sarray_skip_position(&ctx->lz_sarray);
633 static struct raw_match
634 lzms_get_near_optimal_match(struct lzms_compressor *ctx)
636 struct raw_match matches[10];
639 num_matches = lz_sarray_get_matches(&ctx->lz_sarray,
641 lzms_match_cost_fast,
643 if (num_matches == 0)
644 return (struct raw_match) { .len = 0 };
647 fprintf(stderr, "Pos %u/%u: %u matches\n",
648 lz_sarray_get_pos(&ctx->lz_sarray) - 1,
649 ctx->window_size, num_matches);
650 for (u32 i = 0; i < num_matches; i++)
651 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
654 lzms_lz_skip_bytes(ctx, matches[0].len - 1);
659 lzms_slow_encode(struct lzms_compressor *ctx)
661 struct raw_match match;
663 /* Load window into suffix array match-finder. */
664 lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
667 while (ctx->cur_window_pos != ctx->window_size) {
669 match = lzms_get_near_optimal_match(ctx);
670 if (match.len == 0) {
672 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
675 lzms_encode_lz_match(ctx, match.len, match.offset);
681 lzms_init_range_encoder(struct lzms_range_encoder *enc,
682 struct lzms_range_encoder_raw *rc, u32 num_states)
686 enc->mask = num_states - 1;
687 for (u32 i = 0; i < num_states; i++) {
688 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
689 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
694 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
695 struct lzms_output_bitstream *os,
696 const u32 *slot_base_tab,
698 unsigned rebuild_freq)
701 enc->slot_base_tab = slot_base_tab;
702 enc->num_syms_written = rebuild_freq;
703 enc->rebuild_freq = rebuild_freq;
704 enc->num_syms = num_syms;
705 for (unsigned i = 0; i < num_syms; i++)
706 enc->sym_freqs[i] = 1;
709 /* Initialize the LZMS compressor. */
711 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
712 le16 *cdata, u32 clen16)
714 unsigned num_position_slots;
716 /* Copy the uncompressed data into the @ctx->window buffer. */
717 memcpy(ctx->window, udata, ulen);
718 memset(&ctx->window[ulen], 0, 8);
719 ctx->cur_window_pos = 0;
720 ctx->window_size = ulen;
722 /* Initialize the raw range encoder (writing forwards). */
723 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
725 /* Initialize the output bitstream for Huffman symbols and verbatim bits
726 * (writing backwards). */
727 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
729 /* Initialize position and length slot bases if not done already. */
730 lzms_init_slot_bases();
732 /* Calculate the number of position slots needed for this compressed
734 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
736 LZMS_DEBUG("Using %u position slots", num_position_slots);
738 /* Initialize Huffman encoders for each alphabet used in the compressed
740 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
741 NULL, LZMS_NUM_LITERAL_SYMS,
742 LZMS_LITERAL_CODE_REBUILD_FREQ);
744 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
745 lzms_position_slot_base, num_position_slots,
746 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
748 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
749 lzms_length_slot_base, LZMS_NUM_LEN_SYMS,
750 LZMS_LENGTH_CODE_REBUILD_FREQ);
752 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
753 lzms_position_slot_base, num_position_slots,
754 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
756 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
757 NULL, LZMS_NUM_DELTA_POWER_SYMS,
758 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
760 /* Initialize range encoders, all of which wrap around the same
761 * lzms_range_encoder_raw. */
762 lzms_init_range_encoder(&ctx->main_range_encoder,
763 &ctx->rc, LZMS_NUM_MAIN_STATES);
765 lzms_init_range_encoder(&ctx->match_range_encoder,
766 &ctx->rc, LZMS_NUM_MATCH_STATES);
768 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
769 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
771 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
772 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
773 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
775 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
776 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
778 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
779 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
780 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
782 /* Initialize LRU match information. */
783 lzms_init_lru_queues(&ctx->lru);
786 /* Flush the output streams, prepare the final compressed data, and return its
789 * A return value of 0 indicates that the data could not be compressed to fit in
790 * the available space. */
792 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
794 size_t num_forwards_bytes;
795 size_t num_backwards_bytes;
796 size_t compressed_size;
798 /* Flush both the forwards and backwards streams, and make sure they
799 * didn't cross each other and start overwriting each other's data. */
800 if (!lzms_output_bitstream_flush(&ctx->os)) {
801 LZMS_DEBUG("Backwards bitstream overrun.");
805 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
806 LZMS_DEBUG("Forwards bitstream overrun.");
810 if (ctx->rc.out > ctx->os.out) {
811 LZMS_DEBUG("Two bitstreams crossed.");
815 /* Now the compressed buffer contains the data output by the forwards
816 * bitstream, then empty space, then data output by the backwards
817 * bitstream. Move the data output by the forwards bitstream to be
818 * adjacent to the data output by the backwards bitstream, and calculate
819 * the compressed size that this results in. */
820 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
821 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
823 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
825 compressed_size = num_forwards_bytes + num_backwards_bytes;
826 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
827 "compressed_size=%zu",
828 num_forwards_bytes, num_backwards_bytes, compressed_size);
829 LZMS_ASSERT(!(compressed_size & 1));
830 return compressed_size;
834 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
835 void *compressed_data, size_t compressed_size_avail, void *_ctx)
837 struct lzms_compressor *ctx = _ctx;
838 size_t compressed_size;
840 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
841 uncompressed_size, compressed_size_avail);
843 /* Make sure the uncompressed size is compatible with this compressor.
845 if (uncompressed_size > ctx->max_block_size) {
846 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
847 "only supports %u bytes",
848 uncompressed_size, ctx->max_block_size);
852 /* Don't bother compressing extremely small inputs. */
853 if (uncompressed_size < 4)
856 /* Cap the available compressed size to a 32-bit integer, and round it
857 * down to the nearest multiple of 2. */
858 if (compressed_size_avail > UINT32_MAX)
859 compressed_size_avail = UINT32_MAX;
860 if (compressed_size_avail & 1)
861 compressed_size_avail--;
863 /* Initialize the compressor structures. */
864 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
865 compressed_data, compressed_size_avail / 2);
867 /* Preprocess the uncompressed data. */
868 lzms_x86_filter(ctx->window, ctx->window_size,
869 ctx->last_target_usages, false);
871 /* Determine and output a literal/match sequence that decompresses to
872 * the preprocessed data. */
874 lzms_slow_encode(ctx);
876 lzms_fast_encode(ctx);
878 /* Get and return the compressed data size. */
879 compressed_size = lzms_finalize(ctx, compressed_data,
880 compressed_size_avail);
882 if (compressed_size == 0) {
883 LZMS_DEBUG("Data did not compress to requested size or less.");
887 LZMS_DEBUG("Compressed %zu => %zu bytes",
888 uncompressed_size, compressed_size);
890 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
891 /* Verify that we really get the same thing back when decompressing. */
893 struct wimlib_decompressor *decompressor;
895 LZMS_DEBUG("Verifying LZMS compression.");
897 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
903 ret = wimlib_decompress(compressed_data,
908 wimlib_free_decompressor(decompressor);
911 ERROR("Failed to decompress data we "
912 "compressed using LZMS algorithm");
916 if (memcmp(uncompressed_data, ctx->window,
919 ERROR("Data we compressed using LZMS algorithm "
920 "didn't decompress to original");
925 WARNING("Failed to create decompressor for "
926 "data verification!");
929 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION */
931 return compressed_size;
935 lzms_free_compressor(void *_ctx)
937 struct lzms_compressor *ctx = _ctx;
942 lz_sarray_destroy(&ctx->lz_sarray);
948 lzms_create_compressor(size_t max_block_size,
949 const struct wimlib_compressor_params_header *params,
952 struct lzms_compressor *ctx;
954 if (max_block_size == 0 || max_block_size >= INT32_MAX) {
955 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
956 return WIMLIB_ERR_INVALID_PARAM;
959 ctx = CALLOC(1, sizeof(struct lzms_compressor));
963 ctx->window = MALLOC(max_block_size + 8);
964 if (ctx->window == NULL)
967 ctx->prev_tab = MALLOC(max_block_size * sizeof(ctx->prev_tab[0]));
968 if (ctx->prev_tab == NULL)
971 if (!lz_sarray_init(&ctx->lz_sarray,
980 ctx->max_block_size = max_block_size;
986 lzms_free_compressor(ctx);
987 return WIMLIB_ERR_NOMEM;
990 const struct compressor_ops lzms_compressor_ops = {
991 .create_compressor = lzms_create_compressor,
992 .compress = lzms_compress,
993 .free_compressor = lzms_free_compressor,