Coverage Report

Created: 2026-02-24 06:18

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
10.2k
void Z_INTERNAL zng_tr_init(deflate_state *s) {
84
10.2k
    s->l_desc.dyn_tree = s->dyn_ltree;
85
10.2k
    s->l_desc.stat_desc = &static_l_desc;
86
87
10.2k
    s->d_desc.dyn_tree = s->dyn_dtree;
88
10.2k
    s->d_desc.stat_desc = &static_d_desc;
89
90
10.2k
    s->bl_desc.dyn_tree = s->bl_tree;
91
10.2k
    s->bl_desc.stat_desc = &static_bl_desc;
92
93
10.2k
    s->bi_buf = 0;
94
10.2k
    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
10.2k
    init_block(s);
102
10.2k
}
103
104
/* ===========================================================================
105
 * Initialize a new block.
106
 */
107
55.9k
static void init_block(deflate_state *s) {
108
55.9k
    int n; /* iterates over tree elements */
109
110
    /* Initialize the trees. */
111
16.0M
    for (n = 0; n < L_CODES;  n++)
112
15.9M
        s->dyn_ltree[n].Freq = 0;
113
1.73M
    for (n = 0; n < D_CODES;  n++)
114
1.67M
        s->dyn_dtree[n].Freq = 0;
115
1.11M
    for (n = 0; n < BL_CODES; n++)
116
1.06M
        s->bl_tree[n].Freq = 0;
117
118
55.9k
    s->dyn_ltree[END_BLOCK].Freq = 1;
119
55.9k
    s->opt_len = s->static_len = 0;
120
55.9k
    s->sym_next = s->matches = 0;
121
55.9k
}
122
123
16.0M
#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
39.5M
    (tree[n].Freq < tree[m].Freq || \
133
39.5M
    (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
2.65M
#define pqremove(s, depth, heap, tree, top) { \
140
2.65M
    top = heap[SMALLEST]; \
141
2.65M
    heap[SMALLEST] = heap[s->heap_len--]; \
142
2.65M
    pqdownheap(depth, heap, s->heap_len, tree, SMALLEST); \
143
2.65M
}
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
6.69M
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
6.69M
    int j = k << 1;  /* left son of k */
155
6.69M
    const int v = heap[k];
156
157
24.4M
    while (j <= heap_len) {
158
        /* Set j to the smallest of the two sons: */
159
20.1M
        if (j < heap_len && smaller(tree, heap[j+1], heap[j], depth)) {
160
10.0M
            j++;
161
10.0M
        }
162
        /* Exit if v is smaller than both sons */
163
20.1M
        if (smaller(tree, v, heap[j], depth))
164
2.39M
            break;
165
166
        /* Exchange v with the smallest son */
167
17.7M
        heap[k] = heap[j];
168
17.7M
        k = j;
169
170
        /* And continue down the tree, setting j to the left son of k */
171
17.7M
        j <<= 1;
172
17.7M
    }
173
6.69M
    heap[k] = v;
174
6.69M
}
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
136k
static void build_tree(deflate_state *s, tree_desc *desc) {
185
    /* desc: the tree descriptor */
186
136k
    unsigned char *depth  = s->depth;
187
136k
    int *heap             = s->heap;
188
136k
    ct_data *tree         = desc->dyn_tree;
189
136k
    const ct_data *stree  = desc->stat_desc->static_tree;
190
136k
    int elems             = desc->stat_desc->elems;
191
136k
    int n, m;          /* iterate over heap elements */
192
136k
    int max_code = -1; /* largest code with non zero frequency */
193
136k
    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
136k
    s->heap_len = 0;
200
136k
    s->heap_max = HEAP_SIZE;
201
202
15.3M
    for (n = 0; n < elems; n++) {
203
15.2M
        if (tree[n].Freq != 0) {
204
2.73M
            heap[++(s->heap_len)] = max_code = n;
205
2.73M
            depth[n] = 0;
206
12.4M
        } else {
207
12.4M
            tree[n].Len = 0;
208
12.4M
        }
209
15.2M
    }
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
195k
    while (s->heap_len < 2) {
217
59.2k
        node = heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
218
59.2k
        tree[node].Freq = 1;
219
59.2k
        depth[node] = 0;
220
59.2k
        s->opt_len--;
221
59.2k
        if (stree)
222
59.2k
            s->static_len -= stree[node].Len;
223
        /* node is 0 or 1 so it does not have extra bits */
224
59.2k
    }
225
136k
    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
1.50M
    for (n = s->heap_len/2; n >= 1; n--)
231
1.37M
        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
136k
    node = elems;              /* next internal node of the tree */
237
2.65M
    do {
238
2.65M
        pqremove(s, depth, heap, tree, n);  /* n = node of least frequency */
239
2.65M
        m = heap[SMALLEST]; /* m = node of next least frequency */
240
241
2.65M
        heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
242
2.65M
        heap[--(s->heap_max)] = m;
243
244
        /* Create a new node father of n and m */
245
2.65M
        tree[node].Freq = tree[n].Freq + tree[m].Freq;
246
2.65M
        depth[node] = (unsigned char)((depth[n] >= depth[m] ?
247
2.30M
                                          depth[n] : depth[m]) + 1);
248
2.65M
        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
2.65M
        heap[SMALLEST] = node++;
257
2.65M
        pqdownheap(depth, heap, s->heap_len, tree, SMALLEST);
258
2.65M
    } while (s->heap_len >= 2);
259
260
136k
    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
136k
    gen_bitlen(s, (tree_desc *)desc);
266
267
    /* The field len is now set, we can generate the bit codes */
268
136k
    gen_codes((ct_data *)tree, max_code, s->bl_count);
269
136k
}
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
136k
static void gen_bitlen(deflate_state *s, tree_desc *desc) {
282
    /* desc: the tree descriptor */
283
136k
    ct_data *tree           = desc->dyn_tree;
284
136k
    int max_code            = desc->max_code;
285
136k
    const ct_data *stree    = desc->stat_desc->static_tree;
286
136k
    const int *extra        = desc->stat_desc->extra_bits;
287
136k
    int base                = desc->stat_desc->extra_base;
288
136k
    unsigned int max_length = desc->stat_desc->max_length;
289
136k
    int h;              /* heap index */
290
136k
    int n, m;           /* iterate over the tree elements */
291
136k
    unsigned int bits;  /* bit length */
292
136k
    int xbits;          /* extra bits */
293
136k
    uint16_t f;         /* frequency */
294
136k
    int overflow = 0;   /* number of elements with bit length too large */
295
296
2.31M
    for (bits = 0; bits <= MAX_BITS; bits++)
297
2.17M
        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
136k
    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
303
304
5.45M
    for (h = s->heap_max + 1; h < HEAP_SIZE; h++) {
305
5.31M
        n = s->heap[h];
306
5.31M
        bits = tree[tree[n].Dad].Len + 1u;
307
5.31M
        if (bits > max_length){
308
6.77k
            bits = max_length;
309
6.77k
            overflow++;
310
6.77k
        }
311
5.31M
        tree[n].Len = (uint16_t)bits;
312
        /* We overwrite tree[n].Dad which is no longer needed */
313
314
5.31M
        if (n > max_code) /* not a leaf node */
315
2.52M
            continue;
316
317
2.79M
        s->bl_count[bits]++;
318
2.79M
        xbits = 0;
319
2.79M
        if (n >= base)
320
617k
            xbits = extra[n-base];
321
2.79M
        f = tree[n].Freq;
322
2.79M
        s->opt_len += (unsigned int)f * (unsigned int)(bits + xbits);
323
2.79M
        if (stree)
324
2.45M
            s->static_len += (unsigned int)f * (unsigned int)(stree[n].Len + xbits);
325
2.79M
    }
326
136k
    if (overflow == 0)
327
133k
        return;
328
329
2.33k
    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
3.38k
    do {
334
3.38k
        bits = max_length - 1;
335
4.80k
        while (s->bl_count[bits] == 0)
336
1.41k
            bits--;
337
3.38k
        s->bl_count[bits]--;       /* move one leaf down the tree */
338
3.38k
        s->bl_count[bits+1] += 2u; /* move one overflow item as its brother */
339
3.38k
        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
3.38k
        overflow -= 2;
344
3.38k
    } 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
18.7k
    for (bits = max_length; bits != 0; bits--) {
352
16.4k
        n = s->bl_count[bits];
353
58.9k
        while (n != 0) {
354
42.5k
            m = s->heap[--h];
355
42.5k
            if (m > max_code)
356
17.4k
                continue;
357
25.0k
            if (tree[m].Len != bits) {
358
2.93k
                Tracev((stderr, "code %d bits %d->%u\n", m, tree[m].Len, bits));
359
2.93k
                s->opt_len += (unsigned int)(bits * tree[m].Freq);
360
2.93k
                s->opt_len -= (unsigned int)(tree[m].Len * tree[m].Freq);
361
2.93k
                tree[m].Len = (uint16_t)bits;
362
2.93k
            }
363
25.0k
            n--;
364
25.0k
        }
365
16.4k
    }
366
2.33k
}
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
136k
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
136k
    uint16_t next_code[MAX_BITS+1];  /* next code value for each bit length */
