brotli 0.2.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/main.yml +37 -0
  3. data/.github/workflows/publish.yml +24 -0
  4. data/.gitmodules +1 -1
  5. data/Gemfile +6 -3
  6. data/README.md +2 -2
  7. data/Rakefile +16 -9
  8. data/brotli.gemspec +7 -13
  9. data/ext/brotli/brotli.c +210 -31
  10. data/ext/brotli/buffer.c +1 -7
  11. data/ext/brotli/buffer.h +1 -1
  12. data/ext/brotli/extconf.rb +25 -17
  13. data/lib/brotli/version.rb +1 -1
  14. data/test/brotli_test.rb +107 -0
  15. data/test/brotli_writer_test.rb +36 -0
  16. data/test/test_helper.rb +8 -0
  17. data/vendor/brotli/c/common/constants.c +15 -0
  18. data/vendor/brotli/c/common/constants.h +137 -0
  19. data/vendor/brotli/c/common/context.c +156 -0
  20. data/vendor/brotli/c/common/context.h +4 -152
  21. data/vendor/brotli/c/common/dictionary.bin.br +0 -0
  22. data/vendor/brotli/c/common/dictionary.c +14 -3
  23. data/vendor/brotli/c/common/platform.c +23 -0
  24. data/vendor/brotli/c/common/platform.h +95 -122
  25. data/vendor/brotli/c/common/shared_dictionary.c +521 -0
  26. data/vendor/brotli/c/common/shared_dictionary_internal.h +75 -0
  27. data/vendor/brotli/c/common/transform.c +60 -4
  28. data/vendor/brotli/c/common/transform.h +5 -0
  29. data/vendor/brotli/c/common/version.h +31 -6
  30. data/vendor/brotli/c/dec/bit_reader.c +34 -4
  31. data/vendor/brotli/c/dec/bit_reader.h +221 -107
  32. data/vendor/brotli/c/dec/decode.c +772 -403
  33. data/vendor/brotli/c/dec/huffman.c +7 -4
  34. data/vendor/brotli/c/dec/huffman.h +8 -13
  35. data/vendor/brotli/c/dec/prefix.h +1 -18
  36. data/vendor/brotli/c/dec/state.c +40 -21
  37. data/vendor/brotli/c/dec/state.h +201 -59
  38. data/vendor/brotli/c/enc/backward_references.c +88 -25
  39. data/vendor/brotli/c/enc/backward_references.h +10 -8
  40. data/vendor/brotli/c/enc/backward_references_hq.c +194 -80
  41. data/vendor/brotli/c/enc/backward_references_hq.h +17 -13
  42. data/vendor/brotli/c/enc/backward_references_inc.h +52 -16
  43. data/vendor/brotli/c/enc/bit_cost.c +8 -7
  44. data/vendor/brotli/c/enc/bit_cost.h +5 -4
  45. data/vendor/brotli/c/enc/block_splitter.c +40 -17
  46. data/vendor/brotli/c/enc/block_splitter.h +5 -4
  47. data/vendor/brotli/c/enc/block_splitter_inc.h +99 -49
  48. data/vendor/brotli/c/enc/brotli_bit_stream.c +142 -137
  49. data/vendor/brotli/c/enc/brotli_bit_stream.h +11 -6
  50. data/vendor/brotli/c/enc/cluster.c +10 -9
  51. data/vendor/brotli/c/enc/cluster.h +7 -6
  52. data/vendor/brotli/c/enc/cluster_inc.h +30 -22
  53. data/vendor/brotli/c/enc/command.c +28 -0
  54. data/vendor/brotli/c/enc/command.h +17 -16
  55. data/vendor/brotli/c/enc/compound_dictionary.c +207 -0
  56. data/vendor/brotli/c/enc/compound_dictionary.h +74 -0
  57. data/vendor/brotli/c/enc/compress_fragment.c +93 -83
  58. data/vendor/brotli/c/enc/compress_fragment.h +32 -7
  59. data/vendor/brotli/c/enc/compress_fragment_two_pass.c +100 -88
  60. data/vendor/brotli/c/enc/compress_fragment_two_pass.h +21 -3
  61. data/vendor/brotli/c/enc/dictionary_hash.c +1829 -1101
  62. data/vendor/brotli/c/enc/dictionary_hash.h +2 -1
  63. data/vendor/brotli/c/enc/encode.c +550 -416
  64. data/vendor/brotli/c/enc/encoder_dict.c +613 -5
  65. data/vendor/brotli/c/enc/encoder_dict.h +120 -4
  66. data/vendor/brotli/c/enc/entropy_encode.c +5 -2
  67. data/vendor/brotli/c/enc/entropy_encode.h +4 -3
  68. data/vendor/brotli/c/enc/entropy_encode_static.h +5 -2
  69. data/vendor/brotli/c/enc/fast_log.c +105 -0
  70. data/vendor/brotli/c/enc/fast_log.h +21 -101
  71. data/vendor/brotli/c/enc/find_match_length.h +17 -25
  72. data/vendor/brotli/c/enc/hash.h +350 -120
  73. data/vendor/brotli/c/enc/hash_composite_inc.h +71 -67
  74. data/vendor/brotli/c/enc/hash_forgetful_chain_inc.h +92 -51
  75. data/vendor/brotli/c/enc/hash_longest_match64_inc.h +79 -84
  76. data/vendor/brotli/c/enc/hash_longest_match_inc.h +53 -54
  77. data/vendor/brotli/c/enc/hash_longest_match_quickly_inc.h +93 -62
  78. data/vendor/brotli/c/enc/hash_rolling_inc.h +25 -29
  79. data/vendor/brotli/c/enc/hash_to_binary_tree_inc.h +42 -40
  80. data/vendor/brotli/c/enc/histogram.c +4 -4
  81. data/vendor/brotli/c/enc/histogram.h +7 -6
  82. data/vendor/brotli/c/enc/literal_cost.c +20 -15
  83. data/vendor/brotli/c/enc/literal_cost.h +4 -2
  84. data/vendor/brotli/c/enc/memory.c +29 -5
  85. data/vendor/brotli/c/enc/memory.h +43 -14
  86. data/vendor/brotli/c/enc/metablock.c +95 -85
  87. data/vendor/brotli/c/enc/metablock.h +9 -8
  88. data/vendor/brotli/c/enc/metablock_inc.h +9 -7
  89. data/vendor/brotli/c/enc/params.h +7 -4
  90. data/vendor/brotli/c/enc/prefix.h +3 -2
  91. data/vendor/brotli/c/enc/quality.h +40 -3
  92. data/vendor/brotli/c/enc/ringbuffer.h +8 -4
  93. data/vendor/brotli/c/enc/state.h +104 -0
  94. data/vendor/brotli/c/enc/static_dict.c +60 -4
  95. data/vendor/brotli/c/enc/static_dict.h +3 -2
  96. data/vendor/brotli/c/enc/static_dict_lut.h +2 -0
  97. data/vendor/brotli/c/enc/utf8_util.c +2 -2
  98. data/vendor/brotli/c/enc/utf8_util.h +2 -1
  99. data/vendor/brotli/c/enc/write_bits.h +29 -26
  100. data/vendor/brotli/c/include/brotli/decode.h +67 -2
  101. data/vendor/brotli/c/include/brotli/encode.h +77 -3
  102. data/vendor/brotli/c/include/brotli/port.h +34 -3
  103. data/vendor/brotli/c/include/brotli/shared_dictionary.h +100 -0
  104. metadata +23 -97
  105. data/.travis.yml +0 -31
  106. data/docs/Brotli/Error.html +0 -124
  107. data/docs/Brotli.html +0 -485
  108. data/docs/_index.html +0 -122
  109. data/docs/class_list.html +0 -51
  110. data/docs/css/common.css +0 -1
  111. data/docs/css/full_list.css +0 -58
  112. data/docs/css/style.css +0 -496
  113. data/docs/file.README.html +0 -127
  114. data/docs/file_list.html +0 -56
  115. data/docs/frames.html +0 -17
  116. data/docs/index.html +0 -127
  117. data/docs/js/app.js +0 -292
  118. data/docs/js/full_list.js +0 -216
  119. data/docs/js/jquery.js +0 -4
  120. data/docs/method_list.html +0 -67
  121. data/docs/top-level-namespace.html +0 -110
  122. data/spec/brotli_spec.rb +0 -88
  123. data/spec/inflate_spec.rb +0 -75
  124. data/spec/spec_helper.rb +0 -4
@@ -7,6 +7,8 @@
7
7
  /* Implementation of Brotli compressor. */
8
8
 
9
9
  #include <brotli/encode.h>
10
+ #include <brotli/shared_dictionary.h>
11
+ #include <brotli/types.h>
10
12
 
11
13
  #include <stdlib.h> /* free, malloc */
12
14
  #include <string.h> /* memcpy, memset */
@@ -15,24 +17,26 @@
15
17
  #include "../common/context.h"
16
18
  #include "../common/platform.h"
17
19
  #include "../common/version.h"
18
- #include "./backward_references.h"
19
- #include "./backward_references_hq.h"
20
- #include "./bit_cost.h"
21
- #include "./brotli_bit_stream.h"
22
- #include "./compress_fragment.h"
23
- #include "./compress_fragment_two_pass.h"
24
- #include "./encoder_dict.h"
25
- #include "./entropy_encode.h"
26
- #include "./fast_log.h"
27
- #include "./hash.h"
28
- #include "./histogram.h"
29
- #include "./memory.h"
30
- #include "./metablock.h"
31
- #include "./prefix.h"
32
- #include "./quality.h"
33
- #include "./ringbuffer.h"
34
- #include "./utf8_util.h"
35
- #include "./write_bits.h"
20
+ #include "backward_references.h"
21
+ #include "backward_references_hq.h"
22
+ #include "bit_cost.h"
23
+ #include "brotli_bit_stream.h"
24
+ #include "compress_fragment.h"
25
+ #include "compress_fragment_two_pass.h"
26
+ #include "dictionary_hash.h"
27
+ #include "encoder_dict.h"
28
+ #include "entropy_encode.h"
29
+ #include "fast_log.h"
30
+ #include "hash.h"
31
+ #include "histogram.h"
32
+ #include "memory.h"
33
+ #include "metablock.h"
34
+ #include "prefix.h"
35
+ #include "state.h"
36
+ #include "quality.h"
37
+ #include "ringbuffer.h"
38
+ #include "utf8_util.h"
39
+ #include "write_bits.h"
36
40
 
37
41
  #if defined(__cplusplus) || defined(c_plusplus)
