Coverage Report

Created: 2025-06-24 07:01

/src/ghostpdl/brotli/c/enc/compress_fragment.c
Line
Count
Source (jump to first uncovered line)
1
/* Copyright 2015 Google Inc. All Rights Reserved.
2
3
   Distributed under MIT license.
4
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
5
*/
6
7
/* Function for fast encoding of an input fragment, independently from the input
8
   history. This function uses one-pass processing: when we find a backward
9
   match, we immediately emit the corresponding command and literal codes to
10
   the bit stream.
11
12
   Adapted from the CompressFragment() function in
13
   https://github.com/google/snappy/blob/master/snappy.cc */
14
15
#include "compress_fragment.h"
16
17
#include <string.h>  /* memcmp, memcpy, memset */
18
19
#include <brotli/types.h>
20
21
#include "../common/platform.h"
22
#include "brotli_bit_stream.h"
23
#include "entropy_encode.h"
24
#include "fast_log.h"
25
#include "find_match_length.h"
26
#include "write_bits.h"
27
28
#if defined(__cplusplus) || defined(c_plusplus)
29
extern "C" {
30
#endif
31
32
0
#define MAX_DISTANCE (long)BROTLI_MAX_BACKWARD_LIMIT(18)
33
34
/* kHashMul32 multiplier has these properties:
35
   * The multiplier must be odd. Otherwise we may lose the highest bit.
36
   * No long streaks of ones or zeros.
37
   * There is no effort to ensure that it is a prime, the oddity is enough
38
     for this use.
39
   * The number has been tuned heuristically against compression benchmarks. */
40
static const uint32_t kHashMul32 = 0x1E35A7BD;
41
42
0
static BROTLI_INLINE uint32_t Hash(const uint8_t* p, size_t shift) {
43
0
  const uint64_t h = (BROTLI_UNALIGNED_LOAD64LE(p) << 24) * kHashMul32;
44
0
  return (uint32_t)(h >> shift);
45
0
}
46
47
static BROTLI_INLINE uint32_t HashBytesAtOffset(
48
0
    uint64_t v, int offset, size_t shift) {
49
0
  BROTLI_DCHECK(offset >= 0);
50
0
  BROTLI_DCHECK(offset <= 3);
51
0
  {
52
0
    const uint64_t h = ((v >> (8 * offset)) << 24) * kHashMul32;
53
0
    return (uint32_t)(h >> shift);
54
0
  }
55
0
}
56
57
0
static BROTLI_INLINE BROTLI_BOOL IsMatch(const uint8_t* p1, const uint8_t* p2) {
58
0
  return TO_BROTLI_BOOL(
59
0
      BrotliUnalignedRead32(p1) == BrotliUnalignedRead32(p2) &&
60
0
      p1[4] == p2[4]);
61
0
}
62
63
/* Builds a literal prefix code into "depths" and "bits" based on the statistics
64
   of the "input" string and stores it into the bit stream.
65
   Note that the prefix code here is built from the pre-LZ77 input, therefore
66
   we can only approximate the statistics of the actual literal stream.
67
   Moreover, for long inputs we build a histogram from a sample of the input
68
   and thus have to assign a non-zero depth for each literal.
69
   Returns estimated compression ratio millibytes/char for encoding given input
70
   with generated code. */
71
static size_t BuildAndStoreLiteralPrefixCode(BrotliOnePassArena* s,
72
                                             const uint8_t* input,
73
                                             const size_t input_size,
74
                                             uint8_t depths[256],
75
                                             uint16_t bits[256],
76
                                             size_t* storage_ix,
77
0
                                             uint8_t* storage) {
78
0
  uint32_t* BROTLI_RESTRICT const histogram = s->histogram;
79
0
  size_t histogram_total;
80
0
  size_t i;
81
0
  memset(histogram, 0, sizeof(s->histogram));
82
83
0
  if (input_size < (1 << 15)) {
84
0
    for (i = 0; i < input_size; ++i) {
85
0
      ++histogram[input[i]];
86
0
    }
87
0
    histogram_total = input_size;
88
0
    for (i = 0; i < 256; ++i) {
89
      /* We weigh the first 11 samples with weight 3 to account for the
90
         balancing effect of the LZ77 phase on the histogram. */
91
0
      const uint32_t adjust = 2 * BROTLI_MIN(uint32_t, histogram[i], 11u);
92
0
      histogram[i] += adjust;
93
0
      histogram_total += adjust;
94
0
    }
95
0
  } else {
96
0
    static const size_t kSampleRate = 29;
97
0
    for (i = 0; i < input_size; i += kSampleRate) {
98
0
      ++histogram[input[i]];
99
0
    }
100
0
    histogram_total = (input_size + kSampleRate - 1) / kSampleRate;
101
0
    for (i = 0; i < 256; ++i) {
102
      /* We add 1 to each population count to avoid 0 bit depths (since this is
103
         only a sample and we don't know if the symbol appears or not), and we
104
         weigh the first 11 samples with weight 3 to account for the balancing
105
         effect of the LZ77 phase on the histogram (more frequent symbols are
106
         more likely to be in backward references instead as literals). */
107
0
      const uint32_t adjust = 1 + 2 * BROTLI_MIN(uint32_t, histogram[i], 11u);
108
0
      histogram[i] += adjust;
109
0
      histogram_total += adjust;
110
0
    }
111
0
  }
112
0
  BrotliBuildAndStoreHuffmanTreeFast(s->tree, histogram, histogram_total,
113
0
                                     /* max_bits = */ 8,
114
0
                                     depths, bits, storage_ix, storage);
115
0
  {
116
0
    size_t literal_ratio = 0;
117
0
    for (i = 0; i < 256; ++i) {
118
0
      if (histogram[i]) literal_ratio += histogram[i] * depths[i];
119
0
    }
120
    /* Estimated encoding ratio, millibytes per symbol. */
121
0
    return (literal_ratio * 125) / histogram_total;
122
0
  }
123
0
}
124
125
/* Builds a command and distance prefix code (each 64 symbols) into "depth" and
126
   "bits" based on "histogram" and stores it into the bit stream. */
127
static void BuildAndStoreCommandPrefixCode(BrotliOnePassArena* s,
128
0
    size_t* storage_ix, uint8_t* storage) {
129
0
  const uint32_t* const histogram = s->cmd_histo;
130
0
  uint8_t* const depth = s->cmd_depth;
131
0
  uint16_t* const bits = s->cmd_bits;
132
0
  uint8_t* BROTLI_RESTRICT const tmp_depth = s->tmp_depth;
133
0
  uint16_t* BROTLI_RESTRICT const tmp_bits = s->tmp_bits;
134
  /* TODO(eustas): do only once on initialization. */
135
0
  memset(tmp_depth, 0, BROTLI_NUM_COMMAND_SYMBOLS);
136
137
0
  BrotliCreateHuffmanTree(histogram, 64, 15, s->tree, depth);
138
0
  BrotliCreateHuffmanTree(&histogram[64], 64, 14, s->tree, &depth[64]);
139
  /* We have to jump through a few hoops here in order to compute
140
     the command bits because the symbols are in a different order than in
141
     the full alphabet. This looks complicated, but having the symbols
142
     in this order in the command bits saves a few branches in the Emit*
143
     functions. */
144
0
  memcpy(tmp_depth, depth, 24);
145
0
  memcpy(tmp_depth + 24, depth + 40, 8);
146
0
  memcpy(tmp_depth + 32, depth + 24, 8);
147
0
  memcpy(tmp_depth + 40, depth + 48, 8);
148
0
  memcpy(tmp_depth + 48, depth + 32, 8);
149
0
  memcpy(tmp_depth + 56, depth + 56, 8);
150
0
  BrotliConvertBitDepthsToSymbols(tmp_depth, 64, tmp_bits);
151
0
  memcpy(bits, tmp_bits, 48);
152
0
  memcpy(bits + 24, tmp_bits + 32, 16);
153
0
  memcpy(bits + 32, tmp_bits + 48, 16);
154
0
  memcpy(bits + 40, tmp_bits + 24, 16);
155
0
  memcpy(bits + 48, tmp_bits + 40, 16);
156
0
  memcpy(bits + 56, tmp_bits + 56, 16);
157
0
  BrotliConvertBitDepthsToSymbols(&depth[64], 64, &bits[64]);
158
0
  {
159
    /* Create the bit length array for the full command alphabet. */
160
0
    size_t i;
161
0
    memset(tmp_depth, 0, 64);  /* only 64 first values were used */
162
0
    memcpy(tmp_depth, depth, 8);
163
0
    memcpy(tmp_depth + 64, depth + 8, 8);
164
0
    memcpy(tmp_depth + 128, depth + 16, 8);
165
0
    memcpy(tmp_depth + 192, depth + 24, 8);
166
0
    memcpy(tmp_depth + 384, depth + 32, 8);
167
0
    for (i = 0; i < 8; ++i) {
168
0
      tmp_depth[128 + 8 * i] = depth[40 + i];
169
0
      tmp_depth[256 + 8 * i] = depth[48 + i];
170
0
      tmp_depth[448 + 8 * i] = depth[56 + i];
171
0
    }
172
    /* TODO(eustas): could/should full-length machinery be avoided? */
173
0
    BrotliStoreHuffmanTree(
174
0
        tmp_depth, BROTLI_NUM_COMMAND_SYMBOLS, s->tree, storage_ix, storage);
175
0
  }
176
0
  BrotliStoreHuffmanTree(&depth[64], 64, s->tree, storage_ix, storage);
177
0
}
178
179
/* REQUIRES: insertlen < 6210 */
180
static BROTLI_INLINE void EmitInsertLen(size_t insertlen,
181
                                        const uint8_t depth[128],
182
                                        const uint16_t bits[128],
183
                                        uint32_t histo[128],
184
                                        size_t* storage_ix,
185
0
                                        uint8_t* storage) {
186
0
  if (insertlen < 6) {
187
0
    const size_t code = insertlen + 40;
188
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
189
0
    ++histo[code];
190
0
  } else if (insertlen < 130) {
191
0
    const size_t tail = insertlen - 2;
192
0
    const uint32_t nbits = Log2FloorNonZero(tail) - 1u;
193
0
    const size_t prefix = tail >> nbits;
194
0
    const size_t inscode = (nbits << 1) + prefix + 42;
195
0
    BrotliWriteBits(depth[inscode], bits[inscode], storage_ix, storage);
196
0
    BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
197
0
    ++histo[inscode];
198
0
  } else if (insertlen < 2114) {
199
0
    const size_t tail = insertlen - 66;
200
0
    const uint32_t nbits = Log2FloorNonZero(tail);
201
0
    const size_t code = nbits + 50;
202
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
203
0
    BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
204
0
    ++histo[code];
205
0
  } else {
206
0
    BrotliWriteBits(depth[61], bits[61], storage_ix, storage);
207
0
    BrotliWriteBits(12, insertlen - 2114, storage_ix, storage);
208
0
    ++histo[61];
209
0
  }
210
0
}
211
212
static BROTLI_INLINE void EmitLongInsertLen(size_t insertlen,
213
                                            const uint8_t depth[128],
214
                                            const uint16_t bits[128],
215
                                            uint32_t histo[128],
216
                                            size_t* storage_ix,
217
0
                                            uint8_t* storage) {
218
0
  if (insertlen < 22594) {
219
0
    BrotliWriteBits(depth[62], bits[62], storage_ix, storage);
220
0
    BrotliWriteBits(14, insertlen - 6210, storage_ix, storage);
221
0
    ++histo[62];
222
0
  } else {
223
0
    BrotliWriteBits(depth[63], bits[63], storage_ix, storage);
224
0
    BrotliWriteBits(24, insertlen - 22594, storage_ix, storage);
225
0
    ++histo[63];
226
0
  }
227
0
}
228
229
static BROTLI_INLINE void EmitCopyLen(size_t copylen,
230
                                      const uint8_t depth[128],
231
                                      const uint16_t bits[128],
232
                                      uint32_t histo[128],
233
                                      size_t* storage_ix,
234
0
                                      uint8_t* storage) {
235
0
  if (copylen < 10) {
236
0
    BrotliWriteBits(
237
0
        depth[copylen + 14], bits[copylen + 14], storage_ix, storage);
238
0
    ++histo[copylen + 14];
239
0
  } else if (copylen < 134) {
240
0
    const size_t tail = copylen - 6;
241
0
    const uint32_t nbits = Log2FloorNonZero(tail) - 1u;
242
0
    const size_t prefix = tail >> nbits;
243
0
    const size_t code = (nbits << 1) + prefix + 20;
244
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
245
0
    BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
246
0
    ++histo[code];
247
0
  } else if (copylen < 2118) {
248
0
    const size_t tail = copylen - 70;
249
0
    const uint32_t nbits = Log2FloorNonZero(tail);
250
0
    const size_t code = nbits + 28;
251
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
252
0
    BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
253
0
    ++histo[code];
254
0
  } else {
255
0
    BrotliWriteBits(depth[39], bits[39], storage_ix, storage);
256
0
    BrotliWriteBits(24, copylen - 2118, storage_ix, storage);
257
0
    ++histo[39];
258
0
  }
259
0
}
260
261
static BROTLI_INLINE void EmitCopyLenLastDistance(size_t copylen,
262
                                                  const uint8_t depth[128],
263
                                                  const uint16_t bits[128],
264
                                                  uint32_t histo[128],
265
                                                  size_t* storage_ix,
266
0
                                                  uint8_t* storage) {
267
0
  if (copylen < 12) {
268
0
    BrotliWriteBits(depth[copylen - 4], bits[copylen - 4], storage_ix, storage);
269
0
    ++histo[copylen - 4];
270
0
  } else if (copylen < 72) {
271
0
    const size_t tail = copylen - 8;
272
0
    const uint32_t nbits = Log2FloorNonZero(tail) - 1;
273
0
    const size_t prefix = tail >> nbits;
274
0
    const size_t code = (nbits << 1) + prefix + 4;
275
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
276
0
    BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
277
0
    ++histo[code];
278
0
  } else if (copylen < 136) {
279
0
    const size_t tail = copylen - 8;
280
0
    const size_t code = (tail >> 5) + 30;
281
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
282
0
    BrotliWriteBits(5, tail & 31, storage_ix, storage);
283
0
    BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
284
0
    ++histo[code];
285
0
    ++histo[64];
286
0
  } else if (copylen < 2120) {
287
0
    const size_t tail = copylen - 72;
288
0
    const uint32_t nbits = Log2FloorNonZero(tail);
289
0
    const size_t code = nbits + 28;
290
0
    BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
291
0
    BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
292
0
    BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
293
0
    ++histo[code];
294
0
    ++histo[64];
295
0
  } else {
296
0
    BrotliWriteBits(depth[39], bits[39], storage_ix, storage);
297
0
    BrotliWriteBits(24, copylen - 2120, storage_ix, storage);
298
0
    BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
299
0
    ++histo[39];
300
0
    ++histo[64];
301
0
  }
302
0
}
303
304
static BROTLI_INLINE void EmitDistance(size_t distance,
305
                                       const uint8_t depth[128],
306
                                       const uint16_t bits[128],
307
                                       uint32_t histo[128],
308
0
                                       size_t* storage_ix, uint8_t* storage) {
309
0
  const size_t d = distance + 3;
310
0
  const uint32_t nbits = Log2FloorNonZero(d) - 1u;
311
0
  const size_t prefix = (d >> nbits) & 1;
312
0
  const size_t offset = (2 + prefix) << nbits;
313
0
  const size_t distcode = 2 * (nbits - 1) + prefix + 80;
314
0
  BrotliWriteBits(depth[distcode], bits[distcode], storage_ix, storage);
315
0
  BrotliWriteBits(nbits, d - offset, storage_ix, storage);
316
0
  ++histo[distcode];
317
0
}
318
319
static BROTLI_INLINE void EmitLiterals(const uint8_t* input, const size_t len,
320
                                       const uint8_t depth[256],
321
                                       const uint16_t bits[256],
322
0
                                       size_t* storage_ix, uint8_t* storage) {
323
0
  size_t j;
324
0
  for (j = 0; j < len; j++) {
325
0
    const uint8_t lit = input[j];
326
0
    BrotliWriteBits(depth[lit], bits[lit], storage_ix, storage);
327
0
  }
328
0
}
329
330
/* REQUIRES: len <= 1 << 24. */
331
static void BrotliStoreMetaBlockHeader(
332
    size_t len, BROTLI_BOOL is_uncompressed, size_t* storage_ix,
333
0
    uint8_t* storage) {
334
0
  size_t nibbles = 6;
335
  /* ISLAST */
336
0
  BrotliWriteBits(1, 0, storage_ix, storage);
337
0
  if (len <= (1U << 16)) {
338
0
    nibbles = 4;
339
0
  } else if (len <= (1U << 20)) {
340
0
    nibbles = 5;
341
0
  }
342
0
  BrotliWriteBits(2, nibbles - 4, storage_ix, storage);
343
0
  BrotliWriteBits(nibbles * 4, len - 1, storage_ix, storage);
344
  /* ISUNCOMPRESSED */
345
0
  BrotliWriteBits(1, (uint64_t)is_uncompressed, storage_ix, storage);
346
0
}
347
348
static void UpdateBits(size_t n_bits, uint32_t bits, size_t pos,
349
0
    uint8_t* array) {
350
0
  while (n_bits > 0) {
351
0
    size_t byte_pos = pos >> 3;
352
0
    size_t n_unchanged_bits = pos & 7;
353
0
    size_t n_changed_bits = BROTLI_MIN(size_t, n_bits, 8 - n_unchanged_bits);
354
0
    size_t total_bits = n_unchanged_bits + n_changed_bits;
355
0
    uint32_t mask =
356
0
        (~((1u << total_bits) - 1u)) | ((1u << n_unchanged_bits) - 1u);
357
0
    uint32_t unchanged_bits = array[byte_pos] & mask;
358
0
    uint32_t changed_bits = bits & ((1u << n_changed_bits) - 1u);
359
0
    array[byte_pos] =
360
0
        (uint8_t)((changed_bits << n_unchanged_bits) | unchanged_bits);
361
0
    n_bits -= n_changed_bits;
362
0
    bits >>= n_changed_bits;
363
0
    pos += n_changed_bits;
364
0
  }
365
0
}
366
367
static void RewindBitPosition(const size_t new_storage_ix,
368
0
                              size_t* storage_ix, uint8_t* storage) {
369
0
  const size_t bitpos = new_storage_ix & 7;
370
0
  const size_t mask = (1u << bitpos) - 1;
371
0
  storage[new_storage_ix >> 3] &= (uint8_t)mask;
372
0
  *storage_ix = new_storage_ix;
373
0
}
374
375
static BROTLI_BOOL ShouldMergeBlock(BrotliOnePassArena* s,
376
0
    const uint8_t* data, size_t len, const uint8_t* depths) {
377
0
  uint32_t* BROTLI_RESTRICT const histo = s->histogram;
378
0
  static const size_t kSampleRate = 43;
379
0
  size_t i;
380
0
  memset(histo, 0, sizeof(s->histogram));
381
0
  for (i = 0; i < len; i += kSampleRate) {
382
0
    ++histo[data[i]];
383
0
  }
384
0
  {
385
0
    const size_t total = (len + kSampleRate - 1) / kSampleRate;
386
0
    double r = (FastLog2(total) + 0.5) * (double)total + 200;
387
0
    for (i = 0; i < 256; ++i) {
388
0
      r -= (double)histo[i] * (depths[i] + FastLog2(histo[i]));
389
0
    }
390
0
    return TO_BROTLI_BOOL(r >= 0.0);
391
0
  }
392
0
}
393
394
/* Acceptable loss for uncompressible speedup is 2% */
395
#define MIN_RATIO 980
396
397
static BROTLI_INLINE BROTLI_BOOL ShouldUseUncompressedMode(
398
    const uint8_t* metablock_start, const uint8_t* next_emit,
399
0
    const size_t insertlen, const size_t literal_ratio) {
400
0
  const size_t compressed = (size_t)(next_emit - metablock_start);
401
0
  if (compressed * 50 > insertlen) {
402
0
    return BROTLI_FALSE;
403
0
  } else {
404
0
    return TO_BROTLI_BOOL(literal_ratio > MIN_RATIO);
405
0
  }
406
0
}
407
408
static void EmitUncompressedMetaBlock(const uint8_t* begin, const uint8_t* end,
409
                                      const size_t storage_ix_start,
410
0
                                      size_t* storage_ix, uint8_t* storage) {
411
0
  const size_t len = (size_t)(end - begin);
412
0
  RewindBitPosition(storage_ix_start, storage_ix, storage);
413
0
  BrotliStoreMetaBlockHeader(len, 1, storage_ix, storage);
414
0
  *storage_ix = (*storage_ix + 7u) & ~7u;
415
0
  memcpy(&storage[*storage_ix >> 3], begin, len);
416
0
  *storage_ix += len << 3;
417
0
  storage[*storage_ix >> 3] = 0;
418
0
}
419
420
static uint32_t kCmdHistoSeed[128] = {
421
  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
422
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
423
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
424
  0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
425
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
426
  1, 1, 1, 1, 0, 0, 0, 0,
427
};
428
429
static BROTLI_INLINE void BrotliCompressFragmentFastImpl(
430
    BrotliOnePassArena* s, const uint8_t* input, size_t input_size,
431
    BROTLI_BOOL is_last, int* table, size_t table_bits,
432
0
    size_t* storage_ix, uint8_t* storage) {
433
0
  uint8_t* BROTLI_RESTRICT const cmd_depth = s->cmd_depth;
434
0
  uint16_t* BROTLI_RESTRICT const cmd_bits = s->cmd_bits;
435
0
  uint32_t* BROTLI_RESTRICT const cmd_histo = s->cmd_histo;
436
0
  uint8_t* BROTLI_RESTRICT const lit_depth = s->lit_depth;
437
0
  uint16_t* BROTLI_RESTRICT const lit_bits = s->lit_bits;
438
0
  const uint8_t* ip_end;
439
440
  /* "next_emit" is a pointer to the first byte that is not covered by a
441
     previous copy. Bytes between "next_emit" and the start of the next copy or
442
     the end of the input will be emitted as literal bytes. */
443
0
  const uint8_t* next_emit = input;
444
  /* Save the start of the first block for position and distance computations.
445
  */
446
0
  const uint8_t* base_ip = input;
447
448
0
  static const size_t kFirstBlockSize = 3 << 15;
449
0
  static const size_t kMergeBlockSize = 1 << 16;
450
451
0
  const size_t kInputMarginBytes = BROTLI_WINDOW_GAP;
452
0
  const size_t kMinMatchLen = 5;
453
454
0
  const uint8_t* metablock_start = input;
455
0
  size_t block_size = BROTLI_MIN(size_t, input_size, kFirstBlockSize);
456
0
  size_t total_block_size = block_size;
457
  /* Save the bit position of the MLEN field of the meta-block header, so that
458
     we can update it later if we decide to extend this meta-block. */
459
0
  size_t mlen_storage_ix = *storage_ix + 3;
460
461
0
  size_t literal_ratio;
462
463
0
  const uint8_t* ip;
464
0
  int last_distance;
465
466
0
  const size_t shift = 64u - table_bits;
467
468
0
  BrotliStoreMetaBlockHeader(block_size, 0, storage_ix, storage);
469
  /* No block splits, no contexts. */
470
0
  BrotliWriteBits(13, 0, storage_ix, storage);
471
472
0
  literal_ratio = BuildAndStoreLiteralPrefixCode(
473
0
      s, input, block_size, s->lit_depth, s->lit_bits, storage_ix, storage);
474
475
0
  {
476
    /* Store the pre-compressed command and distance prefix codes. */
477
0
    size_t i;
478
0
    for (i = 0; i + 7 < s->cmd_code_numbits; i += 8) {
479
0
      BrotliWriteBits(8, s->cmd_code[i >> 3], storage_ix, storage);
480
0
    }
481
0
  }
482
0
  BrotliWriteBits(s->cmd_code_numbits & 7,
483
0
                  s->cmd_code[s->cmd_code_numbits >> 3], storage_ix, storage);
484
485
0
 emit_commands:
486
  /* Initialize the command and distance histograms. We will gather
487
     statistics of command and distance codes during the processing
488
     of this block and use it to update the command and distance
489
     prefix codes for the next block. */
490
0
  memcpy(s->cmd_histo, kCmdHistoSeed, sizeof(kCmdHistoSeed));
491
492
  /* "ip" is the input pointer. */
493
0
  ip = input;
494
0
  last_distance = -1;
495
0
  ip_end = input + block_size;
496
497
0
  if (BROTLI_PREDICT_TRUE(block_size >= kInputMarginBytes)) {
498
    /* For the last block, we need to keep a 16 bytes margin so that we can be
499
       sure that all distances are at most window size - 16.
500
       For all other blocks, we only need to keep a margin of 5 bytes so that
501
       we don't go over the block size with a copy. */
502
0
    const size_t len_limit = BROTLI_MIN(size_t, block_size - kMinMatchLen,
503
0
                                        input_size - kInputMarginBytes);
504
0
    const uint8_t* ip_limit = input + len_limit;
505
506
0
    uint32_t next_hash;
507
0
    for (next_hash = Hash(++ip, shift); ; ) {
508
      /* Step 1: Scan forward in the input looking for a 5-byte-long match.
509
         If we get close to exhausting the input then goto emit_remainder.
510
511
         Heuristic match skipping: If 32 bytes are scanned with no matches
512
         found, start looking only at every other byte. If 32 more bytes are
513
         scanned, look at every third byte, etc.. When a match is found,
514
         immediately go back to looking at every byte. This is a small loss
515
         (~5% performance, ~0.1% density) for compressible data due to more
516
         bookkeeping, but for non-compressible data (such as JPEG) it's a huge
517
         win since the compressor quickly "realizes" the data is incompressible
518
         and doesn't bother looking for matches everywhere.
519
520
         The "skip" variable keeps track of how many bytes there are since the
521
         last match; dividing it by 32 (i.e. right-shifting by five) gives the
522
         number of bytes to move ahead for each iteration. */
523
0
      uint32_t skip = 32;
524
525
0
      const uint8_t* next_ip = ip;
526
0
      const uint8_t* candidate;
527
0
      BROTLI_DCHECK(next_emit < ip);
528
0
trawl:
529
0
      do {
530
0
        uint32_t hash = next_hash;
531
0
        uint32_t bytes_between_hash_lookups = skip++ >> 5;
532
0
        BROTLI_DCHECK(hash == Hash(next_ip, shift));
533
0
        ip = next_ip;
534
0
        next_ip = ip + bytes_between_hash_lookups;
535
0
        if (BROTLI_PREDICT_FALSE(next_ip > ip_limit)) {
536
0
          goto emit_remainder;
537
0
        }
538
0
        next_hash = Hash(next_ip, shift);
539
0
        candidate = ip - last_distance;
540
0
        if (IsMatch(ip, candidate)) {
541
0
          if (BROTLI_PREDICT_TRUE(candidate < ip)) {
542
0
            table[hash] = (int)(ip - base_ip);
543
0
            break;
544
0
          }
545
0
        }
546
0
        candidate = base_ip + table[hash];
547
0
        BROTLI_DCHECK(candidate >= base_ip);
548
0
        BROTLI_DCHECK(candidate < ip);
549
550
0
        table[hash] = (int)(ip - base_ip);
551
0
      } while (BROTLI_PREDICT_TRUE(!IsMatch(ip, candidate)));
552
553
      /* Check copy distance. If candidate is not feasible, continue search.
554
         Checking is done outside of hot loop to reduce overhead. */
555
0
      if (ip - candidate > MAX_DISTANCE) goto trawl;
556
557
      /* Step 2: Emit the found match together with the literal bytes from
558
         "next_emit" to the bit stream, and then see if we can find a next match
559
         immediately afterwards. Repeat until we find no match for the input
560
         without emitting some literal bytes. */
561
562
0
      {
563
        /* We have a 5-byte match at ip, and we need to emit bytes in
564
           [next_emit, ip). */
565
0
        const uint8_t* base = ip;
566
0
        size_t matched = 5 + FindMatchLengthWithLimit(
567
0
            candidate + 5, ip + 5, (size_t)(ip_end - ip) - 5);
568
0
        int distance = (int)(base - candidate);  /* > 0 */
569
0
        size_t insert = (size_t)(base - next_emit);
570
0
        ip += matched;
571
0
        BROTLI_LOG(("[CompressFragment] pos = %d insert = %lu copy = %d\n",
572
0
                    (int)(next_emit - base_ip), (unsigned long)insert, 2));
573
0
        BROTLI_DCHECK(0 == memcmp(base, candidate, matched));
574
0
        if (BROTLI_PREDICT_TRUE(insert < 6210)) {
575
0
          EmitInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
576
0
                        storage_ix, storage);
577
0
        } else if (ShouldUseUncompressedMode(metablock_start, next_emit, insert,
578
0
                                             literal_ratio)) {
579
0
          EmitUncompressedMetaBlock(metablock_start, base, mlen_storage_ix - 3,
580
0
                                    storage_ix, storage);
581
0
          input_size -= (size_t)(base - input);
582
0
          input = base;
583
0
          next_emit = input;
584
0
          goto next_block;
585
0
        } else {
586
0
          EmitLongInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
587
0
                            storage_ix, storage);
588
0
        }
589
0
        EmitLiterals(next_emit, insert, lit_depth, lit_bits,
590
0
                     storage_ix, storage);
591
0
        if (distance == last_distance) {
592
0
          BrotliWriteBits(cmd_depth[64], cmd_bits[64], storage_ix, storage);
593
0
          ++cmd_histo[64];
594
0
        } else {
595
0
          EmitDistance((size_t)distance, cmd_depth, cmd_bits,
596
0
                       cmd_histo, storage_ix, storage);
597
0
          last_distance = distance;
598
0
        }
599
0
        EmitCopyLenLastDistance(matched, cmd_depth, cmd_bits, cmd_histo,
600
0
                                storage_ix, storage);
601
0
        BROTLI_LOG(("[CompressFragment] pos = %d distance = %d\n"
602
0
                    "[CompressFragment] pos = %d insert = %d copy = %d\n"
603
0
                    "[CompressFragment] pos = %d distance = %d\n",
604
0
                    (int)(base - base_ip), (int)distance,
605
0
                    (int)(base - base_ip) + 2, 0, (int)matched - 2,
606
0
                    (int)(base - base_ip) + 2, (int)distance));
607
608
0
        next_emit = ip;
609
0
        if (BROTLI_PREDICT_FALSE(ip >= ip_limit)) {
610
0
          goto emit_remainder;
611
0
        }
612
        /* We could immediately start working at ip now, but to improve
613
           compression we first update "table" with the hashes of some positions
614
           within the last copy. */
615
0
        {
616
0
          uint64_t input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 3);
617
0
          uint32_t prev_hash = HashBytesAtOffset(input_bytes, 0, shift);
618
0
          uint32_t cur_hash = HashBytesAtOffset(input_bytes, 3, shift);
619
0
          table[prev_hash] = (int)(ip - base_ip - 3);
620
0
          prev_hash = HashBytesAtOffset(input_bytes, 1, shift);
621
0
          table[prev_hash] = (int)(ip - base_ip - 2);
622
0
          prev_hash = HashBytesAtOffset(input_bytes, 2, shift);
623
0
          table[prev_hash] = (int)(ip - base_ip - 1);
624
625
0
          candidate = base_ip + table[cur_hash];
626
0
          table[cur_hash] = (int)(ip - base_ip);
627
0
        }
628
0
      }
629
630
0
      while (IsMatch(ip, candidate)) {
631
        /* We have a 5-byte match at ip, and no need to emit any literal bytes
632
           prior to ip. */
633
0
        const uint8_t* base = ip;
634
0
        size_t matched = 5 + FindMatchLengthWithLimit(
635
0
            candidate + 5, ip + 5, (size_t)(ip_end - ip) - 5);
636
0
        if (ip - candidate > MAX_DISTANCE) break;
637
0
        ip += matched;
638
0
        last_distance = (int)(base - candidate);  /* > 0 */
639
0
        BROTLI_DCHECK(0 == memcmp(base, candidate, matched));
640
0
        EmitCopyLen(matched, cmd_depth, cmd_bits, cmd_histo,
641
0
                    storage_ix, storage);
642
0
        EmitDistance((size_t)last_distance, cmd_depth, cmd_bits,
643
0
                     cmd_histo, storage_ix, storage);
644
0
        BROTLI_LOG(("[CompressFragment] pos = %d insert = %d copy = %d\n"
645
0
                    "[CompressFragment] pos = %d distance = %d\n",
646
0
                    (int)(base - base_ip), 0, (int)matched,
647
0
                    (int)(base - base_ip), (int)last_distance));
648
649
0
        next_emit = ip;
650
0
        if (BROTLI_PREDICT_FALSE(ip >= ip_limit)) {
651
0
          goto emit_remainder;
652
0
        }
653
        /* We could immediately start working at ip now, but to improve
654
           compression we first update "table" with the hashes of some positions
655
           within the last copy. */
656
0
        {
657
0
          uint64_t input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 3);
658
0
          uint32_t prev_hash = HashBytesAtOffset(input_bytes, 0, shift);
659
0
          uint32_t cur_hash = HashBytesAtOffset(input_bytes, 3, shift);
660
0
          table[prev_hash] = (int)(ip - base_ip - 3);
661
0
          prev_hash = HashBytesAtOffset(input_bytes, 1, shift);
662
0
          table[prev_hash] = (int)(ip - base_ip - 2);
663
0
          prev_hash = HashBytesAtOffset(input_bytes, 2, shift);
664
0
          table[prev_hash] = (int)(ip - base_ip - 1);
665
666
0
          candidate = base_ip + table[cur_hash];
667
0
          table[cur_hash] = (int)(ip - base_ip);
668
0
        }
669
0
      }