381
136k
    uint16_t code = 0;               /* running code value */
382
136k
    int bits;                        /* bit index */
383
136k
    int n;                           /* code index */
384
385
    /* The distribution counts are first used to generate the code values
386
     * without bit reversal.
387
     */
388
2.17M
    for (bits = 1; bits <= MAX_BITS; bits++) {
389
2.04M
        code = (code + bl_count[bits-1]) << 1;
390
2.04M
        next_code[bits] = code;
391
2.04M
    }
392
    /* Check that the bit counts in bl_count are consistent. The last code
393
     * must be all ones.
394
     */
395
136k
    Assert(code + bl_count[MAX_BITS]-1 == (1 << MAX_BITS)-1, "inconsistent bit counts");
396
136k
    Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
397
398
13.2M
    for (n = 0;  n <= max_code; n++) {
399
13.1M
        int len = tree[n].Len;
400
13.1M
        if (len == 0)
401
10.3M
            continue;
402
        /* Now reverse the bits */
403
2.79M
        tree[n].Code = bi_reverse(next_code[len]++, len);
404
405
2.79M
        Tracecv(tree != static_ltree, (stderr, "\nn %3d %c l %2d c %4x (%x) ",
406
2.79M
             n, (isgraph(n & 0xff) ? n : ' '), len, tree[n].Code, next_code[len]-1));
407
2.79M
    }
