Coverage Report

Created: 2026-04-09 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ghostpdl/brotli/c/enc/brotli_bit_stream.c
Line
Count
Source
1
/* Copyright 2014 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
/* Brotli bit stream functions to support the low level format. There are no
8
   compression algorithms here, just the right ordering of bits to match the
9
   specs. */
10
11
#include "brotli_bit_stream.h"
12
13
#include "../common/constants.h"
14
#include "../common/context.h"
15
#include "../common/platform.h"
16
#include "entropy_encode.h"
17
#include "entropy_encode_static.h"
18
#include "fast_log.h"
19
#include "histogram.h"
20
#include "memory.h"
21
#include "write_bits.h"
22
23
#if defined(__cplusplus) || defined(c_plusplus)
24
extern "C" {
25
#endif
26
27
#define MAX_HUFFMAN_TREE_SIZE (2 * BROTLI_NUM_COMMAND_SYMBOLS + 1)
28
/* The maximum size of Huffman dictionary for distances assuming that
29
   NPOSTFIX = 0 and NDIRECT = 0. */
30
#define MAX_SIMPLE_DISTANCE_ALPHABET_SIZE \
31
0
  BROTLI_DISTANCE_ALPHABET_SIZE(0, 0, BROTLI_LARGE_MAX_DISTANCE_BITS)
32
/* MAX_SIMPLE_DISTANCE_ALPHABET_SIZE == 140 */
33
34
0
static BROTLI_INLINE uint32_t BlockLengthPrefixCode(uint32_t len) {
35
0
  uint32_t code = (len >= 177) ? (len >= 753 ? 20 : 14) : (len >= 41 ? 7 : 0);
36
0
  while (code < (BROTLI_NUM_BLOCK_LEN_SYMBOLS - 1) &&
37
0
      len >= _kBrotliPrefixCodeRanges[code + 1].offset) ++code;
38
0
  return code;
39
0
}
40
41
static BROTLI_INLINE void GetBlockLengthPrefixCode(uint32_t len, size_t* code,
42
0
    uint32_t* n_extra, uint32_t* extra) {
43
0
  *code = BlockLengthPrefixCode(len);
44
0
  *n_extra = _kBrotliPrefixCodeRanges[*code].nbits;
45
0
  *extra = len - _kBrotliPrefixCodeRanges[*code].offset;
46
0
}
47
48
typedef struct BlockTypeCodeCalculator {
49
  size_t last_type;
50
  size_t second_last_type;
51
} BlockTypeCodeCalculator;
52
53
0
static void InitBlockTypeCodeCalculator(BlockTypeCodeCalculator* self) {
54
0
  self->last_type = 1;
55
0
  self->second_last_type = 0;
56
0
}
57
58
static BROTLI_INLINE size_t NextBlockTypeCode(
59
0
    BlockTypeCodeCalculator* calculator, uint8_t type) {
60
0
  size_t type_code = (type == calculator->last_type + 1) ? 1u :
61
0
      (type == calculator->second_last_type) ? 0u : type + 2u;
62
0
  calculator->second_last_type = calculator->last_type;
63
0
  calculator->last_type = type;
64
0
  return type_code;
65
0
}
66
67
/* |nibblesbits| represents the 2 bits to encode MNIBBLES (0-3)
68
   REQUIRES: length > 0
69
   REQUIRES: length <= (1 << 24) */
70
static void BrotliEncodeMlen(size_t length, uint64_t* bits,
71
0
                             size_t* numbits, uint64_t* nibblesbits) {
72
0
  size_t lg = (length == 1) ? 1 : Log2FloorNonZero((uint32_t)(length - 1)) + 1;
73
0
  size_t mnibbles = (lg < 16 ? 16 : (lg + 3)) / 4;
74
0
  BROTLI_DCHECK(length > 0);
75
0
  BROTLI_DCHECK(length <= (1 << 24));
76
0
  BROTLI_DCHECK(lg <= 24);
77
0
  *nibblesbits = mnibbles - 4;
78
0
  *numbits = mnibbles * 4;
79
0
  *bits = length - 1;
80
0
}
81
82
static BROTLI_INLINE void StoreCommandExtra(
83
0
    const Command* cmd, size_t* storage_ix, uint8_t* storage) {
84
0
  uint32_t copylen_code = CommandCopyLenCode(cmd);
85
0
  uint16_t inscode = GetInsertLengthCode(cmd->insert_len_);
86
0
  uint16_t copycode = GetCopyLengthCode(copylen_code);
87
0
  uint32_t insnumextra = GetInsertExtra(inscode);
88
0
  uint64_t insextraval = cmd->insert_len_ - GetInsertBase(inscode);
89
0
  uint64_t copyextraval = copylen_code - GetCopyBase(copycode);
90
0
  uint64_t bits = (copyextraval << insnumextra) | insextraval;
91
0
  BrotliWriteBits(
92
0
      insnumextra + GetCopyExtra(copycode), bits, storage_ix, storage);
93
0
}
94
95
/* Data structure that stores almost everything that is needed to encode each
96
   block switch command. */
97
typedef struct BlockSplitCode {
98
  BlockTypeCodeCalculator type_code_calculator;
99
  uint8_t type_depths[BROTLI_MAX_BLOCK_TYPE_SYMBOLS];
100
  uint16_t type_bits[BROTLI_MAX_BLOCK_TYPE_SYMBOLS];
101
  uint8_t length_depths[BROTLI_NUM_BLOCK_LEN_SYMBOLS];
102
  uint16_t length_bits[BROTLI_NUM_BLOCK_LEN_SYMBOLS];
103
} BlockSplitCode;
104
105
/* Stores a number between 0 and 255. */
106
0
static void StoreVarLenUint8(size_t n, size_t* storage_ix, uint8_t* storage) {
107
0
  if (n == 0) {
108
0
    BrotliWriteBits(1, 0, storage_ix, storage);
109
0
  } else {
110
0
    size_t nbits = Log2FloorNonZero(n);
111
0
    BrotliWriteBits(1, 1, storage_ix, storage);
112
0
    BrotliWriteBits(3, nbits, storage_ix, storage);
113
0
    BrotliWriteBits(nbits, n - ((size_t)1 << nbits), storage_ix, storage);
114
0
  }
115
0
}
116
117
/* Stores the compressed meta-block header.
118
   REQUIRES: length > 0
119
   REQUIRES: length <= (1 << 24) */
120
static void StoreCompressedMetaBlockHeader(BROTLI_BOOL is_final_block,
121
                                           size_t length,
122
                                           size_t* storage_ix,
123
0
                                           uint8_t* storage) {
124
0
  uint64_t lenbits;
125
0
  size_t nlenbits;
126
0
  uint64_t nibblesbits;
127
128
  /* Write ISLAST bit. */
129
0
  BrotliWriteBits(1, (uint64_t)is_final_block, storage_ix, storage);
130
  /* Write ISEMPTY bit. */
131
0
  if (is_final_block) {
132
0
    BrotliWriteBits(1, 0, storage_ix, storage);
133
0
  }
134
135
0
  BrotliEncodeMlen(length, &lenbits, &nlenbits, &nibblesbits);
136
0
  BrotliWriteBits(2, nibblesbits, storage_ix, storage);
137
0
  BrotliWriteBits(nlenbits, lenbits, storage_ix, storage);
138
139
0
  if (!is_final_block) {
140
    /* Write ISUNCOMPRESSED bit. */
141
0
    BrotliWriteBits(1, 0, storage_ix, storage);
142
0
  }
143
0
}
144
145
/* Stores the uncompressed meta-block header.
146
   REQUIRES: length > 0
147
   REQUIRES: length <= (1 << 24) */
148
static void BrotliStoreUncompressedMetaBlockHeader(size_t length,
149
                                                   size_t* storage_ix,
150
0
                                                   uint8_t* storage) {
151
0
  uint64_t lenbits;
152
0
  size_t nlenbits;
153
0
  uint64_t nibblesbits;
154
155
  /* Write ISLAST bit.
156
     Uncompressed block cannot be the last one, so set to 0. */
157
0
  BrotliWriteBits(1, 0, storage_ix, storage);
158
0
  BrotliEncodeMlen(length, &lenbits, &nlenbits, &nibblesbits);
159
0
  BrotliWriteBits(2, nibblesbits, storage_ix, storage);
160
0
  BrotliWriteBits(nlenbits, lenbits, storage_ix, storage);
161
  /* Write ISUNCOMPRESSED bit. */
162
0
  BrotliWriteBits(1, 1, storage_ix, storage);
163
0
}
164
165
static void BrotliStoreHuffmanTreeOfHuffmanTreeToBitMask(
166
    const int num_codes, const uint8_t* code_length_bitdepth,
167
0
    size_t* storage_ix, uint8_t* storage) {
168
0
  static const BROTLI_MODEL("small")
169
0
  uint8_t kStorageOrder[BROTLI_CODE_LENGTH_CODES] = {
170
0
    1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15
171
0
  };
172
  /* The bit lengths of the Huffman code over the code length alphabet
173
     are compressed with the following static Huffman code:
174
       Symbol   Code
175
       ------   ----
176
       0          00
177
       1        1110
178
       2         110
179
       3          01
180
       4          10
181
       5        1111 */
182
0
  static const BROTLI_MODEL("small")
183
0
  uint8_t kHuffmanBitLengthHuffmanCodeSymbols[6] = {
184
0
     0, 7, 3, 2, 1, 15
185
0
  };
186
0
  static const BROTLI_MODEL("small")
187
0
  uint8_t kHuffmanBitLengthHuffmanCodeBitLengths[6] = {
188
0
    2, 4, 3, 2, 2, 4
189
0
  };
190
191
0
  size_t skip_some = 0;  /* skips none. */
192
193
  /* Throw away trailing zeros: */
194
0
  size_t codes_to_store = BROTLI_CODE_LENGTH_CODES;
195
0
  if (num_codes > 1) {
196
0
    for (; codes_to_store > 0; --codes_to_store) {
197
0
      if (code_length_bitdepth[kStorageOrder[codes_to_store - 1]] != 0) {
198
0
        break;
199
0
      }
200
0
    }
201
0
  }
202
0
  if (code_length_bitdepth[kStorageOrder[0]] == 0 &&
203
0
      code_length_bitdepth[kStorageOrder[1]] == 0) {
204
0
    skip_some = 2;  /* skips two. */
205
0
    if (code_length_bitdepth[kStorageOrder[2]] == 0) {
206
0
      skip_some = 3;  /* skips three. */
207
0
    }
208
0
  }
209
0
  BrotliWriteBits(2, skip_some, storage_ix, storage);
210
0
  {
211
0
    size_t i;
212
0
    for (i = skip_some; i < codes_to_store; ++i) {
213
0
      size_t l = code_length_bitdepth[kStorageOrder[i]];
214
0
      BrotliWriteBits(kHuffmanBitLengthHuffmanCodeBitLengths[l],
215
0
          kHuffmanBitLengthHuffmanCodeSymbols[l], storage_ix, storage);
216
0
    }
217
0
  }
218
0
}
219
220
static void BrotliStoreHuffmanTreeToBitMask(
221
    const size_t huffman_tree_size, const uint8_t* huffman_tree,
222
    const uint8_t* huffman_tree_extra_bits, const uint8_t* code_length_bitdepth,
223
    const uint16_t* code_length_bitdepth_symbols,
224
0
    size_t* BROTLI_RESTRICT storage_ix, uint8_t* BROTLI_RESTRICT storage) {
225
0
  size_t i;
226
0
  for (i = 0; i < huffman_tree_size; ++i) {
227
0
    size_t ix = huffman_tree[i];
228
0
    BrotliWriteBits(code_length_bitdepth[ix], code_length_bitdepth_symbols[ix],
229
0
                    storage_ix, storage);
230
    /* Extra bits */
231
0
    switch (ix) {
232
0
      case BROTLI_REPEAT_PREVIOUS_CODE_LENGTH:
233
0
        BrotliWriteBits(2, huffman_tree_extra_bits[i], storage_ix, storage);
234
0
        break;
235
0
      case BROTLI_REPEAT_ZERO_CODE_LENGTH:
236
0
        BrotliWriteBits(3, huffman_tree_extra_bits[i], storage_ix, storage);
237
0
        break;
238
0
    }
239
0
  }
240
0
}
241
242
static void StoreSimpleHuffmanTree(const uint8_t* depths,
243
                                   size_t symbols[4],
244
                                   size_t num_symbols,
245
                                   size_t max_bits,
246
0
                                   size_t* storage_ix, uint8_t* storage) {
247
  /* value of 1 indicates a simple Huffman code */
248
0
  BrotliWriteBits(2, 1, storage_ix, storage);
249
0
  BrotliWriteBits(2, num_symbols - 1, storage_ix, storage);  /* NSYM - 1 */
250
251
0
  {
252
    /* Sort */
253
0
    size_t i;
254
0
    for (i = 0; i < num_symbols; i++) {
255
0
      size_t j;
256
0
      for (j = i + 1; j < num_symbols; j++) {
257
0
        if (depths[symbols[j]] < depths[symbols[i]]) {
258
0
          BROTLI_SWAP(size_t, symbols, j, i);
259
0
        }
260
0
      }
261
0
    }
262
0
  }
263
264
0
  if (num_symbols == 2) {
265
0
    BrotliWriteBits(max_bits, symbols[0], storage_ix, storage);
266
0
    BrotliWriteBits(max_bits, symbols[1], storage_ix, storage);
267
0
  } else if (num_symbols == 3) {
268
0
    BrotliWriteBits(max_bits, symbols[0], storage_ix, storage);
269
0
    BrotliWriteBits(max_bits, symbols[1], storage_ix, storage);
270
0
    BrotliWriteBits(max_bits, symbols[2], storage_ix, storage);
271
0
  } else {
272
0
    BrotliWriteBits(max_bits, symbols[0], storage_ix, storage);
273
0
    BrotliWriteBits(max_bits, symbols[1], storage_ix, storage);
274
0
    BrotliWriteBits(max_bits, symbols[2], storage_ix, storage);
275
0
    BrotliWriteBits(max_bits, symbols[3], storage_ix, storage);
276
    /* tree-select */
277
0
    BrotliWriteBits(1, depths[symbols[0]] == 1 ? 1 : 0, storage_ix, storage);
278
0
  }
279
0
}
280
281
/* num = alphabet size
282
   depths = symbol depths */
283
void BrotliStoreHuffmanTree(const uint8_t* depths, size_t num,
284
                            HuffmanTree* tree,
285
0
                            size_t* storage_ix, uint8_t* storage) {
286
  /* Write the Huffman tree into the brotli-representation.
287
     The command alphabet is the largest, so this allocation will fit all
288
     alphabets. */
289
  /* TODO(eustas): fix me */
290
0
  uint8_t huffman_tree[BROTLI_NUM_COMMAND_SYMBOLS];
291
0
  uint8_t huffman_tree_extra_bits[BROTLI_NUM_COMMAND_SYMBOLS];
292
0
  size_t huffman_tree_size = 0;
293
0
  uint8_t code_length_bitdepth[BROTLI_CODE_LENGTH_CODES] = { 0 };
294
0
  uint16_t code_length_bitdepth_symbols[BROTLI_CODE_LENGTH_CODES];
295
0
  uint32_t huffman_tree_histogram[BROTLI_CODE_LENGTH_CODES] = { 0 };
296
0
  size_t i;
297
0
  int num_codes = 0;
298
0
  size_t code = 0;
299
300
0
  BROTLI_DCHECK(num <= BROTLI_NUM_COMMAND_SYMBOLS);
301
302
0
  BrotliWriteHuffmanTree(depths, num, &huffman_tree_size, huffman_tree,
303
0
                         huffman_tree_extra_bits);
304
305
  /* Calculate the statistics of the Huffman tree in brotli-representation. */
306
0
  for (i = 0; i < huffman_tree_size; ++i) {
307
0
    ++huffman_tree_histogram[huffman_tree[i]];
308
0
  }
309
310
0
  for (i = 0; i < BROTLI_CODE_LENGTH_CODES; ++i) {
311
0
    if (huffman_tree_histogram[i]) {
312
0
      if (num_codes == 0) {
313
0
        code = i;
314
0
        num_codes = 1;
315
0
      } else if (num_codes == 1) {
316
0
        num_codes = 2;
317
0
        break;
318
0
      }
319
0
    }
320
0
  }
321
322
  /* Calculate another Huffman tree to use for compressing both the
323
     earlier Huffman tree with. */
324
0
  BrotliCreateHuffmanTree(huffman_tree_histogram, BROTLI_CODE_LENGTH_CODES,
325
0
                          5, tree, code_length_bitdepth);
326
0
  BrotliConvertBitDepthsToSymbols(code_length_bitdepth,
327
0
                                  BROTLI_CODE_LENGTH_CODES,
328
0
                                  code_length_bitdepth_symbols);
329
330
  /* Now, we have all the data, let's start storing it */
331
0
  BrotliStoreHuffmanTreeOfHuffmanTreeToBitMask(num_codes, code_length_bitdepth,
332
0
                                               storage_ix, storage);
333
334
0
  if (num_codes == 1) {
335
0
    code_length_bitdepth[code] = 0;
336
0
  }
337
338
  /* Store the real Huffman tree now. */
339
0
  BrotliStoreHuffmanTreeToBitMask(huffman_tree_size,
340
0
                                  huffman_tree,
341
0
                                  huffman_tree_extra_bits,
342
0
                                  code_length_bitdepth,
343
0
                                  code_length_bitdepth_symbols,
344
0
                                  storage_ix, storage);
345
0
}
346
347
/* Builds a Huffman tree from histogram[0:length] into depth[0:length] and
348
   bits[0:length] and stores the encoded tree to the bit stream. */
349
static void BuildAndStoreHuffmanTree(const uint32_t* histogram,
350
                                     const size_t histogram_length,
351
                                     const size_t alphabet_size,
352
                                     HuffmanTree* tree,
353
                                     uint8_t* depth,
354
                                     uint16_t* bits,
355
                                     size_t* storage_ix,
356
0
                                     uint8_t* storage) {
357
0
  size_t count = 0;
358
0
  size_t s4[4] = { 0 };
359
0
  size_t i;
360
0
  size_t max_bits = 0;
361
0
  for (i = 0; i < histogram_length; i++) {
362
0
    if (histogram[i]) {
363
0
      if (count < 4) {
364
0
        s4[count] = i;
365
0
      } else if (count > 4) {
366
0
        break;
367
0
      }
368
0
      count++;
369
0
    }
370
0
  }
371
372
0
  {
373
0
    size_t max_bits_counter = alphabet_size - 1;
374
0
    while (max_bits_counter) {
375
0
      max_bits_counter >>= 1;
376
0
      ++max_bits;
377
0
    }
378
0
  }
379
380
0
  if (count <= 1) {
381
0
    BrotliWriteBits(4, 1, storage_ix, storage);
382
0
    BrotliWriteBits(max_bits, s4[0], storage_ix, storage);
383
0
    depth[s4[0]] = 0;
384
0
    bits[s4[0]] = 0;
385
0
    return;
386
0
  }
387
388
0
  memset(depth, 0, histogram_length * sizeof(depth[0]));
389
0
  BrotliCreateHuffmanTree(histogram, histogram_length, 15, tree, depth);
390
0
  BrotliConvertBitDepthsToSymbols(depth, histogram_length, bits);
391
392
0
  if (count <= 4) {
393
0
    StoreSimpleHuffmanTree(depth, s4, count, max_bits, storage_ix, storage);
394
0
  } else {
395
0
    BrotliStoreHuffmanTree(depth, histogram_length, tree, storage_ix, storage);
396
0
  }
397
0
}
398
399
static BROTLI_INLINE BROTLI_BOOL SortHuffmanTree(
400
0
    const HuffmanTree* v0, const HuffmanTree* v1) {
401
0
  return TO_BROTLI_BOOL(v0->total_count_ < v1->total_count_);
402
0
}
403
404
void BrotliBuildAndStoreHuffmanTreeFast(HuffmanTree* tree,
405
                                        const uint32_t* histogram,
406
                                        const size_t histogram_total,
407
                                        const size_t max_bits,
408
                                        uint8_t* depth, uint16_t* bits,
409
                                        size_t* storage_ix,
410
0
                                        uint8_t* storage) {
411
0
  size_t count = 0;
412
0
  size_t symbols[4] = { 0 };
413
0
  size_t length = 0;
414
0
  size_t total = histogram_total;
415
0
  while (total != 0) {
416
0
    if (histogram[length]) {
417
0
      if (count < 4) {
418
0
        symbols[count] = length;
419
0
      }
420
0
      ++count;
421
0
      total -= histogram[length];
422
0
    }
423
0
    ++length;
424
0
  }
425
426
0
  if (count <= 1) {
427
0
    BrotliWriteBits(4, 1, storage_ix, storage);
428
0
    BrotliWriteBits(max_bits, symbols[0], storage_ix, storage);
429
0
    depth[symbols[0]] = 0;
430
0
    bits[symbols[0]] = 0;
431
0
    return;
432
0
  }
433
434
0
  memset(depth, 0, length * sizeof(depth[0]));
435
0
  {
436
0
    uint32_t count_limit;
437
0
    for (count_limit = 1; ; count_limit *= 2) {
438
0
      HuffmanTree* node = tree;
439
0
      size_t l;
440
0
      for (l = length; l != 0;) {
441
0
        --l;
442
0
        if (histogram[l]) {
443
0
          if (BROTLI_PREDICT_TRUE(histogram[l] >= count_limit)) {
444
0
            InitHuffmanTree(node, histogram[l], -1, (int16_t)l);
445
0
          } else {
446
0
            InitHuffmanTree(node, count_limit, -1, (int16_t)l);
447
0
          }
448
0
          ++node;
449
0
        }
450
0
      }
451
0
      {
452
0
        const int n = (int)(node - tree);
453
0
        HuffmanTree sentinel;
454
0
        int i = 0;      /* Points to the next leaf node. */
455
0
        int j = n + 1;  /* Points to the next non-leaf node. */
456
0
        int k;
457
458
0
        SortHuffmanTreeItems(tree, (size_t)n, SortHuffmanTree);
459
        /* The nodes are:
460
           [0, n): the sorted leaf nodes that we start with.
461
           [n]: we add a sentinel here.
462
           [n + 1, 2n): new parent nodes are added here, starting from
463
                        (n+1). These are naturally in ascending order.
464
           [2n]: we add a sentinel at the end as well.
465
           There will be (2n+1) elements at the end. */
466
0
        InitHuffmanTree(&sentinel, BROTLI_UINT32_MAX, -1, -1);
467
0
        *node++ = sentinel;
468
0
        *node++ = sentinel;
469
470
0
        for (k = n - 1; k > 0; --k) {
471
0
          int left, right;
472
0
          if (tree[i].total_count_ <= tree[j].total_count_) {
473
0
            left = i;
474
0
            ++i;
475
0
          } else {
476
0
            left = j;
477
0
            ++j;
478
0
          }
479
0
          if (tree[i].total_count_ <= tree[j].total_count_) {
480
0
            right = i;
481
0
            ++i;
482
0
          } else {
483
0
            right = j;
484
0
            ++j;
485
0
          }
486
          /* The sentinel node becomes the parent node. */
487
0
          node[-1].total_count_ =
488
0
              tree[left].total_count_ + tree[right].total_count_;
489
0
          node[-1].index_left_ = (int16_t)left;
490
0
          node[-1].index_right_or_value_ = (int16_t)right;
491
          /* Add back the last sentinel node. */
492
0
          *node++ = sentinel;
493
0
        }
494
0
        if (BrotliSetDepth(2 * n - 1, tree, depth, 14)) {
495
          /* We need to pack the Huffman tree in 14 bits. If this was not
496
             successful, add fake entities to the lowest values and retry. */
497
0
          break;
498
0
        }
499
0
      }
500
0
    }
501
0
  }
502
0
  BrotliConvertBitDepthsToSymbols(depth, length, bits);
503
0
  if (count <= 4) {
504
0
    size_t i;
505
    /* value of 1 indicates a simple Huffman code */
506
0
    BrotliWriteBits(2, 1, storage_ix, storage);
507
0
    BrotliWriteBits(2, count - 1, storage_ix, storage);  /* NSYM - 1 */
508
509
    /* Sort */
510
0
    for (i = 0; i < count; i++) {
511
0
      size_t j;
512
0
      for (j = i + 1; j < count; j++) {
513
0
        if (depth[symbols[j]] < depth[symbols[i]]) {
514
0
          BROTLI_SWAP(size_t, symbols, j, i);
515
0
        }
516
0
      }
517
0
    }
518
519
0
    if (count == 2) {
520
0
      BrotliWriteBits(max_bits, symbols[0], storage_ix, storage);
521
0
      BrotliWriteBits(max_bits, symbols[1], storage_ix, storage);
522
0
    } else if (count == 3) {
523
0
      BrotliWriteBits(max_bits, symbols[0], storage_ix, storage);
524
0
      BrotliWriteBits(max_bits, symbols[1], storage_ix, storage);
525
0
      BrotliWriteBits(max_bits, symbols[2], storage_ix, storage);
526
0
    } else {
527
0
      BrotliWriteBits(max_bits, symbols[0], storage_ix, storage);
528
0
      BrotliWriteBits(max_bits, symbols[1], storage_ix, storage);
529
0
      BrotliWriteBits(max_bits, symbols[2], storage_ix, storage);
530
0
      BrotliWriteBits(max_bits, symbols[3], storage_ix, storage);
531
      /* tree-select */
532
0
      BrotliWriteBits(1, depth[symbols[0]] == 1 ? 1 : 0, storage_ix, storage);
533
0
    }
534
0
  } else {
535
0
    uint8_t previous_value = 8;
536
0
    size_t i;
537
    /* Complex Huffman Tree */
538
0
    StoreStaticCodeLengthCode(storage_ix, storage);
539
540
    /* Actual RLE coding. */
541
0
    for (i = 0; i < length;) {
542
0
      const uint8_t value = depth[i];
543
0
      size_t reps = 1;
544
0
      size_t k;
545
0
      for (k = i + 1; k < length && depth[k] == value; ++k) {
546
0
        ++reps;
547
0
      }
548
0
      i += reps;
549
0
      if (value == 0) {
550
0
        BrotliWriteBits(kZeroRepsDepth[reps], kZeroRepsBits[reps],
551
0
                        storage_ix, storage);
552
0
      } else {
553
0
        if (previous_value != value) {
554
0
          BrotliWriteBits(kCodeLengthDepth[value], kCodeLengthBits[value],
555
0
                          storage_ix, storage);
556
0
          --reps;
557
0
        }
558
0
        if (reps < 3) {
559
0
          while (reps != 0) {
560
0
            reps--;
561
0
            BrotliWriteBits(kCodeLengthDepth[value], kCodeLengthBits[value],
562
0
                            storage_ix, storage);
563
0
          }
564
0
        } else {
565
0
          reps -= 3;
566
0
          BrotliWriteBits(kNonZeroRepsDepth[reps], kNonZeroRepsBits[reps],
567
0
                          storage_ix, storage);
568
0
        }
569
0
        previous_value = value;
570
0
      }
571
0
    }
572
0
  }
573
0
}
574
575
0
static size_t IndexOf(const uint8_t* v, size_t v_size, uint8_t value) {
576
0
  size_t i = 0;
577
0
  for (; i < v_size; ++i) {
578
0
    if (v[i] == value) return i;
579
0
  }
580
0
  return i;
581
0
}
582
583
0
static void MoveToFront(uint8_t* v, size_t index) {
584
0
  uint8_t value = v[index];
585
0
  size_t i;
586
0
  for (i = index; i != 0; --i) {
587
0
    v[i] = v[i - 1];
588
0
  }
589
0
  v[0] = value;
590
0
}
591
592
static void MoveToFrontTransform(const uint32_t* BROTLI_RESTRICT v_in,
593
                                 const size_t v_size,
594
0
                                 uint32_t* v_out) {
595
0
  size_t i;
596
0
  uint8_t mtf[256];
597
0
  uint32_t max_value;
598
0
  if (v_size == 0) {
599
0
    return;
600
0
  }
601
0
  max_value = v_in[0];
602
0
  for (i = 1; i < v_size; ++i) {
603
0
    if (v_in[i] > max_value) max_value = v_in[i];
604
0
  }
605
0
  BROTLI_DCHECK(max_value < 256u);
606
0
  for (i = 0; i <= max_value; ++i) {
607
0
    mtf[i] = (uint8_t)i;
608
0
  }
609
0
  {
610
0
    size_t mtf_size = max_value + 1;
611
0
    for (i = 0; i < v_size; ++i) {
612
0
      size_t index = IndexOf(mtf, mtf_size, (uint8_t)v_in[i]);
613
0
      BROTLI_DCHECK(index < mtf_size);
614
0
      v_out[i] = (uint32_t)index;
615
0
      MoveToFront(mtf, index);
616
0
    }
617
0
  }
618
0
}
619
620
/* Finds runs of zeros in v[0..in_size) and replaces them with a prefix code of
621
   the run length plus extra bits (lower 9 bits is the prefix code and the rest
622
   are the extra bits). Non-zero values in v[] are shifted by
623
   *max_length_prefix. Will not create prefix codes bigger than the initial
624
   value of *max_run_length_prefix. The prefix code of run length L is simply
625
   Log2Floor(L) and the number of extra bits is the same as the prefix code. */
626
static void RunLengthCodeZeros(const size_t in_size,
627
    uint32_t* BROTLI_RESTRICT v, size_t* BROTLI_RESTRICT out_size,
628
0
    uint32_t* BROTLI_RESTRICT max_run_length_prefix) {
629
0
  uint32_t max_reps = 0;
630
0
  size_t i;
631
0
  uint32_t max_prefix;
632
0
  for (i = 0; i < in_size;) {
633
0
    uint32_t reps = 0;
634
0
    for (; i < in_size && v[i] != 0; ++i) ;
635
0
    for (; i < in_size && v[i] == 0; ++i) {
636
0
      ++reps;
637
0
    }
638
0
    max_reps = BROTLI_MAX(uint32_t, reps, max_reps);
639
0
  }
640
0
  max_prefix = max_reps > 0 ? Log2FloorNonZero(max_reps) : 0;
641
0
  max_prefix = BROTLI_MIN(uint32_t, max_prefix, *max_run_length_prefix);
642
0
  *max_run_length_prefix = max_prefix;
643
0
  *out_size = 0;
644
0
  for (i = 0; i < in_size;) {
645
0
    BROTLI_DCHECK(*out_size <= i);
646
0
    if (v[i] != 0) {
647
0
      v[*out_size] = v[i] + *max_run_length_prefix;
648
0
      ++i;
649
0
      ++(*out_size);
650
0
    } else {
651
0
      uint32_t reps = 1;
652
0
      size_t k;
653
0
      for (k = i + 1; k < in_size && v[k] == 0; ++k) {
654
0
        ++reps;
655
0
      }
656
0
      i += reps;
657
0
      while (reps != 0) {
658
0
        if (reps < (2u << max_prefix)) {
659
0
          uint32_t run_length_prefix = Log2FloorNonZero(reps);
660
0
          const uint32_t extra_bits = reps - (1u << run_length_prefix);
661
0
          v[*out_size] = run_length_prefix + (extra_bits << 9);
662
0
          ++(*out_size);
663
0
          break;
664
0
        } else {
665
0
          const uint32_t extra_bits = (1u << max_prefix) - 1u;
666
0
          v[*out_size] = max_prefix + (extra_bits << 9);
667
0
          reps -= (2u << max_prefix) - 1u;
668
0
          ++(*out_size);
669
0
        }
670
0
      }
671
0
    }
672
0
  }
673
0
}
674
675
0
#define SYMBOL_BITS 9
676
677
typedef struct EncodeContextMapArena {
678
  uint32_t histogram[BROTLI_MAX_CONTEXT_MAP_SYMBOLS];
679
  uint8_t depths[BROTLI_MAX_CONTEXT_MAP_SYMBOLS];
680
  uint16_t bits[BROTLI_MAX_CONTEXT_MAP_SYMBOLS];
681
} EncodeContextMapArena;
682
683
static void EncodeContextMap(MemoryManager* m,
684
                             EncodeContextMapArena* arena,
685
                             const uint32_t* context_map,
686
                             size_t context_map_size,
687
                             size_t num_clusters,
688
                             HuffmanTree* tree,
689
0
                             size_t* storage_ix, uint8_t* storage) {
690
0
  size_t i;
691
0
  uint32_t* rle_symbols;
692
0
  uint32_t max_run_length_prefix = 6;
693
0
  size_t num_rle_symbols = 0;
694
0
  uint32_t* BROTLI_RESTRICT const histogram = arena->histogram;
695
0
  static const uint32_t kSymbolMask = (1u << SYMBOL_BITS) - 1u;
696
0
  uint8_t* BROTLI_RESTRICT const depths = arena->depths;
697
0
  uint16_t* BROTLI_RESTRICT const bits = arena->bits;
698
699
0
  StoreVarLenUint8(num_clusters - 1, storage_ix, storage);
700
701
0
  if (num_clusters == 1) {
702
0
    return;
703
0
  }
704
705
0
  rle_symbols = BROTLI_ALLOC(m, uint32_t, context_map_size);
706
0
  if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(rle_symbols)) return;
707
0
  MoveToFrontTransform(context_map, context_map_size, rle_symbols);
708
0
  RunLengthCodeZeros(context_map_size, rle_symbols,
709
0
                     &num_rle_symbols, &max_run_length_prefix);
710
0
  memset(histogram, 0, sizeof(arena->histogram));
711
0
  for (i = 0; i < num_rle_symbols; ++i) {
712
0
    ++histogram[rle_symbols[i] & kSymbolMask];
713
0
  }
714
0
  {
715
0
    BROTLI_BOOL use_rle = TO_BROTLI_BOOL(max_run_length_prefix > 0);
716
0
    BrotliWriteBits(1, (uint64_t)use_rle, storage_ix, storage);
717
0
    if (use_rle) {
718
0
      BrotliWriteBits(4, max_run_length_prefix - 1, storage_ix, storage);
719
0
    }
720
0
  }
721
0
  BuildAndStoreHuffmanTree(histogram, num_clusters + max_run_length_prefix,
722
0
                           num_clusters + max_run_length_prefix,
723
0
                           tree, depths, bits, storage_ix, storage);
724
0
  for (i = 0; i < num_rle_symbols; ++i) {
725
0
    const uint32_t rle_symbol = rle_symbols[i] & kSymbolMask;
726
0
    const uint32_t extra_bits_val = rle_symbols[i] >> SYMBOL_BITS;
727
0
    BrotliWriteBits(depths[rle_symbol], bits[rle_symbol], storage_ix, storage);
728
0
    if (rle_symbol > 0 && rle_symbol <= max_run_length_prefix) {
729
0
      BrotliWriteBits(rle_symbol, extra_bits_val, storage_ix, storage);
730
0
    }
731
0
  }
732
0
  BrotliWriteBits(1, 1, storage_ix, storage);  /* use move-to-front */
733
0
  BROTLI_FREE(m, rle_symbols);
734
0
}
735
736
/* Stores the block switch command with index block_ix to the bit stream. */
737
static BROTLI_INLINE void StoreBlockSwitch(BlockSplitCode* code,
738
                                           const uint32_t block_len,
739
                                           const uint8_t block_type,
740
                                           BROTLI_BOOL is_first_block,
741
                                           size_t* storage_ix,
742
0
                                           uint8_t* storage) {
743
0
  size_t typecode = NextBlockTypeCode(&code->type_code_calculator, block_type);
744
0
  size_t lencode;
745
0
  uint32_t len_nextra;
746
0
  uint32_t len_extra;
747
0
  if (!is_first_block) {
748
0
    BrotliWriteBits(code->type_depths[typecode], code->type_bits[typecode],
749
0
                    storage_ix, storage);
750
0
  }
751
0
  GetBlockLengthPrefixCode(block_len, &lencode, &len_nextra, &len_extra);
752
753
0
  BrotliWriteBits(code->length_depths[lencode], code->length_bits[lencode],
754
0
                  storage_ix, storage);
755
0
  BrotliWriteBits(len_nextra, len_extra, storage_ix, storage);
756
0
}
757
758
/* Builds a BlockSplitCode data structure from the block split given by the
759
   vector of block types and block lengths and stores it to the bit stream. */
