Coverage Report

Created: 2025-10-10 06:20

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