408
136k
}
409
410
/* ===========================================================================
411
 * Scan a literal or distance tree to determine the frequencies of the codes
412
 * in the bit length tree.
413
 */
414
90.8k
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
90.8k
    int n;                     /* iterates over all tree elements */
418
90.8k
    int prevlen = -1;          /* last emitted length */
419
90.8k
    int curlen;                /* length of current code */
420
90.8k
    int nextlen = tree[0].Len; /* length of next code */
421
90.8k
    uint16_t count = 0;        /* repeat count of the current code */
422
90.8k
    uint16_t max_count = 7;    /* max repeat count */
423
90.8k
    uint16_t min_count = 4;    /* min repeat count */
424
425
90.8k
    if (nextlen == 0)
426
19.1k
        max_count = 138, min_count = 3;
427
428
90.8k
    tree[max_code+1].Len = (uint16_t)0xffff; /* guard */
429
430
12.3M
    for (n = 0; n <= max_code; n++) {
431
12.2M
        curlen = nextlen;
432
12.2M
        nextlen = tree[n+1].Len;
433
12.2M
        if (++count < max_count && curlen == nextlen) {
434
9.52M
            continue;
435
9.52M
        } else if (count < min_count) {
436
2.09M
            s->bl_tree[curlen].Freq += count;
437
2.09M
        } else if (curlen != 0) {
438
85.9k
            if (curlen != prevlen)
439
61.1k
                s->bl_tree[curlen].Freq++;
440
85.9k
            s->bl_tree[REP_3_6].Freq++;
441
549k
        } else if (count <= 10) {
442
361k
            s->bl_tree[REPZ_3_10].Freq++;
443
361k
        } else {
444
187k
            s->bl_tree[REPZ_11_138].Freq++;
445
187k
        }
446
2.73M
        count = 0;
447
2.73M
        prevlen = curlen;
448
2.73M
        if (nextlen == 0) {
449
998k
            max_count = 138, min_count = 3;
450
1.73M
        } else if (curlen == nextlen) {
451
32.4k
            max_count = 6, min_count = 3;
452
1.70M
        } else {
453
1.70M
            max_count = 7, min_count = 4;
454
1.70M
        }
455
2.73M
    }