760
static void BuildAndStoreBlockSplitCode(const uint8_t* types,
761
                                        const uint32_t* lengths,
762
                                        const size_t num_blocks,
763
                                        const size_t num_types,
764
                                        HuffmanTree* tree,
765
                                        BlockSplitCode* code,
766
                                        size_t* storage_ix,
767
0
                                        uint8_t* storage) {
768
0
  uint32_t type_histo[BROTLI_MAX_BLOCK_TYPE_SYMBOLS];
769
0
  uint32_t length_histo[BROTLI_NUM_BLOCK_LEN_SYMBOLS];
770
0
  size_t i;
771
0
  BlockTypeCodeCalculator type_code_calculator;
772
0
  memset(type_histo, 0, (num_types + 2) * sizeof(type_histo[0]));
773
0
  memset(length_histo, 0, sizeof(length_histo));
774
0
  InitBlockTypeCodeCalculator(&type_code_calculator);
775
0
  for (i = 0; i < num_blocks; ++i) {
776
0
    size_t type_code = NextBlockTypeCode(&type_code_calculator, types[i]);
777
0
    if (i != 0) ++type_histo[type_code];
778
0
    ++length_histo[BlockLengthPrefixCode(lengths[i])];
779
0
  }
780
0
  StoreVarLenUint8(num_types - 1, storage_ix, storage);
781
0
  if (num_types > 1) {  /* TODO(eustas): else? could StoreBlockSwitch occur? */
782
0
    BuildAndStoreHuffmanTree(&type_histo[0], num_types + 2, num_types + 2, tree,
783
0
                             &code->type_depths[0], &code->type_bits[0],
784
0
                             storage_ix, storage);
785
0
    BuildAndStoreHuffmanTree(&length_histo[0], BROTLI_NUM_BLOCK_LEN_SYMBOLS,
786
0
                             BROTLI_NUM_BLOCK_LEN_SYMBOLS,
787
0
                             tree, &code->length_depths[0],
788
0
                             &code->length_bits[0], storage_ix, storage);
789
0
    StoreBlockSwitch(code, lengths[0], types[0], 1, storage_ix, storage);
790
0
  }
791
0
}
792
793
/* Stores a context map where the histogram type is always the block type. */
794
static void StoreTrivialContextMap(EncodeContextMapArena* arena,
795
                                   size_t num_types,
796
                                   size_t context_bits,
797
                                   HuffmanTree* tree,
798
                                   size_t* storage_ix,
799
0
                                   uint8_t* storage) {
800
0
  StoreVarLenUint8(num_types - 1, storage_ix, storage);
801
0
  if (num_types > 1) {
802
0
    size_t repeat_code = context_bits - 1u;
803
0
    size_t repeat_bits = (1u << repeat_code) - 1u;
804
0
    size_t alphabet_size = num_types + repeat_code;
805
0
    uint32_t* BROTLI_RESTRICT const histogram = arena->histogram;
806
0
    uint8_t* BROTLI_RESTRICT const depths = arena->depths;
807
0
    uint16_t* BROTLI_RESTRICT const bits = arena->bits;
808
0
    size_t i;
809
0
    memset(histogram, 0, alphabet_size * sizeof(histogram[0]));
810
    /* Write RLEMAX. */
811
0
    BrotliWriteBits(1, 1, storage_ix, storage);
812
0
    BrotliWriteBits(4, repeat_code - 1, storage_ix, storage);
813
0
    histogram[repeat_code] = (uint32_t)num_types;
814
0
    histogram[0] = 1;
815
0
    for (i = context_bits; i < alphabet_size; ++i) {
816
0
      histogram[i] = 1;
817
0
    }
818
0
    BuildAndStoreHuffmanTree(histogram, alphabet_size, alphabet_size,
819
0
                             tree, depths, bits, storage_ix, storage);
820
0
    for (i = 0; i < num_types; ++i) {
821
0
      size_t code = (i == 0 ? 0 : i + context_bits - 1);
822
0
      BrotliWriteBits(depths[code], bits[code], storage_ix, storage);
823
0
      BrotliWriteBits(
824
0
          depths[repeat_code], bits[repeat_code], storage_ix, storage);
825
0
      BrotliWriteBits(repeat_code, repeat_bits, storage_ix, storage);
826
0
    }
827
    /* Write IMTF (inverse-move-to-front) bit. */
828
0
    BrotliWriteBits(1, 1, storage_ix, storage);
829
0
  }
830
0
}
831
832
/* Manages the encoding of one block category (literal, command or distance). */
833
typedef struct BlockEncoder {
834
  size_t histogram_length_;
835
  size_t num_block_types_;
836
  const uint8_t* block_types_;  /* Not owned. */
837
  const uint32_t* block_lengths_;  /* Not owned. */
838
  size_t num_blocks_;
839
  BlockSplitCode block_split_code_;
840
  size_t block_ix_;
841
  size_t block_len_;
842
  size_t entropy_ix_;
843
  uint8_t* depths_;
844
  uint16_t* bits_;
845
} BlockEncoder;
846
847
static void InitBlockEncoder(BlockEncoder* self, size_t histogram_length,
848
    size_t num_block_types, const uint8_t* block_types,
849
0
    const uint32_t* block_lengths, const size_t num_blocks) {
850
0
  self->histogram_length_ = histogram_length;
851
0
  self->num_block_types_ = num_block_types;
852
0
  self->block_types_ = block_types;
853
0
  self->block_lengths_ = block_lengths;
854
0
  self->num_blocks_ = num_blocks;
855
0
  InitBlockTypeCodeCalculator(&self->block_split_code_.type_code_calculator);
856
0
  self->block_ix_ = 0;
857
0
  self->block_len_ = num_blocks == 0 ? 0 : block_lengths[0];
858
0
  self->entropy_ix_ = 0;
859
0
  self->depths_ = 0;
860
0
  self->bits_ = 0;
861
0
}
862
863
0
static void CleanupBlockEncoder(MemoryManager* m, BlockEncoder* self) {
864
0
  BROTLI_FREE(m, self->depths_);
865
0
  BROTLI_FREE(m, self->bits_);
866
0
}
867
868
/* Creates entropy codes of block lengths and block types and stores them
869
   to the bit stream. */
