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/compiler.h"
36 #include "wimlib/compressor_ops.h"
37 #include "wimlib/compress_common.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/lz_sarray.h"
41 #include "wimlib/lzms.h"
42 #include "wimlib/util.h"
48 struct lzms_compressor;
49 struct lzms_adaptive_state {
50 struct lzms_lz_lru_queues lru;
54 u8 lz_repeat_match_state[LZMS_NUM_RECENT_OFFSETS - 1];
56 #define LZ_ADAPTIVE_STATE struct lzms_adaptive_state
57 #define LZ_COMPRESSOR struct lzms_compressor
58 #include "wimlib/lz_optimal.h"
60 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
61 * a series of 16-bit little endian coding units. */
62 struct lzms_output_bitstream {
63 /* Buffer variable containing zero or more bits that have been logically
64 * written to the bitstream but not yet written to memory. This must be
65 * at least as large as the coding unit size. */
68 /* Number of bits in @bitbuf that are valid. */
69 unsigned num_free_bits;
71 /* Pointer to one past the next position in the compressed data buffer
72 * at which to output a 16-bit coding unit. */
75 /* Maximum number of 16-bit coding units that can still be output to
76 * the compressed data buffer. */
77 size_t num_le16_remaining;
79 /* Set to %true if not all coding units could be output due to
80 * insufficient space. */
84 /* Stucture used for range encoding (raw version). */
85 struct lzms_range_encoder_raw {
87 /* A 33-bit variable that holds the low boundary of the current range.
88 * The 33rd bit is needed to catch carries. */
91 /* Size of the current range. */
94 /* Next 16-bit coding unit to output. */
97 /* Number of 16-bit coding units whose output has been delayed due to
98 * possible carrying. The first such coding unit is @cache; all
99 * subsequent such coding units are 0xffff. */
102 /* Pointer to the next position in the compressed data buffer at which
103 * to output a 16-bit coding unit. */
106 /* Maximum number of 16-bit coding units that can still be output to
107 * the compressed data buffer. */
108 size_t num_le16_remaining;
110 /* %true when the very first coding unit has not yet been output. */
113 /* Set to %true if not all coding units could be output due to
114 * insufficient space. */
118 /* Structure used for range encoding. This wraps around `struct
119 * lzms_range_encoder_raw' to use and maintain probability entries. */
120 struct lzms_range_encoder {
121 /* Pointer to the raw range encoder, which has no persistent knowledge
122 * of probabilities. Multiple lzms_range_encoder's share the same
123 * lzms_range_encoder_raw. */
124 struct lzms_range_encoder_raw *rc;
126 /* Bits recently encoded by this range encoder. This are used as in
127 * index into @prob_entries. */
130 /* Bitmask for @state to prevent its value from exceeding the number of
131 * probability entries. */
134 /* Probability entries being used for this range encoder. */
135 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
138 /* Structure used for Huffman encoding. */
139 struct lzms_huffman_encoder {
141 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
142 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
144 struct lzms_output_bitstream *os;
146 /* Number of symbols that have been written using this code far. Reset
147 * to 0 whenever the code is rebuilt. */
148 u32 num_syms_written;
150 /* When @num_syms_written reaches this number, the Huffman code must be
154 /* Number of symbols in the represented Huffman code. */
157 /* Running totals of symbol frequencies. These are diluted slightly
158 * whenever the code is rebuilt. */
159 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
161 /* The length, in bits, of each symbol in the Huffman code. */
162 u8 lens[LZMS_MAX_NUM_SYMS];
164 /* The codeword of each symbol in the Huffman code. */
165 u16 codewords[LZMS_MAX_NUM_SYMS];
168 /* State of the LZMS compressor. */
169 struct lzms_compressor {
170 /* Pointer to a buffer holding the preprocessed data to compress. */
173 /* Current position in @buffer. */
176 /* Size of the data in @buffer. */
179 /* Suffix array match-finder. */
180 struct lz_sarray lz_sarray;
182 /* Temporary space to store found matches. */
183 struct raw_match *matches;
186 struct lz_match_chooser mc;
188 /* Maximum block size this compressor instantiation allows. This is the
189 * allocated size of @window. */
192 /* Raw range encoder which outputs to the beginning of the compressed
193 * data buffer, proceeding forwards. */
194 struct lzms_range_encoder_raw rc;
196 /* Bitstream which outputs to the end of the compressed data buffer,
197 * proceeding backwards. */
198 struct lzms_output_bitstream os;
200 /* Range encoders. */
201 struct lzms_range_encoder main_range_encoder;
202 struct lzms_range_encoder match_range_encoder;
203 struct lzms_range_encoder lz_match_range_encoder;
204 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
205 struct lzms_range_encoder delta_match_range_encoder;
206 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
208 /* Huffman encoders. */
209 struct lzms_huffman_encoder literal_encoder;
210 struct lzms_huffman_encoder lz_offset_encoder;
211 struct lzms_huffman_encoder length_encoder;
212 struct lzms_huffman_encoder delta_power_encoder;
213 struct lzms_huffman_encoder delta_offset_encoder;
215 /* LRU (least-recently-used) queues for match information. */
216 struct lzms_lru_queues lru;
218 /* Used for preprocessing. */
219 s32 last_target_usages[65536];
222 /* Initialize the output bitstream @os to write forwards to the specified
223 * compressed data buffer @out that is @out_limit 16-bit integers long. */
225 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
226 le16 *out, size_t out_limit)
229 os->num_free_bits = 16;
230 os->out = out + out_limit;
231 os->num_le16_remaining = out_limit;
235 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
236 * from high-order to low-order), to the output bitstream @os. */
238 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
239 u32 bits, unsigned num_bits)
241 bits &= (1U << num_bits) - 1;
243 while (num_bits > os->num_free_bits) {
245 if (unlikely(os->num_le16_remaining == 0)) {
250 unsigned num_fill_bits = os->num_free_bits;
252 os->bitbuf <<= num_fill_bits;
253 os->bitbuf |= bits >> (num_bits - num_fill_bits);
255 *--os->out = cpu_to_le16(os->bitbuf);
256 --os->num_le16_remaining;
258 os->num_free_bits = 16;
259 num_bits -= num_fill_bits;
260 bits &= (1U << num_bits) - 1;
262 os->bitbuf <<= num_bits;
264 os->num_free_bits -= num_bits;
267 /* Flush the output bitstream, ensuring that all bits written to it have been
268 * written to memory. Returns %true if all bits were output successfully, or
269 * %false if an overrun occurred. */
271 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
273 if (os->num_free_bits != 16)
274 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
278 /* Initialize the range encoder @rc to write forwards to the specified
279 * compressed data buffer @out that is @out_limit 16-bit integers long. */
281 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
282 le16 *out, size_t out_limit)
285 rc->range = 0xffffffff;
289 rc->num_le16_remaining = out_limit;
295 * Attempt to flush bits from the range encoder.
297 * Note: this is based on the public domain code for LZMA written by Igor
298 * Pavlov. The only differences in this function are that in LZMS the bits must
299 * be output in 16-bit coding units instead of 8-bit coding units, and that in
300 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
301 * cannot output a dummy value to that position.
303 * The basic idea is that we're writing bits from @rc->low to the output.
304 * However, due to carrying, the writing of coding units with value 0xffff, as
305 * well as one prior coding unit, must be delayed until it is determined whether
309 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
311 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
312 rc->low, rc->cache, rc->cache_size);
313 if ((u32)(rc->low) < 0xffff0000 ||
314 (u32)(rc->low >> 32) != 0)
316 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
317 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
320 if (rc->num_le16_remaining == 0) {
324 *rc->out++ = cpu_to_le16(rc->cache +
325 (u16)(rc->low >> 32));
326 --rc->num_le16_remaining;
332 } while (--rc->cache_size != 0);
334 rc->cache = (rc->low >> 16) & 0xffff;
337 rc->low = (rc->low & 0xffff) << 16;
341 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
343 if (rc->range <= 0xffff) {
345 lzms_range_encoder_raw_shift_low(rc);
350 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
352 for (unsigned i = 0; i < 4; i++)
353 lzms_range_encoder_raw_shift_low(rc);
357 /* Encode the next bit using the range encoder (raw version).
359 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
361 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
364 lzms_range_encoder_raw_normalize(rc);
366 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
375 /* Encode a bit using the specified range encoder. This wraps around
376 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
377 * appropriate probability table. */
379 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
381 struct lzms_probability_entry *prob_entry;
384 /* Load the probability entry corresponding to the current state. */
385 prob_entry = &enc->prob_entries[enc->state];
387 /* Treat the number of zero bits in the most recently encoded
388 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
389 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
390 * don't allow 0% or 100% probabilities. */
391 prob = prob_entry->num_recent_zero_bits;
394 else if (prob == LZMS_PROBABILITY_MAX)
395 prob = LZMS_PROBABILITY_MAX - 1;
397 /* Encode the next bit. */
398 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
400 /* Update the state based on the newly encoded bit. */
401 enc->state = ((enc->state << 1) | bit) & enc->mask;
403 /* Update the recent bits, including the cached count of 0's. */
404 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
406 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
407 /* Replacing 1 bit with 0 bit; increment the zero count.
409 prob_entry->num_recent_zero_bits++;
412 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
413 /* Replacing 0 bit with 1 bit; decrement the zero count.
415 prob_entry->num_recent_zero_bits--;
418 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
421 /* Encode a symbol using the specified Huffman encoder. */
423 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
425 LZMS_ASSERT(sym < enc->num_syms);
426 lzms_output_bitstream_put_bits(enc->os,
429 ++enc->sym_freqs[sym];
430 if (++enc->num_syms_written == enc->rebuild_freq) {
431 /* Adaptive code needs to be rebuilt. */
432 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
433 make_canonical_huffman_code(enc->num_syms,
434 LZMS_MAX_CODEWORD_LEN,
439 /* Dilute the frequencies. */
440 for (unsigned i = 0; i < enc->num_syms; i++) {
441 enc->sym_freqs[i] >>= 1;
442 enc->sym_freqs[i] += 1;
444 enc->num_syms_written = 0;
449 lzms_encode_length(struct lzms_huffman_encoder *enc, u32 length)
452 unsigned num_extra_bits;
455 slot = lzms_get_length_slot(length);
457 num_extra_bits = lzms_extra_length_bits[slot];
459 extra_bits = length - lzms_length_slot_base[slot];
461 lzms_huffman_encode_symbol(enc, slot);
462 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
466 lzms_encode_offset(struct lzms_huffman_encoder *enc, u32 offset)
469 unsigned num_extra_bits;
472 slot = lzms_get_position_slot(offset);
474 num_extra_bits = lzms_extra_position_bits[slot];
476 extra_bits = offset - lzms_position_slot_base[slot];
478 lzms_huffman_encode_symbol(enc, slot);
479 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
483 lzms_begin_encode_item(struct lzms_compressor *ctx)
485 ctx->lru.lz.upcoming_offset = 0;
486 ctx->lru.delta.upcoming_offset = 0;
487 ctx->lru.delta.upcoming_power = 0;
491 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
493 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
494 ctx->cur_window_pos += length;
495 lzms_update_lru_queues(&ctx->lru);
498 /* Encode a literal byte. */
500 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
502 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
503 ctx->cur_window_pos, literal, literal);
505 lzms_begin_encode_item(ctx);
507 /* Main bit: 0 = a literal, not a match. */
508 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
510 /* Encode the literal using the current literal Huffman code. */
511 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
513 lzms_end_encode_item(ctx, 1);
516 /* Encode a (length, offset) pair (LZ match). */
518 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
520 int recent_offset_idx;
522 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
523 ctx->cur_window_pos, length, offset);
525 LZMS_ASSERT(length <= ctx->window_size - ctx->cur_window_pos);
526 LZMS_ASSERT(offset <= ctx->cur_window_pos);
527 LZMS_ASSERT(!memcmp(&ctx->window[ctx->cur_window_pos],
528 &ctx->window[ctx->cur_window_pos - offset],
531 lzms_begin_encode_item(ctx);
533 /* Main bit: 1 = a match, not a literal. */
534 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
536 /* Match bit: 0 = a LZ match, not a delta match. */
537 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
539 /* Determine if the offset can be represented as a recent offset. */
540 for (recent_offset_idx = 0;
541 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
543 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
546 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
547 /* Explicit offset. */
549 /* LZ match bit: 0 = explicit offset, not a recent offset. */
550 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
552 /* Encode the match offset. */
553 lzms_encode_offset(&ctx->lz_offset_encoder, offset);
559 /* LZ match bit: 1 = recent offset, not an explicit offset. */
560 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
562 /* Encode the recent offset index. A 1 bit is encoded for each
563 * index passed up. This sequence of 1 bits is terminated by a
564 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
565 * bits have been encoded. */
566 for (i = 0; i < recent_offset_idx; i++)
567 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
569 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
570 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
572 /* Initial update of the LZ match offset LRU queue. */
573 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
574 ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
577 /* Encode the match length. */
578 lzms_encode_length(&ctx->length_encoder, length);
580 /* Save the match offset for later insertion at the front of the LZ
581 * match offset LRU queue. */
582 ctx->lru.lz.upcoming_offset = offset;
584 lzms_end_encode_item(ctx, length);
587 /* Fast heuristic cost evaluation to use in the inner loop of the match-finder.
588 * Unlike lzms_get_lz_match_cost(), which does a true cost evaluation, this
589 * simply prioritize matches based on their offset. */
591 lzms_lz_match_cost_fast(input_idx_t length, input_idx_t offset, const void *_lru)
593 const struct lzms_lz_lru_queues *lru = _lru;
595 for (input_idx_t i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++)
596 if (offset == lru->recent_offsets[i])
602 #define LZMS_COST_SHIFT 5
604 /*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
607 lzms_rc_costs[LZMS_PROBABILITY_MAX + 1];
609 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
614 lzms_do_init_rc_costs(void)
616 /* Fill in a table that maps range coding probabilities needed to code a
617 * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
618 * handle fractional costs) needed to code that bit X.
620 * Consider the range of the range decoder. To eliminate exactly half
621 * the range (logical probability of 0.5), we need exactly 1 bit. For
622 * lower probabilities we need more bits and for higher probabilities we
623 * need fewer bits. In general, a logical probability of N will
624 * eliminate the proportion 1 - N of the range; this information takes
625 * log2(1 / N) bits to encode.
627 * The below loop is simply calculating this number of bits for each
628 * possible probability allowed by the LZMS compression format, but
629 * without using real numbers. To handle fractional probabilities, each
630 * cost is multiplied by (1 << LZMS_COST_SHIFT). These techniques are
631 * based on those used by LZMA.
633 * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
634 * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
637 for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
642 else if (prob == LZMS_PROBABILITY_MAX)
643 prob = LZMS_PROBABILITY_MAX - 1;
645 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
646 lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
647 (1 << LZMS_COST_SHIFT);
651 for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
654 while (w >= (1U << 16)) {
659 lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
666 lzms_init_rc_costs(void)
668 static bool done = false;
669 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
671 if (unlikely(!done)) {
672 pthread_mutex_lock(&mutex);
674 lzms_do_init_rc_costs();
677 pthread_mutex_unlock(&mutex);
682 * Return the cost to range-encode the specified bit when in the specified
685 * @enc The range encoder to use.
686 * @cur_state Current state, which indicates the probability entry to choose.
687 * Updated by this function.
688 * @bit The bit to encode (0 or 1).
691 lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 *cur_state, int bit)
696 prob_zero = enc->prob_entries[*cur_state & enc->mask].num_recent_zero_bits;
698 *cur_state = (*cur_state << 1) | bit;
701 prob_correct = prob_zero;
703 prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
705 return lzms_rc_costs[prob_correct];
709 lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, u32 sym)
711 return enc->lens[sym] << LZMS_COST_SHIFT;
715 lzms_offset_cost(const struct lzms_huffman_encoder *enc, u32 offset)
721 slot = lzms_get_position_slot(offset);
723 cost += lzms_huffman_symbol_cost(enc, slot);
725 num_extra_bits = lzms_extra_position_bits[slot];
727 cost += num_extra_bits << LZMS_COST_SHIFT;
733 lzms_length_cost(const struct lzms_huffman_encoder *enc, u32 length)
739 slot = lzms_get_length_slot(length);
741 cost += lzms_huffman_symbol_cost(enc, slot);
743 num_extra_bits = lzms_extra_length_bits[slot];
745 cost += num_extra_bits << LZMS_COST_SHIFT;
751 lzms_get_matches(struct lzms_compressor *ctx,
752 const struct lzms_adaptive_state *state,
753 struct raw_match **matches_ret)
755 *matches_ret = ctx->matches;
756 return lz_sarray_get_matches(&ctx->lz_sarray,
758 lzms_lz_match_cost_fast,
763 lzms_skip_bytes(struct lzms_compressor *ctx, input_idx_t n)
766 lz_sarray_skip_position(&ctx->lz_sarray);
770 lzms_get_prev_literal_cost(struct lzms_compressor *ctx,
771 struct lzms_adaptive_state *state)
773 u8 literal = ctx->window[lz_sarray_get_pos(&ctx->lz_sarray) - 1];
776 state->lru.upcoming_offset = 0;
777 lzms_update_lz_lru_queues(&state->lru);
779 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
780 &state->main_state, 0);
782 cost += lzms_huffman_symbol_cost(&ctx->literal_encoder, literal);
788 lzms_get_lz_match_cost(struct lzms_compressor *ctx,
789 struct lzms_adaptive_state *state,
790 input_idx_t length, input_idx_t offset)
793 int recent_offset_idx;
795 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
796 &state->main_state, 1);
797 cost += lzms_rc_bit_cost(&ctx->match_range_encoder,
798 &state->match_state, 0);
800 for (recent_offset_idx = 0;
801 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
803 if (offset == state->lru.recent_offsets[recent_offset_idx])
806 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
807 /* Explicit offset. */
808 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
809 &state->lz_match_state, 0);
811 cost += lzms_offset_cost(&ctx->lz_offset_encoder, offset);
816 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
817 &state->lz_match_state, 1);
819 for (i = 0; i < recent_offset_idx; i++)
820 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
821 &state->lz_repeat_match_state[i], 0);
823 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
824 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
825 &state->lz_repeat_match_state[i], 1);
828 /* Initial update of the LZ match offset LRU queue. */
829 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
830 state->lru.recent_offsets[i] = state->lru.recent_offsets[i + 1];
833 cost += lzms_length_cost(&ctx->length_encoder, length);
835 state->lru.upcoming_offset = offset;
836 lzms_update_lz_lru_queues(&state->lru);
841 static struct raw_match
842 lzms_get_near_optimal_match(struct lzms_compressor *ctx)
844 struct lzms_adaptive_state initial_state;
846 initial_state.lru = ctx->lru.lz;
847 initial_state.main_state = ctx->main_range_encoder.state;
848 initial_state.match_state = ctx->match_range_encoder.state;
849 initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
850 for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
851 initial_state.lz_repeat_match_state[i] =
852 ctx->lz_repeat_match_range_encoders[i].state;
853 return lz_get_near_optimal_match(&ctx->mc,
856 lzms_get_prev_literal_cost,
857 lzms_get_lz_match_cost,
863 * The main loop for the LZMS compressor.
867 * - This uses near-optimal LZ parsing backed by a suffix-array match-finder.
868 * More details can be found in the corresponding files (lz_optimal.h,
871 * - This does not output any delta matches. It would take a specialized
872 * algorithm to find them, then more code in lz_optimal.h and here to handle
873 * evaluating and outputting them.
875 * - The costs of literals and matches are estimated using the range encoder
876 * states and the semi-adaptive Huffman codes. Except for range encoding
877 * states, costs are assumed to be constant throughout a single run of the
878 * parsing algorithm, which can parse up to @optim_array_length (from the
879 * `struct wimlib_lzms_compressor_params') bytes of data. This introduces a
880 * source of inaccuracy because the probabilities and Huffman codes can change
881 * over this part of the data.
884 lzms_encode(struct lzms_compressor *ctx)
886 struct raw_match match;
888 /* Load window into suffix array match-finder. */
889 lz_sarray_load_window(&ctx->lz_sarray, ctx->window, ctx->window_size);
891 /* Reset the match-chooser. */
892 lz_match_chooser_begin(&ctx->mc);
894 while (ctx->cur_window_pos != ctx->window_size) {
895 match = lzms_get_near_optimal_match(ctx);
897 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
899 lzms_encode_lz_match(ctx, match.len, match.offset);
904 lzms_init_range_encoder(struct lzms_range_encoder *enc,
905 struct lzms_range_encoder_raw *rc, u32 num_states)
909 enc->mask = num_states - 1;
910 for (u32 i = 0; i < num_states; i++) {
911 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
912 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
917 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
918 struct lzms_output_bitstream *os,
920 unsigned rebuild_freq)
923 enc->num_syms_written = 0;
924 enc->rebuild_freq = rebuild_freq;
925 enc->num_syms = num_syms;
926 for (unsigned i = 0; i < num_syms; i++)
927 enc->sym_freqs[i] = 1;
929 make_canonical_huffman_code(enc->num_syms,
930 LZMS_MAX_CODEWORD_LEN,
936 /* Initialize the LZMS compressor. */
938 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
939 le16 *cdata, u32 clen16)
941 unsigned num_position_slots;
943 /* Copy the uncompressed data into the @ctx->window buffer. */
944 memcpy(ctx->window, udata, ulen);
945 ctx->cur_window_pos = 0;
946 ctx->window_size = ulen;
948 /* Initialize the raw range encoder (writing forwards). */
949 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
951 /* Initialize the output bitstream for Huffman symbols and verbatim bits
952 * (writing backwards). */
953 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
955 /* Calculate the number of position slots needed for this compressed
957 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
959 LZMS_DEBUG("Using %u position slots", num_position_slots);
961 /* Initialize Huffman encoders for each alphabet used in the compressed
963 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
964 LZMS_NUM_LITERAL_SYMS,
965 LZMS_LITERAL_CODE_REBUILD_FREQ);
967 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
969 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
971 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
973 LZMS_LENGTH_CODE_REBUILD_FREQ);
975 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
977 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
979 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
980 LZMS_NUM_DELTA_POWER_SYMS,
981 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
983 /* Initialize range encoders, all of which wrap around the same
984 * lzms_range_encoder_raw. */
985 lzms_init_range_encoder(&ctx->main_range_encoder,
986 &ctx->rc, LZMS_NUM_MAIN_STATES);
988 lzms_init_range_encoder(&ctx->match_range_encoder,
989 &ctx->rc, LZMS_NUM_MATCH_STATES);
991 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
992 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
994 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
995 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
996 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
998 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
999 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
1001 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
1002 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
1003 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1005 /* Initialize LRU match information. */
1006 lzms_init_lru_queues(&ctx->lru);
1009 /* Flush the output streams, prepare the final compressed data, and return its
1012 * A return value of 0 indicates that the data could not be compressed to fit in
1013 * the available space. */
1015 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
1017 size_t num_forwards_bytes;
1018 size_t num_backwards_bytes;
1019 size_t compressed_size;
1021 /* Flush both the forwards and backwards streams, and make sure they
1022 * didn't cross each other and start overwriting each other's data. */
1023 if (!lzms_output_bitstream_flush(&ctx->os)) {
1024 LZMS_DEBUG("Backwards bitstream overrun.");
1028 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
1029 LZMS_DEBUG("Forwards bitstream overrun.");
1033 if (ctx->rc.out > ctx->os.out) {
1034 LZMS_DEBUG("Two bitstreams crossed.");
1038 /* Now the compressed buffer contains the data output by the forwards
1039 * bitstream, then empty space, then data output by the backwards
1040 * bitstream. Move the data output by the backwards bitstream to be
1041 * adjacent to the data output by the forward bitstream, and calculate
1042 * the compressed size that this results in. */
1043 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
1044 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
1046 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
1048 compressed_size = num_forwards_bytes + num_backwards_bytes;
1049 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
1050 "compressed_size=%zu",
1051 num_forwards_bytes, num_backwards_bytes, compressed_size);
1052 LZMS_ASSERT(compressed_size % 2 == 0);
1053 return compressed_size;
1057 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
1058 void *compressed_data, size_t compressed_size_avail, void *_ctx)
1060 struct lzms_compressor *ctx = _ctx;
1061 size_t compressed_size;
1063 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
1064 uncompressed_size, compressed_size_avail);
1066 /* Make sure the uncompressed size is compatible with this compressor.
1068 if (uncompressed_size > ctx->max_block_size) {
1069 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
1070 "only supports %u bytes",
1071 uncompressed_size, ctx->max_block_size);
1075 /* Don't bother compressing extremely small inputs. */
1076 if (uncompressed_size < 4) {
1077 LZMS_DEBUG("Input too small to bother compressing.");
1081 /* Cap the available compressed size to a 32-bit integer and round it
1082 * down to the nearest multiple of 2. */
1083 if (compressed_size_avail > UINT32_MAX)
1084 compressed_size_avail = UINT32_MAX;
1085 if (compressed_size_avail & 1)
1086 compressed_size_avail--;
1088 /* Initialize the compressor structures. */
1089 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
1090 compressed_data, compressed_size_avail / 2);
1092 /* Preprocess the uncompressed data. */
1093 lzms_x86_filter(ctx->window, ctx->window_size,
1094 ctx->last_target_usages, false);
1096 /* Compute and encode a literal/match sequence that decompresses to the
1097 * preprocessed data. */
1100 /* Get and return the compressed data size. */
1101 compressed_size = lzms_finalize(ctx, compressed_data,
1102 compressed_size_avail);
1104 if (compressed_size == 0) {
1105 LZMS_DEBUG("Data did not compress to requested size or less.");
1109 LZMS_DEBUG("Compressed %zu => %zu bytes",
1110 uncompressed_size, compressed_size);
1112 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
1113 /* Verify that we really get the same thing back when decompressing. */
1115 struct wimlib_decompressor *decompressor;
1117 LZMS_DEBUG("Verifying LZMS compression.");
1119 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
1120 ctx->max_block_size,
1125 ret = wimlib_decompress(compressed_data,
1130 wimlib_free_decompressor(decompressor);
1133 ERROR("Failed to decompress data we "
1134 "compressed using LZMS algorithm");
1138 if (memcmp(uncompressed_data, ctx->window,
1141 ERROR("Data we compressed using LZMS algorithm "
1142 "didn't decompress to original");
1147 WARNING("Failed to create decompressor for "
1148 "data verification!");
1151 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION */
1153 return compressed_size;
1157 lzms_free_compressor(void *_ctx)
1159 struct lzms_compressor *ctx = _ctx;
1164 lz_sarray_destroy(&ctx->lz_sarray);
1165 lz_match_chooser_destroy(&ctx->mc);
1170 static const struct wimlib_lzms_compressor_params lzms_default = {
1172 .size = sizeof(struct wimlib_lzms_compressor_params),
1174 .min_match_length = 2,
1175 .max_match_length = UINT32_MAX,
1176 .nice_match_length = 32,
1177 .max_search_depth = 50,
1178 .max_matches_per_pos = 3,
1179 .optim_array_length = 1024,
1183 lzms_params_valid(const struct wimlib_compressor_params_header *);
1185 static const struct wimlib_lzms_compressor_params *
1186 lzms_get_params(const struct wimlib_compressor_params_header *_params)
1188 const struct wimlib_lzms_compressor_params *params =
1189 (const struct wimlib_lzms_compressor_params*)_params;
1192 params = &lzms_default;
1194 LZMS_ASSERT(lzms_params_valid(¶ms->hdr));
1200 lzms_create_compressor(size_t max_block_size,
1201 const struct wimlib_compressor_params_header *_params,
1204 struct lzms_compressor *ctx;
1205 const struct wimlib_lzms_compressor_params *params = lzms_get_params(_params);
1207 if (max_block_size == 0 || max_block_size >= INT32_MAX) {
1208 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
1209 return WIMLIB_ERR_INVALID_PARAM;
1212 ctx = CALLOC(1, sizeof(struct lzms_compressor));
1216 ctx->window = MALLOC(max_block_size);
1217 if (ctx->window == NULL)
1220 ctx->matches = MALLOC(min(params->max_match_length -
1221 params->min_match_length + 1,
1222 params->max_matches_per_pos) *
1223 sizeof(ctx->matches[0]));
1224 if (ctx->matches == NULL)
1227 if (!lz_sarray_init(&ctx->lz_sarray, max_block_size,
1228 params->min_match_length,
1229 min(params->max_match_length, LZ_SARRAY_LEN_MAX),
1230 params->max_search_depth,
1231 params->max_matches_per_pos))
1234 if (!lz_match_chooser_init(&ctx->mc,
1235 params->optim_array_length,
1236 params->nice_match_length,
1237 params->max_match_length))
1240 /* Initialize position and length slot data if not done already. */
1243 /* Initialize range encoding cost table if not done already. */
1244 lzms_init_rc_costs();
1246 ctx->max_block_size = max_block_size;
1252 lzms_free_compressor(ctx);
1253 return WIMLIB_ERR_NOMEM;
1257 lzms_get_needed_memory(size_t max_block_size,
1258 const struct wimlib_compressor_params_header *_params)
1260 const struct wimlib_lzms_compressor_params *params = lzms_get_params(_params);
1264 size += max_block_size;
1265 size += sizeof(struct lzms_compressor);
1266 size += lz_sarray_get_needed_memory(max_block_size);
1267 size += lz_match_chooser_get_needed_memory(params->optim_array_length,
1268 params->nice_match_length,
1269 params->max_match_length);
1270 size += min(params->max_match_length -
1271 params->min_match_length + 1,
1272 params->max_matches_per_pos) *
1273 sizeof(((struct lzms_compressor*)0)->matches[0]);
1278 lzms_params_valid(const struct wimlib_compressor_params_header *_params)
1280 const struct wimlib_lzms_compressor_params *params =
1281 (const struct wimlib_lzms_compressor_params*)_params;
1283 if (params->hdr.size != sizeof(*params) ||
1284 params->max_match_length < params->min_match_length ||
1285 params->min_match_length < 2 ||
1286 params->optim_array_length == 0 ||
1287 min(params->max_match_length, params->nice_match_length) > 65536)
1293 const struct compressor_ops lzms_compressor_ops = {
1294 .params_valid = lzms_params_valid,
1295 .get_needed_memory = lzms_get_needed_memory,
1296 .create_compressor = lzms_create_compressor,
1297 .compress = lzms_compress,
1298 .free_compressor = lzms_free_compressor,