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;
148 /* Free memory allocated in lz_match_chooser_init(). */
150 lz_match_chooser_destroy(struct lz_match_chooser *mc)
155 /* Call this before starting to parse each new input string. */
157 lz_match_chooser_begin(struct lz_match_chooser *mc)
159 mc->optimum_cur_idx = 0;
160 mc->optimum_end_idx = 0;
164 * Reverse the linked list of near-optimal matches so that they can be returned
167 * Returns the first match in the list.
169 static _always_inline_attribute struct raw_match
170 lz_match_chooser_reverse_list(struct lz_match_chooser *mc, input_idx_t cur_pos)
172 unsigned prev_link, saved_prev_link;
173 unsigned prev_match_offset, saved_prev_match_offset;
175 mc->optimum_end_idx = cur_pos;
177 saved_prev_link = mc->optimum[cur_pos].prev.link;
178 saved_prev_match_offset = mc->optimum[cur_pos].prev.match_offset;
181 prev_link = saved_prev_link;
182 prev_match_offset = saved_prev_match_offset;
184 saved_prev_link = mc->optimum[prev_link].prev.link;
185 saved_prev_match_offset = mc->optimum[prev_link].prev.match_offset;
187 mc->optimum[prev_link].next.link = cur_pos;
188 mc->optimum[prev_link].next.match_offset = prev_match_offset;
191 } while (cur_pos != 0);
193 mc->optimum_cur_idx = mc->optimum[0].next.link;
195 return (struct raw_match)
196 { .len = mc->optimum_cur_idx,
197 .offset = mc->optimum[0].next.match_offset,
201 /* Format-specific functions inlined into lz_get_near_optimal_match(). */
203 /* Get the list of possible matches at the next position. The return value must
204 * be the number of matches found (which may be 0) and a pointer to the returned
205 * matches must be written into @matches_ret. Matches must be of distinct
206 * lengths and sorted in decreasing order by length. Furthermore, match lengths
207 * may not exceed the @max_match_len passed to lz_match_chooser_init(). */
208 typedef u32 (*lz_get_matches_t)(LZ_COMPRESSOR *ctx,
209 const LZ_ADAPTIVE_STATE *state,
210 struct raw_match **matches_ret);
212 /* Skip the specified number of bytes (don't search for matches at them). This
213 * is expected to be faster than simply getting the matches at each position,
214 * but the exact performance difference will be dependent on the match-finder
216 typedef void (*lz_skip_bytes_t)(LZ_COMPRESSOR *ctx, input_idx_t n);
218 /* Get the cost of the literal located at the position at which matches have
219 * most recently been searched. This can optionally update the @state to take
220 * into account format-dependent state that affects match costs, such as repeat
222 typedef lz_mc_cost_t (lz_get_prev_literal_cost_t)(LZ_COMPRESSOR *ctx,
223 LZ_ADAPTIVE_STATE *state);
225 /* Get the cost of a match. This can optionally update the @state to take into
226 * account format-dependent state that affects match costs, such as repeat
228 typedef lz_mc_cost_t (lz_get_match_cost_t)(LZ_COMPRESSOR *ctx,
229 LZ_ADAPTIVE_STATE *state,
234 * lz_get_near_optimal_match() -
236 * Choose an approximately optimal match or literal to use at the next position
237 * in the string, or "window", being LZ-encoded.
239 * This is based on the algorithm used in 7-Zip's DEFLATE encoder, written by
240 * Igor Pavlov. However it also attempts to account for adaptive state, such as
241 * a LRU queue of recent match offsets.
243 * Unlike a greedy parser that always takes the longest match, or even a "lazy"
244 * parser with one match/literal look-ahead like zlib, the algorithm used here
245 * may look ahead many matches/literals to determine the approximately optimal
246 * match/literal to code next. The motivation is that the compression ratio is
247 * improved if the compressor can do things like use a shorter-than-possible
248 * match in order to allow a longer match later, and also take into account the
249 * estimated real cost of coding each match/literal based on the underlying
252 * Still, this is not a true optimal parser for several reasons:
254 * - Very long matches (at least @nice_len) are taken immediately. This is
255 * because locations with long matches are likely to have many possible
256 * alternatives that would cause slow optimal parsing, but also such locations
257 * are already highly compressible so it is not too harmful to just grab the
260 * - Not all possible matches at each location are considered. Users of this
261 * code are expected to provide a @get_matches() function that returns a list
262 * of potentially good matches at the current position, but no more than one
263 * per length. It therefore must use some sort of heuristic (e.g. smallest or
264 * repeat offset) to choose a good match to consider for a given length, if
265 * multiple exist. Furthermore, the @get_matches() implementation may limit
266 * the total number of matches returned and/or the number of computational
267 * steps spent searching for matches at each position.
269 * - This function relies on the user-provided @get_match_cost() and
270 * @get_prev_literal_cost() functions to evaluate match and literal costs,
271 * respectively, but real compression formats use entropy encoding of the
272 * literal/match sequence, so the real cost of coding each match or literal is
273 * unknown until the parse is fully determined. It can be approximated based
274 * on iterative parses, but the end result is not guaranteed to be globally
277 * - Although this function allows @get_match_cost() and
278 * @get_prev_literal_cost() to take into account adaptive state, coding
279 * decisions made with respect to the adaptive state will be locally optimal
280 * but will not necessarily be globally optimal. This is because the
281 * algorithm only keeps the least-costly path to get to a given location and
282 * does not take into account that a slightly more costly path could result in
283 * a different adaptive state that ultimately results in a lower global cost.
285 * - The array space used by this function is bounded, so in degenerate cases it
286 * is forced to start returning matches/literals before the algorithm has
289 * Each call to this function does one of two things:
291 * 1. Build a sequence of near-optimal matches/literals, up to some point, that
292 * will be returned by subsequent calls to this function, then return the
297 * 2. Return the next match/literal previously computed by a call to this
300 * The return value is a (length, offset) pair specifying the match or literal
301 * chosen. For literals, the length is 0 or 1 and the offset is meaningless.
303 * NOTE: this code has been factored out of the LZX compressor so that it can be
304 * shared by other formats such as LZMS. It is inlined so there is no loss of
305 * performance, especially with the different implementations of match-finding,
306 * cost evaluation, and adaptive state.
308 static _always_inline_attribute struct raw_match
309 lz_get_near_optimal_match(struct lz_match_chooser *mc,
310 lz_get_matches_t get_matches,
311 lz_skip_bytes_t skip_bytes,
312 lz_get_prev_literal_cost_t get_prev_literal_cost,
313 lz_get_match_cost_t get_match_cost,
315 const LZ_ADAPTIVE_STATE *initial_state)
317 u32 num_possible_matches;
318 struct raw_match *possible_matches;
319 struct raw_match match;
320 input_idx_t longest_match_len;
322 if (mc->optimum_cur_idx != mc->optimum_end_idx) {
323 /* Case 2: Return the next match/literal already found. */
324 match.len = mc->optimum[mc->optimum_cur_idx].next.link -
326 match.offset = mc->optimum[mc->optimum_cur_idx].next.match_offset;
328 mc->optimum_cur_idx = mc->optimum[mc->optimum_cur_idx].next.link;
332 /* Case 1: Compute a new list of matches/literals to return. */
334 mc->optimum_cur_idx = 0;
335 mc->optimum_end_idx = 0;
337 /* Get matches at this position. */
338 num_possible_matches = (*get_matches)(ctx,
342 /* If no matches found, return literal. */
343 if (num_possible_matches == 0)
344 return (struct raw_match){ .len = 0 };
346 /* The matches that were found are sorted in decreasing order by length.
347 * Get the length of the longest one. */
348 longest_match_len = possible_matches[0].len;
350 /* Greedy heuristic: if the longest match that was found is greater
351 * than nice_len, return it immediately; don't both doing more work. */
352 if (longest_match_len >= mc->nice_len) {
353 (*skip_bytes)(ctx, longest_match_len - 1);
354 return possible_matches[0];
357 /* Calculate the cost to reach the next position by coding a literal.
359 mc->optimum[1].state = *initial_state;
360 mc->optimum[1].cost = (*get_prev_literal_cost)(ctx, &mc->optimum[1].state);
361 mc->optimum[1].prev.link = 0;
363 /* Calculate the cost to reach any position up to and including that
364 * reached by the longest match. Use the shortest available match that
365 * reaches each position, assuming that @get_matches() only returned
366 * shorter matches because their estimated costs were less than that of
367 * the longest match. */
368 for (input_idx_t len = 2, match_idx = num_possible_matches - 1;
369 len <= longest_match_len; len++)
372 LZ_ASSERT(match_idx < num_possible_matches);
373 LZ_ASSERT(len <= possible_matches[match_idx].len);
375 mc->optimum[len].state = *initial_state;
376 mc->optimum[len].prev.link = 0;
377 mc->optimum[len].prev.match_offset = possible_matches[match_idx].offset;
378 mc->optimum[len].cost = (*get_match_cost)(ctx,
379 &mc->optimum[len].state,
381 possible_matches[match_idx].offset);
382 if (len == possible_matches[match_idx].len)
386 /* Step forward, calculating the estimated minimum cost to reach each
387 * position. The algorithm may find multiple paths to reach each
388 * position; only the lowest-cost path is saved.
390 * The progress of the parse is tracked in the @mc->optimum array, which
391 * for each position contains the minimum cost to reach that position,
392 * the index of the start of the match/literal taken to reach that
393 * position through the minimum-cost path, the offset of the match taken
394 * (not relevant for literals), and the adaptive state that will exist
395 * at that position after the minimum-cost path is taken. The @cur_pos
396 * variable stores the position at which the algorithm is currently
397 * considering coding choices, and the @len_end variable stores the
398 * greatest offset at which the costs of coding choices have been saved.
399 * (The algorithm guarantees that all positions before @len_end are
400 * reachable by at least one path and therefore have costs computed.)
402 * The loop terminates when any one of the following conditions occurs:
404 * 1. A match greater than @nice_len is found. When this is found, the
405 * algorithm chooses this match unconditionally, and consequently the
406 * near-optimal match/literal sequence up to and including that match
407 * is fully determined.
409 * 2. @cur_pos reaches a position not overlapped by a preceding match.
410 * In such cases, the near-optimal match/literal sequence up to
411 * @cur_pos is fully determined.
413 * 3. Failing either of the above in a degenerate case, the loop
414 * terminates when space in the @mc->optimum array is exhausted.
415 * This terminates the algorithm and forces it to start returning
416 * matches/literals even though they may not be globally optimal.
418 * Upon loop termination, a nonempty list of matches/literals has been
419 * produced and stored in the @optimum array. They are linked in
420 * reverse order, so the last thing this function does is reverse the
421 * links and return the first match/literal, leaving the rest to be
422 * returned immediately by subsequent calls to this function.
424 input_idx_t cur_pos = 0;
425 input_idx_t len_end = longest_match_len;
427 /* Advance to next position. */
430 /* Check termination conditions (2) and (3) noted above. */
431 if (cur_pos == len_end || cur_pos == mc->array_space)
432 return lz_match_chooser_reverse_list(mc, cur_pos);
434 /* Retrieve a (possibly empty) list of potentially useful
435 * matches available at this position. */
436 num_possible_matches = (*get_matches)(ctx,
437 &mc->optimum[cur_pos].state,
440 if (num_possible_matches == 0)
441 longest_match_len = 0;
443 longest_match_len = possible_matches[0].len;
445 /* Greedy heuristic and termination condition (1) noted above:
446 * if we found a match greater than @nice_len, choose it
447 * unconditionally and begin returning matches/literals. */
448 if (longest_match_len >= mc->nice_len) {
449 /* Build the list of matches to return and get
451 match = lz_match_chooser_reverse_list(mc, cur_pos);
453 /* Append the long match to the end of the list. */
454 mc->optimum[cur_pos].next.match_offset =
455 possible_matches[0].offset;
456 mc->optimum[cur_pos].next.link = cur_pos + longest_match_len;
457 mc->optimum_end_idx = cur_pos + longest_match_len;
459 /* Skip over the remaining bytes of the long match. */
460 (*skip_bytes)(ctx, longest_match_len - 1);
462 /* Return first match in the list. */
466 /* Load minimum cost to reach the current position. */
467 input_idx_t cur_cost = mc->optimum[cur_pos].cost;
469 /* Consider proceeding with a literal byte. */
471 LZ_ADAPTIVE_STATE state;
474 state = mc->optimum[cur_pos].state;
475 cost = cur_cost + (*get_prev_literal_cost)(ctx, &state);
477 if (cost < mc->optimum[cur_pos + 1].cost) {
478 mc->optimum[cur_pos + 1].cost = cost;
479 mc->optimum[cur_pos + 1].prev.link = cur_pos;
480 mc->optimum[cur_pos + 1].state = state;
484 /* If no matches were found, continue to the next position.
485 * Otherwise, consider proceeding with a match. */
487 if (num_possible_matches == 0)
490 /* Initialize any uninitialized costs up to the length of the
491 * longest match found. */
492 while (len_end < cur_pos + longest_match_len)
493 mc->optimum[++len_end].cost = LZ_MC_INFINITE_COST;
495 /* Calculate the minimum cost to reach any position up to and
496 * including that reached by the longest match. Use the
497 * shortest available match that reaches each position, assuming
498 * that @get_matches() only returned shorter matches because
499 * their estimated costs were less than that of the longest
501 for (input_idx_t len = 2, match_idx = num_possible_matches - 1;
502 len <= longest_match_len; len++)
504 LZ_ASSERT(match_idx < num_possible_matches);
505 LZ_ASSERT(len <= possible_matches[match_idx].len);
507 LZ_ADAPTIVE_STATE state;
510 state = mc->optimum[cur_pos].state;
511 cost = cur_cost + (*get_match_cost)(ctx,
514 possible_matches[match_idx].offset);
516 if (cost < mc->optimum[cur_pos + len].cost) {
517 mc->optimum[cur_pos + len].cost = cost;
518 mc->optimum[cur_pos + len].prev.link = cur_pos;
519 mc->optimum[cur_pos + len].prev.match_offset =
520 possible_matches[match_idx].offset;
521 mc->optimum[cur_pos + len].state = state;
524 if (len == possible_matches[match_idx].len)
530 #endif /* _LZ_OPTIMAL_H */