4 * A compressor for the XPRESS compression format (Huffman variant).
8 * Copyright (C) 2012, 2013, 2014 Eric Biggers
10 * This file is free software; you can redistribute it and/or modify it under
11 * the terms of the GNU Lesser General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option) any
15 * This file is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this file; if not, see http://www.gnu.org/licenses/.
29 * The maximum buffer size, in bytes, that can be compressed. An XPRESS
30 * compressor instance must be created with a 'max_bufsize' less than or equal
33 #define XPRESS_MAX_BUFSIZE 65536
36 * Define to 1 to enable the near-optimal parsing algorithm at high compression
37 * levels. The near-optimal parsing algorithm produces a compression ratio
38 * significantly better than the greedy and lazy algorithms. However, it is
41 #define SUPPORT_NEAR_OPTIMAL_PARSING 1
44 * The lowest compression level at which near-optimal parsing is enabled.
46 #define MIN_LEVEL_FOR_NEAR_OPTIMAL 60
49 * Matchfinder definitions. For XPRESS, only a 16-bit matchfinder is needed.
55 * Note: although XPRESS can potentially use a sliding window, it isn't well
56 * suited for large buffers of data because there is no way to reset the Huffman
57 * code. Therefore, we only allow buffers in which there is no restriction on
58 * match offsets (no sliding window). This simplifies the code and allows some
62 #include "wimlib/bitops.h"
63 #include "wimlib/compress_common.h"
64 #include "wimlib/compressor_ops.h"
65 #include "wimlib/endianness.h"
66 #include "wimlib/error.h"
67 #include "wimlib/hc_matchfinder.h"
68 #include "wimlib/unaligned.h"
69 #include "wimlib/util.h"
70 #include "wimlib/xpress_constants.h"
72 #if SUPPORT_NEAR_OPTIMAL_PARSING
75 * CACHE_RESERVE_PER_POS is the number of lz_match structures to reserve in the
76 * match cache for each byte position. This value should be high enough so that
77 * virtually the time, all matches found in the input buffer can fit in the
78 * match cache. However, fallback behavior on cache overflow is still required.
80 #define CACHE_RESERVE_PER_POS 8
83 * We use a binary-tree based matchfinder for optimal parsing because it can
84 * find more matches in the same number of steps compared to hash-chain based
85 * matchfinders. In addition, since we need to find matches at almost every
86 * position, there isn't much penalty for keeping the sequences sorted in the
89 #include "wimlib/bt_matchfinder.h"
91 struct xpress_optimum_node;
93 #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */
97 /* The main XPRESS compressor structure */
98 struct xpress_compressor {
100 /* Pointer to the compress() implementation chosen at allocation time */
101 size_t (*impl)(struct xpress_compressor *,
102 const void *, size_t, void *, size_t);
104 /* Symbol frequency counters for the Huffman code */
105 u32 freqs[XPRESS_NUM_SYMBOLS];
107 /* The Huffman codewords and their lengths */
108 u32 codewords[XPRESS_NUM_SYMBOLS];
109 u8 lens[XPRESS_NUM_SYMBOLS];
111 /* The "nice" match length: if a match of this length is found, then
112 * choose it immediately without further consideration. */
113 unsigned nice_match_length;
115 /* The maximum search depth: consider at most this many potential
116 * matches at each position. */
117 unsigned max_search_depth;
120 /* Data for greedy or lazy parsing */
122 struct xpress_item *chosen_items;
123 struct hc_matchfinder hc_mf;
124 /* hc_mf must be last! */
127 #if SUPPORT_NEAR_OPTIMAL_PARSING
128 /* Data for near-optimal parsing */
130 struct xpress_optimum_node *optimum_nodes;
131 struct lz_match *match_cache;
132 struct lz_match *cache_overflow_mark;
133 unsigned num_optim_passes;
134 u32 costs[XPRESS_NUM_SYMBOLS];
135 struct bt_matchfinder bt_mf;
136 /* bt_mf must be last! */
142 #if SUPPORT_NEAR_OPTIMAL_PARSING
145 * This structure represents a byte position in the input buffer and a node in
146 * the graph of possible match/literal choices.
148 * Logically, each incoming edge to this node is labeled with a literal or a
149 * match that can be taken to reach this position from an earlier position; and
150 * each outgoing edge from this node is labeled with a literal or a match that
151 * can be taken to advance from this position to a later position.
153 * But these "edges" are actually stored elsewhere (in 'match_cache'). Here we
154 * associate with each node just two pieces of information:
156 * 'cost_to_end' is the minimum cost to reach the end of the buffer from
159 * 'item' represents the literal or match that must be chosen from here to
160 * reach the end of the buffer with the minimum cost. Equivalently, this
161 * can be interpreted as the label of the outgoing edge on the minimum cost
162 * path to the "end of buffer" node from this node.
164 struct xpress_optimum_node {
169 * Notes on the match/literal representation used here:
171 * The low bits of 'item' are the length: 1 if the item is a
172 * literal, or the match length if the item is a match.
174 * The high bits of 'item' are the actual literal byte if the item
175 * is a literal, or the match offset if the item is a match.
177 #define OPTIMUM_OFFSET_SHIFT 16
178 #define OPTIMUM_LEN_MASK (((u32)1 << OPTIMUM_OFFSET_SHIFT) - 1)
182 #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */
184 /* An intermediate representation of an XPRESS match or literal */
188 * Bits 9 - 24: Length - XPRESS_MIN_MATCH_LEN
189 * Bits 25 - 28: Number of extra offset bits
190 * Bits 29+ : Extra offset bits
192 * Unfortunately, gcc generates worse code if we use real bitfields here.
198 * Structure to keep track of the current state of sending compressed data to
201 * The XPRESS bitstream is encoded as a sequence of little endian 16-bit coding
202 * units interwoven with literal bytes.
204 struct xpress_output_bitstream {
206 /* Bits that haven't yet been written to the output buffer. */
209 /* Number of bits currently held in @bitbuf. */
212 /* Pointer to the start of the output buffer. */
215 /* Pointer to the location in the ouput buffer at which to write the
219 /* Pointer to the location in the output buffer at which to write the
220 * next 16 bits, after @next_bits. */
223 /* Pointer to the location in the output buffer at which to write the
224 * next literal byte. */
227 /* Pointer to the end of the output buffer. */
231 /* Reset the symbol frequencies for the XPRESS Huffman code. */
233 xpress_reset_symbol_frequencies(struct xpress_compressor *c)
235 memset(c->freqs, 0, sizeof(c->freqs));
239 * Make the Huffman code for XPRESS.
242 * Output: c->lens and c->codewords
245 xpress_make_huffman_code(struct xpress_compressor *c)
247 make_canonical_huffman_code(XPRESS_NUM_SYMBOLS, XPRESS_MAX_CODEWORD_LEN,
248 c->freqs, c->lens, c->codewords);
252 * Initialize the output bitstream.
255 * The output bitstream structure to initialize.
259 * Size of @buffer, in bytes. Must be at least 4.
262 xpress_init_output(struct xpress_output_bitstream *os, void *buffer, size_t size)
267 os->next_bits = os->start;
268 os->next_bits2 = os->start + 2;
269 os->next_byte = os->start + 4;
270 os->end = os->start + size;
274 * Write some bits to the output bitstream.
276 * The bits are given by the low-order @num_bits bits of @bits. Higher-order
277 * bits in @bits cannot be set. At most 16 bits can be written at once.
279 * If the output buffer space is exhausted, then the bits will be ignored, and
280 * xpress_flush_output() will return 0 when it gets called.
283 xpress_write_bits(struct xpress_output_bitstream *os,
284 const u32 bits, const unsigned num_bits)
286 /* This code is optimized for XPRESS, which never needs to write more
287 * than 16 bits at once. */
289 os->bitcount += num_bits;
290 os->bitbuf = (os->bitbuf << num_bits) | bits;
292 if (os->bitcount > 16) {
294 if (os->end - os->next_byte >= 2) {
295 put_unaligned_u16_le(os->bitbuf >> os->bitcount, os->next_bits);
296 os->next_bits = os->next_bits2;
297 os->next_bits2 = os->next_byte;
304 * Interweave a literal byte into the output bitstream.
307 xpress_write_byte(struct xpress_output_bitstream *os, u8 byte)
309 if (os->next_byte < os->end)
310 *os->next_byte++ = byte;
314 * Interweave two literal bytes into the output bitstream.
317 xpress_write_u16(struct xpress_output_bitstream *os, u16 v)
319 if (os->end - os->next_byte >= 2) {
320 put_unaligned_u16_le(v, os->next_byte);
326 * Flush the last coding unit to the output buffer if needed. Return the total
327 * number of bytes written to the output buffer, or 0 if an overflow occurred.
330 xpress_flush_output(struct xpress_output_bitstream *os)
332 if (os->end - os->next_byte < 2)
335 put_unaligned_u16_le(os->bitbuf << (16 - os->bitcount), os->next_bits);
336 put_unaligned_u16_le(0, os->next_bits2);
338 return os->next_byte - os->start;
342 xpress_write_extra_length_bytes(struct xpress_output_bitstream *os,
343 unsigned adjusted_len)
345 /* If length >= 18, output one extra length byte.
346 * If length >= 273, output three (total) extra length bytes. */
347 if (adjusted_len >= 0xF) {
348 u8 byte1 = min(adjusted_len - 0xF, 0xFF);
349 xpress_write_byte(os, byte1);
351 xpress_write_u16(os, adjusted_len);
355 /* Output a match or literal. */
357 xpress_write_item(struct xpress_item item, struct xpress_output_bitstream *os,
358 const u32 codewords[], const u8 lens[])
360 u64 data = item.data;
361 unsigned symbol = data & 0x1FF;
363 xpress_write_bits(os, codewords[symbol], lens[symbol]);
365 if (symbol >= XPRESS_NUM_CHARS) {
366 /* Match, not a literal */
367 xpress_write_extra_length_bytes(os, (data >> 9) & 0xFFFF);
368 xpress_write_bits(os, data >> 29, (data >> 25) & 0xF);
372 /* Output a sequence of XPRESS matches and literals. */
374 xpress_write_items(struct xpress_output_bitstream *os,
375 const struct xpress_item items[], size_t num_items,
376 const u32 codewords[], const u8 lens[])
378 for (size_t i = 0; i < num_items; i++)
379 xpress_write_item(items[i], os, codewords, lens);
382 #if SUPPORT_NEAR_OPTIMAL_PARSING
385 * Follow the minimum cost path in the graph of possible match/literal choices
386 * and write out the matches/literals using the specified Huffman code.
388 * Note: this is slightly duplicated with xpress_write_items(). However, we
389 * don't want to waste time translating between intermediate match/literal
393 xpress_write_item_list(struct xpress_output_bitstream *os,
394 struct xpress_optimum_node *optimum_nodes,
395 size_t count, const u32 codewords[], const u8 lens[])
397 struct xpress_optimum_node *cur_node = optimum_nodes;
398 struct xpress_optimum_node *end_node = optimum_nodes + count;
400 unsigned length = cur_node->item & OPTIMUM_LEN_MASK;
401 unsigned offset = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
405 unsigned literal = offset;
407 xpress_write_bits(os, codewords[literal], lens[literal]);
410 unsigned adjusted_len;
411 unsigned log2_offset;
415 adjusted_len = length - XPRESS_MIN_MATCH_LEN;
416 log2_offset = fls32(offset);
417 len_hdr = min(0xF, adjusted_len);
418 sym = XPRESS_NUM_CHARS + ((log2_offset << 4) | len_hdr);
420 xpress_write_bits(os, codewords[sym], lens[sym]);
421 xpress_write_extra_length_bytes(os, adjusted_len);
422 xpress_write_bits(os, offset - (1U << log2_offset),
426 } while (cur_node != end_node);
428 #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */
431 * Output the XPRESS-compressed data, given the sequence of match/literal
432 * "items" that was chosen to represent the input data.
434 * If @near_optimal is %false, then the items are taken from the array
435 * c->chosen_items[0...count].
437 * If @near_optimal is %true, then the items are taken from the minimum cost
438 * path stored in c->optimum_nodes[0...count].
441 xpress_write(struct xpress_compressor *c, void *out, size_t out_nbytes_avail,
442 size_t count, bool near_optimal)
445 struct xpress_output_bitstream os;
448 /* Account for the end-of-data symbol and make the Huffman code. */
449 c->freqs[XPRESS_END_OF_DATA]++;
450 xpress_make_huffman_code(c);
452 /* Output the Huffman code as a series of 512 4-bit lengths. */
454 for (unsigned i = 0; i < XPRESS_NUM_SYMBOLS; i += 2)
455 *cptr++ = (c->lens[i + 1] << 4) | c->lens[i];
457 xpress_init_output(&os, cptr, out_nbytes_avail - XPRESS_NUM_SYMBOLS / 2);
459 /* Output the Huffman-encoded items. */
460 #if SUPPORT_NEAR_OPTIMAL_PARSING
462 xpress_write_item_list(&os, c->optimum_nodes, count,
463 c->codewords, c->lens);
468 xpress_write_items(&os, c->chosen_items, count,
469 c->codewords, c->lens);
472 /* Write the end-of-data symbol (needed for MS compatibility) */
473 xpress_write_bits(&os, c->codewords[XPRESS_END_OF_DATA],
474 c->lens[XPRESS_END_OF_DATA]);
476 /* Flush any pending data. Then return the compressed size if the
477 * compressed data fit in the output buffer, or 0 if it did not. */
478 out_size = xpress_flush_output(&os);
482 return out_size + XPRESS_NUM_SYMBOLS / 2;
485 /* Tally the Huffman symbol for a literal and return the intermediate
486 * representation of that literal. */
487 static inline struct xpress_item
488 xpress_record_literal(struct xpress_compressor *c, unsigned literal)
492 return (struct xpress_item) {
497 /* Tally the Huffman symbol for a match and return the intermediate
498 * representation of that match. */
499 static inline struct xpress_item
500 xpress_record_match(struct xpress_compressor *c, unsigned length, unsigned offset)
502 unsigned adjusted_len = length - XPRESS_MIN_MATCH_LEN;
503 unsigned len_hdr = min(adjusted_len, 0xF);
504 unsigned log2_offset = fls32(offset);
505 unsigned sym = XPRESS_NUM_CHARS + ((log2_offset << 4) | len_hdr);
509 return (struct xpress_item) {
511 ((u64)adjusted_len << 9) |
512 ((u64)log2_offset << 25) |
513 ((u64)(offset ^ (1U << log2_offset)) << 29),
518 * This is the "greedy" XPRESS compressor. It always chooses the longest match.
519 * (Exception: as a heuristic, we pass up length 3 matches that have large
523 xpress_compress_greedy(struct xpress_compressor * restrict c,
524 const void * restrict in, size_t in_nbytes,
525 void * restrict out, size_t out_nbytes_avail)
527 const u8 * const in_begin = in;
528 const u8 * in_next = in_begin;
529 const u8 * const in_end = in_begin + in_nbytes;
530 struct xpress_item *next_chosen_item = c->chosen_items;
531 unsigned len_3_too_far;
532 u32 next_hashes[2] = {};
534 if (in_nbytes <= 8192)
535 len_3_too_far = 2048;
537 len_3_too_far = 4096;
539 hc_matchfinder_init(&c->hc_mf);
545 length = hc_matchfinder_longest_match(&c->hc_mf,
548 XPRESS_MIN_MATCH_LEN - 1,
550 min(in_end - in_next, c->nice_match_length),
554 if (length >= XPRESS_MIN_MATCH_LEN &&
555 !(length == XPRESS_MIN_MATCH_LEN && offset >= len_3_too_far))
558 *next_chosen_item++ =
559 xpress_record_match(c, length, offset);
561 hc_matchfinder_skip_positions(&c->hc_mf,
567 in_next += length - 1;
570 *next_chosen_item++ =
571 xpress_record_literal(c, *in_next);
574 } while (in_next != in_end);
576 return xpress_write(c, out, out_nbytes_avail,
577 next_chosen_item - c->chosen_items, false);
581 * This is the "lazy" XPRESS compressor. Before choosing a match, it checks to
582 * see if there's a longer match at the next position. If yes, it outputs a
583 * literal and continues to the next position. If no, it outputs the match.
586 xpress_compress_lazy(struct xpress_compressor * restrict c,
587 const void * restrict in, size_t in_nbytes,
588 void * restrict out, size_t out_nbytes_avail)
590 const u8 * const in_begin = in;
591 const u8 * in_next = in_begin;
592 const u8 * const in_end = in_begin + in_nbytes;
593 struct xpress_item *next_chosen_item = c->chosen_items;
594 unsigned len_3_too_far;
595 u32 next_hashes[2] = {};
597 if (in_nbytes <= 8192)
598 len_3_too_far = 2048;
600 len_3_too_far = 4096;
602 hc_matchfinder_init(&c->hc_mf);
608 unsigned next_offset;
610 /* Find the longest match at the current position. */
611 cur_len = hc_matchfinder_longest_match(&c->hc_mf,
614 XPRESS_MIN_MATCH_LEN - 1,
616 min(in_end - in_next, c->nice_match_length),
622 if (cur_len < XPRESS_MIN_MATCH_LEN ||
623 (cur_len == XPRESS_MIN_MATCH_LEN &&
624 cur_offset >= len_3_too_far))
626 /* No match found. Choose a literal. */
627 *next_chosen_item++ =
628 xpress_record_literal(c, *(in_next - 1));
633 /* We have a match at the current position. */
635 /* If the current match is very long, choose it immediately. */
636 if (cur_len >= c->nice_match_length) {
638 *next_chosen_item++ =
639 xpress_record_match(c, cur_len, cur_offset);
641 hc_matchfinder_skip_positions(&c->hc_mf,
647 in_next += cur_len - 1;
652 * Try to find a match at the next position.
654 * Note: since we already have a match at the *current*
655 * position, we use only half the 'max_search_depth' when
656 * checking the *next* position. This is a useful trade-off
657 * because it's more worthwhile to use a greater search depth on
658 * the initial match than on the next match (since a lot of the
659 * time, that next match won't even be used).
661 * Note: it's possible to structure the code such that there's
662 * only one call to longest_match(), which handles both the
663 * "find the initial match" and "try to find a longer match"
664 * cases. However, it is faster to have two call sites, with
665 * longest_match() inlined at each.
667 next_len = hc_matchfinder_longest_match(&c->hc_mf,
672 min(in_end - in_next, c->nice_match_length),
673 c->max_search_depth / 2,
678 if (next_len > cur_len) {
679 /* Found a longer match at the next position, so output
681 *next_chosen_item++ =
682 xpress_record_literal(c, *(in_next - 2));
684 cur_offset = next_offset;
687 /* Didn't find a longer match at the next position, so
688 * output the current match. */
689 *next_chosen_item++ =
690 xpress_record_match(c, cur_len, cur_offset);
691 hc_matchfinder_skip_positions(&c->hc_mf,
697 in_next += cur_len - 2;
700 } while (in_next != in_end);
702 return xpress_write(c, out, out_nbytes_avail,
703 next_chosen_item - c->chosen_items, false);
706 #if SUPPORT_NEAR_OPTIMAL_PARSING
709 * Set Huffman symbol costs for the first optimization pass.
711 * It works well to assume that each Huffman symbol is equally probable. This
712 * results in each symbol being assigned a cost of -log2(1.0/num_syms) where
713 * 'num_syms' is the number of symbols in the alphabet.
716 xpress_set_default_costs(struct xpress_compressor *c)
718 for (unsigned i = 0; i < XPRESS_NUM_SYMBOLS; i++)
722 /* Update the cost model based on the codeword lengths @c->lens. */
724 xpress_update_costs(struct xpress_compressor *c)
726 for (unsigned i = 0; i < XPRESS_NUM_SYMBOLS; i++)
727 c->costs[i] = c->lens[i] ? c->lens[i] : XPRESS_MAX_CODEWORD_LEN;
731 * Follow the minimum cost path in the graph of possible match/literal choices
732 * and compute the frequencies of the Huffman symbols that are needed to output
733 * those matches and literals.
736 xpress_tally_item_list(struct xpress_compressor *c,
737 struct xpress_optimum_node *end_node)
739 struct xpress_optimum_node *cur_node = c->optimum_nodes;
742 unsigned length = cur_node->item & OPTIMUM_LEN_MASK;
743 unsigned offset = cur_node->item >> OPTIMUM_OFFSET_SHIFT;
747 unsigned literal = offset;
752 unsigned adjusted_len;
753 unsigned log2_offset;
757 adjusted_len = length - XPRESS_MIN_MATCH_LEN;
758 log2_offset = fls32(offset);
759 len_hdr = min(0xF, adjusted_len);
760 sym = XPRESS_NUM_CHARS + ((log2_offset << 4) | len_hdr);
765 } while (cur_node != end_node);
769 * Find a new minimum cost path through the graph of possible match/literal
770 * choices. We find the minimum cost path from 'c->optimum_nodes[0]', which
771 * represents the node at the beginning of the input buffer, to
772 * 'c->optimum_nodes[in_nbytes]', which represents the node at the end of the
773 * input buffer. Edge costs are evaluated using the cost model 'c->costs'.
775 * The algorithm works backward, starting at 'c->optimum_nodes[in_nbytes]' and
776 * proceeding backwards one position at a time. At each position, the minimum
777 * cost to reach 'c->optimum_nodes[in_nbytes]' from that position is computed
778 * and the match/literal choice is saved.
781 xpress_find_min_cost_path(struct xpress_compressor *c, size_t in_nbytes,
782 struct lz_match *end_cache_ptr)
784 struct xpress_optimum_node *cur_node = c->optimum_nodes + in_nbytes;
785 struct lz_match *cache_ptr = end_cache_ptr;
787 cur_node->cost_to_end = 0;
791 u32 best_cost_to_end;
792 unsigned num_matches;
793 struct lz_match *match;
799 literal = cache_ptr->offset;
801 /* Consider coding a literal. */
802 best_item = ((u32)literal << OPTIMUM_OFFSET_SHIFT) | 1;
803 best_cost_to_end = c->costs[literal] +
804 (cur_node + 1)->cost_to_end;
806 num_matches = cache_ptr->length;
808 if (num_matches == 0) {
809 /* No matches; the only choice is the literal. */
810 cur_node->cost_to_end = best_cost_to_end;
811 cur_node->item = best_item;
816 * Consider each match length from the minimum
817 * (XPRESS_MIN_MATCH_LEN) to the length of the longest match
818 * found at this position. For each length, consider only the
819 * smallest offset for which that length is available. Although
820 * this is not guaranteed to be optimal due to the possibility
821 * of a larger offset costing less than a smaller offset to
822 * code, this is a very useful heuristic.
824 match = cache_ptr - num_matches;
825 len = XPRESS_MIN_MATCH_LEN;
826 if (cache_ptr[-1].length < 0xF + XPRESS_MIN_MATCH_LEN) {
827 /* All lengths are small. Optimize accordingly. */
830 unsigned log2_offset;
833 offset = match->offset;
834 log2_offset = fls32(offset);
835 offset_cost = log2_offset;
841 len_hdr = len - XPRESS_MIN_MATCH_LEN;
842 sym = XPRESS_NUM_CHARS +
843 ((log2_offset << 4) | len_hdr);
845 offset_cost + c->costs[sym] +
846 (cur_node + len)->cost_to_end;
847 if (cost_to_end < best_cost_to_end) {
848 best_cost_to_end = cost_to_end;
851 OPTIMUM_OFFSET_SHIFT) | len;
853 } while (++len <= match->length);
854 } while (++match != cache_ptr);
856 /* Some lengths are big. */
859 unsigned log2_offset;
862 offset = match->offset;
863 log2_offset = fls32(offset);
864 offset_cost = log2_offset;
866 unsigned adjusted_len;
871 adjusted_len = len - XPRESS_MIN_MATCH_LEN;
872 len_hdr = min(adjusted_len, 0xF);
873 sym = XPRESS_NUM_CHARS +
874 ((log2_offset << 4) | len_hdr);
876 offset_cost + c->costs[sym] +
877 (cur_node + len)->cost_to_end;
878 if (adjusted_len >= 0xF) {
880 if (adjusted_len - 0xF >= 0xFF)
883 if (cost_to_end < best_cost_to_end) {
884 best_cost_to_end = cost_to_end;
887 OPTIMUM_OFFSET_SHIFT) | len;
889 } while (++len <= match->length);
890 } while (++match != cache_ptr);
892 cache_ptr -= num_matches;
893 cur_node->cost_to_end = best_cost_to_end;
894 cur_node->item = best_item;
895 } while (cur_node != c->optimum_nodes);
899 * This routine finds matches at each position in the buffer in[0...in_nbytes].
900 * The matches are cached in the array c->match_cache, and the return value is a
901 * pointer past the last slot in this array that was filled.
903 static struct lz_match *
904 xpress_find_matches(struct xpress_compressor * restrict c,
905 const void * restrict in, size_t in_nbytes)
907 const u8 * const in_begin = in;
908 const u8 *in_next = in_begin;
909 const u8 * const in_end = in_begin + in_nbytes;
910 struct lz_match *cache_ptr = c->match_cache;
913 bt_matchfinder_init(&c->bt_mf);
916 struct lz_match *matches;
919 /* If we've found so many matches that the cache might overflow
920 * if we keep finding more, then stop finding matches. This
921 * case is very unlikely. */
922 if (unlikely(cache_ptr >= c->cache_overflow_mark)) {
924 cache_ptr->length = 0;
925 cache_ptr->offset = *in_next++;
927 } while (in_next != in_end);
933 /* Find matches with the current position using the binary tree
934 * matchfinder and save them in the next available slots in
935 * the match cache. */
937 bt_matchfinder_get_matches(&c->bt_mf,
941 min(in_end - in_next, c->nice_match_length),
946 cache_ptr->length = cache_ptr - matches;
947 cache_ptr->offset = *in_next;
952 * If there was a very long match found, then don't cache any
953 * matches for the bytes covered by that match. This avoids
954 * degenerate behavior when compressing highly redundant data,
955 * where the number of matches can be very large.
957 * This heuristic doesn't actually hurt the compression ratio
958 * very much. If there's a long match, then the data must be
959 * highly compressible, so it doesn't matter as much what we do.
961 if (best_len >= c->nice_match_length) {
964 bt_matchfinder_skip_position(&c->bt_mf,
968 min(in_end - in_next,
969 c->nice_match_length),
973 cache_ptr->length = 0;
974 cache_ptr->offset = *in_next++;
976 } while (--best_len);
978 } while (in_next != in_end);
984 * This is the "near-optimal" XPRESS compressor. It computes a compressed
985 * representation of the input buffer by executing a minimum cost path search
986 * over the graph of possible match/literal choices, assuming a certain cost for
987 * each Huffman symbol. The result is usually close to optimal, but it is *not*
988 * guaranteed to be optimal because of (a) heuristic restrictions in which
989 * matches are considered, and (b) symbol costs are unknown until those symbols
990 * have already been chosen --- so iterative optimization must be used, and the
991 * algorithm might converge on a local optimum rather than a global optimum.
994 xpress_compress_near_optimal(struct xpress_compressor * restrict c,
995 const void * restrict in, size_t in_nbytes,
996 void * restrict out, size_t out_nbytes_avail)
998 struct lz_match *end_cache_ptr;
999 unsigned num_passes_remaining = c->num_optim_passes;
1001 /* Run the input buffer through the matchfinder and save the results. */
1002 end_cache_ptr = xpress_find_matches(c, in, in_nbytes);
1004 /* The first optimization pass uses a default cost model. Each
1005 * additional optimization pass uses a cost model derived from the
1006 * Huffman code computed in the previous pass. */
1007 xpress_set_default_costs(c);
1009 xpress_find_min_cost_path(c, in_nbytes, end_cache_ptr);
1010 xpress_tally_item_list(c, c->optimum_nodes + in_nbytes);
1011 if (num_passes_remaining > 1) {
1012 c->freqs[XPRESS_END_OF_DATA]++;
1013 xpress_make_huffman_code(c);
1014 xpress_update_costs(c);
1015 xpress_reset_symbol_frequencies(c);
1017 } while (--num_passes_remaining);
1019 return xpress_write(c, out, out_nbytes_avail, in_nbytes, true);
1022 #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */
1025 xpress_get_compressor_size(size_t max_bufsize, unsigned compression_level)
1027 #if SUPPORT_NEAR_OPTIMAL_PARSING
1028 if (compression_level >= MIN_LEVEL_FOR_NEAR_OPTIMAL)
1029 return offsetof(struct xpress_compressor, bt_mf) +
1030 bt_matchfinder_size(max_bufsize);
1033 return offsetof(struct xpress_compressor, hc_mf) +
1034 hc_matchfinder_size(max_bufsize);
1038 xpress_get_needed_memory(size_t max_bufsize, unsigned compression_level,
1043 if (max_bufsize > XPRESS_MAX_BUFSIZE)
1046 size += xpress_get_compressor_size(max_bufsize, compression_level);
1048 if (compression_level < MIN_LEVEL_FOR_NEAR_OPTIMAL ||
1049 !SUPPORT_NEAR_OPTIMAL_PARSING) {
1051 size += max_bufsize * sizeof(struct xpress_item);
1053 #if SUPPORT_NEAR_OPTIMAL_PARSING
1056 size += (max_bufsize + 1) * sizeof(struct xpress_optimum_node);
1058 size += ((max_bufsize * CACHE_RESERVE_PER_POS) +
1059 XPRESS_MAX_MATCH_LEN + max_bufsize) *
1060 sizeof(struct lz_match);
1067 xpress_create_compressor(size_t max_bufsize, unsigned compression_level,
1068 bool destructive, void **c_ret)
1070 struct xpress_compressor *c;
1072 if (max_bufsize > XPRESS_MAX_BUFSIZE)
1073 return WIMLIB_ERR_INVALID_PARAM;
1075 c = MALLOC(xpress_get_compressor_size(max_bufsize, compression_level));
1079 if (compression_level < MIN_LEVEL_FOR_NEAR_OPTIMAL ||
1080 !SUPPORT_NEAR_OPTIMAL_PARSING)
1083 c->chosen_items = MALLOC(max_bufsize * sizeof(struct xpress_item));
1084 if (!c->chosen_items)
1087 if (compression_level < 30) {
1088 c->impl = xpress_compress_greedy;
1089 c->max_search_depth = (compression_level * 24) / 16;
1090 c->nice_match_length = (compression_level * 48) / 16;
1092 c->impl = xpress_compress_lazy;
1093 c->max_search_depth = (compression_level * 24) / 32;
1094 c->nice_match_length = (compression_level * 48) / 32;
1096 /* xpress_compress_lazy() needs max_search_depth >= 2
1097 * because it halves the max_search_depth when
1098 * attempting a lazy match, and max_search_depth cannot
1100 if (c->max_search_depth < 2)
1101 c->max_search_depth = 2;
1104 #if SUPPORT_NEAR_OPTIMAL_PARSING
1107 c->optimum_nodes = MALLOC((max_bufsize + 1) *
1108 sizeof(struct xpress_optimum_node));
1109 c->match_cache = MALLOC(((max_bufsize * CACHE_RESERVE_PER_POS) +
1110 XPRESS_MAX_MATCH_LEN + max_bufsize) *
1111 sizeof(struct lz_match));
1112 if (!c->optimum_nodes || !c->match_cache) {
1113 FREE(c->optimum_nodes);
1114 FREE(c->match_cache);
1117 c->cache_overflow_mark =
1118 &c->match_cache[max_bufsize * CACHE_RESERVE_PER_POS];
1120 c->impl = xpress_compress_near_optimal;
1121 c->max_search_depth = (compression_level * 32) / 100;
1122 c->nice_match_length = (compression_level * 50) / 100;
1123 c->num_optim_passes = compression_level / 40;
1125 #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */
1127 /* max_search_depth == 0 is invalid. */
1128 if (c->max_search_depth < 1)
1129 c->max_search_depth = 1;
1137 return WIMLIB_ERR_NOMEM;
1141 xpress_compress(const void *restrict in, size_t in_nbytes,
1142 void *restrict out, size_t out_nbytes_avail, void *restrict _c)
1144 struct xpress_compressor *c = _c;
1146 /* Don't bother trying to compress very small inputs. */
1150 if (out_nbytes_avail <= XPRESS_NUM_SYMBOLS / 2 + 4)
1153 xpress_reset_symbol_frequencies(c);
1155 return (*c->impl)(c, in, in_nbytes, out, out_nbytes_avail);
1159 xpress_free_compressor(void *_c)
1161 struct xpress_compressor *c = _c;
1163 #if SUPPORT_NEAR_OPTIMAL_PARSING
1164 if (c->impl == xpress_compress_near_optimal) {
1165 FREE(c->optimum_nodes);
1166 FREE(c->match_cache);
1169 FREE(c->chosen_items);
1173 const struct compressor_ops xpress_compressor_ops = {
1174 .get_needed_memory = xpress_get_needed_memory,
1175 .create_compressor = xpress_create_compressor,
1176 .compress = xpress_compress,
1177 .free_compressor = xpress_free_compressor,