670
671
0
      next_hash = Hash(++ip, shift);
672
0
    }
673
0
  }
674
675
0
 emit_remainder:
676
0
  BROTLI_DCHECK(next_emit <= ip_end);
677
0
  input += block_size;
678
0
  input_size -= block_size;
679
0
  block_size = BROTLI_MIN(size_t, input_size, kMergeBlockSize);
680
681
  /* Decide if we want to continue this meta-block instead of emitting the
682
     last insert-only command. */
683
0
  if (input_size > 0 &&
684
0
      total_block_size + block_size <= (1 << 20) &&
685
0
      ShouldMergeBlock(s, input, block_size, lit_depth)) {
686
0
    BROTLI_DCHECK(total_block_size > (1 << 16));
687
    /* Update the size of the current meta-block and continue emitting commands.
688
       We can do this because the current size and the new size both have 5
689
       nibbles. */
690
0
    total_block_size += block_size;
691
0
    UpdateBits(20, (uint32_t)(total_block_size - 1), mlen_storage_ix, storage);
692
0
    goto emit_commands;
693
0
  }
694
695
  /* Emit the remaining bytes as literals. */
696
0
  if (next_emit < ip_end) {
697
0
    const size_t insert = (size_t)(ip_end - next_emit);
698
0
    BROTLI_LOG(("[CompressFragment] pos = %d insert = %lu copy = %d\n",
699
0
                (int)(next_emit - base_ip), (unsigned long)insert, 2));
700
0
    if (BROTLI_PREDICT_TRUE(insert < 6210)) {
701
0
      EmitInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
702
0
                    storage_ix, storage);
703
0
      EmitLiterals(next_emit, insert, lit_depth, lit_bits, storage_ix, storage);
704
0
    } else if (ShouldUseUncompressedMode(metablock_start, next_emit, insert,
705
0
                                         literal_ratio)) {
706
0
      EmitUncompressedMetaBlock(metablock_start, ip_end, mlen_storage_ix - 3,
707
0
                                storage_ix, storage);
708
0
    } else {
709
0
      EmitLongInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
710
0
                        storage_ix, storage);