870
static void BuildAndStoreBlockSwitchEntropyCodes(BlockEncoder* self,
871
0
    HuffmanTree* tree, size_t* storage_ix, uint8_t* storage) {
872
0
  BuildAndStoreBlockSplitCode(self->block_types_, self->block_lengths_,
873
0
      self->num_blocks_, self->num_block_types_, tree, &self->block_split_code_,
874
0
      storage_ix, storage);
875
0
}
876
877
/* Stores the next symbol with the entropy code of the current block type.
878
   Updates the block type and block length at block boundaries. */
879
static void StoreSymbol(BlockEncoder* self, size_t symbol, size_t* storage_ix,
880
0
    uint8_t* storage) {
881
0
  if (self->block_len_ == 0) {
882
0
    size_t block_ix = ++self->block_ix_;
883
0
    uint32_t block_len = self->block_lengths_[block_ix];
884
0
    uint8_t block_type = self->block_types_[block_ix];
885
0
    self->block_len_ = block_len;
886
0
    self->entropy_ix_ = block_type * self->histogram_length_;
887
0
    StoreBlockSwitch(&self->block_split_code_, block_len, block_type, 0,
888
0
        storage_ix, storage);
889
0
  }
890
0
  --self->block_len_;
891
0
  {
892
0
    size_t ix = self->entropy_ix_ + symbol;
893
0
    BrotliWriteBits(self->depths_[ix], self->bits_[ix], storage_ix, storage);
894
0
  }
895
0
}
896
897
/* Stores the next symbol with the entropy code of the current block type and
898
   context value.
899
   Updates the block type and block length at block boundaries. */
