+ prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
+}
+
+/* Encode a symbol using the specified Huffman encoder. */
+static void
+lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
+{
+ LZMS_ASSERT(sym < enc->num_syms);
+ lzms_output_bitstream_put_bits(enc->os,
+ enc->codewords[sym],
+ enc->lens[sym]);
+ ++enc->sym_freqs[sym];
+ if (++enc->num_syms_written == enc->rebuild_freq) {
+ /* Adaptive code needs to be rebuilt. */
+ LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
+ make_canonical_huffman_code(enc->num_syms,
+ LZMS_MAX_CODEWORD_LEN,
+ enc->sym_freqs,
+ enc->lens,
+ enc->codewords);
+
+ /* Dilute the frequencies. */
+ for (unsigned i = 0; i < enc->num_syms; i++) {
+ enc->sym_freqs[i] >>= 1;
+ enc->sym_freqs[i] += 1;
+ }
+ enc->num_syms_written = 0;
+ }
+}
+
+static void
+lzms_encode_length(struct lzms_huffman_encoder *enc, u32 length)
+{
+ unsigned slot;
+ unsigned num_extra_bits;
+ u32 extra_bits;
+
+ slot = lzms_get_length_slot(length);
+
+ num_extra_bits = lzms_extra_length_bits[slot];
+
+ extra_bits = length - lzms_length_slot_base[slot];
+
+ lzms_huffman_encode_symbol(enc, slot);
+ lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
+}
+
+static void
+lzms_encode_offset(struct lzms_huffman_encoder *enc, u32 offset)
+{
+ unsigned slot;
+ unsigned num_extra_bits;
+ u32 extra_bits;
+
+ slot = lzms_get_position_slot(offset);
+
+ num_extra_bits = lzms_extra_position_bits[slot];
+
+ extra_bits = offset - lzms_position_slot_base[slot];
+
+ lzms_huffman_encode_symbol(enc, slot);
+ lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
+}
+
+static void
+lzms_begin_encode_item(struct lzms_compressor *ctx)
+{
+ ctx->lru.lz.upcoming_offset = 0;
+ ctx->lru.delta.upcoming_offset = 0;
+ ctx->lru.delta.upcoming_power = 0;
+}
+
+static void
+lzms_end_encode_item(struct lzms_compressor *ctx, u32 length)
+{
+ LZMS_ASSERT(ctx->window_size - ctx->cur_window_pos >= length);
+ ctx->cur_window_pos += length;
+ lzms_update_lru_queues(&ctx->lru);
+}
+
+/* Encode a literal byte. */
+static void
+lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
+{
+ LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
+ ctx->cur_window_pos, literal, literal);
+
+ lzms_begin_encode_item(ctx);
+
+ /* Main bit: 0 = a literal, not a match. */
+ lzms_range_encode_bit(&ctx->main_range_encoder, 0);
+
+ /* Encode the literal using the current literal Huffman code. */
+ lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
+
+ lzms_end_encode_item(ctx, 1);
+}
+
+/* Encode a (length, offset) pair (LZ match). */
+static void
+lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
+{
+ int recent_offset_idx;
+
+ LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
+ ctx->cur_window_pos, length, offset);
+
+ LZMS_ASSERT(length <= ctx->window_size - ctx->cur_window_pos);
+ LZMS_ASSERT(offset <= ctx->cur_window_pos);
+ LZMS_ASSERT(!memcmp(&ctx->window[ctx->cur_window_pos],
+ &ctx->window[ctx->cur_window_pos - offset],
+ length));
+
+ lzms_begin_encode_item(ctx);
+
+ /* Main bit: 1 = a match, not a literal. */
+ lzms_range_encode_bit(&ctx->main_range_encoder, 1);
+
+ /* Match bit: 0 = an LZ match, not a delta match. */
+ lzms_range_encode_bit(&ctx->match_range_encoder, 0);
+
+ /* Determine if the offset can be represented as a recent offset. */
+ for (recent_offset_idx = 0;
+ recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
+ recent_offset_idx++)
+ if (offset == ctx->lru.lz.recent_offsets[recent_offset_idx])
+ break;
+
+ if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
+ /* Explicit offset. */
+
+ /* LZ match bit: 0 = explicit offset, not a recent offset. */
+ lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
+
+ /* Encode the match offset. */
+ lzms_encode_offset(&ctx->lz_offset_encoder, offset);
+ } else {
+ int i;
+
+ /* Recent offset. */
+
+ /* LZ match bit: 1 = recent offset, not an explicit offset. */
+ lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
+
+ /* Encode the recent offset index. A 1 bit is encoded for each
+ * index passed up. This sequence of 1 bits is terminated by a
+ * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
+ * bits have been encoded. */
+ for (i = 0; i < recent_offset_idx; i++)
+ lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
+
+ if (i < LZMS_NUM_RECENT_OFFSETS - 1)
+ lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
+
+ /* Initial update of the LZ match offset LRU queue. */
+ for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
+ ctx->lru.lz.recent_offsets[i] = ctx->lru.lz.recent_offsets[i + 1];
+ }
+
+ /* Encode the match length. */
+ lzms_encode_length(&ctx->length_encoder, length);
+
+ /* Save the match offset for later insertion at the front of the LZ
+ * match offset LRU queue. */
+ ctx->lru.lz.upcoming_offset = offset;
+
+ lzms_end_encode_item(ctx, length);
+}
+
+#define LZMS_COST_SHIFT 5
+
+/*#define LZMS_RC_COSTS_USE_FLOATING_POINT*/
+
+static u32
+lzms_rc_costs[LZMS_PROBABILITY_MAX + 1];
+
+#ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
+# include <math.h>
+#endif
+
+static void
+lzms_do_init_rc_costs(void)
+{
+ /* Fill in a table that maps range coding probabilities needed to code a
+ * bit X (0 or 1) to the number of bits (scaled by a constant factor, to
+ * handle fractional costs) needed to code that bit X.
+ *
+ * Consider the range of the range decoder. To eliminate exactly half
+ * the range (logical probability of 0.5), we need exactly 1 bit. For
+ * lower probabilities we need more bits and for higher probabilities we
+ * need fewer bits. In general, a logical probability of N will
+ * eliminate the proportion 1 - N of the range; this information takes
+ * log2(1 / N) bits to encode.
+ *
+ * The below loop is simply calculating this number of bits for each
+ * possible probability allowed by the LZMS compression format, but
+ * without using real numbers. To handle fractional probabilities, each
+ * cost is multiplied by (1 << LZMS_COST_SHIFT). These techniques are
+ * based on those used by LZMA.
+ *
+ * Note that in LZMS, a probability x really means x / 64, and 0 / 64 is
+ * really interpreted as 1 / 64 and 64 / 64 is really interpreted as
+ * 63 / 64.
+ */
+ for (u32 i = 0; i <= LZMS_PROBABILITY_MAX; i++) {
+ u32 prob = i;
+
+ if (prob == 0)
+ prob = 1;
+ else if (prob == LZMS_PROBABILITY_MAX)
+ prob = LZMS_PROBABILITY_MAX - 1;
+
+ #ifdef LZMS_RC_COSTS_USE_FLOATING_POINT
+ lzms_rc_costs[i] = log2((double)LZMS_PROBABILITY_MAX / prob) *
+ (1 << LZMS_COST_SHIFT);
+ #else
+ u32 w = prob;
+ u32 bit_count = 0;
+ for (u32 j = 0; j < LZMS_COST_SHIFT; j++) {
+ w *= w;
+ bit_count <<= 1;
+ while (w >= (1U << 16)) {
+ w >>= 1;
+ ++bit_count;
+ }
+ }
+ lzms_rc_costs[i] = (LZMS_PROBABILITY_BITS << LZMS_COST_SHIFT) -
+ (15 + bit_count);
+ #endif
+ }
+}
+
+static void
+lzms_init_rc_costs(void)
+{
+ static pthread_once_t once = PTHREAD_ONCE_INIT;
+
+ pthread_once(&once, lzms_do_init_rc_costs);
+}
+
+/*
+ * Return the cost to range-encode the specified bit when in the specified
+ * state.
+ *
+ * @enc The range encoder to use.
+ * @cur_state Current state, which indicates the probability entry to choose.
+ * Updated by this function.
+ * @bit The bit to encode (0 or 1).
+ */
+static u32
+lzms_rc_bit_cost(const struct lzms_range_encoder *enc, u8 *cur_state, int bit)
+{
+ u32 prob_zero;
+ u32 prob_correct;
+
+ prob_zero = enc->prob_entries[*cur_state & enc->mask].num_recent_zero_bits;
+
+ *cur_state = (*cur_state << 1) | bit;
+
+ if (bit == 0)
+ prob_correct = prob_zero;
+ else
+ prob_correct = LZMS_PROBABILITY_MAX - prob_zero;
+
+ return lzms_rc_costs[prob_correct];
+}
+
+static u32
+lzms_huffman_symbol_cost(const struct lzms_huffman_encoder *enc, u32 sym)
+{
+ return enc->lens[sym] << LZMS_COST_SHIFT;
+}
+
+static u32
+lzms_offset_cost(const struct lzms_huffman_encoder *enc, u32 offset)
+{
+ u32 slot;
+ u32 num_extra_bits;
+ u32 cost = 0;
+
+ slot = lzms_get_position_slot(offset);
+
+ cost += lzms_huffman_symbol_cost(enc, slot);
+
+ num_extra_bits = lzms_extra_position_bits[slot];
+
+ cost += num_extra_bits << LZMS_COST_SHIFT;
+
+ return cost;
+}
+
+static u32
+lzms_length_cost(const struct lzms_huffman_encoder *enc, u32 length)
+{
+ u32 slot;
+ u32 num_extra_bits;
+ u32 cost = 0;
+
+ slot = lzms_get_length_slot(length);
+
+ cost += lzms_huffman_symbol_cost(enc, slot);
+
+ num_extra_bits = lzms_extra_length_bits[slot];
+
+ cost += num_extra_bits << LZMS_COST_SHIFT;
+
+ return cost;
+}
+
+static u32
+lzms_get_matches(struct lzms_compressor *ctx, struct raw_match **matches_ret)
+{
+ *matches_ret = ctx->matches;
+ return lz_bt_get_matches(&ctx->mf, ctx->matches);
+}
+
+static void
+lzms_skip_bytes(struct lzms_compressor *ctx, u32 n)
+{
+ lz_bt_skip_positions(&ctx->mf, n);
+}
+
+static u32
+lzms_get_literal_cost(struct lzms_compressor *ctx,
+ struct lzms_adaptive_state *state, u8 literal)
+{
+ u32 cost = 0;
+
+ state->lru.upcoming_offset = 0;
+ lzms_update_lz_lru_queues(&state->lru);
+
+ cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
+ &state->main_state, 0);
+
+ cost += lzms_huffman_symbol_cost(&ctx->literal_encoder, literal);
+
+ return cost;
+}
+
+static u32
+lzms_get_lz_match_cost(struct lzms_compressor *ctx,
+ struct lzms_adaptive_state *state,
+ u32 length, u32 offset)
+{
+ u32 cost = 0;
+ int recent_offset_idx;
+
+ cost += lzms_rc_bit_cost(&ctx->main_range_encoder,
+ &state->main_state, 1);
+ cost += lzms_rc_bit_cost(&ctx->match_range_encoder,
+ &state->match_state, 0);
+
+ for (recent_offset_idx = 0;
+ recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
+ recent_offset_idx++)
+ if (offset == state->lru.recent_offsets[recent_offset_idx])
+ break;
+
+ if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
+ /* Explicit offset. */
+ cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
+ &state->lz_match_state, 0);
+
+ cost += lzms_offset_cost(&ctx->lz_offset_encoder, offset);
+ } else {
+ int i;
+
+ /* Recent offset. */
+ cost += lzms_rc_bit_cost(&ctx->lz_match_range_encoder,
+ &state->lz_match_state, 1);
+
+ for (i = 0; i < recent_offset_idx; i++)
+ cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
+ &state->lz_repeat_match_state[i], 0);
+
+ if (i < LZMS_NUM_RECENT_OFFSETS - 1)
+ cost += lzms_rc_bit_cost(&ctx->lz_repeat_match_range_encoders[i],
+ &state->lz_repeat_match_state[i], 1);
+
+
+ /* Initial update of the LZ match offset LRU queue. */
+ for (; i < LZMS_NUM_RECENT_OFFSETS; i++)
+ state->lru.recent_offsets[i] = state->lru.recent_offsets[i + 1];
+ }
+
+ cost += lzms_length_cost(&ctx->length_encoder, length);
+
+ state->lru.upcoming_offset = offset;
+ lzms_update_lz_lru_queues(&state->lru);
+
+ return cost;
+}
+
+static struct raw_match
+lzms_match_chooser_reverse_list(struct lzms_compressor *ctx, unsigned cur_pos)
+{
+ unsigned prev_link, saved_prev_link;
+ unsigned prev_match_offset, saved_prev_match_offset;
+
+ ctx->optimum_end_idx = cur_pos;
+
+ saved_prev_link = ctx->optimum[cur_pos].prev.link;
+ saved_prev_match_offset = ctx->optimum[cur_pos].prev.match_offset;
+
+ do {
+ prev_link = saved_prev_link;
+ prev_match_offset = saved_prev_match_offset;
+
+ saved_prev_link = ctx->optimum[prev_link].prev.link;
+ saved_prev_match_offset = ctx->optimum[prev_link].prev.match_offset;
+
+ ctx->optimum[prev_link].next.link = cur_pos;
+ ctx->optimum[prev_link].next.match_offset = prev_match_offset;
+
+ cur_pos = prev_link;
+ } while (cur_pos != 0);
+
+ ctx->optimum_cur_idx = ctx->optimum[0].next.link;
+
+ return (struct raw_match)
+ { .len = ctx->optimum_cur_idx,
+ .offset = ctx->optimum[0].next.match_offset,
+ };
+}
+
+/* This is similar to lzx_get_near_optimal_match() in lzx-compress.c.
+ * Read that one if you want to understand it. */
+static struct raw_match
+lzms_get_near_optimal_match(struct lzms_compressor *ctx)
+{
+ u32 num_matches;
+ struct raw_match *matches;
+ struct raw_match match;
+ u32 longest_len;
+ u32 longest_rep_len;
+ u32 longest_rep_offset;
+ struct raw_match *matchptr;
+ unsigned cur_pos;
+ unsigned end_pos;
+ struct lzms_adaptive_state initial_state;
+
+ if (ctx->optimum_cur_idx != ctx->optimum_end_idx) {
+ match.len = ctx->optimum[ctx->optimum_cur_idx].next.link -
+ ctx->optimum_cur_idx;
+ match.offset = ctx->optimum[ctx->optimum_cur_idx].next.match_offset;
+
+ ctx->optimum_cur_idx = ctx->optimum[ctx->optimum_cur_idx].next.link;
+ return match;
+ }
+
+ ctx->optimum_cur_idx = 0;
+ ctx->optimum_end_idx = 0;
+
+ longest_rep_len = ctx->params.min_match_length - 1;
+ if (lz_bt_get_position(&ctx->mf) >= 1) {
+ u32 limit = min(ctx->params.max_match_length,
+ lz_bt_get_remaining_size(&ctx->mf));
+ for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++) {
+ u32 offset = ctx->lru.lz.recent_offsets[i];
+ const u8 *strptr = lz_bt_get_window_ptr(&ctx->mf);
+ const u8 *matchptr = strptr - offset;
+ u32 len = 0;
+ while (len < limit && strptr[len] == matchptr[len])
+ len++;
+ if (len > longest_rep_len) {
+ longest_rep_len = len;
+ longest_rep_offset = offset;
+ }
+ }
+ }
+
+ if (longest_rep_len >= ctx->params.nice_match_length) {
+ lzms_skip_bytes(ctx, longest_rep_len);
+ return (struct raw_match) {
+ .len = longest_rep_len,
+ .offset = longest_rep_offset,
+ };
+ }
+
+ num_matches = lzms_get_matches(ctx, &matches);
+
+ if (num_matches) {
+ longest_len = matches[num_matches - 1].len;
+ if (longest_len >= ctx->params.nice_match_length) {
+ lzms_skip_bytes(ctx, longest_len - 1);
+ return matches[num_matches - 1];
+ }
+ } else {
+ longest_len = 1;
+ }
+
+ initial_state.lru = ctx->lru.lz;
+ initial_state.main_state = ctx->main_range_encoder.state;
+ initial_state.match_state = ctx->match_range_encoder.state;
+ initial_state.lz_match_state = ctx->lz_match_range_encoder.state;
+ for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS - 1; i++)
+ initial_state.lz_repeat_match_state[i] = ctx->lz_repeat_match_range_encoders[i].state;
+
+ ctx->optimum[1].state = initial_state;
+ ctx->optimum[1].cost = lzms_get_literal_cost(ctx,
+ &ctx->optimum[1].state,
+ *(lz_bt_get_window_ptr(&ctx->mf) - 1));
+ ctx->optimum[1].prev.link = 0;
+
+ matchptr = matches;
+ for (u32 len = 2; len <= longest_len; len++) {
+ u32 offset = matchptr->offset;
+
+ ctx->optimum[len].state = initial_state;
+ ctx->optimum[len].prev.link = 0;
+ ctx->optimum[len].prev.match_offset = offset;
+ ctx->optimum[len].cost = lzms_get_lz_match_cost(ctx,
+ &ctx->optimum[len].state,
+ len, offset);
+ if (len == matchptr->len)
+ matchptr++;
+ }
+ end_pos = longest_len;
+
+ if (longest_rep_len >= ctx->params.min_match_length) {
+ struct lzms_adaptive_state state;
+ u32 cost;
+
+ while (end_pos < longest_rep_len)
+ ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
+
+ state = initial_state;
+ cost = lzms_get_lz_match_cost(ctx,
+ &state,
+ longest_rep_len,
+ longest_rep_offset);
+ if (cost <= ctx->optimum[longest_rep_len].cost) {
+ ctx->optimum[longest_rep_len].state = state;
+ ctx->optimum[longest_rep_len].prev.link = 0;
+ ctx->optimum[longest_rep_len].prev.match_offset = longest_rep_offset;
+ ctx->optimum[longest_rep_len].cost = cost;
+ }
+ }
+
+ cur_pos = 0;
+ for (;;) {
+ u32 cost;
+ struct lzms_adaptive_state state;
+
+ cur_pos++;
+
+ if (cur_pos == end_pos || cur_pos == ctx->params.optim_array_length)
+ return lzms_match_chooser_reverse_list(ctx, cur_pos);
+
+ longest_rep_len = ctx->params.min_match_length - 1;
+ u32 limit = min(ctx->params.max_match_length,
+ lz_bt_get_remaining_size(&ctx->mf));
+ for (int i = 0; i < LZMS_NUM_RECENT_OFFSETS; i++) {
+ u32 offset = ctx->optimum[cur_pos].state.lru.recent_offsets[i];
+ const u8 *strptr = lz_bt_get_window_ptr(&ctx->mf);
+ const u8 *matchptr = strptr - offset;
+ u32 len = 0;
+ while (len < limit && strptr[len] == matchptr[len])
+ len++;
+ if (len > longest_rep_len) {
+ longest_rep_len = len;
+ longest_rep_offset = offset;
+ }
+ }
+
+ if (longest_rep_len >= ctx->params.nice_match_length) {
+ match = lzms_match_chooser_reverse_list(ctx, cur_pos);
+
+ ctx->optimum[cur_pos].next.match_offset = longest_rep_offset;
+ ctx->optimum[cur_pos].next.link = cur_pos + longest_rep_len;
+ ctx->optimum_end_idx = cur_pos + longest_rep_len;
+
+ lzms_skip_bytes(ctx, longest_rep_len);
+
+ return match;
+ }
+
+ num_matches = lzms_get_matches(ctx, &matches);
+
+ if (num_matches) {
+ longest_len = matches[num_matches - 1].len;
+ if (longest_len >= ctx->params.nice_match_length) {
+ match = lzms_match_chooser_reverse_list(ctx, cur_pos);
+
+ ctx->optimum[cur_pos].next.match_offset =
+ matches[num_matches - 1].offset;
+ ctx->optimum[cur_pos].next.link = cur_pos + longest_len;
+ ctx->optimum_end_idx = cur_pos + longest_len;
+
+ lzms_skip_bytes(ctx, longest_len - 1);
+
+ return match;
+ }
+ } else {
+ longest_len = 1;
+ }
+
+ while (end_pos < cur_pos + longest_len)
+ ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
+
+ state = ctx->optimum[cur_pos].state;
+ cost = ctx->optimum[cur_pos].cost +
+ lzms_get_literal_cost(ctx,
+ &state,
+ *(lz_bt_get_window_ptr(&ctx->mf) - 1));
+ if (cost < ctx->optimum[cur_pos + 1].cost) {
+ ctx->optimum[cur_pos + 1].state = state;
+ ctx->optimum[cur_pos + 1].cost = cost;
+ ctx->optimum[cur_pos + 1].prev.link = cur_pos;
+ }
+
+ matchptr = matches;
+ for (u32 len = 2; len <= longest_len; len++) {
+ u32 offset;
+
+ offset = matchptr->offset;
+ state = ctx->optimum[cur_pos].state;
+
+ cost = ctx->optimum[cur_pos].cost +
+ lzms_get_lz_match_cost(ctx, &state, len, offset);
+ if (cost < ctx->optimum[cur_pos + len].cost) {
+ ctx->optimum[cur_pos + len].state = state;
+ ctx->optimum[cur_pos + len].prev.link = cur_pos;
+ ctx->optimum[cur_pos + len].prev.match_offset = offset;
+ ctx->optimum[cur_pos + len].cost = cost;
+ }
+ if (len == matchptr->len)
+ matchptr++;
+ }
+
+ if (longest_rep_len >= ctx->params.min_match_length) {
+
+ while (end_pos < cur_pos + longest_rep_len)
+ ctx->optimum[++end_pos].cost = MC_INFINITE_COST;
+
+ state = ctx->optimum[cur_pos].state;
+
+ cost = ctx->optimum[cur_pos].cost +
+ lzms_get_lz_match_cost(ctx,
+ &state,
+ longest_rep_len,
+ longest_rep_offset);
+ if (cost <= ctx->optimum[cur_pos + longest_rep_len].cost) {
+ ctx->optimum[cur_pos + longest_rep_len].state =
+ state;
+ ctx->optimum[cur_pos + longest_rep_len].prev.link =
+ cur_pos;
+ ctx->optimum[cur_pos + longest_rep_len].prev.match_offset =
+ longest_rep_offset;
+ ctx->optimum[cur_pos + longest_rep_len].cost =
+ cost;
+ }
+ }
+ }
+}
+
+/*
+ * The main loop for the LZMS compressor.
+ *
+ * Notes:
+ *
+ * - This uses near-optimal LZ parsing backed by a binary tree match-finder.
+ *
+ * - This does not output any delta matches.
+ *
+ * - The costs of literals and matches are estimated using the range encoder
+ * states and the semi-adaptive Huffman codes. Except for range encoding
+ * states, costs are assumed to be constant throughout a single run of the
+ * parsing algorithm, which can parse up to @optim_array_length (from the
+ * `struct wimlib_lzms_compressor_params') bytes of data. This introduces a
+ * source of inaccuracy because the probabilities and Huffman codes can change
+ * over this part of the data.
+ */
+static void
+lzms_encode(struct lzms_compressor *ctx)
+{
+ struct raw_match match;
+
+ /* Load window into the binary tree match-finder. */
+ lz_bt_load_window(&ctx->mf, ctx->window, ctx->window_size);
+
+ /* Reset the match-chooser. */
+ ctx->optimum_cur_idx = 0;
+ ctx->optimum_end_idx = 0;
+
+ while (ctx->cur_window_pos != ctx->window_size) {
+ match = lzms_get_near_optimal_match(ctx);
+ if (match.len <= 1)
+ lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
+ else
+ lzms_encode_lz_match(ctx, match.len, match.offset);
+ }
+}
+
+static void
+lzms_init_range_encoder(struct lzms_range_encoder *enc,
+ struct lzms_range_encoder_raw *rc, u32 num_states)
+{
+ enc->rc = rc;
+ enc->state = 0;
+ enc->mask = num_states - 1;
+ for (u32 i = 0; i < num_states; i++) {
+ enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
+ enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
+ }
+}
+
+static void
+lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
+ struct lzms_output_bitstream *os,
+ unsigned num_syms,
+ unsigned rebuild_freq)
+{
+ enc->os = os;
+ enc->num_syms_written = 0;
+ enc->rebuild_freq = rebuild_freq;
+ enc->num_syms = num_syms;
+ for (unsigned i = 0; i < num_syms; i++)
+ enc->sym_freqs[i] = 1;
+
+ make_canonical_huffman_code(enc->num_syms,
+ LZMS_MAX_CODEWORD_LEN,
+ enc->sym_freqs,
+ enc->lens,
+ enc->codewords);
+}
+
+/* Initialize the LZMS compressor. */
+static void
+lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
+ le16 *cdata, u32 clen16)
+{
+ unsigned num_position_slots;
+
+ /* Copy the uncompressed data into the @ctx->window buffer. */
+ memcpy(ctx->window, udata, ulen);
+ ctx->cur_window_pos = 0;
+ ctx->window_size = ulen;
+
+ /* Initialize the raw range encoder (writing forwards). */
+ lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
+
+ /* Initialize the output bitstream for Huffman symbols and verbatim bits
+ * (writing backwards). */
+ lzms_output_bitstream_init(&ctx->os, cdata, clen16);
+
+ /* Calculate the number of position slots needed for this compressed
+ * block. */
+ num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
+
+ LZMS_DEBUG("Using %u position slots", num_position_slots);
+
+ /* Initialize Huffman encoders for each alphabet used in the compressed
+ * representation. */
+ lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
+ LZMS_NUM_LITERAL_SYMS,
+ LZMS_LITERAL_CODE_REBUILD_FREQ);
+
+ lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
+ num_position_slots,
+ LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
+
+ lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
+ LZMS_NUM_LEN_SYMS,
+ LZMS_LENGTH_CODE_REBUILD_FREQ);
+
+ lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
+ num_position_slots,
+ LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
+
+ lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
+ LZMS_NUM_DELTA_POWER_SYMS,
+ LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
+
+ /* Initialize range encoders, all of which wrap around the same
+ * lzms_range_encoder_raw. */
+ lzms_init_range_encoder(&ctx->main_range_encoder,
+ &ctx->rc, LZMS_NUM_MAIN_STATES);
+
+ lzms_init_range_encoder(&ctx->match_range_encoder,
+ &ctx->rc, LZMS_NUM_MATCH_STATES);
+
+ lzms_init_range_encoder(&ctx->lz_match_range_encoder,
+ &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
+
+ for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
+ lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
+ &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
+
+ lzms_init_range_encoder(&ctx->delta_match_range_encoder,
+ &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
+
+ for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
+ lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
+ &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
+
+ /* Initialize LRU match information. */
+ lzms_init_lru_queues(&ctx->lru);
+}
+
+/* Flush the output streams, prepare the final compressed data, and return its
+ * size in bytes.
+ *
+ * A return value of 0 indicates that the data could not be compressed to fit in
+ * the available space. */
+static size_t
+lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
+{
+ size_t num_forwards_bytes;
+ size_t num_backwards_bytes;
+ size_t compressed_size;
+
+ /* Flush both the forwards and backwards streams, and make sure they
+ * didn't cross each other and start overwriting each other's data. */
+ if (!lzms_output_bitstream_flush(&ctx->os)) {
+ LZMS_DEBUG("Backwards bitstream overrun.");
+ return 0;
+ }
+
+ if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
+ LZMS_DEBUG("Forwards bitstream overrun.");
+ return 0;
+ }
+
+ if (ctx->rc.out > ctx->os.out) {
+ LZMS_DEBUG("Two bitstreams crossed.");
+ return 0;
+ }
+
+ /* Now the compressed buffer contains the data output by the forwards
+ * bitstream, then empty space, then data output by the backwards
+ * bitstream. Move the data output by the backwards bitstream to be
+ * adjacent to the data output by the forward bitstream, and calculate
+ * the compressed size that this results in. */
+ num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
+ num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
+
+ memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
+
+ compressed_size = num_forwards_bytes + num_backwards_bytes;
+ LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
+ "compressed_size=%zu",
+ num_forwards_bytes, num_backwards_bytes, compressed_size);
+ LZMS_ASSERT(compressed_size % 2 == 0);
+ return compressed_size;