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