900
static void StoreSymbolWithContext(BlockEncoder* self, size_t symbol,
901
    size_t context, const uint32_t* context_map, size_t* storage_ix,
902
0
    uint8_t* storage, const size_t context_bits) {
903
0
  if (self->block_len_ == 0) {
904
0
    size_t block_ix = ++self->block_ix_;
905
0
    uint32_t block_len = self->block_lengths_[block_ix];
906
0
    uint8_t block_type = self->block_types_[block_ix];
907
0
    self->block_len_ = block_len;
908
0
    self->entropy_ix_ = (size_t)block_type << context_bits;
909
0
    StoreBlockSwitch(&self->block_split_code_, block_len, block_type, 0,
910
0
        storage_ix, storage);
911
0
  }
912
0
  --self->block_len_;
913
0
  {
914
0
    size_t histo_ix = context_map[self->entropy_ix_ + context];
915
0
    size_t ix = histo_ix * self->histogram_length_ + symbol;
916
0
    BrotliWriteBits(self->depths_[ix], self->bits_[ix], storage_ix, storage);
917
0
  }
918
0
}
919
920
#define FN(X) X ## Literal
921
/* NOLINTNEXTLINE(build/include) */
922
#include "block_encoder_inc.h"
923
#undef FN
924
925
#define FN(X) X ## Command
926
/* NOLINTNEXTLINE(build/include) */
927
#include "block_encoder_inc.h"
928
#undef FN
929
930
#define FN(X) X ## Distance
931
/* NOLINTNEXTLINE(build/include) */
932
#include "block_encoder_inc.h"
933
#undef FN
934
935
0
static void JumpToByteBoundary(size_t* storage_ix, uint8_t* storage) {
936
0
  *storage_ix = (*storage_ix + 7u) & ~7u;
937
0
  storage[*storage_ix >> 3] = 0;
938
0
}
939
940
typedef struct StoreMetablockArena {
941
  BlockEncoder literal_enc;
942
  BlockEncoder command_enc;
943
  BlockEncoder distance_enc;
944
  EncodeContextMapArena context_map_arena;
945
} StoreMetablockArena;
946
947
void BrotliStoreMetaBlock(MemoryManager* m,
948
    const uint8_t* input, size_t start_pos, size_t length, size_t mask,
949
    uint8_t prev_byte, uint8_t prev_byte2, BROTLI_BOOL is_last,
950
    const BrotliEncoderParams* params, ContextType literal_context_mode,
951
    const Command* commands, size_t n_commands, const MetaBlockSplit* mb,
952
0
    size_t* storage_ix, uint8_t* storage) {
953
954
0
  size_t pos = start_pos;
955
0
  size_t i;
956
0
  uint32_t num_distance_symbols = params->dist.alphabet_size_max;
957
0
  uint32_t num_effective_distance_symbols = params->dist.alphabet_size_limit;
958
0
  HuffmanTree* tree;
959
0
  ContextLut literal_context_lut = BROTLI_CONTEXT_LUT(literal_context_mode);
960
0
  StoreMetablockArena* arena = NULL;
961
0
  BlockEncoder* literal_enc = NULL;
962
0
  BlockEncoder* command_enc = NULL;
963
0
  BlockEncoder* distance_enc = NULL;
964
0
  const BrotliDistanceParams* dist = &params->dist;
965
0
  BROTLI_DCHECK(
966
0
      num_effective_distance_symbols <= BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS);
967
968
0
  StoreCompressedMetaBlockHeader(is_last, length, storage_ix, storage);
969
970
0
  tree = BROTLI_ALLOC(m, HuffmanTree, MAX_HUFFMAN_TREE_SIZE);
971
0
  arena = BROTLI_ALLOC(m, StoreMetablockArena, 1);
972
0
  if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(tree) || BROTLI_IS_NULL(arena)) return;