38
42
  extern "C" {
@@ -40,82 +44,6 @@ extern "C" {
40
44
 
41
45
  #define COPY_ARRAY(dst, src) memcpy(dst, src, sizeof(src));
42
46
 
43
- typedef enum BrotliEncoderStreamState {
44
- /* Default state. */
45
- BROTLI_STREAM_PROCESSING = 0,
46
- /* Intermediate state; after next block is emitted, byte-padding should be
47
- performed before getting back to default state. */
48
- BROTLI_STREAM_FLUSH_REQUESTED = 1,
49
- /* Last metablock was produced; no more input is acceptable. */
50
- BROTLI_STREAM_FINISHED = 2,
51
- /* Flushing compressed block and writing meta-data block header. */
52
- BROTLI_STREAM_METADATA_HEAD = 3,
53
- /* Writing metadata block body. */
54
- BROTLI_STREAM_METADATA_BODY = 4
55
- } BrotliEncoderStreamState;
56
-
57
- typedef struct BrotliEncoderStateStruct {
58
- BrotliEncoderParams params;
59
-
60
- MemoryManager memory_manager_;
61
-
62
- HasherHandle hasher_;
63
- uint64_t input_pos_;
64
- RingBuffer ringbuffer_;
65
- size_t cmd_alloc_size_;
66
- Command* commands_;
67
- size_t num_commands_;
68
- size_t num_literals_;
69
- size_t last_insert_len_;
70
- uint64_t last_flush_pos_;
71
- uint64_t last_processed_pos_;
72
- int dist_cache_[BROTLI_NUM_DISTANCE_SHORT_CODES];
73
- int saved_dist_cache_[4];
74
- uint16_t last_bytes_;
75
- uint8_t last_bytes_bits_;
76
- uint8_t prev_byte_;
77
- uint8_t prev_byte2_;
78
- size_t storage_size_;
79
- uint8_t* storage_;
80
- /* Hash table for FAST_ONE_PASS_COMPRESSION_QUALITY mode. */
81
- int small_table_[1 << 10]; /* 4KiB */
82
- int* large_table_; /* Allocated only when needed */
83
- size_t large_table_size_;
84
- /* Command and distance prefix codes (each 64 symbols, stored back-to-back)
85
- used for the next block in FAST_ONE_PASS_COMPRESSION_QUALITY. The command
86
- prefix code is over a smaller alphabet with the following 64 symbols:
87
- 0 - 15: insert length code 0, copy length code 0 - 15, same distance
88
- 16 - 39: insert length code 0, copy length code 0 - 23
89
- 40 - 63: insert length code 0 - 23, copy length code 0
90
- Note that symbols 16 and 40 represent the same code in the full alphabet,
91
- but we do not use either of them in FAST_ONE_PASS_COMPRESSION_QUALITY. */
92
- uint8_t cmd_depths_[128];
93
- uint16_t cmd_bits_[128];
94
- /* The compressed form of the command and distance prefix codes for the next
95
- block in FAST_ONE_PASS_COMPRESSION_QUALITY. */
96
- uint8_t cmd_code_[512];
97
- size_t cmd_code_numbits_;
98
- /* Command and literal buffers for FAST_TWO_PASS_COMPRESSION_QUALITY. */
99
- uint32_t* command_buf_;
100
- uint8_t* literal_buf_;
101
-
102
- uint8_t* next_out_;
103
- size_t available_out_;
104
- size_t total_out_;
105
- /* Temporary buffer for padding flush bits or metadata block header / body. */
106
- union {
107
- uint64_t u64[2];
108
- uint8_t u8[16];
109
- } tiny_buf_;
110
- uint32_t remaining_metadata_bytes_;
111
- BrotliEncoderStreamState stream_state_;
112
-
113
- BROTLI_BOOL is_last_block_emitted_;
114
- BROTLI_BOOL is_initialized_;
115
- } BrotliEncoderStateStruct;
116
-
117
- static BROTLI_BOOL EnsureInitialized(BrotliEncoderState* s);
118
-
119
47
  static size_t InputBlockSize(BrotliEncoderState* s) {
120
48
  return (size_t)1 << s->params.lgblock;
121
49
  }
@@ -135,7 +63,7 @@ BROTLI_BOOL BrotliEncoderSetParameter(
135
63
  BrotliEncoderState* state, BrotliEncoderParameter p, uint32_t value) {
136
64
  /* Changing parameters on the fly is not implemented yet. */
137
65
  if (state->is_initialized_) return BROTLI_FALSE;
138
- /* TODO: Validate/clamp parameters here. */
66
+ /* TODO(eustas): Validate/clamp parameters here. */
139
67
  switch (p) {
140
68
  case BROTLI_PARAM_MODE:
141
69
  state->params.mode = (BrotliEncoderMode)value;
@@ -174,6 +102,11 @@ BROTLI_BOOL BrotliEncoderSetParameter(
174
102
  state->params.dist.num_direct_distance_codes = value;
175
103
  return BROTLI_TRUE;
176
104
 
105
+ case BROTLI_PARAM_STREAM_OFFSET:
106
+ if (value > (1u << 30)) return BROTLI_FALSE;
107
+ state->params.stream_offset = value;
108
+ return BROTLI_TRUE;
109
+
177
110
  default: return BROTLI_FALSE;
178
111
  }
179
112
  }
@@ -195,7 +128,7 @@ static uint8_t* GetBrotliStorage(BrotliEncoderState* s, size_t size) {
195
128
  if (s->storage_size_ < size) {
196
129
  BROTLI_FREE(m, s->storage_);
197
130
  s->storage_ = BROTLI_ALLOC(m, uint8_t, size);
198
- if (BROTLI_IS_OOM(m)) return NULL;
131
+ if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(s->storage_)) return NULL;
199
132
  s->storage_size_ = size;
200
133
  }
201
134
  return s->storage_;
@@ -234,7 +167,7 @@ static int* GetHashTable(BrotliEncoderState* s, int quality,
234
167
  s->large_table_size_ = htsize;
235
168
  BROTLI_FREE(m, s->large_table_);
236
169
  s->large_table_ = BROTLI_ALLOC(m, int, htsize);
237
- if (BROTLI_IS_OOM(m)) return 0;
170
+ if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(s->large_table_)) return 0;
238
171
  }
239
172
  table = s->large_table_;
240
173
  }
@@ -266,11 +199,9 @@ static void EncodeWindowBits(int lgwin, BROTLI_BOOL large_window,
266
199
  }
267
200
  }
268
201
 
202
+ /* TODO(eustas): move to compress_fragment.c? */
269
203
  /* Initializes the command and distance prefix codes for the first block. */