456
90.8k
}
457
458
/* ===========================================================================
459
 * Send a literal or distance tree in compressed form, using the codes in
460
 * bl_tree.
461
 */
462
46.6k
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
46.6k
    int n;                     /* iterates over all tree elements */
466
46.6k
    int prevlen = -1;          /* last emitted length */
467
46.6k
    int curlen;                /* length of current code */
468
46.6k
    int nextlen = tree[0].Len; /* length of next code */
469
46.6k
    int count = 0;             /* repeat count of the current code */
470
46.6k
    int max_count = 7;         /* max repeat count */
471
46.6k
    int min_count = 4;         /* min repeat count */
472
473
    /* tree[max_code+1].Len = -1; */  /* guard already set */
474
46.6k
    if (nextlen == 0)
475
8.70k
        max_count = 138, min_count = 3;
476
477
    // Temp local variables
478
46.6k
    uint32_t bi_valid = s->bi_valid;
479
46.6k
    uint64_t bi_buf = s->bi_buf;
480
481
6.24M
    for (n = 0; n <= max_code; n++) {
482
6.19M
        curlen = nextlen;
483
6.19M
        nextlen = tree[n+1].Len;
484
6.19M
        if (++count < max_count && curlen == nextlen) {
485
5.15M
            continue;
486
5.15M
        } else if (count < min_count) {
487
923k
            do {
488
923k
                send_code(s, curlen, s->bl_tree, bi_buf, bi_valid);
489
923k
            } while (--count != 0);
490
491
749k
        } else if (curlen != 0) {
492
49.3k
            if (curlen != prevlen) {
493
32.9k
                send_code(s, curlen, s->bl_tree, bi_buf, bi_valid);
494
32.9k
                count--;
495
32.9k
            }
496
49.3k
            Assert(count >= 3 && count <= 6, " 3_6?");
497
49.3k
            send_code(s, REP_3_6, s->bl_tree, bi_buf, bi_valid);
498
49.3k
            send_bits(s, count-3, 2, bi_buf, bi_valid);
499
500
240k
        } else if (count <= 10) {
501
133k
            send_code(s, REPZ_3_10, s->bl_tree, bi_buf, bi_valid);
502
133k
            send_bits(s, count-3, 3, bi_buf, bi_valid);
503
504
133k
        } else {
505
106k
            send_code(s, REPZ_11_138, s->bl_tree, bi_buf, bi_valid);
506
106k
            send_bits(s, count-11, 7, bi_buf, bi_valid);
507
106k
        }
508
1.03M
        count = 0;
509
1.03M
        prevlen = curlen;
510
1.03M
        if (nextlen == 0) {
511
354k
            max_count = 138, min_count = 3;
512
684k
        } else if (curlen == nextlen) {
513
21.4k
            max_count = 6, min_count = 3;
514
662k
        } else {
515
662k
            max_count = 7, min_count = 4;
516
662k
        }
517
1.03M
    }
518
519
    // Store back temp variables
520
46.6k
    s->bi_buf = bi_buf;
521
46.6k
    s->bi_valid = bi_valid;
522
46.6k
}
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
45.4k
static int build_bl_tree(deflate_state *s) {
529
45.4k
    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
45.4k
    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
533
45.4k
    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
534
535
    /* Build the bit length tree: */
536
45.4k
    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
108k
    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
546
108k
        if (s->bl_tree[bl_order[max_blindex]].Len != 0)
547
45.4k
            break;
548
108k
    }