973
0
  literal_enc = &arena->literal_enc;
974
0
  command_enc = &arena->command_enc;
975
0
  distance_enc = &arena->distance_enc;
976
0
  InitBlockEncoder(literal_enc, BROTLI_NUM_LITERAL_SYMBOLS,
977
0
      mb->literal_split.num_types, mb->literal_split.types,
978
0
      mb->literal_split.lengths, mb->literal_split.num_blocks);
979
0
  InitBlockEncoder(command_enc, BROTLI_NUM_COMMAND_SYMBOLS,
980
0
      mb->command_split.num_types, mb->command_split.types,
981
0
      mb->command_split.lengths, mb->command_split.num_blocks);
982
0
  InitBlockEncoder(distance_enc, num_effective_distance_symbols,
983
0
      mb->distance_split.num_types, mb->distance_split.types,
984
0
      mb->distance_split.lengths, mb->distance_split.num_blocks);
985
986
0
  BuildAndStoreBlockSwitchEntropyCodes(literal_enc, tree, storage_ix, storage);
987
0
  BuildAndStoreBlockSwitchEntropyCodes(command_enc, tree, storage_ix, storage);
988
0
  BuildAndStoreBlockSwitchEntropyCodes(distance_enc, tree, storage_ix, storage);
989
990
0
  BrotliWriteBits(2, dist->distance_postfix_bits, storage_ix, storage);
