4 * Near-optimal LZ (Lempel-Ziv) parsing, or "match choosing".
5 * See lz_get_near_optimal_match() for details of the algorithm.
7 * This code is not concerned with actually *finding* LZ matches, as it relies
8 * on an underlying match-finder implementation that can do so.
12 * Copyright (c) 2013 Eric Biggers. All rights reserved.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
29 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
32 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
33 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
34 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 /* Define the following structures before including this header:
43 * Also, the type lz_mc_cost_t can be optionally overridden by providing an
44 * appropriate typedef and defining LZ_MC_COST_T_DEFINED. */
49 #include "wimlib/lz.h"
51 #ifndef LZ_MC_COST_T_DEFINED
52 typedef input_idx_t lz_mc_cost_t;
55 #define LZ_MC_INFINITE_COST (~(lz_mc_cost_t)0)
58 * Match chooser position data:
60 * An array of these structures is used during the match-choosing algorithm.
61 * They correspond to consecutive positions in the window and are used to keep
62 * track of the cost to reach each position, and the match/literal choices that
63 * need to be chosen to reach that position.
65 struct lz_mc_pos_data {
66 /* The approximate minimum cost, in bits, to reach this position in the
67 * window which has been found so far. */
70 /* The union here is just for clarity, since the fields are used in two
71 * slightly different ways. Initially, the @prev structure is filled in
72 * first, and links go from later in the window to earlier in the
73 * window. Later, @next structure is filled in and links go from
74 * earlier in the window to later in the window. */
77 /* Position of the start of the match or literal that
78 * was taken to get to this position in the approximate
79 * minimum-cost parse. */
82 /* Offset (as in an LZ (length, offset) pair) of the
83 * match or literal that was taken to get to this
84 * position in the approximate minimum-cost parse. */
85 input_idx_t match_offset;
88 /* Position at which the match or literal starting at
89 * this position ends in the minimum-cost parse. */
92 /* Offset (as in an LZ (length, offset) pair) of the
93 * match or literal starting at this position in the
94 * approximate minimum-cost parse. */
95 input_idx_t match_offset;
99 /* Format-dependent adaptive state that exists after an approximate
100 * minimum-cost path to reach this position is taken. For example, for
101 * LZX this is the list of recently used match offsets. If the format
102 * does not have any adaptive state that affects match costs,
103 * LZ_ADAPTIVE_STATE could be set to a dummy structure of size 0. */
104 LZ_ADAPTIVE_STATE state;
107 struct lz_match_chooser {
108 /* Temporary space used for the match-choosing algorithm. The size of
109 * this array must be at least one more than @nice_len but otherwise is
110 * arbitrary. More space decreases the frequency at which the algorithm
111 * is forced to terminate early. 4096 spaces seems sufficient for most
113 struct lz_mc_pos_data *optimum;
114 input_idx_t array_space;
116 /* When a match with length greater than or equal to this length is
117 * found, choose it immediately without further consideration. */
118 input_idx_t nice_len;
120 /* When matches have been chosen, optimum_cur_idx is set to the position
121 * in the window of the next match/literal to return and optimum_end_idx
122 * is set to the position in the window at the end of the last
123 * match/literal to return. */
124 input_idx_t optimum_cur_idx;
125 input_idx_t optimum_end_idx;
128 /* Initialize the match-chooser.
130 * After calling this, multiple data buffers can be scanned with it if each is
131 * preceded with a call to lz_match_chooser_begin(). */
133 lz_match_chooser_init(struct lz_match_chooser *mc,
134 input_idx_t array_space,
135 input_idx_t nice_len, input_idx_t max_match_len)
137 input_idx_t extra_len = min(nice_len, max_match_len);
139 LZ_ASSERT(array_space > 0);
140 mc->optimum = MALLOC((array_space + extra_len) * sizeof(mc->optimum[0]));
141 if (mc->optimum == NULL)
143 mc->array_space = array_space;
144 mc->nice_len = nice_len;
149 lz_match_chooser_get_needed_memory(input_idx_t array_space,
150 input_idx_t nice_len,
151 input_idx_t max_match_len)
153 input_idx_t extra_len = min(nice_len, max_match_len);
154 return ((u64)(array_space + extra_len) *
155 sizeof(((struct lz_match_chooser*)0)->optimum[0]));
158 /* Free memory allocated in lz_match_chooser_init(). */
160 lz_match_chooser_destroy(struct lz_match_chooser *mc)
165 /* Call this before starting to parse each new input string. */
167 lz_match_chooser_begin(struct lz_match_chooser *mc)
169 mc->optimum_cur_idx = 0;
170 mc->optimum_end_idx = 0;
174 * Reverse the linked list of near-optimal matches so that they can be returned
177 * Returns the first match in the list.
179 static _always_inline_attribute struct raw_match
180 lz_match_chooser_reverse_list(struct lz_match_chooser *mc, input_idx_t cur_pos)
182 unsigned prev_link, saved_prev_link;
183 unsigned prev_match_offset, saved_prev_match_offset;
185 mc->optimum_end_idx = cur_pos;
187 saved_prev_link = mc->optimum[cur_pos].prev.link;
188 saved_prev_match_offset = mc->optimum[cur_pos].prev.match_offset;
191 prev_link = saved_prev_link;
192 prev_match_offset = saved_prev_match_offset;
194 saved_prev_link = mc->optimum[prev_link].prev.link;
195 saved_prev_match_offset = mc->optimum[prev_link].prev.match_offset;
197 mc->optimum[prev_link].next.link = cur_pos;
198 mc->optimum[prev_link].next.match_offset = prev_match_offset;
201 } while (cur_pos != 0);
203 mc->optimum_cur_idx = mc->optimum[0].next.link;
205 return (struct raw_match)
206 { .len = mc->optimum_cur_idx,
207 .offset = mc->optimum[0].next.match_offset,
211 /* Format-specific functions inlined into lz_get_near_optimal_match(). */
213 /* Get the list of possible matches at the next position. The return value must
214 * be the number of matches found (which may be 0) and a pointer to the returned
215 * matches must be written into @matches_ret. Matches must be of distinct
216 * lengths and sorted in decreasing order by length. Furthermore, match lengths
217 * may not exceed the @max_match_len passed to lz_match_chooser_init(), and all
218 * match lengths must be at least 2. */
219 typedef u32 (*lz_get_matches_t)(LZ_COMPRESSOR *ctx,
220 const LZ_ADAPTIVE_STATE *state,
221 struct raw_match **matches_ret);
223 /* Skip the specified number of bytes (don't search for matches at them). This
224 * is expected to be faster than simply getting the matches at each position,
225 * but the exact performance difference will be dependent on the match-finder
227 typedef void (*lz_skip_bytes_t)(LZ_COMPRESSOR *ctx, input_idx_t n);
229 /* Get the cost of the literal located at the position at which matches have
230 * most recently been searched. This can optionally update the @state to take
231 * into account format-dependent state that affects match costs, such as repeat
233 typedef lz_mc_cost_t (lz_get_prev_literal_cost_t)(LZ_COMPRESSOR *ctx,
234 LZ_ADAPTIVE_STATE *state);
236 /* Get the cost of a match. This can optionally update the @state to take into
237 * account format-dependent state that affects match costs, such as repeat
239 typedef lz_mc_cost_t (lz_get_match_cost_t)(LZ_COMPRESSOR *ctx,
240 LZ_ADAPTIVE_STATE *state,
245 * lz_get_near_optimal_match() -
247 * Choose an approximately optimal match or literal to use at the next position
248 * in the string, or "window", being LZ-encoded.
250 * This is based on the algorithm used in 7-Zip's DEFLATE encoder, written by
251 * Igor Pavlov. However it also attempts to account for adaptive state, such as
252 * a LRU queue of recent match offsets.
254 * Unlike a greedy parser that always takes the longest match, or even a "lazy"
255 * parser with one match/literal look-ahead like zlib, the algorithm used here
256 * may look ahead many matches/literals to determine the approximately optimal
257 * match/literal to code next. The motivation is that the compression ratio is
258 * improved if the compressor can do things like use a shorter-than-possible
259 * match in order to allow a longer match later, and also take into account the
260 * estimated real cost of coding each match/literal based on the underlying
263 * Still, this is not a true optimal parser for several reasons:
265 * - Very long matches (at least @nice_len) are taken immediately. This is
266 * because locations with long matches are likely to have many possible
267 * alternatives that would cause slow optimal parsing, but also such locations
268 * are already highly compressible so it is not too harmful to just grab the
271 * - Not all possible matches at each location are considered. Users of this
272 * code are expected to provide a @get_matches() function that returns a list
273 * of potentially good matches at the current position, but no more than one
274 * per length. It therefore must use some sort of heuristic (e.g. smallest or
275 * repeat offset) to choose a good match to consider for a given length, if
276 * multiple exist. Furthermore, the @get_matches() implementation may limit
277 * the total number of matches returned and/or the number of computational
278 * steps spent searching for matches at each position.
280 * - This function relies on the user-provided @get_match_cost() and
281 * @get_prev_literal_cost() functions to evaluate match and literal costs,
282 * respectively, but real compression formats use entropy encoding of the
283 * literal/match sequence, so the real cost of coding each match or literal is
284 * unknown until the parse is fully determined. It can be approximated based
285 * on iterative parses, but the end result is not guaranteed to be globally
288 * - Although this function allows @get_match_cost() and
289 * @get_prev_literal_cost() to take into account adaptive state, coding
290 * decisions made with respect to the adaptive state will be locally optimal
291 * but will not necessarily be globally optimal. This is because the
292 * algorithm only keeps the least-costly path to get to a given location and
293 * does not take into account that a slightly more costly path could result in
294 * a different adaptive state that ultimately results in a lower global cost.
296 * - The array space used by this function is bounded, so in degenerate cases it
297 * is forced to start returning matches/literals before the algorithm has
300 * Each call to this function does one of two things:
302 * 1. Build a sequence of near-optimal matches/literals, up to some point, that
303 * will be returned by subsequent calls to this function, then return the
308 * 2. Return the next match/literal previously computed by a call to this
311 * The return value is a (length, offset) pair specifying the match or literal
312 * chosen. For literals, the length is 0 or 1 and the offset is meaningless.
314 * NOTE: this code has been factored out of the LZX compressor so that it can be
315 * shared by other formats such as LZMS. It is inlined so there is no loss of
316 * performance, especially with the different implementations of match-finding,
317 * cost evaluation, and adaptive state.
319 static _always_inline_attribute struct raw_match
320 lz_get_near_optimal_match(struct lz_match_chooser *mc,
321 lz_get_matches_t get_matches,
322 lz_skip_bytes_t skip_bytes,
323 lz_get_prev_literal_cost_t get_prev_literal_cost,
324 lz_get_match_cost_t get_match_cost,
326 const LZ_ADAPTIVE_STATE *initial_state)
328 u32 num_possible_matches;
329 struct raw_match *possible_matches;
330 struct raw_match match;
331 input_idx_t longest_match_len;
333 if (mc->optimum_cur_idx != mc->optimum_end_idx) {
334 /* Case 2: Return the next match/literal already found. */
335 match.len = mc->optimum[mc->optimum_cur_idx].next.link -
337 match.offset = mc->optimum[mc->optimum_cur_idx].next.match_offset;
339 mc->optimum_cur_idx = mc->optimum[mc->optimum_cur_idx].next.link;
343 /* Case 1: Compute a new list of matches/literals to return. */
345 mc->optimum_cur_idx = 0;
346 mc->optimum_end_idx = 0;
348 /* Get matches at this position. */
349 num_possible_matches = (*get_matches)(ctx,
353 /* If no matches found, return literal. */
354 if (num_possible_matches == 0)
355 return (struct raw_match){ .len = 0 };
357 /* The matches that were found are sorted in decreasing order by length.
358 * Get the length of the longest one. */
359 longest_match_len = possible_matches[0].len;
361 /* Greedy heuristic: if the longest match that was found is greater
362 * than nice_len, return it immediately; don't both doing more work. */
363 if (longest_match_len >= mc->nice_len) {
364 (*skip_bytes)(ctx, longest_match_len - 1);
365 return possible_matches[0];
368 /* Calculate the cost to reach the next position by coding a literal.
370 mc->optimum[1].state = *initial_state;
371 mc->optimum[1].cost = (*get_prev_literal_cost)(ctx, &mc->optimum[1].state);
372 mc->optimum[1].prev.link = 0;
374 /* Calculate the cost to reach any position up to and including that
375 * reached by the longest match. Use the shortest available match that
376 * reaches each position, assuming that @get_matches() only returned
377 * shorter matches because their estimated costs were less than that of
378 * the longest match. */
379 for (input_idx_t len = 2, match_idx = num_possible_matches - 1;
380 len <= longest_match_len; len++)
383 LZ_ASSERT(match_idx < num_possible_matches);
384 LZ_ASSERT(len <= possible_matches[match_idx].len);
386 mc->optimum[len].state = *initial_state;
387 mc->optimum[len].prev.link = 0;
388 mc->optimum[len].prev.match_offset = possible_matches[match_idx].offset;
389 mc->optimum[len].cost = (*get_match_cost)(ctx,
390 &mc->optimum[len].state,
392 possible_matches[match_idx].offset);
393 if (len == possible_matches[match_idx].len)
397 /* Step forward, calculating the estimated minimum cost to reach each
398 * position. The algorithm may find multiple paths to reach each
399 * position; only the lowest-cost path is saved.
401 * The progress of the parse is tracked in the @mc->optimum array, which
402 * for each position contains the minimum cost to reach that position,
403 * the index of the start of the match/literal taken to reach that
404 * position through the minimum-cost path, the offset of the match taken
405 * (not relevant for literals), and the adaptive state that will exist
406 * at that position after the minimum-cost path is taken. The @cur_pos
407 * variable stores the position at which the algorithm is currently
408 * considering coding choices, and the @len_end variable stores the
409 * greatest offset at which the costs of coding choices have been saved.
410 * (The algorithm guarantees that all positions before @len_end are
411 * reachable by at least one path and therefore have costs computed.)
413 * The loop terminates when any one of the following conditions occurs:
415 * 1. A match greater than @nice_len is found. When this is found, the
416 * algorithm chooses this match unconditionally, and consequently the
417 * near-optimal match/literal sequence up to and including that match
418 * is fully determined.
420 * 2. @cur_pos reaches a position not overlapped by a preceding match.
421 * In such cases, the near-optimal match/literal sequence up to
422 * @cur_pos is fully determined.
424 * 3. Failing either of the above in a degenerate case, the loop
425 * terminates when space in the @mc->optimum array is exhausted.
426 * This terminates the algorithm and forces it to start returning
427 * matches/literals even though they may not be globally optimal.
429 * Upon loop termination, a nonempty list of matches/literals has been
430 * produced and stored in the @optimum array. They are linked in
431 * reverse order, so the last thing this function does is reverse the
432 * links and return the first match/literal, leaving the rest to be
433 * returned immediately by subsequent calls to this function.
435 input_idx_t cur_pos = 0;
436 input_idx_t len_end = longest_match_len;
438 /* Advance to next position. */
441 /* Check termination conditions (2) and (3) noted above. */
442 if (cur_pos == len_end || cur_pos == mc->array_space)
443 return lz_match_chooser_reverse_list(mc, cur_pos);
445 /* Retrieve a (possibly empty) list of potentially useful
446 * matches available at this position. */
447 num_possible_matches = (*get_matches)(ctx,
448 &mc->optimum[cur_pos].state,
451 if (num_possible_matches == 0)
452 longest_match_len = 0;
454 longest_match_len = possible_matches[0].len;
456 /* Greedy heuristic and termination condition (1) noted above:
457 * if we found a match greater than @nice_len, choose it
458 * unconditionally and begin returning matches/literals. */
459 if (longest_match_len >= mc->nice_len) {
460 /* Build the list of matches to return and get
462 match = lz_match_chooser_reverse_list(mc, cur_pos);
464 /* Append the long match to the end of the list. */
465 mc->optimum[cur_pos].next.match_offset =
466 possible_matches[0].offset;
467 mc->optimum[cur_pos].next.link = cur_pos + longest_match_len;
468 mc->optimum_end_idx = cur_pos + longest_match_len;
470 /* Skip over the remaining bytes of the long match. */
471 (*skip_bytes)(ctx, longest_match_len - 1);
473 /* Return first match in the list. */
477 /* Load minimum cost to reach the current position. */
478 input_idx_t cur_cost = mc->optimum[cur_pos].cost;
480 /* Consider proceeding with a literal byte. */
482 LZ_ADAPTIVE_STATE state;
485 state = mc->optimum[cur_pos].state;
486 cost = cur_cost + (*get_prev_literal_cost)(ctx, &state);
488 if (cost < mc->optimum[cur_pos + 1].cost) {
489 mc->optimum[cur_pos + 1].cost = cost;
490 mc->optimum[cur_pos + 1].prev.link = cur_pos;
491 mc->optimum[cur_pos + 1].state = state;
495 /* If no matches were found, continue to the next position.
496 * Otherwise, consider proceeding with a match. */
498 if (num_possible_matches == 0)
501 /* Initialize any uninitialized costs up to the length of the
502 * longest match found. */
503 while (len_end < cur_pos + longest_match_len)
504 mc->optimum[++len_end].cost = LZ_MC_INFINITE_COST;
506 /* Calculate the minimum cost to reach any position up to and
507 * including that reached by the longest match. Use the
508 * shortest available match that reaches each position, assuming
509 * that @get_matches() only returned shorter matches because
510 * their estimated costs were less than that of the longest
512 for (input_idx_t len = 2, match_idx = num_possible_matches - 1;
513 len <= longest_match_len; len++)
515 LZ_ASSERT(match_idx < num_possible_matches);
516 LZ_ASSERT(len <= possible_matches[match_idx].len);
518 LZ_ADAPTIVE_STATE state;
521 state = mc->optimum[cur_pos].state;
522 cost = cur_cost + (*get_match_cost)(ctx,
525 possible_matches[match_idx].offset);
527 if (cost < mc->optimum[cur_pos + len].cost) {
528 mc->optimum[cur_pos + len].cost = cost;
529 mc->optimum[cur_pos + len].prev.link = cur_pos;
530 mc->optimum[cur_pos + len].prev.match_offset =
531 possible_matches[match_idx].offset;
532 mc->optimum[cur_pos + len].state = state;
535 if (len == possible_matches[match_idx].len)
541 #endif /* _LZ_OPTIMAL_H */