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 * NOTE: this compressor currently does not code any delta matches.
35 #include "wimlib/assert.h"
36 #include "wimlib/compiler.h"
37 #include "wimlib/compressor_ops.h"
38 #include "wimlib/compress_common.h"
39 #include "wimlib/endianness.h"
40 #include "wimlib/error.h"
41 #include "wimlib/lz_sarray.h"
42 #include "wimlib/lzms.h"
43 #include "wimlib/util.h"
49 struct lzms_compressor;
50 struct lzms_adaptive_state {
51 struct lzms_lz_lru_queues lru;
55 u8 lz_repeat_match_state[LZMS_NUM_RECENT_OFFSETS - 1];
57 #define LZ_ADAPTIVE_STATE struct lzms_adaptive_state
58 #define LZ_COMPRESSOR struct lzms_compressor
59 #include "wimlib/lz_optimal.h"
61 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
62 * a series of 16-bit little endian coding units. */
63 struct lzms_output_bitstream {
64 /* Buffer variable containing zero or more bits that have been logically
65 * written to the bitstream but not yet written to memory. This must be
66 * at least as large as the coding unit size. */
69 /* Number of bits in @bitbuf that are valid. */
70 unsigned num_free_bits;
72 /* Pointer to one past the next position in the compressed data buffer
73 * at which to output a 16-bit coding unit. */
76 /* Maximum number of 16-bit coding units that can still be output to
77 * the compressed data buffer. */
78 size_t num_le16_remaining;
80 /* Set to %true if not all coding units could be output due to
81 * insufficient space. */
85 /* Stucture used for range encoding (raw version). */
86 struct lzms_range_encoder_raw {
88 /* A 33-bit variable that holds the low boundary of the current range.
89 * The 33rd bit is needed to catch carries. */
92 /* Size of the current range. */
95 /* Next 16-bit coding unit to output. */
98 /* Number of 16-bit coding units whose output has been delayed due to
99 * possible carrying. The first such coding unit is @cache; all
100 * subsequent such coding units are 0xffff. */
103 /* Pointer to the next position in the compressed data buffer at which
104 * to output a 16-bit coding unit. */
107 /* Maximum number of 16-bit coding units that can still be output to
108 * the compressed data buffer. */
109 size_t num_le16_remaining;
111 /* %true when the very first coding unit has not yet been output. */
114 /* Set to %true if not all coding units could be output due to
115 * insufficient space. */
119 /* Structure used for range encoding. This wraps around `struct
120 * lzms_range_encoder_raw' to use and maintain probability entries. */
121 struct lzms_range_encoder {
122 /* Pointer to the raw range encoder, which has no persistent knowledge
123 * of probabilities. Multiple lzms_range_encoder's share the same
124 * lzms_range_encoder_raw. */
125 struct lzms_range_encoder_raw *rc;
127 /* Bits recently encoded by this range encoder. This is used as an
128 * index into @prob_entries. */
131 /* Bitmask for @state to prevent its value from exceeding the number of
132 * probability entries. */
135 /* Probability entries being used for this range encoder. */
136 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
139 /* Structure used for Huffman encoding. */
140 struct lzms_huffman_encoder {
142 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
143 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
145 struct lzms_output_bitstream *os;
147 /* Number of symbols that have been written using this code far. Reset
148 * to 0 whenever the code is rebuilt. */
149 u32 num_syms_written;
151 /* When @num_syms_written reaches this number, the Huffman code must be
155 /* Number of symbols in the represented Huffman code. */
158 /* Running totals of symbol frequencies. These are diluted slightly
159 * whenever the code is rebuilt. */
160 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
162 /* The length, in bits, of each symbol in the Huffman code. */
163 u8 lens[LZMS_MAX_NUM_SYMS];
165 /* The codeword of each symbol in the Huffman code. */
166 u32 codewords[LZMS_MAX_NUM_SYMS];
169 /* State of the LZMS compressor. */
170 struct lzms_compressor {
171 /* Pointer to a buffer holding the preprocessed data to compress. */
174 /* Current position in @buffer. */
177 /* Size of the data in @buffer. */
180 /* Suffix array match-finder. */
181 struct lz_sarray lz_sarray;
183 /* Temporary space to store found matches. */
184 struct raw_match *matches;
187 struct lz_match_chooser mc;
189 /* Maximum block size this compressor instantiation allows. This is the
190 * allocated size of @window. */
193 /* Raw range encoder which outputs to the beginning of the compressed
194 * data buffer, proceeding forwards. */
195 struct lzms_range_encoder_raw rc;
197 /* Bitstream which outputs to the end of the compressed data buffer,
198 * proceeding backwards. */
199 struct lzms_output_bitstream os;
201 /* Range encoders. */
202 struct lzms_range_encoder main_range_encoder;
203 struct lzms_range_encoder match_range_encoder;
204 struct lzms_range_encoder lz_match_range_encoder;
205 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
206 struct lzms_range_encoder delta_match_range_encoder;
207 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
209 /* Huffman encoders. */
210 struct lzms_huffman_encoder literal_encoder;
211 struct lzms_huffman_encoder lz_offset_encoder;
212 struct lzms_huffman_encoder length_encoder;
213 struct lzms_huffman_encoder delta_power_encoder;
214 struct lzms_huffman_encoder delta_offset_encoder;
216 /* LRU (least-recently-used) queues for match information. */
217 struct lzms_lru_queues lru;
219 /* Used for preprocessing. */
220 s32 last_target_usages[65536];
223 /* Initialize the output bitstream @os to write forwards to the specified
224 * compressed data buffer @out that is @out_limit 16-bit integers long. */
226 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
227 le16 *out, size_t out_limit)
230 os->num_free_bits = 16;
231 os->out = out + out_limit;
232 os->num_le16_remaining = out_limit;
236 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
237 * from high-order to low-order), to the output bitstream @os. */
239 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
240 u32 bits, unsigned num_bits)
242 bits &= (1U << num_bits) - 1;
244 while (num_bits > os->num_free_bits) {
246 if (unlikely(os->num_le16_remaining == 0)) {
251 unsigned num_fill_bits = os->num_free_bits;
253 os->bitbuf <<= num_fill_bits;
254 os->bitbuf |= bits >> (num_bits - num_fill_bits);
256 *--os->out = cpu_to_le16(os->bitbuf);
257 --os->num_le16_remaining;
259 os->num_free_bits = 16;
260 num_bits -= num_fill_bits;
261 bits &= (1U << num_bits) - 1;
263 os->bitbuf <<= num_bits;
265 os->num_free_bits -= num_bits;
268 /* Flush the output bitstream, ensuring that all bits written to it have been
269 * written to memory. Returns %true if all bits were output successfully, or
270 * %false if an overrun occurred. */
272 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
274 if (os->num_free_bits != 16)
275 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
279 /* Initialize the range encoder @rc to write forwards to the specified
280 * compressed data buffer @out that is @out_limit 16-bit integers long. */
282 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
283 le16 *out, size_t out_limit)
286 rc->range = 0xffffffff;
290 rc->num_le16_remaining = out_limit;
296 * Attempt to flush bits from the range encoder.
298 * Note: this is based on the public domain code for LZMA written by Igor
299 * Pavlov. The only differences in this function are that in LZMS the bits must
300 * be output in 16-bit coding units instead of 8-bit coding units, and that in
301 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
302 * cannot output a dummy value to that position.
304 * The basic idea is that we're writing bits from @rc->low to the output.
305 * However, due to carrying, the writing of coding units with value 0xffff, as
306 * well as one prior coding unit, must be delayed until it is determined whether
310 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
312 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
313 rc->low, rc->cache, rc->cache_size);
314 if ((u32)(rc->low) < 0xffff0000 ||
315 (u32)(rc->low >> 32) != 0)
317 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
318 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
321 if (rc->num_le16_remaining == 0) {
325 *rc->out++ = cpu_to_le16(rc->cache +
326 (u16)(rc->low >> 32));
327 --rc->num_le16_remaining;
333 } while (--rc->cache_size != 0);
335 rc->cache = (rc->low >> 16) & 0xffff;
338 rc->low = (rc->low & 0xffff) << 16;
342 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
344 if (rc->range <= 0xffff) {
346 lzms_range_encoder_raw_shift_low(rc);
351 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
353 for (unsigned i = 0; i < 4; i++)
354 lzms_range_encoder_raw_shift_low(rc);
358 /* Encode the next bit using the range encoder (raw version).
360 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
362 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
365 lzms_range_encoder_raw_normalize(rc);
367 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
376 /* Encode a bit using the specified range encoder. This wraps around
377 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
378 * appropriate probability table. */
380 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
382 struct lzms_probability_entry *prob_entry;
385 /* Load the probability entry corresponding to the current state. */
386 prob_entry = &enc->prob_entries[enc->state];
388 /* Treat the number of zero bits in the most recently encoded
389 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
390 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
391 * don't allow 0% or 100% probabilities. */
392 prob = prob_entry->num_recent_zero_bits;
395 else if (prob == LZMS_PROBABILITY_MAX)
396 prob = LZMS_PROBABILITY_MAX - 1;
398 /* Encode the next bit. */
399 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
401 /* Update the state based on the newly encoded bit. */
402 enc->state = ((enc->state << 1) | bit) & enc->mask;
404 /* Update the recent bits, including the cached count of 0's. */
405 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
407 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
408 /* Replacing 1 bit with 0 bit; increment the zero count.
410 prob_entry->num_recent_zero_bits++;
413 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
414 /* Replacing 0 bit with 1 bit; decrement the zero count.
416 prob_entry->num_recent_zero_bits--;
419 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
422 /* Encode a symbol using the specified Huffman encoder. */
424 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
426 LZMS_ASSERT(sym < enc->num_syms);
427 lzms_output_bitstream_put_bits(enc->os,
430 ++enc->sym_freqs[sym];
431 if (++enc->num_syms_written == enc->rebuild_freq) {
432 /* Adaptive code needs to be rebuilt. */
433 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
434 make_canonical_huffman_code(enc->num_syms,
435 LZMS_MAX_CODEWORD_LEN,
440 /* Dilute the frequencies. */
441 for (unsigned i = 0; i < enc->num_syms; i++) {
442 enc->sym_freqs[i] >>= 1;
443 enc->sym_freqs[i] += 1;
445 enc->num_syms_written = 0;
450 lzms_encode_length(struct lzms_huffman_encoder *enc, u32 length)
453 unsigned num_extra_bits;
456 slot = lzms_get_length_slot(length);
458 num_extra_bits = lzms_extra_length_bits[slot];
460 extra_bits = length - lzms_length_slot_base[slot];
462 lzms_huffman_encode_symbol(enc, slot);
463 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
467 lzms_encode_offset(struct lzms_huffman_encoder *enc, u32 offset)
470 unsigned num_extra_bits;
473 slot = lzms_get_position_slot(offset);
475 num_extra_bits = lzms_extra_position_bits[slot];
477 extra_bits = offset - lzms_position_slot_base[slot];
479 lzms_huffman_encode_symbol(enc, slot);
480 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
484 lzms_begin_encode_item(struct lzms_compressor *ctx)
486 ctx->lru.lz.upcoming_offset = 0;
487 ctx->lru.delta.upcoming_offset = 0;
488 ctx->lru.delta.upcoming_power = 0;
492 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
494 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
495 ctx->cur_window_pos += length;
496 lzms_update_lru_queues(&ctx->lru);
499 /* Encode a literal byte. */
501 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
503 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
504 ctx->cur_window_pos, literal, literal);
506 lzms_begin_encode_item(ctx);
508 /* Main bit: 0 = a literal, not a match. */
509 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
511 /* Encode the literal using the current literal Huffman code. */
512 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
514 lzms_end_encode_item(ctx, 1);
517 /* Encode a (length, offset) pair (LZ match). */
519 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
521 int recent_offset_idx;
523 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
524 ctx->cur_window_pos, length, offset);
526 LZMS_ASSERT(length <= ctx->window_size - ctx->cur_window_pos);
527 LZMS_ASSERT(offset <= ctx->cur_window_pos);
528 LZMS_ASSERT(!memcmp(&ctx->window[ctx->cur_window_pos],
529 &ctx->window[ctx->cur_window_pos - offset],
532 lzms_begin_encode_item(ctx);
534 /* Main bit: 1 = a match, not a literal. */
535 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
537 /* Match bit: 0 = an LZ match, not a delta match. */
538 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
540 /* Determine if the offset can be represented as a recent offset. */
541 for (recent_offset_idx = 0;
542 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
544 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
547 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
548 /* Explicit offset. */
550 /* LZ match bit: 0 = explicit offset, not a recent offset. */
551 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
553 /* Encode the match offset. */
554 lzms_encode_offset(&ctx->lz_offset_encoder, offset);
560 /* LZ match bit: 1 = recent offset, not an explicit offset. */
561 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
563 /* Encode the recent offset index. A 1 bit is encoded for each
564 * index passed up. This sequence of 1 bits is terminated by a
565 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
566 * bits have been encoded. */
567 for (i = 0; i < recent_offset_idx; i++)
568 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
570 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
571 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
573 /* Initial update of the LZ match offset LRU queue. */
574 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
575 ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
578 /* Encode the match length. */
579 lzms_encode_length(&ctx->length_encoder, length);
581 /* Save the match offset for later insertion at the front of the LZ
582 * match offset LRU queue. */
583 ctx->lru.lz.upcoming_offset = offset;
585 lzms_end_encode_item(ctx, length);
588 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
589 * Unlike lzms_get_lz_match_cost(), which does a true cost evaluation, this
590 * simply prioritize matches based on their offset. */
592 lzms_lz_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_lru)
594 const struct lzms_lz_lru_queues *lru = _lru;
596 for (input_idx_t i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++)
597 if (offset == lru->recent_offsets[i])
603 #define LZMS_COST_SHIFT 5
605 /*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
608 lzms_rc_costs[LZMS_PROBABILITY_MAX + 1];
610 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
615 lzms_do_init_rc_costs(void)
617 /* Fill in a table that maps range coding probabilities needed to code a
618 * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
619 * handle fractional costs) needed to code that bit X.
621 * Consider the range of the range decoder. To eliminate exactly half
622 * the range (logical probability of 0.5), we need exactly 1 bit. For
623 * lower probabilities we need more bits and for higher probabilities we
624 * need fewer bits. In general, a logical probability of N will
625 * eliminate the proportion 1 - N of the range; this information takes
626 * log2(1 / N) bits to encode.
628 * The below loop is simply calculating this number of bits for each
629 * possible probability allowed by the LZMS compression format, but
630 * without using real numbers. To handle fractional probabilities, each
631 * cost is multiplied by (1 << LZMS_COST_SHIFT). These techniques are
632 * based on those used by LZMA.
634 * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
635 * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
638 for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
643 else if (prob == LZMS_PROBABILITY_MAX)
644 prob = LZMS_PROBABILITY_MAX - 1;
646 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
647 lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
648 (1 << LZMS_COST_SHIFT);
652 for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
655 while (w >= (1U << 16)) {
660 lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
667 lzms_init_rc_costs(void)
669 static pthread_once_t once = PTHREAD_ONCE_INIT;
671 pthread_once(&once, lzms_do_init_rc_costs);
675 * Return the cost to range-encode the specified bit when in the specified
678 * @enc The range encoder to use.
679 * @cur_state Current state, which indicates the probability entry to choose.
680 * Updated by this function.
681 * @bit The bit to encode (0 or 1).
684 lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 *cur_state, int bit)
689 prob_zero = enc->prob_entries[*cur_state & enc->mask].num_recent_zero_bits;
691 *cur_state = (*cur_state << 1) | bit;
694 prob_correct = prob_zero;
696 prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
698 return lzms_rc_costs[prob_correct];
702 lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, u32 sym)
704 return enc->lens[sym] << LZMS_COST_SHIFT;
708 lzms_offset_cost(const struct lzms_huffman_encoder *enc, u32 offset)
714 slot = lzms_get_position_slot(offset);
716 cost += lzms_huffman_symbol_cost(enc, slot);
718 num_extra_bits = lzms_extra_position_bits[slot];
720 cost += num_extra_bits << LZMS_COST_SHIFT;
726 lzms_length_cost(const struct lzms_huffman_encoder *enc, u32 length)
732 slot = lzms_get_length_slot(length);
734 cost += lzms_huffman_symbol_cost(enc, slot);
736 num_extra_bits = lzms_extra_length_bits[slot];
738 cost += num_extra_bits << LZMS_COST_SHIFT;
744 lzms_get_matches(struct lzms_compressor *ctx,
745 const struct lzms_adaptive_state *state,
746 struct raw_match **matches_ret)
748 *matches_ret = ctx->matches;
749 return lz_sarray_get_matches(&ctx->lz_sarray,
751 lzms_lz_match_cost_fast,
756 lzms_skip_bytes(struct lzms_compressor *ctx, input_idx_t n)
759 lz_sarray_skip_position(&ctx->lz_sarray);
763 lzms_get_prev_literal_cost(struct lzms_compressor *ctx,
764 struct lzms_adaptive_state *state)
766 u8 literal = ctx->window[lz_sarray_get_pos(&ctx->lz_sarray) - 1];
769 state->lru.upcoming_offset = 0;
770 lzms_update_lz_lru_queues(&state->lru);
772 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
773 &state->main_state, 0);
775 cost += lzms_huffman_symbol_cost(&ctx->literal_encoder, literal);
781 lzms_get_lz_match_cost(struct lzms_compressor *ctx,
782 struct lzms_adaptive_state *state,
783 input_idx_t length, input_idx_t offset)
786 int recent_offset_idx;
788 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
789 &state->main_state, 1);
790 cost += lzms_rc_bit_cost(&ctx->match_range_encoder,
791 &state->match_state, 0);
793 for (recent_offset_idx = 0;
794 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
796 if (offset == state->lru.recent_offsets[recent_offset_idx])
799 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
800 /* Explicit offset. */
801 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
802 &state->lz_match_state, 0);
804 cost += lzms_offset_cost(&ctx->lz_offset_encoder, offset);
809 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
810 &state->lz_match_state, 1);
812 for (i = 0; i < recent_offset_idx; i++)
813 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
814 &state->lz_repeat_match_state[i], 0);
816 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
817 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
818 &state->lz_repeat_match_state[i], 1);
821 /* Initial update of the LZ match offset LRU queue. */
822 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
823 state->lru.recent_offsets[i] = state->lru.recent_offsets[i + 1];
826 cost += lzms_length_cost(&ctx->length_encoder, length);
828 state->lru.upcoming_offset = offset;
829 lzms_update_lz_lru_queues(&state->lru);
834 static struct raw_match
835 lzms_get_near_optimal_match(struct lzms_compressor *ctx)
837 struct lzms_adaptive_state initial_state;
839 initial_state.lru = ctx->lru.lz;
840 initial_state.main_state = ctx->main_range_encoder.state;
841 initial_state.match_state = ctx->match_range_encoder.state;
842 initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
843 for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
844 initial_state.lz_repeat_match_state[i] =
845 ctx->lz_repeat_match_range_encoders[i].state;
846 return lz_get_near_optimal_match(&ctx->mc,
849 lzms_get_prev_literal_cost,
850 lzms_get_lz_match_cost,
856 * The main loop for the LZMS compressor.
860 * - This uses near-optimal LZ parsing backed by a suffix-array match-finder.
861 * More details can be found in the corresponding files (lz_optimal.h,
864 * - This does not output any delta matches. It would take a specialized
865 * algorithm to find them, then more code in lz_optimal.h and here to handle
866 * evaluating and outputting them.
868 * - The costs of literals and matches are estimated using the range encoder
869 * states and the semi-adaptive Huffman codes. Except for range encoding
870 * states, costs are assumed to be constant throughout a single run of the
871 * parsing algorithm, which can parse up to @optim_array_length (from the
872 * `struct wimlib_lzms_compressor_params') bytes of data. This introduces a
873 * source of inaccuracy because the probabilities and Huffman codes can change
874 * over this part of the data.
877 lzms_encode(struct lzms_compressor *ctx)
879 struct raw_match match;
881 /* Load window into suffix array match-finder. */
882 lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
884 /* Reset the match-chooser. */
885 lz_match_chooser_begin(&ctx->mc);
887 while (ctx->cur_window_pos != ctx->window_size) {
888 match = lzms_get_near_optimal_match(ctx);
890 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
892 lzms_encode_lz_match(ctx, match.len, match.offset);
897 lzms_init_range_encoder(struct lzms_range_encoder *enc,
898 struct lzms_range_encoder_raw *rc, u32 num_states)
902 enc->mask = num_states - 1;
903 for (u32 i = 0; i < num_states; i++) {
904 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
905 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
910 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
911 struct lzms_output_bitstream *os,
913 unsigned rebuild_freq)
916 enc->num_syms_written = 0;
917 enc->rebuild_freq = rebuild_freq;
918 enc->num_syms = num_syms;
919 for (unsigned i = 0; i < num_syms; i++)
920 enc->sym_freqs[i] = 1;
922 make_canonical_huffman_code(enc->num_syms,
923 LZMS_MAX_CODEWORD_LEN,
929 /* Initialize the LZMS compressor. */
931 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
932 le16 *cdata, u32 clen16)
934 unsigned num_position_slots;
936 /* Copy the uncompressed data into the @ctx->window buffer. */
937 memcpy(ctx->window, udata, ulen);
938 ctx->cur_window_pos = 0;
939 ctx->window_size = ulen;
941 /* Initialize the raw range encoder (writing forwards). */
942 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
944 /* Initialize the output bitstream for Huffman symbols and verbatim bits
945 * (writing backwards). */
946 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
948 /* Calculate the number of position slots needed for this compressed
950 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
952 LZMS_DEBUG("Using %u position slots", num_position_slots);
954 /* Initialize Huffman encoders for each alphabet used in the compressed
956 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
957 LZMS_NUM_LITERAL_SYMS,
958 LZMS_LITERAL_CODE_REBUILD_FREQ);
960 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
962 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
964 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
966 LZMS_LENGTH_CODE_REBUILD_FREQ);
968 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
970 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
972 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
973 LZMS_NUM_DELTA_POWER_SYMS,
974 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
976 /* Initialize range encoders, all of which wrap around the same
977 * lzms_range_encoder_raw. */
978 lzms_init_range_encoder(&ctx->main_range_encoder,
979 &ctx->rc, LZMS_NUM_MAIN_STATES);
981 lzms_init_range_encoder(&ctx->match_range_encoder,
982 &ctx->rc, LZMS_NUM_MATCH_STATES);
984 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
985 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
987 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
988 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
989 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
991 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
992 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
994 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
995 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
996 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
998 /* Initialize LRU match information. */
999 lzms_init_lru_queues(&ctx->lru);
1002 /* Flush the output streams, prepare the final compressed data, and return its
1005 * A return value of 0 indicates that the data could not be compressed to fit in
1006 * the available space. */
1008 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
1010 size_t num_forwards_bytes;
1011 size_t num_backwards_bytes;
1012 size_t compressed_size;
1014 /* Flush both the forwards and backwards streams, and make sure they
1015 * didn't cross each other and start overwriting each other's data. */
1016 if (!lzms_output_bitstream_flush(&ctx->os)) {
1017 LZMS_DEBUG("Backwards bitstream overrun.");
1021 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
1022 LZMS_DEBUG("Forwards bitstream overrun.");
1026 if (ctx->rc.out > ctx->os.out) {
1027 LZMS_DEBUG("Two bitstreams crossed.");
1031 /* Now the compressed buffer contains the data output by the forwards
1032 * bitstream, then empty space, then data output by the backwards
1033 * bitstream. Move the data output by the backwards bitstream to be
1034 * adjacent to the data output by the forward bitstream, and calculate
1035 * the compressed size that this results in. */
1036 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
1037 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
1039 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
1041 compressed_size = num_forwards_bytes + num_backwards_bytes;
1042 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
1043 "compressed_size=%zu",
1044 num_forwards_bytes, num_backwards_bytes, compressed_size);
1045 LZMS_ASSERT(compressed_size % 2 == 0);
1046 return compressed_size;
1050 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
1051 void *compressed_data, size_t compressed_size_avail, void *_ctx)
1053 struct lzms_compressor *ctx = _ctx;
1054 size_t compressed_size;
1056 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
1057 uncompressed_size, compressed_size_avail);
1059 /* Make sure the uncompressed size is compatible with this compressor.
1061 if (uncompressed_size > ctx->max_block_size) {
1062 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
1063 "only supports %u bytes",
1064 uncompressed_size, ctx->max_block_size);
1068 /* Don't bother compressing extremely small inputs. */
1069 if (uncompressed_size < 4) {
1070 LZMS_DEBUG("Input too small to bother compressing.");
1074 /* Cap the available compressed size to a 32-bit integer and round it
1075 * down to the nearest multiple of 2. */
1076 if (compressed_size_avail > UINT32_MAX)
1077 compressed_size_avail = UINT32_MAX;
1078 if (compressed_size_avail & 1)
1079 compressed_size_avail--;
1081 /* Initialize the compressor structures. */
1082 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
1083 compressed_data, compressed_size_avail / 2);
1085 /* Preprocess the uncompressed data. */
1086 lzms_x86_filter(ctx->window, ctx->window_size,
1087 ctx->last_target_usages, false);
1089 /* Compute and encode a literal/match sequence that decompresses to the
1090 * preprocessed data. */
1093 /* Get and return the compressed data size. */
1094 compressed_size = lzms_finalize(ctx, compressed_data,
1095 compressed_size_avail);
1097 if (compressed_size == 0) {
1098 LZMS_DEBUG("Data did not compress to requested size or less.");
1102 LZMS_DEBUG("Compressed %zu => %zu bytes",
1103 uncompressed_size, compressed_size);
1105 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
1106 /* Verify that we really get the same thing back when decompressing. */
1108 struct wimlib_decompressor *decompressor;
1110 LZMS_DEBUG("Verifying LZMS compression.");
1112 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
1113 ctx->max_block_size,
1118 ret = wimlib_decompress(compressed_data,
1123 wimlib_free_decompressor(decompressor);
1126 ERROR("Failed to decompress data we "
1127 "compressed using LZMS algorithm");
1131 if (memcmp(uncompressed_data, ctx->window,
1134 ERROR("Data we compressed using LZMS algorithm "
1135 "didn't decompress to original");
1140 WARNING("Failed to create decompressor for "
1141 "data verification!");
1144 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION */
1146 return compressed_size;
1150 lzms_free_compressor(void *_ctx)
1152 struct lzms_compressor *ctx = _ctx;
1157 lz_sarray_destroy(&ctx->lz_sarray);
1158 lz_match_chooser_destroy(&ctx->mc);
1163 static const struct wimlib_lzms_compressor_params lzms_default = {
1165 .size = sizeof(struct wimlib_lzms_compressor_params),
1167 .min_match_length = 2,
1168 .max_match_length = UINT32_MAX,
1169 .nice_match_length = 32,
1170 .max_search_depth = 50,
1171 .max_matches_per_pos = 3,
1172 .optim_array_length = 1024,
1176 lzms_params_valid(const struct wimlib_compressor_params_header *);
1178 static const struct wimlib_lzms_compressor_params *
1179 lzms_get_params(const struct wimlib_compressor_params_header *_params)
1181 const struct wimlib_lzms_compressor_params *params =
1182 (const struct wimlib_lzms_compressor_params*)_params;
1185 params = &lzms_default;
1187 LZMS_ASSERT(lzms_params_valid(¶ms->hdr));
1193 lzms_create_compressor(size_t max_block_size,
1194 const struct wimlib_compressor_params_header *_params,
1197 struct lzms_compressor *ctx;
1198 const struct wimlib_lzms_compressor_params *params = lzms_get_params(_params);
1200 if (max_block_size == 0 || max_block_size >= INT32_MAX) {
1201 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
1202 return WIMLIB_ERR_INVALID_PARAM;
1205 ctx = CALLOC(1, sizeof(struct lzms_compressor));
1209 ctx->window = MALLOC(max_block_size);
1210 if (ctx->window == NULL)
1213 ctx->matches = MALLOC(min(params->max_match_length -
1214 params->min_match_length + 1,
1215 params->max_matches_per_pos) *
1216 sizeof(ctx->matches[0]));
1217 if (ctx->matches == NULL)
1220 if (!lz_sarray_init(&ctx->lz_sarray, max_block_size,
1221 params->min_match_length,
1222 min(params->max_match_length, LZ_SARRAY_LEN_MAX),
1223 params->max_search_depth,
1224 params->max_matches_per_pos))
1227 if (!lz_match_chooser_init(&ctx->mc,
1228 params->optim_array_length,
1229 params->nice_match_length,
1230 params->max_match_length))
1233 /* Initialize position and length slot data if not done already. */
1236 /* Initialize range encoding cost table if not done already. */
1237 lzms_init_rc_costs();
1239 ctx->max_block_size = max_block_size;
1245 lzms_free_compressor(ctx);
1246 return WIMLIB_ERR_NOMEM;
1250 lzms_get_needed_memory(size_t max_block_size,
1251 const struct wimlib_compressor_params_header *_params)
1253 const struct wimlib_lzms_compressor_params *params = lzms_get_params(_params);
1257 size += max_block_size;
1258 size += sizeof(struct lzms_compressor);
1259 size += lz_sarray_get_needed_memory(max_block_size);
1260 size += lz_match_chooser_get_needed_memory(params->optim_array_length,
1261 params->nice_match_length,
1262 params->max_match_length);
1263 size += min(params->max_match_length -
1264 params->min_match_length + 1,
1265 params->max_matches_per_pos) *
1266 sizeof(((struct lzms_compressor*)0)->matches[0]);
1271 lzms_params_valid(const struct wimlib_compressor_params_header *_params)
1273 const struct wimlib_lzms_compressor_params *params =
1274 (const struct wimlib_lzms_compressor_params*)_params;
1276 if (params->hdr.size != sizeof(*params) ||
1277 params->max_match_length < params->min_match_length ||
1278 params->min_match_length < 2 ||
1279 params->optim_array_length == 0 ||
1280 min(params->max_match_length, params->nice_match_length) > 65536)
1286 const struct compressor_ops lzms_compressor_ops = {
1287 .params_valid = lzms_params_valid,
1288 .get_needed_memory = lzms_get_needed_memory,
1289 .create_compressor = lzms_create_compressor,
1290 .compress = lzms_compress,
1291 .free_compressor = lzms_free_compressor,