991
0
  BrotliWriteBits(
992
0
      4, dist->num_direct_distance_codes >> dist->distance_postfix_bits,
993
0
      storage_ix, storage);
994
0
  for (i = 0; i < mb->literal_split.num_types; ++i) {
995
0
    BrotliWriteBits(2, literal_context_mode, storage_ix, storage);
996
0
  }
997
998
0
  if (mb->literal_context_map_size == 0) {
999
0
    StoreTrivialContextMap(
1000
0
        &arena->context_map_arena, mb->literal_histograms_size,
1001
0
        BROTLI_LITERAL_CONTEXT_BITS, tree, storage_ix, storage);
1002
0
  } else {
1003
0
    EncodeContextMap(m, &arena->context_map_arena,
1004
0
        mb->literal_context_map, mb->literal_context_map_size,
1005
0
        mb->literal_histograms_size, tree, storage_ix, storage);
1006
0
    if (BROTLI_IS_OOM(m)) return;
1007
0
  }
1008
1009
0
  if (mb->distance_context_map_size == 0) {
1010
0
    StoreTrivialContextMap(
1011
0
        &arena->context_map_arena, mb->distance_histograms_size,
1012
0
        BROTLI_DISTANCE_CONTEXT_BITS, tree, storage_ix, storage);
1013
0
  } else {
1014
0
    EncodeContextMap(m, &arena->context_map_arena,
1015
0
        mb->distance_context_map, mb->distance_context_map_size,
1016
0
        mb->distance_histograms_size, tree, storage_ix, storage);
1017
0
    if (BROTLI_IS_OOM(m)) return;
1018
0
  }
1019
1020
0
  BuildAndStoreEntropyCodesLiteral(m, literal_enc, mb->literal_histograms,
1021
0
      mb->literal_histograms_size, BROTLI_NUM_LITERAL_SYMBOLS, tree,
1022
0
      storage_ix, storage);
1023
0
  if (BROTLI_IS_OOM(m)) return;
1024
0
  BuildAndStoreEntropyCodesCommand(m, command_enc, mb->command_histograms,
1025
0
      mb->command_histograms_size, BROTLI_NUM_COMMAND_SYMBOLS, tree,
1026
0
      storage_ix, storage);
1027
0
  if (BROTLI_IS_OOM(m)) return;