549
    /* Update opt_len to include the bit length tree and counts */
550
45.4k
    s->opt_len += 3*((unsigned int)max_blindex+1) + 5+5+4;
551
45.4k
    Tracev((stderr, "\ndyn trees: dyn %u, stat %u", s->opt_len, s->static_len));
552
553
45.4k
    return max_blindex;
554
45.4k
}
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
23.3k
static void send_all_trees(deflate_state *s, int lcodes, int dcodes, int blcodes) {
562
23.3k
    int rank;                    /* index in bl_order */
563
564
23.3k
    Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
565
23.3k
    Assert(lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes");
566
567
    // Temp local variables
568
23.3k
    uint32_t bi_valid = s->bi_valid;
569
23.3k
    uint64_t bi_buf = s->bi_buf;
570
571
23.3k
    Tracev((stderr, "\nbl counts: "));
572
23.3k
    send_bits(s, lcodes-257, 5, bi_buf, bi_valid); /* not +255 as stated in appnote.txt */
573
23.3k
    send_bits(s, dcodes-1,   5, bi_buf, bi_valid);
574
23.3k
    send_bits(s, blcodes-4,  4, bi_buf, bi_valid); /* not -3 as stated in appnote.txt */
575
436k
    for (rank = 0; rank < blcodes; rank++) {
576
413k
        Tracev((stderr, "\nbl code %2u ", bl_order[rank]));
577
413k
        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3, bi_buf, bi_valid);
578
413k
    }
579
23.3k
    Tracev((stderr, "\nbl tree: sent %lu", s->bits_sent));
580
581
    // Store back temp variables
582
23.3k
    s->bi_buf = bi_buf;
583
23.3k
    s->bi_valid = bi_valid;
584
585
23.3k
    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
586
23.3k
    Tracev((stderr, "\nlit tree: sent %lu", s->bits_sent));
587
588
23.3k
    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
589
23.3k
    Tracev((stderr, "\ndist tree: sent %lu", s->bits_sent));
590
23.3k
}
591
592
/* ===========================================================================
593
 * Send a stored block
594
 */
