Debian Codegraph @

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

raw
1 use alloc::vec::Vec;
2
3 #[cfg(feature = "std")]
4 use log::{debug, log_enabled};
5
6 use crate::{cache::NoCache, deflate::calculate_block_size_auto_type, lz77::Lz77Store};
7
8 /// Finds minimum of function `f(i)` where `i` is of type `usize`, `f(i)` is of type
9 /// `f64`, `i` is in range `start-end` (excluding `end`).
10 /// Returns the index to the minimum and the minimum value.
11 fn find_minimum<F: Fn(usize) -> f64>(f: F, start: usize, end: usize) -> (usize, f64) {
12 if end - start < 1024 {
13 let mut best = f64::INFINITY;
14 let mut result = start;
15 for i in start..end {
16 let v = f(i);
17 if v < best {
18 best = v;
19 result = i;
20 }
21 }
22 (result, best)
23 } else {
24 /* Try to find minimum faster by recursively checking multiple points. */
25 let mut start = start;
26 let mut end = end;
27 const NUM: usize = 9; /* Good value: 9. ?!?!?!?! */
28 let mut p = [0; NUM];
29 let mut vp = [0.0; NUM];
30 let mut lastbest = f64::INFINITY;
31 let mut pos = start;
32
33 while end - start > NUM {
34 let mut besti = 0;
35 let mut best = f64::INFINITY;
36 let multiplier = (end - start) / (NUM + 1);
37 for i in 0..NUM {
38 p[i] = start + (i + 1) * multiplier;
39 vp[i] = f(p[i]);
40 if vp[i] < best {
41 best = vp[i];
42 besti = i;
43 }
44 }
45 if best > lastbest {
46 break;
47 }
48
49 start = if besti == 0 { start } else { p[besti - 1] };
50 end = if besti == NUM - 1 { end } else { p[besti + 1] };
51
52 pos = p[besti];
53 lastbest = best;
54 }
55 (pos, lastbest)
56 }
57 }
58
59 /// Returns estimated cost of a block in bits. It includes the size to encode the
60 /// tree and the size to encode all literal, length and distance symbols and their
61 /// extra bits.
62 ///
63 /// litlens: lz77 lit/lengths
64 /// dists: ll77 distances
65 /// lstart: start of block
66 /// lend: end of block (not inclusive)
67 fn estimate_cost(lz77: &Lz77Store, lstart: usize, lend: usize) -> f64 {
68 calculate_block_size_auto_type(lz77, lstart, lend)
69 }
70
71 /// Finds next block to try to split, the largest of the available ones.
72 /// The largest is chosen to make sure that if only a limited amount of blocks is
73 /// requested, their sizes are spread evenly.
74 /// lz77size: the size of the LL77 data, which is the size of the done array here.
75 /// done: array indicating which blocks starting at that position are no longer
76 /// splittable (splitting them increases rather than decreases cost).
77 /// splitpoints: the splitpoints found so far.
78 /// npoints: the amount of splitpoints found so far.
79 /// lstart: output variable, giving start of block.
80 /// lend: output variable, giving end of block.
81 /// returns 1 if a block was found, 0 if no block found (all are done).
82 fn find_largest_splittable_block(
83 lz77size: usize,
84 done: &[u8],
85 splitpoints: &[usize],
86 ) -> Option<(usize, usize)> {
87 let mut longest = 0;
88 let mut found = None;
89
90 let mut last = 0;
91
92 for &item in splitpoints {
93 if done[last] == 0 && item - last > longest {
94 found = Some((last, item));
95 longest = item - last;
96 }
97 last = item;
98 }
99
100 let end = lz77size - 1;
101 if done[last] == 0 && end - last > longest {
102 found = Some((last, end));
103 }
104
105 found
106 }
107
108 /// Prints the block split points as decimal and hex values in the terminal.
109 #[inline]
110 fn print_block_split_points(lz77: &Lz77Store, lz77splitpoints: &[usize]) {
111 if !log_enabled!(log::Level::Debug) {
112 return;
113 }
114
115 let nlz77points = lz77splitpoints.len();
116 let mut splitpoints = Vec::with_capacity(nlz77points);
117
118 /* The input is given as lz77 indices, but we want to see the uncompressed
119 index values. */
120 let mut pos = 0;
121 if nlz77points > 0 {
122 for (i, item) in lz77.litlens.iter().enumerate() {
123 let length = item.size();
124 if lz77splitpoints[splitpoints.len()] == i {
125 splitpoints.push(pos);
126 if splitpoints.len() == nlz77points {
127 break;
128 }
129 }
130 pos += length;
131 }
132 }
133 debug_assert_eq!(splitpoints.len(), nlz77points);
134
135 debug!(
136 "block split points: {} (hex: {})",
137 splitpoints
138 .iter()
139 .map(|&sp| format!("{sp}"))
140 .collect::<Vec<_>>()
141 .join(" "),
142 splitpoints
143 .iter()
144 .map(|&sp| format!("{sp:x}"))
145 .collect::<Vec<_>>()
146 .join(" ")
147 );
148 }
149
150 /// Does blocksplitting on LZ77 data.
151 /// The output splitpoints are indices in the LZ77 data.
152 /// maxblocks: set a limit to the amount of blocks. Set to 0 to mean no limit.
153 pub fn blocksplit_lz77(lz77: &Lz77Store, maxblocks: u16, splitpoints: &mut Vec<usize>) {
154 if lz77.size() < 10 {
155 return; /* This code fails on tiny files. */
156 }
157
158 let mut numblocks = 1u32;
159 let mut done = vec![0; lz77.size()];
160 let mut lstart = 0;
161 let mut lend = lz77.size();
162
163 while maxblocks != 0 && numblocks < u32::from(maxblocks) {
164 debug_assert!(lstart < lend);
165 let find_minimum_result = find_minimum(
166 |i| estimate_cost(lz77, lstart, i) + estimate_cost(lz77, i, lend),
167 lstart + 1,
168 lend,
169 );
170 let llpos = find_minimum_result.0;
171 let splitcost = find_minimum_result.1;
172
173 debug_assert!(llpos > lstart);
174 debug_assert!(llpos < lend);
175
176 let origcost = estimate_cost(lz77, lstart, lend);
177
178 if splitcost > origcost || llpos == lstart + 1 || llpos == lend {
179 done[lstart] = 1;
180 } else {
181 splitpoints.push(llpos);
182 splitpoints.sort_unstable();
183 numblocks += 1;
184 }
185
186 // If `find_largest_splittable_block` returns `None`, no further split will
187 // likely reduce compression.
188 let is_finished = find_largest_splittable_block(lz77.size(), &done, splitpoints).map_or(
189 true,
190 |(start, end)| {
191 lstart = start;
192 lend = end;
193 lend - lstart < 10
194 },
195 );
196
197 if is_finished {
198 break;
199 }
200 }
201
202 print_block_split_points(lz77, splitpoints);
203 }
204
205 /// Does blocksplitting on uncompressed data.
206 /// The output splitpoints are indices in the uncompressed bytes.
207 ///
208 /// options: general program options.
209 /// in: uncompressed input data
210 /// instart: where to start splitting
211 /// inend: where to end splitting (not inclusive)
212 /// maxblocks: maximum amount of blocks to split into, or 0 for no limit
213 /// splitpoints: dynamic array to put the resulting split point coordinates into.
214 /// The coordinates are indices in the input array.
215 /// npoints: pointer to amount of splitpoints, for the dynamic array. The amount of
216 /// blocks is the amount of splitpoitns + 1.
217 pub fn blocksplit(
218 in_data: &[u8],
219 instart: usize,
220 inend: usize,
221 maxblocks: u16,
222 splitpoints: &mut Vec<usize>,
223 ) {
224 splitpoints.clear();
225 let mut store = Lz77Store::new();
226
227 /* Unintuitively, Using a simple LZ77 method here instead of lz77_optimal
228 results in better blocks. */
229 {
230 store.greedy(&mut NoCache, in_data, instart, inend);
231 }
232
233 let mut lz77splitpoints = Vec::with_capacity(maxblocks as usize);
234 blocksplit_lz77(&store, maxblocks, &mut lz77splitpoints);
235
236 let nlz77points = lz77splitpoints.len();
237
238 /* Convert LZ77 positions to positions in the uncompressed input. */
239 let mut pos = instart;
240 if nlz77points > 0 {
241 for (i, item) in store.litlens.iter().enumerate() {
242 let length = item.size();
243 if lz77splitpoints[splitpoints.len()] == i {
244 splitpoints.push(pos);
245 if splitpoints.len() == nlz77points {
246 break;
247 }
248 }
249 pos += length;
250 }
251 }
252 debug_assert_eq!(splitpoints.len(), nlz77points);
253 }