1028
0
  BuildAndStoreEntropyCodesDistance(m, distance_enc, mb->distance_histograms,
1029
0
      mb->distance_histograms_size, num_distance_symbols, tree,
1030
0
      storage_ix, storage);
1031
0
  if (BROTLI_IS_OOM(m)) return;
1032
0
  BROTLI_FREE(m, tree);
1033
1034
0
  for (i = 0; i < n_commands; ++i) {
1035
0
    const Command cmd = commands[i];
1036
0
    size_t cmd_code = cmd.cmd_prefix_;
1037
0
    StoreSymbol(command_enc, cmd_code, storage_ix, storage);
1038
0
    StoreCommandExtra(&cmd, storage_ix, storage);
1039
0
    if (mb->literal_context_map_size == 0) {
1040
0
      size_t j;
1041
0
      for (j = cmd.insert_len_; j != 0; --j) {
1042
0
        StoreSymbol(literal_enc, input[pos & mask], storage_ix, storage);
1043
0
        ++pos;
1044
0
      }
1045
0
    } else {
1046
0
      size_t j;
1047
0
      for (j = cmd.insert_len_; j != 0; --j) {
1048
0
        size_t context =
1049
0
            BROTLI_CONTEXT(prev_byte, prev_byte2, literal_context_lut);
1050
0
        uint8_t literal = input[pos & mask];
1051
0
        StoreSymbolWithContext(literal_enc, literal, context,
1052
0
            mb->literal_context_map, storage_ix, storage,
1053
0
            BROTLI_LITERAL_CONTEXT_BITS);
1054
0
        prev_byte2 = prev_byte;
1055
0
        prev_byte = literal;
1056
0
        ++pos;
1057
0
      }
1058
0
    }
1059
0
    pos += CommandCopyLen(&cmd);
1060
0
    if (CommandCopyLen(&cmd)) {
1061
0
      prev_byte2 = input[(pos - 2) & mask];
1062
0
      prev_byte = input[(pos - 1) & mask];
1063
0
      if (cmd.cmd_prefix_ >= 128) {
1064
0
        size_t dist_code = cmd.dist_prefix_ & 0x3FF;
1065
0
        uint32_t distnumextra = cmd.dist_prefix_ >> 10;
1066
0
        uint64_t distextra = cmd.dist_extra_;
1067
0
        if (mb->distance_context_map_size == 0) {
1068
0
          StoreSymbol(distance_enc, dist_code, storage_ix, storage);
1069
0
        } else {
1070
0
          size_t context = CommandDistanceContext(&cmd);
1071
0
          StoreSymbolWithContext(distance_enc, dist_code, context,
1072
0
              mb->distance_context_map, storage_ix, storage,
1073
0
              BROTLI_DISTANCE_CONTEXT_BITS);
1074
0
        }
1075
0
        BrotliWriteBits(distnumextra, distextra, storage_ix, storage);
1076
0
      }
1077
0
    }
1078
0
  }
1079
0
  CleanupBlockEncoder(m, distance_enc);
1080
0
  CleanupBlockEncoder(m, command_enc);
1081
0
  CleanupBlockEncoder(m, literal_enc);
1082
0
  BROTLI_FREE(m, arena);
1083
0
  if (is_last) {
1084
0
    JumpToByteBoundary(storage_ix, storage);
1085
0
  }
1086
0
}
1087
1088
static void BuildHistograms(const uint8_t* input,
1089
                            size_t start_pos,
1090
                            size_t mask,
1091
                            const Command* commands,
1092
                            size_t n_commands,
1093
                            HistogramLiteral* lit_histo,
1094
                            HistogramCommand* cmd_histo,
1095
0
                            HistogramDistance* dist_histo) {
1096
0
  size_t pos = start_pos;
1097
0
  size_t i;
1098
0
  for (i = 0; i < n_commands; ++i) {
1099
0
    const Command cmd = commands[i];
1100
0
    size_t j;
1101
0
    HistogramAddCommand(cmd_histo, cmd.cmd_prefix_);
1102
0
    for (j = cmd.insert_len_; j != 0; --j) {
1103
0
      HistogramAddLiteral(lit_histo, input[pos & mask]);
1104
0
      ++pos;
1105
0
    }
1106
0
    pos += CommandCopyLen(&cmd);
1107
0
    if (CommandCopyLen(&cmd) && cmd.cmd_prefix_ >= 128) {
1108
0
      HistogramAddDistance(dist_histo, cmd.dist_prefix_ & 0x3FF);
1109
0
    }
1110
0
  }
1111
0
}
1112
1113
static void StoreDataWithHuffmanCodes(const uint8_t* input,
1114
                                      size_t start_pos,
1115
                                      size_t mask,
1116
                                      const Command* commands,
1117
                                      size_t n_commands,
1118
                                      const uint8_t* lit_depth,
1119
                                      const uint16_t* lit_bits,
1120
                                      const uint8_t* cmd_depth,
1121
                                      const uint16_t* cmd_bits,
1122
                                      const uint8_t* dist_depth,
1123
                                      const uint16_t* dist_bits,
1124
                                      size_t* storage_ix,
1125
0
                                      uint8_t* storage) {
1126
0
  size_t pos = start_pos;
1127
0
  size_t i;
1128
0
  for (i = 0; i < n_commands; ++i) {
1129
0
    const Command cmd = commands[i];
1130
0
    const size_t cmd_code = cmd.cmd_prefix_;
1131
0
    size_t j;
1132
0
    BrotliWriteBits(
1133
0
        cmd_depth[cmd_code], cmd_bits[cmd_code], storage_ix, storage);
1134
0
    StoreCommandExtra(&cmd, storage_ix, storage);
1135
0
    for (j = cmd.insert_len_; j != 0; --j) {
1136
0
      const uint8_t literal = input[pos & mask];
1137
0
      BrotliWriteBits(
1138
0
          lit_depth[literal], lit_bits[literal], storage_ix, storage);
1139
0
      ++pos;
1140
0
    }
1141
0
    pos += CommandCopyLen(&cmd);
1142
0
    if (CommandCopyLen(&cmd) && cmd.cmd_prefix_ >= 128) {
1143
0
      const size_t dist_code = cmd.dist_prefix_ & 0x3FF;
1144
0
      const uint32_t distnumextra = cmd.dist_prefix_ >> 10;
1145
0
      const uint32_t distextra = cmd.dist_extra_;
1146
0
      BrotliWriteBits(dist_depth[dist_code], dist_bits[dist_code],
1147
0
                      storage_ix, storage);
1148
0
      BrotliWriteBits(distnumextra, distextra, storage_ix, storage);
1149
0
    }
1150
0
  }
1151
0
}
1152
1153
/* TODO(eustas): pull alloc/dealloc to caller? */
1154
typedef struct MetablockArena {
1155
  HistogramLiteral lit_histo;
1156
  HistogramCommand cmd_histo;
1157
  HistogramDistance dist_histo;
1158
  /* TODO(eustas): merge bits and depth? */
1159
  uint8_t lit_depth[BROTLI_NUM_LITERAL_SYMBOLS];
1160
  uint16_t lit_bits[BROTLI_NUM_LITERAL_SYMBOLS];
1161
  uint8_t cmd_depth[BROTLI_NUM_COMMAND_SYMBOLS];
1162
  uint16_t cmd_bits[BROTLI_NUM_COMMAND_SYMBOLS];
1163
  uint8_t dist_depth[MAX_SIMPLE_DISTANCE_ALPHABET_SIZE];
1164
  uint16_t dist_bits[MAX_SIMPLE_DISTANCE_ALPHABET_SIZE];
1165
  HuffmanTree tree[MAX_HUFFMAN_TREE_SIZE];
1166
} MetablockArena;
1167
1168
void BrotliStoreMetaBlockTrivial(MemoryManager* m,
1169
    const uint8_t* input, size_t start_pos, size_t length, size_t mask,
1170
    BROTLI_BOOL is_last, const BrotliEncoderParams* params,
1171
    const Command* commands, size_t n_commands,
1172
0
    size_t* storage_ix, uint8_t* storage) {
1173
0
  MetablockArena* arena = BROTLI_ALLOC(m, MetablockArena, 1);
1174
0
  uint32_t num_distance_symbols = params->dist.alphabet_size_max;
1175
0
  if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(arena)) return;
1176
1177
0
  StoreCompressedMetaBlockHeader(is_last, length, storage_ix, storage);
1178
1179
0
  HistogramClearLiteral(&arena->lit_histo);
1180
0
  HistogramClearCommand(&arena->cmd_histo);
1181
0
  HistogramClearDistance(&arena->dist_histo);
1182
1183
0
  BuildHistograms(input, start_pos, mask, commands, n_commands,
1184
0
                  &arena->lit_histo, &arena->cmd_histo, &arena->dist_histo);