595
6.19k
void Z_INTERNAL zng_tr_stored_block(deflate_state *s, unsigned 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
6.19k
    zng_tr_emit_tree(s, STORED_BLOCK, last); /* send block type */
600
6.19k
    zng_tr_emit_align(s);                    /* align on byte boundary */
601
6.19k
    cmpr_bits_align(s);
602
6.19k
    put_short(s, (uint16_t)stored_len);
603
6.19k
    put_short(s, (uint16_t)~stored_len);
604
6.19k
    cmpr_bits_add(s, 32);
605
6.19k
    sent_bits_add(s, 32);
606
6.19k
    if (stored_len) {
607
6.19k
        memcpy(s->pending_buf + s->pending, buf, stored_len);
608
6.19k
        s->pending += stored_len;
609
6.19k
        cmpr_bits_add(s, stored_len << 3);
610
6.19k
        sent_bits_add(s, stored_len << 3);
611
6.19k
    }
612
6.19k
}
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
45.6k
void Z_INTERNAL zng_tr_flush_block(deflate_state *s, unsigned 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
45.6k
    unsigned int opt_lenb, static_lenb; /* opt_len and static_len in bytes */
633
45.6k
    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
45.6k
    if (UNLIKELY(s->sym_next == 0)) {
637
        /* Emit an empty static tree block with no codes */
638
235
        opt_lenb = static_lenb = 0;
639
235
        s->static_len = 7;
640
45.4k
    } else if (s->level > 0) {
641
        /* Check if the file is binary or text */
642
45.4k
        if (s->strm->data_type == Z_UNKNOWN)
643
10.2k
            s->strm->data_type = detect_data_type(s);
644
645
        /* Construct the literal and distance trees */
646
45.4k
        build_tree(s, (tree_desc *)(&(s->l_desc)));
647
45.4k
        Tracev((stderr, "\nlit data: dyn %u, stat %u", s->opt_len, s->static_len));
648
649
45.4k
        build_tree(s, (tree_desc *)(&(s->d_desc)));
650
45.4k
        Tracev((stderr, "\ndist data: dyn %u, stat %u", 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
45.4k
        max_blindex = build_bl_tree(s);
659
660
        /* Determine the best encoding. Compute the block lengths in bytes. */
661
45.4k
        opt_lenb = (s->opt_len + 3 + 7) >> 3;
662
45.4k
        static_lenb = (s->static_len + 3 + 7) >> 3;
663
664
45.4k
        Tracev((stderr, "\nopt %u(%u) stat %u(%u) stored %u lit %u ",
665
45.4k
                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
666
45.4k
                s->sym_next / 3));
667
668
45.4k
        if (static_lenb <= opt_lenb || s->strategy == Z_FIXED)
669
21.7k
            opt_lenb = static_lenb;
670
671
45.4k
    } 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
45.6k
    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
6.19k
        zng_tr_stored_block(s, buf, stored_len, last);
685
686
39.4k
    } else if (static_lenb == opt_lenb) {
687
16.1k
        zng_tr_emit_tree(s, STATIC_TREES, last);
688
16.1k
        compress_block(s, (const ct_data *)static_ltree, (const ct_data *)static_dtree);
689
16.1k
        cmpr_bits_add(s, s->static_len);
690
23.3k
    } else {
691
23.3k
        zng_tr_emit_tree(s, DYN_TREES, last);
692
23.3k
        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1);
693
23.3k
        compress_block(s, (const ct_data *)s->dyn_ltree, (const ct_data *)s->dyn_dtree);
694
23.3k
        cmpr_bits_add(s, s->opt_len);
695
23.3k
    }
696
45.6k
    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
45.6k
    init_block(s);
701
702
45.6k
    if (last) {
703
10.2k
        zng_tr_emit_align(s);
704
10.2k
    }
705
45.6k
    Tracev((stderr, "\ncomprlen %lu(%lu) ", s->compressed_len>>3, s->compressed_len-7*last));
706
45.6k
}
707
708
/* ===========================================================================
709
 * Send the block data compressed using the given Huffman trees
710
 */
711
39.4k
static void compress_block(deflate_state *s, const ct_data *ltree, const ct_data *dtree) {
712
    /* ltree: literal tree */
713
    /* dtree: distance tree */
714
39.4k
    unsigned dist;      /* distance of matched string */
715
39.4k
    int lc;             /* match length or unmatched char (if dist == 0) */
716
39.4k
    unsigned sx = 0;    /* running index in symbol buffers */
717
718
    /* Local pointers to avoid indirection */
719
39.4k
    const unsigned int sym_next = s->sym_next;
720
#ifdef LIT_MEM
721
    uint16_t *d_buf = s->d_buf;
722
    unsigned char *l_buf = s->l_buf;
723
#else
724
39.4k
    unsigned char *sym_buf = s->sym_buf;
725
39.4k
#endif
726
727
    /* Keep bi_buf and bi_valid in registers across the entire loop */
728
39.4k
    uint64_t bi_buf = s->bi_buf;
729
39.4k
    uint32_t bi_valid = s->bi_valid;
730
731
39.4k
    if (sym_next != 0) {
732
9.83M
        do {
733
#ifdef LIT_MEM
734
            dist = d_buf[sx];
735
            lc = l_buf[sx++];
736
#else
737
9.83M
#  if OPTIMAL_CMP >= 32
738
9.83M
            uint32_t val = Z_U32_FROM_LE(zng_memread_4(&sym_buf[sx]));
739
9.83M
            dist = val & 0xffff;
740
9.83M
            lc = (val >> 16) & 0xff;
741
#  else
742
            dist = sym_buf[sx] + ((unsigned)sym_buf[sx + 1] << 8);
743
            lc = sym_buf[sx + 2];
744
#  endif
745
9.83M
            sx += 3;
746
9.83M
#endif
747
9.83M
            if (dist == 0) {
748
9.26M
                zng_emit_lit(s, ltree, lc, &bi_buf, &bi_valid);
749
9.26M
            } else {
750
573k
                zng_emit_dist(s, ltree, dtree, lc, dist, &bi_buf, &bi_valid);
751
573k
            } /* literal or match pair ? */
752
753
            /* Check for no overlay of pending_buf on needed symbols */
754
#ifdef LIT_MEM
755
            Assert(s->pending < 2 * (s->lit_bufsize + sx), "pending_buf overflow");
756
#else
757
9.83M
            Assert(s->pending < s->lit_bufsize + sx, "pending_buf overflow");
758
9.83M
#endif
759
9.83M
        } while (sx < sym_next);
760
39.2k
    }
761
762
39.4k
    zng_emit_end_block(s, ltree, 0, &bi_buf, &bi_valid);
763
764
    /* Write back to state */
765
39.4k
    s->bi_buf = bi_buf;
766
39.4k
    s->bi_valid = bi_valid;
767
39.4k
}
768
769
/* ===========================================================================
770
 * Check if the data type is TEXT or BINARY, using the following algorithm:
771
 * - TEXT if the two conditions below are satisfied:
772
 *    a) There are no non-portable control characters belonging to the
773
 *       "block list" (0..6, 14..25, 28..31).
774
 *    b) There is at least one printable character belonging to the
775
 *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
776
 * - BINARY otherwise.
777
 * - The following partially-portable control characters form a
778
 *   "gray list" that is ignored in this detection algorithm:
779
 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
780
 * IN assertion: the fields Freq of dyn_ltree are set.
781
 */
