6 * Copyright (C) 2013, 2014 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 * Also see lzx-compress.c for general information about match-finding and
28 * match-choosing that also applies to this LZMS compressor.
30 * NOTE: this compressor currently does not code any delta matches.
37 #include "wimlib/assert.h"
38 #include "wimlib/compiler.h"
39 #include "wimlib/compressor_ops.h"
40 #include "wimlib/compress_common.h"
41 #include "wimlib/endianness.h"
42 #include "wimlib/error.h"
43 #include "wimlib/lz_mf.h"
44 #include "wimlib/lz_repsearch.h"
45 #include "wimlib/lzms.h"
46 #include "wimlib/util.h"
52 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
53 * a series of 16-bit little endian coding units. */
54 struct lzms_output_bitstream {
55 /* Buffer variable containing zero or more bits that have been logically
56 * written to the bitstream but not yet written to memory. This must be
57 * at least as large as the coding unit size. */
60 /* Number of bits in @bitbuf that are valid. */
61 unsigned num_free_bits;
63 /* Pointer to one past the next position in the compressed data buffer
64 * at which to output a 16-bit coding unit. */
67 /* Maximum number of 16-bit coding units that can still be output to
68 * the compressed data buffer. */
69 size_t num_le16_remaining;
71 /* Set to %true if not all coding units could be output due to
72 * insufficient space. */
76 /* Stucture used for range encoding (raw version). */
77 struct lzms_range_encoder_raw {
79 /* A 33-bit variable that holds the low boundary of the current range.
80 * The 33rd bit is needed to catch carries. */
83 /* Size of the current range. */
86 /* Next 16-bit coding unit to output. */
89 /* Number of 16-bit coding units whose output has been delayed due to
90 * possible carrying. The first such coding unit is @cache; all
91 * subsequent such coding units are 0xffff. */
94 /* Pointer to the next position in the compressed data buffer at which
95 * to output a 16-bit coding unit. */
98 /* Maximum number of 16-bit coding units that can still be output to
99 * the compressed data buffer. */
100 size_t num_le16_remaining;
102 /* %true when the very first coding unit has not yet been output. */
105 /* Set to %true if not all coding units could be output due to
106 * insufficient space. */
110 /* Structure used for range encoding. This wraps around `struct
111 * lzms_range_encoder_raw' to use and maintain probability entries. */
112 struct lzms_range_encoder {
113 /* Pointer to the raw range encoder, which has no persistent knowledge
114 * of probabilities. Multiple lzms_range_encoder's share the same
115 * lzms_range_encoder_raw. */
116 struct lzms_range_encoder_raw *rc;
118 /* Bits recently encoded by this range encoder. This is used as an
119 * index into @prob_entries. */
122 /* Bitmask for @state to prevent its value from exceeding the number of
123 * probability entries. */
126 /* Probability entries being used for this range encoder. */
127 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
130 /* Structure used for Huffman encoding. */
131 struct lzms_huffman_encoder {
133 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
134 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
136 struct lzms_output_bitstream *os;
138 /* Number of symbols that have been written using this code far. Reset
139 * to 0 whenever the code is rebuilt. */
140 u32 num_syms_written;
142 /* When @num_syms_written reaches this number, the Huffman code must be
146 /* Number of symbols in the represented Huffman code. */
149 /* Running totals of symbol frequencies. These are diluted slightly
150 * whenever the code is rebuilt. */
151 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
153 /* The length, in bits, of each symbol in the Huffman code. */
154 u8 lens[LZMS_MAX_NUM_SYMS];
156 /* The codeword of each symbol in the Huffman code. */
157 u32 codewords[LZMS_MAX_NUM_SYMS];
160 struct lzms_compressor_params {
161 u32 min_match_length;
162 u32 nice_match_length;
163 u32 max_search_depth;
164 u32 optim_array_length;
167 /* State of the LZMS compressor. */
168 struct lzms_compressor {
169 /* Pointer to a buffer holding the preprocessed data to compress. */
172 /* Current position in @buffer. */
175 /* Size of the data in @buffer. */
178 /* Lempel-Ziv match-finder. */
181 /* Temporary space to store found matches. */
182 struct lz_match *matches;
184 /* Match-chooser data. */
185 struct lzms_mc_pos_data *optimum;
186 unsigned optimum_cur_idx;
187 unsigned optimum_end_idx;
189 /* Maximum block size this compressor instantiation allows. This is the
190 * allocated size of @window. */
193 /* Compression parameters. */
194 struct lzms_compressor_params params;
196 /* Raw range encoder which outputs to the beginning of the compressed
197 * data buffer, proceeding forwards. */
198 struct lzms_range_encoder_raw rc;
200 /* Bitstream which outputs to the end of the compressed data buffer,
201 * proceeding backwards. */
202 struct lzms_output_bitstream os;
204 /* Range encoders. */
205 struct lzms_range_encoder main_range_encoder;
206 struct lzms_range_encoder match_range_encoder;
207 struct lzms_range_encoder lz_match_range_encoder;
208 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
209 struct lzms_range_encoder delta_match_range_encoder;
210 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
212 /* Huffman encoders. */
213 struct lzms_huffman_encoder literal_encoder;
214 struct lzms_huffman_encoder lz_offset_encoder;
215 struct lzms_huffman_encoder length_encoder;
216 struct lzms_huffman_encoder delta_power_encoder;
217 struct lzms_huffman_encoder delta_offset_encoder;
219 /* LRU (least-recently-used) queues for match information. */
220 struct lzms_lru_queues lru;
222 /* Used for preprocessing. */
223 s32 last_target_usages[65536];
226 struct lzms_mc_pos_data {
228 #define MC_INFINITE_COST ((u32)~0UL)
239 struct lzms_adaptive_state {
240 struct lzms_lz_lru_queues lru;
244 u8 lz_repeat_match_state[LZMS_NUM_RECENT_OFFSETS - 1];
248 /* Initialize the output bitstream @os to write forwards to the specified
249 * compressed data buffer @out that is @out_limit 16-bit integers long. */
251 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
252 le16 *out, size_t out_limit)
255 os->num_free_bits = 16;
256 os->out = out + out_limit;
257 os->num_le16_remaining = out_limit;
261 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
262 * from high-order to low-order), to the output bitstream @os. */
264 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
265 u32 bits, unsigned num_bits)
267 bits &= (1U << num_bits) - 1;
269 while (num_bits > os->num_free_bits) {
271 if (unlikely(os->num_le16_remaining == 0)) {
276 unsigned num_fill_bits = os->num_free_bits;
278 os->bitbuf <<= num_fill_bits;
279 os->bitbuf |= bits >> (num_bits - num_fill_bits);
281 *--os->out = cpu_to_le16(os->bitbuf);
282 --os->num_le16_remaining;
284 os->num_free_bits = 16;
285 num_bits -= num_fill_bits;
286 bits &= (1U << num_bits) - 1;
288 os->bitbuf <<= num_bits;
290 os->num_free_bits -= num_bits;
293 /* Flush the output bitstream, ensuring that all bits written to it have been
294 * written to memory. Returns %true if all bits were output successfully, or
295 * %false if an overrun occurred. */
297 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
299 if (os->num_free_bits != 16)
300 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
304 /* Initialize the range encoder @rc to write forwards to the specified
305 * compressed data buffer @out that is @out_limit 16-bit integers long. */
307 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
308 le16 *out, size_t out_limit)
311 rc->range = 0xffffffff;
315 rc->num_le16_remaining = out_limit;
321 * Attempt to flush bits from the range encoder.
323 * Note: this is based on the public domain code for LZMA written by Igor
324 * Pavlov. The only differences in this function are that in LZMS the bits must
325 * be output in 16-bit coding units instead of 8-bit coding units, and that in
326 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
327 * cannot output a dummy value to that position.
329 * The basic idea is that we're writing bits from @rc->low to the output.
330 * However, due to carrying, the writing of coding units with value 0xffff, as
331 * well as one prior coding unit, must be delayed until it is determined whether
335 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
337 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
338 rc->low, rc->cache, rc->cache_size);
339 if ((u32)(rc->low) < 0xffff0000 ||
340 (u32)(rc->low >> 32) != 0)
342 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
343 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
346 if (rc->num_le16_remaining == 0) {
350 *rc->out++ = cpu_to_le16(rc->cache +
351 (u16)(rc->low >> 32));
352 --rc->num_le16_remaining;
358 } while (--rc->cache_size != 0);
360 rc->cache = (rc->low >> 16) & 0xffff;
363 rc->low = (rc->low & 0xffff) << 16;
367 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
369 if (rc->range <= 0xffff) {
371 lzms_range_encoder_raw_shift_low(rc);
376 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
378 for (unsigned i = 0; i < 4; i++)
379 lzms_range_encoder_raw_shift_low(rc);
383 /* Encode the next bit using the range encoder (raw version).
385 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
387 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
390 lzms_range_encoder_raw_normalize(rc);
392 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
401 /* Encode a bit using the specified range encoder. This wraps around
402 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
403 * appropriate probability table. */
405 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
407 struct lzms_probability_entry *prob_entry;
410 /* Load the probability entry corresponding to the current state. */
411 prob_entry = &enc->prob_entries[enc->state];
413 /* Treat the number of zero bits in the most recently encoded
414 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
415 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
416 * don't allow 0% or 100% probabilities. */
417 prob = prob_entry->num_recent_zero_bits;
420 else if (prob == LZMS_PROBABILITY_MAX)
421 prob = LZMS_PROBABILITY_MAX - 1;
423 /* Encode the next bit. */
424 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
426 /* Update the state based on the newly encoded bit. */
427 enc->state = ((enc->state << 1) | bit) & enc->mask;
429 /* Update the recent bits, including the cached count of 0's. */
430 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
432 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
433 /* Replacing 1 bit with 0 bit; increment the zero count.
435 prob_entry->num_recent_zero_bits++;
438 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
439 /* Replacing 0 bit with 1 bit; decrement the zero count.
441 prob_entry->num_recent_zero_bits--;
444 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
447 /* Encode a symbol using the specified Huffman encoder. */
449 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
451 LZMS_ASSERT(sym < enc->num_syms);
452 lzms_output_bitstream_put_bits(enc->os,
455 ++enc->sym_freqs[sym];
456 if (++enc->num_syms_written == enc->rebuild_freq) {
457 /* Adaptive code needs to be rebuilt. */
458 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
459 make_canonical_huffman_code(enc->num_syms,
460 LZMS_MAX_CODEWORD_LEN,
465 /* Dilute the frequencies. */
466 for (unsigned i = 0; i < enc->num_syms; i++) {
467 enc->sym_freqs[i] >>= 1;
468 enc->sym_freqs[i] += 1;
470 enc->num_syms_written = 0;
475 lzms_encode_length(struct lzms_huffman_encoder *enc, u32 length)
478 unsigned num_extra_bits;
481 slot = lzms_get_length_slot(length);
483 num_extra_bits = lzms_extra_length_bits[slot];
485 extra_bits = length - lzms_length_slot_base[slot];
487 lzms_huffman_encode_symbol(enc, slot);
488 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
492 lzms_encode_offset(struct lzms_huffman_encoder *enc, u32 offset)
495 unsigned num_extra_bits;
498 slot = lzms_get_position_slot(offset);
500 num_extra_bits = lzms_extra_position_bits[slot];
502 extra_bits = offset - lzms_position_slot_base[slot];
504 lzms_huffman_encode_symbol(enc, slot);
505 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
509 lzms_begin_encode_item(struct lzms_compressor *ctx)
511 ctx->lru.lz.upcoming_offset = 0;
512 ctx->lru.delta.upcoming_offset = 0;
513 ctx->lru.delta.upcoming_power = 0;
517 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
519 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
520 ctx->cur_window_pos += length;
521 lzms_update_lru_queues(&ctx->lru);
524 /* Encode a literal byte. */
526 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
528 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
529 ctx->cur_window_pos, literal, literal);
531 lzms_begin_encode_item(ctx);
533 /* Main bit: 0 = a literal, not a match. */
534 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
536 /* Encode the literal using the current literal Huffman code. */
537 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
539 lzms_end_encode_item(ctx, 1);
542 /* Encode a (length, offset) pair (LZ match). */
544 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
546 int recent_offset_idx;
548 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
549 ctx->cur_window_pos, length, offset);
551 LZMS_ASSERT(length <= ctx->window_size - ctx->cur_window_pos);
552 LZMS_ASSERT(offset <= ctx->cur_window_pos);
553 LZMS_ASSERT(!memcmp(&ctx->window[ctx->cur_window_pos],
554 &ctx->window[ctx->cur_window_pos - offset],
557 lzms_begin_encode_item(ctx);
559 /* Main bit: 1 = a match, not a literal. */
560 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
562 /* Match bit: 0 = an LZ match, not a delta match. */
563 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
565 /* Determine if the offset can be represented as a recent offset. */
566 for (recent_offset_idx = 0;
567 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
569 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
572 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
573 /* Explicit offset. */
575 /* LZ match bit: 0 = explicit offset, not a recent offset. */
576 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
578 /* Encode the match offset. */
579 lzms_encode_offset(&ctx->lz_offset_encoder, offset);
585 /* LZ match bit: 1 = recent offset, not an explicit offset. */
586 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
588 /* Encode the recent offset index. A 1 bit is encoded for each
589 * index passed up. This sequence of 1 bits is terminated by a
590 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
591 * bits have been encoded. */
592 for (i = 0; i < recent_offset_idx; i++)
593 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
595 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
596 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
598 /* Initial update of the LZ match offset LRU queue. */
599 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
600 ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
603 /* Encode the match length. */
604 lzms_encode_length(&ctx->length_encoder, length);
606 /* Save the match offset for later insertion at the front of the LZ
607 * match offset LRU queue. */
608 ctx->lru.lz.upcoming_offset = offset;
610 lzms_end_encode_item(ctx, length);
613 #define LZMS_COST_SHIFT 5
615 /*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
618 lzms_rc_costs[LZMS_PROBABILITY_MAX + 1];
620 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
625 lzms_do_init_rc_costs(void)
627 /* Fill in a table that maps range coding probabilities needed to code a
628 * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
629 * handle fractional costs) needed to code that bit X.
631 * Consider the range of the range decoder. To eliminate exactly half
632 * the range (logical probability of 0.5), we need exactly 1 bit. For
633 * lower probabilities we need more bits and for higher probabilities we
634 * need fewer bits. In general, a logical probability of N will
635 * eliminate the proportion 1 - N of the range; this information takes
636 * log2(1 / N) bits to encode.
638 * The below loop is simply calculating this number of bits for each
639 * possible probability allowed by the LZMS compression format, but
640 * without using real numbers. To handle fractional probabilities, each
641 * cost is multiplied by (1 << LZMS_COST_SHIFT). These techniques are
642 * based on those used by LZMA.
644 * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
645 * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
648 for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
653 else if (prob == LZMS_PROBABILITY_MAX)
654 prob = LZMS_PROBABILITY_MAX - 1;
656 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
657 lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
658 (1 << LZMS_COST_SHIFT);
662 for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
665 while (w >= (1U << 16)) {
670 lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
677 lzms_init_rc_costs(void)
679 static pthread_once_t once = PTHREAD_ONCE_INIT;
681 pthread_once(&once, lzms_do_init_rc_costs);
685 * Return the cost to range-encode the specified bit when in the specified
688 * @enc The range encoder to use.
689 * @cur_state Current state, which indicates the probability entry to choose.
690 * Updated by this function.
691 * @bit The bit to encode (0 or 1).
694 lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 *cur_state, int bit)
699 prob_zero = enc->prob_entries[*cur_state & enc->mask].num_recent_zero_bits;
701 *cur_state = (*cur_state << 1) | bit;
704 prob_correct = prob_zero;
706 prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
708 return lzms_rc_costs[prob_correct];
712 lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, u32 sym)
714 return enc->lens[sym] << LZMS_COST_SHIFT;
718 lzms_offset_cost(const struct lzms_huffman_encoder *enc, u32 offset)
724 slot = lzms_get_position_slot(offset);
726 cost += lzms_huffman_symbol_cost(enc, slot);
728 num_extra_bits = lzms_extra_position_bits[slot];
730 cost += num_extra_bits << LZMS_COST_SHIFT;
736 lzms_get_length_cost(const struct lzms_huffman_encoder *enc, u32 length)
742 slot = lzms_get_length_slot(length);
744 cost += lzms_huffman_symbol_cost(enc, slot);
746 num_extra_bits = lzms_extra_length_bits[slot];
748 cost += num_extra_bits << LZMS_COST_SHIFT;
754 lzms_get_matches(struct lzms_compressor *ctx, struct lz_match **matches_ret)
756 *matches_ret = ctx->matches;
757 return lz_mf_get_matches(ctx->mf, ctx->matches);
761 lzms_skip_bytes(struct lzms_compressor *ctx, u32 n)
763 lz_mf_skip_positions(ctx->mf, n);
767 lzms_get_literal_cost(struct lzms_compressor *ctx,
768 struct lzms_adaptive_state *state, u8 literal)
772 state->lru.upcoming_offset = 0;
773 lzms_update_lz_lru_queues(&state->lru);
775 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
776 &state->main_state, 0);
778 cost += lzms_huffman_symbol_cost(&ctx->literal_encoder, literal);
784 lzms_get_lz_match_cost_nolen(struct lzms_compressor *ctx,
785 struct lzms_adaptive_state *state, u32 offset)
788 int recent_offset_idx;
790 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
791 &state->main_state, 1);
792 cost += lzms_rc_bit_cost(&ctx->match_range_encoder,
793 &state->match_state, 0);
795 for (recent_offset_idx = 0;
796 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
798 if (offset == state->lru.recent_offsets[recent_offset_idx])
801 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
802 /* Explicit offset. */
803 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
804 &state->lz_match_state, 0);
806 cost += lzms_offset_cost(&ctx->lz_offset_encoder, offset);
811 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
812 &state->lz_match_state, 1);
814 for (i = 0; i < recent_offset_idx; i++)
815 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
816 &state->lz_repeat_match_state[i], 0);
818 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
819 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
820 &state->lz_repeat_match_state[i], 1);
823 /* Initial update of the LZ match offset LRU queue. */
824 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
825 state->lru.recent_offsets[i] = state->lru.recent_offsets[i + 1];
829 state->lru.upcoming_offset = offset;
830 lzms_update_lz_lru_queues(&state->lru);
836 lzms_get_lz_match_cost(struct lzms_compressor *ctx,
837 struct lzms_adaptive_state *state,
838 u32 length, u32 offset)
840 return lzms_get_lz_match_cost_nolen(ctx, state, offset) +
841 lzms_get_length_cost(&ctx->length_encoder, length);
845 lzms_repsearch(const u8 * const strptr, const u32 bytes_remaining,
846 const struct lzms_lz_lru_queues *queue, u32 *offset_ret)
851 len = lz_repsearch(strptr, bytes_remaining, UINT32_MAX,
852 queue->recent_offsets, LZMS_NUM_RECENT_OFFSETS, &slot);
853 *offset_ret = queue->recent_offsets[slot];
858 static struct lz_match
859 lzms_match_chooser_reverse_list(struct lzms_compressor *ctx, unsigned cur_pos)
861 unsigned prev_link, saved_prev_link;
862 unsigned prev_match_offset, saved_prev_match_offset;
864 ctx->optimum_end_idx = cur_pos;
866 saved_prev_link = ctx->optimum[cur_pos].prev.link;
867 saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
870 prev_link = saved_prev_link;
871 prev_match_offset = saved_prev_match_offset;
873 saved_prev_link = ctx->optimum[prev_link].prev.link;
874 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
876 ctx->optimum[prev_link].next.link = cur_pos;
877 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
880 } while (cur_pos != 0);
882 ctx->optimum_cur_idx = ctx->optimum[0].next.link;
884 return (struct lz_match)
885 { .len = ctx->optimum_cur_idx,
886 .offset = ctx->optimum[0].next.match_offset,
890 /* This is similar to lzx_choose_near_optimal_item() in lzx-compress.c.
891 * Read that one if you want to understand it. */
892 static struct lz_match
893 lzms_get_near_optimal_item(struct lzms_compressor *ctx)
896 struct lz_match *matches;
897 struct lz_match match;
900 u32 longest_rep_offset;
903 struct lzms_adaptive_state initial_state;
905 if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
906 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
907 ctx->optimum_cur_idx;
908 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
910 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
914 ctx->optimum_cur_idx = 0;
915 ctx->optimum_end_idx = 0;
917 if (lz_mf_get_position(ctx->mf) >= LZMS_MAX_INIT_RECENT_OFFSET) {
918 longest_rep_len = lzms_repsearch(lz_mf_get_window_ptr(ctx->mf),
919 lz_mf_get_bytes_remaining(ctx->mf),
920 &ctx->lru.lz, &longest_rep_offset);
925 if (longest_rep_len >= ctx->params.nice_match_length) {
926 lzms_skip_bytes(ctx, longest_rep_len);
927 return (struct lz_match) {
928 .len = longest_rep_len,
929 .offset = longest_rep_offset,
933 num_matches = lzms_get_matches(ctx, &matches);
936 longest_len = matches[num_matches - 1].len;
937 if (longest_len >= ctx->params.nice_match_length) {
938 lzms_skip_bytes(ctx, longest_len - 1);
939 return matches[num_matches - 1];
945 initial_state.lru = ctx->lru.lz;
946 initial_state.main_state = ctx->main_range_encoder.state;
947 initial_state.match_state = ctx->match_range_encoder.state;
948 initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
949 for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
950 initial_state.lz_repeat_match_state[i] = ctx->lz_repeat_match_range_encoders[i].state;
952 ctx->optimum[1].state = initial_state;
953 ctx->optimum[1].cost = lzms_get_literal_cost(ctx,
954 &ctx->optimum[1].state,
955 *(lz_mf_get_window_ptr(ctx->mf) - 1));
956 ctx->optimum[1].prev.link = 0;
958 for (u32 i = 0, len = 2; i < num_matches; i++) {
959 u32 offset = matches[i].offset;
960 struct lzms_adaptive_state state;
963 state = initial_state;
965 position_cost += lzms_get_lz_match_cost_nolen(ctx, &state, offset);
970 cost = position_cost;
971 cost += lzms_get_length_cost(&ctx->length_encoder, len);
973 ctx->optimum[len].state = state;
974 ctx->optimum[len].prev.link = 0;
975 ctx->optimum[len].prev.match_offset = offset;
976 ctx->optimum[len].cost = cost;
977 } while (++len <= matches[i].len);
979 end_pos = longest_len;
981 if (longest_rep_len) {
982 struct lzms_adaptive_state state;
985 while (end_pos < longest_rep_len)
986 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
988 state = initial_state;
989 cost = lzms_get_lz_match_cost(ctx,
993 if (cost <= ctx->optimum[longest_rep_len].cost) {
994 ctx->optimum[longest_rep_len].state = state;
995 ctx->optimum[longest_rep_len].prev.link = 0;
996 ctx->optimum[longest_rep_len].prev.match_offset = longest_rep_offset;
997 ctx->optimum[longest_rep_len].cost = cost;
1004 struct lzms_adaptive_state state;
1008 if (cur_pos == end_pos || cur_pos == ctx->params.optim_array_length)
1009 return lzms_match_chooser_reverse_list(ctx, cur_pos);
1011 if (lz_mf_get_position(ctx->mf) >= LZMS_MAX_INIT_RECENT_OFFSET) {
1012 longest_rep_len = lzms_repsearch(lz_mf_get_window_ptr(ctx->mf),
1013 lz_mf_get_bytes_remaining(ctx->mf),
1014 &ctx->optimum[cur_pos].state.lru,
1015 &longest_rep_offset);
1017 longest_rep_len = 0;
1020 if (longest_rep_len >= ctx->params.nice_match_length) {
1021 match = lzms_match_chooser_reverse_list(ctx, cur_pos);
1023 ctx->optimum[cur_pos].next.match_offset = longest_rep_offset;
1024 ctx->optimum[cur_pos].next.link = cur_pos + longest_rep_len;
1025 ctx->optimum_end_idx = cur_pos + longest_rep_len;
1027 lzms_skip_bytes(ctx, longest_rep_len);
1032 num_matches = lzms_get_matches(ctx, &matches);
1035 longest_len = matches[num_matches - 1].len;
1036 if (longest_len >= ctx->params.nice_match_length) {
1037 match = lzms_match_chooser_reverse_list(ctx, cur_pos);
1039 ctx->optimum[cur_pos].next.match_offset =
1040 matches[num_matches - 1].offset;
1041 ctx->optimum[cur_pos].next.link = cur_pos + longest_len;
1042 ctx->optimum_end_idx = cur_pos + longest_len;
1044 lzms_skip_bytes(ctx, longest_len - 1);
1052 while (end_pos < cur_pos + longest_len)
1053 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1055 state = ctx->optimum[cur_pos].state;
1056 cost = ctx->optimum[cur_pos].cost +
1057 lzms_get_literal_cost(ctx,
1059 *(lz_mf_get_window_ptr(ctx->mf) - 1));
1060 if (cost < ctx->optimum[cur_pos + 1].cost) {
1061 ctx->optimum[cur_pos + 1].state = state;
1062 ctx->optimum[cur_pos + 1].cost = cost;
1063 ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1066 for (u32 i = 0, len = 2; i < num_matches; i++) {
1067 u32 offset = matches[i].offset;
1068 struct lzms_adaptive_state state;
1071 state = ctx->optimum[cur_pos].state;
1072 position_cost = ctx->optimum[cur_pos].cost;
1073 position_cost += lzms_get_lz_match_cost_nolen(ctx, &state, offset);
1078 cost = position_cost;
1079 cost += lzms_get_length_cost(&ctx->length_encoder, len);
1081 if (cost < ctx->optimum[cur_pos + len].cost) {
1082 ctx->optimum[cur_pos + len].state = state;
1083 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1084 ctx->optimum[cur_pos + len].prev.match_offset = offset;
1085 ctx->optimum[cur_pos + len].cost = cost;
1087 } while (++len <= matches[i].len);
1090 if (longest_rep_len >= ctx->params.min_match_length) {
1092 while (end_pos < cur_pos + longest_rep_len)
1093 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1095 state = ctx->optimum[cur_pos].state;
1097 cost = ctx->optimum[cur_pos].cost +
1098 lzms_get_lz_match_cost(ctx,
1101 longest_rep_offset);
1102 if (cost <= ctx->optimum[cur_pos + longest_rep_len].cost) {
1103 ctx->optimum[cur_pos + longest_rep_len].state =
1105 ctx->optimum[cur_pos + longest_rep_len].prev.link =
1107 ctx->optimum[cur_pos + longest_rep_len].prev.match_offset =
1109 ctx->optimum[cur_pos + longest_rep_len].cost =
1117 * The main loop for the LZMS compressor.
1121 * - This does not output any delta matches.
1123 * - The costs of literals and matches are estimated using the range encoder
1124 * states and the semi-adaptive Huffman codes. Except for range encoding
1125 * states, costs are assumed to be constant throughout a single run of the
1126 * parsing algorithm, which can parse up to @optim_array_length bytes of data.
1127 * This introduces a source of inaccuracy because the probabilities and
1128 * Huffman codes can change over this part of the data.
1131 lzms_encode(struct lzms_compressor *ctx)
1133 struct lz_match item;
1135 /* Load window into the match-finder. */
1136 lz_mf_load_window(ctx->mf, ctx->window, ctx->window_size);
1138 /* Reset the match-chooser. */
1139 ctx->optimum_cur_idx = 0;
1140 ctx->optimum_end_idx = 0;
1142 while (ctx->cur_window_pos != ctx->window_size) {
1143 item = lzms_get_near_optimal_item(ctx);
1145 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
1147 lzms_encode_lz_match(ctx, item.len, item.offset);
1152 lzms_init_range_encoder(struct lzms_range_encoder *enc,
1153 struct lzms_range_encoder_raw *rc, u32 num_states)
1157 enc->mask = num_states - 1;
1158 for (u32 i = 0; i < num_states; i++) {
1159 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
1160 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
1165 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
1166 struct lzms_output_bitstream *os,
1168 unsigned rebuild_freq)
1171 enc->num_syms_written = 0;
1172 enc->rebuild_freq = rebuild_freq;
1173 enc->num_syms = num_syms;
1174 for (unsigned i = 0; i < num_syms; i++)
1175 enc->sym_freqs[i] = 1;
1177 make_canonical_huffman_code(enc->num_syms,
1178 LZMS_MAX_CODEWORD_LEN,
1184 /* Initialize the LZMS compressor. */
1186 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
1187 le16 *cdata, u32 clen16)
1189 unsigned num_position_slots;
1191 /* Copy the uncompressed data into the @ctx->window buffer. */
1192 memcpy(ctx->window, udata, ulen);
1193 ctx->cur_window_pos = 0;
1194 ctx->window_size = ulen;
1196 /* Initialize the raw range encoder (writing forwards). */
1197 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
1199 /* Initialize the output bitstream for Huffman symbols and verbatim bits
1200 * (writing backwards). */
1201 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
1203 /* Calculate the number of position slots needed for this compressed
1205 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
1207 LZMS_DEBUG("Using %u position slots", num_position_slots);
1209 /* Initialize Huffman encoders for each alphabet used in the compressed
1210 * representation. */
1211 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
1212 LZMS_NUM_LITERAL_SYMS,
1213 LZMS_LITERAL_CODE_REBUILD_FREQ);
1215 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
1217 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
1219 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
1221 LZMS_LENGTH_CODE_REBUILD_FREQ);
1223 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
1225 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
1227 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
1228 LZMS_NUM_DELTA_POWER_SYMS,
1229 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
1231 /* Initialize range encoders, all of which wrap around the same
1232 * lzms_range_encoder_raw. */
1233 lzms_init_range_encoder(&ctx->main_range_encoder,
1234 &ctx->rc, LZMS_NUM_MAIN_STATES);
1236 lzms_init_range_encoder(&ctx->match_range_encoder,
1237 &ctx->rc, LZMS_NUM_MATCH_STATES);
1239 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
1240 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
1242 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
1243 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
1244 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
1246 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
1247 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
1249 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
1250 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
1251 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1253 /* Initialize LRU match information. */
1254 lzms_init_lru_queues(&ctx->lru);
1257 /* Flush the output streams, prepare the final compressed data, and return its
1260 * A return value of 0 indicates that the data could not be compressed to fit in
1261 * the available space. */
1263 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
1265 size_t num_forwards_bytes;
1266 size_t num_backwards_bytes;
1267 size_t compressed_size;
1269 /* Flush both the forwards and backwards streams, and make sure they
1270 * didn't cross each other and start overwriting each other's data. */
1271 if (!lzms_output_bitstream_flush(&ctx->os)) {
1272 LZMS_DEBUG("Backwards bitstream overrun.");
1276 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
1277 LZMS_DEBUG("Forwards bitstream overrun.");
1281 if (ctx->rc.out > ctx->os.out) {
1282 LZMS_DEBUG("Two bitstreams crossed.");
1286 /* Now the compressed buffer contains the data output by the forwards
1287 * bitstream, then empty space, then data output by the backwards
1288 * bitstream. Move the data output by the backwards bitstream to be
1289 * adjacent to the data output by the forward bitstream, and calculate
1290 * the compressed size that this results in. */
1291 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
1292 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
1294 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
1296 compressed_size = num_forwards_bytes + num_backwards_bytes;
1297 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
1298 "compressed_size=%zu",
1299 num_forwards_bytes, num_backwards_bytes, compressed_size);
1300 LZMS_ASSERT(compressed_size % 2 == 0);
1301 return compressed_size;
1306 lzms_build_params(unsigned int compression_level,
1307 struct lzms_compressor_params *lzms_params)
1309 lzms_params->min_match_length = (compression_level >= 50) ? 2 : 3;
1310 lzms_params->nice_match_length = max(((u64)compression_level * 32) / 50,
1311 lzms_params->min_match_length);
1312 lzms_params->max_search_depth = ((u64)compression_level * 50) / 50;
1313 lzms_params->optim_array_length = 224 + compression_level * 16;
1317 lzms_build_mf_params(const struct lzms_compressor_params *lzms_params,
1318 u32 max_window_size, struct lz_mf_params *mf_params)
1320 memset(mf_params, 0, sizeof(*mf_params));
1322 mf_params->algorithm = LZ_MF_DEFAULT;
1323 mf_params->max_window_size = max_window_size;
1324 mf_params->min_match_len = lzms_params->min_match_length;
1325 mf_params->max_search_depth = lzms_params->max_search_depth;
1326 mf_params->nice_match_len = lzms_params->nice_match_length;
1330 lzms_free_compressor(void *_ctx);
1333 lzms_get_needed_memory(size_t max_block_size, unsigned int compression_level)
1335 struct lzms_compressor_params params;
1338 if (max_block_size >= INT32_MAX)
1341 lzms_build_params(compression_level, ¶ms);
1343 size += sizeof(struct lzms_compressor);
1344 size += max_block_size;
1345 size += lz_mf_get_needed_memory(LZ_MF_DEFAULT, max_block_size);
1346 size += params.max_search_depth * sizeof(struct lz_match);
1347 size += (params.optim_array_length + params.nice_match_length) *
1348 sizeof(struct lzms_mc_pos_data);
1354 lzms_create_compressor(size_t max_block_size, unsigned int compression_level,
1357 struct lzms_compressor *ctx;
1358 struct lzms_compressor_params params;
1359 struct lz_mf_params mf_params;
1361 if (max_block_size >= INT32_MAX)
1362 return WIMLIB_ERR_INVALID_PARAM;
1364 lzms_build_params(compression_level, ¶ms);
1365 lzms_build_mf_params(¶ms, max_block_size, &mf_params);
1366 if (!lz_mf_params_valid(&mf_params))
1367 return WIMLIB_ERR_INVALID_PARAM;
1369 ctx = CALLOC(1, sizeof(struct lzms_compressor));
1373 ctx->params = params;
1374 ctx->max_block_size = max_block_size;
1376 ctx->window = MALLOC(max_block_size);
1380 ctx->mf = lz_mf_alloc(&mf_params);
1384 ctx->matches = MALLOC(params.max_search_depth * sizeof(struct lz_match));
1388 ctx->optimum = MALLOC((params.optim_array_length +
1389 params.nice_match_length) *
1390 sizeof(struct lzms_mc_pos_data));
1394 /* Initialize position and length slot data if not done already. */
1397 /* Initialize range encoding cost table if not done already. */
1398 lzms_init_rc_costs();
1404 lzms_free_compressor(ctx);
1405 return WIMLIB_ERR_NOMEM;
1409 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
1410 void *compressed_data, size_t compressed_size_avail, void *_ctx)
1412 struct lzms_compressor *ctx = _ctx;
1413 size_t compressed_size;
1415 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
1416 uncompressed_size, compressed_size_avail);
1418 /* Don't bother compressing extremely small inputs. */
1419 if (uncompressed_size < 4) {
1420 LZMS_DEBUG("Input too small to bother compressing.");
1424 /* Cap the available compressed size to a 32-bit integer and round it
1425 * down to the nearest multiple of 2. */
1426 if (compressed_size_avail > UINT32_MAX)
1427 compressed_size_avail = UINT32_MAX;
1428 if (compressed_size_avail & 1)
1429 compressed_size_avail--;
1431 /* Initialize the compressor structures. */
1432 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
1433 compressed_data, compressed_size_avail / 2);
1435 /* Preprocess the uncompressed data. */
1436 lzms_x86_filter(ctx->window, ctx->window_size,
1437 ctx->last_target_usages, false);
1439 /* Compute and encode a literal/match sequence that decompresses to the
1440 * preprocessed data. */
1443 /* Get and return the compressed data size. */
1444 compressed_size = lzms_finalize(ctx, compressed_data,
1445 compressed_size_avail);
1447 if (compressed_size == 0) {
1448 LZMS_DEBUG("Data did not compress to requested size or less.");
1452 LZMS_DEBUG("Compressed %zu => %zu bytes",
1453 uncompressed_size, compressed_size);
1455 return compressed_size;
1459 lzms_free_compressor(void *_ctx)
1461 struct lzms_compressor *ctx = _ctx;
1465 lz_mf_free(ctx->mf);
1472 const struct compressor_ops lzms_compressor_ops = {
1473 .get_needed_memory = lzms_get_needed_memory,
1474 .create_compressor = lzms_create_compressor,
1475 .compress = lzms_compress,
1476 .free_compressor = lzms_free_compressor,