711
0
      EmitLiterals(next_emit, insert, lit_depth, lit_bits,
712
0
                   storage_ix, storage);
713
0
    }
714
0
  }
715
0
  next_emit = ip_end;
716
717
0
next_block:
718
  /* If we have more data, write a new meta-block header and prefix codes and
719
     then continue emitting commands. */
720
0
  if (input_size > 0) {
721
0
    metablock_start = input;
722
0
    block_size = BROTLI_MIN(size_t, input_size, kFirstBlockSize);
723
0
    total_block_size = block_size;
724
    /* Save the bit position of the MLEN field of the meta-block header, so that
725
       we can update it later if we decide to extend this meta-block. */
726
0
    mlen_storage_ix = *storage_ix + 3;
727
0
    BrotliStoreMetaBlockHeader(block_size, 0, storage_ix, storage);
728
    /* No block splits, no contexts. */
729
0
    BrotliWriteBits(13, 0, storage_ix, storage);
730
0
    literal_ratio = BuildAndStoreLiteralPrefixCode(
731
0
        s, input, block_size, lit_depth, lit_bits, storage_ix, storage);
732
0
    BuildAndStoreCommandPrefixCode(s, storage_ix, storage);
733
0
    goto emit_commands;
734
0
  }
735
736
0
  if (!is_last) {
737
    /* If this is not the last block, update the command and distance prefix
738
       codes for the next block and store the compressed forms. */
739
0
    s->cmd_code[0] = 0;
740
0
    s->cmd_code_numbits = 0;
741
0
    BuildAndStoreCommandPrefixCode(s, &s->cmd_code_numbits, s->cmd_code);
742
0
  }
