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 #define LZMS_OPTIM_ARRAY_SIZE 1024
52 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
53 * a series of 16-bit little endian coding units. */
54 struct lzms_output_bitstream {
55 /* Buffer variable containing zero or more bits that have been logically
56 * written to the bitstream but not yet written to memory. This must be
57 * at least as large as the coding unit size. */
60 /* Number of bits in @bitbuf that are valid. */
61 unsigned num_free_bits;
63 /* Pointer to one past the next position in the compressed data buffer
64 * at which to output a 16-bit coding unit. */
67 /* Maximum number of 16-bit coding units that can still be output to
68 * the compressed data buffer. */
69 size_t num_le16_remaining;
71 /* Set to %true if not all coding units could be output due to
72 * insufficient space. */
76 /* Stucture used for range encoding (raw version). */
77 struct lzms_range_encoder_raw {
79 /* A 33-bit variable that holds the low boundary of the current range.
80 * The 33rd bit is needed to catch carries. */
83 /* Size of the current range. */
86 /* Next 16-bit coding unit to output. */
89 /* Number of 16-bit coding units whose output has been delayed due to
90 * possible carrying. The first such coding unit is @cache; all
91 * subsequent such coding units are 0xffff. */
94 /* Pointer to the next position in the compressed data buffer at which
95 * to output a 16-bit coding unit. */
98 /* Maximum number of 16-bit coding units that can still be output to
99 * the compressed data buffer. */
100 size_t num_le16_remaining;
102 /* %true when the very first coding unit has not yet been output. */
105 /* Set to %true if not all coding units could be output due to
106 * insufficient space. */
110 /* Structure used for range encoding. This wraps around `struct
111 * lzms_range_encoder_raw' to use and maintain probability entries. */
112 struct lzms_range_encoder {
113 /* Pointer to the raw range encoder, which has no persistent knowledge
114 * of probabilities. Multiple lzms_range_encoder's share the same
115 * lzms_range_encoder_raw. */
116 struct lzms_range_encoder_raw *rc;
118 /* Bits recently encoded by this range encoder. This are used as in
119 * index into @prob_entries. */
122 /* Bitmask for @state to prevent its value from exceeding the number of
123 * probability entries. */
126 /* Probability entries being used for this range encoder. */
127 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
130 /* Structure used for Huffman encoding, optionally encoding larger "values" as a
131 * Huffman symbol specifying a slot and a slot-dependent number of extra bits.
133 struct lzms_huffman_encoder {
135 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
136 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
138 struct lzms_output_bitstream *os;
140 /* Pointer to the slot base table to use. */
141 const u32 *slot_base_tab;
143 /* Number of symbols that have been written using this code far. Reset
144 * to 0 whenever the code is rebuilt. */
145 u32 num_syms_written;
147 /* When @num_syms_written reaches this number, the Huffman code must be
151 /* Number of symbols in the represented Huffman code. */
154 /* Running totals of symbol frequencies. These are diluted slightly
155 * whenever the code is rebuilt. */
156 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
158 /* The length, in bits, of each symbol in the Huffman code. */
159 u8 lens[LZMS_MAX_NUM_SYMS];
161 /* The codeword of each symbol in the Huffman code. */
162 u16 codewords[LZMS_MAX_NUM_SYMS];
165 /* State of the LZMS compressor. */
166 struct lzms_compressor {
167 /* Pointer to a buffer holding the preprocessed data to compress. */
170 /* Current position in @buffer. */
173 /* Size of the data in @buffer. */
176 /* Temporary array used by lz_analyze_block(); must be at least as long
180 /* Suffix array match-finder. */
181 struct lz_sarray lz_sarray;
183 /* Maximum block size this compressor instantiation allows. This is the
184 * allocated size of @window. */
187 /* Raw range encoder which outputs to the beginning of the compressed
188 * data buffer, proceeding forwards. */
189 struct lzms_range_encoder_raw rc;
191 /* Bitstream which outputs to the end of the compressed data buffer,
192 * proceeding backwards. */
193 struct lzms_output_bitstream os;
195 /* Range encoders. */
196 struct lzms_range_encoder main_range_encoder;
197 struct lzms_range_encoder match_range_encoder;
198 struct lzms_range_encoder lz_match_range_encoder;
199 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
200 struct lzms_range_encoder delta_match_range_encoder;
201 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
203 /* Huffman encoders. */
204 struct lzms_huffman_encoder literal_encoder;
205 struct lzms_huffman_encoder lz_offset_encoder;
206 struct lzms_huffman_encoder length_encoder;
207 struct lzms_huffman_encoder delta_power_encoder;
208 struct lzms_huffman_encoder delta_offset_encoder;
210 /* LRU (least-recently-used) queues for match information. */
211 struct lzms_lru_queues lru;
213 /* Used for preprocessing. */
214 s32 last_target_usages[65536];
217 /* Initialize the output bitstream @os to write forwards to the specified
218 * compressed data buffer @out that is @out_limit 16-bit integers long. */
220 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
221 le16 *out, size_t out_limit)
224 os->num_free_bits = 16;
225 os->out = out + out_limit;
226 os->num_le16_remaining = out_limit;
230 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
231 * from high-order to low-order), to the output bitstream @os. */
233 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
234 u32 bits, unsigned num_bits)
236 bits &= (1U << num_bits) - 1;
238 while (num_bits > os->num_free_bits) {
240 if (unlikely(os->num_le16_remaining == 0)) {
245 unsigned num_fill_bits = os->num_free_bits;
247 os->bitbuf <<= num_fill_bits;
248 os->bitbuf |= bits >> (num_bits - num_fill_bits);
250 *--os->out = cpu_to_le16(os->bitbuf);
251 --os->num_le16_remaining;
253 os->num_free_bits = 16;
254 num_bits -= num_fill_bits;
255 bits &= (1U << num_bits) - 1;
257 os->bitbuf <<= num_bits;
259 os->num_free_bits -= num_bits;
262 /* Flush the output bitstream, ensuring that all bits written to it have been
263 * written to memory. Returns %true if all bits were output successfully, or
264 * %false if an overrun occurred. */
266 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
268 if (os->num_free_bits != 16)
269 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
273 /* Initialize the range encoder @rc to write forwards to the specified
274 * compressed data buffer @out that is @out_limit 16-bit integers long. */
276 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
277 le16 *out, size_t out_limit)
280 rc->range = 0xffffffff;
284 rc->num_le16_remaining = out_limit;
290 * Attempt to flush bits from the range encoder.
292 * Note: this is based on the public domain code for LZMA written by Igor
293 * Pavlov. The only differences in this function are that in LZMS the bits must
294 * be output in 16-bit coding units instead of 8-bit coding units, and that in
295 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
296 * cannot output a dummy value to that position.
298 * The basic idea is that we're writing bits from @rc->low to the output.
299 * However, due to carrying, the writing of coding units with value 0xffff, as
300 * well as one prior coding unit, must be delayed until it is determined whether
304 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
306 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
307 rc->low, rc->cache, rc->cache_size);
308 if ((u32)(rc->low) < 0xffff0000 ||
309 (u32)(rc->low >> 32) != 0)
311 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
312 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
315 if (rc->num_le16_remaining == 0) {
319 *rc->out++ = cpu_to_le16(rc->cache +
320 (u16)(rc->low >> 32));
321 --rc->num_le16_remaining;
327 } while (--rc->cache_size != 0);
329 rc->cache = (rc->low >> 16) & 0xffff;
332 rc->low = (rc->low & 0xffff) << 16;
336 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
338 if (rc->range <= 0xffff) {
340 lzms_range_encoder_raw_shift_low(rc);
345 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
347 for (unsigned i = 0; i < 4; i++)
348 lzms_range_encoder_raw_shift_low(rc);
352 /* Encode the next bit using the range encoder (raw version).
354 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
356 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
359 lzms_range_encoder_raw_normalize(rc);
361 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
370 /* Encode a bit using the specified range encoder. This wraps around
371 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
372 * appropriate probability table. */
374 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
376 struct lzms_probability_entry *prob_entry;
379 /* Load the probability entry corresponding to the current state. */
380 prob_entry = &enc->prob_entries[enc->state];
382 /* Treat the number of zero bits in the most recently encoded
383 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
384 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
385 * don't allow 0% or 100% probabilities. */
386 prob = prob_entry->num_recent_zero_bits;
389 else if (prob == LZMS_PROBABILITY_MAX)
390 prob = LZMS_PROBABILITY_MAX - 1;
392 /* Encode the next bit. */
393 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
395 /* Update the state based on the newly encoded bit. */
396 enc->state = ((enc->state << 1) | bit) & enc->mask;
398 /* Update the recent bits, including the cached count of 0's. */
399 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
401 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
402 /* Replacing 1 bit with 0 bit; increment the zero count.
404 prob_entry->num_recent_zero_bits++;
407 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
408 /* Replacing 0 bit with 1 bit; decrement the zero count.
410 prob_entry->num_recent_zero_bits--;
413 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
416 /* Encode a symbol using the specified Huffman encoder. */
418 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
420 LZMS_ASSERT(sym < enc->num_syms);
421 if (enc->num_syms_written == enc->rebuild_freq) {
422 /* Adaptive code needs to be rebuilt. */
423 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
424 make_canonical_huffman_code(enc->num_syms,
425 LZMS_MAX_CODEWORD_LEN,
430 /* Dilute the frequencies. */
431 for (unsigned i = 0; i < enc->num_syms; i++) {
432 enc->sym_freqs[i] >>= 1;
433 enc->sym_freqs[i] += 1;
435 enc->num_syms_written = 0;
437 lzms_output_bitstream_put_bits(enc->os,
440 ++enc->num_syms_written;
441 ++enc->sym_freqs[sym];
444 /* Encode a number as a Huffman symbol specifying a slot, plus a number of
445 * slot-dependent extra bits. */
447 lzms_encode_value(struct lzms_huffman_encoder *enc, u32 value)
450 unsigned num_extra_bits;
453 LZMS_ASSERT(enc->slot_base_tab != NULL);
455 slot = lzms_get_slot(value, enc->slot_base_tab, enc->num_syms);
457 /* Get the number of extra bits needed to represent the range of values
458 * that share the slot. */
459 num_extra_bits = bsr32(enc->slot_base_tab[slot + 1] -
460 enc->slot_base_tab[slot]);
462 /* Calculate the extra bits as the offset from the slot base. */
463 extra_bits = value - enc->slot_base_tab[slot];
465 /* Output the slot (Huffman-encoded), then the extra bits (verbatim).
467 lzms_huffman_encode_symbol(enc, slot);
468 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
472 lzms_begin_encode_item(struct lzms_compressor *ctx)
474 ctx->lru.lz.upcoming_offset = 0;
475 ctx->lru.delta.upcoming_offset = 0;
476 ctx->lru.delta.upcoming_power = 0;
480 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
482 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
483 ctx->cur_window_pos += length;
484 lzms_update_lru_queues(&ctx->lru);
487 /* Encode a literal byte. */
489 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
491 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
492 ctx->cur_window_pos, literal, literal);
494 lzms_begin_encode_item(ctx);
496 /* Main bit: 0 = a literal, not a match. */
497 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
499 /* Encode the literal using the current literal Huffman code. */
500 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
502 lzms_end_encode_item(ctx, 1);
505 /* Encode a (length, offset) pair (LZ match). */
507 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
509 int recent_offset_idx;
511 lzms_begin_encode_item(ctx);
513 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
514 ctx->cur_window_pos, length, offset);
516 /* Main bit: 1 = a match, not a literal. */
517 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
519 /* Match bit: 0 = a LZ match, not a delta match. */
520 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
522 /* Determine if the offset can be represented as a recent offset. */
523 for (recent_offset_idx = 0;
524 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
526 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
529 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
530 /* Explicit offset. */
532 /* LZ match bit: 0 = explicit offset, not a repeat offset. */
533 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
535 /* Encode the match offset. */
536 lzms_encode_value(&ctx->lz_offset_encoder, offset);
542 /* LZ match bit: 1 = repeat offset, not an explicit offset. */
543 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
545 /* Encode the recent offset index. A 1 bit is encoded for each
546 * index passed up. This sequence of 1 bits is terminated by a
547 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
548 * bits have been encoded. */
549 for (i = 0; i < recent_offset_idx; i++)
550 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
552 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
553 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
555 /* Initial update of the LZ match offset LRU queue. */
556 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
557 ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
560 /* Encode the match length. */
561 lzms_encode_value(&ctx->length_encoder, length);
563 /* Save the match offset for later insertion at the front of the LZ
564 * match offset LRU queue. */
565 ctx->lru.lz.upcoming_offset = offset;
567 lzms_end_encode_item(ctx, length);
571 lzms_record_literal(u8 literal, void *_ctx)
573 struct lzms_compressor *ctx = _ctx;
575 lzms_encode_literal(ctx, literal);
579 lzms_record_match(unsigned length, unsigned offset, void *_ctx)
581 struct lzms_compressor *ctx = _ctx;
583 lzms_encode_lz_match(ctx, length, offset);
587 lzms_fast_encode(struct lzms_compressor *ctx)
589 static const struct lz_params lzms_lz_params = {
591 .max_match = UINT_MAX,
592 .max_offset = UINT_MAX,
596 .max_lazy_match = 258,
600 lz_analyze_block(ctx->window,
610 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
611 * Unlike lzms_match_cost() which does a true cost evaluation, this simply
612 * prioritize matches based on their offset. */
614 lzms_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_lru)
616 const struct lzms_lz_lru_queues *lru = _lru;
619 /* It seems well worth it to take the time to give priority to recently
621 for (input_idx_t i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++)
622 if (offset == lru->recent_offsets[i])
629 lzms_lz_skip_bytes(struct lzms_compressor *ctx, u32 n)
632 lz_sarray_skip_position(&ctx->lz_sarray);
635 static struct raw_match
636 lzms_get_near_optimal_match(struct lzms_compressor *ctx)
638 struct raw_match matches[10];
641 num_matches = lz_sarray_get_matches(&ctx->lz_sarray,
643 lzms_match_cost_fast,
645 if (num_matches == 0)
646 return (struct raw_match) { .len = 0 };
649 fprintf(stderr, "Pos %u/%u: %u matches\n",
650 lz_sarray_get_pos(&ctx->lz_sarray) - 1,
651 ctx->window_size, num_matches);
652 for (u32 i = 0; i < num_matches; i++)
653 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
656 lzms_lz_skip_bytes(ctx, matches[0].len - 1);
661 lzms_slow_encode(struct lzms_compressor *ctx)
663 struct raw_match match;
665 /* Load window into suffix array match-finder. */
666 lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
669 while (ctx->cur_window_pos != ctx->window_size) {
671 match = lzms_get_near_optimal_match(ctx);
672 if (match.len == 0) {
674 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
677 lzms_encode_lz_match(ctx, match.len, match.offset);
683 lzms_init_range_encoder(struct lzms_range_encoder *enc,
684 struct lzms_range_encoder_raw *rc, u32 num_states)
688 enc->mask = num_states - 1;
689 for (u32 i = 0; i < num_states; i++) {
690 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
691 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
696 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
697 struct lzms_output_bitstream *os,
698 const u32 *slot_base_tab,
700 unsigned rebuild_freq)
703 enc->slot_base_tab = slot_base_tab;
704 enc->num_syms_written = rebuild_freq;
705 enc->rebuild_freq = rebuild_freq;
706 enc->num_syms = num_syms;
707 for (unsigned i = 0; i < num_syms; i++)
708 enc->sym_freqs[i] = 1;
711 /* Initialize the LZMS compressor. */
713 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
714 le16 *cdata, u32 clen16)
716 unsigned num_position_slots;
718 /* Copy the uncompressed data into the @ctx->window buffer. */
719 memcpy(ctx->window, udata, ulen);
720 memset(&ctx->window[ulen], 0, 8);
721 ctx->cur_window_pos = 0;
722 ctx->window_size = ulen;
724 /* Initialize the raw range encoder (writing forwards). */
725 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
727 /* Initialize the output bitstream for Huffman symbols and verbatim bits
728 * (writing backwards). */
729 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
731 /* Initialize position and length slot bases if not done already. */
732 lzms_init_slot_bases();
734 /* Calculate the number of position slots needed for this compressed
736 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
738 LZMS_DEBUG("Using %u position slots", num_position_slots);
740 /* Initialize Huffman encoders for each alphabet used in the compressed
742 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
743 NULL, LZMS_NUM_LITERAL_SYMS,
744 LZMS_LITERAL_CODE_REBUILD_FREQ);
746 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
747 lzms_position_slot_base, num_position_slots,
748 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
750 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
751 lzms_length_slot_base, LZMS_NUM_LEN_SYMS,
752 LZMS_LENGTH_CODE_REBUILD_FREQ);
754 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
755 lzms_position_slot_base, num_position_slots,
756 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
758 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
759 NULL, LZMS_NUM_DELTA_POWER_SYMS,
760 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
762 /* Initialize range encoders, all of which wrap around the same
763 * lzms_range_encoder_raw. */
764 lzms_init_range_encoder(&ctx->main_range_encoder,
765 &ctx->rc, LZMS_NUM_MAIN_STATES);
767 lzms_init_range_encoder(&ctx->match_range_encoder,
768 &ctx->rc, LZMS_NUM_MATCH_STATES);
770 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
771 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
773 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
774 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
775 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
777 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
778 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
780 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
781 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
782 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
784 /* Initialize LRU match information. */
785 lzms_init_lru_queues(&ctx->lru);
788 /* Flush the output streams, prepare the final compressed data, and return its
791 * A return value of 0 indicates that the data could not be compressed to fit in
792 * the available space. */
794 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
796 size_t num_forwards_bytes;
797 size_t num_backwards_bytes;
798 size_t compressed_size;
800 /* Flush both the forwards and backwards streams, and make sure they
801 * didn't cross each other and start overwriting each other's data. */
802 if (!lzms_output_bitstream_flush(&ctx->os)) {
803 LZMS_DEBUG("Backwards bitstream overrun.");
807 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
808 LZMS_DEBUG("Forwards bitstream overrun.");
812 if (ctx->rc.out > ctx->os.out) {
813 LZMS_DEBUG("Two bitstreams crossed.");
817 /* Now the compressed buffer contains the data output by the forwards
818 * bitstream, then empty space, then data output by the backwards
819 * bitstream. Move the data output by the forwards bitstream to be
820 * adjacent to the data output by the backwards bitstream, and calculate
821 * the compressed size that this results in. */
822 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
823 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
825 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
827 compressed_size = num_forwards_bytes + num_backwards_bytes;
828 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
829 "compressed_size=%zu",
830 num_forwards_bytes, num_backwards_bytes, compressed_size);
831 LZMS_ASSERT(!(compressed_size & 1));
832 return compressed_size;
836 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
837 void *compressed_data, size_t compressed_size_avail, void *_ctx)
839 struct lzms_compressor *ctx = _ctx;
840 size_t compressed_size;
842 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
843 uncompressed_size, compressed_size_avail);
845 /* Make sure the uncompressed size is compatible with this compressor.
847 if (uncompressed_size > ctx->max_block_size) {
848 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
849 "only supports %u bytes",
850 uncompressed_size, ctx->max_block_size);
854 /* Don't bother compressing extremely small inputs. */
855 if (uncompressed_size < 4)
858 /* Cap the available compressed size to a 32-bit integer, and round it
859 * down to the nearest multiple of 2. */
860 if (compressed_size_avail > UINT32_MAX)
861 compressed_size_avail = UINT32_MAX;
862 if (compressed_size_avail & 1)
863 compressed_size_avail--;
865 /* Initialize the compressor structures. */
866 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
867 compressed_data, compressed_size_avail / 2);
869 /* Preprocess the uncompressed data. */
870 lzms_x86_filter(ctx->window, ctx->window_size,
871 ctx->last_target_usages, false);
873 /* Determine and output a literal/match sequence that decompresses to
874 * the preprocessed data. */
876 lzms_slow_encode(ctx);
878 lzms_fast_encode(ctx);
880 /* Get and return the compressed data size. */
881 compressed_size = lzms_finalize(ctx, compressed_data,
882 compressed_size_avail);
884 if (compressed_size == 0) {
885 LZMS_DEBUG("Data did not compress to requested size or less.");
889 LZMS_DEBUG("Compressed %zu => %zu bytes",
890 uncompressed_size, compressed_size);
892 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
893 /* Verify that we really get the same thing back when decompressing. */
895 struct wimlib_decompressor *decompressor;
897 LZMS_DEBUG("Verifying LZMS compression.");
899 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
905 ret = wimlib_decompress(compressed_data,
910 wimlib_free_decompressor(decompressor);
913 ERROR("Failed to decompress data we "
914 "compressed using LZMS algorithm");
918 if (memcmp(uncompressed_data, ctx->window,
921 ERROR("Data we compressed using LZMS algorithm "
922 "didn't decompress to original");
927 WARNING("Failed to create decompressor for "
928 "data verification!");
931 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION */
933 return compressed_size;
937 lzms_free_compressor(void *_ctx)
939 struct lzms_compressor *ctx = _ctx;
944 lz_sarray_destroy(&ctx->lz_sarray);
950 lzms_create_compressor(size_t max_block_size,
951 const struct wimlib_compressor_params_header *params,
954 struct lzms_compressor *ctx;
956 if (max_block_size == 0 || max_block_size >= INT32_MAX) {
957 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
958 return WIMLIB_ERR_INVALID_PARAM;
961 ctx = CALLOC(1, sizeof(struct lzms_compressor));
965 ctx->window = MALLOC(max_block_size + 8);
966 if (ctx->window == NULL)
969 ctx->prev_tab = MALLOC(max_block_size * sizeof(ctx->prev_tab[0]));
970 if (ctx->prev_tab == NULL)
973 if (!lz_sarray_init(&ctx->lz_sarray,
982 ctx->max_block_size = max_block_size;
988 lzms_free_compressor(ctx);
989 return WIMLIB_ERR_NOMEM;
992 const struct compressor_ops lzms_compressor_ops = {
993 .create_compressor = lzms_create_compressor,
994 .compress = lzms_compress,
995 .free_compressor = lzms_free_compressor,