Debian Codegraph @

debian/rust-vendor/zopfli/src/squeeze.rs

raw
1 //! The squeeze functions do enhanced LZ77 compression by optimal parsing with a
2 //! cost model, rather than greedily choosing the longest length or using a single
3 //! step of lazy matching like regular implementations.
4 //!
5 //! Since the cost model is based on the Huffman tree that can only be calculated
6 //! after the LZ77 data is generated, there is a chicken and egg problem, and
7 //! multiple runs are done with updated cost models to converge to a better
8 //! solution.
9
10 use alloc::vec::Vec;
11 use core::cmp;
12
13 #[cfg(feature = "std")]
14 use log::{debug, trace};
15
16 use crate::{
17 cache::Cache,
18 deflate::{calculate_block_size, BlockType},
19 hash::ZopfliHash,
20 lz77::{find_longest_match, LitLen, Lz77Store},
21 symbols::{get_dist_extra_bits, get_dist_symbol, get_length_extra_bits, get_length_symbol},
22 util::{ZOPFLI_MAX_MATCH, ZOPFLI_NUM_D, ZOPFLI_NUM_LL, ZOPFLI_WINDOW_MASK, ZOPFLI_WINDOW_SIZE},
23 };
24
25 #[cfg(not(feature = "std"))]
26 #[allow(unused_imports)] // False-positive
27 use crate::math::F64MathExt;
28
29 /// Cost model which should exactly match fixed tree.
30 fn get_cost_fixed(litlen: usize, dist: u16) -> f64 {
31 let result = if dist == 0 {
32 if litlen <= 143 {
33 8
34 } else {
35 9
36 }
37 } else {
38 let dbits = get_dist_extra_bits(dist);
39 let lbits = get_length_extra_bits(litlen);
40 let lsym = get_length_symbol(litlen);
41 // Every dist symbol has length 5.
42 7 + u32::from(lsym > 279) + 5 + dbits + lbits
43 };
44 f64::from(result)
45 }
46
47 /// Cost model based on symbol statistics.
48 fn get_cost_stat(litlen: usize, dist: u16, stats: &SymbolStats) -> f64 {
49 assert!(litlen < ZOPFLI_NUM_LL); // Eases inlining and gets rid of index bound checks below
50 if dist == 0 {
51 stats.ll_symbols[litlen]
52 } else {
53 let lsym = get_length_symbol(litlen);
54 let lbits = f64::from(get_length_extra_bits(litlen));
55 let dsym = get_dist_symbol(dist) as usize;
56 let dbits = f64::from(get_dist_extra_bits(dist));
57 lbits + dbits + stats.ll_symbols[lsym] + stats.d_symbols[dsym]
58 }
59 }
60
61 #[derive(Default)]
62 struct RanState {
63 m_w: u32,
64 m_z: u32,
65 }
66
67 impl RanState {
68 const fn new() -> Self {
69 Self { m_w: 1, m_z: 2 }
70 }
71
72 /// Get random number: "Multiply-With-Carry" generator of G. Marsaglia
73 fn random_marsaglia(&mut self) -> u32 {
74 self.m_z = 36969 * (self.m_z & 65535) + (self.m_z >> 16);
75 self.m_w = 18000 * (self.m_w & 65535) + (self.m_w >> 16);
76 (self.m_z << 16).wrapping_add(self.m_w) // 32-bit result.
77 }
78 }
79
80 #[derive(Copy, Clone)]
81 struct SymbolStats {
82 /* The literal and length symbols. */
83 litlens: [usize; ZOPFLI_NUM_LL],
84 /* The 32 unique dist symbols, not the 32768 possible dists. */
85 dists: [usize; ZOPFLI_NUM_D],
86
87 /* Length of each lit/len symbol in bits. */
88 ll_symbols: [f64; ZOPFLI_NUM_LL],
89 /* Length of each dist symbol in bits. */
90 d_symbols: [f64; ZOPFLI_NUM_D],
91 }
92
93 impl Default for SymbolStats {
94 fn default() -> Self {
95 Self {
96 litlens: [0; ZOPFLI_NUM_LL],
97 dists: [0; ZOPFLI_NUM_D],
98 ll_symbols: [0.0; ZOPFLI_NUM_LL],
99 d_symbols: [0.0; ZOPFLI_NUM_D],
100 }
101 }
102 }
103
104 impl SymbolStats {
105 fn randomize_stat_freqs(&mut self, state: &mut RanState) {
106 fn randomize_freqs(freqs: &mut [usize], state: &mut RanState) {
107 let n = freqs.len();
108 let mut i = 0;
109 let end = n;
110
111 while i < end {
112 if (state.random_marsaglia() >> 4) % 3 == 0 {
113 let index = state.random_marsaglia() as usize % n;
114 freqs[i] = freqs[index];
115 }
116 i += 1;
117 }
118 }
119 randomize_freqs(&mut self.litlens, state);
120 randomize_freqs(&mut self.dists, state);
121 self.litlens[256] = 1; // End symbol.
122 }
123
124 /// Calculates the entropy of each symbol, based on the counts of each symbol. The
125 /// result is similar to the result of `length_limited_code_lengths`, but with the
126 /// actual theoretical bit lengths according to the entropy. Since the resulting
127 /// values are fractional, they cannot be used to encode the tree specified by
128 /// DEFLATE.
129 fn calculate_entropy(&mut self) {
130 fn calculate_and_store_entropy(count: &[usize], bitlengths: &mut [f64]) {
131 let n = count.len();
132
133 let sum = count.iter().sum();
134
135 let log2sum = (if sum == 0 { n } else { sum } as f64).log2();
136
137 for i in 0..n {
138 // When the count of the symbol is 0, but its cost is requested anyway, it
139 // means the symbol will appear at least once anyway, so give it the cost as if
140 // its count is 1.
141 if count[i] == 0 {
142 bitlengths[i] = log2sum;
143 } else {
144 bitlengths[i] = log2sum - (count[i] as f64).log2();
145 }
146 }
147 }
148
149 calculate_and_store_entropy(&self.litlens, &mut self.ll_symbols);
150 calculate_and_store_entropy(&self.dists, &mut self.d_symbols);
151 }
152
153 /// Appends the symbol statistics from the store.
154 fn get_statistics(&mut self, store: &Lz77Store) {
155 for &litlen in &store.litlens {
156 match litlen {
157 LitLen::Literal(lit) => self.litlens[lit as usize] += 1,
158 LitLen::LengthDist(len, dist) => {
159 self.litlens[get_length_symbol(len as usize)] += 1;
160 self.dists[get_dist_symbol(dist) as usize] += 1;
161 }
162 }
163 }
164 self.litlens[256] = 1; /* End symbol. */
165
166 self.calculate_entropy();
167 }
168
169 fn clear_freqs(&mut self) {
170 self.litlens = [0; ZOPFLI_NUM_LL];
171 self.dists = [0; ZOPFLI_NUM_D];
172 }
173 }
174
175 fn add_weighed_stat_freqs(
176 stats1: &SymbolStats,
177 w1: f64,
178 stats2: &SymbolStats,
179 w2: f64,
180 ) -> SymbolStats {
181 let mut result = SymbolStats::default();
182
183 for i in 0..ZOPFLI_NUM_LL {
184 result.litlens[i] =
185 (stats1.litlens[i] as f64 * w1 + stats2.litlens[i] as f64 * w2) as usize;
186 }
187 for i in 0..ZOPFLI_NUM_D {
188 result.dists[i] = (stats1.dists[i] as f64 * w1 + stats2.dists[i] as f64 * w2) as usize;
189 }
190 result.litlens[256] = 1; // End symbol.
191 result
192 }
193
194 /// Finds the minimum possible cost this cost model can return for valid length and
195 /// distance symbols.
196 fn get_cost_model_min_cost<F: Fn(usize, u16) -> f64>(costmodel: F) -> f64 {
197 let mut bestlength = 0; // length that has lowest cost in the cost model
198 let mut bestdist = 0; // distance that has lowest cost in the cost model
199
200 // Table of distances that have a different distance symbol in the deflate
201 // specification. Each value is the first distance that has a new symbol. Only
202 // different symbols affect the cost model so only these need to be checked.
203 // See RFC 1951 section 3.2.5. Compressed blocks (length and distance codes).
204
205 const DSYMBOLS: [u16; 30] = [
206 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
207 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
208 ];
209
210 let mut mincost = f64::INFINITY;
211 for i in 3..259 {
212 let c = costmodel(i, 1);
213 if c < mincost {
214 bestlength = i;
215 mincost = c;
216 }
217 }
218
219 mincost = f64::INFINITY;
220 for dsym in DSYMBOLS {
221 let c = costmodel(3, dsym);
222 if c < mincost {
223 bestdist = dsym;
224 mincost = c;
225 }
226 }
227 costmodel(bestlength, bestdist)
228 }
229
230 /// Performs the forward pass for "squeeze". Gets the most optimal length to reach
231 /// every byte from a previous byte, using cost calculations.
232 /// `s`: the `ZopfliBlockState`
233 /// `in_data`: the input data array
234 /// `instart`: where to start
235 /// `inend`: where to stop (not inclusive)
236 /// `costmodel`: function to calculate the cost of some lit/len/dist pair.
237 /// `length_array`: output array of size `(inend - instart)` which will receive the best
238 /// length to reach this byte from a previous byte.
239 /// returns the cost that was, according to the `costmodel`, needed to get to the end.
240 fn get_best_lengths<F: Fn(usize, u16) -> f64, C: Cache>(
241 lmc: &mut C,
242 in_data: &[u8],
243 instart: usize,
244 inend: usize,
245 costmodel: F,
246 h: &mut ZopfliHash,
247 costs: &mut Vec<f32>,
248 ) -> (f64, Vec<u16>) {
249 // Best cost to get here so far.
250 let blocksize = inend - instart;
251 let mut length_array = vec![0; blocksize + 1];
252 if instart == inend {
253 return (0.0, length_array);
254 }
255 let windowstart = instart.saturating_sub(ZOPFLI_WINDOW_SIZE);
256
257 h.reset();
258 let arr = &in_data[..inend];
259 h.warmup(arr, windowstart, inend);
260 for i in windowstart..instart {
261 h.update(arr, i);
262 }
263
264 costs.resize(blocksize + 1, 0.0);
265 for cost in costs.iter_mut().take(blocksize + 1).skip(1) {
266 *cost = f32::INFINITY;
267 }
268 costs[0] = 0.0; /* Because it's the start. */
269
270 let mut i = instart;
271 let mut leng;
272 let mut longest_match;
273 let mut sublen = vec![0; ZOPFLI_MAX_MATCH + 1];
274 let mincost = get_cost_model_min_cost(&costmodel);
275 while i < inend {
276 let mut j = i - instart; // Index in the costs array and length_array.
277 h.update(arr, i);
278
279 // If we're in a long repetition of the same character and have more than
280 // ZOPFLI_MAX_MATCH characters before and after our position.
281 if h.same[i & ZOPFLI_WINDOW_MASK] > ZOPFLI_MAX_MATCH as u16 * 2
282 && i > instart + ZOPFLI_MAX_MATCH + 1
283 && i + ZOPFLI_MAX_MATCH * 2 + 1 < inend
284 && h.same[(i - ZOPFLI_MAX_MATCH) & ZOPFLI_WINDOW_MASK] > ZOPFLI_MAX_MATCH as u16
285 {
286 let symbolcost = costmodel(ZOPFLI_MAX_MATCH, 1);
287 // Set the length to reach each one to ZOPFLI_MAX_MATCH, and the cost to
288 // the cost corresponding to that length. Doing this, we skip
289 // ZOPFLI_MAX_MATCH values to avoid calling ZopfliFindLongestMatch.
290
291 for _ in 0..ZOPFLI_MAX_MATCH {
292 costs[j + ZOPFLI_MAX_MATCH] = costs[j] + symbolcost as f32;
293 length_array[j + ZOPFLI_MAX_MATCH] = ZOPFLI_MAX_MATCH as u16;
294 i += 1;
295 j += 1;
296 h.update(arr, i);
297 }
298 }
299
300 longest_match = find_longest_match(
301 lmc,
302 h,
303 arr,
304 i,
305 inend,
306 instart,
307 ZOPFLI_MAX_MATCH,
308 &mut Some(&mut sublen),
309 );
310 leng = longest_match.length;
311
312 // Literal.
313 if i < inend {
314 let new_cost = costmodel(arr[i] as usize, 0) + f64::from(costs[j]);
315 debug_assert!(new_cost >= 0.0);
316 if new_cost < f64::from(costs[j + 1]) {
317 costs[j + 1] = new_cost as f32;
318 length_array[j + 1] = 1;
319 }
320 }
321 // Lengths.
322 let kend = cmp::min(leng as usize, inend - i);
323 let mincostaddcostj = mincost + f64::from(costs[j]);
324
325 for (k, &sublength) in sublen.iter().enumerate().take(kend + 1).skip(3) {
326 // Calling the cost model is expensive, avoid this if we are already at
327 // the minimum possible cost that it can return.
328 if f64::from(costs[j + k]) <= mincostaddcostj {
329 continue;
330 }
331
332 let new_cost = costmodel(k, sublength) + f64::from(costs[j]);
333 debug_assert!(new_cost >= 0.0);
334 if new_cost < f64::from(costs[j + k]) {
335 debug_assert!(k <= ZOPFLI_MAX_MATCH);
336 costs[j + k] = new_cost as f32;
337 length_array[j + k] = k as u16;
338 }
339 }
340 i += 1;
341 }
342
343 debug_assert!(costs[blocksize] >= 0.0);
344 (f64::from(costs[blocksize]), length_array)
345 }
346
347 /// Calculates the optimal path of lz77 lengths to use, from the calculated
348 /// `length_array`. The `length_array` must contain the optimal length to reach that
349 /// byte. The path will be filled with the lengths to use, so its data size will be
350 /// the amount of lz77 symbols.
351 fn trace(size: usize, length_array: &[u16]) -> Vec<u16> {
352 let mut index = size;
353 if size == 0 {
354 return vec![];
355 }
356 let mut path = Vec::with_capacity(index);
357
358 while index > 0 {
359 let lai = length_array[index];
360 let laiu = lai as usize;
361 path.push(lai);
362 debug_assert!(laiu <= index);
363 debug_assert!(laiu <= ZOPFLI_MAX_MATCH);
364 debug_assert_ne!(lai, 0);
365 index -= laiu;
366 }
367
368 path
369 }
370
371 /// Does a single run for `lz77_optimal`. For good compression, repeated runs
372 /// with updated statistics should be performed.
373 /// `s`: the block state
374 /// `in_data`: the input data array
375 /// `instart`: where to start
376 /// `inend`: where to stop (not inclusive)
377 /// `length_array`: array of size `(inend - instart)` used to store lengths
378 /// `costmodel`: function to use as the cost model for this squeeze run
379 /// `store`: place to output the LZ77 data
380 /// returns the cost that was, according to the `costmodel`, needed to get to the end.
381 /// This is not the actual cost.
382 #[allow(clippy::too_many_arguments)] // Not feasible to refactor in a more readable way
383 fn lz77_optimal_run<F: Fn(usize, u16) -> f64, C: Cache>(
384 lmc: &mut C,
385 in_data: &[u8],
386 instart: usize,
387 inend: usize,
388 costmodel: F,
389 store: &mut Lz77Store,
390 h: &mut ZopfliHash,
391 costs: &mut Vec<f32>,
392 ) {
393 let (cost, length_array) = get_best_lengths(lmc, in_data, instart, inend, costmodel, h, costs);
394 let path = trace(inend - instart, &length_array);
395 store.follow_path(in_data, instart, inend, path, lmc);
396 debug_assert!(cost < f64::INFINITY);
397 }
398
399 /// Does the same as `lz77_optimal`, but optimized for the fixed tree of the
400 /// deflate standard.
401 /// The fixed tree never gives the best compression. But this gives the best
402 /// possible LZ77 encoding possible with the fixed tree.
403 /// This does not create or output any fixed tree, only LZ77 data optimized for
404 /// using with a fixed tree.
405 /// If `instart` is larger than `0`, it uses values before `instart` as starting
406 /// dictionary.
407 pub fn lz77_optimal_fixed<C: Cache>(
408 lmc: &mut C,
409 in_data: &[u8],
410 instart: usize,
411 inend: usize,
412 store: &mut Lz77Store,
413 ) {
414 let mut costs = Vec::with_capacity(inend - instart);
415 lz77_optimal_run(
416 lmc,
417 in_data,
418 instart,
419 inend,
420 get_cost_fixed,
421 store,
422 &mut ZopfliHash::new(),
423 &mut costs,
424 );
425 }
426
427 /// Calculates lit/len and dist pairs for given data.
428 /// If `instart` is larger than 0, it uses values before `instart` as starting
429 /// dictionary.
430 pub fn lz77_optimal<C: Cache>(
431 lmc: &mut C,
432 in_data: &[u8],
433 instart: usize,
434 inend: usize,
435 max_iterations: u64,
436 max_iterations_without_improvement: u64,
437 ) -> Lz77Store {
438 /* Dist to get to here with smallest cost. */
439 let mut currentstore = Lz77Store::new();
440 let mut outputstore = currentstore.clone();
441
442 /* Initial run. */
443 currentstore.greedy(lmc, in_data, instart, inend);
444 let mut stats = SymbolStats::default();
445 stats.get_statistics(&currentstore);
446
447 let mut h = ZopfliHash::new();
448 let mut costs = Vec::with_capacity(inend - instart + 1);
449
450 let mut beststats = SymbolStats::default();
451
452 let mut bestcost = f64::INFINITY;
453 let mut lastcost = 0.0;
454 /* Try randomizing the costs a bit once the size stabilizes. */
455 let mut ran_state = RanState::new();
456 let mut lastrandomstep = u64::MAX;
457
458 /* Do regular deflate, then loop multiple shortest path runs, each time using
459 the statistics of the previous run. */
460 /* Repeat statistics with each time the cost model from the previous stat
461 run. */
462 let mut current_iteration: u64 = 0;
463 let mut iterations_without_improvement: u64 = 0;
464 loop {
465 currentstore.reset();
466 lz77_optimal_run(
467 lmc,
468 in_data,
469 instart,
470 inend,
471 |a, b| get_cost_stat(a, b, &stats),
472 &mut currentstore,
473 &mut h,
474 &mut costs,
475 );
476 let cost = calculate_block_size(&currentstore, 0, currentstore.size(), BlockType::Dynamic);
477
478 if cost < bestcost {
479 iterations_without_improvement = 0;
480 /* Copy to the output store. */
481 outputstore = currentstore.clone();
482 beststats = stats;
483 bestcost = cost;
484
485 debug!("Iteration {current_iteration}: {cost} bit");
486 } else {
487 iterations_without_improvement += 1;
488 trace!("Iteration {current_iteration}: {cost} bit");
489 if iterations_without_improvement >= max_iterations_without_improvement {
490 break;
491 }
492 }
493 current_iteration += 1;
494 if current_iteration >= max_iterations {
495 break;
496 }
497 let laststats = stats;
498 stats.clear_freqs();
499 stats.get_statistics(&currentstore);
500 if lastrandomstep != u64::MAX {
501 /* This makes it converge slower but better. Do it only once the
502 randomness kicks in so that if the user does few iterations, it gives a
503 better result sooner. */
504 stats = add_weighed_stat_freqs(&stats, 1.0, &laststats, 0.5);
505 stats.calculate_entropy();
506 }
507 if current_iteration > 5 && (cost - lastcost).abs() < f64::EPSILON {
508 stats = beststats;
509 stats.randomize_stat_freqs(&mut ran_state);
510 stats.calculate_entropy();
511 lastrandomstep = current_iteration;
512 }
513 lastcost = cost;
514 }
515 outputstore
516 }