1185
1186
0
  BrotliWriteBits(13, 0, storage_ix, storage);
1187
1188
0
  BuildAndStoreHuffmanTree(arena->lit_histo.data_, BROTLI_NUM_LITERAL_SYMBOLS,
1189
0
                           BROTLI_NUM_LITERAL_SYMBOLS, arena->tree,
1190
0
                           arena->lit_depth, arena->lit_bits,
1191
0
                           storage_ix, storage);
1192
0
  BuildAndStoreHuffmanTree(arena->cmd_histo.data_, BROTLI_NUM_COMMAND_SYMBOLS,
1193
0
                           BROTLI_NUM_COMMAND_SYMBOLS, arena->tree,
1194
0
                           arena->cmd_depth, arena->cmd_bits,
1195
0
                           storage_ix, storage);
1196
0
  BuildAndStoreHuffmanTree(arena->dist_histo.data_,
1197
0
                           MAX_SIMPLE_DISTANCE_ALPHABET_SIZE,
1198
0
                           num_distance_symbols, arena->tree,
1199
0
                           arena->dist_depth, arena->dist_bits,
1200
0
                           storage_ix, storage);
1201
0
  StoreDataWithHuffmanCodes(input, start_pos, mask, commands,
1202
0
                            n_commands, arena->lit_depth, arena->lit_bits,
1203
0
                            arena->cmd_depth, arena->cmd_bits,
1204
0
                            arena->dist_depth, arena->dist_bits,
1205
0
                            storage_ix, storage);
1206
0
  BROTLI_FREE(m, arena);
1207
0
  if (is_last) {
1208
0
    JumpToByteBoundary(storage_ix, storage);
1209
0
  }
1210
0
}
1211
1212
void BrotliStoreMetaBlockFast(MemoryManager* m,
1213
    const uint8_t* input, size_t start_pos, size_t length, size_t mask,
1214
    BROTLI_BOOL is_last, const BrotliEncoderParams* params,
1215
    const Command* commands, size_t n_commands,
1216
0
    size_t* storage_ix, uint8_t* storage) {
1217
0
  MetablockArena* arena = BROTLI_ALLOC(m, MetablockArena, 1);
1218
0
  uint32_t num_distance_symbols = params->dist.alphabet_size_max;
1219
0
  uint32_t distance_alphabet_bits =
1220
0
      Log2FloorNonZero(num_distance_symbols - 1) + 1;
1221
0
  if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(arena)) return;
1222
1223
0
  StoreCompressedMetaBlockHeader(is_last, length, storage_ix, storage);
1224
1225
0
  BrotliWriteBits(13, 0, storage_ix, storage);
1226
1227
0
  if (n_commands <= 128) {
1228
0
    uint32_t histogram[BROTLI_NUM_LITERAL_SYMBOLS] = { 0 };
1229
0
    size_t pos = start_pos;
1230
0
    size_t num_literals = 0;
1231
0
    size_t i;
1232
0
    for (i = 0; i < n_commands; ++i) {
1233
0
      const Command cmd = commands[i];
1234
0
      size_t j;
1235
0
      for (j = cmd.insert_len_; j != 0; --j) {
1236
0
        ++histogram[input[pos & mask]];
1237
0
        ++pos;
1238
0
      }
1239
0
      num_literals += cmd.insert_len_;
1240
0
      pos += CommandCopyLen(&cmd);
1241
0
    }
1242
0
    BrotliBuildAndStoreHuffmanTreeFast(arena->tree, histogram, num_literals,
1243
0
                                       /* max_bits = */ 8,
1244
0
                                       arena->lit_depth, arena->lit_bits,
1245
0
                                       storage_ix, storage);
1246
0
    StoreStaticCommandHuffmanTree(storage_ix, storage);
1247
0
    StoreStaticDistanceHuffmanTree(storage_ix, storage);
1248
0
    StoreDataWithHuffmanCodes(input, start_pos, mask, commands,
1249
0
                              n_commands, arena->lit_depth, arena->lit_bits,
1250
0
                              kStaticCommandCodeDepth,
1251
0
                              kStaticCommandCodeBits,
1252
0
                              kStaticDistanceCodeDepth,
1253
0
                              kStaticDistanceCodeBits,
1254
0
                              storage_ix, storage);
1255
0
  } else {
1256
0
    HistogramClearLiteral(&arena->lit_histo);
1257
0
    HistogramClearCommand(&arena->cmd_histo);
1258
0
    HistogramClearDistance(&arena->dist_histo);
1259
0
    BuildHistograms(input, start_pos, mask, commands, n_commands,
1260
0
                    &arena->lit_histo, &arena->cmd_histo, &arena->dist_histo);
1261
0
    BrotliBuildAndStoreHuffmanTreeFast(arena->tree, arena->lit_histo.data_,
1262
0
                                       arena->lit_histo.total_count_,
1263
0
                                       /* max_bits = */ 8,
1264
0
                                       arena->lit_depth, arena->lit_bits,
1265
0
                                       storage_ix, storage);
1266
0
    BrotliBuildAndStoreHuffmanTreeFast(arena->tree, arena->cmd_histo.data_,
1267
0
                                       arena->cmd_histo.total_count_,
1268
0
                                       /* max_bits = */ 10,
1269
0
                                       arena->cmd_depth, arena->cmd_bits,
1270
0
                                       storage_ix, storage);
1271
0
    BrotliBuildAndStoreHuffmanTreeFast(arena->tree, arena->dist_histo.data_,
1272
0
                                       arena->dist_histo.total_count_,
1273
                                       /* max_bits = */
1274
0
                                       distance_alphabet_bits,
1275
0
                                       arena->dist_depth, arena->dist_bits,
1276
0
                                       storage_ix, storage);
1277
0
    StoreDataWithHuffmanCodes(input, start_pos, mask, commands,
1278
0
                              n_commands, arena->lit_depth, arena->lit_bits,
1279
0
                              arena->cmd_depth, arena->cmd_bits,
1280
0
                              arena->dist_depth, arena->dist_bits,
1281
0
                              storage_ix, storage);
1282
0
  }
1283
1284
0
  BROTLI_FREE(m, arena);
1285
1286
0
  if (is_last) {
1287
0
    JumpToByteBoundary(storage_ix, storage);
1288
0
  }
1289
0
}
1290
1291
/* This is for storing uncompressed blocks (simple raw storage of
1292
   bytes-as-bytes). */
1293
void BrotliStoreUncompressedMetaBlock(BROTLI_BOOL is_final_block,
1294
                                      const uint8_t* BROTLI_RESTRICT input,
1295
                                      size_t position, size_t mask,
1296
                                      size_t len,
1297
                                      size_t* BROTLI_RESTRICT storage_ix,
1298
0
                                      uint8_t* BROTLI_RESTRICT storage) {
1299
0
  size_t masked_pos = position & mask;
1300
0
  BrotliStoreUncompressedMetaBlockHeader(len, storage_ix, storage);
1301
0
  JumpToByteBoundary(storage_ix, storage);
1302
1303
0
  if (masked_pos + len > mask + 1) {
1304
0
    size_t len1 = mask + 1 - masked_pos;
1305
0
    memcpy(&storage[*storage_ix >> 3], &input[masked_pos], len1);
1306
0
    *storage_ix += len1 << 3;
1307
0
    len -= len1;
1308
0
    masked_pos = 0;
1309
0
  }
1310
0
  memcpy(&storage[*storage_ix >> 3], &input[masked_pos], len);
1311
0
  *storage_ix += len << 3;
1312
1313
  /* We need to clear the next 4 bytes to continue to be
1314
     compatible with BrotliWriteBits. */
1315
0
  BrotliWriteBitsPrepareStorage(*storage_ix, storage);
1316
1317
  /* Since the uncompressed block itself may not be the final block, add an
1318
     empty one after this. */
1319
0
  if (is_final_block) {
1320
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* islast */
1321
0
    BrotliWriteBits(1, 1, storage_ix, storage);  /* isempty */
1322
0
    JumpToByteBoundary(storage_ix, storage);
1323
0
  }
1324
0
}
1325
1326
#if defined(BROTLI_TEST)
1327
void BrotliGetBlockLengthPrefixCodeForTest(uint32_t len, size_t* code,
1328
                                           uint32_t* n_extra, uint32_t* extra);
1329
void BrotliGetBlockLengthPrefixCodeForTest(uint32_t len, size_t* code,
1330
                                           uint32_t* n_extra, uint32_t* extra) {
1331
  GetBlockLengthPrefixCode(len, code, n_extra, extra);
1332
}
1333
#endif
1334
1335
#if defined(__cplusplus) || defined(c_plusplus)
1336
}  /* extern "C" */
1337
#endif