Line | Count | Source (jump to first uncovered line) |
1 | | /* trees.c -- output deflated data using Huffman coding |
2 | | * Copyright (C) 1995-2024 Jean-loup Gailly |
3 | | * detect_data_type() function provided freely by Cosmin Truta, 2006 |
4 | | * For conditions of distribution and use, see copyright notice in zlib.h |
5 | | */ |
6 | | |
7 | | /* |
8 | | * ALGORITHM |
9 | | * |
10 | | * The "deflation" process uses several Huffman trees. The more |
11 | | * common source values are represented by shorter bit sequences. |
12 | | * |
13 | | * Each code tree is stored in a compressed form which is itself |
14 | | * a Huffman encoding of the lengths of all the code strings (in |
15 | | * ascending order by source values). The actual code strings are |
16 | | * reconstructed from the lengths in the inflate process, as described |
17 | | * in the deflate specification. |
18 | | * |
19 | | * REFERENCES |
20 | | * |
21 | | * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". |
22 | | * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc |
23 | | * |
24 | | * Storer, James A. |
25 | | * Data Compression: Methods and Theory, pp. 49-50. |
26 | | * Computer Science Press, 1988. ISBN 0-7167-8156-5. |
27 | | * |
28 | | * Sedgewick, R. |
29 | | * Algorithms, p290. |
30 | | * Addison-Wesley, 1983. ISBN 0-201-06672-6. |
31 | | */ |
32 | | |
33 | | #include "zbuild.h" |
34 | | #include "deflate.h" |
35 | | #include "trees.h" |
36 | | #include "trees_emit.h" |
37 | | #include "trees_tbl.h" |
38 | | |
39 | | /* The lengths of the bit length codes are sent in order of decreasing |
40 | | * probability, to avoid transmitting the lengths for unused bit length codes. |
41 | | */ |
42 | | |
43 | | /* =========================================================================== |
44 | | * Local data. These are initialized only once. |
45 | | */ |
46 | | |
47 | | struct static_tree_desc_s { |
48 | | const ct_data *static_tree; /* static tree or NULL */ |
49 | | const int *extra_bits; /* extra bits for each code or NULL */ |
50 | | int extra_base; /* base index for extra_bits */ |
51 | | int elems; /* max number of elements in the tree */ |
52 | | unsigned int max_length; /* max bit length for the codes */ |
53 | | }; |
54 | | |
55 | | static const static_tree_desc static_l_desc = |
56 | | {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; |
57 | | |
58 | | static const static_tree_desc static_d_desc = |
59 | | {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; |
60 | | |
61 | | static const static_tree_desc static_bl_desc = |
62 | | {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; |
63 | | |
64 | | /* =========================================================================== |
65 | | * Local (static) routines in this file. |
66 | | */ |
67 | | |
68 | | static void init_block (deflate_state *s); |
69 | | static void pqdownheap (deflate_state *s, ct_data *tree, int k); |
70 | | static void gen_bitlen (deflate_state *s, tree_desc *desc); |
71 | | static void build_tree (deflate_state *s, tree_desc *desc); |
72 | | static void scan_tree (deflate_state *s, ct_data *tree, int max_code); |
73 | | static void send_tree (deflate_state *s, ct_data *tree, int max_code); |
74 | | static int build_bl_tree (deflate_state *s); |
75 | | static void send_all_trees (deflate_state *s, int lcodes, int dcodes, int blcodes); |
76 | | static void compress_block (deflate_state *s, const ct_data *ltree, const ct_data *dtree); |
77 | | static int detect_data_type (deflate_state *s); |
78 | | |
79 | | /* =========================================================================== |
80 | | * Initialize the tree data structures for a new zlib stream. |
81 | | */ |
82 | 18.3k | void Z_INTERNAL zng_tr_init(deflate_state *s) { |
83 | 18.3k | s->l_desc.dyn_tree = s->dyn_ltree; |
84 | 18.3k | s->l_desc.stat_desc = &static_l_desc; |
85 | | |
86 | 18.3k | s->d_desc.dyn_tree = s->dyn_dtree; |
87 | 18.3k | s->d_desc.stat_desc = &static_d_desc; |
88 | | |
89 | 18.3k | s->bl_desc.dyn_tree = s->bl_tree; |
90 | 18.3k | s->bl_desc.stat_desc = &static_bl_desc; |
91 | | |
92 | 18.3k | s->bi_buf = 0; |
93 | 18.3k | s->bi_valid = 0; |
94 | | #ifdef ZLIB_DEBUG |
95 | | s->compressed_len = 0L; |
96 | | s->bits_sent = 0L; |
97 | | #endif |
98 | | |
99 | | /* Initialize the first block of the first file: */ |
100 | 18.3k | init_block(s); |
101 | 18.3k | } |
102 | | |
103 | | /* =========================================================================== |
104 | | * Initialize a new block. |
105 | | */ |
106 | 49.2k | static void init_block(deflate_state *s) { |
107 | 49.2k | int n; /* iterates over tree elements */ |
108 | | |
109 | | /* Initialize the trees. */ |
110 | 14.1M | for (n = 0; n < L_CODES; n++) |
111 | 14.0M | s->dyn_ltree[n].Freq = 0; |
112 | 1.52M | for (n = 0; n < D_CODES; n++) |
113 | 1.47M | s->dyn_dtree[n].Freq = 0; |
114 | 985k | for (n = 0; n < BL_CODES; n++) |
115 | 936k | s->bl_tree[n].Freq = 0; |
116 | | |
117 | 49.2k | s->dyn_ltree[END_BLOCK].Freq = 1; |
118 | 49.2k | s->opt_len = s->static_len = 0L; |
119 | 49.2k | s->sym_next = s->matches = 0; |
120 | 49.2k | } |
121 | | |
122 | 32.5M | #define SMALLEST 1 |
123 | | /* Index within the heap array of least frequent node in the Huffman tree */ |
124 | | |
125 | | |
126 | | /* =========================================================================== |
127 | | * Remove the smallest element from the heap and recreate the heap with |
128 | | * one less element. Updates heap and heap_len. |
129 | | */ |
130 | 5.40M | #define pqremove(s, tree, top) \ |
131 | 5.40M | {\ |
132 | 5.40M | top = s->heap[SMALLEST]; \ |
133 | 5.40M | s->heap[SMALLEST] = s->heap[s->heap_len--]; \ |
134 | 5.40M | pqdownheap(s, tree, SMALLEST); \ |
135 | 5.40M | } |
136 | | |
137 | | /* =========================================================================== |
138 | | * Compares to subtrees, using the tree depth as tie breaker when |
139 | | * the subtrees have equal frequency. This minimizes the worst case length. |
140 | | */ |
141 | | #define smaller(tree, n, m, depth) \ |
142 | 116M | (tree[n].Freq < tree[m].Freq || \ |
143 | 116M | (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) |
144 | | |
145 | | /* =========================================================================== |
146 | | * Restore the heap property by moving down the tree starting at node k, |
147 | | * exchanging a node with the smallest of its two sons if necessary, stopping |
148 | | * when the heap property is re-established (each father smaller than its |
149 | | * two sons). |
150 | | */ |
151 | 13.5M | static void pqdownheap(deflate_state *s, ct_data *tree, int k) { |
152 | | /* tree: the tree to restore */ |
153 | | /* k: node to move down */ |
154 | 13.5M | int v = s->heap[k]; |
155 | 13.5M | int j = k << 1; /* left son of k */ |
156 | 69.3M | while (j <= s->heap_len) { |
157 | | /* Set j to the smallest of the two sons: */ |
158 | 58.8M | if (j < s->heap_len && smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { |
159 | 27.5M | j++; |
160 | 27.5M | } |
161 | | /* Exit if v is smaller than both sons */ |
162 | 58.8M | if (smaller(tree, v, s->heap[j], s->depth)) |
163 | 3.06M | break; |
164 | | |
165 | | /* Exchange v with the smallest son */ |
166 | 55.7M | s->heap[k] = s->heap[j]; |
167 | 55.7M | k = j; |
168 | | |
169 | | /* And continue down the tree, setting j to the left son of k */ |
170 | 55.7M | j <<= 1; |
171 | 55.7M | } |
172 | 13.5M | s->heap[k] = v; |
173 | 13.5M | } |
174 | | |
175 | | /* =========================================================================== |
176 | | * Compute the optimal bit lengths for a tree and update the total bit length |
177 | | * for the current block. |
178 | | * IN assertion: the fields freq and dad are set, heap[heap_max] and |
179 | | * above are the tree nodes sorted by increasing frequency. |
180 | | * OUT assertions: the field len is set to the optimal bit length, the |
181 | | * array bl_count contains the frequencies for each bit length. |
182 | | * The length opt_len is updated; static_len is also updated if stree is |
183 | | * not null. |
184 | | */ |
185 | 92.5k | static void gen_bitlen(deflate_state *s, tree_desc *desc) { |
186 | | /* desc: the tree descriptor */ |
187 | 92.5k | ct_data *tree = desc->dyn_tree; |
188 | 92.5k | int max_code = desc->max_code; |
189 | 92.5k | const ct_data *stree = desc->stat_desc->static_tree; |
190 | 92.5k | const int *extra = desc->stat_desc->extra_bits; |
191 | 92.5k | int base = desc->stat_desc->extra_base; |
192 | 92.5k | unsigned int max_length = desc->stat_desc->max_length; |
193 | 92.5k | int h; /* heap index */ |
194 | 92.5k | int n, m; /* iterate over the tree elements */ |
195 | 92.5k | unsigned int bits; /* bit length */ |
196 | 92.5k | int xbits; /* extra bits */ |
197 | 92.5k | uint16_t f; /* frequency */ |
198 | 92.5k | int overflow = 0; /* number of elements with bit length too large */ |
199 | | |
200 | 1.57M | for (bits = 0; bits <= MAX_BITS; bits++) |
201 | 1.48M | s->bl_count[bits] = 0; |
202 | | |
203 | | /* In a first pass, compute the optimal bit lengths (which may |
204 | | * overflow in the case of the bit length tree). |
205 | | */ |
206 | 92.5k | tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ |
207 | | |
208 | 10.8M | for (h = s->heap_max + 1; h < HEAP_SIZE; h++) { |
209 | 10.8M | n = s->heap[h]; |
210 | 10.8M | bits = tree[tree[n].Dad].Len + 1u; |
211 | 10.8M | if (bits > max_length){ |
212 | 13.3k | bits = max_length; |
213 | 13.3k | overflow++; |
214 | 13.3k | } |
215 | 10.8M | tree[n].Len = (uint16_t)bits; |
216 | | /* We overwrite tree[n].Dad which is no longer needed */ |
217 | | |
218 | 10.8M | if (n > max_code) /* not a leaf node */ |
219 | 5.31M | continue; |
220 | | |
221 | 5.49M | s->bl_count[bits]++; |
222 | 5.49M | xbits = 0; |
223 | 5.49M | if (n >= base) |
224 | 780k | xbits = extra[n-base]; |
225 | 5.49M | f = tree[n].Freq; |
226 | 5.49M | s->opt_len += (unsigned long)f * (unsigned int)(bits + xbits); |
227 | 5.49M | if (stree) |
228 | 5.19M | s->static_len += (unsigned long)f * (unsigned int)(stree[n].Len + xbits); |
229 | 5.49M | } |
230 | 92.5k | if (overflow == 0) |
231 | 88.0k | return; |
232 | | |
233 | 4.47k | Tracev((stderr, "\nbit length overflow\n")); |
234 | | /* This happens for example on obj2 and pic of the Calgary corpus */ |
235 | | |
236 | | /* Find the first bit length which could increase: */ |
237 | 6.66k | do { |
238 | 6.66k | bits = max_length - 1; |
239 | 9.09k | while (s->bl_count[bits] == 0) |
240 | 2.43k | bits--; |
241 | 6.66k | s->bl_count[bits]--; /* move one leaf down the tree */ |
242 | 6.66k | s->bl_count[bits+1] += 2u; /* move one overflow item as its brother */ |
243 | 6.66k | s->bl_count[max_length]--; |
244 | | /* The brother of the overflow item also moves one step up, |
245 | | * but this does not affect bl_count[max_length] |
246 | | */ |
247 | 6.66k | overflow -= 2; |
248 | 6.66k | } while (overflow > 0); |
249 | | |
250 | | /* Now recompute all bit lengths, scanning in increasing frequency. |
251 | | * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all |
252 | | * lengths instead of fixing only the wrong ones. This idea is taken |
253 | | * from 'ar' written by Haruhiko Okumura.) |
254 | | */ |
255 | 35.8k | for (bits = max_length; bits != 0; bits--) { |
256 | 31.3k | n = s->bl_count[bits]; |
257 | 133k | while (n != 0) { |
258 | 102k | m = s->heap[--h]; |
259 | 102k | if (m > max_code) |
260 | 43.1k | continue; |
261 | 59.1k | if (tree[m].Len != bits) { |
262 | 6.45k | Tracev((stderr, "code %d bits %d->%u\n", m, tree[m].Len, bits)); |
263 | 6.45k | s->opt_len += (unsigned long)(bits * tree[m].Freq); |
264 | 6.45k | s->opt_len -= (unsigned long)(tree[m].Len * tree[m].Freq); |
265 | 6.45k | tree[m].Len = (uint16_t)bits; |
266 | 6.45k | } |
267 | 59.1k | n--; |
268 | 59.1k | } |
269 | 31.3k | } |
270 | 4.47k | } |
271 | | |
272 | | /* =========================================================================== |
273 | | * Generate the codes for a given tree and bit counts (which need not be |
274 | | * optimal). |
275 | | * IN assertion: the array bl_count contains the bit length statistics for |
276 | | * the given tree and the field len is set for all tree elements. |
277 | | * OUT assertion: the field code is set for all tree elements of non |
278 | | * zero code length. |
279 | | */ |
280 | 92.5k | Z_INTERNAL void gen_codes(ct_data *tree, int max_code, uint16_t *bl_count) { |
281 | | /* tree: the tree to decorate */ |
282 | | /* max_code: largest code with non zero frequency */ |
283 | | /* bl_count: number of codes at each bit length */ |
284 | 92.5k | uint16_t next_code[MAX_BITS+1]; /* next code value for each bit length */ |
285 | 92.5k | unsigned int code = 0; /* running code value */ |
286 | 92.5k | int bits; /* bit index */ |
287 | 92.5k | int n; /* code index */ |
288 | | |
289 | | /* The distribution counts are first used to generate the code values |
290 | | * without bit reversal. |
291 | | */ |
292 | 1.48M | for (bits = 1; bits <= MAX_BITS; bits++) { |
293 | 1.38M | code = (code + bl_count[bits-1]) << 1; |
294 | 1.38M | next_code[bits] = (uint16_t)code; |
295 | 1.38M | } |
296 | | /* Check that the bit counts in bl_count are consistent. The last code |
297 | | * must be all ones. |
298 | | */ |
299 | 92.5k | Assert(code + bl_count[MAX_BITS]-1 == (1 << MAX_BITS)-1, "inconsistent bit counts"); |
300 | 92.5k | Tracev((stderr, "\ngen_codes: max_code %d ", max_code)); |
301 | | |
302 | 9.54M | for (n = 0; n <= max_code; n++) { |
303 | 9.45M | int len = tree[n].Len; |
304 | 9.45M | if (len == 0) |
305 | 3.95M | continue; |
306 | | /* Now reverse the bits */ |
307 | 5.49M | tree[n].Code = PREFIX(bi_reverse)(next_code[len]++, len); |
308 | | |
309 | 5.49M | Tracecv(tree != static_ltree, (stderr, "\nn %3d %c l %2d c %4x (%x) ", |
310 | 5.49M | n, (isgraph(n & 0xff) ? n : ' '), len, tree[n].Code, next_code[len]-1)); |
311 | 5.49M | } |
312 | 92.5k | } |
313 | | |
314 | | /* =========================================================================== |
315 | | * Construct one Huffman tree and assigns the code bit strings and lengths. |
316 | | * Update the total bit length for the current block. |
317 | | * IN assertion: the field freq is set for all tree elements. |
318 | | * OUT assertions: the fields len and code are set to the optimal bit length |
319 | | * and corresponding code. The length opt_len is updated; static_len is |
320 | | * also updated if stree is not null. The field max_code is set. |
321 | | */ |
322 | 92.5k | static void build_tree(deflate_state *s, tree_desc *desc) { |
323 | | /* desc: the tree descriptor */ |
324 | 92.5k | ct_data *tree = desc->dyn_tree; |
325 | 92.5k | const ct_data *stree = desc->stat_desc->static_tree; |
326 | 92.5k | int elems = desc->stat_desc->elems; |
327 | 92.5k | int n, m; /* iterate over heap elements */ |
328 | 92.5k | int max_code = -1; /* largest code with non zero frequency */ |
329 | 92.5k | int node; /* new node being created */ |
330 | | |
331 | | /* Construct the initial heap, with least frequent element in |
332 | | * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. |
333 | | * heap[0] is not used. |
334 | | */ |
335 | 92.5k | s->heap_len = 0; |
336 | 92.5k | s->heap_max = HEAP_SIZE; |
337 | | |
338 | 10.4M | for (n = 0; n < elems; n++) { |
339 | 10.3M | if (tree[n].Freq != 0) { |
340 | 5.47M | s->heap[++(s->heap_len)] = max_code = n; |
341 | 5.47M | s->depth[n] = 0; |
342 | 5.47M | } else { |
343 | 4.85M | tree[n].Len = 0; |
344 | 4.85M | } |
345 | 10.3M | } |
346 | | |
347 | | /* The pkzip format requires that at least one distance code exists, |
348 | | * and that at least one bit should be sent even if there is only one |
349 | | * possible code. So to avoid special checks later on we force at least |
350 | | * two codes of non zero frequency. |
351 | | */ |
352 | 109k | while (s->heap_len < 2) { |
353 | 17.3k | node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); |
354 | 17.3k | tree[node].Freq = 1; |
355 | 17.3k | s->depth[node] = 0; |
356 | 17.3k | s->opt_len--; |
357 | 17.3k | if (stree) |
358 | 17.3k | s->static_len -= stree[node].Len; |
359 | | /* node is 0 or 1 so it does not have extra bits */ |
360 | 17.3k | } |
361 | 92.5k | desc->max_code = max_code; |
362 | | |
363 | | /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, |
364 | | * establish sub-heaps of increasing lengths: |
365 | | */ |
366 | 2.82M | for (n = s->heap_len/2; n >= 1; n--) |
367 | 2.72M | pqdownheap(s, tree, n); |
368 | | |
369 | | /* Construct the Huffman tree by repeatedly combining the least two |
370 | | * frequent nodes. |
371 | | */ |
372 | 92.5k | node = elems; /* next internal node of the tree */ |
373 | 5.40M | do { |
374 | 5.40M | pqremove(s, tree, n); /* n = node of least frequency */ |
375 | 5.40M | m = s->heap[SMALLEST]; /* m = node of next least frequency */ |
376 | | |
377 | 5.40M | s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ |
378 | 5.40M | s->heap[--(s->heap_max)] = m; |
379 | | |
380 | | /* Create a new node father of n and m */ |
381 | 5.40M | tree[node].Freq = tree[n].Freq + tree[m].Freq; |
382 | 5.40M | s->depth[node] = (unsigned char)((s->depth[n] >= s->depth[m] ? |
383 | 4.71M | s->depth[n] : s->depth[m]) + 1); |
384 | 5.40M | tree[n].Dad = tree[m].Dad = (uint16_t)node; |
385 | | #ifdef DUMP_BL_TREE |
386 | | if (tree == s->bl_tree) { |
387 | | fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)", |
388 | | node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); |
389 | | } |
390 | | #endif |
391 | | /* and insert the new node in the heap */ |
392 | 5.40M | s->heap[SMALLEST] = node++; |
393 | 5.40M | pqdownheap(s, tree, SMALLEST); |
394 | 5.40M | } while (s->heap_len >= 2); |
395 | | |
396 | 92.5k | s->heap[--(s->heap_max)] = s->heap[SMALLEST]; |
397 | | |
398 | | /* At this point, the fields freq and dad are set. We can now |
399 | | * generate the bit lengths. |
400 | | */ |
401 | 92.5k | gen_bitlen(s, (tree_desc *)desc); |
402 | | |
403 | | /* The field len is now set, we can generate the bit codes */ |
404 | 92.5k | gen_codes((ct_data *)tree, max_code, s->bl_count); |
405 | 92.5k | } |
406 | | |
407 | | /* =========================================================================== |
408 | | * Scan a literal or distance tree to determine the frequencies of the codes |
409 | | * in the bit length tree. |
410 | | */ |
411 | 61.6k | static void scan_tree(deflate_state *s, ct_data *tree, int max_code) { |
412 | | /* tree: the tree to be scanned */ |
413 | | /* max_code: and its largest code of non zero frequency */ |
414 | 61.6k | int n; /* iterates over all tree elements */ |
415 | 61.6k | int prevlen = -1; /* last emitted length */ |
416 | 61.6k | int curlen; /* length of current code */ |
417 | 61.6k | int nextlen = tree[0].Len; /* length of next code */ |
418 | 61.6k | uint16_t count = 0; /* repeat count of the current code */ |
419 | 61.6k | uint16_t max_count = 7; /* max repeat count */ |
420 | 61.6k | uint16_t min_count = 4; /* min repeat count */ |
421 | | |
422 | 61.6k | if (nextlen == 0) |
423 | 11.2k | max_count = 138, min_count = 3; |
424 | | |
425 | 61.6k | tree[max_code+1].Len = (uint16_t)0xffff; /* guard */ |
426 | | |
427 | 8.94M | for (n = 0; n <= max_code; n++) { |
428 | 8.88M | curlen = nextlen; |
429 | 8.88M | nextlen = tree[n+1].Len; |
430 | 8.88M | if (++count < max_count && curlen == nextlen) { |
431 | 6.30M | continue; |
432 | 6.30M | } else if (count < min_count) { |
433 | 1.84M | s->bl_tree[curlen].Freq += count; |
434 | 1.84M | } else if (curlen != 0) { |
435 | 528k | if (curlen != prevlen) |
436 | 206k | s->bl_tree[curlen].Freq++; |
437 | 528k | s->bl_tree[REP_3_6].Freq++; |
438 | 528k | } else if (count <= 10) { |
439 | 128k | s->bl_tree[REPZ_3_10].Freq++; |
440 | 128k | } else { |
441 | 71.4k | s->bl_tree[REPZ_11_138].Freq++; |
442 | 71.4k | } |
443 | 2.57M | count = 0; |
444 | 2.57M | prevlen = curlen; |
445 | 2.57M | if (nextlen == 0) { |
446 | 391k | max_count = 138, min_count = 3; |
447 | 2.17M | } else if (curlen == nextlen) { |
448 | 355k | max_count = 6, min_count = 3; |
449 | 1.82M | } else { |
450 | 1.82M | max_count = 7, min_count = 4; |
451 | 1.82M | } |
452 | 2.57M | } |
453 | 61.6k | } |
454 | | |
455 | | /* =========================================================================== |
456 | | * Send a literal or distance tree in compressed form, using the codes in |
457 | | * bl_tree. |
458 | | */ |
459 | 32.2k | static void send_tree(deflate_state *s, ct_data *tree, int max_code) { |
460 | | /* tree: the tree to be scanned */ |
461 | | /* max_code and its largest code of non zero frequency */ |
462 | 32.2k | int n; /* iterates over all tree elements */ |
463 | 32.2k | int prevlen = -1; /* last emitted length */ |
464 | 32.2k | int curlen; /* length of current code */ |
465 | 32.2k | int nextlen = tree[0].Len; /* length of next code */ |
466 | 32.2k | int count = 0; /* repeat count of the current code */ |
467 | 32.2k | int max_count = 7; /* max repeat count */ |
468 | 32.2k | int min_count = 4; /* min repeat count */ |
469 | | |
470 | | /* tree[max_code+1].Len = -1; */ /* guard already set */ |
471 | 32.2k | if (nextlen == 0) |
472 | 7.24k | max_count = 138, min_count = 3; |
473 | | |
474 | | // Temp local variables |
475 | 32.2k | uint32_t bi_valid = s->bi_valid; |
476 | 32.2k | uint64_t bi_buf = s->bi_buf; |
477 | | |
478 | 4.91M | for (n = 0; n <= max_code; n++) { |
479 | 4.88M | curlen = nextlen; |
480 | 4.88M | nextlen = tree[n+1].Len; |
481 | 4.88M | if (++count < max_count && curlen == nextlen) { |
482 | 2.99M | continue; |
483 | 2.99M | } else if (count < min_count) { |
484 | 1.96M | do { |
485 | 1.96M | send_code(s, curlen, s->bl_tree, bi_buf, bi_valid); |
486 | 1.96M | } while (--count != 0); |
487 | | |
488 | 1.48M | } else if (curlen != 0) { |
489 | 299k | if (curlen != prevlen) { |
490 | 176k | send_code(s, curlen, s->bl_tree, bi_buf, bi_valid); |
491 | 176k | count--; |
492 | 176k | } |
493 | 299k | Assert(count >= 3 && count <= 6, " 3_6?"); |
494 | 299k | send_code(s, REP_3_6, s->bl_tree, bi_buf, bi_valid); |
495 | 299k | send_bits(s, count-3, 2, bi_buf, bi_valid); |
496 | | |
497 | 299k | } else if (count <= 10) { |
498 | 78.3k | send_code(s, REPZ_3_10, s->bl_tree, bi_buf, bi_valid); |
499 | 78.3k | send_bits(s, count-3, 3, bi_buf, bi_valid); |
500 | | |
501 | 78.3k | } else { |
502 | 28.2k | send_code(s, REPZ_11_138, s->bl_tree, bi_buf, bi_valid); |
503 | 28.2k | send_bits(s, count-11, 7, bi_buf, bi_valid); |
504 | 28.2k | } |
505 | 1.89M | count = 0; |
506 | 1.89M | prevlen = curlen; |
507 | 1.89M | if (nextlen == 0) { |
508 | 241k | max_count = 138, min_count = 3; |
509 | 1.65M | } else if (curlen == nextlen) { |
510 | 148k | max_count = 6, min_count = 3; |
511 | 1.50M | } else { |
512 | 1.50M | max_count = 7, min_count = 4; |
513 | 1.50M | } |
514 | 1.89M | } |
515 | | |
516 | | // Store back temp variables |
517 | 32.2k | s->bi_buf = bi_buf; |
518 | 32.2k | s->bi_valid = bi_valid; |
519 | 32.2k | } |
520 | | |
521 | | /* =========================================================================== |
522 | | * Construct the Huffman tree for the bit lengths and return the index in |
523 | | * bl_order of the last bit length code to send. |
524 | | */ |
525 | 30.8k | static int build_bl_tree(deflate_state *s) { |
526 | 30.8k | int max_blindex; /* index of last bit length code of non zero freq */ |
527 | | |
528 | | /* Determine the bit length frequencies for literal and distance trees */ |
529 | 30.8k | scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); |
530 | 30.8k | scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); |
531 | | |
532 | | /* Build the bit length tree: */ |
533 | 30.8k | build_tree(s, (tree_desc *)(&(s->bl_desc))); |
534 | | /* opt_len now includes the length of the tree representations, except |
535 | | * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. |
536 | | */ |
537 | | |
538 | | /* Determine the number of bit length codes to send. The pkzip format |
539 | | * requires that at least 4 bit length codes be sent. (appnote.txt says |
540 | | * 3 but the actual value used is 4.) |
541 | | */ |
542 | 83.0k | for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { |
543 | 83.0k | if (s->bl_tree[bl_order[max_blindex]].Len != 0) |
544 | 30.8k | break; |
545 | 83.0k | } |
546 | | /* Update opt_len to include the bit length tree and counts */ |
547 | 30.8k | s->opt_len += 3*((unsigned long)max_blindex+1) + 5+5+4; |
548 | 30.8k | Tracev((stderr, "\ndyn trees: dyn %lu, stat %lu", s->opt_len, s->static_len)); |
549 | | |
550 | 30.8k | return max_blindex; |
551 | 30.8k | } |
552 | | |
553 | | /* =========================================================================== |
554 | | * Send the header for a block using dynamic Huffman trees: the counts, the |
555 | | * lengths of the bit length codes, the literal tree and the distance tree. |
556 | | * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. |
557 | | */ |
558 | 16.1k | static void send_all_trees(deflate_state *s, int lcodes, int dcodes, int blcodes) { |
559 | 16.1k | int rank; /* index in bl_order */ |
560 | | |
561 | 16.1k | Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); |
562 | 16.1k | Assert(lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes"); |
563 | | |
564 | | // Temp local variables |
565 | 16.1k | uint32_t bi_valid = s->bi_valid; |
566 | 16.1k | uint64_t bi_buf = s->bi_buf; |
567 | | |
568 | 16.1k | Tracev((stderr, "\nbl counts: ")); |
569 | 16.1k | send_bits(s, lcodes-257, 5, bi_buf, bi_valid); /* not +255 as stated in appnote.txt */ |
570 | 16.1k | send_bits(s, dcodes-1, 5, bi_buf, bi_valid); |
571 | 16.1k | send_bits(s, blcodes-4, 4, bi_buf, bi_valid); /* not -3 as stated in appnote.txt */ |
572 | 288k | for (rank = 0; rank < blcodes; rank++) { |
573 | 271k | Tracev((stderr, "\nbl code %2u ", bl_order[rank])); |
574 | 271k | send_bits(s, s->bl_tree[bl_order[rank]].Len, 3, bi_buf, bi_valid); |
575 | 271k | } |
576 | 16.1k | Tracev((stderr, "\nbl tree: sent %lu", s->bits_sent)); |
577 | | |
578 | | // Store back temp variables |
579 | 16.1k | s->bi_buf = bi_buf; |
580 | 16.1k | s->bi_valid = bi_valid; |
581 | | |
582 | 16.1k | send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ |
583 | 16.1k | Tracev((stderr, "\nlit tree: sent %lu", s->bits_sent)); |
584 | | |
585 | 16.1k | send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ |
586 | 16.1k | Tracev((stderr, "\ndist tree: sent %lu", s->bits_sent)); |
587 | 16.1k | } |
588 | | |
589 | | /* =========================================================================== |
590 | | * Send a stored block |
591 | | */ |
592 | 6.20k | void Z_INTERNAL zng_tr_stored_block(deflate_state *s, char *buf, uint32_t stored_len, int last) { |
593 | | /* buf: input block */ |
594 | | /* stored_len: length of input block */ |
595 | | /* last: one if this is the last block for a file */ |
596 | 6.20k | zng_tr_emit_tree(s, STORED_BLOCK, last); /* send block type */ |
597 | 6.20k | zng_tr_emit_align(s); /* align on byte boundary */ |
598 | 6.20k | cmpr_bits_align(s); |
599 | 6.20k | put_short(s, (uint16_t)stored_len); |
600 | 6.20k | put_short(s, (uint16_t)~stored_len); |
601 | 6.20k | cmpr_bits_add(s, 32); |
602 | 6.20k | sent_bits_add(s, 32); |
603 | 6.20k | if (stored_len) { |
604 | 6.20k | memcpy(s->pending_buf + s->pending, (unsigned char *)buf, stored_len); |
605 | 6.20k | s->pending += stored_len; |
606 | 6.20k | cmpr_bits_add(s, stored_len << 3); |
607 | 6.20k | sent_bits_add(s, stored_len << 3); |
608 | 6.20k | } |
609 | 6.20k | } |
610 | | |
611 | | /* =========================================================================== |
612 | | * Send one empty static block to give enough lookahead for inflate. |
613 | | * This takes 10 bits, of which 7 may remain in the bit buffer. |
614 | | */ |
615 | 0 | void Z_INTERNAL zng_tr_align(deflate_state *s) { |
616 | 0 | zng_tr_emit_tree(s, STATIC_TREES, 0); |
617 | 0 | zng_tr_emit_end_block(s, static_ltree, 0); |
618 | 0 | zng_tr_flush_bits(s); |
619 | 0 | } |
620 | | |
621 | | /* =========================================================================== |
622 | | * Determine the best encoding for the current block: dynamic trees, static |
623 | | * trees or store, and write out the encoded block. |
624 | | */ |
625 | 30.8k | void Z_INTERNAL zng_tr_flush_block(deflate_state *s, char *buf, uint32_t stored_len, int last) { |
626 | | /* buf: input block, or NULL if too old */ |
627 | | /* stored_len: length of input block */ |
628 | | /* last: one if this is the last block for a file */ |
629 | 30.8k | unsigned long opt_lenb, static_lenb; /* opt_len and static_len in bytes */ |
630 | 30.8k | int max_blindex = 0; /* index of last bit length code of non zero freq */ |
631 | | |
632 | | /* Build the Huffman trees unless a stored block is forced */ |
633 | 30.8k | if (UNLIKELY(s->sym_next == 0)) { |
634 | | /* Emit an empty static tree block with no codes */ |
635 | 32 | opt_lenb = static_lenb = 0; |
636 | 32 | s->static_len = 7; |
637 | 30.8k | } else if (s->level > 0) { |
638 | | /* Check if the file is binary or text */ |
639 | 30.8k | if (s->strm->data_type == Z_UNKNOWN) |
640 | 13.7k | s->strm->data_type = detect_data_type(s); |
641 | | |
642 | | /* Construct the literal and distance trees */ |
643 | 30.8k | build_tree(s, (tree_desc *)(&(s->l_desc))); |
644 | 30.8k | Tracev((stderr, "\nlit data: dyn %lu, stat %lu", s->opt_len, s->static_len)); |
645 | | |
646 | 30.8k | build_tree(s, (tree_desc *)(&(s->d_desc))); |
647 | 30.8k | Tracev((stderr, "\ndist data: dyn %lu, stat %lu", s->opt_len, s->static_len)); |
648 | | /* At this point, opt_len and static_len are the total bit lengths of |
649 | | * the compressed block data, excluding the tree representations. |
650 | | */ |
651 | | |
652 | | /* Build the bit length tree for the above two trees, and get the index |
653 | | * in bl_order of the last bit length code to send. |
654 | | */ |
655 | 30.8k | max_blindex = build_bl_tree(s); |
656 | | |
657 | | /* Determine the best encoding. Compute the block lengths in bytes. */ |
658 | 30.8k | opt_lenb = (s->opt_len+3+7) >> 3; |
659 | 30.8k | static_lenb = (s->static_len+3+7) >> 3; |
660 | | |
661 | 30.8k | Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %u lit %u ", |
662 | 30.8k | opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, |
663 | 30.8k | s->sym_next / 3)); |
664 | | |
665 | 30.8k | if (static_lenb <= opt_lenb || s->strategy == Z_FIXED) |
666 | 9.08k | opt_lenb = static_lenb; |
667 | | |
668 | 30.8k | } else { |
669 | 0 | Assert(buf != NULL, "lost buf"); |
670 | 0 | opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ |
671 | 0 | } |
672 | | |
673 | 30.8k | if (stored_len+4 <= opt_lenb && buf != NULL) { |
674 | | /* 4: two words for the lengths |
675 | | * The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. |
676 | | * Otherwise we can't have processed more than WSIZE input bytes since |
677 | | * the last block flush, because compression would have been |
678 | | * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to |
679 | | * transform a block into a stored block. |
680 | | */ |
681 | 6.20k | zng_tr_stored_block(s, buf, stored_len, last); |
682 | | |
683 | 24.6k | } else if (static_lenb == opt_lenb) { |
684 | 8.54k | zng_tr_emit_tree(s, STATIC_TREES, last); |
685 | 8.54k | compress_block(s, (const ct_data *)static_ltree, (const ct_data *)static_dtree); |
686 | 8.54k | cmpr_bits_add(s, s->static_len); |
687 | 16.1k | } else { |
688 | 16.1k | zng_tr_emit_tree(s, DYN_TREES, last); |
689 | 16.1k | send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1); |
690 | 16.1k | compress_block(s, (const ct_data *)s->dyn_ltree, (const ct_data *)s->dyn_dtree); |
691 | 16.1k | cmpr_bits_add(s, s->opt_len); |
692 | 16.1k | } |
693 | 30.8k | Assert(s->compressed_len == s->bits_sent, "bad compressed size"); |
694 | | /* The above check is made mod 2^32, for files larger than 512 MB |
695 | | * and unsigned long implemented on 32 bits. |
696 | | */ |
697 | 30.8k | init_block(s); |
698 | | |
699 | 30.8k | if (last) { |
700 | 13.7k | zng_tr_emit_align(s); |
701 | 13.7k | } |
702 | 30.8k | Tracev((stderr, "\ncomprlen %lu(%lu) ", s->compressed_len>>3, s->compressed_len-7*last)); |
703 | 30.8k | } |
704 | | |
705 | | /* =========================================================================== |
706 | | * Send the block data compressed using the given Huffman trees |
707 | | */ |
708 | 24.6k | static void compress_block(deflate_state *s, const ct_data *ltree, const ct_data *dtree) { |
709 | | /* ltree: literal tree */ |
710 | | /* dtree: distance tree */ |
711 | 24.6k | unsigned dist; /* distance of matched string */ |
712 | 24.6k | int lc; /* match length or unmatched char (if dist == 0) */ |
713 | 24.6k | unsigned sx = 0; /* running index in symbol buffers */ |
714 | | |
715 | 24.6k | if (s->sym_next != 0) { |
716 | 208M | do { |
717 | 208M | #ifdef LIT_MEM |
718 | 208M | dist = s->d_buf[sx]; |
719 | 208M | lc = s->l_buf[sx++]; |
720 | | #else |
721 | | dist = s->sym_buf[sx++] & 0xff; |
722 | | dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8; |
723 | | lc = s->sym_buf[sx++]; |
724 | | #endif |
725 | 208M | if (dist == 0) { |
726 | 193M | zng_emit_lit(s, ltree, lc); |
727 | 193M | } else { |
728 | 15.1M | zng_emit_dist(s, ltree, dtree, lc, dist); |
729 | 15.1M | } /* literal or match pair ? */ |
730 | | |
731 | | /* Check for no overlay of pending_buf on needed symbols */ |
732 | 208M | #ifdef LIT_MEM |
733 | 208M | Assert(s->pending < 2 * (s->lit_bufsize + sx), "pending_buf overflow"); |
734 | | #else |
735 | | Assert(s->pending < s->lit_bufsize + sx, "pending_buf overflow"); |
736 | | #endif |
737 | 208M | } while (sx < s->sym_next); |
738 | 24.6k | } |
739 | | |
740 | 24.6k | zng_emit_end_block(s, ltree, 0); |
741 | 24.6k | } |
742 | | |
743 | | /* =========================================================================== |
744 | | * Check if the data type is TEXT or BINARY, using the following algorithm: |
745 | | * - TEXT if the two conditions below are satisfied: |
746 | | * a) There are no non-portable control characters belonging to the |
747 | | * "black list" (0..6, 14..25, 28..31). |
748 | | * b) There is at least one printable character belonging to the |
749 | | * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). |
750 | | * - BINARY otherwise. |
751 | | * - The following partially-portable control characters form a |
752 | | * "gray list" that is ignored in this detection algorithm: |
753 | | * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). |
754 | | * IN assertion: the fields Freq of dyn_ltree are set. |
755 | | */ |
756 | 13.7k | static int detect_data_type(deflate_state *s) { |
757 | | /* black_mask is the bit mask of black-listed bytes |
758 | | * set bits 0..6, 14..25, and 28..31 |
759 | | * 0xf3ffc07f = binary 11110011111111111100000001111111 |
760 | | */ |
761 | 13.7k | unsigned long black_mask = 0xf3ffc07fUL; |
762 | 13.7k | int n; |
763 | | |
764 | | /* Check for non-textual ("black-listed") bytes. */ |
765 | 87.6k | for (n = 0; n <= 31; n++, black_mask >>= 1) |
766 | 85.6k | if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) |
767 | 11.7k | return Z_BINARY; |
768 | | |
769 | | /* Check for textual ("white-listed") bytes. */ |
770 | 2.02k | if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 || s->dyn_ltree[13].Freq != 0) |
771 | 665 | return Z_TEXT; |
772 | 78.8k | for (n = 32; n < LITERALS; n++) |
773 | 78.7k | if (s->dyn_ltree[n].Freq != 0) |
774 | 1.36k | return Z_TEXT; |
775 | | |
776 | | /* There are no "black-listed" or "white-listed" bytes: |
777 | | * this stream either is empty or has tolerated ("gray-listed") bytes only. |
778 | | */ |
779 | 3 | return Z_BINARY; |
780 | 1.36k | } |
781 | | |
782 | | /* =========================================================================== |
783 | | * Flush the bit buffer, keeping at most 7 bits in it. |
784 | | */ |
785 | 73.6k | void Z_INTERNAL zng_tr_flush_bits(deflate_state *s) { |
786 | 73.6k | if (s->bi_valid >= 48) { |
787 | 2.79k | put_uint32(s, (uint32_t)s->bi_buf); |
788 | 2.79k | put_short(s, (uint16_t)(s->bi_buf >> 32)); |
789 | 2.79k | s->bi_buf >>= 48; |
790 | 2.79k | s->bi_valid -= 48; |
791 | 70.8k | } else if (s->bi_valid >= 32) { |
792 | 3.03k | put_uint32(s, (uint32_t)s->bi_buf); |
793 | 3.03k | s->bi_buf >>= 32; |
794 | 3.03k | s->bi_valid -= 32; |
795 | 3.03k | } |
796 | 73.6k | if (s->bi_valid >= 16) { |
797 | 3.08k | put_short(s, (uint16_t)s->bi_buf); |
798 | 3.08k | s->bi_buf >>= 16; |
799 | 3.08k | s->bi_valid -= 16; |
800 | 3.08k | } |
801 | 73.6k | if (s->bi_valid >= 8) { |
802 | 6.14k | put_byte(s, s->bi_buf); |
803 | 6.14k | s->bi_buf >>= 8; |
804 | 6.14k | s->bi_valid -= 8; |
805 | 6.14k | } |
806 | 73.6k | } |
807 | | |
808 | | /* =========================================================================== |
809 | | * Reverse the first len bits of a code using bit manipulation |
810 | | */ |
811 | 5.49M | Z_INTERNAL uint16_t PREFIX(bi_reverse)(unsigned code, int len) { |
812 | | /* code: the value to invert */ |
813 | | /* len: its bit length */ |
814 | 5.49M | Assert(len >= 1 && len <= 15, "code length must be 1-15"); |
815 | 5.49M | #define bitrev8(b) \ |
816 | 10.9M | (uint8_t)((((uint8_t)(b) * 0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL >> 32) |
817 | 5.49M | return (bitrev8(code >> 8) | (uint16_t)bitrev8(code) << 8) >> (16 - len); |
818 | 5.49M | } |