743
0
}
744
745
0
#define FOR_TABLE_BITS_(X) X(9) X(11) X(13) X(15)
746
747
#define BAKE_METHOD_PARAM_(B) \
748
static BROTLI_NOINLINE void BrotliCompressFragmentFastImpl ## B(             \
749
    BrotliOnePassArena* s, const uint8_t* input, size_t input_size,          \
750
0
    BROTLI_BOOL is_last, int* table, size_t* storage_ix, uint8_t* storage) { \
751
0
  BrotliCompressFragmentFastImpl(s, input, input_size, is_last, table, B,    \
752
0
      storage_ix, storage);                                                  \
753
0
}
Unexecuted instantiation: compress_fragment.c:BrotliCompressFragmentFastImpl9
Unexecuted instantiation: compress_fragment.c:BrotliCompressFragmentFastImpl11
Unexecuted instantiation: compress_fragment.c:BrotliCompressFragmentFastImpl13
Unexecuted instantiation: compress_fragment.c:BrotliCompressFragmentFastImpl15
754
FOR_TABLE_BITS_(BAKE_METHOD_PARAM_)
755
#undef BAKE_METHOD_PARAM_
756
757
void BrotliCompressFragmentFast(
758
    BrotliOnePassArena* s, const uint8_t* input, size_t input_size,
759
    BROTLI_BOOL is_last, int* table, size_t table_size,
760
0
    size_t* storage_ix, uint8_t* storage) {
761
0
  const size_t initial_storage_ix = *storage_ix;
762
0
  const size_t table_bits = Log2FloorNonZero(table_size);
763
764
0
  if (input_size == 0) {
765
0
    BROTLI_DCHECK(is_last);
766
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* islast */
767
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* isempty */
768
0
    *storage_ix = (*storage_ix + 7u) & ~7u;
769
0
    return;
770
0
  }
771
772
0
  switch (table_bits) {
773
0
#define CASE_(B)                                                     \
774
0
    case B:                                                          \
775
0
      BrotliCompressFragmentFastImpl ## B(                           \
776
0
          s, input, input_size, is_last, table, storage_ix, storage);\
777
0
      break;
778
0
    FOR_TABLE_BITS_(CASE_)
779
0
#undef CASE_
780
0
    default: BROTLI_DCHECK(0); break;
781
0
  }
782
783
  /* If output is larger than single uncompressed block, rewrite it. */
784
0
  if (*storage_ix - initial_storage_ix > 31 + (input_size << 3)) {
785
0
    EmitUncompressedMetaBlock(input, input + input_size, initial_storage_ix,
786
0
                              storage_ix, storage);
787
0
  }
788
789
0
  if (is_last) {
790
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* islast */
791
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* isempty */
792
0
    *storage_ix = (*storage_ix + 7u) & ~7u;
793
0
  }
794
0
}
795
796
#undef FOR_TABLE_BITS_
797
798
#if defined(__cplusplus) || defined(c_plusplus)
799
}  /* extern "C" */
800
#endif