270
- static void InitCommandPrefixCodes(uint8_t cmd_depths[128],
271
- uint16_t cmd_bits[128],
272
- uint8_t cmd_code[512],
273
- size_t* cmd_code_numbits) {
204
+ static void InitCommandPrefixCodes(BrotliOnePassArena* s) {
274
205
  static const uint8_t kDefaultCommandDepths[128] = {
275
206
  0, 4, 4, 5, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
276
207
  0, 0, 0, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7,
@@ -303,13 +234,13 @@ static void InitCommandPrefixCodes(uint8_t cmd_depths[128],
303
234
  0x46, 0xe1, 0xb0, 0xd0, 0x4e, 0xb2, 0xf7, 0x04, 0x00,
304
235
  };
305
236
  static const size_t kDefaultCommandCodeNumBits = 448;
306
- COPY_ARRAY(cmd_depths, kDefaultCommandDepths);
307
- COPY_ARRAY(cmd_bits, kDefaultCommandBits);
237
+ COPY_ARRAY(s->cmd_depth, kDefaultCommandDepths);
238
+ COPY_ARRAY(s->cmd_bits, kDefaultCommandBits);
308
239
 
309
240
  /* Initialize the pre-compressed form of the command and distance prefix
310
241
  codes. */
311
- COPY_ARRAY(cmd_code, kDefaultCommandCode);
312
- *cmd_code_numbits = kDefaultCommandCodeNumBits;
242
+ COPY_ARRAY(s->cmd_code, kDefaultCommandCode);
243
+ s->cmd_code_numbits = kDefaultCommandCodeNumBits;
313
244
  }
314
245
 
315
246
  /* Decide about the context map based on the ability of the prediction
@@ -384,7 +315,8 @@ static void ChooseContextMap(int quality,
384
315
  first 5 bits of literals. */
385
316
  static BROTLI_BOOL ShouldUseComplexStaticContextMap(const uint8_t* input,
386
317
  size_t start_pos, size_t length, size_t mask, int quality, size_t size_hint,
387
- size_t* num_literal_contexts, const uint32_t** literal_context_map) {
318
+ size_t* num_literal_contexts, const uint32_t** literal_context_map,
319
+ uint32_t* arena) {
388
320
  static const uint32_t kStaticContextMapComplexUTF8[64] = {
389
321
  11, 11, 12, 12, /* 0 special */
390
322
  0, 0, 0, 0, /* 4 lf */
@@ -409,16 +341,17 @@ static BROTLI_BOOL ShouldUseComplexStaticContextMap(const uint8_t* input,
409
341
  return BROTLI_FALSE;
410
342
  } else {
411
343
  const size_t end_pos = start_pos + length;
412
- /* To make entropy calculations faster and to fit on the stack, we collect
413
- histograms over the 5 most significant bits of literals. One histogram
344
+ /* To make entropy calculations faster, we collect histograms
345
+ over the 5 most significant bits of literals. One histogram
414
346
  without context and 13 additional histograms for each context value. */
415
- uint32_t combined_histo[32] = { 0 };
416
- uint32_t context_histo[13][32] = { { 0 } };
347
+ uint32_t* BROTLI_RESTRICT const combined_histo = arena;
348
+ uint32_t* BROTLI_RESTRICT const context_histo = arena + 32;
417
349
  uint32_t total = 0;
418
350
  double entropy[3];
419
351
  size_t dummy;
420
352
  size_t i;
421
353
  ContextLut utf8_lut = BROTLI_CONTEXT_LUT(CONTEXT_UTF8);
354
+ memset(arena, 0, sizeof(arena[0]) * 32 * 14);
422
355
  for (; start_pos + 64 <= end_pos; start_pos += 4096) {
423
356
  const size_t stride_end_pos = start_pos + 64;
424
357
  uint8_t prev2 = input[start_pos & mask];
@@ -432,7 +365,7 @@ static BROTLI_BOOL ShouldUseComplexStaticContextMap(const uint8_t* input,
432
365
  BROTLI_CONTEXT(prev1, prev2, utf8_lut)];
433
366
  ++total;
434
367
  ++combined_histo[literal >> 3];
435
- ++context_histo[context][literal >> 3];
368
+ ++context_histo[(context << 5) + (literal >> 3)];
436
369
  prev2 = prev1;
437
370
  prev1 = literal;
438
371
  }
@@ -440,7 +373,7 @@ static BROTLI_BOOL ShouldUseComplexStaticContextMap(const uint8_t* input,
440
373
  entropy[1] = ShannonEntropy(combined_histo, 32, &dummy);
441
374
  entropy[2] = 0;
442
375
  for (i = 0; i < 13; ++i) {
443
- entropy[2] += ShannonEntropy(&context_histo[i][0], 32, &dummy);
376
+ entropy[2] += ShannonEntropy(context_histo + (i << 5), 32, &dummy);
444
377
  }
445
378
  entropy[0] = 1.0 / (double)total;
446
379
  entropy[1] *= entropy[0];
@@ -464,19 +397,21 @@ static BROTLI_BOOL ShouldUseComplexStaticContextMap(const uint8_t* input,
464
397
 
465
398
  static void DecideOverLiteralContextModeling(const uint8_t* input,
466
399
  size_t start_pos, size_t length, size_t mask, int quality, size_t size_hint,
467
- size_t* num_literal_contexts, const uint32_t** literal_context_map) {
400
+ size_t* num_literal_contexts, const uint32_t** literal_context_map,
401
+ uint32_t* arena) {
468
402
  if (quality < MIN_QUALITY_FOR_CONTEXT_MODELING || length < 64) {
469
403
  return;
470
404
  } else if (ShouldUseComplexStaticContextMap(
471
405
  input, start_pos, length, mask, quality, size_hint,
472
- num_literal_contexts, literal_context_map)) {
406
+ num_literal_contexts, literal_context_map, arena)) {
473
407
  /* Context map was already set, nothing else to do. */
474
408
  } else {
475
409
  /* Gather bi-gram data of the UTF8 byte prefixes. To make the analysis of
476
410
  UTF8 data faster we only examine 64 byte long strides at every 4kB
477
411
  intervals. */
478
412
  const size_t end_pos = start_pos + length;
479
- uint32_t bigram_prefix_histo[9] = { 0 };
413
+ uint32_t* BROTLI_RESTRICT const bigram_prefix_histo = arena;
414
+ memset(bigram_prefix_histo, 0, sizeof(arena[0]) * 9);
480
415
  for (; start_pos + 64 <= end_pos; start_pos += 4096) {
481
416
  static const int lut[4] = { 0, 0, 1, 2 };
482
417
  const size_t stride_end_pos = start_pos + 64;
@@ -496,10 +431,10 @@ static void DecideOverLiteralContextModeling(const uint8_t* input,
496
431
  static BROTLI_BOOL ShouldCompress(
497
432
  const uint8_t* data, const size_t mask, const uint64_t last_flush_pos,
498
433
  const size_t bytes, const size_t num_literals, const size_t num_commands) {
499
- /* TODO: find more precise minimal block overhead. */
434
+ /* TODO(eustas): find more precise minimal block overhead. */
500
435
  if (bytes <= 2) return BROTLI_FALSE;
501
436
  if (num_commands < (bytes >> 8) + 2) {
502
- if (num_literals > 0.99 * (double)bytes) {
437
+ if ((double)num_literals > 0.99 * (double)bytes) {
503
438
  uint32_t literal_histo[256] = { 0 };
504
439
  static const uint32_t kSampleRate = 13;
505
440
  static const double kMinEntropy = 7.92;
@@ -596,10 +531,14 @@ static void WriteMetaBlockInternal(MemoryManager* m,
596
531
  size_t num_literal_contexts = 1;
597
532
  const uint32_t* literal_context_map = NULL;
598
533
  if (!params->disable_literal_context_modeling) {
534
+ /* TODO(eustas): pull to higher level and reuse. */
535
+ uint32_t* arena = BROTLI_ALLOC(m, uint32_t, 14 * 32);
536
+ if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(arena)) return;
599
537
  DecideOverLiteralContextModeling(
600
538
  data, wrapped_last_flush_pos, bytes, mask, params->quality,
601
539
  params->size_hint, &num_literal_contexts,
602
- &literal_context_map);
540
+ &literal_context_map, arena);
541
+ BROTLI_FREE(m, arena);
603
542
  }
604
543
  BrotliBuildMetaBlockGreedy(m, data, wrapped_last_flush_pos, mask,
605
544
  prev_byte, prev_byte2, literal_context_lut, num_literal_contexts,
@@ -617,11 +556,7 @@ static void WriteMetaBlockInternal(MemoryManager* m,
617
556
  /* The number of distance symbols effectively used for distance
618
557
  histograms. It might be less than distance alphabet size
619
558
  for "Large Window Brotli" (32-bit). */
620
- uint32_t num_effective_dist_codes = block_params.dist.alphabet_size;
621
- if (num_effective_dist_codes > BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS) {
622
- num_effective_dist_codes = BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS;
623
- }
624
- BrotliOptimizeHistograms(num_effective_dist_codes, &mb);
559
+ BrotliOptimizeHistograms(block_params.dist.alphabet_size_limit, &mb);
625
560
  }
626
561
  BrotliStoreMetaBlock(m, data, wrapped_last_flush_pos, bytes, mask,
627
562
  prev_byte, prev_byte2,
@@ -668,22 +603,34 @@ static void ChooseDistanceParams(BrotliEncoderParams* params) {
668
603
  }
669
604
  }
670
605
 
671
- BrotliInitDistanceParams(
672
- params, distance_postfix_bits, num_direct_distance_codes);
606
+ BrotliInitDistanceParams(&params->dist, distance_postfix_bits,
607
+ num_direct_distance_codes, params->large_window);
673
608
  }
674
609
 
675
610
  static BROTLI_BOOL EnsureInitialized(BrotliEncoderState* s) {
676
- if (BROTLI_IS_OOM(&s->memory_manager_)) return BROTLI_FALSE;
611
+ MemoryManager* m = &s->memory_manager_;
612
+ if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
677
613
  if (s->is_initialized_) return BROTLI_TRUE;
678
614
 
679
615
  s->last_bytes_bits_ = 0;
680
616
  s->last_bytes_ = 0;
617
+ s->flint_ = BROTLI_FLINT_DONE;
681
618
  s->remaining_metadata_bytes_ = BROTLI_UINT32_MAX;
682
619
 
683
620
  SanitizeParams(&s->params);
684
621
  s->params.lgblock = ComputeLgBlock(&s->params);
685
622
  ChooseDistanceParams(&s->params);
686
623
 
624
+ if (s->params.stream_offset != 0) {
625
+ s->flint_ = BROTLI_FLINT_NEEDS_2_BYTES;
626
+ /* Poison the distance cache. -16 +- 3 is still less than zero (invalid). */
627
+ s->dist_cache_[0] = -16;
628
+ s->dist_cache_[1] = -16;
629
+ s->dist_cache_[2] = -16;
630
+ s->dist_cache_[3] = -16;
631
+ memcpy(s->saved_dist_cache_, s->dist_cache_, sizeof(s->saved_dist_cache_));
632
+ }
633
+
687
634
  RingBufferSetup(&s->params, &s->ringbuffer_);
688
635
 
689
636
  /* Initialize last byte with stream header. */
@@ -693,13 +640,23 @@ static BROTLI_BOOL EnsureInitialized(BrotliEncoderState* s) {
693
640
  s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY) {
694
641
  lgwin = BROTLI_MAX(int, lgwin, 18);
695
642
  }
696
- EncodeWindowBits(lgwin, s->params.large_window,
697
- &s->last_bytes_, &s->last_bytes_bits_);
643
+ if (s->params.stream_offset == 0) {
644
+ EncodeWindowBits(lgwin, s->params.large_window,
645
+ &s->last_bytes_, &s->last_bytes_bits_);
646
+ } else {
647
+ /* Bigger values have the same effect, but could cause overflows. */
648
+ s->params.stream_offset = BROTLI_MIN(size_t,
649
+ s->params.stream_offset, BROTLI_MAX_BACKWARD_LIMIT(lgwin));
650
+ }
698
651
  }
699
652
 
700
653
  if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY) {
701
- InitCommandPrefixCodes(s->cmd_depths_, s->cmd_bits_,
702
- s->cmd_code_, &s->cmd_code_numbits_);
654
+ s->one_pass_arena_ = BROTLI_ALLOC(m, BrotliOnePassArena, 1);
655
+ if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
656
+ InitCommandPrefixCodes(s->one_pass_arena_);
657
+ } else if (s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY) {
658
+ s->two_pass_arena_ = BROTLI_ALLOC(m, BrotliTwoPassArena, 1);
659
+ if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
703
660
  }
704
661
 
705
662
  s->is_initialized_ = BROTLI_TRUE;
@@ -712,16 +669,23 @@ static void BrotliEncoderInitParams(BrotliEncoderParams* params) {
712
669
  params->quality = BROTLI_DEFAULT_QUALITY;
713
670
  params->lgwin = BROTLI_DEFAULT_WINDOW;
714
671
  params->lgblock = 0;
672
+ params->stream_offset = 0;
715
673
  params->size_hint = 0;
716
674
  params->disable_literal_context_modeling = BROTLI_FALSE;
717
- BrotliInitEncoderDictionary(&params->dictionary);
675
+ BrotliInitSharedEncoderDictionary(&params->dictionary);
718
676
  params->dist.distance_postfix_bits = 0;
719
677
  params->dist.num_direct_distance_codes = 0;
720
- params->dist.alphabet_size =
678
+ params->dist.alphabet_size_max =
721
679
  BROTLI_DISTANCE_ALPHABET_SIZE(0, 0, BROTLI_MAX_DISTANCE_BITS);
680
+ params->dist.alphabet_size_limit = params->dist.alphabet_size_max;
722
681
  params->dist.max_distance = BROTLI_MAX_DISTANCE;
723
682
  }
724
683
 
684
+ static void BrotliEncoderCleanupParams(MemoryManager* m,
685
+ BrotliEncoderParams* params) {
686
+ BrotliCleanupSharedEncoderDictionary(m, &params->dictionary);
687
+ }
688
+
725
689
  static void BrotliEncoderInitState(BrotliEncoderState* s) {
726
690
  BrotliEncoderInitParams(&s->params);
727
691
  s->input_pos_ = 0;
@@ -734,12 +698,14 @@ static void BrotliEncoderInitState(BrotliEncoderState* s) {
734
698
  s->prev_byte2_ = 0;
735
699
  s->storage_size_ = 0;
736
700
  s->storage_ = 0;
737
- s->hasher_ = NULL;
701
+ HasherInit(&s->hasher_);
738
702
  s->large_table_ = NULL;
739
703
  s->large_table_size_ = 0;
740
- s->cmd_code_numbits_ = 0;
704
+ s->one_pass_arena_ = NULL;
705
+ s->two_pass_arena_ = NULL;
741
706
  s->command_buf_ = NULL;
742
707
  s->literal_buf_ = NULL;
708
+ s->total_in_ = 0;
743
709
  s->next_out_ = NULL;
744
710
  s->available_out_ = 0;
745
711
  s->total_out_ = 0;
@@ -764,13 +730,9 @@ static void BrotliEncoderInitState(BrotliEncoderState* s) {
764
730
 
765
731
  BrotliEncoderState* BrotliEncoderCreateInstance(
766
732
  brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
767
- BrotliEncoderState* state = 0;
768
- if (!alloc_func && !free_func) {
769
- state = (BrotliEncoderState*)malloc(sizeof(BrotliEncoderState));
770
- } else if (alloc_func && free_func) {
771
- state = (BrotliEncoderState*)alloc_func(opaque, sizeof(BrotliEncoderState));
772
- }
773
- if (state == 0) {
733
+ BrotliEncoderState* state = (BrotliEncoderState*)BrotliBootstrapAlloc(
734
+ sizeof(BrotliEncoderState), alloc_func, free_func, opaque);
735
+ if (state == NULL) {
774
736
  /* BROTLI_DUMP(); */
775
737
  return 0;
776
738
  }
@@ -780,19 +742,36 @@ BrotliEncoderState* BrotliEncoderCreateInstance(
780
742
  return state;
781
743
  }
782
744
 
745
+ #ifdef BROTLI_REPORTING
746
+ /* When BROTLI_REPORTING is defined extra reporting module have to be linked. */
747
+ void BrotliEncoderOnFinish(const BrotliEncoderState* s);
748
+ #define BROTLI_ENCODER_ON_FINISH(s) BrotliEncoderOnFinish(s);
749
+ #else
750
+ #if !defined(BROTLI_ENCODER_ON_FINISH)
751
+ #define BROTLI_ENCODER_ON_FINISH(s) (void)(s);
752
+ #endif
753
+ #endif
754
+
783
755
  static void BrotliEncoderCleanupState(BrotliEncoderState* s) {
784
756
  MemoryManager* m = &s->memory_manager_;
757
+
758
+ BROTLI_ENCODER_ON_FINISH(s);
759
+
785
760
  if (BROTLI_IS_OOM(m)) {
786
761
  BrotliWipeOutMemoryManager(m);
787
762
  return;
788
763
  }
764
+
789
765
  BROTLI_FREE(m, s->storage_);
790
766
  BROTLI_FREE(m, s->commands_);
791
767
  RingBufferFree(m, &s->ringbuffer_);
792
768
  DestroyHasher(m, &s->hasher_);
793
769
  BROTLI_FREE(m, s->large_table_);
770
+ BROTLI_FREE(m, s->one_pass_arena_);
771
+ BROTLI_FREE(m, s->two_pass_arena_);
794
772
  BROTLI_FREE(m, s->command_buf_);
795
773
  BROTLI_FREE(m, s->literal_buf_);
774
+ BrotliEncoderCleanupParams(m, &s->params);
796
775
  }
797
776
 
798
777
  /* Deinitializes and frees BrotliEncoderState instance. */
@@ -800,11 +779,8 @@ void BrotliEncoderDestroyInstance(BrotliEncoderState* state) {
800
779
  if (!state) {
801
780
  return;
802
781
  } else {
803
- MemoryManager* m = &state->memory_manager_;
804
- brotli_free_func free_func = m->free_func;
805
- void* opaque = m->opaque;
806
782
  BrotliEncoderCleanupState(state);
807
- free_func(opaque, state);
783
+ BrotliBootstrapFree(state, &state->memory_manager_);
808
784
  }
809
785
  }
810
786
 
@@ -893,6 +869,8 @@ static void ExtendLastCommand(BrotliEncoderState* s, uint32_t* bytes,
893
869
  uint64_t cmd_dist = (uint64_t)s->dist_cache_[0];
894
870
  uint32_t distance_code = CommandRestoreDistanceCode(last_command,
895
871
  &s->params.dist);
872
+ const CompoundDictionary* dict = &s->params.dictionary.compound;
873
+ size_t compound_dictionary_size = dict->total_size;
896
874
  if (distance_code < BROTLI_NUM_DISTANCE_SHORT_CODES ||
897
875
  distance_code - (BROTLI_NUM_DISTANCE_SHORT_CODES - 1) == cmd_dist) {
898
876
  if (cmd_dist <= max_distance) {
@@ -902,6 +880,39 @@ static void ExtendLastCommand(BrotliEncoderState* s, uint32_t* bytes,
902
880
  (*bytes)--;
903
881
  (*wrapped_last_processed_pos)++;
904
882
  }
883
+ } else {
884
+ if ((cmd_dist - max_distance - 1) < compound_dictionary_size &&
885
+ last_copy_len < cmd_dist - max_distance) {
886
+ size_t address =
887
+ compound_dictionary_size - (size_t)(cmd_dist - max_distance) +
888
+ (size_t)last_copy_len;
889
+ size_t br_index = 0;
890
+ size_t br_offset;
891
+ const uint8_t* chunk;
892
+ size_t chunk_length;
893
+ while (address >= dict->chunk_offsets[br_index + 1]) br_index++;
894
+ br_offset = address - dict->chunk_offsets[br_index];
895
+ chunk = dict->chunk_source[br_index];
896
+ chunk_length =
897
+ dict->chunk_offsets[br_index + 1] - dict->chunk_offsets[br_index];
898
+ while (*bytes != 0 && data[*wrapped_last_processed_pos & mask] ==
899
+ chunk[br_offset]) {
900
+ last_command->copy_len_++;
901
+ (*bytes)--;
902
+ (*wrapped_last_processed_pos)++;
903
+ if (++br_offset == chunk_length) {
904
+ br_index++;
905
+ br_offset = 0;
906
+ if (br_index != dict->num_chunks) {
907
+ chunk = dict->chunk_source[br_index];
908
+ chunk_length = dict->chunk_offsets[br_index + 1] -
909
+ dict->chunk_offsets[br_index];
910
+ } else {
911
+ break;
912
+ }
913
+ }
914
+ }
915
+ }
905
916
  }
906
917
  /* The copy length is at most the metablock size, and thus expressible. */
907
918
  GetLengthCode(last_command->insert_len_,
@@ -919,8 +930,8 @@ static void ExtendLastCommand(BrotliEncoderState* s, uint32_t* bytes,
919
930
  If |*out_size| is positive, |*output| points to the start of the output
920
931
  data. If |is_last| or |force_flush| is BROTLI_TRUE, an output meta-block is
921
932
  always created. However, until |is_last| is BROTLI_TRUE encoder may retain up
922
- to 7 bits of the last byte of output. To force encoder to dump the remaining
923
- bits use WriteMetadata() to append an empty meta-data block.
933
+ to 7 bits of the last byte of output. Byte-alignment could be enforced by
934
+ emitting an empty meta-data block.
924
935
  Returns BROTLI_FALSE if the size of the input data is larger than
925
936
  input_block_size().
926
937
  */
@@ -934,10 +945,40 @@ static BROTLI_BOOL EncodeData(
934
945
  uint32_t mask;
935
946
  MemoryManager* m = &s->memory_manager_;
936
947
  ContextType literal_context_mode;
948
+ ContextLut literal_context_lut;
949
+ BROTLI_BOOL fast_compress =
950
+ s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY ||
951
+ s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY;
937
952
 
938
953
  data = s->ringbuffer_.buffer_;
939
954
  mask = s->ringbuffer_.mask_;
940
955
 
956
+ if (delta == 0) { /* No new input; still might want to flush or finish. */
957
+ if (!data) { /* No input has been processed so far. */
958
+ if (is_last) { /* Emit complete finalized stream. */
959
+ BROTLI_DCHECK(s->last_bytes_bits_ <= 14);
960
+ s->last_bytes_ |= (uint16_t)(3u << s->last_bytes_bits_);
961
+ s->last_bytes_bits_ = (uint8_t)(s->last_bytes_bits_ + 2u);
962
+ s->tiny_buf_.u8[0] = (uint8_t)s->last_bytes_;
963
+ s->tiny_buf_.u8[1] = (uint8_t)(s->last_bytes_ >> 8);
964
+ *output = s->tiny_buf_.u8;
965
+ *out_size = (s->last_bytes_bits_ + 7u) >> 3u;
966
+ return BROTLI_TRUE;
967
+ } else { /* No data, not last -> no-op. */
968
+ *out_size = 0;
969
+ return BROTLI_TRUE;
970
+ }
971
+ } else {
972
+ /* Fast compress performs flush every block -> flush is no-op. */
973
+ if (!is_last && (!force_flush || fast_compress)) { /* Another no-op. */
974
+ *out_size = 0;
975
+ return BROTLI_TRUE;
976
+ }
977
+ }
978
+ }
979
+ BROTLI_DCHECK(data);
980
+
981
+ if (s->params.quality > s->params.dictionary.max_quality) return BROTLI_FALSE;
941
982
  /* Adding more blocks after "last" block is forbidden. */
942
983
  if (s->is_last_block_emitted_) return BROTLI_FALSE;
943
984
  if (is_last) s->is_last_block_emitted_ = BROTLI_TRUE;
@@ -951,22 +992,18 @@ static BROTLI_BOOL EncodeData(
951
992
  BROTLI_ALLOC(m, uint32_t, kCompressFragmentTwoPassBlockSize);
952
993
  s->literal_buf_ =
953
994
  BROTLI_ALLOC(m, uint8_t, kCompressFragmentTwoPassBlockSize);
954
- if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
995
+ if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(s->command_buf_) ||
996
+ BROTLI_IS_NULL(s->literal_buf_)) {
997
+ return BROTLI_FALSE;
998
+ }
955
999
  }
956
1000
 
957
- if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY ||
958
- s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY) {
1001
+ if (fast_compress) {
959
1002
  uint8_t* storage;
960
1003
  size_t storage_ix = s->last_bytes_bits_;
961
1004
  size_t table_size;
962
1005
  int* table;
963
1006
 
964
- if (delta == 0 && !is_last) {
965
- /* We have no new input data and we don't have to finish the stream, so
966
- nothing to do. */
967
- *out_size = 0;
968
- return BROTLI_TRUE;
969
- }
970
1007
  storage = GetBrotliStorage(s, 2 * bytes + 503);
971
1008
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
972
1009
  storage[0] = (uint8_t)s->last_bytes_;
@@ -975,16 +1012,14 @@ static BROTLI_BOOL EncodeData(
975
1012
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
976
1013
  if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY) {
977
1014
  BrotliCompressFragmentFast(
978
- m, &data[wrapped_last_processed_pos & mask],
1015
+ s->one_pass_arena_, &data[wrapped_last_processed_pos & mask],
979
1016
  bytes, is_last,
980
1017
  table, table_size,
981
- s->cmd_depths_, s->cmd_bits_,
982
- &s->cmd_code_numbits_, s->cmd_code_,
983
1018
  &storage_ix, storage);
984
1019
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
985
1020
  } else {
986
1021
  BrotliCompressFragmentTwoPass(
987
- m, &data[wrapped_last_processed_pos & mask],
1022
+ s->two_pass_arena_, &data[wrapped_last_processed_pos & mask],
988
1023
  bytes, is_last,
989
1024
  s->command_buf_, s->literal_buf_,
990
1025
  table, table_size,
@@ -1009,7 +1044,7 @@ static BROTLI_BOOL EncodeData(
1009
1044
  newsize += (bytes / 4) + 16;
1010
1045
  s->cmd_alloc_size_ = newsize;
1011
1046
  new_commands = BROTLI_ALLOC(m, Command, newsize);
1012
- if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1047
+ if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(new_commands)) return BROTLI_FALSE;
1013
1048
  if (s->commands_) {
1014
1049
  memcpy(new_commands, s->commands_, sizeof(Command) * s->num_commands_);
1015
1050
  BROTLI_FREE(m, s->commands_);
@@ -1024,6 +1059,7 @@ static BROTLI_BOOL EncodeData(
1024
1059
  literal_context_mode = ChooseContextMode(
1025
1060
  &s->params, data, WrapPosition(s->last_flush_pos_),
1026
1061
  mask, (size_t)(s->input_pos_ - s->last_flush_pos_));
1062
+ literal_context_lut = BROTLI_CONTEXT_LUT(literal_context_mode);
1027
1063
 
1028
1064
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1029
1065
 
@@ -1034,20 +1070,23 @@ static BROTLI_BOOL EncodeData(
1034
1070
  if (s->params.quality == ZOPFLIFICATION_QUALITY) {
1035
1071
  BROTLI_DCHECK(s->params.hasher.type == 10);
1036
1072
  BrotliCreateZopfliBackwardReferences(m, bytes, wrapped_last_processed_pos,
1037
- data, mask, &s->params, s->hasher_, s->dist_cache_,
1073
+ data, mask, literal_context_lut, &s->params,
1074
+ &s->hasher_, s->dist_cache_,
1038
1075
  &s->last_insert_len_, &s->commands_[s->num_commands_],
1039
1076
  &s->num_commands_, &s->num_literals_);
1040
1077
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1041
1078
  } else if (s->params.quality == HQ_ZOPFLIFICATION_QUALITY) {
1042
1079
  BROTLI_DCHECK(s->params.hasher.type == 10);
1043
1080
  BrotliCreateHqZopfliBackwardReferences(m, bytes, wrapped_last_processed_pos,
1044
- data, mask, &s->params, s->hasher_, s->dist_cache_,
1081
+ data, mask, literal_context_lut, &s->params,
1082
+ &s->hasher_, s->dist_cache_,
1045
1083
  &s->last_insert_len_, &s->commands_[s->num_commands_],
1046
1084
  &s->num_commands_, &s->num_literals_);
1047
1085
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1048
1086
  } else {
1049
1087
  BrotliCreateBackwardReferences(bytes, wrapped_last_processed_pos,
1050
- data, mask, &s->params, s->hasher_, s->dist_cache_,
1088
+ data, mask, literal_context_lut, &s->params,
1089
+ &s->hasher_, s->dist_cache_,
1051
1090
  &s->last_insert_len_, &s->commands_[s->num_commands_],
1052
1091
  &s->num_commands_, &s->num_literals_);
1053
1092
  }
@@ -1058,7 +1097,7 @@ static BROTLI_BOOL EncodeData(
1058
1097
  const size_t max_commands = max_length / 8;
1059
1098
  const size_t processed_bytes = (size_t)(s->input_pos_ - s->last_flush_pos_);
1060
1099
  /* If maximal possible additional block doesn't fit metablock, flush now. */
1061
- /* TODO: Postpone decision until next block arrives? */
1100
+ /* TODO(eustas): Postpone decision until next block arrives? */
1062
1101
  const BROTLI_BOOL next_input_fits_metablock = TO_BROTLI_BOOL(
1063
1102
  processed_bytes + InputBlockSize(s) <= max_length);
1064
1103
  /* If block splitting is not used, then flush as soon as there is some
@@ -1072,7 +1111,7 @@ static BROTLI_BOOL EncodeData(
1072
1111
  s->num_commands_ < max_commands) {
1073
1112
  /* Merge with next input block. Everything will happen later. */
1074
1113
  if (UpdateLastProcessedPos(s)) {
1075
- HasherReset(s->hasher_);
1114
+ HasherReset(&s->hasher_);
1076
1115
  }
1077
1116
  *out_size = 0;
1078
1117
  return BROTLI_TRUE;
@@ -1113,7 +1152,7 @@ static BROTLI_BOOL EncodeData(
1113
1152
  s->last_bytes_bits_ = storage_ix & 7u;
1114
1153
  s->last_flush_pos_ = s->input_pos_;
1115
1154
  if (UpdateLastProcessedPos(s)) {
1116
- HasherReset(s->hasher_);
1155
+ HasherReset(&s->hasher_);
1117
1156
  }
1118
1157
  if (s->last_flush_pos_ > 0) {
1119
1158
  s->prev_byte_ = data[((uint32_t)s->last_flush_pos_ - 1) & mask];
@@ -1151,7 +1190,7 @@ static size_t WriteMetadataHeader(
1151
1190
  if (block_size == 0) {
1152
1191
  BrotliWriteBits(2, 0, &storage_ix, header);
1153
1192
  } else {
1154
- uint32_t nbits = (block_size == 1) ? 0 :
1193
+ uint32_t nbits = (block_size == 1) ? 1 :
1155
1194
  (Log2FloorNonZero((uint32_t)block_size - 1) + 1);
1156
1195
  uint32_t nbytes = (nbits + 7) / 8;
1157
1196
  BrotliWriteBits(2, nbytes, &storage_ix, header);
@@ -1160,229 +1199,6 @@ static size_t WriteMetadataHeader(
1160
1199
  return (storage_ix + 7u) >> 3;
1161
1200
  }
1162
1201
 
1163
- static BROTLI_BOOL BrotliCompressBufferQuality10(
1164
- int lgwin, size_t input_size, const uint8_t* input_buffer,
1165
- size_t* encoded_size, uint8_t* encoded_buffer) {
1166
- MemoryManager memory_manager;
1167
- MemoryManager* m = &memory_manager;
1168
-
1169
- const size_t mask = BROTLI_SIZE_MAX >> 1;
1170
- int dist_cache[4] = { 4, 11, 15, 16 };
1171
- int saved_dist_cache[4] = { 4, 11, 15, 16 };
1172
- BROTLI_BOOL ok = BROTLI_TRUE;
1173
- const size_t max_out_size = *encoded_size;
1174
- size_t total_out_size = 0;
1175
- uint16_t last_bytes;
1176
- uint8_t last_bytes_bits;
1177
- HasherHandle hasher = NULL;
1178
-
1179
- const size_t hasher_eff_size = BROTLI_MIN(size_t,
1180
- input_size, BROTLI_MAX_BACKWARD_LIMIT(lgwin) + BROTLI_WINDOW_GAP);
1181
-
1182
- BrotliEncoderParams params;
1183
-
1184
- const int lgmetablock = BROTLI_MIN(int, 24, lgwin + 1);
1185
- size_t max_block_size;
1186
- const size_t max_metablock_size = (size_t)1 << lgmetablock;
1187
- const size_t max_literals_per_metablock = max_metablock_size / 8;
1188
- const size_t max_commands_per_metablock = max_metablock_size / 8;
1189
- size_t metablock_start = 0;
1190
- uint8_t prev_byte = 0;
1191
- uint8_t prev_byte2 = 0;
1192
-
1193
- BrotliEncoderInitParams(&params);
1194
- params.quality = 10;
1195
- params.lgwin = lgwin;
1196
- if (lgwin > BROTLI_MAX_WINDOW_BITS) {
1197
- params.large_window = BROTLI_TRUE;
1198
- }
1199
- SanitizeParams(&params);
1200
- params.lgblock = ComputeLgBlock(&params);
1201
- ChooseDistanceParams(&params);
1202
- max_block_size = (size_t)1 << params.lgblock;
1203
-
1204
- BrotliInitMemoryManager(m, 0, 0, 0);
1205
-
1206
- BROTLI_DCHECK(input_size <= mask + 1);
1207
- EncodeWindowBits(lgwin, params.large_window, &last_bytes, &last_bytes_bits);
1208
- InitOrStitchToPreviousBlock(m, &hasher, input_buffer, mask, &params,
1209
- 0, hasher_eff_size, BROTLI_TRUE);
1210
- if (BROTLI_IS_OOM(m)) goto oom;
1211
-
1212
- while (ok && metablock_start < input_size) {
1213
- const size_t metablock_end =
1214
- BROTLI_MIN(size_t, input_size, metablock_start + max_metablock_size);
1215
- const size_t expected_num_commands =
1216
- (metablock_end - metablock_start) / 12 + 16;
1217
- Command* commands = 0;
1218
- size_t num_commands = 0;
1219
- size_t last_insert_len = 0;
1220
- size_t num_literals = 0;
1221
- size_t metablock_size = 0;
1222
- size_t cmd_alloc_size = 0;
1223
- BROTLI_BOOL is_last;
1224
- uint8_t* storage;
1225
- size_t storage_ix;
1226
-
1227
- ContextType literal_context_mode = ChooseContextMode(&params,
1228
- input_buffer, metablock_start, mask, metablock_end - metablock_start);
1229
-
1230
- size_t block_start;
1231
- for (block_start = metablock_start; block_start < metablock_end; ) {
1232
- size_t block_size =
1233
- BROTLI_MIN(size_t, metablock_end - block_start, max_block_size);
1234
- ZopfliNode* nodes = BROTLI_ALLOC(m, ZopfliNode, block_size + 1);
1235
- size_t path_size;
1236
- size_t new_cmd_alloc_size;
1237
- if (BROTLI_IS_OOM(m)) goto oom;
1238
- BrotliInitZopfliNodes(nodes, block_size + 1);
1239
- StitchToPreviousBlockH10(hasher, block_size, block_start,
1240
- input_buffer, mask);
1241
- path_size = BrotliZopfliComputeShortestPath(m, block_size, block_start,
1242
- input_buffer, mask, &params, dist_cache, hasher,
1243
- nodes);
1244
- if (BROTLI_IS_OOM(m)) goto oom;
1245
- /* We allocate a command buffer in the first iteration of this loop that
1246
- will be likely big enough for the whole metablock, so that for most
1247
- inputs we will not have to reallocate in later iterations. We do the
1248
- allocation here and not before the loop, because if the input is small,
1249
- this will be allocated after the Zopfli cost model is freed, so this
1250
- will not increase peak memory usage.
1251
- TODO: If the first allocation is too small, increase command
1252
- buffer size exponentially. */
1253
- new_cmd_alloc_size = BROTLI_MAX(size_t, expected_num_commands,
1254
- num_commands + path_size + 1);
1255
- if (cmd_alloc_size != new_cmd_alloc_size) {
1256
- Command* new_commands = BROTLI_ALLOC(m, Command, new_cmd_alloc_size);
1257
- if (BROTLI_IS_OOM(m)) goto oom;
1258
- cmd_alloc_size = new_cmd_alloc_size;
1259
- if (commands) {
1260
- memcpy(new_commands, commands, sizeof(Command) * num_commands);
1261
- BROTLI_FREE(m, commands);
1262
- }
1263
- commands = new_commands;
1264
- }
1265
- BrotliZopfliCreateCommands(block_size, block_start, &nodes[0], dist_cache,
1266
- &last_insert_len, &params, &commands[num_commands], &num_literals);
1267
- num_commands += path_size;
1268
- block_start += block_size;
1269
- metablock_size += block_size;
1270
- BROTLI_FREE(m, nodes);
1271
- if (num_literals > max_literals_per_metablock ||
1272
- num_commands > max_commands_per_metablock) {
1273
- break;
1274
- }
1275
- }
1276
-
1277
- if (last_insert_len > 0) {
1278
- InitInsertCommand(&commands[num_commands++], last_insert_len);
1279
- num_literals += last_insert_len;
1280
- }
1281
-
1282
- is_last = TO_BROTLI_BOOL(metablock_start + metablock_size == input_size);
1283
- storage = NULL;
1284
- storage_ix = last_bytes_bits;
1285
-
1286
- if (metablock_size == 0) {
1287
- /* Write the ISLAST and ISEMPTY bits. */
1288
- storage = BROTLI_ALLOC(m, uint8_t, 16);
1289
- if (BROTLI_IS_OOM(m)) goto oom;
1290
- storage[0] = (uint8_t)last_bytes;
1291
- storage[1] = (uint8_t)(last_bytes >> 8);
1292
- BrotliWriteBits(2, 3, &storage_ix, storage);
1293
- storage_ix = (storage_ix + 7u) & ~7u;
1294
- } else if (!ShouldCompress(input_buffer, mask, metablock_start,
1295
- metablock_size, num_literals, num_commands)) {
1296
- /* Restore the distance cache, as its last update by
1297
- CreateBackwardReferences is now unused. */
1298
- memcpy(dist_cache, saved_dist_cache, 4 * sizeof(dist_cache[0]));
1299
- storage = BROTLI_ALLOC(m, uint8_t, metablock_size + 16);
1300
- if (BROTLI_IS_OOM(m)) goto oom;
1301
- storage[0] = (uint8_t)last_bytes;
1302
- storage[1] = (uint8_t)(last_bytes >> 8);
1303
- BrotliStoreUncompressedMetaBlock(is_last, input_buffer,
1304
- metablock_start, mask, metablock_size,
1305
- &storage_ix, storage);
1306
- } else {
1307
- MetaBlockSplit mb;
1308
- BrotliEncoderParams block_params = params;
1309
- InitMetaBlockSplit(&mb);
1310
- BrotliBuildMetaBlock(m, input_buffer, metablock_start, mask,
1311
- &block_params,
1312
- prev_byte, prev_byte2,
1313
- commands, num_commands,
1314
- literal_context_mode,
1315
- &mb);
1316
- if (BROTLI_IS_OOM(m)) goto oom;
1317
- {
1318
- /* The number of distance symbols effectively used for distance
1319
- histograms. It might be less than distance alphabet size
1320
- for "Large Window Brotli" (32-bit). */
1321
- uint32_t num_effective_dist_codes = block_params.dist.alphabet_size;
1322
- if (num_effective_dist_codes > BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS) {
1323
- num_effective_dist_codes = BROTLI_NUM_HISTOGRAM_DISTANCE_SYMBOLS;
1324
- }
1325
- BrotliOptimizeHistograms(num_effective_dist_codes, &mb);
1326
- }
1327
- storage = BROTLI_ALLOC(m, uint8_t, 2 * metablock_size + 503);
1328
- if (BROTLI_IS_OOM(m)) goto oom;
1329
- storage[0] = (uint8_t)last_bytes;
1330
- storage[1] = (uint8_t)(last_bytes >> 8);
1331
- BrotliStoreMetaBlock(m, input_buffer, metablock_start, metablock_size,
1332
- mask, prev_byte, prev_byte2,
1333
- is_last,
1334
- &block_params,
1335
- literal_context_mode,
1336
- commands, num_commands,
1337
- &mb,
1338
- &storage_ix, storage);
1339
- if (BROTLI_IS_OOM(m)) goto oom;
1340
- if (metablock_size + 4 < (storage_ix >> 3)) {
1341
- /* Restore the distance cache and last byte. */
1342
- memcpy(dist_cache, saved_dist_cache, 4 * sizeof(dist_cache[0]));
1343
- storage[0] = (uint8_t)last_bytes;
1344
- storage[1] = (uint8_t)(last_bytes >> 8);
1345
- storage_ix = last_bytes_bits;
1346
- BrotliStoreUncompressedMetaBlock(is_last, input_buffer,
1347
- metablock_start, mask,
1348
- metablock_size, &storage_ix, storage);
1349
- }
1350
- DestroyMetaBlockSplit(m, &mb);
1351
- }
1352
- last_bytes = (uint16_t)(storage[storage_ix >> 3]);
1353
- last_bytes_bits = storage_ix & 7u;
1354
- metablock_start += metablock_size;
1355
- if (metablock_start < input_size) {
1356
- prev_byte = input_buffer[metablock_start - 1];
1357
- prev_byte2 = input_buffer[metablock_start - 2];
1358
- }
1359
- /* Save the state of the distance cache in case we need to restore it for
1360
- emitting an uncompressed block. */
1361
- memcpy(saved_dist_cache, dist_cache, 4 * sizeof(dist_cache[0]));
1362
-
1363
- {
1364
- const size_t out_size = storage_ix >> 3;
1365
- total_out_size += out_size;
1366
- if (total_out_size <= max_out_size) {
1367
- memcpy(encoded_buffer, storage, out_size);
1368
- encoded_buffer += out_size;
1369
- } else {
1370
- ok = BROTLI_FALSE;
1371
- }
1372
- }
1373
- BROTLI_FREE(m, storage);
1374
- BROTLI_FREE(m, commands);
1375
- }
1376
-
1377
- *encoded_size = total_out_size;
1378
- DestroyHasher(m, &hasher);
1379
- return ok;
1380
-
1381
- oom:
1382
- BrotliWipeOutMemoryManager(m);
1383
- return BROTLI_FALSE;
1384
- }
1385
-
1386
1202
  size_t BrotliEncoderMaxCompressedSize(size_t input_size) {
1387
1203
  /* [window bits / empty metadata] + N * [uncompressed] + [last empty] */
1388
1204
  size_t num_large_blocks = input_size >> 14;
@@ -1430,8 +1246,9 @@ static size_t MakeUncompressedStream(
1430
1246
 
1431
1247
  BROTLI_BOOL BrotliEncoderCompress(
1432
1248
  int quality, int lgwin, BrotliEncoderMode mode, size_t input_size,
1433
- const uint8_t* input_buffer, size_t* encoded_size,
1434
- uint8_t* encoded_buffer) {
1249
+ const uint8_t input_buffer[BROTLI_ARRAY_PARAM(input_size)],
1250
+ size_t* encoded_size,
1251
+ uint8_t encoded_buffer[BROTLI_ARRAY_PARAM(*encoded_size)]) {
1435
1252
  BrotliEncoderState* s;
1436
1253
  size_t out_size = *encoded_size;
1437
1254
  const uint8_t* input_start = input_buffer;
@@ -1447,17 +1264,6 @@ BROTLI_BOOL BrotliEncoderCompress(
1447
1264
  *encoded_buffer = 6;
1448
1265
  return BROTLI_TRUE;
1449
1266
  }
1450
- if (quality == 10) {
1451
- /* TODO: Implement this direct path for all quality levels. */
1452
- const int lg_win = BROTLI_MIN(int, BROTLI_LARGE_MAX_WINDOW_BITS,
1453
- BROTLI_MAX(int, 16, lgwin));
1454
- int ok = BrotliCompressBufferQuality10(lg_win, input_size, input_buffer,
1455
- encoded_size, encoded_buffer);
1456
- if (!ok || (max_out_size && *encoded_size > max_out_size)) {
1457
- goto fallback;
1458
- }
1459
- return BROTLI_TRUE;
1460
- }
1461
1267
 
1462
1268
  s = BrotliEncoderCreateInstance(0, 0, 0);
1463
1269
  if (!s) {
@@ -1469,6 +1275,7 @@ BROTLI_BOOL BrotliEncoderCompress(
1469
1275
  uint8_t* next_out = encoded_buffer;
1470
1276
  size_t total_out = 0;
1471
1277
  BROTLI_BOOL result = BROTLI_FALSE;
1278
+ /* TODO(eustas): check that parameters are sane. */
1472
1279
  BrotliEncoderSetParameter(s, BROTLI_PARAM_QUALITY, (uint32_t)quality);
1473
1280
  BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, (uint32_t)lgwin);
1474
1281
  BrotliEncoderSetParameter(s, BROTLI_PARAM_MODE, (uint32_t)mode);
@@ -1520,6 +1327,18 @@ static void InjectBytePaddingBlock(BrotliEncoderState* s) {
1520
1327
  s->available_out_ += (seal_bits + 7) >> 3;
1521
1328
  }
1522
1329
 
1330
+ /* Fills the |total_out|, if it is not NULL. */
1331
+ static void SetTotalOut(BrotliEncoderState* s, size_t* total_out) {
1332
+ if (total_out) {
1333
+ /* Saturating conversion uint64_t -> size_t */
1334
+ size_t result = (size_t)-1;
1335
+ if (s->total_out_ < result) {
1336
+ result = (size_t)s->total_out_;
1337
+ }
1338
+ *total_out = result;
1339
+ }
1340
+ }
1341
+
1523
1342
  /* Injects padding bits or pushes compressed data to output.
1524
1343
  Returns false if nothing is done. */
1525
1344
  static BROTLI_BOOL InjectFlushOrPushOutput(BrotliEncoderState* s,
@@ -1539,7 +1358,7 @@ static BROTLI_BOOL InjectFlushOrPushOutput(BrotliEncoderState* s,
1539
1358
  s->next_out_ += copy_output_size;
1540
1359
  s->available_out_ -= copy_output_size;
1541
1360
  s->total_out_ += copy_output_size;
1542
- if (total_out) *total_out = s->total_out_;
1361
+ SetTotalOut(s, total_out);
1543
1362
  return BROTLI_TRUE;
1544
1363
  }
1545
1364
 
@@ -1576,7 +1395,10 @@ static BROTLI_BOOL BrotliEncoderCompressStreamFast(
1576
1395
  BROTLI_ALLOC(m, uint32_t, kCompressFragmentTwoPassBlockSize);
1577
1396
  s->literal_buf_ =
1578
1397
  BROTLI_ALLOC(m, uint8_t, kCompressFragmentTwoPassBlockSize);
1579
- if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1398
+ if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(s->command_buf_) ||
1399
+ BROTLI_IS_NULL(s->literal_buf_)) {
1400
+ return BROTLI_FALSE;
1401
+ }
1580
1402
  }
1581
1403
  if (s->command_buf_) {
1582
1404
  command_buf = s->command_buf_;
@@ -1584,7 +1406,10 @@ static BROTLI_BOOL BrotliEncoderCompressStreamFast(
1584
1406
  } else {
1585
1407
  tmp_command_buf = BROTLI_ALLOC(m, uint32_t, buf_size);
1586
1408
  tmp_literal_buf = BROTLI_ALLOC(m, uint8_t, buf_size);
1587
- if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1409
+ if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(tmp_command_buf) ||
1410
+ BROTLI_IS_NULL(tmp_literal_buf)) {
1411
+ return BROTLI_FALSE;
1412
+ }
1588
1413
  command_buf = tmp_command_buf;
1589
1414
  literal_buf = tmp_literal_buf;
1590
1415
  }
@@ -1630,18 +1455,20 @@ static BROTLI_BOOL BrotliEncoderCompressStreamFast(
1630
1455
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1631
1456
 
1632
1457
  if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY) {
1633
- BrotliCompressFragmentFast(m, *next_in, block_size, is_last, table,
1634
- table_size, s->cmd_depths_, s->cmd_bits_, &s->cmd_code_numbits_,
1635
- s->cmd_code_, &storage_ix, storage);
1458
+ BrotliCompressFragmentFast(s->one_pass_arena_, *next_in, block_size,
1459
+ is_last, table, table_size, &storage_ix, storage);
1636
1460
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1637
1461
  } else {
1638
- BrotliCompressFragmentTwoPass(m, *next_in, block_size, is_last,
1639
- command_buf, literal_buf, table, table_size,
1462
+ BrotliCompressFragmentTwoPass(s->two_pass_arena_, *next_in, block_size,
1463
+ is_last, command_buf, literal_buf, table, table_size,
1640
1464
  &storage_ix, storage);
1641
1465
  if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1642
1466
  }
1643
- *next_in += block_size;
1644
- *available_in -= block_size;
1467
+ if (block_size != 0) {
1468
+ *next_in += block_size;
1469
+ *available_in -= block_size;
1470
+ s->total_in_ += block_size;
1471
+ }
1645
1472
  if (inplace) {
1646
1473
  size_t out_bytes = storage_ix >> 3;
1647
1474
  BROTLI_DCHECK(out_bytes <= *available_out);
@@ -1649,7 +1476,7 @@ static BROTLI_BOOL BrotliEncoderCompressStreamFast(
1649
1476
  *next_out += out_bytes;
1650
1477
  *available_out -= out_bytes;
1651
1478
  s->total_out_ += out_bytes;
1652
- if (total_out) *total_out = s->total_out_;
1479
+ SetTotalOut(s, total_out);
1653
1480
  } else {
1654
1481
  size_t out_bytes = storage_ix >> 3;
1655
1482
  s->next_out_ = storage;
@@ -1718,6 +1545,7 @@ static BROTLI_BOOL ProcessMetadata(
1718
1545
  memcpy(*next_out, *next_in, copy);
1719
1546
  *next_in += copy;
1720
1547
  *available_in -= copy;
1548
+ s->total_in_ += copy; /* not actually data input, though */
1721
1549
  s->remaining_metadata_bytes_ -= copy;
1722
1550
  *next_out += copy;
1723
1551
  *available_out -= copy;
@@ -1728,6 +1556,7 @@ static BROTLI_BOOL ProcessMetadata(
1728
1556
  memcpy(s->next_out_, *next_in, copy);
1729
1557
  *next_in += copy;
1730
1558
  *available_in -= copy;
1559
+ s->total_in_ += copy; /* not actually data input, though */
1731
1560
  s->remaining_metadata_bytes_ -= copy;
1732
1561
  s->available_out_ = copy;
1733
1562
  }
@@ -1755,7 +1584,7 @@ static void UpdateSizeHint(BrotliEncoderState* s, size_t available_in) {
1755
1584
 
1756
1585
  BROTLI_BOOL BrotliEncoderCompressStream(
1757
1586
  BrotliEncoderState* s, BrotliEncoderOperation op, size_t* available_in,
1758
- const uint8_t** next_in, size_t* available_out,uint8_t** next_out,
1587
+ const uint8_t** next_in, size_t* available_out, uint8_t** next_out,
1759
1588
  size_t* total_out) {
1760
1589
  if (!EnsureInitialized(s)) return BROTLI_FALSE;
1761
1590
 
@@ -1786,6 +1615,10 @@ BROTLI_BOOL BrotliEncoderCompressStream(
1786
1615
  }
1787
1616
  while (BROTLI_TRUE) {
1788
1617
  size_t remaining_block_size = RemainingInputBlockSize(s);
1618
+ /* Shorten input to flint size. */
1619
+ if (s->flint_ >= 0 && remaining_block_size > (size_t)s->flint_) {
1620
+ remaining_block_size = (size_t)s->flint_;
1621
+ }
1789
1622
 
1790
1623
  if (remaining_block_size != 0 && *available_in != 0) {
1791
1624
  size_t copy_input_size =
@@ -1793,10 +1626,19 @@ BROTLI_BOOL BrotliEncoderCompressStream(
1793
1626
  CopyInputToRingBuffer(s, copy_input_size, *next_in);
1794
1627
  *next_in += copy_input_size;
1795
1628
  *available_in -= copy_input_size;
1629
+ s->total_in_ += copy_input_size;
1630
+ if (s->flint_ > 0) s->flint_ = (int8_t)(s->flint_ - (int)copy_input_size);
1796
1631
  continue;
1797
1632
  }
1798
1633
 
1799
1634
  if (InjectFlushOrPushOutput(s, available_out, next_out, total_out)) {
1635
+ /* Exit the "emit flint" workflow. */
1636
+ if (s->flint_ == BROTLI_FLINT_WAITING_FOR_FLUSHING) {
1637
+ CheckFlushComplete(s);
1638
+ if (s->stream_state_ == BROTLI_STREAM_PROCESSING) {
1639
+ s->flint_ = BROTLI_FLINT_DONE;
1640
+ }
1641
+ }
1800
1642
  continue;
1801
1643
  }
1802
1644
 
@@ -1810,6 +1652,11 @@ BROTLI_BOOL BrotliEncoderCompressStream(
1810
1652
  BROTLI_BOOL force_flush = TO_BROTLI_BOOL(
1811
1653
  (*available_in == 0) && op == BROTLI_OPERATION_FLUSH);
1812
1654
  BROTLI_BOOL result;
1655
+ /* Force emitting (uncompressed) piece containing flint. */
1656
+ if (!is_last && s->flint_ == 0) {
1657
+ s->flint_ = BROTLI_FLINT_WAITING_FOR_FLUSHING;
1658
+ force_flush = BROTLI_TRUE;
1659
+ }
1813
1660
  UpdateSizeHint(s, *available_in);
1814
1661
  result = EncodeData(s, is_last, force_flush,
1815
1662
  &s->available_out_, &s->next_out_);
@@ -1857,6 +1704,293 @@ uint32_t BrotliEncoderVersion(void) {
1857
1704
  return BROTLI_VERSION;
1858
1705
  }
1859
1706
 
1707
+ BrotliEncoderPreparedDictionary* BrotliEncoderPrepareDictionary(
1708
+ BrotliSharedDictionaryType type, size_t size,
1709
+ const uint8_t data[BROTLI_ARRAY_PARAM(size)], int quality,
1710
+ brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
1711
+ ManagedDictionary* managed_dictionary = NULL;
1712
+ BROTLI_BOOL type_is_known = BROTLI_FALSE;
1713
+ type_is_known |= (type == BROTLI_SHARED_DICTIONARY_RAW);
1714
+ #if defined(BROTLI_EXPERIMENTAL)
1715
+ type_is_known |= (type == BROTLI_SHARED_DICTIONARY_SERIALIZED);
1716
+ #endif /* BROTLI_EXPERIMENTAL */
1717
+ if (!type_is_known) {
1718
+ return NULL;
1719
+ }
1720
+ managed_dictionary =
1721
+ BrotliCreateManagedDictionary(alloc_func, free_func, opaque);
1722
+ if (managed_dictionary == NULL) {
1723
+ return NULL;
1724
+ }
1725
+ if (type == BROTLI_SHARED_DICTIONARY_RAW) {
1726
+ managed_dictionary->dictionary = (uint32_t*)CreatePreparedDictionary(
1727
+ &managed_dictionary->memory_manager_, data, size);
1728
+ }
1729
+ #if defined(BROTLI_EXPERIMENTAL)
1730
+ if (type == BROTLI_SHARED_DICTIONARY_SERIALIZED) {
1731
+ SharedEncoderDictionary* dict = (SharedEncoderDictionary*)BrotliAllocate(
1732
+ &managed_dictionary->memory_manager_, sizeof(SharedEncoderDictionary));
1733
+ managed_dictionary->dictionary = (uint32_t*)dict;
1734
+ if (dict != NULL) {
1735
+ BROTLI_BOOL ok = BrotliInitCustomSharedEncoderDictionary(
1736
+ &managed_dictionary->memory_manager_, data, size, quality, dict);
1737
+ if (!ok) {
1738
+ BrotliFree(&managed_dictionary->memory_manager_, dict);
1739
+ managed_dictionary->dictionary = NULL;
1740
+ }
1741
+ }
1742
+ }
1743
+ #else /* BROTLI_EXPERIMENTAL */
1744
+ (void)quality;
1745
+ #endif /* BROTLI_EXPERIMENTAL */
1746
+ if (managed_dictionary->dictionary == NULL) {
1747
+ BrotliDestroyManagedDictionary(managed_dictionary);
1748
+ return NULL;
1749
+ }
1750
+ return (BrotliEncoderPreparedDictionary*)managed_dictionary;
1751
+ }
1752
+
1753
+ void BrotliEncoderDestroyPreparedDictionary(
1754
+ BrotliEncoderPreparedDictionary* dictionary) {
1755
+ ManagedDictionary* dict = (ManagedDictionary*)dictionary;
1756
+ if (!dictionary) return;
1757
+ /* First field of dictionary structs. */
1758
+ /* Only managed dictionaries are eligible for destruction by this method. */
1759
+ if (dict->magic != kManagedDictionaryMagic) {
1760
+ return;
1761
+ }
1762
+ if (dict->dictionary == NULL) {
1763
+ /* This should never ever happen. */
1764
+ } else if (*dict->dictionary == kLeanPreparedDictionaryMagic) {
1765
+ DestroyPreparedDictionary(
1766
+ &dict->memory_manager_, (PreparedDictionary*)dict->dictionary);
1767
+ } else if (*dict->dictionary == kSharedDictionaryMagic) {
1768
+ BrotliCleanupSharedEncoderDictionary(&dict->memory_manager_,
1769
+ (SharedEncoderDictionary*)dict->dictionary);
1770
+ BrotliFree(&dict->memory_manager_, dict->dictionary);
1771
+ } else {
1772
+ /* There is also kPreparedDictionaryMagic, but such instances should be
1773
+ * constructed and destroyed by different means. */
1774
+ }
1775
+ dict->dictionary = NULL;
1776
+ BrotliDestroyManagedDictionary(dict);
1777
+ }
1778
+
1779
+ BROTLI_BOOL BrotliEncoderAttachPreparedDictionary(BrotliEncoderState* state,
1780
+ const BrotliEncoderPreparedDictionary* dictionary) {
1781
+ /* First field of dictionary structs */
1782
+ const BrotliEncoderPreparedDictionary* dict = dictionary;
1783
+ uint32_t magic = *((const uint32_t*)dict);
1784
+ SharedEncoderDictionary* current = NULL;
1785
+ if (magic == kManagedDictionaryMagic) {
1786
+ /* Unwrap managed dictionary. */
1787
+ ManagedDictionary* managed_dictionary = (ManagedDictionary*)dict;
1788
+ magic = *managed_dictionary->dictionary;
1789
+ dict = (BrotliEncoderPreparedDictionary*)managed_dictionary->dictionary;
1790
+ }
1791
+ current = &state->params.dictionary;
1792
+ if (magic == kPreparedDictionaryMagic ||
1793
+ magic == kLeanPreparedDictionaryMagic) {
1794
+ const PreparedDictionary* prepared = (const PreparedDictionary*)dict;
1795
+ if (!AttachPreparedDictionary(&current->compound, prepared)) {
1796
+ return BROTLI_FALSE;
1797
+ }
1798
+ } else if (magic == kSharedDictionaryMagic) {
1799
+ const SharedEncoderDictionary* attached =
1800
+ (const SharedEncoderDictionary*)dict;
1801
+ BROTLI_BOOL was_default = !current->contextual.context_based &&
1802
+ current->contextual.num_dictionaries == 1 &&
1803
+ current->contextual.dict[0]->hash_table_words ==
1804
+ kStaticDictionaryHashWords &&
1805
+ current->contextual.dict[0]->hash_table_lengths ==
1806
+ kStaticDictionaryHashLengths;
1807
+ BROTLI_BOOL new_default = !attached->contextual.context_based &&
1808
+ attached->contextual.num_dictionaries == 1 &&
1809
+ attached->contextual.dict[0]->hash_table_words ==
1810
+ kStaticDictionaryHashWords &&
1811
+ attached->contextual.dict[0]->hash_table_lengths ==
1812
+ kStaticDictionaryHashLengths;
1813
+ size_t i;
1814
+ if (state->is_initialized_) return BROTLI_FALSE;
1815
+ current->max_quality =
1816
+ BROTLI_MIN(int, current->max_quality, attached->max_quality);
1817
+ for (i = 0; i < attached->compound.num_chunks; i++) {
1818
+ if (!AttachPreparedDictionary(&current->compound,
1819
+ attached->compound.chunks[i])) {
1820
+ return BROTLI_FALSE;
1821
+ }
1822
+ }
1823
+ if (!new_default) {
1824
+ if (!was_default) return BROTLI_FALSE;
1825
+ /* Copy by value, but then set num_instances_ to 0 because their memory
1826
+ is managed by attached, not by current */
1827
+ current->contextual = attached->contextual;
1828
+ current->contextual.num_instances_ = 0;
1829
+ }
1830
+ } else {
1831
+ return BROTLI_FALSE;
1832
+ }
1833
+ return BROTLI_TRUE;
1834
+ }
1835
+
1836
+ size_t BrotliEncoderEstimatePeakMemoryUsage(int quality, int lgwin,
1837
+ size_t input_size) {
1838
+ BrotliEncoderParams params;
1839
+ size_t memory_manager_slots = BROTLI_ENCODER_MEMORY_MANAGER_SLOTS;
1840
+ size_t memory_manager_size = memory_manager_slots * sizeof(void*);
1841
+ BrotliEncoderInitParams(&params);
1842
+ params.quality = quality;
1843
+ params.lgwin = lgwin;
1844
+ params.size_hint = input_size;
1845
+ params.large_window = lgwin > BROTLI_MAX_WINDOW_BITS;
1846
+ SanitizeParams(&params);
1847
+ params.lgblock = ComputeLgBlock(&params);
1848
+ ChooseHasher(&params, &params.hasher);
1849
+ if (params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY ||
1850
+ params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY) {
1851
+ size_t state_size = sizeof(BrotliEncoderState);
1852
+ size_t block_size = BROTLI_MIN(size_t, input_size, (1ul << params.lgwin));
1853
+ size_t hash_table_size =
1854
+ HashTableSize(MaxHashTableSize(params.quality), block_size);
1855
+ size_t hash_size =
1856
+ (hash_table_size < (1u << 10)) ? 0 : sizeof(int) * hash_table_size;
1857
+ size_t cmdbuf_size = params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY ?
1858
+ 5 * BROTLI_MIN(size_t, block_size, 1ul << 17) : 0;
1859
+ if (params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY) {
1860
+ state_size += sizeof(BrotliOnePassArena);
1861
+ } else {
1862
+ state_size += sizeof(BrotliTwoPassArena);
1863
+ }
1864
+ return hash_size + cmdbuf_size + state_size;
1865
+ } else {
1866
+ size_t short_ringbuffer_size = (size_t)1 << params.lgblock;
1867
+ int ringbuffer_bits = ComputeRbBits(&params);
1868
+ size_t ringbuffer_size = input_size < short_ringbuffer_size ?
1869
+ input_size : (1u << ringbuffer_bits) + short_ringbuffer_size;
1870
+ size_t hash_size[4] = {0};
1871
+ size_t metablock_size =
1872
+ BROTLI_MIN(size_t, input_size, MaxMetablockSize(&params));
1873
+ size_t inputblock_size =
1874
+ BROTLI_MIN(size_t, input_size, (size_t)1 << params.lgblock);
1875
+ size_t cmdbuf_size = metablock_size * 2 + inputblock_size * 6;
1876
+ size_t outbuf_size = metablock_size * 2 + 503;
1877
+ size_t histogram_size = 0;
1878
+ HasherSize(&params, BROTLI_TRUE, input_size, hash_size);
1879
+ if (params.quality < MIN_QUALITY_FOR_BLOCK_SPLIT) {
1880
+ cmdbuf_size = BROTLI_MIN(size_t, cmdbuf_size,
1881
+ MAX_NUM_DELAYED_SYMBOLS * sizeof(Command) + inputblock_size * 12);
1882
+ }
1883
+ if (params.quality >= MIN_QUALITY_FOR_HQ_BLOCK_SPLITTING) {
1884
+ /* Only a very rough estimation, based on enwik8. */
1885
+ histogram_size = 200 << 20;
1886
+ } else if (params.quality >= MIN_QUALITY_FOR_BLOCK_SPLIT) {
1887
+ size_t literal_histograms =
1888
+ BROTLI_MIN(size_t, metablock_size / 6144, 256);
1889
+ size_t command_histograms =
1890
+ BROTLI_MIN(size_t, metablock_size / 6144, 256);
1891
+ size_t distance_histograms =
1892
+ BROTLI_MIN(size_t, metablock_size / 6144, 256);
1893
+ histogram_size = literal_histograms * sizeof(HistogramLiteral) +
1894
+ command_histograms * sizeof(HistogramCommand) +
1895
+ distance_histograms * sizeof(HistogramDistance);
1896
+ }
1897
+ return (memory_manager_size + ringbuffer_size +
1898
+ hash_size[0] + hash_size[1] + hash_size[2] + hash_size[3] +
1899
+ cmdbuf_size +
1900
+ outbuf_size +
1901
+ histogram_size);
1902
+ }
1903
+ }
1904
+ size_t BrotliEncoderGetPreparedDictionarySize(
1905
+ const BrotliEncoderPreparedDictionary* prepared_dictionary) {
1906
+ /* First field of dictionary structs */
1907
+ const BrotliEncoderPreparedDictionary* prepared = prepared_dictionary;
1908
+ uint32_t magic = *((const uint32_t*)prepared);
1909
+ size_t overhead = 0;
1910
+ if (magic == kManagedDictionaryMagic) {
1911
+ const ManagedDictionary* managed = (const ManagedDictionary*)prepared;
1912
+ overhead = sizeof(ManagedDictionary);
1913
+ magic = *managed->dictionary;
1914
+ prepared = (const BrotliEncoderPreparedDictionary*)managed->dictionary;
1915
+ }
1916
+
1917
+ if (magic == kPreparedDictionaryMagic) {
1918
+ const PreparedDictionary* dictionary =
1919
+ (const PreparedDictionary*)prepared;
1920
+ /* Keep in sync with step 3 of CreatePreparedDictionary */
1921
+ return sizeof(PreparedDictionary) + dictionary->source_size +
1922
+ (sizeof(uint32_t) << dictionary->slot_bits) +
1923
+ (sizeof(uint16_t) << dictionary->bucket_bits) +
1924
+ (sizeof(uint32_t) * dictionary->num_items) + overhead;
1925
+ } else if (magic == kLeanPreparedDictionaryMagic) {
1926
+ const PreparedDictionary* dictionary =
1927
+ (const PreparedDictionary*)prepared;
1928
+ /* Keep in sync with step 3 of CreatePreparedDictionary */
1929
+ return sizeof(PreparedDictionary) + sizeof(uint8_t*) +
1930
+ (sizeof(uint32_t) << dictionary->slot_bits) +
1931
+ (sizeof(uint16_t) << dictionary->bucket_bits) +
1932
+ (sizeof(uint32_t) * dictionary->num_items) + overhead;
1933
+ } else if (magic == kSharedDictionaryMagic) {
1934
+ const SharedEncoderDictionary* dictionary =
1935
+ (const SharedEncoderDictionary*)prepared;
1936
+ const CompoundDictionary* compound = &dictionary->compound;
1937
+ const ContextualEncoderDictionary* contextual = &dictionary->contextual;
1938
+ size_t result = sizeof(*dictionary);
1939
+ size_t i;
1940
+ size_t num_instances;
1941
+ const BrotliEncoderDictionary* instances;
1942
+ for (i = 0; i < compound->num_prepared_instances_; i++) {
1943
+ size_t size = BrotliEncoderGetPreparedDictionarySize(
1944
+ (const BrotliEncoderPreparedDictionary*)
1945
+ compound->prepared_instances_[i]);
1946
+ if (!size) return 0; /* error */
1947
+ result += size;
1948
+ }
1949
+ if (contextual->context_based) {
1950
+ num_instances = contextual->num_instances_;
1951
+ instances = contextual->instances_;
1952
+ result += sizeof(*instances) * num_instances;
1953
+ } else {
1954
+ num_instances = 1;
1955
+ instances = &contextual->instance_;
1956
+ }
1957
+ for (i = 0; i < num_instances; i++) {
1958
+ const BrotliEncoderDictionary* dict = &instances[i];
1959
+ result += dict->trie.pool_capacity * sizeof(BrotliTrieNode);
1960
+ if (dict->hash_table_data_words_) {
1961
+ result += sizeof(kStaticDictionaryHashWords);
1962
+ }
1963
+ if (dict->hash_table_data_lengths_) {
1964
+ result += sizeof(kStaticDictionaryHashLengths);
1965
+ }
1966
+ if (dict->buckets_data_) {
1967
+ result += sizeof(*dict->buckets_data_) * dict->buckets_alloc_size_;
1968
+ }
1969
+ if (dict->dict_words_data_) {
1970
+ result += sizeof(*dict->dict_words) * dict->dict_words_alloc_size_;
1971
+ }
1972
+ if (dict->words_instance_) {
1973
+ result += sizeof(*dict->words_instance_);
1974
+ /* data_size not added here: it is never allocated by the
1975
+ SharedEncoderDictionary, instead it always points to the file
1976
+ already loaded in memory. So if the caller wants to include
1977
+ this memory as well, add the size of the loaded dictionary
1978
+ file to this. */
1979
+ }
1980
+ }
1981
+ return result + overhead;
1982
+ }
1983
+ return 0; /* error */
1984
+ }
1985
+
1986
+ #if defined(BROTLI_TEST)
1987
+ size_t MakeUncompressedStreamForTest(const uint8_t*, size_t, uint8_t*);
1988
+ size_t MakeUncompressedStreamForTest(
1989
+ const uint8_t* input, size_t input_size, uint8_t* output) {
1990
+ return MakeUncompressedStream(input, input_size, output);
1991
+ }
1992
+ #endif
1993
+
1860
1994
  #if defined(__cplusplus) || defined(c_plusplus)
1861
1995
  } /* extern "C" */
1862
1996
  #endif