/src/libdeflate/lib/deflate_compress.c
Line | Count | Source |
1 | | /* |
2 | | * deflate_compress.c - a compressor for DEFLATE |
3 | | * |
4 | | * Copyright 2016 Eric Biggers |
5 | | * |
6 | | * Permission is hereby granted, free of charge, to any person |
7 | | * obtaining a copy of this software and associated documentation |
8 | | * files (the "Software"), to deal in the Software without |
9 | | * restriction, including without limitation the rights to use, |
10 | | * copy, modify, merge, publish, distribute, sublicense, and/or sell |
11 | | * copies of the Software, and to permit persons to whom the |
12 | | * Software is furnished to do so, subject to the following |
13 | | * conditions: |
14 | | * |
15 | | * The above copyright notice and this permission notice shall be |
16 | | * included in all copies or substantial portions of the Software. |
17 | | * |
18 | | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
19 | | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES |
20 | | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
21 | | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
22 | | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, |
23 | | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
24 | | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR |
25 | | * OTHER DEALINGS IN THE SOFTWARE. |
26 | | */ |
27 | | |
28 | | #include "deflate_compress.h" |
29 | | #include "deflate_constants.h" |
30 | | |
31 | | /******************************************************************************/ |
32 | | |
33 | | /* |
34 | | * The following parameters can be changed at build time to customize the |
35 | | * compression algorithms slightly: |
36 | | * |
37 | | * (Note, not all customizable parameters are here. Some others can be found in |
38 | | * libdeflate_alloc_compressor() and in *_matchfinder.h.) |
39 | | */ |
40 | | |
41 | | /* |
42 | | * If this parameter is defined to 1, then the near-optimal parsing algorithm |
43 | | * will be included, and compression levels 10-12 will use it. This algorithm |
44 | | * usually produces a compression ratio significantly better than the other |
45 | | * algorithms. However, it is slow. If this parameter is defined to 0, then |
46 | | * levels 10-12 will be the same as level 9 and will use the lazy2 algorithm. |
47 | | */ |
48 | | #define SUPPORT_NEAR_OPTIMAL_PARSING 1 |
49 | | |
50 | | /* |
51 | | * This is the minimum block length that the compressor will use, in |
52 | | * uncompressed bytes. This should be a value below which using shorter blocks |
53 | | * is unlikely to be worthwhile, due to the per-block overhead. This value does |
54 | | * not apply to the final block, which may be shorter than this (if the input is |
55 | | * shorter, it will have to be), or to the final uncompressed block in a series |
56 | | * of uncompressed blocks that cover more than UINT16_MAX bytes. |
57 | | * |
58 | | * This value is also approximately the amount by which what would otherwise be |
59 | | * the second-to-last block is allowed to grow past the soft maximum length in |
60 | | * order to avoid having to use a very short final block. |
61 | | * |
62 | | * Defining a fixed minimum block length is needed in order to guarantee a |
63 | | * reasonable upper bound on the compressed size. It's also needed because our |
64 | | * block splitting algorithm doesn't work well on very short blocks. |
65 | | */ |
66 | 3.91M | #define MIN_BLOCK_LENGTH 5000 |
67 | | |
68 | | /* |
69 | | * For the greedy, lazy, lazy2, and near-optimal compressors: This is the soft |
70 | | * maximum block length, in uncompressed bytes. The compressor will try to end |
71 | | * blocks at this length, but it may go slightly past it if there is a match |
72 | | * that straddles this limit or if the input data ends soon after this limit. |
73 | | * This parameter doesn't apply to uncompressed blocks, which the DEFLATE format |
74 | | * limits to 65535 bytes. |
75 | | * |
76 | | * This should be a value above which it is very likely that splitting the block |
77 | | * would produce a better compression ratio. For the near-optimal compressor, |
78 | | * increasing/decreasing this parameter will increase/decrease per-compressor |
79 | | * memory usage linearly. |
80 | | */ |
81 | 1.82k | #define SOFT_MAX_BLOCK_LENGTH 300000 |
82 | | |
83 | | /* |
84 | | * For the greedy, lazy, and lazy2 compressors: this is the length of the |
85 | | * sequence store, which is an array where the compressor temporarily stores |
86 | | * matches that it's going to use in the current block. This value is the |
87 | | * maximum number of matches that can be used in a block. If the sequence store |
88 | | * fills up, then the compressor will be forced to end the block early. This |
89 | | * value should be large enough so that this rarely happens, due to the block |
90 | | * being ended normally before then. Increasing/decreasing this value will |
91 | | * increase/decrease per-compressor memory usage linearly. |
92 | | */ |
93 | 1.44M | #define SEQ_STORE_LENGTH 50000 |
94 | | |
95 | | /* |
96 | | * For deflate_compress_fastest(): This is the soft maximum block length. |
97 | | * deflate_compress_fastest() doesn't use the regular block splitting algorithm; |
98 | | * it only ends blocks when they reach FAST_SOFT_MAX_BLOCK_LENGTH bytes or |
99 | | * FAST_SEQ_STORE_LENGTH matches. Therefore, this value should be lower than |
100 | | * the regular SOFT_MAX_BLOCK_LENGTH. |
101 | | */ |
102 | 0 | #define FAST_SOFT_MAX_BLOCK_LENGTH 65535 |
103 | | |
104 | | /* |
105 | | * For deflate_compress_fastest(): this is the length of the sequence store. |
106 | | * This is like SEQ_STORE_LENGTH, but this should be a lower value. |
107 | | */ |
108 | 0 | #define FAST_SEQ_STORE_LENGTH 8192 |
109 | | |
110 | | /* |
111 | | * These are the maximum codeword lengths, in bits, the compressor will use for |
112 | | * each Huffman code. The DEFLATE format defines limits for these. However, |
113 | | * further limiting litlen codewords to 14 bits is beneficial, since it has |
114 | | * negligible effect on compression ratio but allows some optimizations when |
115 | | * outputting bits. (It allows 4 literals to be written at once rather than 3.) |
116 | | */ |
117 | 3.32k | #define MAX_LITLEN_CODEWORD_LEN 14 |
118 | 3.32k | #define MAX_OFFSET_CODEWORD_LEN DEFLATE_MAX_OFFSET_CODEWORD_LEN |
119 | 1.82k | #define MAX_PRE_CODEWORD_LEN DEFLATE_MAX_PRE_CODEWORD_LEN |
120 | | |
121 | | #if SUPPORT_NEAR_OPTIMAL_PARSING |
122 | | |
123 | | /* Parameters specific to the near-optimal parsing algorithm */ |
124 | | |
125 | | /* |
126 | | * BIT_COST is a scaling factor that allows the near-optimal compressor to |
127 | | * consider fractional bit costs when deciding which literal/match sequence to |
128 | | * use. This is useful when the true symbol costs are unknown. For example, if |
129 | | * the compressor thinks that a symbol has 6.5 bits of entropy, it can set its |
130 | | * cost to 6.5 bits rather than have to use 6 or 7 bits. Although in the end |
131 | | * each symbol will use a whole number of bits due to the Huffman coding, |
132 | | * considering fractional bits can be helpful due to the limited information. |
133 | | * |
134 | | * BIT_COST should be a power of 2. A value of 8 or 16 works well. A higher |
135 | | * value isn't very useful since the calculations are approximate anyway. |
136 | | * |
137 | | * BIT_COST doesn't apply to deflate_flush_block() and |
138 | | * deflate_compute_true_cost(), which consider whole bits. |
139 | | */ |
140 | 0 | #define BIT_COST 16 |
141 | | |
142 | | /* |
143 | | * The NOSTAT_BITS value for a given alphabet is the number of bits assumed to |
144 | | * be needed to output a symbol that was unused in the previous optimization |
145 | | * pass. Assigning a default cost allows the symbol to be used in the next |
146 | | * optimization pass. However, the cost should be relatively high because the |
147 | | * symbol probably won't be used very many times (if at all). |
148 | | */ |
149 | 0 | #define LITERAL_NOSTAT_BITS 13 |
150 | 0 | #define LENGTH_NOSTAT_BITS 13 |
151 | 0 | #define OFFSET_NOSTAT_BITS 10 |
152 | | |
153 | | /* |
154 | | * This is (slightly less than) the maximum number of matches that the |
155 | | * near-optimal compressor will cache per block. This behaves similarly to |
156 | | * SEQ_STORE_LENGTH for the other compressors. |
157 | | */ |
158 | 0 | #define MATCH_CACHE_LENGTH (SOFT_MAX_BLOCK_LENGTH * 5) |
159 | | |
160 | | #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */ |
161 | | |
162 | | /******************************************************************************/ |
163 | | |
164 | | /* Include the needed matchfinders. */ |
165 | 21.1M | #define MATCHFINDER_WINDOW_ORDER DEFLATE_WINDOW_ORDER |
166 | | #include "hc_matchfinder.h" |
167 | | #include "ht_matchfinder.h" |
168 | | #if SUPPORT_NEAR_OPTIMAL_PARSING |
169 | | # include "bt_matchfinder.h" |
170 | | /* |
171 | | * This is the maximum number of matches the binary trees matchfinder can find |
172 | | * at a single position. Since the matchfinder never finds more than one match |
173 | | * for the same length, presuming one of each possible length is sufficient for |
174 | | * an upper bound. (This says nothing about whether it is worthwhile to |
175 | | * consider so many matches; this is just defining the worst case.) |
176 | | */ |
177 | | #define MAX_MATCHES_PER_POS \ |
178 | | (DEFLATE_MAX_MATCH_LEN - DEFLATE_MIN_MATCH_LEN + 1) |
179 | | #endif |
180 | | |
181 | | /* |
182 | | * The largest block length we will ever use is when the final block is of |
183 | | * length SOFT_MAX_BLOCK_LENGTH + MIN_BLOCK_LENGTH - 1, or when any block is of |
184 | | * length SOFT_MAX_BLOCK_LENGTH + 1 + DEFLATE_MAX_MATCH_LEN. The latter case |
185 | | * occurs when the lazy2 compressor chooses two literals and a maximum-length |
186 | | * match, starting at SOFT_MAX_BLOCK_LENGTH - 1. |
187 | | */ |
188 | | #define MAX_BLOCK_LENGTH \ |
189 | | MAX(SOFT_MAX_BLOCK_LENGTH + MIN_BLOCK_LENGTH - 1, \ |
190 | | SOFT_MAX_BLOCK_LENGTH + 1 + DEFLATE_MAX_MATCH_LEN) |
191 | | |
192 | | static forceinline void |
193 | | check_buildtime_parameters(void) |
194 | 1.49k | { |
195 | | /* |
196 | | * Verify that MIN_BLOCK_LENGTH is being honored, as |
197 | | * libdeflate_deflate_compress_bound() depends on it. |
198 | | */ |
199 | 1.49k | STATIC_ASSERT(SOFT_MAX_BLOCK_LENGTH >= MIN_BLOCK_LENGTH); |
200 | 1.49k | STATIC_ASSERT(FAST_SOFT_MAX_BLOCK_LENGTH >= MIN_BLOCK_LENGTH); |
201 | 1.49k | STATIC_ASSERT(SEQ_STORE_LENGTH * DEFLATE_MIN_MATCH_LEN >= |
202 | 1.49k | MIN_BLOCK_LENGTH); |
203 | 1.49k | STATIC_ASSERT(FAST_SEQ_STORE_LENGTH * HT_MATCHFINDER_MIN_MATCH_LEN >= |
204 | 1.49k | MIN_BLOCK_LENGTH); |
205 | 1.49k | #if SUPPORT_NEAR_OPTIMAL_PARSING |
206 | 1.49k | STATIC_ASSERT(MIN_BLOCK_LENGTH * MAX_MATCHES_PER_POS <= |
207 | 1.49k | MATCH_CACHE_LENGTH); |
208 | 1.49k | #endif |
209 | | |
210 | | /* The definition of MAX_BLOCK_LENGTH assumes this. */ |
211 | 1.49k | STATIC_ASSERT(FAST_SOFT_MAX_BLOCK_LENGTH <= SOFT_MAX_BLOCK_LENGTH); |
212 | | |
213 | | /* Verify that the sequence stores aren't uselessly large. */ |
214 | 1.49k | STATIC_ASSERT(SEQ_STORE_LENGTH * DEFLATE_MIN_MATCH_LEN <= |
215 | 1.49k | SOFT_MAX_BLOCK_LENGTH + MIN_BLOCK_LENGTH); |
216 | 1.49k | STATIC_ASSERT(FAST_SEQ_STORE_LENGTH * HT_MATCHFINDER_MIN_MATCH_LEN <= |
217 | 1.49k | FAST_SOFT_MAX_BLOCK_LENGTH + MIN_BLOCK_LENGTH); |
218 | | |
219 | | /* Verify that the maximum codeword lengths are valid. */ |
220 | 1.49k | STATIC_ASSERT( |
221 | 1.49k | MAX_LITLEN_CODEWORD_LEN <= DEFLATE_MAX_LITLEN_CODEWORD_LEN); |
222 | 1.49k | STATIC_ASSERT( |
223 | 1.49k | MAX_OFFSET_CODEWORD_LEN <= DEFLATE_MAX_OFFSET_CODEWORD_LEN); |
224 | 1.49k | STATIC_ASSERT( |
225 | 1.49k | MAX_PRE_CODEWORD_LEN <= DEFLATE_MAX_PRE_CODEWORD_LEN); |
226 | 1.49k | STATIC_ASSERT( |
227 | 1.49k | (1U << MAX_LITLEN_CODEWORD_LEN) >= DEFLATE_NUM_LITLEN_SYMS); |
228 | 1.49k | STATIC_ASSERT( |
229 | 1.49k | (1U << MAX_OFFSET_CODEWORD_LEN) >= DEFLATE_NUM_OFFSET_SYMS); |
230 | 1.49k | STATIC_ASSERT( |
231 | 1.49k | (1U << MAX_PRE_CODEWORD_LEN) >= DEFLATE_NUM_PRECODE_SYMS); |
232 | 1.49k | } |
233 | | |
234 | | /******************************************************************************/ |
235 | | |
236 | | /* Table: length slot => length slot base value */ |
237 | | static const u32 deflate_length_slot_base[] = { |
238 | | 3, 4, 5, 6, 7, 8, 9, 10, |
239 | | 11, 13, 15, 17, 19, 23, 27, 31, |
240 | | 35, 43, 51, 59, 67, 83, 99, 115, |
241 | | 131, 163, 195, 227, 258, |
242 | | }; |
243 | | |
244 | | /* Table: length slot => number of extra length bits */ |
245 | | static const u8 deflate_extra_length_bits[] = { |
246 | | 0, 0, 0, 0, 0, 0, 0, 0, |
247 | | 1, 1, 1, 1, 2, 2, 2, 2, |
248 | | 3, 3, 3, 3, 4, 4, 4, 4, |
249 | | 5, 5, 5, 5, 0, |
250 | | }; |
251 | | |
252 | | /* Table: offset slot => offset slot base value */ |
253 | | static const u32 deflate_offset_slot_base[] = { |
254 | | 1, 2, 3, 4, 5, 7, 9, 13, |
255 | | 17, 25, 33, 49, 65, 97, 129, 193, |
256 | | 257, 385, 513, 769, 1025, 1537, 2049, 3073, |
257 | | 4097, 6145, 8193, 12289, 16385, 24577, |
258 | | }; |
259 | | |
260 | | /* Table: offset slot => number of extra offset bits */ |
261 | | static const u8 deflate_extra_offset_bits[] = { |
262 | | 0, 0, 0, 0, 1, 1, 2, 2, |
263 | | 3, 3, 4, 4, 5, 5, 6, 6, |
264 | | 7, 7, 8, 8, 9, 9, 10, 10, |
265 | | 11, 11, 12, 12, 13, 13, |
266 | | }; |
267 | | |
268 | | /* Table: length => length slot */ |
269 | | static const u8 deflate_length_slot[DEFLATE_MAX_MATCH_LEN + 1] = { |
270 | | 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, |
271 | | 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, |
272 | | 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, |
273 | | 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, |
274 | | 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, |
275 | | 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, |
276 | | 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, |
277 | | 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, |
278 | | 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, |
279 | | 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, |
280 | | 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, |
281 | | 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, |
282 | | 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, |
283 | | 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, |
284 | | 27, 27, 28, |
285 | | }; |
286 | | |
287 | | /* |
288 | | * Table: 'offset - 1 => offset_slot' for offset <= 256. |
289 | | * This was generated by scripts/gen_offset_slot_map.py. |
290 | | */ |
291 | | static const u8 deflate_offset_slot[256] = { |
292 | | 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, |
293 | | 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, |
294 | | 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, |
295 | | 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, |
296 | | 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, |
297 | | 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, |
298 | | 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, |
299 | | 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, |
300 | | 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, |
301 | | 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, |
302 | | 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, |
303 | | 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, |
304 | | 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, |
305 | | 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, |
306 | | 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, |
307 | | 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, |
308 | | }; |
309 | | |
310 | | /* The order in which precode codeword lengths are stored */ |
311 | | static const u8 deflate_precode_lens_permutation[DEFLATE_NUM_PRECODE_SYMS] = { |
312 | | 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 |
313 | | }; |
314 | | |
315 | | /* Table: precode symbol => number of extra bits */ |
316 | | static const u8 deflate_extra_precode_bits[DEFLATE_NUM_PRECODE_SYMS] = { |
317 | | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 |
318 | | }; |
319 | | |
320 | | /* Codewords for the DEFLATE Huffman codes */ |
321 | | struct deflate_codewords { |
322 | | u32 litlen[DEFLATE_NUM_LITLEN_SYMS]; |
323 | | u32 offset[DEFLATE_NUM_OFFSET_SYMS]; |
324 | | }; |
325 | | |
326 | | /* |
327 | | * Codeword lengths (in bits) for the DEFLATE Huffman codes. |
328 | | * A zero length means the corresponding symbol had zero frequency. |
329 | | */ |
330 | | struct deflate_lens { |
331 | | u8 litlen[DEFLATE_NUM_LITLEN_SYMS]; |
332 | | u8 offset[DEFLATE_NUM_OFFSET_SYMS]; |
333 | | }; |
334 | | |
335 | | /* Codewords and lengths for the DEFLATE Huffman codes */ |
336 | | struct deflate_codes { |
337 | | struct deflate_codewords codewords; |
338 | | struct deflate_lens lens; |
339 | | }; |
340 | | |
341 | | /* Symbol frequency counters for the DEFLATE Huffman codes */ |
342 | | struct deflate_freqs { |
343 | | u32 litlen[DEFLATE_NUM_LITLEN_SYMS]; |
344 | | u32 offset[DEFLATE_NUM_OFFSET_SYMS]; |
345 | | }; |
346 | | |
347 | | /* |
348 | | * Represents a run of literals followed by a match or end-of-block. This |
349 | | * struct is needed to temporarily store items chosen by the parser, since items |
350 | | * cannot be written until all items for the block have been chosen and the |
351 | | * block's Huffman codes have been computed. |
352 | | */ |
353 | | struct deflate_sequence { |
354 | | |
355 | | /* |
356 | | * Bits 0..22: the number of literals in this run. This may be 0 and |
357 | | * can be at most MAX_BLOCK_LENGTH. The literals are not stored |
358 | | * explicitly in this structure; instead, they are read directly from |
359 | | * the uncompressed data. |
360 | | * |
361 | | * Bits 23..31: the length of the match which follows the literals, or 0 |
362 | | * if this literal run was the last in the block, so there is no match |
363 | | * which follows it. |
364 | | */ |
365 | 942k | #define SEQ_LENGTH_SHIFT 23 |
366 | 314k | #define SEQ_LITRUNLEN_MASK (((u32)1 << SEQ_LENGTH_SHIFT) - 1) |
367 | | u32 litrunlen_and_length; |
368 | | |
369 | | /* |
370 | | * If 'length' doesn't indicate end-of-block, then this is the offset of |
371 | | * the match which follows the literals. |
372 | | */ |
373 | | u16 offset; |
374 | | |
375 | | /* |
376 | | * If 'length' doesn't indicate end-of-block, then this is the offset |
377 | | * slot of the match which follows the literals. |
378 | | */ |
379 | | u16 offset_slot; |
380 | | }; |
381 | | |
382 | | #if SUPPORT_NEAR_OPTIMAL_PARSING |
383 | | |
384 | | /* Costs for the near-optimal parsing algorithm */ |
385 | | struct deflate_costs { |
386 | | |
387 | | /* The cost to output each possible literal */ |
388 | | u32 literal[DEFLATE_NUM_LITERALS]; |
389 | | |
390 | | /* The cost to output each possible match length */ |
391 | | u32 length[DEFLATE_MAX_MATCH_LEN + 1]; |
392 | | |
393 | | /* The cost to output a match offset of each possible offset slot */ |
394 | | u32 offset_slot[DEFLATE_NUM_OFFSET_SYMS]; |
395 | | }; |
396 | | |
397 | | /* |
398 | | * This structure represents a byte position in the input data and a node in the |
399 | | * graph of possible match/literal choices for the current block. |
400 | | * |
401 | | * Logically, each incoming edge to this node is labeled with a literal or a |
402 | | * match that can be taken to reach this position from an earlier position; and |
403 | | * each outgoing edge from this node is labeled with a literal or a match that |
404 | | * can be taken to advance from this position to a later position. |
405 | | * |
406 | | * But these "edges" are actually stored elsewhere (in 'match_cache'). Here we |
407 | | * associate with each node just two pieces of information: |
408 | | * |
409 | | * 'cost_to_end' is the minimum cost to reach the end of the block from |
410 | | * this position. |
411 | | * |
412 | | * 'item' represents the literal or match that must be chosen from here to |
413 | | * reach the end of the block with the minimum cost. Equivalently, this |
414 | | * can be interpreted as the label of the outgoing edge on the minimum-cost |
415 | | * path to the "end of block" node from this node. |
416 | | */ |
417 | | struct deflate_optimum_node { |
418 | | |
419 | | u32 cost_to_end; |
420 | | |
421 | | /* |
422 | | * Notes on the match/literal representation used here: |
423 | | * |
424 | | * The low bits of 'item' are the length: 1 if this is a literal, |
425 | | * or the match length if this is a match. |
426 | | * |
427 | | * The high bits of 'item' are the actual literal byte if this is a |
428 | | * literal, or the match offset if this is a match. |
429 | | */ |
430 | 0 | #define OPTIMUM_OFFSET_SHIFT 9 |
431 | 0 | #define OPTIMUM_LEN_MASK (((u32)1 << OPTIMUM_OFFSET_SHIFT) - 1) |
432 | | u32 item; |
433 | | |
434 | | }; |
435 | | |
436 | | #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */ |
437 | | |
438 | | /* Block split statistics. See "Block splitting algorithm" below. */ |
439 | 334k | #define NUM_LITERAL_OBSERVATION_TYPES 8 |
440 | 21.7k | #define NUM_MATCH_OBSERVATION_TYPES 2 |
441 | 21.7k | #define NUM_OBSERVATION_TYPES (NUM_LITERAL_OBSERVATION_TYPES + \ |
442 | 21.7k | NUM_MATCH_OBSERVATION_TYPES) |
443 | 2.88M | #define NUM_OBSERVATIONS_PER_BLOCK_CHECK 512 |
444 | | struct block_split_stats { |
445 | | u32 new_observations[NUM_OBSERVATION_TYPES]; |
446 | | u32 observations[NUM_OBSERVATION_TYPES]; |
447 | | u32 num_new_observations; |
448 | | u32 num_observations; |
449 | | }; |
450 | | |
451 | | struct deflate_output_bitstream; |
452 | | |
453 | | /* The main DEFLATE compressor structure */ |
454 | | struct libdeflate_compressor { |
455 | | |
456 | | /* Pointer to the compress() implementation chosen at allocation time */ |
457 | | void (*impl)(struct libdeflate_compressor *restrict c, const u8 *in, |
458 | | size_t in_nbytes, struct deflate_output_bitstream *os); |
459 | | |
460 | | /* The free() function for this struct, chosen at allocation time */ |
461 | | free_func_t free_func; |
462 | | |
463 | | /* The compression level with which this compressor was created */ |
464 | | unsigned compression_level; |
465 | | |
466 | | /* Anything of this size or less we won't bother trying to compress. */ |
467 | | size_t max_passthrough_size; |
468 | | |
469 | | /* |
470 | | * The maximum search depth: consider at most this many potential |
471 | | * matches at each position |
472 | | */ |
473 | | u32 max_search_depth; |
474 | | |
475 | | /* |
476 | | * The "nice" match length: if a match of this length is found, choose |
477 | | * it immediately without further consideration |
478 | | */ |
479 | | u32 nice_match_length; |
480 | | |
481 | | /* Frequency counters for the current block */ |
482 | | struct deflate_freqs freqs; |
483 | | |
484 | | /* Block split statistics for the current block */ |
485 | | struct block_split_stats split_stats; |
486 | | |
487 | | /* Dynamic Huffman codes for the current block */ |
488 | | struct deflate_codes codes; |
489 | | |
490 | | /* The static Huffman codes defined by the DEFLATE format */ |
491 | | struct deflate_codes static_codes; |
492 | | |
493 | | /* Temporary space for block flushing */ |
494 | | union { |
495 | | /* Information about the precode */ |
496 | | struct { |
497 | | u32 freqs[DEFLATE_NUM_PRECODE_SYMS]; |
498 | | u32 codewords[DEFLATE_NUM_PRECODE_SYMS]; |
499 | | u8 lens[DEFLATE_NUM_PRECODE_SYMS]; |
500 | | unsigned items[DEFLATE_NUM_LITLEN_SYMS + |
501 | | DEFLATE_NUM_OFFSET_SYMS]; |
502 | | unsigned num_litlen_syms; |
503 | | unsigned num_offset_syms; |
504 | | unsigned num_explicit_lens; |
505 | | unsigned num_items; |
506 | | } precode; |
507 | | /* |
508 | | * The "full" length codewords. Used only after the information |
509 | | * in 'precode' is no longer needed. |
510 | | */ |
511 | | struct { |
512 | | u32 codewords[DEFLATE_MAX_MATCH_LEN + 1]; |
513 | | u8 lens[DEFLATE_MAX_MATCH_LEN + 1]; |
514 | | } length; |
515 | | } o; |
516 | | |
517 | | union { |
518 | | /* Data for greedy or lazy parsing */ |
519 | | struct { |
520 | | /* Matches and literals chosen for the current block */ |
521 | | struct deflate_sequence sequences[SEQ_STORE_LENGTH + 1]; |
522 | | |
523 | | /* |
524 | | * Hash chains matchfinder. This must be last, since |
525 | | * only the part of it that will be used is allocated. |
526 | | */ |
527 | | struct hc_matchfinder hc_mf; |
528 | | |
529 | | } g; /* (g)reedy */ |
530 | | |
531 | | /* Data for fastest parsing */ |
532 | | struct { |
533 | | /* Hash table matchfinder */ |
534 | | struct ht_matchfinder ht_mf; |
535 | | |
536 | | /* Matches and literals chosen for the current block */ |
537 | | struct deflate_sequence sequences[ |
538 | | FAST_SEQ_STORE_LENGTH + 1]; |
539 | | |
540 | | } f; /* (f)astest */ |
541 | | |
542 | | #if SUPPORT_NEAR_OPTIMAL_PARSING |
543 | | /* Data for near-optimal parsing */ |
544 | | struct { |
545 | | |
546 | | /* Binary tree matchfinder */ |
547 | | struct bt_matchfinder bt_mf; |
548 | | |
549 | | /* |
550 | | * Cached matches for the current block. This array |
551 | | * contains the matches that were found at each position |
552 | | * in the block. Specifically, for each position, there |
553 | | * is a list of matches found at that position, if any, |
554 | | * sorted by strictly increasing length. In addition, |
555 | | * following the matches for each position, there is a |
556 | | * special 'struct lz_match' whose 'length' member |
557 | | * contains the number of matches found at that |
558 | | * position, and whose 'offset' member contains the |
559 | | * literal at that position. |
560 | | * |
561 | | * Note: in rare cases, there will be a very high number |
562 | | * of matches in the block and this array will overflow. |
563 | | * If this happens, we force the end of the current |
564 | | * block. MATCH_CACHE_LENGTH is the length at which we |
565 | | * actually check for overflow. The extra slots beyond |
566 | | * this are enough to absorb the worst case overflow, |
567 | | * which occurs if starting at |
568 | | * &match_cache[MATCH_CACHE_LENGTH - 1], we write |
569 | | * MAX_MATCHES_PER_POS matches and a match count header, |
570 | | * then skip searching for matches at |
571 | | * 'DEFLATE_MAX_MATCH_LEN - 1' positions and write the |
572 | | * match count header for each. |
573 | | */ |
574 | | struct lz_match match_cache[MATCH_CACHE_LENGTH + |
575 | | MAX_MATCHES_PER_POS + |
576 | | DEFLATE_MAX_MATCH_LEN - 1]; |
577 | | |
578 | | /* |
579 | | * Array of nodes, one per position, for running the |
580 | | * minimum-cost path algorithm. |
581 | | * |
582 | | * This array must be large enough to accommodate the |
583 | | * worst-case number of nodes, which is MAX_BLOCK_LENGTH |
584 | | * plus 1 for the end-of-block node. |
585 | | */ |
586 | | struct deflate_optimum_node optimum_nodes[ |
587 | | MAX_BLOCK_LENGTH + 1]; |
588 | | |
589 | | /* The current cost model being used */ |
590 | | struct deflate_costs costs; |
591 | | |
592 | | /* Saved cost model */ |
593 | | struct deflate_costs costs_saved; |
594 | | |
595 | | /* |
596 | | * A table that maps match offset to offset slot. This |
597 | | * differs from deflate_offset_slot[] in that this is a |
598 | | * full map, not a condensed one. The full map is more |
599 | | * appropriate for the near-optimal parser, since the |
600 | | * near-optimal parser does more offset => offset_slot |
601 | | * translations, it doesn't intersperse them with |
602 | | * matchfinding (so cache evictions are less of a |
603 | | * concern), and it uses more memory anyway. |
604 | | */ |
605 | | u8 offset_slot_full[DEFLATE_MAX_MATCH_OFFSET + 1]; |
606 | | |
607 | | /* Literal/match statistics saved from previous block */ |
608 | | u32 prev_observations[NUM_OBSERVATION_TYPES]; |
609 | | u32 prev_num_observations; |
610 | | |
611 | | /* |
612 | | * Approximate match length frequencies based on a |
613 | | * greedy parse, gathered during matchfinding. This is |
614 | | * used for setting the initial symbol costs. |
615 | | */ |
616 | | u32 new_match_len_freqs[DEFLATE_MAX_MATCH_LEN + 1]; |
617 | | u32 match_len_freqs[DEFLATE_MAX_MATCH_LEN + 1]; |
618 | | |
619 | | /* |
620 | | * The maximum number of optimization passes |
621 | | * (min-cost path searches) per block. |
622 | | * Larger values = more compression. |
623 | | */ |
624 | | unsigned max_optim_passes; |
625 | | |
626 | | /* |
627 | | * If an optimization pass improves the cost by fewer |
628 | | * than this number of bits, then optimization will stop |
629 | | * early, before max_optim_passes has been reached. |
630 | | * Smaller values = more compression. |
631 | | */ |
632 | | u32 min_improvement_to_continue; |
633 | | |
634 | | /* |
635 | | * The minimum number of bits that would need to be |
636 | | * saved for it to be considered worth the time to |
637 | | * regenerate and use the min-cost path from a previous |
638 | | * optimization pass, in the case where the final |
639 | | * optimization pass actually increased the cost. |
640 | | * Smaller values = more compression. |
641 | | */ |
642 | | u32 min_bits_to_use_nonfinal_path; |
643 | | |
644 | | /* |
645 | | * The maximum block length, in uncompressed bytes, at |
646 | | * which to find and consider the optimal match/literal |
647 | | * list for the static Huffman codes. This strategy |
648 | | * improves the compression ratio produced by static |
649 | | * Huffman blocks and can discover more cases in which |
650 | | * static blocks are worthwhile. This helps mostly with |
651 | | * small blocks, hence why this parameter is a max_len. |
652 | | * |
653 | | * Above this block length, static Huffman blocks are |
654 | | * only used opportunistically. I.e. a static Huffman |
655 | | * block is only used if a static block using the same |
656 | | * match/literal list as the optimized dynamic block |
657 | | * happens to be cheaper than the dynamic block itself. |
658 | | */ |
659 | | u32 max_len_to_optimize_static_block; |
660 | | |
661 | | } n; /* (n)ear-optimal */ |
662 | | #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */ |
663 | | |
664 | | } p; /* (p)arser */ |
665 | | }; |
666 | | |
667 | | /* |
668 | | * The type for the bitbuffer variable, which temporarily holds bits that are |
669 | | * being packed into bytes and written to the output buffer. For best |
670 | | * performance, this should have size equal to a machine word. |
671 | | */ |
672 | | typedef machine_word_t bitbuf_t; |
673 | | |
674 | | /* |
675 | | * The capacity of the bitbuffer, in bits. This is 1 less than the real size, |
676 | | * in order to avoid undefined behavior when doing bitbuf >>= bitcount & ~7. |
677 | | */ |
678 | 941k | #define BITBUF_NBITS (8 * sizeof(bitbuf_t) - 1) |
679 | | |
680 | | /* |
681 | | * Can the specified number of bits always be added to 'bitbuf' after any |
682 | | * pending bytes have been flushed? There can be up to 7 bits remaining after a |
683 | | * flush, so the count must not exceed BITBUF_NBITS after adding 'n' more bits. |
684 | | */ |
685 | 941k | #define CAN_BUFFER(n) (7 + (n) <= BITBUF_NBITS) |
686 | | |
687 | | /* |
688 | | * Structure to keep track of the current state of sending bits to the |
689 | | * compressed output buffer |
690 | | */ |
691 | | struct deflate_output_bitstream { |
692 | | |
693 | | /* Bits that haven't yet been written to the output buffer */ |
694 | | bitbuf_t bitbuf; |
695 | | |
696 | | /* |
697 | | * Number of bits currently held in @bitbuf. This can be between 0 and |
698 | | * BITBUF_NBITS in general, or between 0 and 7 after a flush. |
699 | | */ |
700 | | unsigned bitcount; |
701 | | |
702 | | /* |
703 | | * Pointer to the position in the output buffer at which the next byte |
704 | | * should be written |
705 | | */ |
706 | | u8 *next; |
707 | | |
708 | | /* Pointer to the end of the output buffer */ |
709 | | u8 *end; |
710 | | |
711 | | /* true if the output buffer ran out of space */ |
712 | | bool overflow; |
713 | | }; |
714 | | |
715 | | /* |
716 | | * Add some bits to the bitbuffer variable of the output bitstream. The caller |
717 | | * must ensure that 'bitcount + n <= BITBUF_NBITS', by calling FLUSH_BITS() |
718 | | * frequently enough. |
719 | | */ |
720 | 2.67M | #define ADD_BITS(bits, n) \ |
721 | 2.67M | do { \ |
722 | 2.67M | bitbuf |= (bitbuf_t)(bits) << bitcount; \ |
723 | 2.67M | bitcount += (n); \ |
724 | 2.67M | ASSERT(bitcount <= BITBUF_NBITS); \ |
725 | 2.67M | } while (0) |
726 | | |
727 | | /* |
728 | | * Flush bits from the bitbuffer variable to the output buffer. After this, the |
729 | | * bitbuffer will contain at most 7 bits (a partial byte). |
730 | | * |
731 | | * Since deflate_flush_block() verified ahead of time that there is enough space |
732 | | * remaining before actually writing the block, it's guaranteed that out_next |
733 | | * won't exceed os->end. However, there might not be enough space remaining to |
734 | | * flush a whole word, even though that's fastest. Therefore, flush a whole |
735 | | * word if there is space for it, otherwise flush a byte at a time. |
736 | | */ |
737 | 998k | #define FLUSH_BITS() \ |
738 | 998k | do { \ |
739 | 998k | if (UNALIGNED_ACCESS_IS_FAST && likely(out_next < out_fast_end)) { \ |
740 | 998k | /* Flush a whole word (branchlessly). */ \ |
741 | 998k | put_unaligned_leword(bitbuf, out_next); \ |
742 | 998k | bitbuf >>= bitcount & ~7; \ |
743 | 998k | out_next += bitcount >> 3; \ |
744 | 998k | bitcount &= 7; \ |
745 | 998k | } else { \ |
746 | 0 | /* Flush a byte at a time. */ \ |
747 | 0 | while (bitcount >= 8) { \ |
748 | 0 | ASSERT(out_next < os->end); \ |
749 | 0 | *out_next++ = bitbuf; \ |
750 | 0 | bitcount -= 8; \ |
751 | 0 | bitbuf >>= 8; \ |
752 | 0 | } \ |
753 | 0 | } \ |
754 | 998k | } while (0) |
755 | | |
756 | | /* |
757 | | * Given the binary tree node A[subtree_idx] whose children already satisfy the |
758 | | * maxheap property, swap the node with its greater child until it is greater |
759 | | * than or equal to both of its children, so that the maxheap property is |
760 | | * satisfied in the subtree rooted at A[subtree_idx]. 'A' uses 1-based indices. |
761 | | */ |
762 | | static void |
763 | | heapify_subtree(u32 A[], unsigned length, unsigned subtree_idx) |
764 | 8.55k | { |
765 | 8.55k | unsigned parent_idx; |
766 | 8.55k | unsigned child_idx; |
767 | 8.55k | u32 v; |
768 | | |
769 | 8.55k | v = A[subtree_idx]; |
770 | 8.55k | parent_idx = subtree_idx; |
771 | 14.7k | while ((child_idx = parent_idx * 2) <= length) { |
772 | 8.25k | if (child_idx < length && A[child_idx + 1] > A[child_idx]) |
773 | 2.10k | child_idx++; |
774 | 8.25k | if (v >= A[child_idx]) |
775 | 2.09k | break; |
776 | 6.15k | A[parent_idx] = A[child_idx]; |
777 | 6.15k | parent_idx = child_idx; |
778 | 6.15k | } |
779 | 8.55k | A[parent_idx] = v; |
780 | 8.55k | } |
781 | | |
782 | | /* |
783 | | * Rearrange the array 'A' so that it satisfies the maxheap property. |
784 | | * 'A' uses 1-based indices, so the children of A[i] are A[i*2] and A[i*2 + 1]. |
785 | | */ |
786 | | static void |
787 | | heapify_array(u32 A[], unsigned length) |
788 | 8.46k | { |
789 | 8.46k | unsigned subtree_idx; |
790 | | |
791 | 11.6k | for (subtree_idx = length / 2; subtree_idx >= 1; subtree_idx--) |
792 | 3.16k | heapify_subtree(A, length, subtree_idx); |
793 | 8.46k | } |
794 | | |
795 | | /* |
796 | | * Sort the array 'A', which contains 'length' unsigned 32-bit integers. |
797 | | * |
798 | | * Note: name this function heap_sort() instead of heapsort() to avoid colliding |
799 | | * with heapsort() from stdlib.h on BSD-derived systems. |
800 | | */ |
801 | | static void |
802 | | heap_sort(u32 A[], unsigned length) |
803 | 8.46k | { |
804 | 8.46k | A--; /* Use 1-based indices */ |
805 | | |
806 | 8.46k | heapify_array(A, length); |
807 | | |
808 | 13.8k | while (length >= 2) { |
809 | 5.38k | u32 tmp = A[length]; |
810 | | |
811 | 5.38k | A[length] = A[1]; |
812 | 5.38k | A[1] = tmp; |
813 | 5.38k | length--; |
814 | 5.38k | heapify_subtree(A, length, 1); |
815 | 5.38k | } |
816 | 8.46k | } |
817 | | |
818 | 9.71M | #define NUM_SYMBOL_BITS 10 |
819 | | #define NUM_FREQ_BITS (32 - NUM_SYMBOL_BITS) |
820 | 5.95M | #define SYMBOL_MASK ((1 << NUM_SYMBOL_BITS) - 1) |
821 | 2.92M | #define FREQ_MASK (~SYMBOL_MASK) |
822 | | |
823 | 8.46k | #define GET_NUM_COUNTERS(num_syms) (num_syms) |
824 | | |
825 | | /* |
826 | | * Sort the symbols primarily by frequency and secondarily by symbol value. |
827 | | * Discard symbols with zero frequency and fill in an array with the remaining |
828 | | * symbols, along with their frequencies. The low NUM_SYMBOL_BITS bits of each |
829 | | * array entry will contain the symbol value, and the remaining bits will |
830 | | * contain the frequency. |
831 | | * |
832 | | * @num_syms |
833 | | * Number of symbols in the alphabet, at most 1 << NUM_SYMBOL_BITS. |
834 | | * |
835 | | * @freqs[num_syms] |
836 | | * Frequency of each symbol, summing to at most (1 << NUM_FREQ_BITS) - 1. |
837 | | * |
838 | | * @lens[num_syms] |
839 | | * An array that eventually will hold the length of each codeword. This |
840 | | * function only fills in the codeword lengths for symbols that have zero |
841 | | * frequency, which are not well defined per se but will be set to 0. |
842 | | * |
843 | | * @symout[num_syms] |
844 | | * The output array, described above. |
845 | | * |
846 | | * Returns the number of entries in 'symout' that were filled. This is the |
847 | | * number of symbols that have nonzero frequency. |
848 | | */ |
849 | | static unsigned |
850 | | sort_symbols(unsigned num_syms, const u32 freqs[], u8 lens[], u32 symout[]) |
851 | 8.46k | { |
852 | 8.46k | unsigned sym; |
853 | 8.46k | unsigned i; |
854 | 8.46k | unsigned num_used_syms; |
855 | 8.46k | unsigned num_counters; |
856 | 8.46k | unsigned counters[GET_NUM_COUNTERS(DEFLATE_MAX_NUM_SYMS)]; |
857 | | |
858 | | /* |
859 | | * We use heapsort, but with an added optimization. Since often most |
860 | | * symbol frequencies are low, we first do a count sort using a limited |
861 | | * number of counters. High frequencies are counted in the last |
862 | | * counter, and only they will be sorted with heapsort. |
863 | | * |
864 | | * Note: with more symbols, it is generally beneficial to have more |
865 | | * counters. About 1 counter per symbol seems fastest. |
866 | | */ |
867 | | |
868 | 8.46k | num_counters = GET_NUM_COUNTERS(num_syms); |
869 | | |
870 | 8.46k | memset(counters, 0, num_counters * sizeof(counters[0])); |
871 | | |
872 | | /* Count the frequencies. */ |
873 | 1.10M | for (sym = 0; sym < num_syms; sym++) |
874 | 1.09M | counters[MIN(freqs[sym], num_counters - 1)]++; |
875 | | |
876 | | /* |
877 | | * Make the counters cumulative, ignoring the zero-th, which counted |
878 | | * symbols with zero frequency. As a side effect, this calculates the |
879 | | * number of symbols with nonzero frequency. |
880 | | */ |
881 | 8.46k | num_used_syms = 0; |
882 | 1.09M | for (i = 1; i < num_counters; i++) { |
883 | 1.08M | unsigned count = counters[i]; |
884 | | |
885 | 1.08M | counters[i] = num_used_syms; |
886 | 1.08M | num_used_syms += count; |
887 | 1.08M | } |
888 | | |
889 | | /* |
890 | | * Sort nonzero-frequency symbols using the counters. At the same time, |
891 | | * set the codeword lengths of zero-frequency symbols to 0. |
892 | | */ |
893 | 1.10M | for (sym = 0; sym < num_syms; sym++) { |
894 | 1.09M | u32 freq = freqs[sym]; |
895 | | |
896 | 1.09M | if (freq != 0) { |
897 | 766k | symout[counters[MIN(freq, num_counters - 1)]++] = |
898 | 766k | sym | (freq << NUM_SYMBOL_BITS); |
899 | 766k | } else { |
900 | 330k | lens[sym] = 0; |
901 | 330k | } |
902 | 1.09M | } |
903 | | |
904 | | /* Sort the symbols counted in the last counter. */ |
905 | 8.46k | heap_sort(symout + counters[num_counters - 2], |
906 | 8.46k | counters[num_counters - 1] - counters[num_counters - 2]); |
907 | | |
908 | 8.46k | return num_used_syms; |
909 | 8.46k | } |
910 | | |
911 | | /* |
912 | | * Build a Huffman tree. |
913 | | * |
914 | | * This is an optimized implementation that |
915 | | * (a) takes advantage of the frequencies being already sorted; |
916 | | * (b) only generates non-leaf nodes, since the non-leaf nodes of a Huffman |
917 | | * tree are sufficient to generate a canonical code; |
918 | | * (c) Only stores parent pointers, not child pointers; |
919 | | * (d) Produces the nodes in the same memory used for input frequency |
920 | | * information. |
921 | | * |
922 | | * Array 'A', which contains 'sym_count' entries, is used for both input and |
923 | | * output. For this function, 'sym_count' must be at least 2. |
924 | | * |
925 | | * For input, the array must contain the frequencies of the symbols, sorted in |
926 | | * increasing order. Specifically, each entry must contain a frequency left |
927 | | * shifted by NUM_SYMBOL_BITS bits. Any data in the low NUM_SYMBOL_BITS bits of |
928 | | * the entries will be ignored by this function. Although these bits will, in |
929 | | * fact, contain the symbols that correspond to the frequencies, this function |
930 | | * is concerned with frequencies only and keeps the symbols as-is. |
931 | | * |
932 | | * For output, this function will produce the non-leaf nodes of the Huffman |
933 | | * tree. These nodes will be stored in the first (sym_count - 1) entries of the |
934 | | * array. Entry A[sym_count - 2] will represent the root node. Each other node |
935 | | * will contain the zero-based index of its parent node in 'A', left shifted by |
936 | | * NUM_SYMBOL_BITS bits. The low NUM_SYMBOL_BITS bits of each entry in A will |
937 | | * be kept as-is. Again, note that although these low bits will, in fact, |
938 | | * contain a symbol value, this symbol will have *no relationship* with the |
939 | | * Huffman tree node that happens to occupy the same slot. This is because this |
940 | | * implementation only generates the non-leaf nodes of the tree. |
941 | | */ |
942 | | static void |
943 | | build_tree(u32 A[], unsigned sym_count) |
944 | 8.37k | { |
945 | 8.37k | const unsigned last_idx = sym_count - 1; |
946 | | |
947 | | /* Index of the next lowest frequency leaf that still needs a parent */ |
948 | 8.37k | unsigned i = 0; |
949 | | |
950 | | /* |
951 | | * Index of the next lowest frequency non-leaf that still needs a |
952 | | * parent, or 'e' if there is currently no such node |
953 | | */ |
954 | 8.37k | unsigned b = 0; |
955 | | |
956 | | /* Index of the next spot for a non-leaf (will overwrite a leaf) */ |
957 | 8.37k | unsigned e = 0; |
958 | | |
959 | 757k | do { |
960 | 757k | u32 new_freq; |
961 | | |
962 | | /* |
963 | | * Select the next two lowest frequency nodes among the leaves |
964 | | * A[i] and non-leaves A[b], and create a new node A[e] to be |
965 | | * their parent. Set the new node's frequency to the sum of the |
966 | | * frequencies of its two children. |
967 | | * |
968 | | * Usually the next two lowest frequency nodes are of the same |
969 | | * type (leaf or non-leaf), so check those cases first. |
970 | | */ |
971 | 757k | if (i + 1 <= last_idx && |
972 | 535k | (b == e || (A[i + 1] & FREQ_MASK) <= (A[b] & FREQ_MASK))) { |
973 | | /* Two leaves */ |
974 | 364k | new_freq = (A[i] & FREQ_MASK) + (A[i + 1] & FREQ_MASK); |
975 | 364k | i += 2; |
976 | 392k | } else if (b + 2 <= e && |
977 | 388k | (i > last_idx || |
978 | 356k | (A[b + 1] & FREQ_MASK) < (A[i] & FREQ_MASK))) { |
979 | | /* Two non-leaves */ |
980 | 356k | new_freq = (A[b] & FREQ_MASK) + (A[b + 1] & FREQ_MASK); |
981 | 356k | A[b] = (e << NUM_SYMBOL_BITS) | (A[b] & SYMBOL_MASK); |
982 | 356k | A[b + 1] = (e << NUM_SYMBOL_BITS) | |
983 | 356k | (A[b + 1] & SYMBOL_MASK); |
984 | 356k | b += 2; |
985 | 356k | } else { |
986 | | /* One leaf and one non-leaf */ |
987 | 36.5k | new_freq = (A[i] & FREQ_MASK) + (A[b] & FREQ_MASK); |
988 | 36.5k | A[b] = (e << NUM_SYMBOL_BITS) | (A[b] & SYMBOL_MASK); |
989 | 36.5k | i++; |
990 | 36.5k | b++; |
991 | 36.5k | } |
992 | 757k | A[e] = new_freq | (A[e] & SYMBOL_MASK); |
993 | | /* |
994 | | * A binary tree with 'n' leaves has 'n - 1' non-leaves, so the |
995 | | * tree is complete once we've created 'n - 1' non-leaves. |
996 | | */ |
997 | 757k | } while (++e < last_idx); |
998 | 8.37k | } |
999 | | |
1000 | | /* |
1001 | | * Given the stripped-down Huffman tree constructed by build_tree(), determine |
1002 | | * the number of codewords that should be assigned each possible length, taking |
1003 | | * into account the length-limited constraint. |
1004 | | * |
1005 | | * @A |
1006 | | * The array produced by build_tree(), containing parent index information |
1007 | | * for the non-leaf nodes of the Huffman tree. Each entry in this array is |
1008 | | * a node; a node's parent always has a greater index than that node |
1009 | | * itself. This function will overwrite the parent index information in |
1010 | | * this array, so essentially it will destroy the tree. However, the data |
1011 | | * in the low NUM_SYMBOL_BITS of each entry will be preserved. |
1012 | | * |
1013 | | * @root_idx |
1014 | | * The 0-based index of the root node in 'A', and consequently one less |
1015 | | * than the number of tree node entries in 'A'. (Or, really 2 less than |
1016 | | * the actual length of 'A'.) |
1017 | | * |
1018 | | * @len_counts |
1019 | | * An array of length ('max_codeword_len' + 1) in which the number of |
1020 | | * codewords having each length <= max_codeword_len will be returned. |
1021 | | * |
1022 | | * @max_codeword_len |
1023 | | * The maximum permissible codeword length. |
1024 | | */ |
1025 | | static void |
1026 | | compute_length_counts(u32 A[], unsigned root_idx, unsigned len_counts[], |
1027 | | unsigned max_codeword_len) |
1028 | 8.37k | { |
1029 | 8.37k | unsigned len; |
1030 | 8.37k | int node; |
1031 | | |
1032 | | /* |
1033 | | * The key observations are: |
1034 | | * |
1035 | | * (1) We can traverse the non-leaf nodes of the tree, always visiting a |
1036 | | * parent before its children, by simply iterating through the array |
1037 | | * in reverse order. Consequently, we can compute the depth of each |
1038 | | * node in one pass, overwriting the parent indices with depths. |
1039 | | * |
1040 | | * (2) We can initially assume that in the real Huffman tree, both |
1041 | | * children of the root are leaves. This corresponds to two |
1042 | | * codewords of length 1. Then, whenever we visit a (non-leaf) node |
1043 | | * during the traversal, we modify this assumption to account for |
1044 | | * the current node *not* being a leaf, but rather its two children |
1045 | | * being leaves. This causes the loss of one codeword for the |
1046 | | * current depth and the addition of two codewords for the current |
1047 | | * depth plus one. |
1048 | | * |
1049 | | * (3) We can handle the length-limited constraint fairly easily by |
1050 | | * simply using the largest length available when a depth exceeds |
1051 | | * max_codeword_len. |
1052 | | */ |
1053 | | |
1054 | 124k | for (len = 0; len <= max_codeword_len; len++) |
1055 | 116k | len_counts[len] = 0; |
1056 | 8.37k | len_counts[1] = 2; |
1057 | | |
1058 | | /* Set the root node's depth to 0. */ |
1059 | 8.37k | A[root_idx] &= SYMBOL_MASK; |
1060 | | |
1061 | 757k | for (node = root_idx - 1; node >= 0; node--) { |
1062 | | |
1063 | | /* Calculate the depth of this node. */ |
1064 | | |
1065 | 749k | unsigned parent = A[node] >> NUM_SYMBOL_BITS; |
1066 | 749k | unsigned parent_depth = A[parent] >> NUM_SYMBOL_BITS; |
1067 | 749k | unsigned depth = parent_depth + 1; |
1068 | | |
1069 | | /* |
1070 | | * Set the depth of this node so that it is available when its |
1071 | | * children (if any) are processed. |
1072 | | */ |
1073 | 749k | A[node] = (A[node] & SYMBOL_MASK) | (depth << NUM_SYMBOL_BITS); |
1074 | | |
1075 | | /* |
1076 | | * If needed, decrease the length to meet the length-limited |
1077 | | * constraint. This is not the optimal method for generating |
1078 | | * length-limited Huffman codes! But it should be good enough. |
1079 | | */ |
1080 | 749k | if (depth >= max_codeword_len) { |
1081 | 427 | depth = max_codeword_len; |
1082 | 535 | do { |
1083 | 535 | depth--; |
1084 | 535 | } while (len_counts[depth] == 0); |
1085 | 427 | } |
1086 | | |
1087 | | /* |
1088 | | * Account for the fact that we have a non-leaf node at the |
1089 | | * current depth. |
1090 | | */ |
1091 | 749k | len_counts[depth]--; |
1092 | 749k | len_counts[depth + 1] += 2; |
1093 | 749k | } |
1094 | 8.37k | } |
1095 | | |
1096 | | /* |
1097 | | * DEFLATE uses bit-reversed codewords, so we must bit-reverse the codewords |
1098 | | * after generating them. All codewords have length <= 16 bits. If the CPU has |
1099 | | * a bit-reversal instruction, then that is the fastest method. Otherwise the |
1100 | | * fastest method is to reverse the bits in each of the two bytes using a table. |
1101 | | * The table method is slightly faster than using bitwise operations to flip |
1102 | | * adjacent 1, 2, 4, and then 8-bit fields, even if 2 to 4 codewords are packed |
1103 | | * into a machine word and processed together using that method. |
1104 | | */ |
1105 | | |
1106 | | #ifdef rbit32 |
1107 | | static forceinline u32 reverse_codeword(u32 codeword, u8 len) |
1108 | | { |
1109 | | return rbit32(codeword) >> ((32 - len) & 31); |
1110 | | } |
1111 | | #else |
1112 | | /* Generated by scripts/gen_bitreverse_tab.py */ |
1113 | | static const u8 bitreverse_tab[256] = { |
1114 | | 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, |
1115 | | 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, |
1116 | | 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, |
1117 | | 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, |
1118 | | 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, |
1119 | | 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, |
1120 | | 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, |
1121 | | 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, |
1122 | | 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, |
1123 | | 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, |
1124 | | 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, |
1125 | | 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, |
1126 | | 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, |
1127 | | 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, |
1128 | | 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, |
1129 | | 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, |
1130 | | 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, |
1131 | | 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, |
1132 | | 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, |
1133 | | 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, |
1134 | | 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, |
1135 | | 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, |
1136 | | 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, |
1137 | | 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, |
1138 | | 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, |
1139 | | 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, |
1140 | | 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, |
1141 | | 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, |
1142 | | 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, |
1143 | | 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, |
1144 | | 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, |
1145 | | 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff, |
1146 | | }; |
1147 | | |
1148 | | static forceinline u32 reverse_codeword(u32 codeword, u8 len) |
1149 | 1.09M | { |
1150 | 1.09M | STATIC_ASSERT(DEFLATE_MAX_CODEWORD_LEN <= 16); |
1151 | 1.09M | codeword = ((u32)bitreverse_tab[codeword & 0xff] << 8) | |
1152 | 1.09M | bitreverse_tab[codeword >> 8]; |
1153 | 1.09M | return codeword >> (16 - len); |
1154 | 1.09M | } |
1155 | | #endif /* !rbit32 */ |
1156 | | |
1157 | | /* |
1158 | | * Generate the codewords for a canonical Huffman code. |
1159 | | * |
1160 | | * @A |
1161 | | * The output array for codewords. In addition, initially this |
1162 | | * array must contain the symbols, sorted primarily by frequency and |
1163 | | * secondarily by symbol value, in the low NUM_SYMBOL_BITS bits of |
1164 | | * each entry. |
1165 | | * |
1166 | | * @len |
1167 | | * Output array for codeword lengths. |
1168 | | * |
1169 | | * @len_counts |
1170 | | * An array that provides the number of codewords that will have |
1171 | | * each possible length <= max_codeword_len. |
1172 | | * |
1173 | | * @max_codeword_len |
1174 | | * Maximum length, in bits, of each codeword. |
1175 | | * |
1176 | | * @num_syms |
1177 | | * Number of symbols in the alphabet, including symbols with zero |
1178 | | * frequency. This is the length of the 'A' and 'len' arrays. |
1179 | | */ |
1180 | | static void |
1181 | | gen_codewords(u32 A[], u8 lens[], const unsigned len_counts[], |
1182 | | unsigned max_codeword_len, unsigned num_syms) |
1183 | 8.37k | { |
1184 | 8.37k | u32 next_codewords[DEFLATE_MAX_CODEWORD_LEN + 1]; |
1185 | 8.37k | unsigned i; |
1186 | 8.37k | unsigned len; |
1187 | 8.37k | unsigned sym; |
1188 | | |
1189 | | /* |
1190 | | * Given the number of codewords that will have each length, assign |
1191 | | * codeword lengths to symbols. We do this by assigning the lengths in |
1192 | | * decreasing order to the symbols sorted primarily by increasing |
1193 | | * frequency and secondarily by increasing symbol value. |
1194 | | */ |
1195 | 116k | for (i = 0, len = max_codeword_len; len >= 1; len--) { |
1196 | 107k | unsigned count = len_counts[len]; |
1197 | | |
1198 | 873k | while (count--) |
1199 | 766k | lens[A[i++] & SYMBOL_MASK] = len; |
1200 | 107k | } |
1201 | | |
1202 | | /* |
1203 | | * Generate the codewords themselves. We initialize the |
1204 | | * 'next_codewords' array to provide the lexicographically first |
1205 | | * codeword of each length, then assign codewords in symbol order. This |
1206 | | * produces a canonical code. |
1207 | | */ |
1208 | 8.37k | next_codewords[0] = 0; |
1209 | 8.37k | next_codewords[1] = 0; |
1210 | 107k | for (len = 2; len <= max_codeword_len; len++) |
1211 | 99.3k | next_codewords[len] = |
1212 | 99.3k | (next_codewords[len - 1] + len_counts[len - 1]) << 1; |
1213 | | |
1214 | 1.10M | for (sym = 0; sym < num_syms; sym++) { |
1215 | | /* DEFLATE requires bit-reversed codewords. */ |
1216 | 1.09M | A[sym] = reverse_codeword(next_codewords[lens[sym]]++, |
1217 | 1.09M | lens[sym]); |
1218 | 1.09M | } |
1219 | 8.37k | } |
1220 | | |
1221 | | /* |
1222 | | * --------------------------------------------------------------------- |
1223 | | * deflate_make_huffman_code() |
1224 | | * --------------------------------------------------------------------- |
1225 | | * |
1226 | | * Given an alphabet and the frequency of each symbol in it, construct a |
1227 | | * length-limited canonical Huffman code. |
1228 | | * |
1229 | | * @num_syms |
1230 | | * The number of symbols in the alphabet. The symbols are the integers in |
1231 | | * the range [0, num_syms - 1]. This parameter must be at least 2 and |
1232 | | * must not exceed (1 << NUM_SYMBOL_BITS). |
1233 | | * |
1234 | | * @max_codeword_len |
1235 | | * The maximum permissible codeword length. |
1236 | | * |
1237 | | * @freqs |
1238 | | * An array of length @num_syms that gives the frequency of each symbol. |
1239 | | * It is valid for some, none, or all of the frequencies to be 0. The sum |
1240 | | * of frequencies must not exceed (1 << NUM_FREQ_BITS) - 1. |
1241 | | * |
1242 | | * @lens |
1243 | | * An array of @num_syms entries in which this function will return the |
1244 | | * length, in bits, of the codeword assigned to each symbol. Symbols with |
1245 | | * 0 frequency will not have codewords per se, but their entries in this |
1246 | | * array will be set to 0. No lengths greater than @max_codeword_len will |
1247 | | * be assigned. |
1248 | | * |
1249 | | * @codewords |
1250 | | * An array of @num_syms entries in which this function will return the |
1251 | | * codeword for each symbol, right-justified and padded on the left with |
1252 | | * zeroes. Codewords for symbols with 0 frequency will be undefined. |
1253 | | * |
1254 | | * --------------------------------------------------------------------- |
1255 | | * |
1256 | | * This function builds a length-limited canonical Huffman code. |
1257 | | * |
1258 | | * A length-limited Huffman code contains no codewords longer than some |
1259 | | * specified length, and has exactly (with some algorithms) or approximately |
1260 | | * (with the algorithm used here) the minimum weighted path length from the |
1261 | | * root, given this constraint. |
1262 | | * |
1263 | | * A canonical Huffman code satisfies the properties that a longer codeword |
1264 | | * never lexicographically precedes a shorter codeword, and the lexicographic |
1265 | | * ordering of codewords of the same length is the same as the lexicographic |
1266 | | * ordering of the corresponding symbols. A canonical Huffman code, or more |
1267 | | * generally a canonical prefix code, can be reconstructed from only a list |
1268 | | * containing the codeword length of each symbol. |
1269 | | * |
1270 | | * The classic algorithm to generate a Huffman code creates a node for each |
1271 | | * symbol, then inserts these nodes into a min-heap keyed by symbol frequency. |
1272 | | * Then, repeatedly, the two lowest-frequency nodes are removed from the |
1273 | | * min-heap and added as the children of a new node having frequency equal to |
1274 | | * the sum of its two children, which is then inserted into the min-heap. When |
1275 | | * only a single node remains in the min-heap, it is the root of the Huffman |
1276 | | * tree. The codeword for each symbol is determined by the path needed to reach |
1277 | | * the corresponding node from the root. Descending to the left child appends a |
1278 | | * 0 bit, whereas descending to the right child appends a 1 bit. |
1279 | | * |
1280 | | * The classic algorithm is relatively easy to understand, but it is subject to |
1281 | | * a number of inefficiencies. In practice, it is fastest to first sort the |
1282 | | * symbols by frequency. (This itself can be subject to an optimization based |
1283 | | * on the fact that most frequencies tend to be low.) At the same time, we sort |
1284 | | * secondarily by symbol value, which aids the process of generating a canonical |
1285 | | * code. Then, during tree construction, no heap is necessary because both the |
1286 | | * leaf nodes and the unparented non-leaf nodes can be easily maintained in |
1287 | | * sorted order. Consequently, there can never be more than two possibilities |
1288 | | * for the next-lowest-frequency node. |
1289 | | * |
1290 | | * In addition, because we're generating a canonical code, we actually don't |
1291 | | * need the leaf nodes of the tree at all, only the non-leaf nodes. This is |
1292 | | * because for canonical code generation we don't need to know where the symbols |
1293 | | * are in the tree. Rather, we only need to know how many leaf nodes have each |
1294 | | * depth (codeword length). And this information can, in fact, be quickly |
1295 | | * generated from the tree of non-leaves only. |
1296 | | * |
1297 | | * Furthermore, we can build this stripped-down Huffman tree directly in the |
1298 | | * array in which the codewords are to be generated, provided that these array |
1299 | | * slots are large enough to hold a symbol and frequency value. |
1300 | | * |
1301 | | * Still furthermore, we don't even need to maintain explicit child pointers. |
1302 | | * We only need the parent pointers, and even those can be overwritten in-place |
1303 | | * with depth information as part of the process of extracting codeword lengths |
1304 | | * from the tree. So in summary, we do NOT need a big structure like: |
1305 | | * |
1306 | | * struct huffman_tree_node { |
1307 | | * unsigned int symbol; |
1308 | | * unsigned int frequency; |
1309 | | * unsigned int depth; |
1310 | | * struct huffman_tree_node *left_child; |
1311 | | * struct huffman_tree_node *right_child; |
1312 | | * }; |
1313 | | * |
1314 | | * |
1315 | | * ... which often gets used in "naive" implementations of Huffman code |
1316 | | * generation. |
1317 | | * |
1318 | | * Many of these optimizations are based on the implementation in 7-Zip (source |
1319 | | * file: C/HuffEnc.c), which was placed in the public domain by Igor Pavlov. |
1320 | | */ |
1321 | | static void |
1322 | | deflate_make_huffman_code(unsigned num_syms, unsigned max_codeword_len, |
1323 | | const u32 freqs[], u8 lens[], u32 codewords[]) |
1324 | 8.46k | { |
1325 | 8.46k | u32 *A = codewords; |
1326 | 8.46k | unsigned num_used_syms; |
1327 | | |
1328 | 8.46k | STATIC_ASSERT(DEFLATE_MAX_NUM_SYMS <= 1 << NUM_SYMBOL_BITS); |
1329 | 8.46k | STATIC_ASSERT(MAX_BLOCK_LENGTH <= ((u32)1 << NUM_FREQ_BITS) - 1); |
1330 | | |
1331 | | /* |
1332 | | * We begin by sorting the symbols primarily by frequency and |
1333 | | * secondarily by symbol value. As an optimization, the array used for |
1334 | | * this purpose ('A') shares storage with the space in which we will |
1335 | | * eventually return the codewords. |
1336 | | */ |
1337 | 8.46k | num_used_syms = sort_symbols(num_syms, freqs, lens, A); |
1338 | | /* |
1339 | | * 'num_used_syms' is the number of symbols with nonzero frequency. |
1340 | | * This may be less than @num_syms. 'num_used_syms' is also the number |
1341 | | * of entries in 'A' that are valid. Each entry consists of a distinct |
1342 | | * symbol and a nonzero frequency packed into a 32-bit integer. |
1343 | | */ |
1344 | | |
1345 | | /* |
1346 | | * A complete Huffman code must contain at least 2 codewords. Yet, it's |
1347 | | * possible that fewer than 2 symbols were used. When this happens, |
1348 | | * it's usually for the offset code (0-1 symbols used). But it's also |
1349 | | * theoretically possible for the litlen and pre codes (1 symbol used). |
1350 | | * |
1351 | | * The DEFLATE RFC explicitly allows the offset code to contain just 1 |
1352 | | * codeword, or even be completely empty. But it's silent about the |
1353 | | * other codes. It also doesn't say whether, in the 1-codeword case, |
1354 | | * the codeword (which it says must be 1 bit) is '0' or '1'. |
1355 | | * |
1356 | | * In any case, some DEFLATE decompressors reject these cases. zlib |
1357 | | * generally allows them, but it does reject precodes that have just 1 |
1358 | | * codeword. More problematically, zlib v1.2.1 and earlier rejected |
1359 | | * empty offset codes, and this behavior can also be seen in Windows |
1360 | | * Explorer's ZIP unpacker (supposedly even still in Windows 11). |
1361 | | * |
1362 | | * Other DEFLATE compressors, including zlib, always send at least 2 |
1363 | | * codewords in order to make a complete Huffman code. Therefore, this |
1364 | | * is a case where practice does not entirely match the specification. |
1365 | | * We follow practice by generating 2 codewords of length 1: codeword |
1366 | | * '0' for symbol 0, and codeword '1' for another symbol -- the used |
1367 | | * symbol if it exists and is not symbol 0, otherwise symbol 1. This |
1368 | | * does worsen the compression ratio by having to send an unnecessary |
1369 | | * offset codeword length. But this only affects rare cases such as |
1370 | | * blocks containing all literals, and it only makes a tiny difference. |
1371 | | */ |
1372 | 8.46k | if (unlikely(num_used_syms < 2)) { |
1373 | 93 | unsigned sym = num_used_syms ? (A[0] & SYMBOL_MASK) : 0; |
1374 | 93 | unsigned nonzero_idx = sym ? sym : 1; |
1375 | | |
1376 | 93 | codewords[0] = 0; |
1377 | 93 | lens[0] = 1; |
1378 | 93 | codewords[nonzero_idx] = 1; |
1379 | 93 | lens[nonzero_idx] = 1; |
1380 | 93 | return; |
1381 | 93 | } |
1382 | | |
1383 | | /* |
1384 | | * Build a stripped-down version of the Huffman tree, sharing the array |
1385 | | * 'A' with the symbol values. Then extract length counts from the tree |
1386 | | * and use them to generate the final codewords. |
1387 | | */ |
1388 | | |
1389 | 8.37k | build_tree(A, num_used_syms); |
1390 | | |
1391 | 8.37k | { |
1392 | 8.37k | unsigned len_counts[DEFLATE_MAX_CODEWORD_LEN + 1]; |
1393 | | |
1394 | 8.37k | compute_length_counts(A, num_used_syms - 2, |
1395 | 8.37k | len_counts, max_codeword_len); |
1396 | | |
1397 | 8.37k | gen_codewords(A, lens, len_counts, max_codeword_len, num_syms); |
1398 | 8.37k | } |
1399 | 8.37k | } |
1400 | | |
1401 | | /* |
1402 | | * Clear the Huffman symbol frequency counters. This must be called when |
1403 | | * starting a new DEFLATE block. |
1404 | | */ |
1405 | | static void |
1406 | | deflate_reset_symbol_frequencies(struct libdeflate_compressor *c) |
1407 | 1.82k | { |
1408 | 1.82k | memset(&c->freqs, 0, sizeof(c->freqs)); |
1409 | 1.82k | } |
1410 | | |
1411 | | /* |
1412 | | * Build the literal/length and offset Huffman codes for a DEFLATE block. |
1413 | | * |
1414 | | * This takes as input the frequency tables for each alphabet and produces as |
1415 | | * output a set of tables that map symbols to codewords and codeword lengths. |
1416 | | */ |
1417 | | static void |
1418 | | deflate_make_huffman_codes(const struct deflate_freqs *freqs, |
1419 | | struct deflate_codes *codes) |
1420 | 3.32k | { |
1421 | 3.32k | deflate_make_huffman_code(DEFLATE_NUM_LITLEN_SYMS, |
1422 | 3.32k | MAX_LITLEN_CODEWORD_LEN, |
1423 | 3.32k | freqs->litlen, |
1424 | 3.32k | codes->lens.litlen, |
1425 | 3.32k | codes->codewords.litlen); |
1426 | | |
1427 | 3.32k | deflate_make_huffman_code(DEFLATE_NUM_OFFSET_SYMS, |
1428 | 3.32k | MAX_OFFSET_CODEWORD_LEN, |
1429 | 3.32k | freqs->offset, |
1430 | 3.32k | codes->lens.offset, |
1431 | 3.32k | codes->codewords.offset); |
1432 | 3.32k | } |
1433 | | |
1434 | | /* Initialize c->static_codes. */ |
1435 | | static void |
1436 | | deflate_init_static_codes(struct libdeflate_compressor *c) |
1437 | 1.49k | { |
1438 | 1.49k | unsigned i; |
1439 | | |
1440 | 216k | for (i = 0; i < 144; i++) |
1441 | 214k | c->freqs.litlen[i] = 1 << (9 - 8); |
1442 | 168k | for (; i < 256; i++) |
1443 | 167k | c->freqs.litlen[i] = 1 << (9 - 9); |
1444 | 37.3k | for (; i < 280; i++) |
1445 | 35.8k | c->freqs.litlen[i] = 1 << (9 - 7); |
1446 | 13.4k | for (; i < 288; i++) |
1447 | 11.9k | c->freqs.litlen[i] = 1 << (9 - 8); |
1448 | | |
1449 | 49.2k | for (i = 0; i < 32; i++) |
1450 | 47.7k | c->freqs.offset[i] = 1 << (5 - 5); |
1451 | | |
1452 | 1.49k | deflate_make_huffman_codes(&c->freqs, &c->static_codes); |
1453 | 1.49k | } |
1454 | | |
1455 | | /* Return the offset slot for the given match offset, using the small map. */ |
1456 | | static forceinline unsigned |
1457 | | deflate_get_offset_slot(u32 offset) |
1458 | 312k | { |
1459 | | /* |
1460 | | * 1 <= offset <= 32768 here. For 1 <= offset <= 256, |
1461 | | * deflate_offset_slot[offset - 1] gives the slot. |
1462 | | * |
1463 | | * For 257 <= offset <= 32768, we take advantage of the fact that 257 is |
1464 | | * the beginning of slot 16, and each slot [16..30) is exactly 1 << 7 == |
1465 | | * 128 times larger than each slot [2..16) (since the number of extra |
1466 | | * bits increases by 1 every 2 slots). Thus, the slot is: |
1467 | | * |
1468 | | * deflate_offset_slot[2 + ((offset - 257) >> 7)] + (16 - 2) |
1469 | | * == deflate_offset_slot[((offset - 1) >> 7)] + 14 |
1470 | | * |
1471 | | * Define 'n = (offset <= 256) ? 0 : 7'. Then any offset is handled by: |
1472 | | * |
1473 | | * deflate_offset_slot[(offset - 1) >> n] + (n << 1) |
1474 | | * |
1475 | | * For better performance, replace 'n = (offset <= 256) ? 0 : 7' with |
1476 | | * the equivalent (for offset <= 536871168) 'n = (256 - offset) >> 29'. |
1477 | | */ |
1478 | 312k | unsigned n = (256 - offset) >> 29; |
1479 | | |
1480 | 312k | ASSERT(offset >= 1 && offset <= 32768); |
1481 | | |
1482 | 312k | return deflate_offset_slot[(offset - 1) >> n] + (n << 1); |
1483 | 312k | } |
1484 | | |
1485 | | static unsigned |
1486 | | deflate_compute_precode_items(const u8 lens[], const unsigned num_lens, |
1487 | | u32 precode_freqs[], unsigned precode_items[]) |
1488 | 1.82k | { |
1489 | 1.82k | unsigned *itemptr; |
1490 | 1.82k | unsigned run_start; |
1491 | 1.82k | unsigned run_end; |
1492 | 1.82k | unsigned extra_bits; |
1493 | 1.82k | u8 len; |
1494 | | |
1495 | 1.82k | memset(precode_freqs, 0, |
1496 | 1.82k | DEFLATE_NUM_PRECODE_SYMS * sizeof(precode_freqs[0])); |
1497 | | |
1498 | 1.82k | itemptr = precode_items; |
1499 | 1.82k | run_start = 0; |
1500 | 249k | do { |
1501 | | /* Find the next run of codeword lengths. */ |
1502 | | |
1503 | | /* len = the length being repeated */ |
1504 | 249k | len = lens[run_start]; |
1505 | | |
1506 | | /* Extend the run. */ |
1507 | 249k | run_end = run_start; |
1508 | 552k | do { |
1509 | 552k | run_end++; |
1510 | 552k | } while (run_end != num_lens && len == lens[run_end]); |
1511 | | |
1512 | 249k | if (len == 0) { |
1513 | | /* Run of zeroes. */ |
1514 | | |
1515 | | /* Symbol 18: RLE 11 to 138 zeroes at a time. */ |
1516 | 65.2k | while ((run_end - run_start) >= 11) { |
1517 | 4.23k | extra_bits = MIN((run_end - run_start) - 11, |
1518 | 4.23k | 0x7F); |
1519 | 4.23k | precode_freqs[18]++; |
1520 | 4.23k | *itemptr++ = 18 | (extra_bits << 5); |
1521 | 4.23k | run_start += 11 + extra_bits; |
1522 | 4.23k | } |
1523 | | |
1524 | | /* Symbol 17: RLE 3 to 10 zeroes at a time. */ |
1525 | 60.9k | if ((run_end - run_start) >= 3) { |
1526 | 18.3k | extra_bits = MIN((run_end - run_start) - 3, |
1527 | 18.3k | 0x7); |
1528 | 18.3k | precode_freqs[17]++; |
1529 | 18.3k | *itemptr++ = 17 | (extra_bits << 5); |
1530 | 18.3k | run_start += 3 + extra_bits; |
1531 | 18.3k | } |
1532 | 188k | } else { |
1533 | | |
1534 | | /* A run of nonzero lengths. */ |
1535 | | |
1536 | | /* Symbol 16: RLE 3 to 6 of the previous length. */ |
1537 | 188k | if ((run_end - run_start) >= 4) { |
1538 | 6.97k | precode_freqs[len]++; |
1539 | 6.97k | *itemptr++ = len; |
1540 | 6.97k | run_start++; |
1541 | 7.85k | do { |
1542 | 7.85k | extra_bits = MIN((run_end - run_start) - |
1543 | 7.85k | 3, 0x3); |
1544 | 7.85k | precode_freqs[16]++; |
1545 | 7.85k | *itemptr++ = 16 | (extra_bits << 5); |
1546 | 7.85k | run_start += 3 + extra_bits; |
1547 | 7.85k | } while ((run_end - run_start) >= 3); |
1548 | 6.97k | } |
1549 | 188k | } |
1550 | | |
1551 | | /* Output any remaining lengths without RLE. */ |
1552 | 529k | while (run_start != run_end) { |
1553 | 279k | precode_freqs[len]++; |
1554 | 279k | *itemptr++ = len; |
1555 | 279k | run_start++; |
1556 | 279k | } |
1557 | 249k | } while (run_start != num_lens); |
1558 | | |
1559 | 1.82k | return itemptr - precode_items; |
1560 | 1.82k | } |
1561 | | |
1562 | | /* |
1563 | | * Huffman codeword lengths for dynamic Huffman blocks are compressed using a |
1564 | | * separate Huffman code, the "precode", which contains a symbol for each |
1565 | | * possible codeword length in the larger code as well as several special |
1566 | | * symbols to represent repeated codeword lengths (a form of run-length |
1567 | | * encoding). The precode is itself constructed in canonical form, and its |
1568 | | * codeword lengths are represented literally in 19 3-bit fields that |
1569 | | * immediately precede the compressed codeword lengths of the larger code. |
1570 | | */ |
1571 | | |
1572 | | /* Precompute the information needed to output dynamic Huffman codes. */ |
1573 | | static void |
1574 | | deflate_precompute_huffman_header(struct libdeflate_compressor *c) |
1575 | 1.82k | { |
1576 | | /* Compute how many litlen and offset symbols are needed. */ |
1577 | | |
1578 | 1.82k | for (c->o.precode.num_litlen_syms = DEFLATE_NUM_LITLEN_SYMS; |
1579 | 11.9k | c->o.precode.num_litlen_syms > 257; |
1580 | 10.0k | c->o.precode.num_litlen_syms--) |
1581 | 11.9k | if (c->codes.lens.litlen[c->o.precode.num_litlen_syms - 1] != 0) |
1582 | 1.82k | break; |
1583 | | |
1584 | 1.82k | for (c->o.precode.num_offset_syms = DEFLATE_NUM_OFFSET_SYMS; |
1585 | 24.0k | c->o.precode.num_offset_syms > 1; |
1586 | 22.2k | c->o.precode.num_offset_syms--) |
1587 | 24.0k | if (c->codes.lens.offset[c->o.precode.num_offset_syms - 1] != 0) |
1588 | 1.82k | break; |
1589 | | |
1590 | | /* |
1591 | | * If we're not using the full set of literal/length codeword lengths, |
1592 | | * then temporarily move the offset codeword lengths over so that the |
1593 | | * literal/length and offset codeword lengths are contiguous. |
1594 | | */ |
1595 | 1.82k | STATIC_ASSERT(offsetof(struct deflate_lens, offset) == |
1596 | 1.82k | DEFLATE_NUM_LITLEN_SYMS); |
1597 | 1.82k | if (c->o.precode.num_litlen_syms != DEFLATE_NUM_LITLEN_SYMS) { |
1598 | 1.82k | memmove((u8 *)&c->codes.lens + c->o.precode.num_litlen_syms, |
1599 | 1.82k | (u8 *)&c->codes.lens + DEFLATE_NUM_LITLEN_SYMS, |
1600 | 1.82k | c->o.precode.num_offset_syms); |
1601 | 1.82k | } |
1602 | | |
1603 | | /* |
1604 | | * Compute the "items" (RLE / literal tokens and extra bits) with which |
1605 | | * the codeword lengths in the larger code will be output. |
1606 | | */ |
1607 | 1.82k | c->o.precode.num_items = |
1608 | 1.82k | deflate_compute_precode_items((u8 *)&c->codes.lens, |
1609 | 1.82k | c->o.precode.num_litlen_syms + |
1610 | 1.82k | c->o.precode.num_offset_syms, |
1611 | 1.82k | c->o.precode.freqs, |
1612 | 1.82k | c->o.precode.items); |
1613 | | |
1614 | | /* Build the precode. */ |
1615 | 1.82k | deflate_make_huffman_code(DEFLATE_NUM_PRECODE_SYMS, |
1616 | 1.82k | MAX_PRE_CODEWORD_LEN, |
1617 | 1.82k | c->o.precode.freqs, c->o.precode.lens, |
1618 | 1.82k | c->o.precode.codewords); |
1619 | | |
1620 | | /* Count how many precode lengths we actually need to output. */ |
1621 | 1.82k | for (c->o.precode.num_explicit_lens = DEFLATE_NUM_PRECODE_SYMS; |
1622 | 6.92k | c->o.precode.num_explicit_lens > 4; |
1623 | 5.09k | c->o.precode.num_explicit_lens--) |
1624 | 6.92k | if (c->o.precode.lens[deflate_precode_lens_permutation[ |
1625 | 6.92k | c->o.precode.num_explicit_lens - 1]] != 0) |
1626 | 1.82k | break; |
1627 | | |
1628 | | /* Restore the offset codeword lengths if needed. */ |
1629 | 1.82k | if (c->o.precode.num_litlen_syms != DEFLATE_NUM_LITLEN_SYMS) { |
1630 | 1.82k | memmove((u8 *)&c->codes.lens + DEFLATE_NUM_LITLEN_SYMS, |
1631 | 1.82k | (u8 *)&c->codes.lens + c->o.precode.num_litlen_syms, |
1632 | 1.82k | c->o.precode.num_offset_syms); |
1633 | 1.82k | } |
1634 | 1.82k | } |
1635 | | |
1636 | | /* |
1637 | | * To make it faster to output matches, compute the "full" match length |
1638 | | * codewords, i.e. the concatenation of the litlen codeword and the extra bits |
1639 | | * for each possible match length. |
1640 | | */ |
1641 | | static void |
1642 | | deflate_compute_full_len_codewords(struct libdeflate_compressor *c, |
1643 | | const struct deflate_codes *codes) |
1644 | 1.82k | { |
1645 | 1.82k | u32 len; |
1646 | | |
1647 | 1.82k | STATIC_ASSERT(MAX_LITLEN_CODEWORD_LEN + |
1648 | 1.82k | DEFLATE_MAX_EXTRA_LENGTH_BITS <= 32); |
1649 | | |
1650 | 469k | for (len = DEFLATE_MIN_MATCH_LEN; len <= DEFLATE_MAX_MATCH_LEN; len++) { |
1651 | 467k | unsigned slot = deflate_length_slot[len]; |
1652 | 467k | unsigned litlen_sym = DEFLATE_FIRST_LEN_SYM + slot; |
1653 | 467k | u32 extra_bits = len - deflate_length_slot_base[slot]; |
1654 | | |
1655 | 467k | c->o.length.codewords[len] = |
1656 | 467k | codes->codewords.litlen[litlen_sym] | |
1657 | 467k | (extra_bits << codes->lens.litlen[litlen_sym]); |
1658 | 467k | c->o.length.lens[len] = codes->lens.litlen[litlen_sym] + |
1659 | 467k | deflate_extra_length_bits[slot]; |
1660 | 467k | } |
1661 | 1.82k | } |
1662 | | |
1663 | | /* Write a match to the output buffer. */ |
1664 | 312k | #define WRITE_MATCH(c_, codes_, length_, offset_, offset_slot_) \ |
1665 | 312k | do { \ |
1666 | 312k | const struct libdeflate_compressor *c__ = (c_); \ |
1667 | 312k | const struct deflate_codes *codes__ = (codes_); \ |
1668 | 312k | u32 length__ = (length_); \ |
1669 | 312k | u32 offset__ = (offset_); \ |
1670 | 312k | unsigned offset_slot__ = (offset_slot_); \ |
1671 | 312k | \ |
1672 | 312k | /* Litlen symbol and extra length bits */ \ |
1673 | 312k | STATIC_ASSERT(CAN_BUFFER(MAX_LITLEN_CODEWORD_LEN + \ |
1674 | 312k | DEFLATE_MAX_EXTRA_LENGTH_BITS)); \ |
1675 | 312k | ADD_BITS(c__->o.length.codewords[length__], \ |
1676 | 312k | c__->o.length.lens[length__]); \ |
1677 | 312k | \ |
1678 | 312k | if (!CAN_BUFFER(MAX_LITLEN_CODEWORD_LEN + \ |
1679 | 312k | DEFLATE_MAX_EXTRA_LENGTH_BITS + \ |
1680 | 312k | MAX_OFFSET_CODEWORD_LEN + \ |
1681 | 312k | DEFLATE_MAX_EXTRA_OFFSET_BITS)) \ |
1682 | 312k | FLUSH_BITS(); \ |
1683 | 312k | \ |
1684 | 312k | /* Offset symbol */ \ |
1685 | 312k | ADD_BITS(codes__->codewords.offset[offset_slot__], \ |
1686 | 312k | codes__->lens.offset[offset_slot__]); \ |
1687 | 312k | \ |
1688 | 312k | if (!CAN_BUFFER(MAX_OFFSET_CODEWORD_LEN + \ |
1689 | 312k | DEFLATE_MAX_EXTRA_OFFSET_BITS)) \ |
1690 | 312k | FLUSH_BITS(); \ |
1691 | 312k | \ |
1692 | 312k | /* Extra offset bits */ \ |
1693 | 312k | ADD_BITS(offset__ - deflate_offset_slot_base[offset_slot__], \ |
1694 | 312k | deflate_extra_offset_bits[offset_slot__]); \ |
1695 | 312k | \ |
1696 | 312k | FLUSH_BITS(); \ |
1697 | 312k | } while (0) |
1698 | | |
1699 | | /* |
1700 | | * Choose the best type of block to use (dynamic Huffman, static Huffman, or |
1701 | | * uncompressed), then output it. |
1702 | | * |
1703 | | * The uncompressed data of the block is @block_begin[0..@block_length-1]. The |
1704 | | * sequence of literals and matches that will be used to compress the block (if |
1705 | | * a compressed block is chosen) is given by @sequences if it's non-NULL, or |
1706 | | * else @c->p.n.optimum_nodes. @c->freqs and @c->codes must be already set |
1707 | | * according to the literals, matches, and end-of-block symbol. |
1708 | | */ |
1709 | | static void |
1710 | | deflate_flush_block(struct libdeflate_compressor *c, |
1711 | | struct deflate_output_bitstream *os, |
1712 | | const u8 *block_begin, u32 block_length, |
1713 | | const struct deflate_sequence *sequences, |
1714 | | bool is_final_block) |
1715 | 1.82k | { |
1716 | | /* |
1717 | | * It is hard to get compilers to understand that writes to 'os->next' |
1718 | | * don't alias 'os'. That hurts performance significantly, as |
1719 | | * everything in 'os' would keep getting re-loaded. ('restrict' |
1720 | | * *should* do the trick, but it's unreliable.) Therefore, we keep all |
1721 | | * the output bitstream state in local variables, and output bits using |
1722 | | * macros. This is similar to what the decompressor does. |
1723 | | */ |
1724 | 1.82k | const u8 *in_next = block_begin; |
1725 | 1.82k | const u8 * const in_end = block_begin + block_length; |
1726 | 1.82k | bitbuf_t bitbuf = os->bitbuf; |
1727 | 1.82k | unsigned bitcount = os->bitcount; |
1728 | 1.82k | u8 *out_next = os->next; |
1729 | 1.82k | u8 * const out_fast_end = |
1730 | 1.82k | os->end - MIN(WORDBYTES - 1, os->end - out_next); |
1731 | | /* |
1732 | | * The cost for each block type, in bits. Start with the cost of the |
1733 | | * block header which is 3 bits. |
1734 | | */ |
1735 | 1.82k | u32 dynamic_cost = 3; |
1736 | 1.82k | u32 static_cost = 3; |
1737 | 1.82k | u32 uncompressed_cost = 3; |
1738 | 1.82k | u32 best_cost; |
1739 | 1.82k | struct deflate_codes *codes; |
1740 | 1.82k | unsigned sym; |
1741 | | |
1742 | 1.82k | ASSERT(block_length >= MIN_BLOCK_LENGTH || |
1743 | 1.82k | (is_final_block && block_length > 0)); |
1744 | 1.82k | ASSERT(block_length <= MAX_BLOCK_LENGTH); |
1745 | 1.82k | ASSERT(bitcount <= 7); |
1746 | 1.82k | ASSERT((bitbuf & ~(((bitbuf_t)1 << bitcount) - 1)) == 0); |
1747 | 1.82k | ASSERT(out_next <= os->end); |
1748 | 1.82k | ASSERT(!os->overflow); |
1749 | | |
1750 | | /* Precompute the precode items and build the precode. */ |
1751 | 1.82k | deflate_precompute_huffman_header(c); |
1752 | | |
1753 | | /* Account for the cost of encoding dynamic Huffman codes. */ |
1754 | 1.82k | dynamic_cost += 5 + 5 + 4 + (3 * c->o.precode.num_explicit_lens); |
1755 | 36.5k | for (sym = 0; sym < DEFLATE_NUM_PRECODE_SYMS; sym++) { |
1756 | 34.7k | u32 extra = deflate_extra_precode_bits[sym]; |
1757 | | |
1758 | 34.7k | dynamic_cost += c->o.precode.freqs[sym] * |
1759 | 34.7k | (extra + c->o.precode.lens[sym]); |
1760 | 34.7k | } |
1761 | | |
1762 | | /* Account for the cost of encoding literals. */ |
1763 | 264k | for (sym = 0; sym < 144; sym++) { |
1764 | 263k | dynamic_cost += c->freqs.litlen[sym] * |
1765 | 263k | c->codes.lens.litlen[sym]; |
1766 | 263k | static_cost += c->freqs.litlen[sym] * 8; |
1767 | 263k | } |
1768 | 206k | for (; sym < 256; sym++) { |
1769 | 204k | dynamic_cost += c->freqs.litlen[sym] * |
1770 | 204k | c->codes.lens.litlen[sym]; |
1771 | 204k | static_cost += c->freqs.litlen[sym] * 9; |
1772 | 204k | } |
1773 | | |
1774 | | /* Account for the cost of encoding the end-of-block symbol. */ |
1775 | 1.82k | dynamic_cost += c->codes.lens.litlen[DEFLATE_END_OF_BLOCK]; |
1776 | 1.82k | static_cost += 7; |
1777 | | |
1778 | | /* Account for the cost of encoding lengths. */ |
1779 | 1.82k | for (sym = DEFLATE_FIRST_LEN_SYM; |
1780 | 54.8k | sym < DEFLATE_FIRST_LEN_SYM + ARRAY_LEN(deflate_extra_length_bits); |
1781 | 52.9k | sym++) { |
1782 | 52.9k | u32 extra = deflate_extra_length_bits[ |
1783 | 52.9k | sym - DEFLATE_FIRST_LEN_SYM]; |
1784 | | |
1785 | 52.9k | dynamic_cost += c->freqs.litlen[sym] * |
1786 | 52.9k | (extra + c->codes.lens.litlen[sym]); |
1787 | 52.9k | static_cost += c->freqs.litlen[sym] * |
1788 | 52.9k | (extra + c->static_codes.lens.litlen[sym]); |
1789 | 52.9k | } |
1790 | | |
1791 | | /* Account for the cost of encoding offsets. */ |
1792 | 56.6k | for (sym = 0; sym < ARRAY_LEN(deflate_extra_offset_bits); sym++) { |
1793 | 54.8k | u32 extra = deflate_extra_offset_bits[sym]; |
1794 | | |
1795 | 54.8k | dynamic_cost += c->freqs.offset[sym] * |
1796 | 54.8k | (extra + c->codes.lens.offset[sym]); |
1797 | 54.8k | static_cost += c->freqs.offset[sym] * (extra + 5); |
1798 | 54.8k | } |
1799 | | |
1800 | | /* Compute the cost of using uncompressed blocks. */ |
1801 | 1.82k | uncompressed_cost += (-(bitcount + 3) & 7) + 32 + |
1802 | 1.82k | (40 * (DIV_ROUND_UP(block_length, |
1803 | 1.82k | UINT16_MAX) - 1)) + |
1804 | 1.82k | (8 * block_length); |
1805 | | |
1806 | | /* |
1807 | | * Choose and output the cheapest type of block. If there is a tie, |
1808 | | * prefer uncompressed, then static, then dynamic. |
1809 | | */ |
1810 | | |
1811 | 1.82k | best_cost = MIN(dynamic_cost, MIN(static_cost, uncompressed_cost)); |
1812 | | |
1813 | | /* If the block isn't going to fit, then stop early. */ |
1814 | 1.82k | if (DIV_ROUND_UP(bitcount + best_cost, 8) > os->end - out_next) { |
1815 | 0 | os->overflow = true; |
1816 | 0 | return; |
1817 | 0 | } |
1818 | | /* |
1819 | | * Else, now we know that the block fits, so no further bounds checks on |
1820 | | * the output buffer are required until the next block. |
1821 | | */ |
1822 | | |
1823 | 1.82k | if (best_cost == uncompressed_cost) { |
1824 | | /* |
1825 | | * Uncompressed block(s). DEFLATE limits the length of |
1826 | | * uncompressed blocks to UINT16_MAX bytes, so if the length of |
1827 | | * the "block" we're flushing is over UINT16_MAX, we actually |
1828 | | * output multiple blocks. |
1829 | | */ |
1830 | 2 | do { |
1831 | 2 | u8 bfinal = 0; |
1832 | 2 | size_t len = UINT16_MAX; |
1833 | | |
1834 | 2 | if (in_end - in_next <= UINT16_MAX) { |
1835 | 2 | bfinal = is_final_block; |
1836 | 2 | len = in_end - in_next; |
1837 | 2 | } |
1838 | | /* It was already checked that there is enough space. */ |
1839 | 2 | ASSERT(os->end - out_next >= |
1840 | 2 | DIV_ROUND_UP(bitcount + 3, 8) + 4 + len); |
1841 | | /* |
1842 | | * Output BFINAL (1 bit) and BTYPE (2 bits), then align |
1843 | | * to a byte boundary. |
1844 | | */ |
1845 | 2 | STATIC_ASSERT(DEFLATE_BLOCKTYPE_UNCOMPRESSED == 0); |
1846 | 2 | *out_next++ = (bfinal << bitcount) | bitbuf; |
1847 | 2 | if (bitcount > 5) |
1848 | 0 | *out_next++ = 0; |
1849 | 2 | bitbuf = 0; |
1850 | 2 | bitcount = 0; |
1851 | | /* Output LEN and NLEN, then the data itself. */ |
1852 | 2 | put_unaligned_le16(len, out_next); |
1853 | 2 | out_next += 2; |
1854 | 2 | put_unaligned_le16(~len, out_next); |
1855 | 2 | out_next += 2; |
1856 | 2 | memcpy(out_next, in_next, len); |
1857 | 2 | out_next += len; |
1858 | 2 | in_next += len; |
1859 | 2 | } while (in_next != in_end); |
1860 | | /* Done outputting uncompressed block(s) */ |
1861 | 2 | goto out; |
1862 | 2 | } |
1863 | | |
1864 | 1.82k | if (best_cost == static_cost) { |
1865 | | /* Static Huffman block */ |
1866 | 555 | codes = &c->static_codes; |
1867 | 555 | ADD_BITS(is_final_block, 1); |
1868 | 555 | ADD_BITS(DEFLATE_BLOCKTYPE_STATIC_HUFFMAN, 2); |
1869 | 555 | FLUSH_BITS(); |
1870 | 1.27k | } else { |
1871 | 1.27k | const unsigned num_explicit_lens = c->o.precode.num_explicit_lens; |
1872 | 1.27k | const unsigned num_precode_items = c->o.precode.num_items; |
1873 | 1.27k | unsigned precode_sym, precode_item; |
1874 | 1.27k | unsigned i; |
1875 | | |
1876 | | /* Dynamic Huffman block */ |
1877 | | |
1878 | 1.27k | codes = &c->codes; |
1879 | 1.27k | STATIC_ASSERT(CAN_BUFFER(1 + 2 + 5 + 5 + 4 + 3)); |
1880 | 1.27k | ADD_BITS(is_final_block, 1); |
1881 | 1.27k | ADD_BITS(DEFLATE_BLOCKTYPE_DYNAMIC_HUFFMAN, 2); |
1882 | 1.27k | ADD_BITS(c->o.precode.num_litlen_syms - 257, 5); |
1883 | 1.27k | ADD_BITS(c->o.precode.num_offset_syms - 1, 5); |
1884 | 1.27k | ADD_BITS(num_explicit_lens - 4, 4); |
1885 | | |
1886 | | /* Output the lengths of the codewords in the precode. */ |
1887 | 1.27k | if (CAN_BUFFER(3 * (DEFLATE_NUM_PRECODE_SYMS - 1))) { |
1888 | | /* |
1889 | | * A 64-bit bitbuffer is just one bit too small to hold |
1890 | | * the maximum number of precode lens, so to minimize |
1891 | | * flushes we merge one len with the previous fields. |
1892 | | */ |
1893 | 1.27k | precode_sym = deflate_precode_lens_permutation[0]; |
1894 | 1.27k | ADD_BITS(c->o.precode.lens[precode_sym], 3); |
1895 | 1.27k | FLUSH_BITS(); |
1896 | 1.27k | i = 1; /* num_explicit_lens >= 4 */ |
1897 | 19.2k | do { |
1898 | 19.2k | precode_sym = |
1899 | 19.2k | deflate_precode_lens_permutation[i]; |
1900 | 19.2k | ADD_BITS(c->o.precode.lens[precode_sym], 3); |
1901 | 19.2k | } while (++i < num_explicit_lens); |
1902 | 1.27k | FLUSH_BITS(); |
1903 | 1.27k | } else { |
1904 | 0 | FLUSH_BITS(); |
1905 | 0 | i = 0; |
1906 | 0 | do { |
1907 | 0 | precode_sym = |
1908 | 0 | deflate_precode_lens_permutation[i]; |
1909 | 0 | ADD_BITS(c->o.precode.lens[precode_sym], 3); |
1910 | 0 | FLUSH_BITS(); |
1911 | 0 | } while (++i < num_explicit_lens); |
1912 | 0 | } |
1913 | | |
1914 | | /* |
1915 | | * Output the lengths of the codewords in the litlen and offset |
1916 | | * codes, encoded by the precode. |
1917 | | */ |
1918 | 1.27k | i = 0; |
1919 | 254k | do { |
1920 | 254k | precode_item = c->o.precode.items[i]; |
1921 | 254k | precode_sym = precode_item & 0x1F; |
1922 | 254k | STATIC_ASSERT(CAN_BUFFER(MAX_PRE_CODEWORD_LEN + 7)); |
1923 | 254k | ADD_BITS(c->o.precode.codewords[precode_sym], |
1924 | 254k | c->o.precode.lens[precode_sym]); |
1925 | 254k | ADD_BITS(precode_item >> 5, |
1926 | 254k | deflate_extra_precode_bits[precode_sym]); |
1927 | 254k | FLUSH_BITS(); |
1928 | 254k | } while (++i < num_precode_items); |
1929 | 1.27k | } |
1930 | | |
1931 | | /* Output the literals and matches for a dynamic or static block. */ |
1932 | 1.82k | ASSERT(bitcount <= 7); |
1933 | 1.82k | deflate_compute_full_len_codewords(c, codes); |
1934 | 1.82k | #if SUPPORT_NEAR_OPTIMAL_PARSING |
1935 | 1.82k | if (sequences == NULL) { |
1936 | | /* Output the literals and matches from the minimum-cost path */ |
1937 | 0 | struct deflate_optimum_node *cur_node = |
1938 | 0 | &c->p.n.optimum_nodes[0]; |
1939 | 0 | struct deflate_optimum_node * const end_node = |
1940 | 0 | &c->p.n.optimum_nodes[block_length]; |
1941 | 0 | do { |
1942 | 0 | u32 length = cur_node->item & OPTIMUM_LEN_MASK; |
1943 | 0 | u32 offset = cur_node->item >> OPTIMUM_OFFSET_SHIFT; |
1944 | |
|
1945 | 0 | if (length == 1) { |
1946 | | /* Literal */ |
1947 | 0 | ADD_BITS(codes->codewords.litlen[offset], |
1948 | 0 | codes->lens.litlen[offset]); |
1949 | 0 | FLUSH_BITS(); |
1950 | 0 | } else { |
1951 | | /* Match */ |
1952 | 0 | WRITE_MATCH(c, codes, length, offset, |
1953 | 0 | c->p.n.offset_slot_full[offset]); |
1954 | 0 | } |
1955 | 0 | cur_node += length; |
1956 | 0 | } while (cur_node != end_node); |
1957 | 0 | } else |
1958 | 1.82k | #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */ |
1959 | 1.82k | { |
1960 | | /* Output the literals and matches from the sequences list. */ |
1961 | 1.82k | const struct deflate_sequence *seq; |
1962 | | |
1963 | 314k | for (seq = sequences; ; seq++) { |
1964 | 314k | u32 litrunlen = seq->litrunlen_and_length & |
1965 | 314k | SEQ_LITRUNLEN_MASK; |
1966 | 314k | u32 length = seq->litrunlen_and_length >> |
1967 | 314k | SEQ_LENGTH_SHIFT; |
1968 | 314k | unsigned lit; |
1969 | | |
1970 | | /* Output a run of literals. */ |
1971 | 314k | if (CAN_BUFFER(4 * MAX_LITLEN_CODEWORD_LEN)) { |
1972 | 522k | for (; litrunlen >= 4; litrunlen -= 4) { |
1973 | 208k | lit = *in_next++; |
1974 | 208k | ADD_BITS(codes->codewords.litlen[lit], |
1975 | 208k | codes->lens.litlen[lit]); |
1976 | 208k | lit = *in_next++; |
1977 | 208k | ADD_BITS(codes->codewords.litlen[lit], |
1978 | 208k | codes->lens.litlen[lit]); |
1979 | 208k | lit = *in_next++; |
1980 | 208k | ADD_BITS(codes->codewords.litlen[lit], |
1981 | 208k | codes->lens.litlen[lit]); |
1982 | 208k | lit = *in_next++; |
1983 | 208k | ADD_BITS(codes->codewords.litlen[lit], |
1984 | 208k | codes->lens.litlen[lit]); |
1985 | 208k | FLUSH_BITS(); |
1986 | 208k | } |
1987 | 314k | if (litrunlen-- != 0) { |
1988 | 217k | lit = *in_next++; |
1989 | 217k | ADD_BITS(codes->codewords.litlen[lit], |
1990 | 217k | codes->lens.litlen[lit]); |
1991 | 217k | if (litrunlen-- != 0) { |
1992 | 109k | lit = *in_next++; |
1993 | 109k | ADD_BITS(codes->codewords.litlen[lit], |
1994 | 109k | codes->lens.litlen[lit]); |
1995 | 109k | if (litrunlen-- != 0) { |
1996 | 35.7k | lit = *in_next++; |
1997 | 35.7k | ADD_BITS(codes->codewords.litlen[lit], |
1998 | 35.7k | codes->lens.litlen[lit]); |
1999 | 35.7k | } |
2000 | 109k | } |
2001 | 217k | FLUSH_BITS(); |
2002 | 217k | } |
2003 | 314k | } else { |
2004 | 0 | while (litrunlen--) { |
2005 | 0 | lit = *in_next++; |
2006 | 0 | ADD_BITS(codes->codewords.litlen[lit], |
2007 | 0 | codes->lens.litlen[lit]); |
2008 | 0 | FLUSH_BITS(); |
2009 | 0 | } |
2010 | 0 | } |
2011 | | |
2012 | 314k | if (length == 0) { /* Last sequence? */ |
2013 | 1.82k | ASSERT(in_next == in_end); |
2014 | 1.82k | break; |
2015 | 1.82k | } |
2016 | | |
2017 | | /* Output a match. */ |
2018 | 312k | WRITE_MATCH(c, codes, length, seq->offset, |
2019 | 312k | seq->offset_slot); |
2020 | 312k | in_next += length; |
2021 | 312k | } |
2022 | 1.82k | } |
2023 | | |
2024 | | /* Output the end-of-block symbol. */ |
2025 | 1.82k | ASSERT(bitcount <= 7); |
2026 | 1.82k | ADD_BITS(codes->codewords.litlen[DEFLATE_END_OF_BLOCK], |
2027 | 1.82k | codes->lens.litlen[DEFLATE_END_OF_BLOCK]); |
2028 | 1.82k | FLUSH_BITS(); |
2029 | 1.82k | out: |
2030 | 1.82k | ASSERT(bitcount <= 7); |
2031 | | /* |
2032 | | * Assert that the block cost was computed correctly. This is relied on |
2033 | | * above for the bounds check on the output buffer. Also, |
2034 | | * libdeflate_deflate_compress_bound() relies on this via the assumption |
2035 | | * that uncompressed blocks will always be used when cheapest. |
2036 | | */ |
2037 | 1.82k | ASSERT(8 * (out_next - os->next) + bitcount - os->bitcount == best_cost); |
2038 | 1.82k | os->bitbuf = bitbuf; |
2039 | 1.82k | os->bitcount = bitcount; |
2040 | 1.82k | os->next = out_next; |
2041 | 1.82k | } |
2042 | | |
2043 | | static void |
2044 | | deflate_finish_block(struct libdeflate_compressor *c, |
2045 | | struct deflate_output_bitstream *os, |
2046 | | const u8 *block_begin, u32 block_length, |
2047 | | const struct deflate_sequence *sequences, |
2048 | | bool is_final_block) |
2049 | 1.82k | { |
2050 | 1.82k | c->freqs.litlen[DEFLATE_END_OF_BLOCK]++; |
2051 | 1.82k | deflate_make_huffman_codes(&c->freqs, &c->codes); |
2052 | 1.82k | deflate_flush_block(c, os, block_begin, block_length, sequences, |
2053 | 1.82k | is_final_block); |
2054 | 1.82k | } |
2055 | | |
2056 | | /******************************************************************************/ |
2057 | | |
2058 | | /* |
2059 | | * Block splitting algorithm. The problem is to decide when it is worthwhile to |
2060 | | * start a new block with new Huffman codes. There is a theoretically optimal |
2061 | | * solution: recursively consider every possible block split, considering the |
2062 | | * exact cost of each block, and choose the minimum cost approach. But this is |
2063 | | * far too slow. Instead, as an approximation, we can count symbols and after |
2064 | | * every N symbols, compare the expected distribution of symbols based on the |
2065 | | * previous data with the actual distribution. If they differ "by enough", then |
2066 | | * start a new block. |
2067 | | * |
2068 | | * As an optimization and heuristic, we don't distinguish between every symbol |
2069 | | * but rather we combine many symbols into a single "observation type". For |
2070 | | * literals we only look at the high bits and low bits, and for matches we only |
2071 | | * look at whether the match is long or not. The assumption is that for typical |
2072 | | * "real" data, places that are good block boundaries will tend to be noticeable |
2073 | | * based only on changes in these aggregate probabilities, without looking for |
2074 | | * subtle differences in individual symbols. For example, a change from ASCII |
2075 | | * bytes to non-ASCII bytes, or from few matches (generally less compressible) |
2076 | | * to many matches (generally more compressible), would be easily noticed based |
2077 | | * on the aggregates. |
2078 | | * |
2079 | | * For determining whether the probability distributions are "different enough" |
2080 | | * to start a new block, the simple heuristic of splitting when the sum of |
2081 | | * absolute differences exceeds a constant seems to be good enough. We also add |
2082 | | * a number proportional to the block length so that the algorithm is more |
2083 | | * likely to end long blocks than short blocks. This reflects the general |
2084 | | * expectation that it will become increasingly beneficial to start a new block |
2085 | | * as the current block grows longer. |
2086 | | * |
2087 | | * Finally, for an approximation, it is not strictly necessary that the exact |
2088 | | * symbols being used are considered. With "near-optimal parsing", for example, |
2089 | | * the actual symbols that will be used are unknown until after the block |
2090 | | * boundary is chosen and the block has been optimized. Since the final choices |
2091 | | * cannot be used, we can use preliminary "greedy" choices instead. |
2092 | | */ |
2093 | | |
2094 | | /* Initialize the block split statistics when starting a new block. */ |
2095 | | static void |
2096 | | init_block_split_stats(struct block_split_stats *stats) |
2097 | 1.82k | { |
2098 | 1.82k | int i; |
2099 | | |
2100 | 20.0k | for (i = 0; i < NUM_OBSERVATION_TYPES; i++) { |
2101 | 18.2k | stats->new_observations[i] = 0; |
2102 | 18.2k | stats->observations[i] = 0; |
2103 | 18.2k | } |
2104 | 1.82k | stats->num_new_observations = 0; |
2105 | 1.82k | stats->num_observations = 0; |
2106 | 1.82k | } |
2107 | | |
2108 | | /* |
2109 | | * Literal observation. Heuristic: use the top 2 bits and low 1 bits of the |
2110 | | * literal, for 8 possible literal observation types. |
2111 | | */ |
2112 | | static forceinline void |
2113 | | observe_literal(struct block_split_stats *stats, u8 lit) |
2114 | 1.19M | { |
2115 | 1.19M | stats->new_observations[((lit >> 5) & 0x6) | (lit & 1)]++; |
2116 | 1.19M | stats->num_new_observations++; |
2117 | 1.19M | } |
2118 | | |
2119 | | /* |
2120 | | * Match observation. Heuristic: use one observation type for "short match" and |
2121 | | * one observation type for "long match". |
2122 | | */ |
2123 | | static forceinline void |
2124 | | observe_match(struct block_split_stats *stats, u32 length) |
2125 | 312k | { |
2126 | 312k | stats->new_observations[NUM_LITERAL_OBSERVATION_TYPES + |
2127 | 312k | (length >= 9)]++; |
2128 | 312k | stats->num_new_observations++; |
2129 | 312k | } |
2130 | | |
2131 | | static void |
2132 | | merge_new_observations(struct block_split_stats *stats) |
2133 | 108 | { |
2134 | 108 | int i; |
2135 | | |
2136 | 1.18k | for (i = 0; i < NUM_OBSERVATION_TYPES; i++) { |
2137 | 1.08k | stats->observations[i] += stats->new_observations[i]; |
2138 | 1.08k | stats->new_observations[i] = 0; |
2139 | 1.08k | } |
2140 | 108 | stats->num_observations += stats->num_new_observations; |
2141 | 108 | stats->num_new_observations = 0; |
2142 | 108 | } |
2143 | | |
2144 | | static bool |
2145 | | do_end_block_check(struct block_split_stats *stats, u32 block_length) |
2146 | 109 | { |
2147 | 109 | if (stats->num_observations > 0) { |
2148 | | /* |
2149 | | * Compute the sum of absolute differences of probabilities. To |
2150 | | * avoid needing to use floating point arithmetic or do slow |
2151 | | * divisions, we do all arithmetic with the probabilities |
2152 | | * multiplied by num_observations * num_new_observations. E.g., |
2153 | | * for the "old" observations the probabilities would be |
2154 | | * (double)observations[i] / num_observations, but since we |
2155 | | * multiply by both num_observations and num_new_observations we |
2156 | | * really do observations[i] * num_new_observations. |
2157 | | */ |
2158 | 41 | u32 total_delta = 0; |
2159 | 41 | u32 num_items; |
2160 | 41 | u32 cutoff; |
2161 | 41 | int i; |
2162 | | |
2163 | 451 | for (i = 0; i < NUM_OBSERVATION_TYPES; i++) { |
2164 | 410 | u32 expected = stats->observations[i] * |
2165 | 410 | stats->num_new_observations; |
2166 | 410 | u32 actual = stats->new_observations[i] * |
2167 | 410 | stats->num_observations; |
2168 | 410 | u32 delta = (actual > expected) ? actual - expected : |
2169 | 410 | expected - actual; |
2170 | | |
2171 | 410 | total_delta += delta; |
2172 | 410 | } |
2173 | | |
2174 | 41 | num_items = stats->num_observations + |
2175 | 41 | stats->num_new_observations; |
2176 | | /* |
2177 | | * Heuristic: the cutoff is when the sum of absolute differences |
2178 | | * of probabilities becomes at least 200/512. As above, the |
2179 | | * probability is multiplied by both num_new_observations and |
2180 | | * num_observations. Be careful to avoid integer overflow. |
2181 | | */ |
2182 | 41 | cutoff = stats->num_new_observations * 200 / 512 * |
2183 | 41 | stats->num_observations; |
2184 | | /* |
2185 | | * Very short blocks have a lot of overhead for the Huffman |
2186 | | * codes, so only use them if it clearly seems worthwhile. |
2187 | | * (This is an additional penalty, which adds to the smaller |
2188 | | * penalty below which scales more slowly.) |
2189 | | */ |
2190 | 41 | if (block_length < 10000 && num_items < 8192) |
2191 | 41 | cutoff += (u64)cutoff * (8192 - num_items) / 8192; |
2192 | | |
2193 | | /* Ready to end the block? */ |
2194 | 41 | if (total_delta + |
2195 | 41 | (block_length / 4096) * stats->num_observations >= cutoff) |
2196 | 1 | return true; |
2197 | 41 | } |
2198 | 108 | merge_new_observations(stats); |
2199 | 108 | return false; |
2200 | 109 | } |
2201 | | |
2202 | | static forceinline bool |
2203 | | ready_to_check_block(const struct block_split_stats *stats, |
2204 | | const u8 *in_block_begin, const u8 *in_next, |
2205 | | const u8 *in_end) |
2206 | 1.44M | { |
2207 | 1.44M | return stats->num_new_observations >= NUM_OBSERVATIONS_PER_BLOCK_CHECK |
2208 | 827k | && in_next - in_block_begin >= MIN_BLOCK_LENGTH |
2209 | 201k | && in_end - in_next >= MIN_BLOCK_LENGTH; |
2210 | 1.44M | } |
2211 | | |
2212 | | static forceinline bool |
2213 | | should_end_block(struct block_split_stats *stats, |
2214 | | const u8 *in_block_begin, const u8 *in_next, const u8 *in_end) |
2215 | 1.44M | { |
2216 | | /* Ready to try to end the block (again)? */ |
2217 | 1.44M | if (!ready_to_check_block(stats, in_block_begin, in_next, in_end)) |
2218 | 1.44M | return false; |
2219 | | |
2220 | 109 | return do_end_block_check(stats, in_next - in_block_begin); |
2221 | 1.44M | } |
2222 | | |
2223 | | /******************************************************************************/ |
2224 | | |
2225 | | static void |
2226 | | deflate_begin_sequences(struct libdeflate_compressor *c, |
2227 | | struct deflate_sequence *first_seq) |
2228 | 1.82k | { |
2229 | 1.82k | deflate_reset_symbol_frequencies(c); |
2230 | 1.82k | first_seq->litrunlen_and_length = 0; |
2231 | 1.82k | } |
2232 | | |
2233 | | static forceinline void |
2234 | | deflate_choose_literal(struct libdeflate_compressor *c, unsigned literal, |
2235 | | bool gather_split_stats, struct deflate_sequence *seq) |
2236 | 1.19M | { |
2237 | 1.19M | c->freqs.litlen[literal]++; |
2238 | | |
2239 | 1.19M | if (gather_split_stats) |
2240 | 1.19M | observe_literal(&c->split_stats, literal); |
2241 | | |
2242 | 1.19M | STATIC_ASSERT(MAX_BLOCK_LENGTH <= SEQ_LITRUNLEN_MASK); |
2243 | 1.19M | seq->litrunlen_and_length++; |
2244 | 1.19M | } |
2245 | | |
2246 | | static forceinline void |
2247 | | deflate_choose_match(struct libdeflate_compressor *c, |
2248 | | u32 length, u32 offset, bool gather_split_stats, |
2249 | | struct deflate_sequence **seq_p) |
2250 | 312k | { |
2251 | 312k | struct deflate_sequence *seq = *seq_p; |
2252 | 312k | unsigned length_slot = deflate_length_slot[length]; |
2253 | 312k | unsigned offset_slot = deflate_get_offset_slot(offset); |
2254 | | |
2255 | 312k | c->freqs.litlen[DEFLATE_FIRST_LEN_SYM + length_slot]++; |
2256 | 312k | c->freqs.offset[offset_slot]++; |
2257 | 312k | if (gather_split_stats) |
2258 | 312k | observe_match(&c->split_stats, length); |
2259 | | |
2260 | 312k | seq->litrunlen_and_length |= length << SEQ_LENGTH_SHIFT; |
2261 | 312k | seq->offset = offset; |
2262 | 312k | seq->offset_slot = offset_slot; |
2263 | | |
2264 | 312k | seq++; |
2265 | 312k | seq->litrunlen_and_length = 0; |
2266 | 312k | *seq_p = seq; |
2267 | 312k | } |
2268 | | |
2269 | | /* |
2270 | | * Decrease the maximum and nice match lengths if we're approaching the end of |
2271 | | * the input buffer. |
2272 | | */ |
2273 | | static forceinline void |
2274 | | adjust_max_and_nice_len(u32 *max_len, u32 *nice_len, size_t remaining) |
2275 | 2.12M | { |
2276 | 2.12M | if (unlikely(remaining < DEFLATE_MAX_MATCH_LEN)) { |
2277 | 116k | *max_len = remaining; |
2278 | 116k | *nice_len = MIN(*nice_len, *max_len); |
2279 | 116k | } |
2280 | 2.12M | } |
2281 | | |
2282 | | /* |
2283 | | * Choose the minimum match length for the greedy and lazy parsers. |
2284 | | * |
2285 | | * By default the minimum match length is 3, which is the smallest length the |
2286 | | * DEFLATE format allows. However, with greedy and lazy parsing, some data |
2287 | | * (e.g. DNA sequencing data) benefits greatly from a longer minimum length. |
2288 | | * Typically, this is because literals are very cheap. In general, the |
2289 | | * near-optimal parser handles this case naturally, but the greedy and lazy |
2290 | | * parsers need a heuristic to decide when to use short matches. |
2291 | | * |
2292 | | * The heuristic we use is to make the minimum match length depend on the number |
2293 | | * of different literals that exist in the data. If there are many different |
2294 | | * literals, then literals will probably be expensive, so short matches will |
2295 | | * probably be worthwhile. Conversely, if not many literals are used, then |
2296 | | * probably literals will be cheap and short matches won't be worthwhile. |
2297 | | */ |
2298 | | static u32 |
2299 | | choose_min_match_len(u32 num_used_literals, u32 max_search_depth) |
2300 | 1.72k | { |
2301 | | /* map from num_used_literals to min_len */ |
2302 | 1.72k | static const u8 min_lens[] = { |
2303 | 1.72k | 9, 9, 9, 9, 9, 9, 8, 8, 7, 7, 6, 6, 6, 6, 6, 6, |
2304 | 1.72k | 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, |
2305 | 1.72k | 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, |
2306 | 1.72k | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, |
2307 | 1.72k | 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, |
2308 | | /* The rest is implicitly 3. */ |
2309 | 1.72k | }; |
2310 | 1.72k | u32 min_len; |
2311 | | |
2312 | 1.72k | STATIC_ASSERT(DEFLATE_MIN_MATCH_LEN <= 3); |
2313 | 1.72k | STATIC_ASSERT(ARRAY_LEN(min_lens) <= DEFLATE_NUM_LITERALS + 1); |
2314 | | |
2315 | 1.72k | if (num_used_literals >= ARRAY_LEN(min_lens)) |
2316 | 1.14k | return 3; |
2317 | 580 | min_len = min_lens[num_used_literals]; |
2318 | | /* |
2319 | | * With a low max_search_depth, it may be too hard to find long matches. |
2320 | | */ |
2321 | 580 | if (max_search_depth < 16) { |
2322 | 0 | if (max_search_depth < 5) |
2323 | 0 | min_len = MIN(min_len, 4); |
2324 | 0 | else if (max_search_depth < 10) |
2325 | 0 | min_len = MIN(min_len, 5); |
2326 | 0 | else |
2327 | 0 | min_len = MIN(min_len, 7); |
2328 | 0 | } |
2329 | 580 | return min_len; |
2330 | 1.72k | } |
2331 | | |
2332 | | static u32 |
2333 | | calculate_min_match_len(const u8 *data, size_t data_len, u32 max_search_depth) |
2334 | 1.82k | { |
2335 | 1.82k | u8 used[256] = { 0 }; |
2336 | 1.82k | u32 num_used_literals = 0; |
2337 | 1.82k | size_t i; |
2338 | | |
2339 | | /* |
2340 | | * For very short inputs, the static Huffman code has a good chance of |
2341 | | * being best, in which case there is no reason to avoid short matches. |
2342 | | */ |
2343 | 1.82k | if (data_len < 512) |
2344 | 171 | return DEFLATE_MIN_MATCH_LEN; |
2345 | | |
2346 | | /* |
2347 | | * For an initial approximation, scan the first 4 KiB of data. The |
2348 | | * caller may use recalculate_min_match_len() to update min_len later. |
2349 | | */ |
2350 | 1.65k | data_len = MIN(data_len, 4096); |
2351 | 4.72M | for (i = 0; i < data_len; i++) |
2352 | 4.72M | used[data[i]] = 1; |
2353 | 425k | for (i = 0; i < 256; i++) |
2354 | 423k | num_used_literals += used[i]; |
2355 | 1.65k | return choose_min_match_len(num_used_literals, max_search_depth); |
2356 | 1.82k | } |
2357 | | |
2358 | | /* |
2359 | | * Recalculate the minimum match length for a block, now that we know the |
2360 | | * distribution of literals that are actually being used (freqs->litlen). |
2361 | | */ |
2362 | | static u32 |
2363 | | recalculate_min_match_len(const struct deflate_freqs *freqs, |
2364 | | u32 max_search_depth) |
2365 | 69 | { |
2366 | 69 | u32 literal_freq = 0; |
2367 | 69 | u32 cutoff; |
2368 | 69 | u32 num_used_literals = 0; |
2369 | 69 | int i; |
2370 | | |
2371 | 17.7k | for (i = 0; i < DEFLATE_NUM_LITERALS; i++) |
2372 | 17.6k | literal_freq += freqs->litlen[i]; |
2373 | | |
2374 | 69 | cutoff = literal_freq >> 10; /* Ignore literals used very rarely. */ |
2375 | | |
2376 | 17.7k | for (i = 0; i < DEFLATE_NUM_LITERALS; i++) { |
2377 | 17.6k | if (freqs->litlen[i] > cutoff) |
2378 | 14.6k | num_used_literals++; |
2379 | 17.6k | } |
2380 | 69 | return choose_min_match_len(num_used_literals, max_search_depth); |
2381 | 69 | } |
2382 | | |
2383 | | static forceinline const u8 * |
2384 | | choose_max_block_end(const u8 *in_block_begin, const u8 *in_end, |
2385 | | size_t soft_max_len) |
2386 | 1.82k | { |
2387 | 1.82k | if (in_end - in_block_begin < soft_max_len + MIN_BLOCK_LENGTH) |
2388 | 1.82k | return in_end; |
2389 | 0 | return in_block_begin + soft_max_len; |
2390 | 1.82k | } |
2391 | | |
2392 | | /* |
2393 | | * This is the level 0 "compressor". It always outputs uncompressed blocks. |
2394 | | */ |
2395 | | static size_t |
2396 | | deflate_compress_none(const u8 *in, size_t in_nbytes, |
2397 | | u8 *out, size_t out_nbytes_avail) |
2398 | 110 | { |
2399 | 110 | const u8 *in_next = in; |
2400 | 110 | const u8 * const in_end = in + in_nbytes; |
2401 | 110 | u8 *out_next = out; |
2402 | 110 | u8 * const out_end = out + out_nbytes_avail; |
2403 | | |
2404 | | /* |
2405 | | * If the input is zero-length, we still must output a block in order |
2406 | | * for the output to be a valid DEFLATE stream. Handle this case |
2407 | | * specially to avoid potentially passing NULL to memcpy() below. |
2408 | | */ |
2409 | 110 | if (unlikely(in_nbytes == 0)) { |
2410 | 0 | if (out_nbytes_avail < 5) |
2411 | 0 | return 0; |
2412 | | /* BFINAL and BTYPE */ |
2413 | 0 | *out_next++ = 1 | (DEFLATE_BLOCKTYPE_UNCOMPRESSED << 1); |
2414 | | /* LEN and NLEN */ |
2415 | 0 | put_unaligned_le32(0xFFFF0000, out_next); |
2416 | 0 | return 5; |
2417 | 0 | } |
2418 | | |
2419 | 110 | do { |
2420 | 110 | u8 bfinal = 0; |
2421 | 110 | size_t len = UINT16_MAX; |
2422 | | |
2423 | 110 | if (in_end - in_next <= UINT16_MAX) { |
2424 | 110 | bfinal = 1; |
2425 | 110 | len = in_end - in_next; |
2426 | 110 | } |
2427 | 110 | if (out_end - out_next < 5 + len) |
2428 | 0 | return 0; |
2429 | | /* |
2430 | | * Output BFINAL and BTYPE. The stream is already byte-aligned |
2431 | | * here, so this step always requires outputting exactly 1 byte. |
2432 | | */ |
2433 | 110 | *out_next++ = bfinal | (DEFLATE_BLOCKTYPE_UNCOMPRESSED << 1); |
2434 | | |
2435 | | /* Output LEN and NLEN, then the data itself. */ |
2436 | 110 | put_unaligned_le16(len, out_next); |
2437 | 110 | out_next += 2; |
2438 | 110 | put_unaligned_le16(~len, out_next); |
2439 | 110 | out_next += 2; |
2440 | 110 | memcpy(out_next, in_next, len); |
2441 | 110 | out_next += len; |
2442 | 110 | in_next += len; |
2443 | 110 | } while (in_next != in_end); |
2444 | | |
2445 | 110 | return out_next - out; |
2446 | 110 | } |
2447 | | |
2448 | | /* |
2449 | | * This is a faster variant of deflate_compress_greedy(). It uses the |
2450 | | * ht_matchfinder rather than the hc_matchfinder. It also skips the block |
2451 | | * splitting algorithm and just uses fixed length blocks. c->max_search_depth |
2452 | | * has no effect with this algorithm, as it is hardcoded in ht_matchfinder.h. |
2453 | | */ |
2454 | | static void |
2455 | | deflate_compress_fastest(struct libdeflate_compressor * restrict c, |
2456 | | const u8 *in, size_t in_nbytes, |
2457 | | struct deflate_output_bitstream *os) |
2458 | 0 | { |
2459 | 0 | const u8 *in_next = in; |
2460 | 0 | const u8 *in_end = in_next + in_nbytes; |
2461 | 0 | const u8 *in_cur_base = in_next; |
2462 | 0 | u32 max_len = DEFLATE_MAX_MATCH_LEN; |
2463 | 0 | u32 nice_len = MIN(c->nice_match_length, max_len); |
2464 | 0 | u32 next_hash = 0; |
2465 | |
|
2466 | 0 | ht_matchfinder_init(&c->p.f.ht_mf); |
2467 | |
|
2468 | 0 | do { |
2469 | | /* Starting a new DEFLATE block */ |
2470 | |
|
2471 | 0 | const u8 * const in_block_begin = in_next; |
2472 | 0 | const u8 * const in_max_block_end = choose_max_block_end( |
2473 | 0 | in_next, in_end, FAST_SOFT_MAX_BLOCK_LENGTH); |
2474 | 0 | struct deflate_sequence *seq = c->p.f.sequences; |
2475 | |
|
2476 | 0 | deflate_begin_sequences(c, seq); |
2477 | |
|
2478 | 0 | do { |
2479 | 0 | u32 length; |
2480 | 0 | u32 offset; |
2481 | 0 | size_t remaining = in_end - in_next; |
2482 | |
|
2483 | 0 | if (unlikely(remaining < DEFLATE_MAX_MATCH_LEN)) { |
2484 | 0 | max_len = remaining; |
2485 | 0 | if (max_len < HT_MATCHFINDER_REQUIRED_NBYTES) { |
2486 | 0 | do { |
2487 | 0 | deflate_choose_literal(c, |
2488 | 0 | *in_next++, false, seq); |
2489 | 0 | } while (--max_len); |
2490 | 0 | break; |
2491 | 0 | } |
2492 | 0 | nice_len = MIN(nice_len, max_len); |
2493 | 0 | } |
2494 | 0 | length = ht_matchfinder_longest_match(&c->p.f.ht_mf, |
2495 | 0 | &in_cur_base, |
2496 | 0 | in_next, |
2497 | 0 | max_len, |
2498 | 0 | nice_len, |
2499 | 0 | &next_hash, |
2500 | 0 | &offset); |
2501 | 0 | if (length) { |
2502 | | /* Match found */ |
2503 | 0 | deflate_choose_match(c, length, offset, false, |
2504 | 0 | &seq); |
2505 | 0 | ht_matchfinder_skip_bytes(&c->p.f.ht_mf, |
2506 | 0 | &in_cur_base, |
2507 | 0 | in_next + 1, |
2508 | 0 | in_end, |
2509 | 0 | length - 1, |
2510 | 0 | &next_hash); |
2511 | 0 | in_next += length; |
2512 | 0 | } else { |
2513 | | /* No match found */ |
2514 | 0 | deflate_choose_literal(c, *in_next++, false, |
2515 | 0 | seq); |
2516 | 0 | } |
2517 | | |
2518 | | /* Check if it's time to output another block. */ |
2519 | 0 | } while (in_next < in_max_block_end && |
2520 | 0 | seq < &c->p.f.sequences[FAST_SEQ_STORE_LENGTH]); |
2521 | |
|
2522 | 0 | deflate_finish_block(c, os, in_block_begin, |
2523 | 0 | in_next - in_block_begin, |
2524 | 0 | c->p.f.sequences, in_next == in_end); |
2525 | 0 | } while (in_next != in_end && !os->overflow); |
2526 | 0 | } |
2527 | | |
2528 | | /* |
2529 | | * Whether the greedy and lazy compressors use multi-hop links in the hash |
2530 | | * chains matchfinder (see 'next_tab' in hc_matchfinder.h). Multi-hop links |
2531 | | * make searching faster but inserting slower, so they pay off only for the |
2532 | | * deeper searches done by the lazy compressors. The choice doesn't affect the |
2533 | | * output. |
2534 | | */ |
2535 | 1.49k | #define GREEDY_MULTI_HOP false |
2536 | 2.36M | #define LAZY_MULTI_HOP true |
2537 | | |
2538 | | /* |
2539 | | * This is the "greedy" DEFLATE compressor. It always chooses the longest match. |
2540 | | */ |
2541 | | static void |
2542 | | deflate_compress_greedy(struct libdeflate_compressor * restrict c, |
2543 | | const u8 *in, size_t in_nbytes, |
2544 | | struct deflate_output_bitstream *os) |
2545 | 0 | { |
2546 | 0 | const u8 *in_next = in; |
2547 | 0 | const u8 *in_end = in_next + in_nbytes; |
2548 | 0 | const u8 *in_cur_base = in_next; |
2549 | 0 | u32 max_len = DEFLATE_MAX_MATCH_LEN; |
2550 | 0 | u32 nice_len = MIN(c->nice_match_length, max_len); |
2551 | 0 | u32 next_hashes[2] = {0, 0}; |
2552 | |
|
2553 | 0 | hc_matchfinder_init(&c->p.g.hc_mf, GREEDY_MULTI_HOP); |
2554 | |
|
2555 | 0 | do { |
2556 | | /* Starting a new DEFLATE block */ |
2557 | |
|
2558 | 0 | const u8 * const in_block_begin = in_next; |
2559 | 0 | const u8 * const in_max_block_end = choose_max_block_end( |
2560 | 0 | in_next, in_end, SOFT_MAX_BLOCK_LENGTH); |
2561 | 0 | struct deflate_sequence *seq = c->p.g.sequences; |
2562 | 0 | u32 min_len; |
2563 | |
|
2564 | 0 | init_block_split_stats(&c->split_stats); |
2565 | 0 | deflate_begin_sequences(c, seq); |
2566 | 0 | min_len = calculate_min_match_len(in_next, |
2567 | 0 | in_max_block_end - in_next, |
2568 | 0 | c->max_search_depth); |
2569 | 0 | do { |
2570 | 0 | u32 length; |
2571 | 0 | u32 offset; |
2572 | |
|
2573 | 0 | adjust_max_and_nice_len(&max_len, &nice_len, |
2574 | 0 | in_end - in_next); |
2575 | 0 | length = hc_matchfinder_longest_match( |
2576 | 0 | &c->p.g.hc_mf, |
2577 | 0 | &in_cur_base, |
2578 | 0 | in_next, |
2579 | 0 | min_len - 1, |
2580 | 0 | max_len, |
2581 | 0 | nice_len, |
2582 | 0 | c->max_search_depth, |
2583 | 0 | next_hashes, |
2584 | 0 | &offset, |
2585 | 0 | GREEDY_MULTI_HOP); |
2586 | |
|
2587 | 0 | if (length >= min_len && |
2588 | 0 | (length > DEFLATE_MIN_MATCH_LEN || |
2589 | 0 | offset <= 4096)) { |
2590 | | /* Match found */ |
2591 | 0 | deflate_choose_match(c, length, offset, true, |
2592 | 0 | &seq); |
2593 | 0 | hc_matchfinder_skip_bytes(&c->p.g.hc_mf, |
2594 | 0 | &in_cur_base, |
2595 | 0 | in_next + 1, |
2596 | 0 | in_end, |
2597 | 0 | length - 1, |
2598 | 0 | next_hashes, |
2599 | 0 | GREEDY_MULTI_HOP); |
2600 | 0 | in_next += length; |
2601 | 0 | } else { |
2602 | | /* No match found */ |
2603 | 0 | deflate_choose_literal(c, *in_next++, true, |
2604 | 0 | seq); |
2605 | 0 | } |
2606 | | |
2607 | | /* Check if it's time to output another block. */ |
2608 | 0 | } while (in_next < in_max_block_end && |
2609 | 0 | seq < &c->p.g.sequences[SEQ_STORE_LENGTH] && |
2610 | 0 | !should_end_block(&c->split_stats, |
2611 | 0 | in_block_begin, in_next, in_end)); |
2612 | |
|
2613 | 0 | deflate_finish_block(c, os, in_block_begin, |
2614 | 0 | in_next - in_block_begin, |
2615 | 0 | c->p.g.sequences, in_next == in_end); |
2616 | 0 | } while (in_next != in_end && !os->overflow); |
2617 | 0 | } |
2618 | | |
2619 | | static forceinline void |
2620 | | deflate_compress_lazy_generic(struct libdeflate_compressor * restrict c, |
2621 | | const u8 *in, size_t in_nbytes, |
2622 | | struct deflate_output_bitstream *os, bool lazy2) |
2623 | 1.82k | { |
2624 | 1.82k | const u8 *in_next = in; |
2625 | 1.82k | const u8 *in_end = in_next + in_nbytes; |
2626 | 1.82k | const u8 *in_cur_base = in_next; |
2627 | 1.82k | u32 max_len = DEFLATE_MAX_MATCH_LEN; |
2628 | 1.82k | u32 nice_len = MIN(c->nice_match_length, max_len); |
2629 | 1.82k | u32 next_hashes[2] = {0, 0}; |
2630 | | |
2631 | 1.82k | hc_matchfinder_init(&c->p.g.hc_mf, LAZY_MULTI_HOP); |
2632 | | |
2633 | 1.82k | do { |
2634 | | /* Starting a new DEFLATE block */ |
2635 | | |
2636 | 1.82k | const u8 * const in_block_begin = in_next; |
2637 | 1.82k | const u8 * const in_max_block_end = choose_max_block_end( |
2638 | 1.82k | in_next, in_end, SOFT_MAX_BLOCK_LENGTH); |
2639 | 1.82k | const u8 *next_recalc_min_len = |
2640 | 1.82k | in_next + MIN(in_end - in_next, 10000); |
2641 | 1.82k | struct deflate_sequence *seq = c->p.g.sequences; |
2642 | 1.82k | u32 min_len; |
2643 | | |
2644 | 1.82k | init_block_split_stats(&c->split_stats); |
2645 | 1.82k | deflate_begin_sequences(c, seq); |
2646 | 1.82k | min_len = calculate_min_match_len(in_next, |
2647 | 1.82k | in_max_block_end - in_next, |
2648 | 1.82k | c->max_search_depth); |
2649 | 1.44M | do { |
2650 | 1.44M | u32 cur_len; |
2651 | 1.44M | u32 cur_offset; |
2652 | 1.44M | u32 next_len; |
2653 | 1.44M | u32 next_offset; |
2654 | | |
2655 | | /* |
2656 | | * Recalculate the minimum match length if it hasn't |
2657 | | * been done recently. |
2658 | | */ |
2659 | 1.44M | if (in_next >= next_recalc_min_len) { |
2660 | 69 | min_len = recalculate_min_match_len( |
2661 | 69 | &c->freqs, |
2662 | 69 | c->max_search_depth); |
2663 | 69 | next_recalc_min_len += |
2664 | 69 | MIN(in_end - next_recalc_min_len, |
2665 | 69 | in_next - in_block_begin); |
2666 | 69 | } |
2667 | | |
2668 | | /* Find the longest match at the current position. */ |
2669 | 1.44M | adjust_max_and_nice_len(&max_len, &nice_len, |
2670 | 1.44M | in_end - in_next); |
2671 | 1.44M | cur_len = hc_matchfinder_longest_match( |
2672 | 1.44M | &c->p.g.hc_mf, |
2673 | 1.44M | &in_cur_base, |
2674 | 1.44M | in_next, |
2675 | 1.44M | min_len - 1, |
2676 | 1.44M | max_len, |
2677 | 1.44M | nice_len, |
2678 | 1.44M | c->max_search_depth, |
2679 | 1.44M | next_hashes, |
2680 | 1.44M | &cur_offset, |
2681 | 1.44M | LAZY_MULTI_HOP); |
2682 | 1.44M | if (cur_len < min_len || |
2683 | 313k | (cur_len == DEFLATE_MIN_MATCH_LEN && |
2684 | 1.12M | cur_offset > 8192)) { |
2685 | | /* No match found. Choose a literal. */ |
2686 | 1.12M | deflate_choose_literal(c, *in_next++, true, |
2687 | 1.12M | seq); |
2688 | 1.12M | continue; |
2689 | 1.12M | } |
2690 | 312k | in_next++; |
2691 | | |
2692 | 365k | have_cur_match: |
2693 | | /* |
2694 | | * We have a match at the current position. |
2695 | | * If it's very long, choose it immediately. |
2696 | | */ |
2697 | 365k | if (cur_len >= nice_len) { |
2698 | 6.50k | deflate_choose_match(c, cur_len, cur_offset, |
2699 | 6.50k | true, &seq); |
2700 | 6.50k | hc_matchfinder_skip_bytes(&c->p.g.hc_mf, |
2701 | 6.50k | &in_cur_base, |
2702 | 6.50k | in_next, |
2703 | 6.50k | in_end, |
2704 | 6.50k | cur_len - 1, |
2705 | 6.50k | next_hashes, |
2706 | 6.50k | LAZY_MULTI_HOP); |
2707 | 6.50k | in_next += cur_len - 1; |
2708 | 6.50k | continue; |
2709 | 6.50k | } |
2710 | | |
2711 | | /* |
2712 | | * Try to find a better match at the next position. |
2713 | | * |
2714 | | * Note: since we already have a match at the *current* |
2715 | | * position, we use only half the 'max_search_depth' |
2716 | | * when checking the *next* position. This is a useful |
2717 | | * trade-off because it's more worthwhile to use a |
2718 | | * greater search depth on the initial match. |
2719 | | * |
2720 | | * Note: it's possible to structure the code such that |
2721 | | * there's only one call to longest_match(), which |
2722 | | * handles both the "find the initial match" and "try to |
2723 | | * find a better match" cases. However, it is faster to |
2724 | | * have two call sites, with longest_match() inlined at |
2725 | | * each. |
2726 | | */ |
2727 | 359k | adjust_max_and_nice_len(&max_len, &nice_len, |
2728 | 359k | in_end - in_next); |
2729 | 359k | next_len = hc_matchfinder_longest_match( |
2730 | 359k | &c->p.g.hc_mf, |
2731 | 359k | &in_cur_base, |
2732 | 359k | in_next++, |
2733 | 359k | cur_len - 1, |
2734 | 359k | max_len, |
2735 | 359k | nice_len, |
2736 | 359k | c->max_search_depth >> 1, |
2737 | 359k | next_hashes, |
2738 | 359k | &next_offset, |
2739 | 359k | LAZY_MULTI_HOP); |
2740 | 359k | if (next_len >= cur_len && |
2741 | 60.5k | 4 * (int)(next_len - cur_len) + |
2742 | 60.5k | ((int)bsr32(cur_offset) - |
2743 | 60.5k | (int)bsr32(next_offset)) > 2) { |
2744 | | /* |
2745 | | * Found a better match at the next position. |
2746 | | * Output a literal. Then the next match |
2747 | | * becomes the current match. |
2748 | | */ |
2749 | 38.8k | deflate_choose_literal(c, *(in_next - 2), true, |
2750 | 38.8k | seq); |
2751 | 38.8k | cur_len = next_len; |
2752 | 38.8k | cur_offset = next_offset; |
2753 | 38.8k | goto have_cur_match; |
2754 | 38.8k | } |
2755 | | |
2756 | 320k | if (lazy2) { |
2757 | | /* In lazy2 mode, look ahead another position */ |
2758 | 320k | adjust_max_and_nice_len(&max_len, &nice_len, |
2759 | 320k | in_end - in_next); |
2760 | 320k | next_len = hc_matchfinder_longest_match( |
2761 | 320k | &c->p.g.hc_mf, |
2762 | 320k | &in_cur_base, |
2763 | 320k | in_next++, |
2764 | 320k | cur_len - 1, |
2765 | 320k | max_len, |
2766 | 320k | nice_len, |
2767 | 320k | c->max_search_depth >> 2, |
2768 | 320k | next_hashes, |
2769 | 320k | &next_offset, |
2770 | 320k | LAZY_MULTI_HOP); |
2771 | 320k | if (next_len >= cur_len && |
2772 | 24.8k | 4 * (int)(next_len - cur_len) + |
2773 | 24.8k | ((int)bsr32(cur_offset) - |
2774 | 24.8k | (int)bsr32(next_offset)) > 6) { |
2775 | | /* |
2776 | | * There's a much better match two |
2777 | | * positions ahead, so use two literals. |
2778 | | */ |
2779 | 14.0k | deflate_choose_literal( |
2780 | 14.0k | c, *(in_next - 3), true, seq); |
2781 | 14.0k | deflate_choose_literal( |
2782 | 14.0k | c, *(in_next - 2), true, seq); |
2783 | 14.0k | cur_len = next_len; |
2784 | 14.0k | cur_offset = next_offset; |
2785 | 14.0k | goto have_cur_match; |
2786 | 14.0k | } |
2787 | | /* |
2788 | | * No better match at either of the next 2 |
2789 | | * positions. Output the current match. |
2790 | | */ |
2791 | 306k | deflate_choose_match(c, cur_len, cur_offset, |
2792 | 306k | true, &seq); |
2793 | 306k | if (cur_len > 3) { |
2794 | 229k | hc_matchfinder_skip_bytes(&c->p.g.hc_mf, |
2795 | 229k | &in_cur_base, |
2796 | 229k | in_next, |
2797 | 229k | in_end, |
2798 | 229k | cur_len - 3, |
2799 | 229k | next_hashes, |
2800 | 229k | LAZY_MULTI_HOP); |
2801 | 229k | in_next += cur_len - 3; |
2802 | 229k | } |
2803 | 306k | } else { /* !lazy2 */ |
2804 | | /* |
2805 | | * No better match at the next position. Output |
2806 | | * the current match. |
2807 | | */ |
2808 | 0 | deflate_choose_match(c, cur_len, cur_offset, |
2809 | 0 | true, &seq); |
2810 | 0 | hc_matchfinder_skip_bytes(&c->p.g.hc_mf, |
2811 | 0 | &in_cur_base, |
2812 | 0 | in_next, |
2813 | 0 | in_end, |
2814 | 0 | cur_len - 2, |
2815 | 0 | next_hashes, |
2816 | 0 | LAZY_MULTI_HOP); |
2817 | 0 | in_next += cur_len - 2; |
2818 | 0 | } |
2819 | | /* Check if it's time to output another block. */ |
2820 | 1.44M | } while (in_next < in_max_block_end && |
2821 | 1.44M | seq < &c->p.g.sequences[SEQ_STORE_LENGTH] && |
2822 | 1.44M | !should_end_block(&c->split_stats, |
2823 | 1.44M | in_block_begin, in_next, in_end)); |
2824 | | |
2825 | 1.82k | deflate_finish_block(c, os, in_block_begin, |
2826 | 1.82k | in_next - in_block_begin, |
2827 | 1.82k | c->p.g.sequences, in_next == in_end); |
2828 | 1.82k | } while (in_next != in_end && !os->overflow); |
2829 | 1.82k | } |
2830 | | |
2831 | | /* |
2832 | | * This is the "lazy" DEFLATE compressor. Before choosing a match, it checks to |
2833 | | * see if there's a better match at the next position. If yes, it outputs a |
2834 | | * literal and continues to the next position. If no, it outputs the match. |
2835 | | */ |
2836 | | static void |
2837 | | deflate_compress_lazy(struct libdeflate_compressor * restrict c, |
2838 | | const u8 *in, size_t in_nbytes, |
2839 | | struct deflate_output_bitstream *os) |
2840 | 0 | { |
2841 | 0 | deflate_compress_lazy_generic(c, in, in_nbytes, os, false); |
2842 | 0 | } |
2843 | | |
2844 | | /* |
2845 | | * The lazy2 compressor. This is similar to the regular lazy one, but it looks |
2846 | | * for a better match at the next 2 positions rather than the next 1. This |
2847 | | * makes it take slightly more time, but compress some inputs slightly more. |
2848 | | */ |
2849 | | static void |
2850 | | deflate_compress_lazy2(struct libdeflate_compressor * restrict c, |
2851 | | const u8 *in, size_t in_nbytes, |
2852 | | struct deflate_output_bitstream *os) |
2853 | 1.82k | { |
2854 | 1.82k | deflate_compress_lazy_generic(c, in, in_nbytes, os, true); |
2855 | 1.82k | } |
2856 | | |
2857 | | #if SUPPORT_NEAR_OPTIMAL_PARSING |
2858 | | |
2859 | | /* |
2860 | | * Follow the minimum-cost path in the graph of possible match/literal choices |
2861 | | * for the current block and compute the frequencies of the Huffman symbols that |
2862 | | * would be needed to output those matches and literals. |
2863 | | */ |
2864 | | static void |
2865 | | deflate_tally_item_list(struct libdeflate_compressor *c, u32 block_length) |
2866 | 0 | { |
2867 | 0 | struct deflate_optimum_node *cur_node = &c->p.n.optimum_nodes[0]; |
2868 | 0 | struct deflate_optimum_node *end_node = |
2869 | 0 | &c->p.n.optimum_nodes[block_length]; |
2870 | |
|
2871 | 0 | do { |
2872 | 0 | u32 length = cur_node->item & OPTIMUM_LEN_MASK; |
2873 | 0 | u32 offset = cur_node->item >> OPTIMUM_OFFSET_SHIFT; |
2874 | |
|
2875 | 0 | if (length == 1) { |
2876 | | /* Literal */ |
2877 | 0 | c->freqs.litlen[offset]++; |
2878 | 0 | } else { |
2879 | | /* Match */ |
2880 | 0 | c->freqs.litlen[DEFLATE_FIRST_LEN_SYM + |
2881 | 0 | deflate_length_slot[length]]++; |
2882 | 0 | c->freqs.offset[c->p.n.offset_slot_full[offset]]++; |
2883 | 0 | } |
2884 | 0 | cur_node += length; |
2885 | 0 | } while (cur_node != end_node); |
2886 | | |
2887 | | /* Tally the end-of-block symbol. */ |
2888 | 0 | c->freqs.litlen[DEFLATE_END_OF_BLOCK]++; |
2889 | 0 | } |
2890 | | |
2891 | | static void |
2892 | | deflate_choose_all_literals(struct libdeflate_compressor *c, |
2893 | | const u8 *block, u32 block_length) |
2894 | 0 | { |
2895 | 0 | u32 i; |
2896 | |
|
2897 | 0 | deflate_reset_symbol_frequencies(c); |
2898 | 0 | for (i = 0; i < block_length; i++) |
2899 | 0 | c->freqs.litlen[block[i]]++; |
2900 | 0 | c->freqs.litlen[DEFLATE_END_OF_BLOCK]++; |
2901 | |
|
2902 | 0 | deflate_make_huffman_codes(&c->freqs, &c->codes); |
2903 | 0 | } |
2904 | | |
2905 | | /* |
2906 | | * Compute the exact cost, in bits, that would be required to output the matches |
2907 | | * and literals described by @c->freqs as a dynamic Huffman block. The litlen |
2908 | | * and offset codes are assumed to have already been built in @c->codes. |
2909 | | */ |
2910 | | static u32 |
2911 | | deflate_compute_true_cost(struct libdeflate_compressor *c) |
2912 | 0 | { |
2913 | 0 | u32 cost = 0; |
2914 | 0 | unsigned sym; |
2915 | |
|
2916 | 0 | deflate_precompute_huffman_header(c); |
2917 | |
|
2918 | 0 | memset(&c->codes.lens.litlen[c->o.precode.num_litlen_syms], 0, |
2919 | 0 | DEFLATE_NUM_LITLEN_SYMS - c->o.precode.num_litlen_syms); |
2920 | |
|
2921 | 0 | cost += 5 + 5 + 4 + (3 * c->o.precode.num_explicit_lens); |
2922 | 0 | for (sym = 0; sym < DEFLATE_NUM_PRECODE_SYMS; sym++) { |
2923 | 0 | cost += c->o.precode.freqs[sym] * |
2924 | 0 | (c->o.precode.lens[sym] + |
2925 | 0 | deflate_extra_precode_bits[sym]); |
2926 | 0 | } |
2927 | |
|
2928 | 0 | for (sym = 0; sym < DEFLATE_FIRST_LEN_SYM; sym++) |
2929 | 0 | cost += c->freqs.litlen[sym] * c->codes.lens.litlen[sym]; |
2930 | |
|
2931 | 0 | for (; sym < DEFLATE_FIRST_LEN_SYM + |
2932 | 0 | ARRAY_LEN(deflate_extra_length_bits); sym++) |
2933 | 0 | cost += c->freqs.litlen[sym] * |
2934 | 0 | (c->codes.lens.litlen[sym] + |
2935 | 0 | deflate_extra_length_bits[sym - DEFLATE_FIRST_LEN_SYM]); |
2936 | |
|
2937 | 0 | for (sym = 0; sym < ARRAY_LEN(deflate_extra_offset_bits); sym++) |
2938 | 0 | cost += c->freqs.offset[sym] * |
2939 | 0 | (c->codes.lens.offset[sym] + |
2940 | 0 | deflate_extra_offset_bits[sym]); |
2941 | 0 | return cost; |
2942 | 0 | } |
2943 | | |
2944 | | /* Set the current cost model from the codeword lengths specified in @lens. */ |
2945 | | static void |
2946 | | deflate_set_costs_from_codes(struct libdeflate_compressor *c, |
2947 | | const struct deflate_lens *lens) |
2948 | 0 | { |
2949 | 0 | unsigned i; |
2950 | | |
2951 | | /* Literals */ |
2952 | 0 | for (i = 0; i < DEFLATE_NUM_LITERALS; i++) { |
2953 | 0 | u32 bits = (lens->litlen[i] ? |
2954 | 0 | lens->litlen[i] : LITERAL_NOSTAT_BITS); |
2955 | |
|
2956 | 0 | c->p.n.costs.literal[i] = bits * BIT_COST; |
2957 | 0 | } |
2958 | | |
2959 | | /* Lengths */ |
2960 | 0 | for (i = DEFLATE_MIN_MATCH_LEN; i <= DEFLATE_MAX_MATCH_LEN; i++) { |
2961 | 0 | unsigned length_slot = deflate_length_slot[i]; |
2962 | 0 | unsigned litlen_sym = DEFLATE_FIRST_LEN_SYM + length_slot; |
2963 | 0 | u32 bits = (lens->litlen[litlen_sym] ? |
2964 | 0 | lens->litlen[litlen_sym] : LENGTH_NOSTAT_BITS); |
2965 | |
|
2966 | 0 | bits += deflate_extra_length_bits[length_slot]; |
2967 | 0 | c->p.n.costs.length[i] = bits * BIT_COST; |
2968 | 0 | } |
2969 | | |
2970 | | /* Offset slots */ |
2971 | 0 | for (i = 0; i < ARRAY_LEN(deflate_offset_slot_base); i++) { |
2972 | 0 | u32 bits = (lens->offset[i] ? |
2973 | 0 | lens->offset[i] : OFFSET_NOSTAT_BITS); |
2974 | |
|
2975 | 0 | bits += deflate_extra_offset_bits[i]; |
2976 | 0 | c->p.n.costs.offset_slot[i] = bits * BIT_COST; |
2977 | 0 | } |
2978 | 0 | } |
2979 | | |
2980 | | /* |
2981 | | * This lookup table gives the default cost of a literal symbol and of a length |
2982 | | * symbol, depending on the characteristics of the input data. It was generated |
2983 | | * by scripts/gen_default_litlen_costs.py. |
2984 | | * |
2985 | | * This table is indexed first by the estimated match probability: |
2986 | | * |
2987 | | * i=0: data doesn't contain many matches [match_prob=0.25] |
2988 | | * i=1: neutral [match_prob=0.50] |
2989 | | * i=2: data contains lots of matches [match_prob=0.75] |
2990 | | * |
2991 | | * This lookup produces a subtable which maps the number of distinct used |
2992 | | * literals to the default cost of a literal symbol, i.e.: |
2993 | | * |
2994 | | * int(-log2((1 - match_prob) / num_used_literals) * BIT_COST) |
2995 | | * |
2996 | | * ... for num_used_literals in [1, 256] (and 0, which is copied from 1). This |
2997 | | * accounts for literals usually getting cheaper as the number of distinct |
2998 | | * literals decreases, and as the proportion of literals to matches increases. |
2999 | | * |
3000 | | * The lookup also produces the cost of a length symbol, which is: |
3001 | | * |
3002 | | * int(-log2(match_prob/NUM_LEN_SLOTS) * BIT_COST) |
3003 | | * |
3004 | | * Note: we don't currently assign different costs to different literal symbols, |
3005 | | * or to different length symbols, as this is hard to do in a useful way. |
3006 | | */ |
3007 | | static const struct { |
3008 | | u8 used_lits_to_lit_cost[257]; |
3009 | | u8 len_sym_cost; |
3010 | | } default_litlen_costs[] = { |
3011 | | { /* match_prob = 0.25 */ |
3012 | | .used_lits_to_lit_cost = { |
3013 | | 6, 6, 22, 32, 38, 43, 48, 51, |
3014 | | 54, 57, 59, 61, 64, 65, 67, 69, |
3015 | | 70, 72, 73, 74, 75, 76, 77, 79, |
3016 | | 80, 80, 81, 82, 83, 84, 85, 85, |
3017 | | 86, 87, 88, 88, 89, 89, 90, 91, |
3018 | | 91, 92, 92, 93, 93, 94, 95, 95, |
3019 | | 96, 96, 96, 97, 97, 98, 98, 99, |
3020 | | 99, 99, 100, 100, 101, 101, 101, 102, |
3021 | | 102, 102, 103, 103, 104, 104, 104, 105, |
3022 | | 105, 105, 105, 106, 106, 106, 107, 107, |
3023 | | 107, 108, 108, 108, 108, 109, 109, 109, |
3024 | | 109, 110, 110, 110, 111, 111, 111, 111, |
3025 | | 112, 112, 112, 112, 112, 113, 113, 113, |
3026 | | 113, 114, 114, 114, 114, 114, 115, 115, |
3027 | | 115, 115, 115, 116, 116, 116, 116, 116, |
3028 | | 117, 117, 117, 117, 117, 118, 118, 118, |
3029 | | 118, 118, 118, 119, 119, 119, 119, 119, |
3030 | | 120, 120, 120, 120, 120, 120, 121, 121, |
3031 | | 121, 121, 121, 121, 121, 122, 122, 122, |
3032 | | 122, 122, 122, 123, 123, 123, 123, 123, |
3033 | | 123, 123, 124, 124, 124, 124, 124, 124, |
3034 | | 124, 125, 125, 125, 125, 125, 125, 125, |
3035 | | 125, 126, 126, 126, 126, 126, 126, 126, |
3036 | | 127, 127, 127, 127, 127, 127, 127, 127, |
3037 | | 128, 128, 128, 128, 128, 128, 128, 128, |
3038 | | 128, 129, 129, 129, 129, 129, 129, 129, |
3039 | | 129, 129, 130, 130, 130, 130, 130, 130, |
3040 | | 130, 130, 130, 131, 131, 131, 131, 131, |
3041 | | 131, 131, 131, 131, 131, 132, 132, 132, |
3042 | | 132, 132, 132, 132, 132, 132, 132, 133, |
3043 | | 133, 133, 133, 133, 133, 133, 133, 133, |
3044 | | 133, 134, 134, 134, 134, 134, 134, 134, |
3045 | | 134, |
3046 | | }, |
3047 | | .len_sym_cost = 109, |
3048 | | }, { /* match_prob = 0.5 */ |
3049 | | .used_lits_to_lit_cost = { |
3050 | | 16, 16, 32, 41, 48, 53, 57, 60, |
3051 | | 64, 66, 69, 71, 73, 75, 76, 78, |
3052 | | 80, 81, 82, 83, 85, 86, 87, 88, |
3053 | | 89, 90, 91, 92, 92, 93, 94, 95, |
3054 | | 96, 96, 97, 98, 98, 99, 99, 100, |
3055 | | 101, 101, 102, 102, 103, 103, 104, 104, |
3056 | | 105, 105, 106, 106, 107, 107, 108, 108, |
3057 | | 108, 109, 109, 110, 110, 110, 111, 111, |
3058 | | 112, 112, 112, 113, 113, 113, 114, 114, |
3059 | | 114, 115, 115, 115, 115, 116, 116, 116, |
3060 | | 117, 117, 117, 118, 118, 118, 118, 119, |
3061 | | 119, 119, 119, 120, 120, 120, 120, 121, |
3062 | | 121, 121, 121, 122, 122, 122, 122, 122, |
3063 | | 123, 123, 123, 123, 124, 124, 124, 124, |
3064 | | 124, 125, 125, 125, 125, 125, 126, 126, |
3065 | | 126, 126, 126, 127, 127, 127, 127, 127, |
3066 | | 128, 128, 128, 128, 128, 128, 129, 129, |
3067 | | 129, 129, 129, 129, 130, 130, 130, 130, |
3068 | | 130, 130, 131, 131, 131, 131, 131, 131, |
3069 | | 131, 132, 132, 132, 132, 132, 132, 133, |
3070 | | 133, 133, 133, 133, 133, 133, 134, 134, |
3071 | | 134, 134, 134, 134, 134, 134, 135, 135, |
3072 | | 135, 135, 135, 135, 135, 135, 136, 136, |
3073 | | 136, 136, 136, 136, 136, 136, 137, 137, |
3074 | | 137, 137, 137, 137, 137, 137, 138, 138, |
3075 | | 138, 138, 138, 138, 138, 138, 138, 139, |
3076 | | 139, 139, 139, 139, 139, 139, 139, 139, |
3077 | | 140, 140, 140, 140, 140, 140, 140, 140, |
3078 | | 140, 141, 141, 141, 141, 141, 141, 141, |
3079 | | 141, 141, 141, 142, 142, 142, 142, 142, |
3080 | | 142, 142, 142, 142, 142, 142, 143, 143, |
3081 | | 143, 143, 143, 143, 143, 143, 143, 143, |
3082 | | 144, |
3083 | | }, |
3084 | | .len_sym_cost = 93, |
3085 | | }, { /* match_prob = 0.75 */ |
3086 | | .used_lits_to_lit_cost = { |
3087 | | 32, 32, 48, 57, 64, 69, 73, 76, |
3088 | | 80, 82, 85, 87, 89, 91, 92, 94, |
3089 | | 96, 97, 98, 99, 101, 102, 103, 104, |
3090 | | 105, 106, 107, 108, 108, 109, 110, 111, |
3091 | | 112, 112, 113, 114, 114, 115, 115, 116, |
3092 | | 117, 117, 118, 118, 119, 119, 120, 120, |
3093 | | 121, 121, 122, 122, 123, 123, 124, 124, |
3094 | | 124, 125, 125, 126, 126, 126, 127, 127, |
3095 | | 128, 128, 128, 129, 129, 129, 130, 130, |
3096 | | 130, 131, 131, 131, 131, 132, 132, 132, |
3097 | | 133, 133, 133, 134, 134, 134, 134, 135, |
3098 | | 135, 135, 135, 136, 136, 136, 136, 137, |
3099 | | 137, 137, 137, 138, 138, 138, 138, 138, |
3100 | | 139, 139, 139, 139, 140, 140, 140, 140, |
3101 | | 140, 141, 141, 141, 141, 141, 142, 142, |
3102 | | 142, 142, 142, 143, 143, 143, 143, 143, |
3103 | | 144, 144, 144, 144, 144, 144, 145, 145, |
3104 | | 145, 145, 145, 145, 146, 146, 146, 146, |
3105 | | 146, 146, 147, 147, 147, 147, 147, 147, |
3106 | | 147, 148, 148, 148, 148, 148, 148, 149, |
3107 | | 149, 149, 149, 149, 149, 149, 150, 150, |
3108 | | 150, 150, 150, 150, 150, 150, 151, 151, |
3109 | | 151, 151, 151, 151, 151, 151, 152, 152, |
3110 | | 152, 152, 152, 152, 152, 152, 153, 153, |
3111 | | 153, 153, 153, 153, 153, 153, 154, 154, |
3112 | | 154, 154, 154, 154, 154, 154, 154, 155, |
3113 | | 155, 155, 155, 155, 155, 155, 155, 155, |
3114 | | 156, 156, 156, 156, 156, 156, 156, 156, |
3115 | | 156, 157, 157, 157, 157, 157, 157, 157, |
3116 | | 157, 157, 157, 158, 158, 158, 158, 158, |
3117 | | 158, 158, 158, 158, 158, 158, 159, 159, |
3118 | | 159, 159, 159, 159, 159, 159, 159, 159, |
3119 | | 160, |
3120 | | }, |
3121 | | .len_sym_cost = 84, |
3122 | | }, |
3123 | | }; |
3124 | | |
3125 | | /* |
3126 | | * Choose the default costs for literal and length symbols. These symbols are |
3127 | | * both part of the litlen alphabet. |
3128 | | */ |
3129 | | static void |
3130 | | deflate_choose_default_litlen_costs(struct libdeflate_compressor *c, |
3131 | | const u8 *block_begin, u32 block_length, |
3132 | | u32 *lit_cost, u32 *len_sym_cost) |
3133 | 0 | { |
3134 | 0 | u32 num_used_literals = 0; |
3135 | 0 | u32 literal_freq = block_length; |
3136 | 0 | u32 match_freq = 0; |
3137 | 0 | u32 cutoff; |
3138 | 0 | u32 i; |
3139 | | |
3140 | | /* Calculate the number of distinct literals that exist in the data. */ |
3141 | 0 | memset(c->freqs.litlen, 0, |
3142 | 0 | DEFLATE_NUM_LITERALS * sizeof(c->freqs.litlen[0])); |
3143 | 0 | cutoff = literal_freq >> 11; /* Ignore literals used very rarely. */ |
3144 | 0 | for (i = 0; i < block_length; i++) |
3145 | 0 | c->freqs.litlen[block_begin[i]]++; |
3146 | 0 | for (i = 0; i < DEFLATE_NUM_LITERALS; i++) { |
3147 | 0 | if (c->freqs.litlen[i] > cutoff) |
3148 | 0 | num_used_literals++; |
3149 | 0 | } |
3150 | 0 | if (num_used_literals == 0) |
3151 | 0 | num_used_literals = 1; |
3152 | | |
3153 | | /* |
3154 | | * Estimate the relative frequency of literals and matches in the |
3155 | | * optimal parsing solution. We don't know the optimal solution, so |
3156 | | * this can only be a very rough estimate. Therefore, we basically use |
3157 | | * the match frequency from a greedy parse. We also apply the min_len |
3158 | | * heuristic used by the greedy and lazy parsers, to avoid counting too |
3159 | | * many matches when literals are cheaper than short matches. |
3160 | | */ |
3161 | 0 | match_freq = 0; |
3162 | 0 | i = choose_min_match_len(num_used_literals, c->max_search_depth); |
3163 | 0 | for (; i < ARRAY_LEN(c->p.n.match_len_freqs); i++) { |
3164 | 0 | match_freq += c->p.n.match_len_freqs[i]; |
3165 | 0 | literal_freq -= i * c->p.n.match_len_freqs[i]; |
3166 | 0 | } |
3167 | 0 | if ((s32)literal_freq < 0) /* shouldn't happen */ |
3168 | 0 | literal_freq = 0; |
3169 | |
|
3170 | 0 | if (match_freq > literal_freq) |
3171 | 0 | i = 2; /* many matches */ |
3172 | 0 | else if (match_freq * 4 > literal_freq) |
3173 | 0 | i = 1; /* neutral */ |
3174 | 0 | else |
3175 | 0 | i = 0; /* few matches */ |
3176 | |
|
3177 | 0 | STATIC_ASSERT(BIT_COST == 16); |
3178 | 0 | *lit_cost = default_litlen_costs[i].used_lits_to_lit_cost[ |
3179 | 0 | num_used_literals]; |
3180 | 0 | *len_sym_cost = default_litlen_costs[i].len_sym_cost; |
3181 | 0 | } |
3182 | | |
3183 | | static forceinline u32 |
3184 | | deflate_default_length_cost(u32 len, u32 len_sym_cost) |
3185 | 0 | { |
3186 | 0 | unsigned slot = deflate_length_slot[len]; |
3187 | 0 | u32 num_extra_bits = deflate_extra_length_bits[slot]; |
3188 | |
|
3189 | 0 | return len_sym_cost + (num_extra_bits * BIT_COST); |
3190 | 0 | } |
3191 | | |
3192 | | static forceinline u32 |
3193 | | deflate_default_offset_slot_cost(unsigned slot) |
3194 | 0 | { |
3195 | 0 | u32 num_extra_bits = deflate_extra_offset_bits[slot]; |
3196 | | /* |
3197 | | * Assume that all offset symbols are equally probable. |
3198 | | * The resulting cost is 'int(-log2(1/30) * BIT_COST)', |
3199 | | * where 30 is the number of potentially-used offset symbols. |
3200 | | */ |
3201 | 0 | u32 offset_sym_cost = 4*BIT_COST + (907*BIT_COST)/1000; |
3202 | |
|
3203 | 0 | return offset_sym_cost + (num_extra_bits * BIT_COST); |
3204 | 0 | } |
3205 | | |
3206 | | /* Set default symbol costs for the first block's first optimization pass. */ |
3207 | | static void |
3208 | | deflate_set_default_costs(struct libdeflate_compressor *c, |
3209 | | u32 lit_cost, u32 len_sym_cost) |
3210 | 0 | { |
3211 | 0 | u32 i; |
3212 | | |
3213 | | /* |
3214 | | * Also zero the entries that are never used, so that cost models can |
3215 | | * be compared with memcmp(). |
3216 | | */ |
3217 | 0 | memset(&c->p.n.costs, 0, sizeof(c->p.n.costs)); |
3218 | | |
3219 | | /* Literals */ |
3220 | 0 | for (i = 0; i < DEFLATE_NUM_LITERALS; i++) |
3221 | 0 | c->p.n.costs.literal[i] = lit_cost; |
3222 | | |
3223 | | /* Lengths */ |
3224 | 0 | for (i = DEFLATE_MIN_MATCH_LEN; i <= DEFLATE_MAX_MATCH_LEN; i++) |
3225 | 0 | c->p.n.costs.length[i] = |
3226 | 0 | deflate_default_length_cost(i, len_sym_cost); |
3227 | | |
3228 | | /* Offset slots */ |
3229 | 0 | for (i = 0; i < ARRAY_LEN(deflate_offset_slot_base); i++) |
3230 | 0 | c->p.n.costs.offset_slot[i] = |
3231 | 0 | deflate_default_offset_slot_cost(i); |
3232 | 0 | } |
3233 | | |
3234 | | static forceinline void |
3235 | | deflate_adjust_cost(u32 *cost_p, u32 default_cost, int change_amount) |
3236 | 0 | { |
3237 | 0 | if (change_amount == 0) |
3238 | | /* Block is very similar to previous; prefer previous costs. */ |
3239 | 0 | *cost_p = (default_cost + 3 * *cost_p) / 4; |
3240 | 0 | else if (change_amount == 1) |
3241 | 0 | *cost_p = (default_cost + *cost_p) / 2; |
3242 | 0 | else if (change_amount == 2) |
3243 | 0 | *cost_p = (5 * default_cost + 3 * *cost_p) / 8; |
3244 | 0 | else |
3245 | | /* Block differs greatly from previous; prefer default costs. */ |
3246 | 0 | *cost_p = (3 * default_cost + *cost_p) / 4; |
3247 | 0 | } |
3248 | | |
3249 | | static forceinline void |
3250 | | deflate_adjust_costs_impl(struct libdeflate_compressor *c, |
3251 | | u32 lit_cost, u32 len_sym_cost, int change_amount) |
3252 | 0 | { |
3253 | 0 | u32 i; |
3254 | | |
3255 | | /* Literals */ |
3256 | 0 | for (i = 0; i < DEFLATE_NUM_LITERALS; i++) |
3257 | 0 | deflate_adjust_cost(&c->p.n.costs.literal[i], lit_cost, |
3258 | 0 | change_amount); |
3259 | | |
3260 | | /* Lengths */ |
3261 | 0 | for (i = DEFLATE_MIN_MATCH_LEN; i <= DEFLATE_MAX_MATCH_LEN; i++) |
3262 | 0 | deflate_adjust_cost(&c->p.n.costs.length[i], |
3263 | 0 | deflate_default_length_cost(i, |
3264 | 0 | len_sym_cost), |
3265 | 0 | change_amount); |
3266 | | |
3267 | | /* Offset slots */ |
3268 | 0 | for (i = 0; i < ARRAY_LEN(deflate_offset_slot_base); i++) |
3269 | 0 | deflate_adjust_cost(&c->p.n.costs.offset_slot[i], |
3270 | 0 | deflate_default_offset_slot_cost(i), |
3271 | 0 | change_amount); |
3272 | 0 | } |
3273 | | |
3274 | | /* |
3275 | | * Adjust the costs when beginning a new block. |
3276 | | * |
3277 | | * Since the current costs are optimized for the data already, it can be helpful |
3278 | | * to reuse them instead of starting over with the default costs. However, this |
3279 | | * depends on how similar the new block is to the previous block. Therefore, |
3280 | | * use a heuristic to decide how similar the blocks are, and mix together the |
3281 | | * current costs and the default costs accordingly. |
3282 | | */ |
3283 | | static void |
3284 | | deflate_adjust_costs(struct libdeflate_compressor *c, |
3285 | | u32 lit_cost, u32 len_sym_cost) |
3286 | 0 | { |
3287 | 0 | u64 total_delta = 0; |
3288 | 0 | u64 cutoff; |
3289 | 0 | int i; |
3290 | | |
3291 | | /* |
3292 | | * Decide how different the current block is from the previous block, |
3293 | | * using the block splitting statistics from the current and previous |
3294 | | * blocks. The more different the current block is, the more we prefer |
3295 | | * the default costs rather than the previous block's costs. |
3296 | | * |
3297 | | * The algorithm here is similar to the end-of-block check one, but here |
3298 | | * we compare two entire blocks rather than a partial block with a small |
3299 | | * extra part, and therefore we need 64-bit numbers in some places. |
3300 | | */ |
3301 | 0 | for (i = 0; i < NUM_OBSERVATION_TYPES; i++) { |
3302 | 0 | u64 prev = (u64)c->p.n.prev_observations[i] * |
3303 | 0 | c->split_stats.num_observations; |
3304 | 0 | u64 cur = (u64)c->split_stats.observations[i] * |
3305 | 0 | c->p.n.prev_num_observations; |
3306 | |
|
3307 | 0 | total_delta += prev > cur ? prev - cur : cur - prev; |
3308 | 0 | } |
3309 | 0 | cutoff = ((u64)c->p.n.prev_num_observations * |
3310 | 0 | c->split_stats.num_observations * 200) / 512; |
3311 | |
|
3312 | 0 | if (total_delta > 3 * cutoff) |
3313 | | /* Big change in the data; just use the default costs. */ |
3314 | 0 | deflate_set_default_costs(c, lit_cost, len_sym_cost); |
3315 | 0 | else if (4 * total_delta > 9 * cutoff) |
3316 | 0 | deflate_adjust_costs_impl(c, lit_cost, len_sym_cost, 3); |
3317 | 0 | else if (2 * total_delta > 3 * cutoff) |
3318 | 0 | deflate_adjust_costs_impl(c, lit_cost, len_sym_cost, 2); |
3319 | 0 | else if (2 * total_delta > cutoff) |
3320 | 0 | deflate_adjust_costs_impl(c, lit_cost, len_sym_cost, 1); |
3321 | 0 | else |
3322 | 0 | deflate_adjust_costs_impl(c, lit_cost, len_sym_cost, 0); |
3323 | 0 | } |
3324 | | |
3325 | | static void |
3326 | | deflate_set_initial_costs(struct libdeflate_compressor *c, |
3327 | | const u8 *block_begin, u32 block_length, |
3328 | | bool is_first_block) |
3329 | 0 | { |
3330 | 0 | u32 lit_cost, len_sym_cost; |
3331 | |
|
3332 | 0 | deflate_choose_default_litlen_costs(c, block_begin, block_length, |
3333 | 0 | &lit_cost, &len_sym_cost); |
3334 | 0 | if (is_first_block) |
3335 | 0 | deflate_set_default_costs(c, lit_cost, len_sym_cost); |
3336 | 0 | else |
3337 | 0 | deflate_adjust_costs(c, lit_cost, len_sym_cost); |
3338 | 0 | } |
3339 | | |
3340 | | /* |
3341 | | * Find the minimum-cost path through the graph of possible match/literal |
3342 | | * choices for this block. |
3343 | | * |
3344 | | * We find the minimum cost path from 'c->p.n.optimum_nodes[0]', which |
3345 | | * represents the node at the beginning of the block, to |
3346 | | * 'c->p.n.optimum_nodes[block_length]', which represents the node at the end of |
3347 | | * the block. Edge costs are evaluated using the cost model 'c->p.n.costs'. |
3348 | | * |
3349 | | * The algorithm works backwards, starting at the end node and proceeding |
3350 | | * backwards one node at a time. At each node, the minimum cost to reach the |
3351 | | * end node is computed and the match/literal choice that begins that path is |
3352 | | * saved. |
3353 | | */ |
3354 | | static void |
3355 | | deflate_find_min_cost_path(struct libdeflate_compressor *c, |
3356 | | const u32 block_length, |
3357 | | const struct lz_match *cache_ptr) |
3358 | 0 | { |
3359 | 0 | struct deflate_optimum_node *end_node = |
3360 | 0 | &c->p.n.optimum_nodes[block_length]; |
3361 | 0 | struct deflate_optimum_node *cur_node = end_node; |
3362 | |
|
3363 | 0 | cur_node->cost_to_end = 0; |
3364 | 0 | do { |
3365 | 0 | unsigned num_matches; |
3366 | 0 | u32 literal; |
3367 | 0 | u32 best_cost_to_end; |
3368 | 0 | u32 best_item; |
3369 | |
|
3370 | 0 | cur_node--; |
3371 | 0 | cache_ptr--; |
3372 | |
|
3373 | 0 | num_matches = cache_ptr->length; |
3374 | 0 | literal = cache_ptr->offset; |
3375 | | |
3376 | | /* It's always possible to choose a literal. */ |
3377 | 0 | best_cost_to_end = c->p.n.costs.literal[literal] + |
3378 | 0 | (cur_node + 1)->cost_to_end; |
3379 | 0 | best_item = (literal << OPTIMUM_OFFSET_SHIFT) | 1; |
3380 | | |
3381 | | /* Also consider matches if there are any. */ |
3382 | 0 | if (num_matches) { |
3383 | 0 | const struct lz_match *match; |
3384 | 0 | u32 len; |
3385 | 0 | u32 offset; |
3386 | 0 | u32 offset_slot; |
3387 | 0 | u32 offset_cost; |
3388 | 0 | u32 cost_to_end; |
3389 | | |
3390 | | /* |
3391 | | * Consider each length from the minimum |
3392 | | * (DEFLATE_MIN_MATCH_LEN) to the length of the longest |
3393 | | * match found at this position. For each length, we |
3394 | | * consider only the smallest offset for which that |
3395 | | * length is available. Although this is not guaranteed |
3396 | | * to be optimal due to the possibility of a larger |
3397 | | * offset costing less than a smaller offset to code, |
3398 | | * this is a very useful heuristic. |
3399 | | */ |
3400 | 0 | match = cache_ptr - num_matches; |
3401 | 0 | len = DEFLATE_MIN_MATCH_LEN; |
3402 | 0 | do { |
3403 | 0 | u32 offset_bits; |
3404 | |
|
3405 | 0 | offset = match->offset; |
3406 | 0 | offset_slot = c->p.n.offset_slot_full[offset]; |
3407 | 0 | offset_cost = |
3408 | 0 | c->p.n.costs.offset_slot[offset_slot]; |
3409 | 0 | offset_bits = offset << OPTIMUM_OFFSET_SHIFT; |
3410 | 0 | do { |
3411 | 0 | bool better; |
3412 | |
|
3413 | 0 | cost_to_end = offset_cost + |
3414 | 0 | c->p.n.costs.length[len] + |
3415 | 0 | (cur_node + len)->cost_to_end; |
3416 | | /* |
3417 | | * Whether this is the best choice so |
3418 | | * far is hard to predict, so update the |
3419 | | * best choice without branching. |
3420 | | */ |
3421 | 0 | better = cost_to_end < best_cost_to_end; |
3422 | 0 | best_cost_to_end = better ? |
3423 | 0 | cost_to_end : best_cost_to_end; |
3424 | 0 | best_item = better ? |
3425 | 0 | (len | offset_bits) : best_item; |
3426 | 0 | } while (++len <= match->length); |
3427 | 0 | } while (++match != cache_ptr); |
3428 | 0 | cache_ptr -= num_matches; |
3429 | 0 | } |
3430 | 0 | cur_node->cost_to_end = best_cost_to_end; |
3431 | 0 | cur_node->item = best_item; |
3432 | 0 | } while (cur_node != &c->p.n.optimum_nodes[0]); |
3433 | |
|
3434 | 0 | deflate_reset_symbol_frequencies(c); |
3435 | 0 | deflate_tally_item_list(c, block_length); |
3436 | 0 | deflate_make_huffman_codes(&c->freqs, &c->codes); |
3437 | 0 | } |
3438 | | |
3439 | | /* |
3440 | | * Choose the literals and matches for the current block, then output the block. |
3441 | | * |
3442 | | * To choose the literal/match sequence, we find the minimum-cost path through |
3443 | | * the block's graph of literal/match choices, given a cost model. However, the |
3444 | | * true cost of each symbol is unknown until the Huffman codes have been built, |
3445 | | * but at the same time the Huffman codes depend on the frequencies of chosen |
3446 | | * symbols. Consequently, multiple passes must be used to try to approximate an |
3447 | | * optimal solution. The first pass uses default costs, mixed with the costs |
3448 | | * from the previous block when it seems appropriate. Later passes use the |
3449 | | * Huffman codeword lengths from the previous pass as the costs. |
3450 | | * |
3451 | | * As an alternate strategy, also consider using only literals. The boolean |
3452 | | * returned in *used_only_literals indicates whether that strategy was best. |
3453 | | */ |
3454 | | static void |
3455 | | deflate_optimize_and_flush_block(struct libdeflate_compressor *c, |
3456 | | struct deflate_output_bitstream *os, |
3457 | | const u8 *block_begin, u32 block_length, |
3458 | | const struct lz_match *cache_ptr, |
3459 | | bool is_first_block, bool is_final_block, |
3460 | | bool *used_only_literals) |
3461 | 0 | { |
3462 | 0 | unsigned num_passes_remaining = c->p.n.max_optim_passes; |
3463 | 0 | u32 best_true_cost = UINT32_MAX; |
3464 | 0 | u32 true_cost; |
3465 | 0 | u32 only_lits_cost; |
3466 | 0 | u32 static_cost = UINT32_MAX; |
3467 | 0 | struct deflate_sequence seq_; |
3468 | 0 | struct deflate_sequence *seq = NULL; |
3469 | 0 | u32 i; |
3470 | | |
3471 | | /* |
3472 | | * On some data, using only literals (no matches) ends up being better |
3473 | | * than what the iterative optimization algorithm produces. Therefore, |
3474 | | * consider using only literals. |
3475 | | */ |
3476 | 0 | deflate_choose_all_literals(c, block_begin, block_length); |
3477 | 0 | only_lits_cost = deflate_compute_true_cost(c); |
3478 | | |
3479 | | /* |
3480 | | * Force the block to really end at the desired length, even if some |
3481 | | * matches extend beyond it. |
3482 | | */ |
3483 | 0 | for (i = block_length; |
3484 | 0 | i <= MIN(block_length - 1 + DEFLATE_MAX_MATCH_LEN, |
3485 | 0 | ARRAY_LEN(c->p.n.optimum_nodes) - 1); i++) |
3486 | 0 | c->p.n.optimum_nodes[i].cost_to_end = 0x80000000; |
3487 | | |
3488 | | /* |
3489 | | * Sometimes a static Huffman block ends up being cheapest, particularly |
3490 | | * if the block is small. So, if the block is sufficiently small, find |
3491 | | * the optimal static block solution and remember its cost. |
3492 | | */ |
3493 | 0 | if (block_length <= c->p.n.max_len_to_optimize_static_block) { |
3494 | | /* Save c->p.n.costs temporarily. */ |
3495 | 0 | c->p.n.costs_saved = c->p.n.costs; |
3496 | |
|
3497 | 0 | deflate_set_costs_from_codes(c, &c->static_codes.lens); |
3498 | 0 | deflate_find_min_cost_path(c, block_length, cache_ptr); |
3499 | 0 | static_cost = c->p.n.optimum_nodes[0].cost_to_end / BIT_COST; |
3500 | 0 | static_cost += 7; /* for the end-of-block symbol */ |
3501 | | |
3502 | | /* Restore c->p.n.costs. */ |
3503 | 0 | c->p.n.costs = c->p.n.costs_saved; |
3504 | 0 | } |
3505 | | |
3506 | | /* Initialize c->p.n.costs with default costs. */ |
3507 | 0 | deflate_set_initial_costs(c, block_begin, block_length, is_first_block); |
3508 | |
|
3509 | 0 | do { |
3510 | | /* |
3511 | | * Find the minimum-cost path for this pass. |
3512 | | * Also set c->freqs and c->codes to match the path. |
3513 | | */ |
3514 | 0 | deflate_find_min_cost_path(c, block_length, cache_ptr); |
3515 | | |
3516 | | /* |
3517 | | * Compute the exact cost of the block if the path were to be |
3518 | | * used. Note that this differs from |
3519 | | * c->p.n.optimum_nodes[0].cost_to_end in that true_cost uses |
3520 | | * the actual Huffman codes instead of c->p.n.costs. |
3521 | | */ |
3522 | 0 | true_cost = deflate_compute_true_cost(c); |
3523 | | |
3524 | | /* |
3525 | | * If the cost didn't improve much from the previous pass, then |
3526 | | * doing more passes probably won't be helpful, so stop early. |
3527 | | */ |
3528 | 0 | if (true_cost + c->p.n.min_improvement_to_continue > |
3529 | 0 | best_true_cost) |
3530 | 0 | break; |
3531 | | |
3532 | 0 | best_true_cost = true_cost; |
3533 | | |
3534 | | /* Save the cost model that gave 'best_true_cost'. */ |
3535 | 0 | c->p.n.costs_saved = c->p.n.costs; |
3536 | | |
3537 | | /* Update the cost model from the Huffman codes. */ |
3538 | 0 | deflate_set_costs_from_codes(c, &c->codes.lens); |
3539 | | |
3540 | | /* |
3541 | | * If the cost model didn't change, then another pass would just |
3542 | | * find the same path again, and then stop because the cost |
3543 | | * didn't improve. Skip that pass. |
3544 | | */ |
3545 | 0 | if (memcmp(&c->p.n.costs, &c->p.n.costs_saved, |
3546 | 0 | sizeof(c->p.n.costs)) == 0) |
3547 | 0 | break; |
3548 | 0 | } while (--num_passes_remaining); |
3549 | |
|
3550 | 0 | *used_only_literals = false; |
3551 | 0 | if (MIN(only_lits_cost, static_cost) < best_true_cost) { |
3552 | 0 | if (only_lits_cost < static_cost) { |
3553 | | /* Using only literals ended up being best! */ |
3554 | 0 | deflate_choose_all_literals(c, block_begin, block_length); |
3555 | 0 | deflate_set_costs_from_codes(c, &c->codes.lens); |
3556 | 0 | seq_.litrunlen_and_length = block_length; |
3557 | 0 | seq = &seq_; |
3558 | 0 | *used_only_literals = true; |
3559 | 0 | } else { |
3560 | | /* Static block ended up being best! */ |
3561 | 0 | deflate_set_costs_from_codes(c, &c->static_codes.lens); |
3562 | 0 | deflate_find_min_cost_path(c, block_length, cache_ptr); |
3563 | 0 | } |
3564 | 0 | } else if (true_cost >= |
3565 | 0 | best_true_cost + c->p.n.min_bits_to_use_nonfinal_path) { |
3566 | | /* |
3567 | | * The best solution was actually from a non-final optimization |
3568 | | * pass, so recover and use the min-cost path from that pass. |
3569 | | */ |
3570 | 0 | c->p.n.costs = c->p.n.costs_saved; |
3571 | 0 | deflate_find_min_cost_path(c, block_length, cache_ptr); |
3572 | 0 | deflate_set_costs_from_codes(c, &c->codes.lens); |
3573 | 0 | } |
3574 | 0 | deflate_flush_block(c, os, block_begin, block_length, seq, |
3575 | 0 | is_final_block); |
3576 | 0 | } |
3577 | | |
3578 | | static void |
3579 | | deflate_near_optimal_init_stats(struct libdeflate_compressor *c) |
3580 | 0 | { |
3581 | 0 | init_block_split_stats(&c->split_stats); |
3582 | 0 | memset(c->p.n.new_match_len_freqs, 0, |
3583 | 0 | sizeof(c->p.n.new_match_len_freqs)); |
3584 | 0 | memset(c->p.n.match_len_freqs, 0, sizeof(c->p.n.match_len_freqs)); |
3585 | 0 | } |
3586 | | |
3587 | | static void |
3588 | | deflate_near_optimal_merge_stats(struct libdeflate_compressor *c) |
3589 | 0 | { |
3590 | 0 | unsigned i; |
3591 | |
|
3592 | 0 | merge_new_observations(&c->split_stats); |
3593 | 0 | for (i = 0; i < ARRAY_LEN(c->p.n.match_len_freqs); i++) { |
3594 | 0 | c->p.n.match_len_freqs[i] += c->p.n.new_match_len_freqs[i]; |
3595 | 0 | c->p.n.new_match_len_freqs[i] = 0; |
3596 | 0 | } |
3597 | 0 | } |
3598 | | |
3599 | | /* |
3600 | | * Save some literal/match statistics from the previous block so that |
3601 | | * deflate_adjust_costs() will be able to decide how much the current block |
3602 | | * differs from the previous one. |
3603 | | */ |
3604 | | static void |
3605 | | deflate_near_optimal_save_stats(struct libdeflate_compressor *c) |
3606 | 0 | { |
3607 | 0 | int i; |
3608 | |
|
3609 | 0 | for (i = 0; i < NUM_OBSERVATION_TYPES; i++) |
3610 | 0 | c->p.n.prev_observations[i] = c->split_stats.observations[i]; |
3611 | 0 | c->p.n.prev_num_observations = c->split_stats.num_observations; |
3612 | 0 | } |
3613 | | |
3614 | | static void |
3615 | | deflate_near_optimal_clear_old_stats(struct libdeflate_compressor *c) |
3616 | 0 | { |
3617 | 0 | int i; |
3618 | |
|
3619 | 0 | for (i = 0; i < NUM_OBSERVATION_TYPES; i++) |
3620 | 0 | c->split_stats.observations[i] = 0; |
3621 | 0 | c->split_stats.num_observations = 0; |
3622 | 0 | memset(c->p.n.match_len_freqs, 0, sizeof(c->p.n.match_len_freqs)); |
3623 | 0 | } |
3624 | | |
3625 | | /* |
3626 | | * This is the "near-optimal" DEFLATE compressor. It computes the optimal |
3627 | | * representation of each DEFLATE block using a minimum-cost path search over |
3628 | | * the graph of possible match/literal choices for that block, assuming a |
3629 | | * certain cost for each Huffman symbol. |
3630 | | * |
3631 | | * For several reasons, the end result is not guaranteed to be optimal: |
3632 | | * |
3633 | | * - Nonoptimal choice of blocks |
3634 | | * - Heuristic limitations on which matches are actually considered |
3635 | | * - Symbol costs are unknown until the symbols have already been chosen |
3636 | | * (so iterative optimization must be used) |
3637 | | */ |
3638 | | static void |
3639 | | deflate_compress_near_optimal(struct libdeflate_compressor * restrict c, |
3640 | | const u8 *in, size_t in_nbytes, |
3641 | | struct deflate_output_bitstream *os) |
3642 | 0 | { |
3643 | 0 | const u8 *in_next = in; |
3644 | 0 | const u8 *in_block_begin = in_next; |
3645 | 0 | const u8 *in_end = in_next + in_nbytes; |
3646 | 0 | const u8 *in_cur_base = in_next; |
3647 | 0 | const u8 *in_next_slide = |
3648 | 0 | in_next + MIN(in_end - in_next, MATCHFINDER_WINDOW_SIZE); |
3649 | 0 | u32 max_len = DEFLATE_MAX_MATCH_LEN; |
3650 | 0 | u32 nice_len = MIN(c->nice_match_length, max_len); |
3651 | 0 | struct lz_match *cache_ptr = c->p.n.match_cache; |
3652 | 0 | u32 next_hashes[2] = {0, 0}; |
3653 | 0 | bool prev_block_used_only_literals = false; |
3654 | |
|
3655 | 0 | bt_matchfinder_init(&c->p.n.bt_mf); |
3656 | 0 | deflate_near_optimal_init_stats(c); |
3657 | |
|
3658 | 0 | do { |
3659 | | /* Starting a new DEFLATE block */ |
3660 | 0 | const u8 * const in_max_block_end = choose_max_block_end( |
3661 | 0 | in_block_begin, in_end, SOFT_MAX_BLOCK_LENGTH); |
3662 | 0 | const u8 *prev_end_block_check = NULL; |
3663 | 0 | bool change_detected = false; |
3664 | 0 | const u8 *next_observation = in_next; |
3665 | 0 | u32 min_len; |
3666 | | |
3667 | | /* |
3668 | | * Use the minimum match length heuristic to improve the |
3669 | | * literal/match statistics gathered during matchfinding. |
3670 | | * However, the actual near-optimal parse won't respect min_len, |
3671 | | * as it can accurately assess the costs of different matches. |
3672 | | * |
3673 | | * If the "use only literals" strategy happened to be the best |
3674 | | * strategy on the previous block, then probably the |
3675 | | * min_match_len heuristic is still not aggressive enough for |
3676 | | * the data, so force gathering literal stats only. |
3677 | | */ |
3678 | 0 | if (prev_block_used_only_literals) |
3679 | 0 | min_len = DEFLATE_MAX_MATCH_LEN + 1; |
3680 | 0 | else |
3681 | 0 | min_len = calculate_min_match_len( |
3682 | 0 | in_block_begin, |
3683 | 0 | in_max_block_end - in_block_begin, |
3684 | 0 | c->max_search_depth); |
3685 | | |
3686 | | /* |
3687 | | * Find matches until we decide to end the block. We end the |
3688 | | * block if any of the following is true: |
3689 | | * |
3690 | | * (1) Maximum block length has been reached |
3691 | | * (2) Match catch may overflow. |
3692 | | * (3) Block split heuristic says to split now. |
3693 | | */ |
3694 | 0 | for (;;) { |
3695 | 0 | struct lz_match *matches; |
3696 | 0 | u32 best_len; |
3697 | 0 | size_t remaining = in_end - in_next; |
3698 | | |
3699 | | /* Slide the window forward if needed. */ |
3700 | 0 | if (in_next == in_next_slide) { |
3701 | 0 | bt_matchfinder_slide_window(&c->p.n.bt_mf); |
3702 | 0 | in_cur_base = in_next; |
3703 | 0 | in_next_slide = in_next + |
3704 | 0 | MIN(remaining, MATCHFINDER_WINDOW_SIZE); |
3705 | 0 | } |
3706 | | |
3707 | | /* |
3708 | | * Find matches with the current position using the |
3709 | | * binary tree matchfinder and save them in match_cache. |
3710 | | * |
3711 | | * Note: the binary tree matchfinder is more suited for |
3712 | | * optimal parsing than the hash chain matchfinder. The |
3713 | | * reasons for this include: |
3714 | | * |
3715 | | * - The binary tree matchfinder can find more matches |
3716 | | * in the same number of steps. |
3717 | | * - One of the major advantages of hash chains is that |
3718 | | * skipping positions (not searching for matches at |
3719 | | * them) is faster; however, with optimal parsing we |
3720 | | * search for matches at almost all positions, so this |
3721 | | * advantage of hash chains is negated. |
3722 | | */ |
3723 | 0 | matches = cache_ptr; |
3724 | 0 | best_len = 0; |
3725 | 0 | adjust_max_and_nice_len(&max_len, &nice_len, remaining); |
3726 | 0 | if (likely(max_len >= BT_MATCHFINDER_REQUIRED_NBYTES)) { |
3727 | 0 | cache_ptr = bt_matchfinder_get_matches( |
3728 | 0 | &c->p.n.bt_mf, |
3729 | 0 | in_cur_base, |
3730 | 0 | in_next - in_cur_base, |
3731 | 0 | max_len, |
3732 | 0 | nice_len, |
3733 | 0 | c->max_search_depth, |
3734 | 0 | next_hashes, |
3735 | 0 | matches); |
3736 | 0 | if (cache_ptr > matches) |
3737 | 0 | best_len = cache_ptr[-1].length; |
3738 | 0 | } |
3739 | 0 | if (in_next >= next_observation) { |
3740 | 0 | if (best_len >= min_len) { |
3741 | 0 | observe_match(&c->split_stats, |
3742 | 0 | best_len); |
3743 | 0 | next_observation = in_next + best_len; |
3744 | 0 | c->p.n.new_match_len_freqs[best_len]++; |
3745 | 0 | } else { |
3746 | 0 | observe_literal(&c->split_stats, |
3747 | 0 | *in_next); |
3748 | 0 | next_observation = in_next + 1; |
3749 | 0 | } |
3750 | 0 | } |
3751 | |
|
3752 | 0 | cache_ptr->length = cache_ptr - matches; |
3753 | 0 | cache_ptr->offset = *in_next; |
3754 | 0 | in_next++; |
3755 | 0 | cache_ptr++; |
3756 | | |
3757 | | /* |
3758 | | * If there was a very long match found, don't cache any |
3759 | | * matches for the bytes covered by that match. This |
3760 | | * avoids degenerate behavior when compressing highly |
3761 | | * redundant data, where the number of matches can be |
3762 | | * very large. |
3763 | | * |
3764 | | * This heuristic doesn't actually hurt the compression |
3765 | | * ratio very much. If there's a long match, then the |
3766 | | * data must be highly compressible, so it doesn't |
3767 | | * matter much what we do. |
3768 | | */ |
3769 | 0 | if (best_len >= DEFLATE_MIN_MATCH_LEN && |
3770 | 0 | best_len >= nice_len) { |
3771 | 0 | --best_len; |
3772 | 0 | do { |
3773 | 0 | remaining = in_end - in_next; |
3774 | 0 | if (in_next == in_next_slide) { |
3775 | 0 | bt_matchfinder_slide_window( |
3776 | 0 | &c->p.n.bt_mf); |
3777 | 0 | in_cur_base = in_next; |
3778 | 0 | in_next_slide = in_next + |
3779 | 0 | MIN(remaining, |
3780 | 0 | MATCHFINDER_WINDOW_SIZE); |
3781 | 0 | } |
3782 | 0 | adjust_max_and_nice_len(&max_len, |
3783 | 0 | &nice_len, |
3784 | 0 | remaining); |
3785 | 0 | if (max_len >= |
3786 | 0 | BT_MATCHFINDER_REQUIRED_NBYTES) { |
3787 | 0 | bt_matchfinder_skip_byte( |
3788 | 0 | &c->p.n.bt_mf, |
3789 | 0 | in_cur_base, |
3790 | 0 | in_next - in_cur_base, |
3791 | 0 | nice_len, |
3792 | 0 | c->max_search_depth, |
3793 | 0 | next_hashes); |
3794 | 0 | } |
3795 | 0 | cache_ptr->length = 0; |
3796 | 0 | cache_ptr->offset = *in_next; |
3797 | 0 | in_next++; |
3798 | 0 | cache_ptr++; |
3799 | 0 | } while (--best_len); |
3800 | 0 | } |
3801 | | /* Maximum block length or end of input reached? */ |
3802 | 0 | if (in_next >= in_max_block_end) |
3803 | 0 | break; |
3804 | | /* Match cache overflowed? */ |
3805 | 0 | if (cache_ptr >= |
3806 | 0 | &c->p.n.match_cache[MATCH_CACHE_LENGTH]) |
3807 | 0 | break; |
3808 | | /* Not ready to try to end the block (again)? */ |
3809 | 0 | if (!ready_to_check_block(&c->split_stats, |
3810 | 0 | in_block_begin, in_next, |
3811 | 0 | in_end)) |
3812 | 0 | continue; |
3813 | | /* Check if it would be worthwhile to end the block. */ |
3814 | 0 | if (do_end_block_check(&c->split_stats, |
3815 | 0 | in_next - in_block_begin)) { |
3816 | 0 | change_detected = true; |
3817 | 0 | break; |
3818 | 0 | } |
3819 | | /* Ending the block doesn't seem worthwhile here. */ |
3820 | 0 | deflate_near_optimal_merge_stats(c); |
3821 | 0 | prev_end_block_check = in_next; |
3822 | 0 | } |
3823 | | /* |
3824 | | * All the matches for this block have been cached. Now choose |
3825 | | * the precise end of the block and the sequence of items to |
3826 | | * output to represent it, then flush the block. |
3827 | | */ |
3828 | 0 | if (change_detected && prev_end_block_check != NULL) { |
3829 | | /* |
3830 | | * The block is being ended because a recent chunk of |
3831 | | * data differs from the rest of the block. We could |
3832 | | * end the block at 'in_next' like the greedy and lazy |
3833 | | * compressors do, but that's not ideal since it would |
3834 | | * include the differing chunk in the block. The |
3835 | | * near-optimal compressor has time to do a better job. |
3836 | | * Therefore, we rewind to just before the chunk, and |
3837 | | * output a block that only goes up to there. |
3838 | | * |
3839 | | * We then set things up to correctly start the next |
3840 | | * block, considering that some work has already been |
3841 | | * done on it (some matches found and stats gathered). |
3842 | | */ |
3843 | 0 | struct lz_match *orig_cache_ptr = cache_ptr; |
3844 | 0 | const u8 *in_block_end = prev_end_block_check; |
3845 | 0 | u32 block_length = in_block_end - in_block_begin; |
3846 | 0 | bool is_first = (in_block_begin == in); |
3847 | 0 | bool is_final = false; |
3848 | 0 | u32 num_bytes_to_rewind = in_next - in_block_end; |
3849 | 0 | size_t cache_len_rewound; |
3850 | | |
3851 | | /* Rewind the match cache. */ |
3852 | 0 | do { |
3853 | 0 | cache_ptr--; |
3854 | 0 | cache_ptr -= cache_ptr->length; |
3855 | 0 | } while (--num_bytes_to_rewind); |
3856 | 0 | cache_len_rewound = orig_cache_ptr - cache_ptr; |
3857 | |
|
3858 | 0 | deflate_optimize_and_flush_block( |
3859 | 0 | c, os, in_block_begin, |
3860 | 0 | block_length, cache_ptr, |
3861 | 0 | is_first, is_final, |
3862 | 0 | &prev_block_used_only_literals); |
3863 | 0 | memmove(c->p.n.match_cache, cache_ptr, |
3864 | 0 | cache_len_rewound * sizeof(*cache_ptr)); |
3865 | 0 | cache_ptr = &c->p.n.match_cache[cache_len_rewound]; |
3866 | 0 | deflate_near_optimal_save_stats(c); |
3867 | | /* |
3868 | | * Clear the stats for the just-flushed block, leaving |
3869 | | * just the stats for the beginning of the next block. |
3870 | | */ |
3871 | 0 | deflate_near_optimal_clear_old_stats(c); |
3872 | 0 | in_block_begin = in_block_end; |
3873 | 0 | } else { |
3874 | | /* |
3875 | | * The block is being ended for a reason other than a |
3876 | | * differing data chunk being detected. Don't rewind at |
3877 | | * all; just end the block at the current position. |
3878 | | */ |
3879 | 0 | u32 block_length = in_next - in_block_begin; |
3880 | 0 | bool is_first = (in_block_begin == in); |
3881 | 0 | bool is_final = (in_next == in_end); |
3882 | |
|
3883 | 0 | deflate_near_optimal_merge_stats(c); |
3884 | 0 | deflate_optimize_and_flush_block( |
3885 | 0 | c, os, in_block_begin, |
3886 | 0 | block_length, cache_ptr, |
3887 | 0 | is_first, is_final, |
3888 | 0 | &prev_block_used_only_literals); |
3889 | 0 | cache_ptr = &c->p.n.match_cache[0]; |
3890 | 0 | deflate_near_optimal_save_stats(c); |
3891 | 0 | deflate_near_optimal_init_stats(c); |
3892 | 0 | in_block_begin = in_next; |
3893 | 0 | } |
3894 | 0 | } while (in_next != in_end && !os->overflow); |
3895 | 0 | } |
3896 | | |
3897 | | /* Initialize c->p.n.offset_slot_full. */ |
3898 | | static void |
3899 | | deflate_init_offset_slot_full(struct libdeflate_compressor *c) |
3900 | 0 | { |
3901 | 0 | u32 offset_slot; |
3902 | 0 | u32 offset; |
3903 | 0 | u32 offset_end; |
3904 | |
|
3905 | 0 | for (offset_slot = 0; offset_slot < ARRAY_LEN(deflate_offset_slot_base); |
3906 | 0 | offset_slot++) { |
3907 | 0 | offset = deflate_offset_slot_base[offset_slot]; |
3908 | 0 | offset_end = offset + |
3909 | 0 | (1 << deflate_extra_offset_bits[offset_slot]); |
3910 | 0 | do { |
3911 | 0 | c->p.n.offset_slot_full[offset] = offset_slot; |
3912 | 0 | } while (++offset != offset_end); |
3913 | 0 | } |
3914 | 0 | } |
3915 | | |
3916 | | #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */ |
3917 | | |
3918 | | LIBDEFLATEAPI struct libdeflate_compressor * |
3919 | | libdeflate_alloc_compressor_ex(int compression_level, |
3920 | | const struct libdeflate_options *options) |
3921 | 1.49k | { |
3922 | 1.49k | struct libdeflate_compressor *c; |
3923 | 1.49k | size_t size = offsetof(struct libdeflate_compressor, p); |
3924 | | |
3925 | 1.49k | check_buildtime_parameters(); |
3926 | | |
3927 | | /* |
3928 | | * Note: if more fields are added to libdeflate_options, this code will |
3929 | | * need to be updated to support both the old and new structs. |
3930 | | */ |
3931 | 1.49k | if (options->sizeof_options != sizeof(*options)) |
3932 | 0 | return NULL; |
3933 | | |
3934 | | /* |
3935 | | * Note: For similarity with zlib's API, -1 is accepted as an alias for |
3936 | | * the default compression level. |
3937 | | */ |
3938 | 1.49k | if (compression_level == -1) |
3939 | 0 | compression_level = 6; |
3940 | | |
3941 | 1.49k | if (compression_level < 0 || compression_level > 12) |
3942 | 0 | return NULL; |
3943 | | |
3944 | 1.49k | #if SUPPORT_NEAR_OPTIMAL_PARSING |
3945 | 1.49k | if (compression_level >= 10) |
3946 | 0 | size += sizeof(c->p.n); |
3947 | 1.49k | else |
3948 | 1.49k | #endif |
3949 | 1.49k | { |
3950 | 1.49k | if (compression_level >= 2) { |
3951 | | /* Levels 5 and higher use the lazy compressors. */ |
3952 | 1.49k | size = offsetof(struct libdeflate_compressor, |
3953 | 1.49k | p.g.hc_mf) + |
3954 | 1.49k | hc_matchfinder_size(compression_level >= 5 ? |
3955 | 1.49k | LAZY_MULTI_HOP : |
3956 | 1.49k | GREEDY_MULTI_HOP); |
3957 | 1.49k | } else if (compression_level == 1) { |
3958 | 0 | size += sizeof(c->p.f); |
3959 | 0 | } |
3960 | 1.49k | } |
3961 | | |
3962 | 1.49k | c = libdeflate_aligned_malloc(options->malloc_func ? |
3963 | 0 | options->malloc_func : |
3964 | 1.49k | libdeflate_default_malloc_func, |
3965 | 1.49k | MATCHFINDER_MEM_ALIGNMENT, size); |
3966 | 1.49k | if (!c) |
3967 | 0 | return NULL; |
3968 | 1.49k | c->free_func = options->free_func ? |
3969 | 1.49k | options->free_func : libdeflate_default_free_func; |
3970 | | |
3971 | 1.49k | c->compression_level = compression_level; |
3972 | | |
3973 | | /* |
3974 | | * The higher the compression level, the more we should bother trying to |
3975 | | * compress very small inputs. |
3976 | | */ |
3977 | 1.49k | c->max_passthrough_size = 55 - (compression_level * 4); |
3978 | | |
3979 | 1.49k | switch (compression_level) { |
3980 | 0 | case 0: |
3981 | 0 | c->max_passthrough_size = SIZE_MAX; |
3982 | 0 | c->impl = NULL; /* not used */ |
3983 | 0 | break; |
3984 | 0 | case 1: |
3985 | 0 | c->impl = deflate_compress_fastest; |
3986 | | /* max_search_depth is unused. */ |
3987 | 0 | c->nice_match_length = 32; |
3988 | 0 | break; |
3989 | 0 | case 2: |
3990 | 0 | c->impl = deflate_compress_greedy; |
3991 | 0 | c->max_search_depth = 6; |
3992 | 0 | c->nice_match_length = 10; |
3993 | 0 | break; |
3994 | 0 | case 3: |
3995 | 0 | c->impl = deflate_compress_greedy; |
3996 | 0 | c->max_search_depth = 12; |
3997 | 0 | c->nice_match_length = 14; |
3998 | 0 | break; |
3999 | 0 | case 4: |
4000 | 0 | c->impl = deflate_compress_greedy; |
4001 | 0 | c->max_search_depth = 16; |
4002 | 0 | c->nice_match_length = 30; |
4003 | 0 | break; |
4004 | 0 | case 5: |
4005 | 0 | c->impl = deflate_compress_lazy; |
4006 | 0 | c->max_search_depth = 16; |
4007 | 0 | c->nice_match_length = 30; |
4008 | 0 | break; |
4009 | 0 | case 6: |
4010 | 0 | c->impl = deflate_compress_lazy; |
4011 | 0 | c->max_search_depth = 35; |
4012 | 0 | c->nice_match_length = 65; |
4013 | 0 | break; |
4014 | 0 | case 7: |
4015 | 0 | c->impl = deflate_compress_lazy; |
4016 | 0 | c->max_search_depth = 100; |
4017 | 0 | c->nice_match_length = 130; |
4018 | 0 | break; |
4019 | 1.49k | case 8: |
4020 | 1.49k | c->impl = deflate_compress_lazy2; |
4021 | 1.49k | c->max_search_depth = 300; |
4022 | 1.49k | c->nice_match_length = DEFLATE_MAX_MATCH_LEN; |
4023 | 1.49k | break; |
4024 | 0 | case 9: |
4025 | | #if !SUPPORT_NEAR_OPTIMAL_PARSING |
4026 | | default: |
4027 | | #endif |
4028 | 0 | c->impl = deflate_compress_lazy2; |
4029 | 0 | c->max_search_depth = 600; |
4030 | 0 | c->nice_match_length = DEFLATE_MAX_MATCH_LEN; |
4031 | 0 | break; |
4032 | 0 | #if SUPPORT_NEAR_OPTIMAL_PARSING |
4033 | 0 | case 10: |
4034 | 0 | c->impl = deflate_compress_near_optimal; |
4035 | 0 | c->max_search_depth = 35; |
4036 | 0 | c->nice_match_length = 75; |
4037 | 0 | c->p.n.max_optim_passes = 2; |
4038 | 0 | c->p.n.min_improvement_to_continue = 32; |
4039 | 0 | c->p.n.min_bits_to_use_nonfinal_path = 32; |
4040 | 0 | c->p.n.max_len_to_optimize_static_block = 0; |
4041 | 0 | deflate_init_offset_slot_full(c); |
4042 | 0 | break; |
4043 | 0 | case 11: |
4044 | 0 | c->impl = deflate_compress_near_optimal; |
4045 | 0 | c->max_search_depth = 100; |
4046 | 0 | c->nice_match_length = 150; |
4047 | 0 | c->p.n.max_optim_passes = 4; |
4048 | 0 | c->p.n.min_improvement_to_continue = 16; |
4049 | 0 | c->p.n.min_bits_to_use_nonfinal_path = 16; |
4050 | 0 | c->p.n.max_len_to_optimize_static_block = 1000; |
4051 | 0 | deflate_init_offset_slot_full(c); |
4052 | 0 | break; |
4053 | 0 | case 12: |
4054 | 0 | default: |
4055 | 0 | c->impl = deflate_compress_near_optimal; |
4056 | 0 | c->max_search_depth = 300; |
4057 | 0 | c->nice_match_length = DEFLATE_MAX_MATCH_LEN; |
4058 | 0 | c->p.n.max_optim_passes = 10; |
4059 | 0 | c->p.n.min_improvement_to_continue = 1; |
4060 | 0 | c->p.n.min_bits_to_use_nonfinal_path = 1; |
4061 | 0 | c->p.n.max_len_to_optimize_static_block = 10000; |
4062 | 0 | deflate_init_offset_slot_full(c); |
4063 | 0 | break; |
4064 | 1.49k | #endif /* SUPPORT_NEAR_OPTIMAL_PARSING */ |
4065 | 1.49k | } |
4066 | | |
4067 | 1.49k | deflate_init_static_codes(c); |
4068 | | |
4069 | 1.49k | return c; |
4070 | 1.49k | } |
4071 | | |
4072 | | |
4073 | | LIBDEFLATEAPI struct libdeflate_compressor * |
4074 | | libdeflate_alloc_compressor(int compression_level) |
4075 | 1.49k | { |
4076 | 1.49k | static const struct libdeflate_options defaults = { |
4077 | 1.49k | .sizeof_options = sizeof(defaults), |
4078 | 1.49k | }; |
4079 | 1.49k | return libdeflate_alloc_compressor_ex(compression_level, &defaults); |
4080 | 1.49k | } |
4081 | | |
4082 | | LIBDEFLATEAPI size_t |
4083 | | libdeflate_deflate_compress(struct libdeflate_compressor *c, |
4084 | | const void *in, size_t in_nbytes, |
4085 | | void *out, size_t out_nbytes_avail) |
4086 | 1.93k | { |
4087 | 1.93k | struct deflate_output_bitstream os; |
4088 | | |
4089 | | /* |
4090 | | * For extremely short inputs, or for compression level 0, just output |
4091 | | * uncompressed blocks. |
4092 | | */ |
4093 | 1.93k | if (unlikely(in_nbytes <= c->max_passthrough_size)) |
4094 | 110 | return deflate_compress_none(in, in_nbytes, |
4095 | 110 | out, out_nbytes_avail); |
4096 | | |
4097 | | /* Initialize the output bitstream structure. */ |
4098 | 1.82k | os.bitbuf = 0; |
4099 | 1.82k | os.bitcount = 0; |
4100 | 1.82k | os.next = out; |
4101 | 1.82k | os.end = os.next + out_nbytes_avail; |
4102 | 1.82k | os.overflow = false; |
4103 | | |
4104 | | /* Call the actual compression function. */ |
4105 | 1.82k | (*c->impl)(c, in, in_nbytes, &os); |
4106 | | |
4107 | | /* Return 0 if the output buffer is too small. */ |
4108 | 1.82k | if (os.overflow) |
4109 | 0 | return 0; |
4110 | | |
4111 | | /* |
4112 | | * Write the final byte if needed. This can't overflow the output |
4113 | | * buffer because deflate_flush_block() would have set the overflow flag |
4114 | | * if there wasn't enough space remaining for the full final block. |
4115 | | */ |
4116 | 1.82k | ASSERT(os.bitcount <= 7); |
4117 | 1.82k | if (os.bitcount) { |
4118 | 1.60k | ASSERT(os.next < os.end); |
4119 | 1.60k | *os.next++ = os.bitbuf; |
4120 | 1.60k | } |
4121 | | |
4122 | | /* Return the compressed size in bytes. */ |
4123 | 1.82k | return os.next - (u8 *)out; |
4124 | 1.82k | } |
4125 | | |
4126 | | LIBDEFLATEAPI void |
4127 | | libdeflate_free_compressor(struct libdeflate_compressor *c) |
4128 | 1.49k | { |
4129 | 1.49k | if (c) |
4130 | 1.49k | libdeflate_aligned_free(c->free_func, c); |
4131 | 1.49k | } |
4132 | | |
4133 | | unsigned int |
4134 | | libdeflate_get_compression_level(struct libdeflate_compressor *c) |
4135 | 1.93k | { |
4136 | 1.93k | return c->compression_level; |
4137 | 1.93k | } |
4138 | | |
4139 | | LIBDEFLATEAPI size_t |
4140 | | libdeflate_deflate_compress_bound(struct libdeflate_compressor *c, |
4141 | | size_t in_nbytes) |
4142 | 1.93k | { |
4143 | 1.93k | size_t max_blocks; |
4144 | | |
4145 | | /* |
4146 | | * Since the compressor never uses a compressed block when an |
4147 | | * uncompressed block is cheaper, the worst case can be no worse than |
4148 | | * the case where only uncompressed blocks are used. |
4149 | | * |
4150 | | * This is true even though up to 7 bits are "wasted" to byte-align the |
4151 | | * bitstream when a compressed block is followed by an uncompressed |
4152 | | * block. This is because a compressed block wouldn't have been used if |
4153 | | * it wasn't cheaper than an uncompressed block, and uncompressed blocks |
4154 | | * always end on a byte boundary. So the alignment bits will, at worst, |
4155 | | * go up to the place where the uncompressed block would have ended. |
4156 | | */ |
4157 | | |
4158 | | /* |
4159 | | * Calculate the maximum number of uncompressed blocks that the |
4160 | | * compressor can use for 'in_nbytes' of data. |
4161 | | * |
4162 | | * The minimum length that is passed to deflate_flush_block() is |
4163 | | * MIN_BLOCK_LENGTH bytes, except for the final block if needed. If |
4164 | | * deflate_flush_block() decides to use an uncompressed block, it |
4165 | | * actually will (in general) output a series of uncompressed blocks in |
4166 | | * order to stay within the UINT16_MAX limit of DEFLATE. But this can |
4167 | | * be disregarded here as long as '2 * MIN_BLOCK_LENGTH <= UINT16_MAX', |
4168 | | * as in that case this behavior can't result in more blocks than the |
4169 | | * case where deflate_flush_block() is called with min-length inputs. |
4170 | | * |
4171 | | * So the number of uncompressed blocks needed would be bounded by |
4172 | | * DIV_ROUND_UP(in_nbytes, MIN_BLOCK_LENGTH). However, empty inputs |
4173 | | * need 1 (empty) block, which gives the final expression below. |
4174 | | */ |
4175 | 1.93k | STATIC_ASSERT(2 * MIN_BLOCK_LENGTH <= UINT16_MAX); |
4176 | 1.93k | max_blocks = MAX(DIV_ROUND_UP(in_nbytes, MIN_BLOCK_LENGTH), 1); |
4177 | | |
4178 | | /* |
4179 | | * Each uncompressed block has 5 bytes of overhead, for the BFINAL, |
4180 | | * BTYPE, LEN, and NLEN fields. (For the reason explained earlier, the |
4181 | | * alignment bits at the very start of the block can be disregarded; |
4182 | | * they would otherwise increase the overhead to 6 bytes per block.) |
4183 | | * Therefore, the maximum number of overhead bytes is '5 * max_blocks'. |
4184 | | * To get the final bound, add the number of uncompressed bytes. |
4185 | | */ |
4186 | 1.93k | return (5 * max_blocks) + in_nbytes; |
4187 | 1.93k | } |