Coverage Report

Created: 2026-11-12 07:35

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