782
10.2k
static int detect_data_type(deflate_state *s) {
783
    /* block_mask is the bit mask of block-listed bytes
784
     * set bits 0..6, 14..25, and 28..31
785
     * 0xf3ffc07f = binary 11110011111111111100000001111111
786
     */
787
10.2k
    unsigned long block_mask = 0xf3ffc07fUL;
788
10.2k
    int n;
789
790
    /* Check for non-textual ("block-listed") bytes. */
791
190k
    for (n = 0; n <= 31; n++, block_mask >>= 1)
792
185k
        if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
793
5.01k
            return Z_BINARY;
794
795
    /* Check for textual ("allow-listed") bytes. */
796
5.25k
    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 || s->dyn_ltree[13].Freq != 0)
797
321
        return Z_TEXT;
798
653k
    for (n = 32; n < LITERALS; n++)
799
652k
        if (s->dyn_ltree[n].Freq != 0)
800
4.05k
            return Z_TEXT;
801
802
    /* There are no "block-listed" or "allow-listed" bytes:
803
     * this stream either is empty or has tolerated ("gray-listed") bytes only.
804
     */
805
885
    return Z_BINARY;
806
4.93k
}
807
808
/* ===========================================================================
809
 * Flush the bit buffer, keeping at most 7 bits in it.
810
 */
811
66.1k
void Z_INTERNAL zng_tr_flush_bits(deflate_state *s) {
812
66.1k
    if (s->bi_valid >= 48) {
813
7.40k
        put_uint32(s, (uint32_t)s->bi_buf);
814
7.40k
        put_short(s, (uint16_t)(s->bi_buf >> 32));
815
7.40k
        s->bi_buf >>= 48;
816
7.40k
        s->bi_valid -= 48;
817
58.7k
    } else if (s->bi_valid >= 32) {
818
8.81k
        put_uint32(s, (uint32_t)s->bi_buf);
819
8.81k
        s->bi_buf >>= 32;
820
8.81k
        s->bi_valid -= 32;
821
8.81k
    }
822
66.1k
    if (s->bi_valid >= 16) {
823
6.47k
        put_short(s, (uint16_t)s->bi_buf);
824
6.47k
        s->bi_buf >>= 16;
825
6.47k
        s->bi_valid -= 16;
826
6.47k
    }
827
66.1k
    if (s->bi_valid >= 8) {
828
14.3k
        put_byte(s, s->bi_buf);
829
14.3k
        s->bi_buf >>= 8;
830
14.3k
        s->bi_valid -= 8;
831
14.3k
    }
832
66.1k
}