6 * Copyright (C) 2013 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
10 * wimlib is free software; you can redistribute it and/or modify it under the
11 * terms of the GNU General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option)
15 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 * A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with wimlib; if not, see http://www.gnu.org/licenses/.
24 /* This a compressor for the LZMS compression format. More details about this
25 * format can be found in lzms-decompress.c.
27 * This is currently an unsophisticated implementation that is fast but does not
28 * attain the best compression ratios allowed by the format.
36 #include "wimlib/assert.h"
37 #include "wimlib/compiler.h"
38 #include "wimlib/compressor_ops.h"
39 #include "wimlib/compress_common.h"
40 #include "wimlib/endianness.h"
41 #include "wimlib/error.h"
42 #include "wimlib/lzms.h"
43 #include "wimlib/util.h"
47 /* Stucture used for writing raw bits to the end of the LZMS-compressed data as
48 * a series of 16-bit little endian coding units. */
49 struct lzms_output_bitstream {
50 /* Buffer variable containing zero or more bits that have been logically
51 * written to the bitstream but not yet written to memory. This must be
52 * at least as large as the coding unit size. */
55 /* Number of bits in @bitbuf that are valid. */
56 unsigned num_free_bits;
58 /* Pointer to one past the next position in the compressed data buffer
59 * at which to output a 16-bit coding unit. */
62 /* Maximum number of 16-bit coding units that can still be output to
63 * the compressed data buffer. */
64 size_t num_le16_remaining;
66 /* Set to %true if not all coding units could be output due to
67 * insufficient space. */
71 /* Stucture used for range encoding (raw version). */
72 struct lzms_range_encoder_raw {
74 /* A 33-bit variable that holds the low boundary of the current range.
75 * The 33rd bit is needed to catch carries. */
78 /* Size of the current range. */
81 /* Next 16-bit coding unit to output. */
84 /* Number of 16-bit coding units whose output has been delayed due to
85 * possible carrying. The first such coding unit is @cache; all
86 * subsequent such coding units are 0xffff. */
89 /* Pointer to the next position in the compressed data buffer at which
90 * to output a 16-bit coding unit. */
93 /* Maximum number of 16-bit coding units that can still be output to
94 * the compressed data buffer. */
95 size_t num_le16_remaining;
97 /* %true when the very first coding unit has not yet been output. */
100 /* Set to %true if not all coding units could be output due to
101 * insufficient space. */
105 /* Structure used for range encoding. This wraps around `struct
106 * lzms_range_encoder_raw' to use and maintain probability entries. */
107 struct lzms_range_encoder {
108 /* Pointer to the raw range encoder, which has no persistent knowledge
109 * of probabilities. Multiple lzms_range_encoder's share the same
110 * lzms_range_encoder_raw. */
111 struct lzms_range_encoder_raw *rc;
113 /* Bits recently encoded by this range encoder. This are used as in
114 * index into @prob_entries. */
117 /* Bitmask for @state to prevent its value from exceeding the number of
118 * probability entries. */
121 /* Probability entries being used for this range encoder. */
122 struct lzms_probability_entry prob_entries[LZMS_MAX_NUM_STATES];
125 /* Structure used for Huffman encoding, optionally encoding larger "values" as a
126 * Huffman symbol specifying a slot and a slot-dependent number of extra bits.
128 struct lzms_huffman_encoder {
130 /* Bitstream to write Huffman-encoded symbols and verbatim bits to.
131 * Multiple lzms_huffman_encoder's share the same lzms_output_bitstream.
133 struct lzms_output_bitstream *os;
135 /* Pointer to the slot base table to use. */
136 const u32 *slot_base_tab;
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 u16 codewords[LZMS_MAX_NUM_SYMS];
160 /* State of the LZMS compressor. */
161 struct lzms_compressor {
162 /* Pointer to a buffer holding the preprocessed data to compress. */
165 /* Current position in @buffer. */
168 /* Size of the data in @buffer. */
171 /* Maximum block size this compressor instantiation allows. This is the
172 * allocated size of @window. */
175 /* Raw range encoder which outputs to the beginning of the compressed
176 * data buffer, proceeding forwards. */
177 struct lzms_range_encoder_raw rc;
179 /* Bitstream which outputs to the end of the compressed data buffer,
180 * proceeding backwards. */
181 struct lzms_output_bitstream os;
183 /* Range encoders. */
184 struct lzms_range_encoder main_range_encoder;
185 struct lzms_range_encoder match_range_encoder;
186 struct lzms_range_encoder lz_match_range_encoder;
187 struct lzms_range_encoder lz_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
188 struct lzms_range_encoder delta_match_range_encoder;
189 struct lzms_range_encoder delta_repeat_match_range_encoders[LZMS_NUM_RECENT_OFFSETS - 1];
191 /* Huffman encoders. */
192 struct lzms_huffman_encoder literal_encoder;
193 struct lzms_huffman_encoder lz_offset_encoder;
194 struct lzms_huffman_encoder length_encoder;
195 struct lzms_huffman_encoder delta_power_encoder;
196 struct lzms_huffman_encoder delta_offset_encoder;
198 /* LRU (least-recently-used) queue of LZ match offsets. */
199 u64 recent_lz_offsets[LZMS_NUM_RECENT_OFFSETS + 1];
201 /* LRU (least-recently-used) queue of delta match powers. */
202 u32 recent_delta_powers[LZMS_NUM_RECENT_OFFSETS + 1];
204 /* LRU (least-recently-used) queue of delta match offsets. */
205 u32 recent_delta_offsets[LZMS_NUM_RECENT_OFFSETS + 1];
207 /* These variables are used to delay updates to the LRU queues by one
210 u32 prev_delta_power;
211 u32 prev_delta_offset;
212 u32 upcoming_lz_offset;
213 u32 upcoming_delta_power;
214 u32 upcoming_delta_offset;
216 /* Used for preprocessing. */
217 s32 last_target_usages[65536];
225 /* Initialize the output bitstream @os to write forwards to the specified
226 * compressed data buffer @out that is @out_limit 16-bit integers long. */
228 lzms_output_bitstream_init(struct lzms_output_bitstream *os,
229 le16 *out, size_t out_limit)
232 os->num_free_bits = 16;
233 os->out = out + out_limit;
234 os->num_le16_remaining = out_limit;
238 /* Write @num_bits bits, contained in the low @num_bits bits of @bits (ordered
239 * from high-order to low-order), to the output bitstream @os. */
241 lzms_output_bitstream_put_bits(struct lzms_output_bitstream *os,
242 u32 bits, unsigned num_bits)
244 bits &= (1U << num_bits) - 1;
246 while (num_bits > os->num_free_bits) {
248 if (unlikely(os->num_le16_remaining == 0)) {
253 unsigned num_fill_bits = os->num_free_bits;
255 os->bitbuf <<= num_fill_bits;
256 os->bitbuf |= bits >> (num_bits - num_fill_bits);
258 *--os->out = cpu_to_le16(os->bitbuf);
259 --os->num_le16_remaining;
261 os->num_free_bits = 16;
262 num_bits -= num_fill_bits;
263 bits &= (1U << num_bits) - 1;
265 os->bitbuf <<= num_bits;
267 os->num_free_bits -= num_bits;
270 /* Flush the output bitstream, ensuring that all bits written to it have been
271 * written to memory. Returns %true if all bits were output successfully, or
272 * %false if an overrun occurred. */
274 lzms_output_bitstream_flush(struct lzms_output_bitstream *os)
276 if (os->num_free_bits != 16)
277 lzms_output_bitstream_put_bits(os, 0, os->num_free_bits + 1);
281 /* Initialize the range encoder @rc to write forwards to the specified
282 * compressed data buffer @out that is @out_limit 16-bit integers long. */
284 lzms_range_encoder_raw_init(struct lzms_range_encoder_raw *rc,
285 le16 *out, size_t out_limit)
288 rc->range = 0xffffffff;
292 rc->num_le16_remaining = out_limit;
298 * Attempt to flush bits from the range encoder.
300 * Note: this is based on the public domain code for LZMA written by Igor
301 * Pavlov. The only differences in this function are that in LZMS the bits must
302 * be output in 16-bit coding units instead of 8-bit coding units, and that in
303 * LZMS the first coding unit is not ignored by the decompressor, so the encoder
304 * cannot output a dummy value to that position.
306 * The basic idea is that we're writing bits from @rc->low to the output.
307 * However, due to carrying, the writing of coding units with value 0xffff, as
308 * well as one prior coding unit, must be delayed until it is determined whether
312 lzms_range_encoder_raw_shift_low(struct lzms_range_encoder_raw *rc)
314 LZMS_DEBUG("low=%"PRIx64", cache=%"PRIx64", cache_size=%u",
315 rc->low, rc->cache, rc->cache_size);
316 if ((u32)(rc->low) < 0xffff0000 ||
317 (u32)(rc->low >> 32) != 0)
319 /* Carry not needed (rc->low < 0xffff0000), or carry occurred
320 * ((rc->low >> 32) != 0, a.k.a. the carry bit is 1). */
323 if (rc->num_le16_remaining == 0) {
327 *rc->out++ = cpu_to_le16(rc->cache +
328 (u16)(rc->low >> 32));
329 --rc->num_le16_remaining;
335 } while (--rc->cache_size != 0);
337 rc->cache = (rc->low >> 16) & 0xffff;
340 rc->low = (rc->low & 0xffff) << 16;
344 lzms_range_encoder_raw_normalize(struct lzms_range_encoder_raw *rc)
346 if (rc->range <= 0xffff) {
348 lzms_range_encoder_raw_shift_low(rc);
353 lzms_range_encoder_raw_flush(struct lzms_range_encoder_raw *rc)
355 for (unsigned i = 0; i < 4; i++)
356 lzms_range_encoder_raw_shift_low(rc);
360 /* Encode the next bit using the range encoder (raw version).
362 * @prob is the chance out of LZMS_PROBABILITY_MAX that the next bit is 0. */
364 lzms_range_encoder_raw_encode_bit(struct lzms_range_encoder_raw *rc, int bit,
367 lzms_range_encoder_raw_normalize(rc);
369 u32 bound = (rc->range >> LZMS_PROBABILITY_BITS) * prob;
378 /* Encode a bit using the specified range encoder. This wraps around
379 * lzms_range_encoder_raw_encode_bit() to handle using and updating the
380 * appropriate probability table. */
382 lzms_range_encode_bit(struct lzms_range_encoder *enc, int bit)
384 struct lzms_probability_entry *prob_entry;
387 /* Load the probability entry corresponding to the current state. */
388 prob_entry = &enc->prob_entries[enc->state];
390 /* Treat the number of zero bits in the most recently encoded
391 * LZMS_PROBABILITY_MAX bits with this probability entry as the chance,
392 * out of LZMS_PROBABILITY_MAX, that the next bit will be a 0. However,
393 * don't allow 0% or 100% probabilities. */
394 prob = prob_entry->num_recent_zero_bits;
397 else if (prob == LZMS_PROBABILITY_MAX)
398 prob = LZMS_PROBABILITY_MAX - 1;
400 /* Encode the next bit. */
401 lzms_range_encoder_raw_encode_bit(enc->rc, bit, prob);
403 /* Update the state based on the newly encoded bit. */
404 enc->state = ((enc->state << 1) | bit) & enc->mask;
406 /* Update the recent bits, including the cached count of 0's. */
407 BUILD_BUG_ON(LZMS_PROBABILITY_MAX > sizeof(prob_entry->recent_bits) * 8);
409 if (prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1))) {
410 /* Replacing 1 bit with 0 bit; increment the zero count.
412 prob_entry->num_recent_zero_bits++;
415 if (!(prob_entry->recent_bits & (1ULL << (LZMS_PROBABILITY_MAX - 1)))) {
416 /* Replacing 0 bit with 1 bit; decrement the zero count.
418 prob_entry->num_recent_zero_bits--;
421 prob_entry->recent_bits = (prob_entry->recent_bits << 1) | bit;
424 /* Encode a symbol using the specified Huffman encoder. */
426 lzms_huffman_encode_symbol(struct lzms_huffman_encoder *enc, u32 sym)
428 LZMS_ASSERT(sym < enc->num_syms);
429 if (enc->num_syms_written == enc->rebuild_freq) {
430 /* Adaptive code needs to be rebuilt. */
431 LZMS_DEBUG("Rebuilding code (num_syms=%u)", enc->num_syms);
432 make_canonical_huffman_code(enc->num_syms,
433 LZMS_MAX_CODEWORD_LEN,
438 /* Dilute the frequencies. */
439 for (unsigned i = 0; i < enc->num_syms; i++) {
440 enc->sym_freqs[i] >>= 1;
441 enc->sym_freqs[i] += 1;
443 enc->num_syms_written = 0;
445 lzms_output_bitstream_put_bits(enc->os,
448 ++enc->num_syms_written;
449 ++enc->sym_freqs[sym];
452 /* Encode a number as a Huffman symbol specifying a slot, plus a number of
453 * slot-dependent extra bits. */
455 lzms_encode_value(struct lzms_huffman_encoder *enc, u32 value)
458 unsigned num_extra_bits;
461 LZMS_ASSERT(enc->slot_base_tab != NULL);
463 slot = lzms_get_slot(value, enc->slot_base_tab, enc->num_syms);
465 /* Get the number of extra bits needed to represent the range of values
466 * that share the slot. */
467 num_extra_bits = bsr32(enc->slot_base_tab[slot + 1] -
468 enc->slot_base_tab[slot]);
470 /* Calculate the extra bits as the offset from the slot base. */
471 extra_bits = value - enc->slot_base_tab[slot];
473 /* Output the slot (Huffman-encoded), then the extra bits (verbatim).
475 lzms_huffman_encode_symbol(enc, slot);
476 lzms_output_bitstream_put_bits(enc->os, extra_bits, num_extra_bits);
479 /* Encode a literal byte. */
481 lzms_encode_literal(struct lzms_compressor *ctx, u8 literal)
483 LZMS_DEBUG("Position %u: Encoding literal 0x%02x ('%c')",
484 ctx->cur_window_pos, literal, literal);
486 /* Main bit: 0 = a literal, not a match. */
487 lzms_range_encode_bit(&ctx->main_range_encoder, 0);
489 /* Encode the literal using the current literal Huffman code. */
490 lzms_huffman_encode_symbol(&ctx->literal_encoder, literal);
493 /* Encode a (length, offset) pair (LZ match). */
495 lzms_encode_lz_match(struct lzms_compressor *ctx, u32 length, u32 offset)
497 int recent_offset_idx;
499 LZMS_DEBUG("Position %u: Encoding LZ match {length=%u, offset=%u}",
500 ctx->cur_window_pos, length, offset);
502 /* Main bit: 1 = a match, not a literal. */
503 lzms_range_encode_bit(&ctx->main_range_encoder, 1);
505 /* Match bit: 0 = a LZ match, not a delta match. */
506 lzms_range_encode_bit(&ctx->match_range_encoder, 0);
508 /* Determine if the offset can be represented as a recent offset. */
509 for (recent_offset_idx = 0;
510 recent_offset_idx < LZMS_NUM_RECENT_OFFSETS;
512 if (offset == ctx->recent_lz_offsets[recent_offset_idx])
515 if (recent_offset_idx == LZMS_NUM_RECENT_OFFSETS) {
516 /* Explicit offset. */
518 /* LZ match bit: 0 = explicit offset, not a repeat offset. */
519 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 0);
521 /* Encode the match offset. */
522 lzms_encode_value(&ctx->lz_offset_encoder, offset);
529 /* LZ match bit: 0 = repeat offset, not an explicit offset. */
530 lzms_range_encode_bit(&ctx->lz_match_range_encoder, 1);
532 /* Encode the recent offset index. A 1 bit is encoded for each
533 * index passed up. This sequence of 1 bits is terminated by a
534 * 0 bit, or automatically when (LZMS_NUM_RECENT_OFFSETS - 1) 1
535 * bits have been encoded. */
536 for (i = 0; i < recent_offset_idx - 1; i++)
537 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 1);
539 if (i < LZMS_NUM_RECENT_OFFSETS - 1)
540 lzms_range_encode_bit(&ctx->lz_repeat_match_range_encoders[i], 0);
542 /* Initial update of the LZ match offset LRU queue. */
543 for (i = recent_offset_idx; i < LZMS_NUM_RECENT_OFFSETS; i++)
544 ctx->recent_lz_offsets[i] = ctx->recent_lz_offsets[i + 1];
547 /* Encode the match length. */
548 lzms_encode_value(&ctx->length_encoder, length);
550 /* Save the match offset for later insertion at the front of the LZ
551 * match offset LRU queue. */
552 ctx->upcoming_lz_offset = offset;
555 static struct lzms_match
556 lzms_get_best_match(struct lzms_compressor *ctx)
558 struct lzms_match match;
568 lzms_init_range_encoder(struct lzms_range_encoder *enc,
569 struct lzms_range_encoder_raw *rc, u32 num_states)
573 enc->mask = num_states - 1;
574 for (u32 i = 0; i < num_states; i++) {
575 enc->prob_entries[i].num_recent_zero_bits = LZMS_INITIAL_PROBABILITY;
576 enc->prob_entries[i].recent_bits = LZMS_INITIAL_RECENT_BITS;
581 lzms_init_huffman_encoder(struct lzms_huffman_encoder *enc,
582 struct lzms_output_bitstream *os,
583 const u32 *slot_base_tab,
585 unsigned rebuild_freq)
588 enc->slot_base_tab = slot_base_tab;
589 enc->num_syms_written = rebuild_freq;
590 enc->rebuild_freq = rebuild_freq;
591 enc->num_syms = num_syms;
592 for (unsigned i = 0; i < num_syms; i++)
593 enc->sym_freqs[i] = 1;
596 /* Initialize the LZMS compressor. */
598 lzms_init_compressor(struct lzms_compressor *ctx, const u8 *udata, u32 ulen,
599 le16 *cdata, u32 clen16)
601 unsigned num_position_slots;
603 /* Copy the uncompressed data into the @ctx->window buffer. */
604 memcpy(ctx->window, udata, ulen);
605 ctx->cur_window_pos = 0;
606 ctx->window_size = ulen;
608 /* Initialize the raw range encoder (writing forwards). */
609 lzms_range_encoder_raw_init(&ctx->rc, cdata, clen16);
611 /* Initialize the output bitstream for Huffman symbols and verbatim bits
612 * (writing backwards). */
613 lzms_output_bitstream_init(&ctx->os, cdata, clen16);
615 /* Initialize position and length slot bases if not done already. */
616 lzms_init_slot_bases();
618 /* Calculate the number of position slots needed for this compressed
620 num_position_slots = lzms_get_position_slot(ulen - 1) + 1;
622 LZMS_DEBUG("Using %u position slots", num_position_slots);
624 /* Initialize Huffman encoders for each alphabet used in the compressed
626 lzms_init_huffman_encoder(&ctx->literal_encoder, &ctx->os,
627 NULL, LZMS_NUM_LITERAL_SYMS,
628 LZMS_LITERAL_CODE_REBUILD_FREQ);
630 lzms_init_huffman_encoder(&ctx->lz_offset_encoder, &ctx->os,
631 lzms_position_slot_base, num_position_slots,
632 LZMS_LZ_OFFSET_CODE_REBUILD_FREQ);
634 lzms_init_huffman_encoder(&ctx->length_encoder, &ctx->os,
635 lzms_length_slot_base, LZMS_NUM_LEN_SYMS,
636 LZMS_LENGTH_CODE_REBUILD_FREQ);
638 lzms_init_huffman_encoder(&ctx->delta_offset_encoder, &ctx->os,
639 lzms_position_slot_base, num_position_slots,
640 LZMS_DELTA_OFFSET_CODE_REBUILD_FREQ);
642 lzms_init_huffman_encoder(&ctx->delta_power_encoder, &ctx->os,
643 NULL, LZMS_NUM_DELTA_POWER_SYMS,
644 LZMS_DELTA_POWER_CODE_REBUILD_FREQ);
646 /* Initialize range encoders, all of which wrap around the same
647 * lzms_range_encoder_raw. */
648 lzms_init_range_encoder(&ctx->main_range_encoder,
649 &ctx->rc, LZMS_NUM_MAIN_STATES);
651 lzms_init_range_encoder(&ctx->match_range_encoder,
652 &ctx->rc, LZMS_NUM_MATCH_STATES);
654 lzms_init_range_encoder(&ctx->lz_match_range_encoder,
655 &ctx->rc, LZMS_NUM_LZ_MATCH_STATES);
657 for (size_t i = 0; i < ARRAY_LEN(ctx->lz_repeat_match_range_encoders); i++)
658 lzms_init_range_encoder(&ctx->lz_repeat_match_range_encoders[i],
659 &ctx->rc, LZMS_NUM_LZ_REPEAT_MATCH_STATES);
661 lzms_init_range_encoder(&ctx->delta_match_range_encoder,
662 &ctx->rc, LZMS_NUM_DELTA_MATCH_STATES);
664 for (size_t i = 0; i < ARRAY_LEN(ctx->delta_repeat_match_range_encoders); i++)
665 lzms_init_range_encoder(&ctx->delta_repeat_match_range_encoders[i],
666 &ctx->rc, LZMS_NUM_DELTA_REPEAT_MATCH_STATES);
668 /* Initialize the LRU queue for recent match offsets. */
669 for (size_t i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++)
670 ctx->recent_lz_offsets[i] = i + 1;
672 for (size_t i = 0; i < LZMS_NUM_RECENT_OFFSETS + 1; i++) {
673 ctx->recent_delta_powers[i] = 0;
674 ctx->recent_delta_offsets[i] = i + 1;
676 ctx->prev_lz_offset = 0;
677 ctx->prev_delta_offset = 0;
678 ctx->prev_delta_power = 0;
679 ctx->upcoming_lz_offset = 0;
680 ctx->upcoming_delta_offset = 0;
681 ctx->upcoming_delta_power = 0;
684 /* Flush the output streams, prepare the final compressed data, and return its
687 * A return value of 0 indicates that the data could not be compressed to fit in
688 * the available space. */
690 lzms_finalize(struct lzms_compressor *ctx, u8 *cdata, size_t csize_avail)
692 size_t num_forwards_bytes;
693 size_t num_backwards_bytes;
694 size_t compressed_size;
696 /* Flush both the forwards and backwards streams, and make sure they
697 * didn't cross each other and start overwriting each other's data. */
698 if (!lzms_output_bitstream_flush(&ctx->os)) {
699 LZMS_DEBUG("Backwards bitstream overrun.");
703 if (!lzms_range_encoder_raw_flush(&ctx->rc)) {
704 LZMS_DEBUG("Forwards bitstream overrun.");
708 if (ctx->rc.out > ctx->os.out) {
709 LZMS_DEBUG("Two bitstreams crossed.");
713 /* Now the compressed buffer contains the data output by the forwards
714 * bitstream, then empty space, then data output by the backwards
715 * bitstream. Move the data output by the forwards bitstream to be
716 * adjacent to the data output by the backwards bitstream, and calculate
717 * the compressed size that this results in. */
718 num_forwards_bytes = (u8*)ctx->rc.out - (u8*)cdata;
719 num_backwards_bytes = ((u8*)cdata + csize_avail) - (u8*)ctx->os.out;
721 memmove(cdata + num_forwards_bytes, ctx->os.out, num_backwards_bytes);
723 compressed_size = num_forwards_bytes + num_backwards_bytes;
724 LZMS_DEBUG("num_forwards_bytes=%zu, num_backwards_bytes=%zu, "
725 "compressed_size=%zu",
726 num_forwards_bytes, num_backwards_bytes, compressed_size);
727 LZMS_ASSERT(!(compressed_size & 1));
728 return compressed_size;
732 lzms_compress(const void *uncompressed_data, size_t uncompressed_size,
733 void *compressed_data, size_t compressed_size_avail, void *_ctx)
735 struct lzms_compressor *ctx = _ctx;
736 struct lzms_match match;
737 size_t compressed_size;
739 LZMS_DEBUG("uncompressed_size=%zu, compressed_size_avail=%zu",
740 uncompressed_size, compressed_size_avail);
742 /* Make sure the uncompressed size is compatible with this compressor.
744 if (uncompressed_size > ctx->max_block_size) {
745 LZMS_DEBUG("Can't compress %zu bytes: LZMS context "
746 "only supports %u bytes",
747 uncompressed_size, ctx->max_block_size);
751 /* Don't bother compressing extremely small inputs. */
752 if (uncompressed_size < 4)
755 /* Cap the available compressed size to a 32-bit integer, and round it
756 * down to the nearest multiple of 2. */
757 if (compressed_size_avail > UINT32_MAX)
758 compressed_size_avail = UINT32_MAX;
759 if (compressed_size_avail & 1)
760 compressed_size_avail--;
762 /* Initialize the compressor structures. */
763 lzms_init_compressor(ctx, uncompressed_data, uncompressed_size,
764 compressed_data, compressed_size_avail / 2);
766 /* Preprocess the uncompressed data. */
767 lzms_x86_filter(ctx->window, ctx->window_size,
768 ctx->last_target_usages, false);
770 /* Determine and output a literal/match sequence that decompresses to
771 * the preprocessed data. */
772 while (ctx->cur_window_pos != ctx->window_size) {
773 match = lzms_get_best_match(ctx);
774 if (match.length == 0) {
776 lzms_encode_literal(ctx, ctx->window[ctx->cur_window_pos]);
777 ctx->cur_window_pos++;
780 lzms_encode_lz_match(ctx, match.length, match.offset);
781 ctx->cur_window_pos += match.length;
785 /* Get and return the compressed data size. */
786 compressed_size = lzms_finalize(ctx, compressed_data,
787 compressed_size_avail);
789 if (compressed_size == 0) {
790 LZMS_DEBUG("Data did not compress to requested size or less.");
794 LZMS_DEBUG("Compressed %zu => %zu bytes",
795 uncompressed_size, compressed_size);
797 #if defined(ENABLE_VERIFY_COMPRESSION) || defined(ENABLE_LZMS_DEBUG)
798 /* Verify that we really get the same thing back when decompressing. */
800 struct wimlib_decompressor *decompressor;
802 LZMS_DEBUG("Verifying LZMS compression.");
804 if (0 == wimlib_create_decompressor(WIMLIB_COMPRESSION_TYPE_LZMS,
810 ret = wimlib_decompress(compressed_data,
815 wimlib_free_decompressor(decompressor);
818 ERROR("Failed to decompress data we "
819 "compressed using LZMN algorithm");
823 if (memcmp(uncompressed_data, ctx->window,
826 ERROR("Data we compressed using LZMN algorithm "
827 "didn't decompress to original");
832 WARNING("Failed to create decompressor for "
833 "data verification!");
836 #endif /* ENABLE_LZMS_DEBUG || ENABLE_VERIFY_COMPRESSION */
838 return compressed_size;
842 lzms_free_compressor(void *_ctx)
844 struct lzms_compressor *ctx = _ctx;
853 lzms_create_compressor(size_t max_block_size,
854 const struct wimlib_compressor_params_header *params,
857 struct lzms_compressor *ctx;
859 if (max_block_size == 0 || max_block_size >= INT32_MAX) {
860 LZMS_DEBUG("Invalid max_block_size (%u)", max_block_size);
861 return WIMLIB_ERR_INVALID_PARAM;
864 ctx = CALLOC(1, sizeof(struct lzms_compressor));
868 ctx->window = MALLOC(max_block_size);
869 if (ctx->window == NULL)
871 ctx->max_block_size = max_block_size;
877 lzms_free_compressor(ctx);
878 return WIMLIB_ERR_NOMEM;
881 const struct compressor_ops lzms_compressor_ops = {
882 .create_compressor = lzms_create_compressor,
883 .compress = lzms_compress,
884 .free_compressor = lzms_free_compressor,