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"
51 #define LZMS_OPTIM_ARRAY_SIZE 1024
53 struct lzms_compressor;
54 struct lzms_adaptive_state {
55 struct lzms_lz_lru_queues lru;
59 u8 lz_repeat_match_state[LZMS_NUM_RECENT_OFFSETS - 1];
61 #define LZ_ADAPTIVE_STATE struct lzms_adaptive_state
62 #define LZ_COMPRESSOR struct lzms_compressor
63 #include "wimlib/lz_optimal.h"
65 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
66 * a series of 16-bit little endian coding units. */
67 struct lzms_output_bitstream {
68 /* Buffer variable containing zero or more bits that have been logically
69 * written to the bitstream but not yet written to memory. This must be
70 * at least as large as the coding unit size. */
73 /* Number of bits in @bitbuf that are valid. */
74 unsigned num_free_bits;
76 /* Pointer to one past the next position in the compressed data buffer
77 * at which to output a 16-bit coding unit. */
80 /* Maximum number of 16-bit coding units that can still be output to
81 * the compressed data buffer. */
82 size_t num_le16_remaining;
84 /* Set to %true if not all coding units could be output due to
85 * insufficient space. */
89 /* Stucture used for range encoding (raw version). */
90 struct lzms_range_encoder_raw {
92 /* A 33-bit variable that holds the low boundary of the current range.
93 * The 33rd bit is needed to catch carries. */
96 /* Size of the current range. */
99 /* Next 16-bit coding unit to output. */
102 /* Number of 16-bit coding units whose output has been delayed due to
103 * possible carrying. The first such coding unit is @cache; all
104 * subsequent such coding units are 0xffff. */
107 /* Pointer to the next position in the compressed data buffer at which
108 * to output a 16-bit coding unit. */
111 /* Maximum number of 16-bit coding units that can still be output to
112 * the compressed data buffer. */
113 size_t num_le16_remaining;
115 /* %true when the very first coding unit has not yet been output. */
118 /* Set to %true if not all coding units could be output due to
119 * insufficient space. */
123 /* Structure used for range encoding. This wraps around `struct
124 * lzms_range_encoder_raw' to use and maintain probability entries. */
125 struct lzms_range_encoder {
126 /* Pointer to the raw range encoder, which has no persistent knowledge
127 * of probabilities. Multiple lzms_range_encoder's share the same
128 * lzms_range_encoder_raw. */
129 struct lzms_range_encoder_raw *rc;
131 /* Bits recently encoded by this range encoder. This are used as in
132 * index into @prob_entries. */
135 /* Bitmask for @state to prevent its value from exceeding the number of
136 * probability entries. */
139 /* Probability entries being used for this range encoder. */
140 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
143 /* Structure used for Huffman encoding, optionally encoding larger "values" as a
144 * Huffman symbol specifying a slot and a slot-dependent number of extra bits.
146 struct lzms_huffman_encoder {
148 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
149 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
151 struct lzms_output_bitstream *os;
153 /* Pointer to the slot base table to use. */
154 const u32 *slot_base_tab;
156 /* Number of symbols that have been written using this code far. Reset
157 * to 0 whenever the code is rebuilt. */
158 u32 num_syms_written;
160 /* When @num_syms_written reaches this number, the Huffman code must be
164 /* Number of symbols in the represented Huffman code. */
167 /* Running totals of symbol frequencies. These are diluted slightly
168 * whenever the code is rebuilt. */
169 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
171 /* The length, in bits, of each symbol in the Huffman code. */
172 u8 lens[LZMS_MAX_NUM_SYMS];
174 /* The codeword of each symbol in the Huffman code. */
175 u16 codewords[LZMS_MAX_NUM_SYMS];
178 /* State of the LZMS compressor. */
179 struct lzms_compressor {
180 /* Pointer to a buffer holding the preprocessed data to compress. */
183 /* Current position in @buffer. */
186 /* Size of the data in @buffer. */
190 /* Temporary array used by lz_analyze_block(); must be at least as long
195 /* Suffix array match-finder. */
196 struct lz_sarray lz_sarray;
198 struct raw_match matches[64];
201 struct lz_match_chooser mc;
203 /* Maximum block size this compressor instantiation allows. This is the
204 * allocated size of @window. */
207 /* Raw range encoder which outputs to the beginning of the compressed
208 * data buffer, proceeding forwards. */
209 struct lzms_range_encoder_raw rc;
211 /* Bitstream which outputs to the end of the compressed data buffer,
212 * proceeding backwards. */
213 struct lzms_output_bitstream os;
215 /* Range encoders. */
216 struct lzms_range_encoder main_range_encoder;
217 struct lzms_range_encoder match_range_encoder;
218 struct lzms_range_encoder lz_match_range_encoder;
219 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
220 struct lzms_range_encoder delta_match_range_encoder;
221 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
223 /* Huffman encoders. */
224 struct lzms_huffman_encoder literal_encoder;
225 struct lzms_huffman_encoder lz_offset_encoder;
226 struct lzms_huffman_encoder length_encoder;
227 struct lzms_huffman_encoder delta_power_encoder;
228 struct lzms_huffman_encoder delta_offset_encoder;
230 /* LRU (least-recently-used) queues for match information. */
231 struct lzms_lru_queues lru;
233 /* Used for preprocessing. */
234 s32 last_target_usages[65536];
237 /* Initialize the output bitstream @os to write forwards to the specified
238 * compressed data buffer @out that is @out_limit 16-bit integers long. */
240 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
241 le16 *out, size_t out_limit)
244 os->num_free_bits = 16;
245 os->out = out + out_limit;
246 os->num_le16_remaining = out_limit;
250 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
251 * from high-order to low-order), to the output bitstream @os. */
253 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
254 u32 bits, unsigned num_bits)
256 bits &= (1U << num_bits) - 1;
258 while (num_bits > os->num_free_bits) {
260 if (unlikely(os->num_le16_remaining == 0)) {
265 unsigned num_fill_bits = os->num_free_bits;
267 os->bitbuf <<= num_fill_bits;
268 os->bitbuf |= bits >> (num_bits - num_fill_bits);
270 *--os->out = cpu_to_le16(os->bitbuf);
271 --os->num_le16_remaining;
273 os->num_free_bits = 16;
274 num_bits -= num_fill_bits;
275 bits &= (1U << num_bits) - 1;
277 os->bitbuf <<= num_bits;
279 os->num_free_bits -= num_bits;
282 /* Flush the output bitstream, ensuring that all bits written to it have been
283 * written to memory. Returns %true if all bits were output successfully, or
284 * %false if an overrun occurred. */
286 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
288 if (os->num_free_bits != 16)
289 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
293 /* Initialize the range encoder @rc to write forwards to the specified
294 * compressed data buffer @out that is @out_limit 16-bit integers long. */
296 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
297 le16 *out, size_t out_limit)
300 rc->range = 0xffffffff;
304 rc->num_le16_remaining = out_limit;
310 * Attempt to flush bits from the range encoder.
312 * Note: this is based on the public domain code for LZMA written by Igor
313 * Pavlov. The only differences in this function are that in LZMS the bits must
314 * be output in 16-bit coding units instead of 8-bit coding units, and that in
315 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
316 * cannot output a dummy value to that position.
318 * The basic idea is that we're writing bits from @rc->low to the output.
319 * However, due to carrying, the writing of coding units with value 0xffff, as
320 * well as one prior coding unit, must be delayed until it is determined whether
324 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
326 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
327 rc->low, rc->cache, rc->cache_size);
328 if ((u32)(rc->low) < 0xffff0000 ||
329 (u32)(rc->low >> 32) != 0)
331 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
332 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
335 if (rc->num_le16_remaining == 0) {
339 *rc->out++ = cpu_to_le16(rc->cache +
340 (u16)(rc->low >> 32));
341 --rc->num_le16_remaining;
347 } while (--rc->cache_size != 0);
349 rc->cache = (rc->low >> 16) & 0xffff;
352 rc->low = (rc->low & 0xffff) << 16;
356 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
358 if (rc->range <= 0xffff) {
360 lzms_range_encoder_raw_shift_low(rc);
365 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
367 for (unsigned i = 0; i < 4; i++)
368 lzms_range_encoder_raw_shift_low(rc);
372 /* Encode the next bit using the range encoder (raw version).
374 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
376 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
379 lzms_range_encoder_raw_normalize(rc);
381 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
390 /* Encode a bit using the specified range encoder. This wraps around
391 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
392 * appropriate probability table. */
394 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
396 struct lzms_probability_entry *prob_entry;
399 /* Load the probability entry corresponding to the current state. */
400 prob_entry = &enc->prob_entries[enc->state];
402 /* Treat the number of zero bits in the most recently encoded
403 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
404 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
405 * don't allow 0% or 100% probabilities. */
406 prob = prob_entry->num_recent_zero_bits;
409 else if (prob == LZMS_PROBABILITY_MAX)
410 prob = LZMS_PROBABILITY_MAX - 1;
412 /* Encode the next bit. */
413 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
415 /* Update the state based on the newly encoded bit. */
416 enc->state = ((enc->state << 1) | bit) & enc->mask;
418 /* Update the recent bits, including the cached count of 0's. */
419 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
421 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
422 /* Replacing 1 bit with 0 bit; increment the zero count.
424 prob_entry->num_recent_zero_bits++;
427 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
428 /* Replacing 0 bit with 1 bit; decrement the zero count.
430 prob_entry->num_recent_zero_bits--;
433 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
436 /* Encode a symbol using the specified Huffman encoder. */
438 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
440 LZMS_ASSERT(sym < enc->num_syms);
441 lzms_output_bitstream_put_bits(enc->os,
444 ++enc->sym_freqs[sym];
445 if (++enc->num_syms_written == enc->rebuild_freq) {
446 /* Adaptive code needs to be rebuilt. */
447 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
448 make_canonical_huffman_code(enc->num_syms,
449 LZMS_MAX_CODEWORD_LEN,
454 /* Dilute the frequencies. */
455 for (unsigned i = 0; i < enc->num_syms; i++) {
456 enc->sym_freqs[i] >>= 1;
457 enc->sym_freqs[i] += 1;
459 enc->num_syms_written = 0;
463 /* Encode a number as a Huffman symbol specifying a slot, plus a number of
464 * slot-dependent extra bits. */
466 lzms_encode_value(struct lzms_huffman_encoder *enc, u32 value)
469 unsigned num_extra_bits;
472 LZMS_ASSERT(enc->slot_base_tab != NULL);
474 slot = lzms_get_slot(value, enc->slot_base_tab, enc->num_syms);
476 /* Get the number of extra bits needed to represent the range of values
477 * that share the slot. */
478 num_extra_bits = bsr32(enc->slot_base_tab[slot + 1] -
479 enc->slot_base_tab[slot]);
481 /* Calculate the extra bits as the offset from the slot base. */
482 extra_bits = value - enc->slot_base_tab[slot];
484 /* Output the slot (Huffman-encoded), then the extra bits (verbatim).
486 lzms_huffman_encode_symbol(enc, slot);
487 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
491 lzms_begin_encode_item(struct lzms_compressor *ctx)
493 ctx->lru.lz.upcoming_offset = 0;
494 ctx->lru.delta.upcoming_offset = 0;
495 ctx->lru.delta.upcoming_power = 0;
499 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
501 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
502 ctx->cur_window_pos += length;
503 lzms_update_lru_queues(&ctx->lru);
506 /* Encode a literal byte. */
508 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
510 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
511 ctx->cur_window_pos, literal, literal);
513 lzms_begin_encode_item(ctx);
515 /* Main bit: 0 = a literal, not a match. */
516 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
518 /* Encode the literal using the current literal Huffman code. */
519 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
521 lzms_end_encode_item(ctx, 1);
524 /* Encode a (length, offset) pair (LZ match). */
526 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
528 int recent_offset_idx;
530 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
531 ctx->cur_window_pos, length, offset);
533 LZMS_ASSERT(length <= ctx->window_size - ctx->cur_window_pos);
534 LZMS_ASSERT(offset <= ctx->cur_window_pos);
535 LZMS_ASSERT(!memcmp(&ctx->window[ctx->cur_window_pos],
536 &ctx->window[ctx->cur_window_pos - offset],
539 lzms_begin_encode_item(ctx);
541 /* Main bit: 1 = a match, not a literal. */
542 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
544 /* Match bit: 0 = a LZ match, not a delta match. */
545 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
547 /* Determine if the offset can be represented as a recent offset. */
548 for (recent_offset_idx = 0;
549 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
551 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
554 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
555 /* Explicit offset. */
557 /* LZ match bit: 0 = explicit offset, not a recent offset. */
558 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
560 /* Encode the match offset. */
561 lzms_encode_value(&ctx->lz_offset_encoder, offset);
567 /* LZ match bit: 1 = recent offset, not an explicit offset. */
568 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
570 /* Encode the recent offset index. A 1 bit is encoded for each
571 * index passed up. This sequence of 1 bits is terminated by a
572 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
573 * bits have been encoded. */
574 for (i = 0; i < recent_offset_idx; i++)
575 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
577 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
578 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
580 /* Initial update of the LZ match offset LRU queue. */
581 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
582 ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
585 /* Encode the match length. */
586 lzms_encode_value(&ctx->length_encoder, length);
588 /* Save the match offset for later insertion at the front of the LZ
589 * match offset LRU queue. */
590 ctx->lru.lz.upcoming_offset = offset;
592 lzms_end_encode_item(ctx, length);
597 lzms_record_literal(u8 literal, void *_ctx)
599 struct lzms_compressor *ctx = _ctx;
601 lzms_encode_literal(ctx, literal);
605 lzms_record_match(unsigned length, unsigned offset, void *_ctx)
607 struct lzms_compressor *ctx = _ctx;
609 lzms_encode_lz_match(ctx, length, offset);
613 lzms_fast_encode(struct lzms_compressor *ctx)
615 static const struct lz_params lzms_lz_params = {
617 .max_match = UINT_MAX,
618 .max_offset = UINT_MAX,
622 .max_lazy_match = 258,
626 lz_analyze_block(ctx->window,
637 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
638 * Unlike lzms_get_lz_match_cost(), which does a true cost evaluation, this
639 * simply prioritize matches based on their offset. */
641 lzms_lz_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_lru)
643 const struct lzms_lz_lru_queues *lru = _lru;
645 for (input_idx_t i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++)
646 if (offset == lru->recent_offsets[i])
652 #define LZMS_COST_SHIFT 5
654 /*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
657 lzms_rc_costs[LZMS_PROBABILITY_MAX];
659 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
664 lzms_do_init_rc_costs(void)
666 /* Fill in a table that maps range coding probabilities needed to code a
667 * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
668 * handle fractional costs) needed to code that bit X.
670 * Consider the range of the range decoder. To eliminate exactly half
671 * the range (logical probability of 0.5), we need exactly 1 bit. For
672 * lower probabilities we need more bits and for higher probabilities we
673 * need fewer bits. In general, a logical probability of N will
674 * eliminate the proportion 1 - N of the range; this information takes
675 * log2(1 / N) bits to encode.
677 * The below loop is simply calculating this number of bits for each
678 * possible probability allowed by the LZMS compression format, but
679 * without using real numbers. To handle fractional probabilities, each
680 * cost is multiplied by (1 << LZMS_COST_SHIFT). These techniques are
681 * based on those used by LZMA.
683 * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
684 * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
687 for (u32 i = 0; i < LZMS_PROBABILITY_MAX; i++) {
692 else if (prob == LZMS_PROBABILITY_MAX)
693 prob = LZMS_PROBABILITY_MAX - 1;
695 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
696 lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
697 (1 << LZMS_COST_SHIFT);
701 for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
704 while (w >= (1U << 16)) {
709 lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
716 lzms_init_rc_costs(void)
718 static bool done = false;
719 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
722 pthread_mutex_lock(&mutex);
724 lzms_do_init_rc_costs();
727 pthread_mutex_unlock(&mutex);
732 * Return the cost to range-encode the specified bit when in the specified
735 * @enc The range encoder to use.
736 * @cur_state Current state, which indicates the probability entry to choose.
737 * Updated by this function.
738 * @bit The bit to encode (0 or 1).
741 lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 *cur_state, int bit)
746 prob_zero = enc->prob_entries[*cur_state & enc->mask].num_recent_zero_bits;
748 *cur_state = (*cur_state << 1) | bit;
752 else if (prob_zero == LZMS_PROBABILITY_MAX)
753 prob_zero = LZMS_PROBABILITY_MAX - 1;
756 prob_correct = prob_zero;
758 prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
760 return lzms_rc_costs[prob_correct];
764 lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, u32 sym)
766 return enc->lens[sym] << LZMS_COST_SHIFT;
769 /* Compute the cost to encode a number with lzms_encode_value(). */
771 lzms_value_cost(const struct lzms_huffman_encoder *enc, u32 value)
777 slot = lzms_get_slot(value, enc->slot_base_tab, enc->num_syms);
779 cost += lzms_huffman_symbol_cost(enc, slot);
781 num_extra_bits = bsr32(enc->slot_base_tab[slot + 1] -
782 enc->slot_base_tab[slot]);
784 cost += num_extra_bits << LZMS_COST_SHIFT;
790 lzms_get_matches(struct lzms_compressor *ctx,
791 const struct lzms_adaptive_state *state,
792 struct raw_match **matches_ret)
795 struct raw_match *matches = ctx->matches;
797 num_matches = lz_sarray_get_matches(&ctx->lz_sarray,
799 lzms_lz_match_cost_fast,
802 fprintf(stderr, "Pos %u: %u matches\n",
803 lz_sarray_get_pos(&ctx->lz_sarray) - 1, num_matches);
804 for (u32 i = 0; i < num_matches; i++)
805 fprintf(stderr, "\tLen %u Offset %u\n", matches[i].len, matches[i].offset);
808 #ifdef ENABLE_LZMS_DEBUG
809 LZMS_ASSERT(lz_sarray_get_pos(&ctx->lz_sarray) > 0);
810 u32 curpos = lz_sarray_get_pos(&ctx->lz_sarray) - 1;
811 for (u32 i = 0; i < num_matches; i++) {
812 LZMS_ASSERT(matches[i].len <= ctx->window_size - curpos);
813 LZMS_ASSERT(matches[i].offset > 0);
814 LZMS_ASSERT(matches[i].offset <= curpos);
815 LZMS_ASSERT(!memcmp(&ctx->window[curpos],
816 &ctx->window[curpos - matches[i].offset],
818 if (i < num_matches - 1)
819 LZMS_ASSERT(matches[i].len > matches[i + 1].len);
823 *matches_ret = matches;
828 lzms_skip_bytes(struct lzms_compressor *ctx, input_idx_t n)
831 lz_sarray_skip_position(&ctx->lz_sarray);
835 lzms_get_prev_literal_cost(struct lzms_compressor *ctx,
836 struct lzms_adaptive_state *state)
838 u8 literal = ctx->window[lz_sarray_get_pos(&ctx->lz_sarray) - 1];
841 state->lru.upcoming_offset = 0;
842 lzms_update_lz_lru_queues(&state->lru);
844 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
845 &state->main_state, 0);
847 cost += lzms_huffman_symbol_cost(&ctx->literal_encoder, literal);
853 lzms_get_lz_match_cost(struct lzms_compressor *ctx,
854 struct lzms_adaptive_state *state,
855 input_idx_t length, input_idx_t offset)
858 int recent_offset_idx;
860 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
861 &state->main_state, 1);
862 cost += lzms_rc_bit_cost(&ctx->match_range_encoder,
863 &state->match_state, 0);
865 for (recent_offset_idx = 0;
866 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
868 if (offset == state->lru.recent_offsets[recent_offset_idx])
871 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
872 /* Explicit offset. */
873 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
874 &state->lz_match_state, 0);
876 cost += lzms_value_cost(&ctx->lz_offset_encoder, offset);
881 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
882 &state->lz_match_state, 1);
884 for (i = 0; i < recent_offset_idx; i++)
885 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
886 &state->lz_repeat_match_state[i], 0);
888 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
889 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
890 &state->lz_repeat_match_state[i], 1);
893 /* Initial update of the LZ match offset LRU queue. */
894 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
895 state->lru.recent_offsets[i] = state->lru.recent_offsets[i + 1];
898 cost += lzms_value_cost(&ctx->length_encoder, length);
900 state->lru.upcoming_offset = offset;
901 lzms_update_lz_lru_queues(&state->lru);
906 static struct raw_match
907 lzms_get_near_optimal_match(struct lzms_compressor *ctx)
909 struct lzms_adaptive_state initial_state;
911 initial_state.lru = ctx->lru.lz;
912 initial_state.main_state = ctx->main_range_encoder.state;
913 initial_state.match_state = ctx->match_range_encoder.state;
914 initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
915 for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
916 initial_state.lz_repeat_match_state[i] =
917 ctx->lz_repeat_match_range_encoders[i].state;
918 return lz_get_near_optimal_match(&ctx->mc,
921 lzms_get_prev_literal_cost,
922 lzms_get_lz_match_cost,
928 * The main loop for the LZMS compressor.
932 * - This uses near-optimal LZ parsing backed by a suffix-array match-finder.
933 * More details can be found in the corresponding files (lz_optimal.h,
936 * - This does not output any delta matches. It would take a specialized
937 * algorithm to find them, then more code in lz_optimal.h and here to handle
938 * evaluating and outputting them.
940 * - The costs of literals and matches are estimated using the range encoder
941 * states and the semi-adaptive Huffman codes. Except for range encoding
942 * states, costs are assumed to be constant throughout a single run of the
943 * parsing algorithm, which can parse up to LZMS_OPTIM_ARRAY_SIZE bytes of
944 * data. This introduces a source of inaccuracy because the probabilities and
945 * Huffman codes can change over this part of the data.
948 lzms_normal_encode(struct lzms_compressor *ctx)
950 struct raw_match match;
952 /* Load window into suffix array match-finder. */
953 lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
955 /* Reset the match-chooser. */
956 lz_match_chooser_begin(&ctx->mc);
958 while (ctx->cur_window_pos != ctx->window_size) {
959 match = lzms_get_near_optimal_match(ctx);
961 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
963 lzms_encode_lz_match(ctx, match.len, match.offset);
968 lzms_init_range_encoder(struct lzms_range_encoder *enc,
969 struct lzms_range_encoder_raw *rc, u32 num_states)
973 enc->mask = num_states - 1;
974 for (u32 i = 0; i < num_states; i++) {
975 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
976 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
981 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
982 struct lzms_output_bitstream *os,
983 const u32 *slot_base_tab,
985 unsigned rebuild_freq)
988 enc->slot_base_tab = slot_base_tab;
989 enc->num_syms_written = 0;
990 enc->rebuild_freq = rebuild_freq;
991 enc->num_syms = num_syms;
992 for (unsigned i = 0; i < num_syms; i++)
993 enc->sym_freqs[i] = 1;
995 make_canonical_huffman_code(enc->num_syms,
996 LZMS_MAX_CODEWORD_LEN,
1002 /* Initialize the LZMS compressor. */
1004 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
1005 le16 *cdata, u32 clen16)
1007 unsigned num_position_slots;
1009 /* Copy the uncompressed data into the @ctx->window buffer. */
1010 memcpy(ctx->window, udata, ulen);
1011 memset(&ctx->window[ulen], 0, 8);
1012 ctx->cur_window_pos = 0;
1013 ctx->window_size = ulen;
1015 /* Initialize the raw range encoder (writing forwards). */
1016 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
1018 /* Initialize the output bitstream for Huffman symbols and verbatim bits
1019 * (writing backwards). */
1020 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
1022 /* Calculate the number of position slots needed for this compressed
1024 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
1026 LZMS_DEBUG("Using %u position slots", num_position_slots);
1028 /* Initialize Huffman encoders for each alphabet used in the compressed
1029 * representation. */
1030 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
1031 NULL, LZMS_NUM_LITERAL_SYMS,
1032 LZMS_LITERAL_CODE_REBUILD_FREQ);
1034 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
1035 lzms_position_slot_base, num_position_slots,
1036 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
1038 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
1039 lzms_length_slot_base, LZMS_NUM_LEN_SYMS,
1040 LZMS_LENGTH_CODE_REBUILD_FREQ);
1042 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
1043 lzms_position_slot_base, num_position_slots,
1044 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
1046 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
1047 NULL, LZMS_NUM_DELTA_POWER_SYMS,
1048 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
1050 /* Initialize range encoders, all of which wrap around the same
1051 * lzms_range_encoder_raw. */
1052 lzms_init_range_encoder(&ctx->main_range_encoder,
1053 &ctx->rc, LZMS_NUM_MAIN_STATES);
1055 lzms_init_range_encoder(&ctx->match_range_encoder,
1056 &ctx->rc, LZMS_NUM_MATCH_STATES);
1058 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
1059 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
1061 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
1062 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
1063 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
1065 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
1066 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
1068 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
1069 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
1070 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1072 /* Initialize LRU match information. */
1073 lzms_init_lru_queues(&ctx->lru);
1076 /* Flush the output streams, prepare the final compressed data, and return its
1079 * A return value of 0 indicates that the data could not be compressed to fit in
1080 * the available space. */
1082 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
1084 size_t num_forwards_bytes;
1085 size_t num_backwards_bytes;
1086 size_t compressed_size;
1088 /* Flush both the forwards and backwards streams, and make sure they
1089 * didn't cross each other and start overwriting each other's data. */
1090 if (!lzms_output_bitstream_flush(&ctx->os)) {
1091 LZMS_DEBUG("Backwards bitstream overrun.");
1095 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
1096 LZMS_DEBUG("Forwards bitstream overrun.");
1100 if (ctx->rc.out > ctx->os.out) {
1101 LZMS_DEBUG("Two bitstreams crossed.");
1105 /* Now the compressed buffer contains the data output by the forwards
1106 * bitstream, then empty space, then data output by the backwards
1107 * bitstream. Move the data output by the backwards bitstream to be
1108 * adjacent to the data output by the forward bitstream, and calculate
1109 * the compressed size that this results in. */
1110 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
1111 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
1113 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
1115 compressed_size = num_forwards_bytes + num_backwards_bytes;
1116 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
1117 "compressed_size=%zu",
1118 num_forwards_bytes, num_backwards_bytes, compressed_size);
1119 LZMS_ASSERT(compressed_size % 2 == 0);
1120 return compressed_size;
1124 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
1125 void *compressed_data, size_t compressed_size_avail, void *_ctx)
1127 struct lzms_compressor *ctx = _ctx;
1128 size_t compressed_size;
1130 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
1131 uncompressed_size, compressed_size_avail);
1133 /* Make sure the uncompressed size is compatible with this compressor.
1135 if (uncompressed_size > ctx->max_block_size) {
1136 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
1137 "only supports %u bytes",
1138 uncompressed_size, ctx->max_block_size);
1142 /* Don't bother compressing extremely small inputs. */
1143 if (uncompressed_size < 4) {
1144 LZMS_DEBUG("Input too small to bother compressing.");
1148 /* Cap the available compressed size to a 32-bit integer and round it
1149 * down to the nearest multiple of 2. */
1150 if (compressed_size_avail > UINT32_MAX)
1151 compressed_size_avail = UINT32_MAX;
1152 if (compressed_size_avail & 1)
1153 compressed_size_avail--;
1155 /* Initialize the compressor structures. */
1156 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
1157 compressed_data, compressed_size_avail / 2);
1159 /* Preprocess the uncompressed data. */
1160 lzms_x86_filter(ctx->window, ctx->window_size,
1161 ctx->last_target_usages, false);
1163 /* Compute and encode a literal/match sequence that decompresses to the
1164 * preprocessed data. */
1165 lzms_normal_encode(ctx);
1167 lzms_fast_encode(ctx);
1170 /* Get and return the compressed data size. */
1171 compressed_size = lzms_finalize(ctx, compressed_data,
1172 compressed_size_avail);
1174 if (compressed_size == 0) {
1175 LZMS_DEBUG("Data did not compress to requested size or less.");
1179 LZMS_DEBUG("Compressed %zu => %zu bytes",
1180 uncompressed_size, compressed_size);
1182 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
1183 /* Verify that we really get the same thing back when decompressing. */
1185 struct wimlib_decompressor *decompressor;
1187 LZMS_DEBUG("Verifying LZMS compression.");
1189 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
1190 ctx->max_block_size,
1195 ret = wimlib_decompress(compressed_data,
1200 wimlib_free_decompressor(decompressor);
1203 ERROR("Failed to decompress data we "
1204 "compressed using LZMS algorithm");
1208 if (memcmp(uncompressed_data, ctx->window,
1211 ERROR("Data we compressed using LZMS algorithm "
1212 "didn't decompress to original");
1217 WARNING("Failed to create decompressor for "
1218 "data verification!");
1221 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION */
1223 return compressed_size;
1227 lzms_free_compressor(void *_ctx)
1229 struct lzms_compressor *ctx = _ctx;
1234 FREE(ctx->prev_tab);
1236 lz_sarray_destroy(&ctx->lz_sarray);
1237 lz_match_chooser_destroy(&ctx->mc);
1242 static const struct wimlib_lzms_compressor_params default_params = {
1243 .hdr = sizeof(struct wimlib_lzms_compressor_params),
1244 .min_match_length = 2,
1245 .max_match_length = UINT32_MAX,
1246 .nice_match_length = 32,
1247 .max_search_depth = 50,
1248 .max_matches_per_pos = 3,
1249 .optim_array_length = 1024,
1253 lzms_create_compressor(size_t max_block_size,
1254 const struct wimlib_compressor_params_header *_params,
1257 struct lzms_compressor *ctx;
1258 const struct wimlib_lzms_compressor_params *params;
1260 if (max_block_size == 0 || max_block_size >= INT32_MAX) {
1261 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
1262 return WIMLIB_ERR_INVALID_PARAM;
1266 params = (const struct wimlib_lzms_compressor_params*)_params;
1268 params = &default_params;
1270 if (params->max_match_length < params->min_match_length ||
1271 params->min_match_length < 2 ||
1272 params->optim_array_length == 0 ||
1273 min(params->max_match_length, params->nice_match_length) > 65536) {
1274 LZMS_DEBUG("Invalid compression parameter!");
1275 return WIMLIB_ERR_INVALID_PARAM;
1278 ctx = CALLOC(1, sizeof(struct lzms_compressor));
1282 ctx->window = MALLOC(max_block_size + 8);
1283 if (ctx->window == NULL)
1287 ctx->prev_tab = MALLOC(max_block_size * sizeof(ctx->prev_tab[0]));
1288 if (ctx->prev_tab == NULL)
1292 if (!lz_sarray_init(&ctx->lz_sarray, max_block_size,
1293 params->min_match_length,
1294 params->max_match_length,
1295 params->max_search_depth,
1296 params->max_matches_per_pos))
1299 if (!lz_match_chooser_init(&ctx->mc,
1300 params->optim_array_length,
1301 params->nice_match_length,
1302 params->max_match_length))
1305 /* Initialize position and length slot bases if not done already. */
1306 lzms_init_slot_bases();
1308 /* Initialize range encoding cost table if not done already. */
1309 lzms_init_rc_costs();
1311 ctx->max_block_size = max_block_size;
1317 lzms_free_compressor(ctx);
1318 return WIMLIB_ERR_NOMEM;
1321 const struct compressor_ops lzms_compressor_ops = {
1322 .create_compressor = lzms_create_compressor,
1323 .compress = lzms_compress,
1324 .free_compressor = lzms_free_compressor,