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/lzms.h"
45 #include "wimlib/util.h"
51 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
52 * a series of 16-bit little endian coding units. */
53 struct lzms_output_bitstream {
54 /* Buffer variable containing zero or more bits that have been logically
55 * written to the bitstream but not yet written to memory. This must be
56 * at least as large as the coding unit size. */
59 /* Number of bits in @bitbuf that are valid. */
60 unsigned num_free_bits;
62 /* Pointer to one past the next position in the compressed data buffer
63 * at which to output a 16-bit coding unit. */
66 /* Maximum number of 16-bit coding units that can still be output to
67 * the compressed data buffer. */
68 size_t num_le16_remaining;
70 /* Set to %true if not all coding units could be output due to
71 * insufficient space. */
75 /* Stucture used for range encoding (raw version). */
76 struct lzms_range_encoder_raw {
78 /* A 33-bit variable that holds the low boundary of the current range.
79 * The 33rd bit is needed to catch carries. */
82 /* Size of the current range. */
85 /* Next 16-bit coding unit to output. */
88 /* Number of 16-bit coding units whose output has been delayed due to
89 * possible carrying. The first such coding unit is @cache; all
90 * subsequent such coding units are 0xffff. */
93 /* Pointer to the next position in the compressed data buffer at which
94 * to output a 16-bit coding unit. */
97 /* Maximum number of 16-bit coding units that can still be output to
98 * the compressed data buffer. */
99 size_t num_le16_remaining;
101 /* %true when the very first coding unit has not yet been output. */
104 /* Set to %true if not all coding units could be output due to
105 * insufficient space. */
109 /* Structure used for range encoding. This wraps around `struct
110 * lzms_range_encoder_raw' to use and maintain probability entries. */
111 struct lzms_range_encoder {
112 /* Pointer to the raw range encoder, which has no persistent knowledge
113 * of probabilities. Multiple lzms_range_encoder's share the same
114 * lzms_range_encoder_raw. */
115 struct lzms_range_encoder_raw *rc;
117 /* Bits recently encoded by this range encoder. This is used as an
118 * index into @prob_entries. */
121 /* Bitmask for @state to prevent its value from exceeding the number of
122 * probability entries. */
125 /* Probability entries being used for this range encoder. */
126 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
129 /* Structure used for Huffman encoding. */
130 struct lzms_huffman_encoder {
132 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
133 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
135 struct lzms_output_bitstream *os;
137 /* Number of symbols that have been written using this code far. Reset
138 * to 0 whenever the code is rebuilt. */
139 u32 num_syms_written;
141 /* When @num_syms_written reaches this number, the Huffman code must be
145 /* Number of symbols in the represented Huffman code. */
148 /* Running totals of symbol frequencies. These are diluted slightly
149 * whenever the code is rebuilt. */
150 u32 sym_freqs[LZMS_MAX_NUM_SYMS];
152 /* The length, in bits, of each symbol in the Huffman code. */
153 u8 lens[LZMS_MAX_NUM_SYMS];
155 /* The codeword of each symbol in the Huffman code. */
156 u32 codewords[LZMS_MAX_NUM_SYMS];
159 struct lzms_compressor_params {
160 u32 min_match_length;
161 u32 nice_match_length;
162 u32 max_search_depth;
163 u32 optim_array_length;
166 /* State of the LZMS compressor. */
167 struct lzms_compressor {
168 /* Pointer to a buffer holding the preprocessed data to compress. */
171 /* Current position in @buffer. */
174 /* Size of the data in @buffer. */
177 /* Lempel-Ziv match-finder. */
180 /* Temporary space to store found matches. */
181 struct lz_match *matches;
183 /* Match-chooser data. */
184 struct lzms_mc_pos_data *optimum;
185 unsigned optimum_cur_idx;
186 unsigned optimum_end_idx;
188 /* Maximum block size this compressor instantiation allows. This is the
189 * allocated size of @window. */
192 /* Compression parameters. */
193 struct lzms_compressor_params params;
195 /* Raw range encoder which outputs to the beginning of the compressed
196 * data buffer, proceeding forwards. */
197 struct lzms_range_encoder_raw rc;
199 /* Bitstream which outputs to the end of the compressed data buffer,
200 * proceeding backwards. */
201 struct lzms_output_bitstream os;
203 /* Range encoders. */
204 struct lzms_range_encoder main_range_encoder;
205 struct lzms_range_encoder match_range_encoder;
206 struct lzms_range_encoder lz_match_range_encoder;
207 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
208 struct lzms_range_encoder delta_match_range_encoder;
209 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
211 /* Huffman encoders. */
212 struct lzms_huffman_encoder literal_encoder;
213 struct lzms_huffman_encoder lz_offset_encoder;
214 struct lzms_huffman_encoder length_encoder;
215 struct lzms_huffman_encoder delta_power_encoder;
216 struct lzms_huffman_encoder delta_offset_encoder;
218 /* LRU (least-recently-used) queues for match information. */
219 struct lzms_lru_queues lru;
221 /* Used for preprocessing. */
222 s32 last_target_usages[65536];
225 struct lzms_mc_pos_data {
227 #define MC_INFINITE_COST ((u32)~0UL)
238 struct lzms_adaptive_state {
239 struct lzms_lz_lru_queues lru;
243 u8 lz_repeat_match_state[LZMS_NUM_RECENT_OFFSETS - 1];
247 /* Initialize the output bitstream @os to write forwards to the specified
248 * compressed data buffer @out that is @out_limit 16-bit integers long. */
250 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
251 le16 *out, size_t out_limit)
254 os->num_free_bits = 16;
255 os->out = out + out_limit;
256 os->num_le16_remaining = out_limit;
260 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
261 * from high-order to low-order), to the output bitstream @os. */
263 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
264 u32 bits, unsigned num_bits)
266 bits &= (1U << num_bits) - 1;
268 while (num_bits > os->num_free_bits) {
270 if (unlikely(os->num_le16_remaining == 0)) {
275 unsigned num_fill_bits = os->num_free_bits;
277 os->bitbuf <<= num_fill_bits;
278 os->bitbuf |= bits >> (num_bits - num_fill_bits);
280 *--os->out = cpu_to_le16(os->bitbuf);
281 --os->num_le16_remaining;
283 os->num_free_bits = 16;
284 num_bits -= num_fill_bits;
285 bits &= (1U << num_bits) - 1;
287 os->bitbuf <<= num_bits;
289 os->num_free_bits -= num_bits;
292 /* Flush the output bitstream, ensuring that all bits written to it have been
293 * written to memory. Returns %true if all bits were output successfully, or
294 * %false if an overrun occurred. */
296 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
298 if (os->num_free_bits != 16)
299 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
303 /* Initialize the range encoder @rc to write forwards to the specified
304 * compressed data buffer @out that is @out_limit 16-bit integers long. */
306 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
307 le16 *out, size_t out_limit)
310 rc->range = 0xffffffff;
314 rc->num_le16_remaining = out_limit;
320 * Attempt to flush bits from the range encoder.
322 * Note: this is based on the public domain code for LZMA written by Igor
323 * Pavlov. The only differences in this function are that in LZMS the bits must
324 * be output in 16-bit coding units instead of 8-bit coding units, and that in
325 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
326 * cannot output a dummy value to that position.
328 * The basic idea is that we're writing bits from @rc->low to the output.
329 * However, due to carrying, the writing of coding units with value 0xffff, as
330 * well as one prior coding unit, must be delayed until it is determined whether
334 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
336 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
337 rc->low, rc->cache, rc->cache_size);
338 if ((u32)(rc->low) < 0xffff0000 ||
339 (u32)(rc->low >> 32) != 0)
341 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
342 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
345 if (rc->num_le16_remaining == 0) {
349 *rc->out++ = cpu_to_le16(rc->cache +
350 (u16)(rc->low >> 32));
351 --rc->num_le16_remaining;
357 } while (--rc->cache_size != 0);
359 rc->cache = (rc->low >> 16) & 0xffff;
362 rc->low = (rc->low & 0xffff) << 16;
366 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
368 if (rc->range <= 0xffff) {
370 lzms_range_encoder_raw_shift_low(rc);
375 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
377 for (unsigned i = 0; i < 4; i++)
378 lzms_range_encoder_raw_shift_low(rc);
382 /* Encode the next bit using the range encoder (raw version).
384 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
386 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
389 lzms_range_encoder_raw_normalize(rc);
391 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
400 /* Encode a bit using the specified range encoder. This wraps around
401 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
402 * appropriate probability table. */
404 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
406 struct lzms_probability_entry *prob_entry;
409 /* Load the probability entry corresponding to the current state. */
410 prob_entry = &enc->prob_entries[enc->state];
412 /* Treat the number of zero bits in the most recently encoded
413 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
414 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
415 * don't allow 0% or 100% probabilities. */
416 prob = prob_entry->num_recent_zero_bits;
419 else if (prob == LZMS_PROBABILITY_MAX)
420 prob = LZMS_PROBABILITY_MAX - 1;
422 /* Encode the next bit. */
423 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
425 /* Update the state based on the newly encoded bit. */
426 enc->state = ((enc->state << 1) | bit) & enc->mask;
428 /* Update the recent bits, including the cached count of 0's. */
429 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
431 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
432 /* Replacing 1 bit with 0 bit; increment the zero count.
434 prob_entry->num_recent_zero_bits++;
437 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
438 /* Replacing 0 bit with 1 bit; decrement the zero count.
440 prob_entry->num_recent_zero_bits--;
443 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
446 /* Encode a symbol using the specified Huffman encoder. */
448 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
450 LZMS_ASSERT(sym < enc->num_syms);
451 lzms_output_bitstream_put_bits(enc->os,
454 ++enc->sym_freqs[sym];
455 if (++enc->num_syms_written == enc->rebuild_freq) {
456 /* Adaptive code needs to be rebuilt. */
457 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
458 make_canonical_huffman_code(enc->num_syms,
459 LZMS_MAX_CODEWORD_LEN,
464 /* Dilute the frequencies. */
465 for (unsigned i = 0; i < enc->num_syms; i++) {
466 enc->sym_freqs[i] >>= 1;
467 enc->sym_freqs[i] += 1;
469 enc->num_syms_written = 0;
474 lzms_encode_length(struct lzms_huffman_encoder *enc, u32 length)
477 unsigned num_extra_bits;
480 slot = lzms_get_length_slot(length);
482 num_extra_bits = lzms_extra_length_bits[slot];
484 extra_bits = length - lzms_length_slot_base[slot];
486 lzms_huffman_encode_symbol(enc, slot);
487 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
491 lzms_encode_offset(struct lzms_huffman_encoder *enc, u32 offset)
494 unsigned num_extra_bits;
497 slot = lzms_get_position_slot(offset);
499 num_extra_bits = lzms_extra_position_bits[slot];
501 extra_bits = offset - lzms_position_slot_base[slot];
503 lzms_huffman_encode_symbol(enc, slot);
504 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
508 lzms_begin_encode_item(struct lzms_compressor *ctx)
510 ctx->lru.lz.upcoming_offset = 0;
511 ctx->lru.delta.upcoming_offset = 0;
512 ctx->lru.delta.upcoming_power = 0;
516 lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
518 LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
519 ctx->cur_window_pos += length;
520 lzms_update_lru_queues(&ctx->lru);
523 /* Encode a literal byte. */
525 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
527 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
528 ctx->cur_window_pos, literal, literal);
530 lzms_begin_encode_item(ctx);
532 /* Main bit: 0 = a literal, not a match. */
533 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
535 /* Encode the literal using the current literal Huffman code. */
536 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
538 lzms_end_encode_item(ctx, 1);
541 /* Encode a (length, offset) pair (LZ match). */
543 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
545 int recent_offset_idx;
547 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
548 ctx->cur_window_pos, length, offset);
550 LZMS_ASSERT(length <= ctx->window_size - ctx->cur_window_pos);
551 LZMS_ASSERT(offset <= ctx->cur_window_pos);
552 LZMS_ASSERT(!memcmp(&ctx->window[ctx->cur_window_pos],
553 &ctx->window[ctx->cur_window_pos - offset],
556 lzms_begin_encode_item(ctx);
558 /* Main bit: 1 = a match, not a literal. */
559 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
561 /* Match bit: 0 = an LZ match, not a delta match. */
562 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
564 /* Determine if the offset can be represented as a recent offset. */
565 for (recent_offset_idx = 0;
566 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
568 if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
571 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
572 /* Explicit offset. */
574 /* LZ match bit: 0 = explicit offset, not a recent offset. */
575 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
577 /* Encode the match offset. */
578 lzms_encode_offset(&ctx->lz_offset_encoder, offset);
584 /* LZ match bit: 1 = recent offset, not an explicit offset. */
585 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
587 /* Encode the recent offset index. A 1 bit is encoded for each
588 * index passed up. This sequence of 1 bits is terminated by a
589 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
590 * bits have been encoded. */
591 for (i = 0; i < recent_offset_idx; i++)
592 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
594 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
595 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
597 /* Initial update of the LZ match offset LRU queue. */
598 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
599 ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
602 /* Encode the match length. */
603 lzms_encode_length(&ctx->length_encoder, length);
605 /* Save the match offset for later insertion at the front of the LZ
606 * match offset LRU queue. */
607 ctx->lru.lz.upcoming_offset = offset;
609 lzms_end_encode_item(ctx, length);
612 #define LZMS_COST_SHIFT 5
614 /*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
617 lzms_rc_costs[LZMS_PROBABILITY_MAX + 1];
619 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
624 lzms_do_init_rc_costs(void)
626 /* Fill in a table that maps range coding probabilities needed to code a
627 * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
628 * handle fractional costs) needed to code that bit X.
630 * Consider the range of the range decoder. To eliminate exactly half
631 * the range (logical probability of 0.5), we need exactly 1 bit. For
632 * lower probabilities we need more bits and for higher probabilities we
633 * need fewer bits. In general, a logical probability of N will
634 * eliminate the proportion 1 - N of the range; this information takes
635 * log2(1 / N) bits to encode.
637 * The below loop is simply calculating this number of bits for each
638 * possible probability allowed by the LZMS compression format, but
639 * without using real numbers. To handle fractional probabilities, each
640 * cost is multiplied by (1 << LZMS_COST_SHIFT). These techniques are
641 * based on those used by LZMA.
643 * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
644 * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
647 for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
652 else if (prob == LZMS_PROBABILITY_MAX)
653 prob = LZMS_PROBABILITY_MAX - 1;
655 #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
656 lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
657 (1 << LZMS_COST_SHIFT);
661 for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
664 while (w >= (1U << 16)) {
669 lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
676 lzms_init_rc_costs(void)
678 static pthread_once_t once = PTHREAD_ONCE_INIT;
680 pthread_once(&once, lzms_do_init_rc_costs);
684 * Return the cost to range-encode the specified bit when in the specified
687 * @enc The range encoder to use.
688 * @cur_state Current state, which indicates the probability entry to choose.
689 * Updated by this function.
690 * @bit The bit to encode (0 or 1).
693 lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 *cur_state, int bit)
698 prob_zero = enc->prob_entries[*cur_state & enc->mask].num_recent_zero_bits;
700 *cur_state = (*cur_state << 1) | bit;
703 prob_correct = prob_zero;
705 prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
707 return lzms_rc_costs[prob_correct];
711 lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, u32 sym)
713 return enc->lens[sym] << LZMS_COST_SHIFT;
717 lzms_offset_cost(const struct lzms_huffman_encoder *enc, u32 offset)
723 slot = lzms_get_position_slot(offset);
725 cost += lzms_huffman_symbol_cost(enc, slot);
727 num_extra_bits = lzms_extra_position_bits[slot];
729 cost += num_extra_bits << LZMS_COST_SHIFT;
735 lzms_get_length_cost(const struct lzms_huffman_encoder *enc, u32 length)
741 slot = lzms_get_length_slot(length);
743 cost += lzms_huffman_symbol_cost(enc, slot);
745 num_extra_bits = lzms_extra_length_bits[slot];
747 cost += num_extra_bits << LZMS_COST_SHIFT;
753 lzms_get_matches(struct lzms_compressor *ctx, struct lz_match **matches_ret)
755 *matches_ret = ctx->matches;
756 return lz_mf_get_matches(ctx->mf, ctx->matches);
760 lzms_skip_bytes(struct lzms_compressor *ctx, u32 n)
762 lz_mf_skip_positions(ctx->mf, n);
766 lzms_get_literal_cost(struct lzms_compressor *ctx,
767 struct lzms_adaptive_state *state, u8 literal)
771 state->lru.upcoming_offset = 0;
772 lzms_update_lz_lru_queues(&state->lru);
774 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
775 &state->main_state, 0);
777 cost += lzms_huffman_symbol_cost(&ctx->literal_encoder, literal);
783 lzms_get_lz_match_cost_nolen(struct lzms_compressor *ctx,
784 struct lzms_adaptive_state *state, u32 offset)
787 int recent_offset_idx;
789 cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
790 &state->main_state, 1);
791 cost += lzms_rc_bit_cost(&ctx->match_range_encoder,
792 &state->match_state, 0);
794 for (recent_offset_idx = 0;
795 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
797 if (offset == state->lru.recent_offsets[recent_offset_idx])
800 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
801 /* Explicit offset. */
802 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
803 &state->lz_match_state, 0);
805 cost += lzms_offset_cost(&ctx->lz_offset_encoder, offset);
810 cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
811 &state->lz_match_state, 1);
813 for (i = 0; i < recent_offset_idx; i++)
814 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
815 &state->lz_repeat_match_state[i], 0);
817 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
818 cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
819 &state->lz_repeat_match_state[i], 1);
822 /* Initial update of the LZ match offset LRU queue. */
823 for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
824 state->lru.recent_offsets[i] = state->lru.recent_offsets[i + 1];
828 state->lru.upcoming_offset = offset;
829 lzms_update_lz_lru_queues(&state->lru);
835 lzms_get_lz_match_cost(struct lzms_compressor *ctx,
836 struct lzms_adaptive_state *state,
837 u32 length, u32 offset)
839 return lzms_get_lz_match_cost_nolen(ctx, state, offset) +
840 lzms_get_length_cost(&ctx->length_encoder, length);
843 static struct lz_match
844 lzms_match_chooser_reverse_list(struct lzms_compressor *ctx, unsigned cur_pos)
846 unsigned prev_link, saved_prev_link;
847 unsigned prev_match_offset, saved_prev_match_offset;
849 ctx->optimum_end_idx = cur_pos;
851 saved_prev_link = ctx->optimum[cur_pos].prev.link;
852 saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
855 prev_link = saved_prev_link;
856 prev_match_offset = saved_prev_match_offset;
858 saved_prev_link = ctx->optimum[prev_link].prev.link;
859 saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
861 ctx->optimum[prev_link].next.link = cur_pos;
862 ctx->optimum[prev_link].next.match_offset = prev_match_offset;
865 } while (cur_pos != 0);
867 ctx->optimum_cur_idx = ctx->optimum[0].next.link;
869 return (struct lz_match)
870 { .len = ctx->optimum_cur_idx,
871 .offset = ctx->optimum[0].next.match_offset,
875 /* This is similar to lzx_choose_near_optimal_item() in lzx-compress.c.
876 * Read that one if you want to understand it. */
877 static struct lz_match
878 lzms_get_near_optimal_item(struct lzms_compressor *ctx)
881 struct lz_match *matches;
882 struct lz_match match;
885 u32 longest_rep_offset;
888 struct lzms_adaptive_state initial_state;
890 if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
891 match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
892 ctx->optimum_cur_idx;
893 match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
895 ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
899 ctx->optimum_cur_idx = 0;
900 ctx->optimum_end_idx = 0;
902 longest_rep_len = ctx->params.min_match_length - 1;
903 if (lz_mf_get_position(ctx->mf) >= LZMS_MAX_INIT_RECENT_OFFSET) {
904 u32 limit = lz_mf_get_bytes_remaining(ctx->mf);
905 for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++) {
906 u32 offset = ctx->lru.lz.recent_offsets[i];
907 const u8 *strptr = lz_mf_get_window_ptr(ctx->mf);
908 const u8 *matchptr = strptr - offset;
910 while (len < limit && strptr[len] == matchptr[len])
912 if (len > longest_rep_len) {
913 longest_rep_len = len;
914 longest_rep_offset = offset;
919 if (longest_rep_len >= ctx->params.nice_match_length) {
920 lzms_skip_bytes(ctx, longest_rep_len);
921 return (struct lz_match) {
922 .len = longest_rep_len,
923 .offset = longest_rep_offset,
927 num_matches = lzms_get_matches(ctx, &matches);
930 longest_len = matches[num_matches - 1].len;
931 if (longest_len >= ctx->params.nice_match_length) {
932 lzms_skip_bytes(ctx, longest_len - 1);
933 return matches[num_matches - 1];
939 initial_state.lru = ctx->lru.lz;
940 initial_state.main_state = ctx->main_range_encoder.state;
941 initial_state.match_state = ctx->match_range_encoder.state;
942 initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
943 for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
944 initial_state.lz_repeat_match_state[i] = ctx->lz_repeat_match_range_encoders[i].state;
946 ctx->optimum[1].state = initial_state;
947 ctx->optimum[1].cost = lzms_get_literal_cost(ctx,
948 &ctx->optimum[1].state,
949 *(lz_mf_get_window_ptr(ctx->mf) - 1));
950 ctx->optimum[1].prev.link = 0;
952 for (u32 i = 0, len = 2; i < num_matches; i++) {
953 u32 offset = matches[i].offset;
954 struct lzms_adaptive_state state;
957 state = initial_state;
959 position_cost += lzms_get_lz_match_cost_nolen(ctx, &state, offset);
964 cost = position_cost;
965 cost += lzms_get_length_cost(&ctx->length_encoder, len);
967 ctx->optimum[len].state = state;
968 ctx->optimum[len].prev.link = 0;
969 ctx->optimum[len].prev.match_offset = offset;
970 ctx->optimum[len].cost = cost;
971 } while (++len <= matches[i].len);
973 end_pos = longest_len;
975 if (longest_rep_len >= ctx->params.min_match_length) {
976 struct lzms_adaptive_state state;
979 while (end_pos < longest_rep_len)
980 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
982 state = initial_state;
983 cost = lzms_get_lz_match_cost(ctx,
987 if (cost <= ctx->optimum[longest_rep_len].cost) {
988 ctx->optimum[longest_rep_len].state = state;
989 ctx->optimum[longest_rep_len].prev.link = 0;
990 ctx->optimum[longest_rep_len].prev.match_offset = longest_rep_offset;
991 ctx->optimum[longest_rep_len].cost = cost;
998 struct lzms_adaptive_state state;
1002 if (cur_pos == end_pos || cur_pos == ctx->params.optim_array_length)
1003 return lzms_match_chooser_reverse_list(ctx, cur_pos);
1005 longest_rep_len = ctx->params.min_match_length - 1;
1006 if (lz_mf_get_position(ctx->mf) >= LZMS_MAX_INIT_RECENT_OFFSET) {
1007 u32 limit = lz_mf_get_bytes_remaining(ctx->mf);
1008 for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++) {
1009 u32 offset = ctx->optimum[cur_pos].state.lru.recent_offsets[i];
1010 const u8 *strptr = lz_mf_get_window_ptr(ctx->mf);
1011 const u8 *matchptr = strptr - offset;
1013 while (len < limit && strptr[len] == matchptr[len])
1015 if (len > longest_rep_len) {
1016 longest_rep_len = len;
1017 longest_rep_offset = offset;
1022 if (longest_rep_len >= ctx->params.nice_match_length) {
1023 match = lzms_match_chooser_reverse_list(ctx, cur_pos);
1025 ctx->optimum[cur_pos].next.match_offset = longest_rep_offset;
1026 ctx->optimum[cur_pos].next.link = cur_pos + longest_rep_len;
1027 ctx->optimum_end_idx = cur_pos + longest_rep_len;
1029 lzms_skip_bytes(ctx, longest_rep_len);
1034 num_matches = lzms_get_matches(ctx, &matches);
1037 longest_len = matches[num_matches - 1].len;
1038 if (longest_len >= ctx->params.nice_match_length) {
1039 match = lzms_match_chooser_reverse_list(ctx, cur_pos);
1041 ctx->optimum[cur_pos].next.match_offset =
1042 matches[num_matches - 1].offset;
1043 ctx->optimum[cur_pos].next.link = cur_pos + longest_len;
1044 ctx->optimum_end_idx = cur_pos + longest_len;
1046 lzms_skip_bytes(ctx, longest_len - 1);
1054 while (end_pos < cur_pos + longest_len)
1055 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1057 state = ctx->optimum[cur_pos].state;
1058 cost = ctx->optimum[cur_pos].cost +
1059 lzms_get_literal_cost(ctx,
1061 *(lz_mf_get_window_ptr(ctx->mf) - 1));
1062 if (cost < ctx->optimum[cur_pos + 1].cost) {
1063 ctx->optimum[cur_pos + 1].state = state;
1064 ctx->optimum[cur_pos + 1].cost = cost;
1065 ctx->optimum[cur_pos + 1].prev.link = cur_pos;
1068 for (u32 i = 0, len = 2; i < num_matches; i++) {
1069 u32 offset = matches[i].offset;
1070 struct lzms_adaptive_state state;
1073 state = ctx->optimum[cur_pos].state;
1074 position_cost = ctx->optimum[cur_pos].cost;
1075 position_cost += lzms_get_lz_match_cost_nolen(ctx, &state, offset);
1080 cost = position_cost;
1081 cost += lzms_get_length_cost(&ctx->length_encoder, len);
1083 if (cost < ctx->optimum[cur_pos + len].cost) {
1084 ctx->optimum[cur_pos + len].state = state;
1085 ctx->optimum[cur_pos + len].prev.link = cur_pos;
1086 ctx->optimum[cur_pos + len].prev.match_offset = offset;
1087 ctx->optimum[cur_pos + len].cost = cost;
1089 } while (++len <= matches[i].len);
1092 if (longest_rep_len >= ctx->params.min_match_length) {
1094 while (end_pos < cur_pos + longest_rep_len)
1095 ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
1097 state = ctx->optimum[cur_pos].state;
1099 cost = ctx->optimum[cur_pos].cost +
1100 lzms_get_lz_match_cost(ctx,
1103 longest_rep_offset);
1104 if (cost <= ctx->optimum[cur_pos + longest_rep_len].cost) {
1105 ctx->optimum[cur_pos + longest_rep_len].state =
1107 ctx->optimum[cur_pos + longest_rep_len].prev.link =
1109 ctx->optimum[cur_pos + longest_rep_len].prev.match_offset =
1111 ctx->optimum[cur_pos + longest_rep_len].cost =
1119 * The main loop for the LZMS compressor.
1123 * - This does not output any delta matches.
1125 * - The costs of literals and matches are estimated using the range encoder
1126 * states and the semi-adaptive Huffman codes. Except for range encoding
1127 * states, costs are assumed to be constant throughout a single run of the
1128 * parsing algorithm, which can parse up to @optim_array_length bytes of data.
1129 * This introduces a source of inaccuracy because the probabilities and
1130 * Huffman codes can change over this part of the data.
1133 lzms_encode(struct lzms_compressor *ctx)
1135 struct lz_match item;
1137 /* Load window into the match-finder. */
1138 lz_mf_load_window(ctx->mf, ctx->window, ctx->window_size);
1140 /* Reset the match-chooser. */
1141 ctx->optimum_cur_idx = 0;
1142 ctx->optimum_end_idx = 0;
1144 while (ctx->cur_window_pos != ctx->window_size) {
1145 item = lzms_get_near_optimal_item(ctx);
1147 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
1149 lzms_encode_lz_match(ctx, item.len, item.offset);
1154 lzms_init_range_encoder(struct lzms_range_encoder *enc,
1155 struct lzms_range_encoder_raw *rc, u32 num_states)
1159 enc->mask = num_states - 1;
1160 for (u32 i = 0; i < num_states; i++) {
1161 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
1162 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
1167 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
1168 struct lzms_output_bitstream *os,
1170 unsigned rebuild_freq)
1173 enc->num_syms_written = 0;
1174 enc->rebuild_freq = rebuild_freq;
1175 enc->num_syms = num_syms;
1176 for (unsigned i = 0; i < num_syms; i++)
1177 enc->sym_freqs[i] = 1;
1179 make_canonical_huffman_code(enc->num_syms,
1180 LZMS_MAX_CODEWORD_LEN,
1186 /* Initialize the LZMS compressor. */
1188 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
1189 le16 *cdata, u32 clen16)
1191 unsigned num_position_slots;
1193 /* Copy the uncompressed data into the @ctx->window buffer. */
1194 memcpy(ctx->window, udata, ulen);
1195 ctx->cur_window_pos = 0;
1196 ctx->window_size = ulen;
1198 /* Initialize the raw range encoder (writing forwards). */
1199 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
1201 /* Initialize the output bitstream for Huffman symbols and verbatim bits
1202 * (writing backwards). */
1203 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
1205 /* Calculate the number of position slots needed for this compressed
1207 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
1209 LZMS_DEBUG("Using %u position slots", num_position_slots);
1211 /* Initialize Huffman encoders for each alphabet used in the compressed
1212 * representation. */
1213 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
1214 LZMS_NUM_LITERAL_SYMS,
1215 LZMS_LITERAL_CODE_REBUILD_FREQ);
1217 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
1219 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
1221 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
1223 LZMS_LENGTH_CODE_REBUILD_FREQ);
1225 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
1227 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
1229 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
1230 LZMS_NUM_DELTA_POWER_SYMS,
1231 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
1233 /* Initialize range encoders, all of which wrap around the same
1234 * lzms_range_encoder_raw. */
1235 lzms_init_range_encoder(&ctx->main_range_encoder,
1236 &ctx->rc, LZMS_NUM_MAIN_STATES);
1238 lzms_init_range_encoder(&ctx->match_range_encoder,
1239 &ctx->rc, LZMS_NUM_MATCH_STATES);
1241 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
1242 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
1244 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
1245 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
1246 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
1248 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
1249 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
1251 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
1252 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
1253 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
1255 /* Initialize LRU match information. */
1256 lzms_init_lru_queues(&ctx->lru);
1259 /* Flush the output streams, prepare the final compressed data, and return its
1262 * A return value of 0 indicates that the data could not be compressed to fit in
1263 * the available space. */
1265 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
1267 size_t num_forwards_bytes;
1268 size_t num_backwards_bytes;
1269 size_t compressed_size;
1271 /* Flush both the forwards and backwards streams, and make sure they
1272 * didn't cross each other and start overwriting each other's data. */
1273 if (!lzms_output_bitstream_flush(&ctx->os)) {
1274 LZMS_DEBUG("Backwards bitstream overrun.");
1278 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
1279 LZMS_DEBUG("Forwards bitstream overrun.");
1283 if (ctx->rc.out > ctx->os.out) {
1284 LZMS_DEBUG("Two bitstreams crossed.");
1288 /* Now the compressed buffer contains the data output by the forwards
1289 * bitstream, then empty space, then data output by the backwards
1290 * bitstream. Move the data output by the backwards bitstream to be
1291 * adjacent to the data output by the forward bitstream, and calculate
1292 * the compressed size that this results in. */
1293 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
1294 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
1296 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
1298 compressed_size = num_forwards_bytes + num_backwards_bytes;
1299 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
1300 "compressed_size=%zu",
1301 num_forwards_bytes, num_backwards_bytes, compressed_size);
1302 LZMS_ASSERT(compressed_size % 2 == 0);
1303 return compressed_size;
1308 lzms_build_params(unsigned int compression_level,
1309 struct lzms_compressor_params *lzms_params)
1311 lzms_params->min_match_length = (compression_level >= 50) ? 2 : 3;
1312 lzms_params->nice_match_length = max(((u64)compression_level * 32) / 50,
1313 lzms_params->min_match_length);
1314 lzms_params->max_search_depth = ((u64)compression_level * 50) / 50;
1315 lzms_params->optim_array_length = 224 + compression_level * 16;
1319 lzms_build_mf_params(const struct lzms_compressor_params *lzms_params,
1320 u32 max_window_size, struct lz_mf_params *mf_params)
1322 memset(mf_params, 0, sizeof(*mf_params));
1324 mf_params->algorithm = LZ_MF_DEFAULT;
1325 mf_params->max_window_size = max_window_size;
1326 mf_params->min_match_len = lzms_params->min_match_length;
1327 mf_params->max_search_depth = lzms_params->max_search_depth;
1328 mf_params->nice_match_len = lzms_params->nice_match_length;
1332 lzms_free_compressor(void *_ctx);
1335 lzms_get_needed_memory(size_t max_block_size, unsigned int compression_level)
1337 struct lzms_compressor_params params;
1340 if (max_block_size >= INT32_MAX)
1343 lzms_build_params(compression_level, ¶ms);
1345 size += sizeof(struct lzms_compressor);
1346 size += max_block_size;
1347 size += lz_mf_get_needed_memory(LZ_MF_DEFAULT, max_block_size);
1348 size += params.max_search_depth * sizeof(struct lz_match);
1349 size += (params.optim_array_length + params.nice_match_length) *
1350 sizeof(struct lzms_mc_pos_data);
1356 lzms_create_compressor(size_t max_block_size, unsigned int compression_level,
1359 struct lzms_compressor *ctx;
1360 struct lzms_compressor_params params;
1361 struct lz_mf_params mf_params;
1363 if (max_block_size >= INT32_MAX)
1364 return WIMLIB_ERR_INVALID_PARAM;
1366 lzms_build_params(compression_level, ¶ms);
1367 lzms_build_mf_params(¶ms, max_block_size, &mf_params);
1368 if (!lz_mf_params_valid(&mf_params))
1369 return WIMLIB_ERR_INVALID_PARAM;
1371 ctx = CALLOC(1, sizeof(struct lzms_compressor));
1375 ctx->params = params;
1376 ctx->max_block_size = max_block_size;
1378 ctx->window = MALLOC(max_block_size);
1382 ctx->mf = lz_mf_alloc(&mf_params);
1386 ctx->matches = MALLOC(params.max_search_depth * sizeof(struct lz_match));
1390 ctx->optimum = MALLOC((params.optim_array_length +
1391 params.nice_match_length) *
1392 sizeof(struct lzms_mc_pos_data));
1396 /* Initialize position and length slot data if not done already. */
1399 /* Initialize range encoding cost table if not done already. */
1400 lzms_init_rc_costs();
1406 lzms_free_compressor(ctx);
1407 return WIMLIB_ERR_NOMEM;
1411 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
1412 void *compressed_data, size_t compressed_size_avail, void *_ctx)
1414 struct lzms_compressor *ctx = _ctx;
1415 size_t compressed_size;
1417 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
1418 uncompressed_size, compressed_size_avail);
1420 /* Don't bother compressing extremely small inputs. */
1421 if (uncompressed_size < 4) {
1422 LZMS_DEBUG("Input too small to bother compressing.");
1426 /* Cap the available compressed size to a 32-bit integer and round it
1427 * down to the nearest multiple of 2. */
1428 if (compressed_size_avail > UINT32_MAX)
1429 compressed_size_avail = UINT32_MAX;
1430 if (compressed_size_avail & 1)
1431 compressed_size_avail--;
1433 /* Initialize the compressor structures. */
1434 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
1435 compressed_data, compressed_size_avail / 2);
1437 /* Preprocess the uncompressed data. */
1438 lzms_x86_filter(ctx->window, ctx->window_size,
1439 ctx->last_target_usages, false);
1441 /* Compute and encode a literal/match sequence that decompresses to the
1442 * preprocessed data. */
1445 /* Get and return the compressed data size. */
1446 compressed_size = lzms_finalize(ctx, compressed_data,
1447 compressed_size_avail);
1449 if (compressed_size == 0) {
1450 LZMS_DEBUG("Data did not compress to requested size or less.");
1454 LZMS_DEBUG("Compressed %zu => %zu bytes",
1455 uncompressed_size, compressed_size);
1457 return compressed_size;
1461 lzms_free_compressor(void *_ctx)
1463 struct lzms_compressor *ctx = _ctx;
1467 lz_mf_free(ctx->mf);
1474 const struct compressor_ops lzms_compressor_ops = {
1475 .get_needed_memory = lzms_get_needed_memory,
1476 .create_compressor = lzms_create_compressor,
1477 .compress = lzms_compress,
1478 .free_compressor = lzms_free_compressor,