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/lzms.h"
43 #include "wimlib/util.h"
48 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
49 * a series of 16-bit little endian coding units. */
50 struct lzms_output_bitstream {
51 /* Buffer variable containing zero or more bits that have been logically
52 * written to the bitstream but not yet written to memory. This must be
53 * at least as large as the coding unit size. */
56 /* Number of bits in @bitbuf that are valid. */
57 unsigned num_free_bits;
59 /* Pointer to one past the next position in the compressed data buffer
60 * at which to output a 16-bit coding unit. */
63 /* Maximum number of 16-bit coding units that can still be output to
64 * the compressed data buffer. */
65 size_t num_le16_remaining;
67 /* Set to %true if not all coding units could be output due to
68 * insufficient space. */
72 /* Stucture used for range encoding (raw version). */
73 struct lzms_range_encoder_raw {
75 /* A 33-bit variable that holds the low boundary of the current range.
76 * The 33rd bit is needed to catch carries. */
79 /* Size of the current range. */
82 /* Next 16-bit coding unit to output. */
85 /* Number of 16-bit coding units whose output has been delayed due to
86 * possible carrying. The first such coding unit is @cache; all
87 * subsequent such coding units are 0xffff. */
90 /* Pointer to the next position in the compressed data buffer at which
91 * to output a 16-bit coding unit. */
94 /* Maximum number of 16-bit coding units that can still be output to
95 * the compressed data buffer. */
96 size_t num_le16_remaining;
98 /* %true when the very first coding unit has not yet been output. */
101 /* Set to %true if not all coding units could be output due to
102 * insufficient space. */
106 /* Structure used for range encoding. This wraps around `struct
107 * lzms_range_encoder_raw' to use and maintain probability entries. */
108 struct lzms_range_encoder {
109 /* Pointer to the raw range encoder, which has no persistent knowledge
110 * of probabilities. Multiple lzms_range_encoder's share the same
111 * lzms_range_encoder_raw. */
112 struct lzms_range_encoder_raw *rc;
114 /* Bits recently encoded by this range encoder. This are used as in
115 * index into @prob_entries. */
118 /* Bitmask for @state to prevent its value from exceeding the number of
119 * probability entries. */
122 /* Probability entries being used for this range encoder. */
123 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
126 /* Structure used for Huffman encoding, optionally encoding larger "values" as a
127 * Huffman symbol specifying a slot and a slot-dependent number of extra bits.
129 struct lzms_huffman_encoder {
131 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
132 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
134 struct lzms_output_bitstream *os;
136 /* Pointer to the slot base table to use. */
137 const u32 *slot_base_tab;
139 /* Number of symbols that have been written using this code far. Reset
140 * to 0 whenever the code is rebuilt. */
141 u32 num_syms_written;
143 /* When @num_syms_written reaches this number, the Huffman code must be
147 /* Number of symbols in the represented Huffman code. */
150 /* Running totals of symbol frequencies. These are diluted slightly
151 * whenever the code is rebuilt. */
152 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
154 /* The length, in bits, of each symbol in the Huffman code. */
155 u8 lens[LZMS_MAX_NUM_SYMS];
157 /* The codeword of each symbol in the Huffman code. */
158 u16 codewords[LZMS_MAX_NUM_SYMS];
161 /* State of the LZMS compressor. */
162 struct lzms_compressor {
163 /* Pointer to a buffer holding the preprocessed data to compress. */
166 /* Current position in @buffer. */
169 /* Size of the data in @buffer. */
172 /* Temporary array used by lz_analyze_block(); must be at least as long
176 /* Maximum block size this compressor instantiation allows. This is the
177 * allocated size of @window. */
180 /* Raw range encoder which outputs to the beginning of the compressed
181 * data buffer, proceeding forwards. */
182 struct lzms_range_encoder_raw rc;
184 /* Bitstream which outputs to the end of the compressed data buffer,
185 * proceeding backwards. */
186 struct lzms_output_bitstream os;
188 /* Range encoders. */
189 struct lzms_range_encoder main_range_encoder;
190 struct lzms_range_encoder match_range_encoder;
191 struct lzms_range_encoder lz_match_range_encoder;
192 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
193 struct lzms_range_encoder delta_match_range_encoder;
194 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
196 /* Huffman encoders. */
197 struct lzms_huffman_encoder literal_encoder;
198 struct lzms_huffman_encoder lz_offset_encoder;
199 struct lzms_huffman_encoder length_encoder;
200 struct lzms_huffman_encoder delta_power_encoder;
201 struct lzms_huffman_encoder delta_offset_encoder;
203 /* LRU (least-recently-used) queue of LZ match offsets. */
204 u64 recent_lz_offsets[LZMS_NUM_RECENT_OFFSETS + 1];
206 /* LRU (least-recently-used) queue of delta match powers. */
207 u32 recent_delta_powers[LZMS_NUM_RECENT_OFFSETS + 1];
209 /* LRU (least-recently-used) queue of delta match offsets. */
210 u32 recent_delta_offsets[LZMS_NUM_RECENT_OFFSETS + 1];
212 /* These variables are used to delay updates to the LRU queues by one
215 u32 prev_delta_power;
216 u32 prev_delta_offset;
217 u32 upcoming_lz_offset;
218 u32 upcoming_delta_power;
219 u32 upcoming_delta_offset;
221 /* Used for preprocessing. */
222 s32 last_target_usages[65536];
230 /* Initialize the output bitstream @os to write forwards to the specified
231 * compressed data buffer @out that is @out_limit 16-bit integers long. */
233 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
234 le16 *out, size_t out_limit)
237 os->num_free_bits = 16;
238 os->out = out + out_limit;
239 os->num_le16_remaining = out_limit;
243 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
244 * from high-order to low-order), to the output bitstream @os. */
246 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
247 u32 bits, unsigned num_bits)
249 bits &= (1U << num_bits) - 1;
251 while (num_bits > os->num_free_bits) {
253 if (unlikely(os->num_le16_remaining == 0)) {
258 unsigned num_fill_bits = os->num_free_bits;
260 os->bitbuf <<= num_fill_bits;
261 os->bitbuf |= bits >> (num_bits - num_fill_bits);
263 *--os->out = cpu_to_le16(os->bitbuf);
264 --os->num_le16_remaining;
266 os->num_free_bits = 16;
267 num_bits -= num_fill_bits;
268 bits &= (1U << num_bits) - 1;
270 os->bitbuf <<= num_bits;
272 os->num_free_bits -= num_bits;
275 /* Flush the output bitstream, ensuring that all bits written to it have been
276 * written to memory. Returns %true if all bits were output successfully, or
277 * %false if an overrun occurred. */
279 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
281 if (os->num_free_bits != 16)
282 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
286 /* Initialize the range encoder @rc to write forwards to the specified
287 * compressed data buffer @out that is @out_limit 16-bit integers long. */
289 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
290 le16 *out, size_t out_limit)
293 rc->range = 0xffffffff;
297 rc->num_le16_remaining = out_limit;
303 * Attempt to flush bits from the range encoder.
305 * Note: this is based on the public domain code for LZMA written by Igor
306 * Pavlov. The only differences in this function are that in LZMS the bits must
307 * be output in 16-bit coding units instead of 8-bit coding units, and that in
308 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
309 * cannot output a dummy value to that position.
311 * The basic idea is that we're writing bits from @rc->low to the output.
312 * However, due to carrying, the writing of coding units with value 0xffff, as
313 * well as one prior coding unit, must be delayed until it is determined whether
317 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
319 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
320 rc->low, rc->cache, rc->cache_size);
321 if ((u32)(rc->low) < 0xffff0000 ||
322 (u32)(rc->low >> 32) != 0)
324 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
325 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
328 if (rc->num_le16_remaining == 0) {
332 *rc->out++ = cpu_to_le16(rc->cache +
333 (u16)(rc->low >> 32));
334 --rc->num_le16_remaining;
340 } while (--rc->cache_size != 0);
342 rc->cache = (rc->low >> 16) & 0xffff;
345 rc->low = (rc->low & 0xffff) << 16;
349 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
351 if (rc->range <= 0xffff) {
353 lzms_range_encoder_raw_shift_low(rc);
358 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
360 for (unsigned i = 0; i < 4; i++)
361 lzms_range_encoder_raw_shift_low(rc);
365 /* Encode the next bit using the range encoder (raw version).
367 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
369 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
372 lzms_range_encoder_raw_normalize(rc);
374 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
383 /* Encode a bit using the specified range encoder. This wraps around
384 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
385 * appropriate probability table. */
387 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
389 struct lzms_probability_entry *prob_entry;
392 /* Load the probability entry corresponding to the current state. */
393 prob_entry = &enc->prob_entries[enc->state];
395 /* Treat the number of zero bits in the most recently encoded
396 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
397 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
398 * don't allow 0% or 100% probabilities. */
399 prob = prob_entry->num_recent_zero_bits;
402 else if (prob == LZMS_PROBABILITY_MAX)
403 prob = LZMS_PROBABILITY_MAX - 1;
405 /* Encode the next bit. */
406 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
408 /* Update the state based on the newly encoded bit. */
409 enc->state = ((enc->state << 1) | bit) & enc->mask;
411 /* Update the recent bits, including the cached count of 0's. */
412 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
414 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
415 /* Replacing 1 bit with 0 bit; increment the zero count.
417 prob_entry->num_recent_zero_bits++;
420 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
421 /* Replacing 0 bit with 1 bit; decrement the zero count.
423 prob_entry->num_recent_zero_bits--;
426 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
429 /* Encode a symbol using the specified Huffman encoder. */
431 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
433 LZMS_ASSERT(sym < enc->num_syms);
434 if (enc->num_syms_written == enc->rebuild_freq) {
435 /* Adaptive code needs to be rebuilt. */
436 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
437 make_canonical_huffman_code(enc->num_syms,
438 LZMS_MAX_CODEWORD_LEN,
443 /* Dilute the frequencies. */
444 for (unsigned i = 0; i < enc->num_syms; i++) {
445 enc->sym_freqs[i] >>= 1;
446 enc->sym_freqs[i] += 1;
448 enc->num_syms_written = 0;
450 lzms_output_bitstream_put_bits(enc->os,
453 ++enc->num_syms_written;
454 ++enc->sym_freqs[sym];
457 /* Encode a number as a Huffman symbol specifying a slot, plus a number of
458 * slot-dependent extra bits. */
460 lzms_encode_value(struct lzms_huffman_encoder *enc, u32 value)
463 unsigned num_extra_bits;
466 LZMS_ASSERT(enc->slot_base_tab != NULL);
468 slot = lzms_get_slot(value, enc->slot_base_tab, enc->num_syms);
470 /* Get the number of extra bits needed to represent the range of values
471 * that share the slot. */
472 num_extra_bits = bsr32(enc->slot_base_tab[slot + 1] -
473 enc->slot_base_tab[slot]);
475 /* Calculate the extra bits as the offset from the slot base. */
476 extra_bits = value - enc->slot_base_tab[slot];
478 /* Output the slot (Huffman-encoded), then the extra bits (verbatim).
480 lzms_huffman_encode_symbol(enc, slot);
481 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
485 lzms_begin_encode_item(struct lzms_compressor *ctx)
487 ctx->upcoming_delta_offset = 0;
488 ctx->upcoming_lz_offset = 0;
489 ctx->upcoming_delta_power = 0;
493 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
495 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
496 ctx->cur_window_pos += length;
498 /* Update LRU queues */
499 if (ctx->prev_lz_offset != 0) {
500 for (int i = LZMS_NUM_RECENT_OFFSETS - 1; i >= 0; i--)
501 ctx->recent_lz_offsets[i + 1] = ctx->recent_lz_offsets[i];
502 ctx->recent_lz_offsets[0] = ctx->prev_lz_offset;
505 if (ctx->prev_delta_offset != 0) {
506 for (int i = LZMS_NUM_RECENT_OFFSETS - 1; i >= 0; i--) {
507 ctx->recent_delta_powers[i + 1] = ctx->recent_delta_powers[i];
508 ctx->recent_delta_offsets[i + 1] = ctx->recent_delta_offsets[i];
510 ctx->recent_delta_powers[0] = ctx->prev_delta_power;
511 ctx->recent_delta_offsets[0] = ctx->prev_delta_offset;
514 ctx->prev_lz_offset = ctx->upcoming_lz_offset;
515 ctx->prev_delta_offset = ctx->upcoming_delta_offset;
516 ctx->prev_delta_power = ctx->upcoming_delta_power;
519 /* Encode a literal byte. */
521 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
523 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
524 ctx->cur_window_pos, literal, literal);
526 lzms_begin_encode_item(ctx);
528 /* Main bit: 0 = a literal, not a match. */
529 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
531 /* Encode the literal using the current literal Huffman code. */
532 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
534 lzms_end_encode_item(ctx, 1);
537 /* Encode a (length, offset) pair (LZ match). */
539 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
541 int recent_offset_idx;
543 lzms_begin_encode_item(ctx);
545 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
546 ctx->cur_window_pos, length, offset);
548 /* Main bit: 1 = a match, not a literal. */
549 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
551 /* Match bit: 0 = a LZ match, not a delta match. */
552 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
554 /* Determine if the offset can be represented as a recent offset. */
555 for (recent_offset_idx = 0;
556 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
558 if (offset == ctx->recent_lz_offsets[recent_offset_idx])
561 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
562 /* Explicit offset. */
564 /* LZ match bit: 0 = explicit offset, not a repeat offset. */
565 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
567 /* Encode the match offset. */
568 lzms_encode_value(&ctx->lz_offset_encoder, offset);
574 /* LZ match bit: 1 = repeat offset, not an explicit offset. */
575 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
577 /* Encode the recent offset index. A 1 bit is encoded for each
578 * index passed up. This sequence of 1 bits is terminated by a
579 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
580 * bits have been encoded. */
581 for (i = 0; i < recent_offset_idx; i++)
582 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
584 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
585 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
587 /* Initial update of the LZ match offset LRU queue. */
588 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
589 ctx->recent_lz_offsets[i] = ctx->recent_lz_offsets[i + 1];
592 /* Encode the match length. */
593 lzms_encode_value(&ctx->length_encoder, length);
595 /* Save the match offset for later insertion at the front of the LZ
596 * match offset LRU queue. */
597 ctx->upcoming_lz_offset = offset;
599 lzms_end_encode_item(ctx, length);
603 lzms_record_literal(u8 literal, void *_ctx)
605 struct lzms_compressor *ctx = _ctx;
607 lzms_encode_literal(ctx, literal);
611 lzms_record_match(unsigned length, unsigned offset, void *_ctx)
613 struct lzms_compressor *ctx = _ctx;
615 lzms_encode_lz_match(ctx, length, offset);
619 lzms_fast_encode(struct lzms_compressor *ctx)
621 static const struct lz_params lzms_lz_params = {
623 .max_match = UINT_MAX,
624 .max_offset = UINT_MAX,
628 .max_lazy_match = 258,
632 lz_analyze_block(ctx->window,
644 static struct lzms_match
645 lzms_get_best_match(struct lzms_compressor *ctx)
647 struct lzms_match match;
657 lzms_slow_encode(struct lzms_compressor *ctx)
659 struct lzms_match match;
662 while (ctx->cur_window_pos != ctx->window_size) {
663 match = lzms_get_best_match(ctx);
664 if (match.length == 0) {
666 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
669 lzms_encode_lz_match(ctx, match.length, match.offset);
676 lzms_init_range_encoder(struct lzms_range_encoder *enc,
677 struct lzms_range_encoder_raw *rc, u32 num_states)
681 enc->mask = num_states - 1;
682 for (u32 i = 0; i < num_states; i++) {
683 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
684 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
689 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
690 struct lzms_output_bitstream *os,
691 const u32 *slot_base_tab,
693 unsigned rebuild_freq)
696 enc->slot_base_tab = slot_base_tab;
697 enc->num_syms_written = rebuild_freq;
698 enc->rebuild_freq = rebuild_freq;
699 enc->num_syms = num_syms;
700 for (unsigned i = 0; i < num_syms; i++)
701 enc->sym_freqs[i] = 1;
704 /* Initialize the LZMS compressor. */
706 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
707 le16 *cdata, u32 clen16)
709 unsigned num_position_slots;
711 /* Copy the uncompressed data into the @ctx->window buffer. */
712 memcpy(ctx->window, udata, ulen);
713 memset(&ctx->window[ulen], 0, 8);
714 ctx->cur_window_pos = 0;
715 ctx->window_size = ulen;
717 /* Initialize the raw range encoder (writing forwards). */
718 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
720 /* Initialize the output bitstream for Huffman symbols and verbatim bits
721 * (writing backwards). */
722 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
724 /* Initialize position and length slot bases if not done already. */
725 lzms_init_slot_bases();
727 /* Calculate the number of position slots needed for this compressed
729 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
731 LZMS_DEBUG("Using %u position slots", num_position_slots);
733 /* Initialize Huffman encoders for each alphabet used in the compressed
735 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
736 NULL, LZMS_NUM_LITERAL_SYMS,
737 LZMS_LITERAL_CODE_REBUILD_FREQ);
739 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
740 lzms_position_slot_base, num_position_slots,
741 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
743 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
744 lzms_length_slot_base, LZMS_NUM_LEN_SYMS,
745 LZMS_LENGTH_CODE_REBUILD_FREQ);
747 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
748 lzms_position_slot_base, num_position_slots,
749 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
751 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
752 NULL, LZMS_NUM_DELTA_POWER_SYMS,
753 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
755 /* Initialize range encoders, all of which wrap around the same
756 * lzms_range_encoder_raw. */
757 lzms_init_range_encoder(&ctx->main_range_encoder,
758 &ctx->rc, LZMS_NUM_MAIN_STATES);
760 lzms_init_range_encoder(&ctx->match_range_encoder,
761 &ctx->rc, LZMS_NUM_MATCH_STATES);
763 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
764 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
766 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
767 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
768 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
770 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
771 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
773 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
774 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
775 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
777 /* Initialize the LRU queue for recent match offsets. */
778 for (size_t i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++)
779 ctx->recent_lz_offsets[i] = i + 1;
781 for (size_t i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++) {
782 ctx->recent_delta_powers[i] = 0;
783 ctx->recent_delta_offsets[i] = i + 1;
785 ctx->prev_lz_offset = 0;
786 ctx->prev_delta_offset = 0;
787 ctx->prev_delta_power = 0;
788 ctx->upcoming_lz_offset = 0;
789 ctx->upcoming_delta_offset = 0;
790 ctx->upcoming_delta_power = 0;
793 /* Flush the output streams, prepare the final compressed data, and return its
796 * A return value of 0 indicates that the data could not be compressed to fit in
797 * the available space. */
799 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
801 size_t num_forwards_bytes;
802 size_t num_backwards_bytes;
803 size_t compressed_size;
805 /* Flush both the forwards and backwards streams, and make sure they
806 * didn't cross each other and start overwriting each other's data. */
807 if (!lzms_output_bitstream_flush(&ctx->os)) {
808 LZMS_DEBUG("Backwards bitstream overrun.");
812 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
813 LZMS_DEBUG("Forwards bitstream overrun.");
817 if (ctx->rc.out > ctx->os.out) {
818 LZMS_DEBUG("Two bitstreams crossed.");
822 /* Now the compressed buffer contains the data output by the forwards
823 * bitstream, then empty space, then data output by the backwards
824 * bitstream. Move the data output by the forwards bitstream to be
825 * adjacent to the data output by the backwards bitstream, and calculate
826 * the compressed size that this results in. */
827 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
828 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
830 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
832 compressed_size = num_forwards_bytes + num_backwards_bytes;
833 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
834 "compressed_size=%zu",
835 num_forwards_bytes, num_backwards_bytes, compressed_size);
836 LZMS_ASSERT(!(compressed_size & 1));
837 return compressed_size;
841 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
842 void *compressed_data, size_t compressed_size_avail, void *_ctx)
844 struct lzms_compressor *ctx = _ctx;
845 size_t compressed_size;
847 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
848 uncompressed_size, compressed_size_avail);
850 /* Make sure the uncompressed size is compatible with this compressor.
852 if (uncompressed_size > ctx->max_block_size) {
853 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
854 "only supports %u bytes",
855 uncompressed_size, ctx->max_block_size);
859 /* Don't bother compressing extremely small inputs. */
860 if (uncompressed_size < 4)
863 /* Cap the available compressed size to a 32-bit integer, and round it
864 * down to the nearest multiple of 2. */
865 if (compressed_size_avail > UINT32_MAX)
866 compressed_size_avail = UINT32_MAX;
867 if (compressed_size_avail & 1)
868 compressed_size_avail--;
870 /* Initialize the compressor structures. */
871 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
872 compressed_data, compressed_size_avail / 2);
874 /* Preprocess the uncompressed data. */
875 lzms_x86_filter(ctx->window, ctx->window_size,
876 ctx->last_target_usages, false);
878 /* Determine and output a literal/match sequence that decompresses to
879 * the preprocessed data. */
880 lzms_fast_encode(ctx);
882 /* Get and return the compressed data size. */
883 compressed_size = lzms_finalize(ctx, compressed_data,
884 compressed_size_avail);
886 if (compressed_size == 0) {
887 LZMS_DEBUG("Data did not compress to requested size or less.");
891 LZMS_DEBUG("Compressed %zu => %zu bytes",
892 uncompressed_size, compressed_size);
894 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
895 /* Verify that we really get the same thing back when decompressing. */
897 struct wimlib_decompressor *decompressor;
899 LZMS_DEBUG("Verifying LZMS compression.");
901 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
907 ret = wimlib_decompress(compressed_data,
912 wimlib_free_decompressor(decompressor);
915 ERROR("Failed to decompress data we "
916 "compressed using LZMS algorithm");
920 if (memcmp(uncompressed_data, ctx->window,
923 ERROR("Data we compressed using LZMS algorithm "
924 "didn't decompress to original");
929 WARNING("Failed to create decompressor for "
930 "data verification!");
933 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION */
935 return compressed_size;
939 lzms_free_compressor(void *_ctx)
941 struct lzms_compressor *ctx = _ctx;
951 lzms_create_compressor(size_t max_block_size,
952 const struct wimlib_compressor_params_header *params,
955 struct lzms_compressor *ctx;
957 if (max_block_size == 0 || max_block_size >= INT32_MAX) {
958 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
959 return WIMLIB_ERR_INVALID_PARAM;
962 ctx = CALLOC(1, sizeof(struct lzms_compressor));
966 ctx->window = MALLOC(max_block_size + 8);
967 if (ctx->window == NULL)
970 ctx->prev_tab = MALLOC(max_block_size * sizeof(ctx->prev_tab[0]));
971 if (ctx->prev_tab == NULL)
974 ctx->max_block_size = max_block_size;
980 lzms_free_compressor(ctx);
981 return WIMLIB_ERR_NOMEM;
984 const struct compressor_ops lzms_compressor_ops = {
985 .create_compressor = lzms_create_compressor,
986 .compress = lzms_compress,
987 .free_compressor = lzms_free_compressor,