1 /* Copyright 2013 Google Inc. All Rights Reserved.
3 Distributed under MIT license.
4 See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
13 //#include <stdlib.h> /* free, malloc */
14 //#include <string.h> /* memcpy, memset */
15 #include <BrotliDecompressLibInternal.h>
17 #include "../common/constants.h"
18 #include "../common/dictionary.h"
19 #include "./bit_reader.h"
20 #include "./context.h"
21 #include "./huffman.h"
25 #include "./transform.h"
27 #if defined(__cplusplus) || defined(c_plusplus)
31 #define BROTLI_FAILURE(CODE) (BROTLI_DUMP(), CODE)
33 #define BROTLI_LOG_UINT(name) \
34 BROTLI_LOG(("[%s] %s = %lu\n", __func__, #name, (unsigned long)(name)))
35 #define BROTLI_LOG_ARRAY_INDEX(array_name, idx) \
36 BROTLI_LOG(("[%s] %s[%lu] = %lu\n", __func__, #array_name, \
37 (unsigned long)(idx), (unsigned long)array_name[idx]))
39 #define HUFFMAN_TABLE_BITS 8U
40 #define HUFFMAN_TABLE_MASK 0xff
42 static const uint8_t kCodeLengthCodeOrder
[BROTLI_CODE_LENGTH_CODES
] = {
43 1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15,
46 /* Static prefix code for the complex code length code lengths. */
47 static const uint8_t kCodeLengthPrefixLength
[16] = {
48 2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4,
51 static const uint8_t kCodeLengthPrefixValue
[16] = {
52 0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5,
55 BrotliDecoderState
* BrotliDecoderCreateInstance(
56 brotli_alloc_func alloc_func
, brotli_free_func free_func
, void* opaque
) {
57 BrotliDecoderState
* state
= 0;
58 if (!alloc_func
&& !free_func
) {
59 state
= (BrotliDecoderState
*)malloc(sizeof(BrotliDecoderState
));
60 } else if (alloc_func
&& free_func
) {
61 state
= (BrotliDecoderState
*)alloc_func(opaque
, sizeof(BrotliDecoderState
));
67 BrotliDecoderStateInitWithCustomAllocators(
68 state
, alloc_func
, free_func
, opaque
);
69 state
->error_code
= BROTLI_DECODER_NO_ERROR
;
73 /* Deinitializes and frees BrotliDecoderState instance. */
74 void BrotliDecoderDestroyInstance(BrotliDecoderState
* state
) {
78 brotli_free_func free_func
= state
->free_func
;
79 void* opaque
= state
->memory_manager_opaque
;
80 BrotliDecoderStateCleanup(state
);
81 free_func(opaque
, state
);
85 /* Saves error code and converts it to BrotliDecoderResult */
86 static BROTLI_NOINLINE BrotliDecoderResult
SaveErrorCode(
87 BrotliDecoderState
* s
, BrotliDecoderErrorCode e
) {
88 s
->error_code
= (int)e
;
90 case BROTLI_DECODER_SUCCESS
:
91 return BROTLI_DECODER_RESULT_SUCCESS
;
92 case BROTLI_DECODER_NEEDS_MORE_INPUT
:
93 return BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
;
94 case BROTLI_DECODER_NEEDS_MORE_OUTPUT
:
95 return BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT
;
97 return BROTLI_DECODER_RESULT_ERROR
;
101 /* Decodes a number in the range [9..24], by reading 1 - 7 bits.
102 Precondition: bit-reader accumulator has at least 7 bits. */
103 static uint32_t DecodeWindowBits(BrotliBitReader
* br
) {
105 BrotliTakeBits(br
, 1, &n
);
109 BrotliTakeBits(br
, 3, &n
);
113 BrotliTakeBits(br
, 3, &n
);
120 static BROTLI_INLINE
void memmove16(uint8_t* dst
, uint8_t* src
) {
121 #if defined(__ARM_NEON__)
122 vst1q_u8(dst
, vld1q_u8(src
));
125 memcpy(buffer
, src
, 16);
126 memcpy(dst
, buffer
, 16);
130 /* Decodes a number in the range [0..255], by reading 1 - 11 bits. */
131 static BROTLI_NOINLINE BrotliDecoderErrorCode
DecodeVarLenUint8(
132 BrotliDecoderState
* s
, BrotliBitReader
* br
, uint32_t* value
) {
134 switch (s
->substate_decode_uint8
) {
135 case BROTLI_STATE_DECODE_UINT8_NONE
:
136 if (PREDICT_FALSE(!BrotliSafeReadBits(br
, 1, &bits
))) {
137 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
141 return BROTLI_DECODER_SUCCESS
;
143 /* No break, transit to the next state. */
145 case BROTLI_STATE_DECODE_UINT8_SHORT
:
146 if (PREDICT_FALSE(!BrotliSafeReadBits(br
, 3, &bits
))) {
147 s
->substate_decode_uint8
= BROTLI_STATE_DECODE_UINT8_SHORT
;
148 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
152 s
->substate_decode_uint8
= BROTLI_STATE_DECODE_UINT8_NONE
;
153 return BROTLI_DECODER_SUCCESS
;
155 /* Use output value as a temporary storage. It MUST be persisted. */
157 /* No break, transit to the next state. */
159 case BROTLI_STATE_DECODE_UINT8_LONG
:
160 if (PREDICT_FALSE(!BrotliSafeReadBits(br
, *value
, &bits
))) {
161 s
->substate_decode_uint8
= BROTLI_STATE_DECODE_UINT8_LONG
;
162 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
164 *value
= (1U << *value
) + bits
;
165 s
->substate_decode_uint8
= BROTLI_STATE_DECODE_UINT8_NONE
;
166 return BROTLI_DECODER_SUCCESS
;
170 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE
);
174 /* Decodes a metablock length and flags by reading 2 - 31 bits. */
175 static BrotliDecoderErrorCode BROTLI_NOINLINE
DecodeMetaBlockLength(
176 BrotliDecoderState
* s
, BrotliBitReader
* br
) {
180 switch (s
->substate_metablock_header
) {
181 case BROTLI_STATE_METABLOCK_HEADER_NONE
:
182 if (!BrotliSafeReadBits(br
, 1, &bits
)) {
183 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
185 s
->is_last_metablock
= (uint8_t)bits
;
186 s
->meta_block_remaining_len
= 0;
187 s
->is_uncompressed
= 0;
189 if (!s
->is_last_metablock
) {
190 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_NIBBLES
;
193 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_EMPTY
;
194 /* No break, transit to the next state. */
196 case BROTLI_STATE_METABLOCK_HEADER_EMPTY
:
197 if (!BrotliSafeReadBits(br
, 1, &bits
)) {
198 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
201 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_NONE
;
202 return BROTLI_DECODER_SUCCESS
;
204 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_NIBBLES
;
205 /* No break, transit to the next state. */
207 case BROTLI_STATE_METABLOCK_HEADER_NIBBLES
:
208 if (!BrotliSafeReadBits(br
, 2, &bits
)) {
209 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
211 s
->size_nibbles
= (uint8_t)(bits
+ 4);
215 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_RESERVED
;
218 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_SIZE
;
219 /* No break, transit to the next state. */
221 case BROTLI_STATE_METABLOCK_HEADER_SIZE
:
223 for (; i
< s
->size_nibbles
; ++i
) {
224 if (!BrotliSafeReadBits(br
, 4, &bits
)) {
226 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
228 if (i
+ 1 == s
->size_nibbles
&& s
->size_nibbles
> 4 && bits
== 0) {
229 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE
);
231 s
->meta_block_remaining_len
|= (int)(bits
<< (i
* 4));
233 s
->substate_metablock_header
=
234 BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED
;
235 /* No break, transit to the next state. */
237 case BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED
:
238 if (!s
->is_last_metablock
) {
239 if (!BrotliSafeReadBits(br
, 1, &bits
)) {
240 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
242 s
->is_uncompressed
= (uint8_t)bits
;
244 ++s
->meta_block_remaining_len
;
245 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_NONE
;
246 return BROTLI_DECODER_SUCCESS
;
248 case BROTLI_STATE_METABLOCK_HEADER_RESERVED
:
249 if (!BrotliSafeReadBits(br
, 1, &bits
)) {
250 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
253 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_RESERVED
);
255 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_BYTES
;
256 /* No break, transit to the next state. */
258 case BROTLI_STATE_METABLOCK_HEADER_BYTES
:
259 if (!BrotliSafeReadBits(br
, 2, &bits
)) {
260 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
263 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_NONE
;
264 return BROTLI_DECODER_SUCCESS
;
266 s
->size_nibbles
= (uint8_t)bits
;
267 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_METADATA
;
268 /* No break, transit to the next state. */
270 case BROTLI_STATE_METABLOCK_HEADER_METADATA
:
272 for (; i
< s
->size_nibbles
; ++i
) {
273 if (!BrotliSafeReadBits(br
, 8, &bits
)) {
275 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
277 if (i
+ 1 == s
->size_nibbles
&& s
->size_nibbles
> 1 && bits
== 0) {
278 return BROTLI_FAILURE(
279 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE
);
281 s
->meta_block_remaining_len
|= (int)(bits
<< (i
* 8));
283 ++s
->meta_block_remaining_len
;
284 s
->substate_metablock_header
= BROTLI_STATE_METABLOCK_HEADER_NONE
;
285 return BROTLI_DECODER_SUCCESS
;
289 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE
);
294 /* Decodes the Huffman code.
295 This method doesn't read data from the bit reader, BUT drops the amount of
296 bits that correspond to the decoded symbol.
297 bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits. */
298 static BROTLI_INLINE
uint32_t DecodeSymbol(uint32_t bits
,
299 const HuffmanCode
* table
,
300 BrotliBitReader
* br
) {
301 table
+= bits
& HUFFMAN_TABLE_MASK
;
302 if (table
->bits
> HUFFMAN_TABLE_BITS
) {
303 uint32_t nbits
= table
->bits
- HUFFMAN_TABLE_BITS
;
304 BrotliDropBits(br
, HUFFMAN_TABLE_BITS
);
305 table
+= table
->value
;
306 table
+= (bits
>> HUFFMAN_TABLE_BITS
) & BitMask(nbits
);
308 BrotliDropBits(br
, table
->bits
);
312 /* Reads and decodes the next Huffman code from bit-stream.
313 This method peeks 16 bits of input and drops 0 - 15 of them. */
314 static BROTLI_INLINE
uint32_t ReadSymbol(const HuffmanCode
* table
,
315 BrotliBitReader
* br
) {
316 return DecodeSymbol(BrotliGet16BitsUnmasked(br
), table
, br
);
319 /* Same as DecodeSymbol, but it is known that there is less than 15 bits of
320 input are currently available. */
321 static BROTLI_NOINLINE BROTLI_BOOL
SafeDecodeSymbol(
322 const HuffmanCode
* table
, BrotliBitReader
* br
, uint32_t* result
) {
324 uint32_t available_bits
= BrotliGetAvailableBits(br
);
325 if (available_bits
== 0) {
326 if (table
->bits
== 0) {
327 *result
= table
->value
;
330 return BROTLI_FALSE
; /* No valid bits at all. */
332 val
= (uint32_t)BrotliGetBitsUnmasked(br
);
333 table
+= val
& HUFFMAN_TABLE_MASK
;
334 if (table
->bits
<= HUFFMAN_TABLE_BITS
) {
335 if (table
->bits
<= available_bits
) {
336 BrotliDropBits(br
, table
->bits
);
337 *result
= table
->value
;
340 return BROTLI_FALSE
; /* Not enough bits for the first level. */
343 if (available_bits
<= HUFFMAN_TABLE_BITS
) {
344 return BROTLI_FALSE
; /* Not enough bits to move to the second level. */
347 /* Speculatively drop HUFFMAN_TABLE_BITS. */
348 val
= (val
& BitMask(table
->bits
)) >> HUFFMAN_TABLE_BITS
;
349 available_bits
-= HUFFMAN_TABLE_BITS
;
350 table
+= table
->value
+ val
;
351 if (available_bits
< table
->bits
) {
352 return BROTLI_FALSE
; /* Not enough bits for the second level. */
355 BrotliDropBits(br
, HUFFMAN_TABLE_BITS
+ table
->bits
);
356 *result
= table
->value
;
360 static BROTLI_INLINE BROTLI_BOOL
SafeReadSymbol(
361 const HuffmanCode
* table
, BrotliBitReader
* br
, uint32_t* result
) {
363 if (PREDICT_TRUE(BrotliSafeGetBits(br
, 15, &val
))) {
364 *result
= DecodeSymbol(val
, table
, br
);
367 return SafeDecodeSymbol(table
, br
, result
);
370 /* Makes a look-up in first level Huffman table. Peeks 8 bits. */
371 static BROTLI_INLINE
void PreloadSymbol(int safe
,
372 const HuffmanCode
* table
,
379 table
+= BrotliGetBits(br
, HUFFMAN_TABLE_BITS
);
381 *value
= table
->value
;
384 /* Decodes the next Huffman code using data prepared by PreloadSymbol.
385 Reads 0 - 15 bits. Also peeks 8 following bits. */
386 static BROTLI_INLINE
uint32_t ReadPreloadedSymbol(const HuffmanCode
* table
,
390 uint32_t result
= *value
;
391 if (PREDICT_FALSE(*bits
> HUFFMAN_TABLE_BITS
)) {
392 uint32_t val
= BrotliGet16BitsUnmasked(br
);
393 const HuffmanCode
* ext
= table
+ (val
& HUFFMAN_TABLE_MASK
) + *value
;
394 uint32_t mask
= BitMask((*bits
- HUFFMAN_TABLE_BITS
));
395 BrotliDropBits(br
, HUFFMAN_TABLE_BITS
);
396 ext
+= (val
>> HUFFMAN_TABLE_BITS
) & mask
;
397 BrotliDropBits(br
, ext
->bits
);
400 BrotliDropBits(br
, *bits
);
402 PreloadSymbol(0, table
, br
, bits
, value
);
406 static BROTLI_INLINE
uint32_t Log2Floor(uint32_t x
) {
415 /* Reads (s->symbol + 1) symbols.
416 Totally 1..4 symbols are read, 1..10 bits each.
417 The list of symbols MUST NOT contain duplicates.
419 static BrotliDecoderErrorCode
ReadSimpleHuffmanSymbols(
420 uint32_t alphabet_size
, BrotliDecoderState
* s
) {
421 /* max_bits == 1..10; symbol == 0..3; 1..40 bits will be read. */
422 BrotliBitReader
* br
= &s
->br
;
423 uint32_t max_bits
= Log2Floor(alphabet_size
- 1);
424 uint32_t i
= s
->sub_loop_counter
;
425 uint32_t num_symbols
= s
->symbol
;
426 while (i
<= num_symbols
) {
428 if (PREDICT_FALSE(!BrotliSafeReadBits(br
, max_bits
, &v
))) {
429 s
->sub_loop_counter
= i
;
430 s
->substate_huffman
= BROTLI_STATE_HUFFMAN_SIMPLE_READ
;
431 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
433 if (v
>= alphabet_size
) {
435 BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET
);
437 s
->symbols_lists_array
[i
] = (uint16_t)v
;
438 BROTLI_LOG_UINT(s
->symbols_lists_array
[i
]);
442 for (i
= 0; i
< num_symbols
; ++i
) {
444 for (; k
<= num_symbols
; ++k
) {
445 if (s
->symbols_lists_array
[i
] == s
->symbols_lists_array
[k
]) {
446 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME
);
451 return BROTLI_DECODER_SUCCESS
;
454 /* Process single decoded symbol code length:
455 A) reset the repeat variable
456 B) remember code length (if it is not 0)
457 C) extend corredponding index-chain
458 D) reduce the huffman space
459 E) update the histogram
461 static BROTLI_INLINE
void ProcessSingleCodeLength(uint32_t code_len
,
462 uint32_t* symbol
, uint32_t* repeat
, uint32_t* space
,
463 uint32_t* prev_code_len
, uint16_t* symbol_lists
,
464 uint16_t* code_length_histo
, int* next_symbol
) {
466 if (code_len
!= 0) { /* code_len == 1..15 */
467 symbol_lists
[next_symbol
[code_len
]] = (uint16_t)(*symbol
);
468 next_symbol
[code_len
] = (int)(*symbol
);
469 *prev_code_len
= code_len
;
470 *space
-= 32768U >> code_len
;
471 code_length_histo
[code_len
]++;
472 BROTLI_LOG(("[ReadHuffmanCode] code_length[%d] = %d\n", *symbol
, code_len
));
477 /* Process repeated symbol code length.
478 A) Check if it is the extension of previous repeat sequence; if the decoded
479 value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new
481 B) Update repeat variable
482 C) Check if operation is feasible (fits alphapet)
483 D) For each symbol do the same operations as in ProcessSingleCodeLength
485 PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or
486 code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH
488 static BROTLI_INLINE
void ProcessRepeatedCodeLength(uint32_t code_len
,
489 uint32_t repeat_delta
, uint32_t alphabet_size
, uint32_t* symbol
,
490 uint32_t* repeat
, uint32_t* space
, uint32_t* prev_code_len
,
491 uint32_t* repeat_code_len
, uint16_t* symbol_lists
,
492 uint16_t* code_length_histo
, int* next_symbol
) {
494 uint32_t extra_bits
= 3; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
495 uint32_t new_len
= 0; /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
496 if (code_len
== BROTLI_REPEAT_PREVIOUS_CODE_LENGTH
) {
497 new_len
= *prev_code_len
;
500 if (*repeat_code_len
!= new_len
) {
502 *repeat_code_len
= new_len
;
504 old_repeat
= *repeat
;
507 *repeat
<<= extra_bits
;
509 *repeat
+= repeat_delta
+ 3U;
510 repeat_delta
= *repeat
- old_repeat
;
511 if (*symbol
+ repeat_delta
> alphabet_size
) {
513 *symbol
= alphabet_size
;
517 BROTLI_LOG(("[ReadHuffmanCode] code_length[%d..%d] = %d\n",
518 *symbol
, *symbol
+ repeat_delta
- 1, *repeat_code_len
));
519 if (*repeat_code_len
!= 0) {
520 unsigned last
= *symbol
+ repeat_delta
;
521 int next
= next_symbol
[*repeat_code_len
];
523 symbol_lists
[next
] = (uint16_t)*symbol
;
525 } while (++(*symbol
) != last
);
526 next_symbol
[*repeat_code_len
] = next
;
527 *space
-= repeat_delta
<< (15 - *repeat_code_len
);
528 code_length_histo
[*repeat_code_len
] =
529 (uint16_t)(code_length_histo
[*repeat_code_len
] + repeat_delta
);
531 *symbol
+= repeat_delta
;
535 /* Reads and decodes symbol codelengths. */
536 static BrotliDecoderErrorCode
ReadSymbolCodeLengths(
537 uint32_t alphabet_size
, BrotliDecoderState
* s
) {
538 BrotliBitReader
* br
= &s
->br
;
539 uint32_t symbol
= s
->symbol
;
540 uint32_t repeat
= s
->repeat
;
541 uint32_t space
= s
->space
;
542 uint32_t prev_code_len
= s
->prev_code_len
;
543 uint32_t repeat_code_len
= s
->repeat_code_len
;
544 uint16_t* symbol_lists
= s
->symbol_lists
;
545 uint16_t* code_length_histo
= s
->code_length_histo
;
546 int* next_symbol
= s
->next_symbol
;
547 if (!BrotliWarmupBitReader(br
)) {
548 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
550 while (symbol
< alphabet_size
&& space
> 0) {
551 const HuffmanCode
* p
= s
->table
;
553 if (!BrotliCheckInputAmount(br
, BROTLI_SHORT_FILL_BIT_WINDOW_READ
)) {
556 s
->prev_code_len
= prev_code_len
;
557 s
->repeat_code_len
= repeat_code_len
;
559 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
561 BrotliFillBitWindow16(br
);
562 p
+= BrotliGetBitsUnmasked(br
) &
563 BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH
);
564 BrotliDropBits(br
, p
->bits
); /* Use 1..5 bits */
565 code_len
= p
->value
; /* code_len == 0..17 */
566 if (code_len
< BROTLI_REPEAT_PREVIOUS_CODE_LENGTH
) {
567 ProcessSingleCodeLength(code_len
, &symbol
, &repeat
, &space
,
568 &prev_code_len
, symbol_lists
, code_length_histo
, next_symbol
);
569 } else { /* code_len == 16..17, extra_bits == 2..3 */
570 uint32_t extra_bits
=
571 (code_len
== BROTLI_REPEAT_PREVIOUS_CODE_LENGTH
) ? 2 : 3;
572 uint32_t repeat_delta
=
573 (uint32_t)BrotliGetBitsUnmasked(br
) & BitMask(extra_bits
);
574 BrotliDropBits(br
, extra_bits
);
575 ProcessRepeatedCodeLength(code_len
, repeat_delta
, alphabet_size
,
576 &symbol
, &repeat
, &space
, &prev_code_len
, &repeat_code_len
,
577 symbol_lists
, code_length_histo
, next_symbol
);
581 return BROTLI_DECODER_SUCCESS
;
584 static BrotliDecoderErrorCode
SafeReadSymbolCodeLengths(
585 uint32_t alphabet_size
, BrotliDecoderState
* s
) {
586 BrotliBitReader
* br
= &s
->br
;
587 while (s
->symbol
< alphabet_size
&& s
->space
> 0) {
588 const HuffmanCode
* p
= s
->table
;
591 uint32_t available_bits
= BrotliGetAvailableBits(br
);
592 if (available_bits
!= 0) {
593 bits
= (uint32_t)BrotliGetBitsUnmasked(br
);
595 p
+= bits
& BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH
);
596 if (p
->bits
> available_bits
) goto pullMoreInput
;
597 code_len
= p
->value
; /* code_len == 0..17 */
598 if (code_len
< BROTLI_REPEAT_PREVIOUS_CODE_LENGTH
) {
599 BrotliDropBits(br
, p
->bits
);
600 ProcessSingleCodeLength(code_len
, &s
->symbol
, &s
->repeat
, &s
->space
,
601 &s
->prev_code_len
, s
->symbol_lists
, s
->code_length_histo
,
603 } else { /* code_len == 16..17, extra_bits == 2..3 */
604 uint32_t extra_bits
= code_len
- 14U;
605 uint32_t repeat_delta
= (bits
>> p
->bits
) & BitMask(extra_bits
);
606 if (available_bits
< p
->bits
+ extra_bits
) goto pullMoreInput
;
607 BrotliDropBits(br
, p
->bits
+ extra_bits
);
608 ProcessRepeatedCodeLength(code_len
, repeat_delta
, alphabet_size
,
609 &s
->symbol
, &s
->repeat
, &s
->space
, &s
->prev_code_len
,
610 &s
->repeat_code_len
, s
->symbol_lists
, s
->code_length_histo
,
616 if (!BrotliPullByte(br
)) {
617 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
620 return BROTLI_DECODER_SUCCESS
;
623 /* Reads and decodes 15..18 codes using static prefix code.
624 Each code is 2..4 bits long. In total 30..72 bits are used. */
625 static BrotliDecoderErrorCode
ReadCodeLengthCodeLengths(BrotliDecoderState
* s
) {
626 BrotliBitReader
* br
= &s
->br
;
627 uint32_t num_codes
= s
->repeat
;
628 unsigned space
= s
->space
;
629 uint32_t i
= s
->sub_loop_counter
;
630 for (; i
< BROTLI_CODE_LENGTH_CODES
; ++i
) {
631 const uint8_t code_len_idx
= kCodeLengthCodeOrder
[i
];
634 if (PREDICT_FALSE(!BrotliSafeGetBits(br
, 4, &ix
))) {
635 uint32_t available_bits
= BrotliGetAvailableBits(br
);
636 if (available_bits
!= 0) {
637 ix
= BrotliGetBitsUnmasked(br
) & 0xF;
641 if (kCodeLengthPrefixLength
[ix
] > available_bits
) {
642 s
->sub_loop_counter
= i
;
643 s
->repeat
= num_codes
;
645 s
->substate_huffman
= BROTLI_STATE_HUFFMAN_COMPLEX
;
646 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
649 v
= kCodeLengthPrefixValue
[ix
];
650 BrotliDropBits(br
, kCodeLengthPrefixLength
[ix
]);
651 s
->code_length_code_lengths
[code_len_idx
] = (uint8_t)v
;
652 BROTLI_LOG_ARRAY_INDEX(s
->code_length_code_lengths
, code_len_idx
);
654 space
= space
- (32U >> v
);
656 ++s
->code_length_histo
[v
];
657 if (space
- 1U >= 32U) {
658 /* space is 0 or wrapped around */
663 if (!(num_codes
== 1 || space
== 0)) {
664 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CL_SPACE
);
666 return BROTLI_DECODER_SUCCESS
;
669 /* Decodes the Huffman tables.
670 There are 2 scenarios:
671 A) Huffman code contains only few symbols (1..4). Those symbols are read
672 directly; their code lengths are defined by the number of symbols.
673 For this scenario 4 - 45 bits will be read.
676 B.1) Small Huffman table is decoded; it is specified with code lengths
677 encoded with predefined entropy code. 32 - 74 bits are used.
678 B.2) Decoded table is used to decode code lengths of symbols in resulting
679 Huffman table. In worst case 3520 bits are read.
681 static BrotliDecoderErrorCode
ReadHuffmanCode(uint32_t alphabet_size
,
683 uint32_t* opt_table_size
,
684 BrotliDecoderState
* s
) {
685 BrotliBitReader
* br
= &s
->br
;
686 /* Unnecessary masking, but might be good for safety. */
687 alphabet_size
&= 0x3ff;
689 switch (s
->substate_huffman
) {
690 case BROTLI_STATE_HUFFMAN_NONE
:
691 if (!BrotliSafeReadBits(br
, 2, &s
->sub_loop_counter
)) {
692 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
694 BROTLI_LOG_UINT(s
->sub_loop_counter
);
695 /* The value is used as follows:
697 0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
698 if (s
->sub_loop_counter
!= 1) {
700 s
->repeat
= 0; /* num_codes */
701 memset(&s
->code_length_histo
[0], 0, sizeof(s
->code_length_histo
[0]) *
702 (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH
+ 1));
703 memset(&s
->code_length_code_lengths
[0], 0,
704 sizeof(s
->code_length_code_lengths
));
705 s
->substate_huffman
= BROTLI_STATE_HUFFMAN_COMPLEX
;
708 /* No break, transit to the next state. */
710 case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE
:
711 /* Read symbols, codes & code lengths directly. */
712 if (!BrotliSafeReadBits(br
, 2, &s
->symbol
)) { /* num_symbols */
713 s
->substate_huffman
= BROTLI_STATE_HUFFMAN_SIMPLE_SIZE
;
714 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
716 s
->sub_loop_counter
= 0;
717 /* No break, transit to the next state. */
718 case BROTLI_STATE_HUFFMAN_SIMPLE_READ
: {
719 BrotliDecoderErrorCode result
=
720 ReadSimpleHuffmanSymbols(alphabet_size
, s
);
721 if (result
!= BROTLI_DECODER_SUCCESS
) {
724 /* No break, transit to the next state. */
726 case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD
: {
728 if (s
->symbol
== 3) {
730 if (!BrotliSafeReadBits(br
, 1, &bits
)) {
731 s
->substate_huffman
= BROTLI_STATE_HUFFMAN_SIMPLE_BUILD
;
732 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
736 BROTLI_LOG_UINT(s
->symbol
);
737 table_size
= BrotliBuildSimpleHuffmanTable(
738 table
, HUFFMAN_TABLE_BITS
, s
->symbols_lists_array
, s
->symbol
);
739 if (opt_table_size
) {
740 *opt_table_size
= table_size
;
742 s
->substate_huffman
= BROTLI_STATE_HUFFMAN_NONE
;
743 return BROTLI_DECODER_SUCCESS
;
746 Complex
: /* Decode Huffman-coded code lengths. */
747 case BROTLI_STATE_HUFFMAN_COMPLEX
: {
749 BrotliDecoderErrorCode result
= ReadCodeLengthCodeLengths(s
);
750 if (result
!= BROTLI_DECODER_SUCCESS
) {
753 BrotliBuildCodeLengthsHuffmanTable(s
->table
,
754 s
->code_length_code_lengths
,
755 s
->code_length_histo
);
756 memset(&s
->code_length_histo
[0], 0, sizeof(s
->code_length_histo
));
757 for (i
= 0; i
<= BROTLI_HUFFMAN_MAX_CODE_LENGTH
; ++i
) {
758 s
->next_symbol
[i
] = (int)i
- (BROTLI_HUFFMAN_MAX_CODE_LENGTH
+ 1);
759 s
->symbol_lists
[(int)i
- (BROTLI_HUFFMAN_MAX_CODE_LENGTH
+ 1)] = 0xFFFF;
763 s
->prev_code_len
= BROTLI_INITIAL_REPEATED_CODE_LENGTH
;
765 s
->repeat_code_len
= 0;
767 s
->substate_huffman
= BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS
;
768 /* No break, transit to the next state. */
770 case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS
: {
772 BrotliDecoderErrorCode result
= ReadSymbolCodeLengths(alphabet_size
, s
);
773 if (result
== BROTLI_DECODER_NEEDS_MORE_INPUT
) {
774 result
= SafeReadSymbolCodeLengths(alphabet_size
, s
);
776 if (result
!= BROTLI_DECODER_SUCCESS
) {
781 BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", s
->space
));
782 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE
);
784 table_size
= BrotliBuildHuffmanTable(
785 table
, HUFFMAN_TABLE_BITS
, s
->symbol_lists
, s
->code_length_histo
);
786 if (opt_table_size
) {
787 *opt_table_size
= table_size
;
789 s
->substate_huffman
= BROTLI_STATE_HUFFMAN_NONE
;
790 return BROTLI_DECODER_SUCCESS
;
795 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE
);
799 /* Decodes a block length by reading 3..39 bits. */
800 static BROTLI_INLINE
uint32_t ReadBlockLength(const HuffmanCode
* table
,
801 BrotliBitReader
* br
) {
804 code
= ReadSymbol(table
, br
);
805 if (code
>= BROTLI_NUM_BLOCK_LEN_SYMBOLS
) code
= BROTLI_NUM_BLOCK_LEN_SYMBOLS
- 1;
806 nbits
= kBlockLengthPrefixCode
[code
].nbits
; /* nbits == 2..24 */
807 return kBlockLengthPrefixCode
[code
].offset
+ BrotliReadBits(br
, nbits
);
810 /* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
811 reading can't be continued with ReadBlockLength. */
812 static BROTLI_INLINE BROTLI_BOOL
SafeReadBlockLength(
813 BrotliDecoderState
* s
, uint32_t* result
, const HuffmanCode
* table
,
814 BrotliBitReader
* br
) {
816 if (s
->substate_read_block_length
== BROTLI_STATE_READ_BLOCK_LENGTH_NONE
) {
817 if (!SafeReadSymbol(table
, br
, &index
)) {
821 index
= s
->block_length_index
;
825 uint32_t nbits
= kBlockLengthPrefixCode
[index
].nbits
; /* nbits == 2..24 */
826 if (!BrotliSafeReadBits(br
, nbits
, &bits
)) {
827 s
->block_length_index
= index
;
828 s
->substate_read_block_length
= BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX
;
831 *result
= kBlockLengthPrefixCode
[index
].offset
+ bits
;
832 s
->substate_read_block_length
= BROTLI_STATE_READ_BLOCK_LENGTH_NONE
;
838 1) initialize list L with values 0, 1,... 255
839 2) For each input element X:
841 2.2) remove X-th element from L
843 2.4) append Y to output
845 In most cases max(Y) <= 7, so most of L remains intact.
846 To reduce the cost of initialization, we reuse L, remember the upper bound
847 of Y values, and reinitialize only first elements in L.
849 Most of input values are 0 and 1. To reduce number of branches, we replace
850 inner for loop with do-while.
852 static BROTLI_NOINLINE
void InverseMoveToFrontTransform(
853 uint8_t* v
, uint32_t v_len
, BrotliDecoderState
* state
) {
854 /* Reinitialize elements that could have been changed. */
856 uint32_t upper_bound
= state
->mtf_upper_bound
;
857 uint8_t* mtf
= &state
->mtf
[4]; /* Make mtf[-1] addressable. */
858 /* Load endian-aware constant. */
859 const uint8_t b0123
[4] = {0, 1, 2, 3};
861 memcpy(&pattern
, &b0123
, 4);
863 /* Initialize list using 4 consequent values pattern. */
864 *(uint32_t*)mtf
= pattern
;
866 pattern
+= 0x04040404; /* Advance all 4 values by 4. */
867 *(uint32_t*)(mtf
+ i
) = pattern
;
869 } while (i
<= upper_bound
);
871 /* Transform the input. */
873 for (i
= 0; i
< v_len
; ++i
) {
875 uint8_t value
= mtf
[index
];
876 upper_bound
|= (uint32_t)v
[i
];
881 mtf
[index
+ 1] = mtf
[index
];
884 /* Remember amount of elements to be reinitialized. */
885 state
->mtf_upper_bound
= upper_bound
;
888 /* Decodes a series of Huffman table using ReadHuffmanCode function. */
889 static BrotliDecoderErrorCode
HuffmanTreeGroupDecode(
890 HuffmanTreeGroup
* group
, BrotliDecoderState
* s
) {
891 if (s
->substate_tree_group
!= BROTLI_STATE_TREE_GROUP_LOOP
) {
892 s
->next
= group
->codes
;
894 s
->substate_tree_group
= BROTLI_STATE_TREE_GROUP_LOOP
;
896 while (s
->htree_index
< group
->num_htrees
) {
898 BrotliDecoderErrorCode result
=
899 ReadHuffmanCode(group
->alphabet_size
, s
->next
, &table_size
, s
);
900 if (result
!= BROTLI_DECODER_SUCCESS
) return result
;
901 group
->htrees
[s
->htree_index
] = s
->next
;
902 s
->next
+= table_size
;
905 s
->substate_tree_group
= BROTLI_STATE_TREE_GROUP_NONE
;
906 return BROTLI_DECODER_SUCCESS
;
909 /* Decodes a context map.
910 Decoding is done in 4 phases:
911 1) Read auxiliary information (6..16 bits) and allocate memory.
912 In case of trivial context map, decoding is finished at this phase.
913 2) Decode Huffman table using ReadHuffmanCode function.
914 This table will be used for reading context map items.
915 3) Read context map items; "0" values could be run-length encoded.
916 4) Optionally, apply InverseMoveToFront transform to the resulting map.
918 static BrotliDecoderErrorCode
DecodeContextMap(uint32_t context_map_size
,
919 uint32_t* num_htrees
,
920 uint8_t** context_map_arg
,
921 BrotliDecoderState
* s
) {
922 BrotliBitReader
* br
= &s
->br
;
923 BrotliDecoderErrorCode result
= BROTLI_DECODER_SUCCESS
;
925 switch ((int)s
->substate_context_map
) {
926 case BROTLI_STATE_CONTEXT_MAP_NONE
:
927 result
= DecodeVarLenUint8(s
, br
, num_htrees
);
928 if (result
!= BROTLI_DECODER_SUCCESS
) {
932 s
->context_index
= 0;
933 BROTLI_LOG_UINT(context_map_size
);
934 BROTLI_LOG_UINT(*num_htrees
);
935 *context_map_arg
= (uint8_t*)BROTLI_ALLOC(s
, (size_t)context_map_size
);
936 if (*context_map_arg
== 0) {
937 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP
);
939 if (*num_htrees
<= 1) {
940 memset(*context_map_arg
, 0, (size_t)context_map_size
);
941 return BROTLI_DECODER_SUCCESS
;
943 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_READ_PREFIX
;
944 /* No break, continue to next state. */
945 case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX
: {
947 /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe
948 to peek 4 bits ahead. */
949 if (!BrotliSafeGetBits(br
, 5, &bits
)) {
950 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
952 if ((bits
& 1) != 0) { /* Use RLE for zeroes. */
953 s
->max_run_length_prefix
= (bits
>> 1) + 1;
954 BrotliDropBits(br
, 5);
956 s
->max_run_length_prefix
= 0;
957 BrotliDropBits(br
, 1);
959 BROTLI_LOG_UINT(s
->max_run_length_prefix
);
960 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_HUFFMAN
;
961 /* No break, continue to next state. */
963 case BROTLI_STATE_CONTEXT_MAP_HUFFMAN
:
964 result
= ReadHuffmanCode(*num_htrees
+ s
->max_run_length_prefix
,
965 s
->context_map_table
, NULL
, s
);
966 if (result
!= BROTLI_DECODER_SUCCESS
) return result
;
968 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_DECODE
;
969 /* No break, continue to next state. */
970 case BROTLI_STATE_CONTEXT_MAP_DECODE
: {
971 uint32_t context_index
= s
->context_index
;
972 uint32_t max_run_length_prefix
= s
->max_run_length_prefix
;
973 uint8_t* context_map
= *context_map_arg
;
974 uint32_t code
= s
->code
;
975 if (code
!= 0xFFFF) {
978 while (context_index
< context_map_size
) {
979 if (!SafeReadSymbol(s
->context_map_table
, br
, &code
)) {
981 s
->context_index
= context_index
;
982 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
984 BROTLI_LOG_UINT(code
);
987 context_map
[context_index
++] = 0;
990 if (code
> max_run_length_prefix
) {
991 context_map
[context_index
++] =
992 (uint8_t)(code
- max_run_length_prefix
);
998 if (!BrotliSafeReadBits(br
, code
, &reps
)) {
1000 s
->context_index
= context_index
;
1001 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
1004 BROTLI_LOG_UINT(reps
);
1005 if (context_index
+ reps
> context_map_size
) {
1007 BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT
);
1010 context_map
[context_index
++] = 0;
1014 /* No break, continue to next state. */
1016 case BROTLI_STATE_CONTEXT_MAP_TRANSFORM
: {
1018 if (!BrotliSafeReadBits(br
, 1, &bits
)) {
1019 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_TRANSFORM
;
1020 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
1023 InverseMoveToFrontTransform(*context_map_arg
, context_map_size
, s
);
1025 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_NONE
;
1026 return BROTLI_DECODER_SUCCESS
;
1030 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE
);
1034 /* Decodes a command or literal and updates block type ringbuffer.
1035 Reads 3..54 bits. */
1036 static BROTLI_INLINE BROTLI_BOOL
DecodeBlockTypeAndLength(
1037 int safe
, BrotliDecoderState
* s
, int tree_type
) {
1038 uint32_t max_block_type
= s
->num_block_types
[tree_type
];
1039 const HuffmanCode
* type_tree
= &s
->block_type_trees
[
1040 tree_type
* BROTLI_HUFFMAN_MAX_SIZE_258
];
1041 const HuffmanCode
* len_tree
= &s
->block_len_trees
[
1042 tree_type
* BROTLI_HUFFMAN_MAX_SIZE_26
];
1043 BrotliBitReader
* br
= &s
->br
;
1044 uint32_t* ringbuffer
= &s
->block_type_rb
[tree_type
* 2];
1045 uint32_t block_type
;
1047 /* Read 0..15 + 3..39 bits */
1049 block_type
= ReadSymbol(type_tree
, br
);
1050 s
->block_length
[tree_type
] = ReadBlockLength(len_tree
, br
);
1052 BrotliBitReaderState memento
;
1053 BrotliBitReaderSaveState(br
, &memento
);
1054 if (!SafeReadSymbol(type_tree
, br
, &block_type
)) return BROTLI_FALSE
;
1055 if (!SafeReadBlockLength(s
, &s
->block_length
[tree_type
], len_tree
, br
)) {
1056 s
->substate_read_block_length
= BROTLI_STATE_READ_BLOCK_LENGTH_NONE
;
1057 BrotliBitReaderRestoreState(br
, &memento
);
1058 return BROTLI_FALSE
;
1062 if (block_type
== 1) {
1063 block_type
= ringbuffer
[1] + 1;
1064 } else if (block_type
== 0) {
1065 block_type
= ringbuffer
[0];
1069 if (block_type
>= max_block_type
) {
1070 block_type
-= max_block_type
;
1072 ringbuffer
[0] = ringbuffer
[1];
1073 ringbuffer
[1] = block_type
;
1077 static BROTLI_INLINE
void DetectTrivialLiteralBlockTypes(
1078 BrotliDecoderState
* s
) {
1080 for (i
= 0; i
< 8; ++i
) s
->trivial_literal_contexts
[i
] = 0;
1081 for (i
= 0; i
< s
->num_block_types
[0]; i
++) {
1082 size_t offset
= i
<< BROTLI_LITERAL_CONTEXT_BITS
;
1084 size_t sample
= s
->context_map
[offset
];
1086 for (j
= 0; j
< (1u << BROTLI_LITERAL_CONTEXT_BITS
);) {
1087 BROTLI_REPEAT(4, error
|= s
->context_map
[offset
+ j
++] ^ sample
;)
1090 s
->trivial_literal_contexts
[i
>> 5] |= 1u << (i
& 31);
1095 static BROTLI_INLINE
void PrepareLiteralDecoding(BrotliDecoderState
* s
) {
1096 uint8_t context_mode
;
1098 uint32_t block_type
= s
->block_type_rb
[1];
1099 uint32_t context_offset
= block_type
<< BROTLI_LITERAL_CONTEXT_BITS
;
1100 s
->context_map_slice
= s
->context_map
+ context_offset
;
1101 trivial
= s
->trivial_literal_contexts
[block_type
>> 5];
1102 s
->trivial_literal_context
= (trivial
>> (block_type
& 31)) & 1;
1103 s
->literal_htree
= s
->literal_hgroup
.htrees
[s
->context_map_slice
[0]];
1104 context_mode
= s
->context_modes
[block_type
];
1105 s
->context_lookup1
= &kContextLookup
[kContextLookupOffsets
[context_mode
]];
1106 s
->context_lookup2
= &kContextLookup
[kContextLookupOffsets
[context_mode
+ 1]];
1109 /* Decodes the block type and updates the state for literal context.
1110 Reads 3..54 bits. */
1111 static BROTLI_INLINE BROTLI_BOOL
DecodeLiteralBlockSwitchInternal(
1112 int safe
, BrotliDecoderState
* s
) {
1113 if (!DecodeBlockTypeAndLength(safe
, s
, 0)) {
1114 return BROTLI_FALSE
;
1116 PrepareLiteralDecoding(s
);
1120 static void BROTLI_NOINLINE
DecodeLiteralBlockSwitch(BrotliDecoderState
* s
) {
1121 DecodeLiteralBlockSwitchInternal(0, s
);
1124 static BROTLI_BOOL BROTLI_NOINLINE
SafeDecodeLiteralBlockSwitch(
1125 BrotliDecoderState
* s
) {
1126 return DecodeLiteralBlockSwitchInternal(1, s
);
1129 /* Block switch for insert/copy length.
1130 Reads 3..54 bits. */
1131 static BROTLI_INLINE BROTLI_BOOL
DecodeCommandBlockSwitchInternal(
1132 int safe
, BrotliDecoderState
* s
) {
1133 if (!DecodeBlockTypeAndLength(safe
, s
, 1)) {
1134 return BROTLI_FALSE
;
1136 s
->htree_command
= s
->insert_copy_hgroup
.htrees
[s
->block_type_rb
[3]];
1140 static void BROTLI_NOINLINE
DecodeCommandBlockSwitch(BrotliDecoderState
* s
) {
1141 DecodeCommandBlockSwitchInternal(0, s
);
1143 static BROTLI_BOOL BROTLI_NOINLINE
SafeDecodeCommandBlockSwitch(
1144 BrotliDecoderState
* s
) {
1145 return DecodeCommandBlockSwitchInternal(1, s
);
1148 /* Block switch for distance codes.
1149 Reads 3..54 bits. */
1150 static BROTLI_INLINE BROTLI_BOOL
DecodeDistanceBlockSwitchInternal(
1151 int safe
, BrotliDecoderState
* s
) {
1152 if (!DecodeBlockTypeAndLength(safe
, s
, 2)) {
1153 return BROTLI_FALSE
;
1155 s
->dist_context_map_slice
= s
->dist_context_map
+
1156 (s
->block_type_rb
[5] << BROTLI_DISTANCE_CONTEXT_BITS
);
1157 s
->dist_htree_index
= s
->dist_context_map_slice
[s
->distance_context
];
1161 static void BROTLI_NOINLINE
DecodeDistanceBlockSwitch(BrotliDecoderState
* s
) {
1162 DecodeDistanceBlockSwitchInternal(0, s
);
1165 static BROTLI_BOOL BROTLI_NOINLINE
SafeDecodeDistanceBlockSwitch(
1166 BrotliDecoderState
* s
) {
1167 return DecodeDistanceBlockSwitchInternal(1, s
);
1170 static size_t UnwrittenBytes(const BrotliDecoderState
* s
, BROTLI_BOOL wrap
) {
1171 size_t pos
= wrap
&& s
->pos
> s
->ringbuffer_size
?
1172 (size_t)s
->ringbuffer_size
: (size_t)(s
->pos
);
1173 size_t partial_pos_rb
= (s
->rb_roundtrips
* (size_t)s
->ringbuffer_size
) + pos
;
1174 return partial_pos_rb
- s
->partial_pos_out
;
1177 static BrotliDecoderErrorCode BROTLI_NOINLINE
WriteRingBuffer(
1178 BrotliDecoderState
* s
, size_t* available_out
, uint8_t** next_out
,
1179 size_t* total_out
) {
1181 s
->ringbuffer
+ (s
->partial_pos_out
& (size_t)s
->ringbuffer_mask
);
1182 size_t to_write
= UnwrittenBytes(s
, BROTLI_TRUE
);
1183 size_t num_written
= *available_out
;
1184 if (num_written
> to_write
) {
1185 num_written
= to_write
;
1187 if (s
->meta_block_remaining_len
< 0) {
1188 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1
);
1190 memcpy(*next_out
, start
, num_written
);
1191 *next_out
+= num_written
;
1192 *available_out
-= num_written
;
1193 BROTLI_LOG_UINT(to_write
);
1194 BROTLI_LOG_UINT(num_written
);
1195 s
->partial_pos_out
+= num_written
;
1196 if (total_out
) *total_out
= s
->partial_pos_out
;
1197 if (num_written
< to_write
) {
1198 return BROTLI_DECODER_NEEDS_MORE_OUTPUT
;
1201 if (s
->pos
>= s
->ringbuffer_size
) {
1202 s
->pos
-= s
->ringbuffer_size
;
1205 return BROTLI_DECODER_SUCCESS
;
1208 /* Allocates ringbuffer.
1210 s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
1211 this function is called.
1213 Last two bytes of ringbuffer are initialized to 0, so context calculation
1214 could be done uniformly for the first two and all other positions.
1216 Custom dictionary, if any, is copied to the end of ringbuffer.
1218 static BROTLI_BOOL BROTLI_NOINLINE
BrotliAllocateRingBuffer(
1219 BrotliDecoderState
* s
) {
1220 /* We need the slack region for the following reasons:
1221 - doing up to two 16-byte copies for fast backward copying
1222 - inserting transformed dictionary word (5 prefix + 24 base + 8 suffix) */
1223 static const int kRingBufferWriteAheadSlack
= 42;
1224 s
->ringbuffer
= (uint8_t*)BROTLI_ALLOC(s
, (size_t)(s
->ringbuffer_size
+
1225 kRingBufferWriteAheadSlack
));
1226 if (s
->ringbuffer
== 0) {
1227 return BROTLI_FALSE
;
1230 s
->ringbuffer_end
= s
->ringbuffer
+ s
->ringbuffer_size
;
1232 s
->ringbuffer
[s
->ringbuffer_size
- 2] = 0;
1233 s
->ringbuffer
[s
->ringbuffer_size
- 1] = 0;
1235 if (s
->custom_dict
) {
1236 memcpy(&s
->ringbuffer
[(-s
->custom_dict_size
) & s
->ringbuffer_mask
],
1237 s
->custom_dict
, (size_t)s
->custom_dict_size
);
1243 static BrotliDecoderErrorCode BROTLI_NOINLINE
CopyUncompressedBlockToOutput(
1244 size_t* available_out
, uint8_t** next_out
, size_t* total_out
,
1245 BrotliDecoderState
* s
) {
1246 /* TODO: avoid allocation for single uncompressed block. */
1247 if (!s
->ringbuffer
&& !BrotliAllocateRingBuffer(s
)) {
1248 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1
);
1253 switch (s
->substate_uncompressed
) {
1254 case BROTLI_STATE_UNCOMPRESSED_NONE
: {
1255 int nbytes
= (int)BrotliGetRemainingBytes(&s
->br
);
1256 if (nbytes
> s
->meta_block_remaining_len
) {
1257 nbytes
= s
->meta_block_remaining_len
;
1259 if (s
->pos
+ nbytes
> s
->ringbuffer_size
) {
1260 nbytes
= s
->ringbuffer_size
- s
->pos
;
1262 /* Copy remaining bytes from s->br.buf_ to ringbuffer. */
1263 BrotliCopyBytes(&s
->ringbuffer
[s
->pos
], &s
->br
, (size_t)nbytes
);
1265 s
->meta_block_remaining_len
-= nbytes
;
1266 if (s
->pos
< s
->ringbuffer_size
) {
1267 if (s
->meta_block_remaining_len
== 0) {
1268 return BROTLI_DECODER_SUCCESS
;
1270 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
1272 s
->substate_uncompressed
= BROTLI_STATE_UNCOMPRESSED_WRITE
;
1273 /* No break, continue to next state */
1275 case BROTLI_STATE_UNCOMPRESSED_WRITE
: {
1276 BrotliDecoderErrorCode result
=
1277 WriteRingBuffer(s
, available_out
, next_out
, total_out
);
1278 if (result
!= BROTLI_DECODER_SUCCESS
) {
1281 s
->max_distance
= s
->max_backward_distance
;
1282 s
->substate_uncompressed
= BROTLI_STATE_UNCOMPRESSED_NONE
;
1287 BROTLI_DCHECK(0); /* Unreachable */
1290 BROTLI_BOOL
BrotliDecompressedSize(size_t encoded_size
,
1291 const uint8_t* encoded_buffer
,
1292 size_t* decoded_size
) {
1293 size_t total_size
= 0;
1294 BrotliDecoderState s
;
1295 BrotliBitReader
* br
;
1296 BrotliDecoderStateInit(&s
);
1299 br
->next_in
= encoded_buffer
;
1300 br
->avail_in
= encoded_size
;
1301 if (!BrotliWarmupBitReader(br
)) return BROTLI_FALSE
;
1302 DecodeWindowBits(br
);
1305 if (DecodeMetaBlockLength(&s
, br
) != BROTLI_DECODER_SUCCESS
) {
1306 return BROTLI_FALSE
;
1308 block_size
= (size_t)s
.meta_block_remaining_len
;
1309 if (!s
.is_metadata
) {
1310 if ((block_size
+ total_size
) < total_size
) return BROTLI_FALSE
;
1311 total_size
+= block_size
;
1313 if (s
.is_last_metablock
) {
1314 *decoded_size
= total_size
;
1317 if (!s
.is_uncompressed
&& !s
.is_metadata
) return BROTLI_FALSE
;
1318 if (!BrotliJumpToByteBoundary(br
)) return BROTLI_FALSE
;
1319 BrotliBitReaderUnload(br
);
1320 if (br
->avail_in
< block_size
) return BROTLI_FALSE
;
1321 br
->avail_in
-= block_size
;
1322 br
->next_in
+= block_size
;
1323 if (!BrotliWarmupBitReader(br
)) return BROTLI_FALSE
;
1327 /* Calculates the smallest feasible ring buffer.
1329 If we know the data size is small, do not allocate more ringbuffer
1330 size than needed to reduce memory usage.
1332 When this method is called, metablock size and flags MUST be decoded.
1334 static void BROTLI_NOINLINE
BrotliCalculateRingBufferSize(
1335 BrotliDecoderState
* s
, BrotliBitReader
* br
) {
1336 BROTLI_BOOL is_last
= TO_BROTLI_BOOL(s
->is_last_metablock
);
1337 int window_size
= 1 << s
->window_bits
;
1338 s
->ringbuffer_size
= window_size
;
1340 if (s
->is_uncompressed
) {
1341 int next_block_header
=
1342 BrotliPeekByte(br
, (size_t)s
->meta_block_remaining_len
);
1343 if (next_block_header
!= -1) { /* Peek succeeded */
1344 if ((next_block_header
& 3) == 3) { /* ISLAST and ISEMPTY */
1345 is_last
= BROTLI_TRUE
;
1350 /* We need at least 2 bytes of ring buffer size to get the last two
1351 bytes for context from there */
1353 int min_size_x2
= (s
->meta_block_remaining_len
+ s
->custom_dict_size
) * 2;
1354 while (s
->ringbuffer_size
>= min_size_x2
&& s
->ringbuffer_size
> 32) {
1355 s
->ringbuffer_size
>>= 1;
1359 s
->ringbuffer_mask
= s
->ringbuffer_size
- 1;
1362 /* Reads 1..256 2-bit context modes. */
1363 static BrotliDecoderErrorCode
ReadContextModes(BrotliDecoderState
* s
) {
1364 BrotliBitReader
* br
= &s
->br
;
1365 int i
= s
->loop_counter
;
1367 while (i
< (int)s
->num_block_types
[0]) {
1369 if (!BrotliSafeReadBits(br
, 2, &bits
)) {
1370 s
->loop_counter
= i
;
1371 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
1373 s
->context_modes
[i
] = (uint8_t)(bits
<< 1);
1374 BROTLI_LOG_ARRAY_INDEX(s
->context_modes
, i
);
1377 return BROTLI_DECODER_SUCCESS
;
1380 static BROTLI_INLINE
void TakeDistanceFromRingBuffer(BrotliDecoderState
* s
) {
1381 if (s
->distance_code
== 0) {
1383 s
->distance_code
= s
->dist_rb
[s
->dist_rb_idx
& 3];
1385 int distance_code
= s
->distance_code
<< 1;
1386 /* kDistanceShortCodeIndexOffset has 2-bit values from LSB: */
1387 /* 3, 2, 1, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2 */
1388 const uint32_t kDistanceShortCodeIndexOffset
= 0xaaafff1b;
1389 /* kDistanceShortCodeValueOffset has 2-bit values from LSB: */
1390 /*-0, 0,-0, 0,-1, 1,-2, 2,-3, 3,-1, 1,-2, 2,-3, 3 */
1391 const uint32_t kDistanceShortCodeValueOffset
= 0xfa5fa500;
1392 int v
= (s
->dist_rb_idx
+
1393 (int)(kDistanceShortCodeIndexOffset
>> distance_code
)) & 0x3;
1394 s
->distance_code
= s
->dist_rb
[v
];
1395 v
= (int)(kDistanceShortCodeValueOffset
>> distance_code
) & 0x3;
1396 if ((distance_code
& 0x3) != 0) {
1397 s
->distance_code
+= v
;
1399 s
->distance_code
-= v
;
1400 if (s
->distance_code
<= 0) {
1401 /* A huge distance will cause a BROTLI_FAILURE() soon. */
1402 /* This is a little faster than failing here. */
1403 s
->distance_code
= 0x0fffffff;
1409 static BROTLI_INLINE BROTLI_BOOL
SafeReadBits(
1410 BrotliBitReader
* const br
, uint32_t n_bits
, uint32_t* val
) {
1412 return BrotliSafeReadBits(br
, n_bits
, val
);
1419 /* Precondition: s->distance_code < 0 */
1420 static BROTLI_INLINE BROTLI_BOOL
ReadDistanceInternal(
1421 int safe
, BrotliDecoderState
* s
, BrotliBitReader
* br
) {
1423 BrotliBitReaderState memento
;
1424 HuffmanCode
* distance_tree
= s
->distance_hgroup
.htrees
[s
->dist_htree_index
];
1426 s
->distance_code
= (int)ReadSymbol(distance_tree
, br
);
1429 BrotliBitReaderSaveState(br
, &memento
);
1430 if (!SafeReadSymbol(distance_tree
, br
, &code
)) {
1431 return BROTLI_FALSE
;
1433 s
->distance_code
= (int)code
;
1435 /* Convert the distance code to the actual distance by possibly */
1436 /* looking up past distances from the s->ringbuffer. */
1437 if ((s
->distance_code
& ~0xf) == 0) {
1438 TakeDistanceFromRingBuffer(s
);
1439 --s
->block_length
[2];
1442 distval
= s
->distance_code
- (int)s
->num_direct_distance_codes
;
1447 if (!safe
&& (s
->distance_postfix_bits
== 0)) {
1448 nbits
= ((uint32_t)distval
>> 1) + 1;
1449 offset
= ((2 + (distval
& 1)) << nbits
) - 4;
1450 s
->distance_code
= (int)s
->num_direct_distance_codes
+ offset
+
1451 (int)BrotliReadBits(br
, nbits
);
1453 /* This branch also works well when s->distance_postfix_bits == 0 */
1455 postfix
= distval
& s
->distance_postfix_mask
;
1456 distval
>>= s
->distance_postfix_bits
;
1457 nbits
= ((uint32_t)distval
>> 1) + 1;
1459 if (!SafeReadBits(br
, nbits
, &bits
)) {
1460 s
->distance_code
= -1; /* Restore precondition. */
1461 BrotliBitReaderRestoreState(br
, &memento
);
1462 return BROTLI_FALSE
;
1465 bits
= BrotliReadBits(br
, nbits
);
1467 offset
= ((2 + (distval
& 1)) << nbits
) - 4;
1468 s
->distance_code
= (int)s
->num_direct_distance_codes
+
1469 ((offset
+ (int)bits
) << s
->distance_postfix_bits
) + postfix
;
1472 s
->distance_code
= s
->distance_code
- BROTLI_NUM_DISTANCE_SHORT_CODES
+ 1;
1473 --s
->block_length
[2];
1477 static BROTLI_INLINE
void ReadDistance(
1478 BrotliDecoderState
* s
, BrotliBitReader
* br
) {
1479 ReadDistanceInternal(0, s
, br
);
1482 static BROTLI_INLINE BROTLI_BOOL
SafeReadDistance(
1483 BrotliDecoderState
* s
, BrotliBitReader
* br
) {
1484 return ReadDistanceInternal(1, s
, br
);
1487 static BROTLI_INLINE BROTLI_BOOL
ReadCommandInternal(
1488 int safe
, BrotliDecoderState
* s
, BrotliBitReader
* br
, int* insert_length
) {
1490 uint32_t insert_len_extra
= 0;
1491 uint32_t copy_length
;
1493 BrotliBitReaderState memento
;
1495 cmd_code
= ReadSymbol(s
->htree_command
, br
);
1497 BrotliBitReaderSaveState(br
, &memento
);
1498 if (!SafeReadSymbol(s
->htree_command
, br
, &cmd_code
)) {
1499 return BROTLI_FALSE
;
1502 if (cmd_code
>= BROTLI_NUM_COMMAND_SYMBOLS
) cmd_code
= BROTLI_NUM_COMMAND_SYMBOLS
- 1;
1503 v
= kCmdLut
[cmd_code
];
1504 s
->distance_code
= v
.distance_code
;
1505 s
->distance_context
= v
.context
;
1506 s
->dist_htree_index
= s
->dist_context_map_slice
[s
->distance_context
];
1507 *insert_length
= v
.insert_len_offset
;
1509 if (PREDICT_FALSE(v
.insert_len_extra_bits
!= 0)) {
1510 insert_len_extra
= BrotliReadBits(br
, v
.insert_len_extra_bits
);
1512 copy_length
= BrotliReadBits(br
, v
.copy_len_extra_bits
);
1514 if (!SafeReadBits(br
, v
.insert_len_extra_bits
, &insert_len_extra
) ||
1515 !SafeReadBits(br
, v
.copy_len_extra_bits
, ©_length
)) {
1516 BrotliBitReaderRestoreState(br
, &memento
);
1517 return BROTLI_FALSE
;
1520 s
->copy_length
= (int)copy_length
+ v
.copy_len_offset
;
1521 --s
->block_length
[1];
1522 *insert_length
+= (int)insert_len_extra
;
1526 static BROTLI_INLINE
void ReadCommand(
1527 BrotliDecoderState
* s
, BrotliBitReader
* br
, int* insert_length
) {
1528 ReadCommandInternal(0, s
, br
, insert_length
);
1531 static BROTLI_INLINE BROTLI_BOOL
SafeReadCommand(
1532 BrotliDecoderState
* s
, BrotliBitReader
* br
, int* insert_length
) {
1533 return ReadCommandInternal(1, s
, br
, insert_length
);
1536 static BROTLI_INLINE BROTLI_BOOL
CheckInputAmount(
1537 int safe
, BrotliBitReader
* const br
, size_t num
) {
1541 return BrotliCheckInputAmount(br
, num
);
1544 #define BROTLI_SAFE(METHOD) \
1547 if (!Safe##METHOD) { \
1548 result = BROTLI_DECODER_NEEDS_MORE_INPUT; \
1549 goto saveStateAndReturn; \
1556 static BROTLI_INLINE BrotliDecoderErrorCode
ProcessCommandsInternal(
1557 int safe
, BrotliDecoderState
* s
) {
1559 int i
= s
->loop_counter
;
1560 BrotliDecoderErrorCode result
= BROTLI_DECODER_SUCCESS
;
1561 BrotliBitReader
* br
= &s
->br
;
1563 if (!CheckInputAmount(safe
, br
, 28)) {
1564 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1565 goto saveStateAndReturn
;
1568 BROTLI_UNUSED(BrotliWarmupBitReader(br
));
1571 /* Jump into state machine. */
1572 if (s
->state
== BROTLI_STATE_COMMAND_BEGIN
) {
1574 } else if (s
->state
== BROTLI_STATE_COMMAND_INNER
) {
1576 } else if (s
->state
== BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
) {
1577 goto CommandPostDecodeLiterals
;
1578 } else if (s
->state
== BROTLI_STATE_COMMAND_POST_WRAP_COPY
) {
1579 goto CommandPostWrapCopy
;
1581 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE
);
1586 s
->state
= BROTLI_STATE_COMMAND_BEGIN
;
1588 if (!CheckInputAmount(safe
, br
, 28)) { /* 156 bits + 7 bytes */
1589 s
->state
= BROTLI_STATE_COMMAND_BEGIN
;
1590 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1591 goto saveStateAndReturn
;
1593 if (PREDICT_FALSE(s
->block_length
[1] == 0)) {
1594 BROTLI_SAFE(DecodeCommandBlockSwitch(s
));
1597 /* Read the insert/copy length in the command */
1598 BROTLI_SAFE(ReadCommand(s
, br
, &i
));
1599 BROTLI_LOG(("[ProcessCommandsInternal] pos = %d insert = %d copy = %d\n",
1600 pos
, i
, s
->copy_length
));
1602 goto CommandPostDecodeLiterals
;
1604 s
->meta_block_remaining_len
-= i
;
1608 s
->state
= BROTLI_STATE_COMMAND_INNER
;
1610 /* Read the literals in the command */
1611 if (s
->trivial_literal_context
) {
1614 PreloadSymbol(safe
, s
->literal_htree
, br
, &bits
, &value
);
1616 if (!CheckInputAmount(safe
, br
, 28)) { /* 162 bits + 7 bytes */
1617 s
->state
= BROTLI_STATE_COMMAND_INNER
;
1618 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1619 goto saveStateAndReturn
;
1621 if (PREDICT_FALSE(s
->block_length
[0] == 0)) {
1622 BROTLI_SAFE(DecodeLiteralBlockSwitch(s
));
1623 PreloadSymbol(safe
, s
->literal_htree
, br
, &bits
, &value
);
1624 if (!s
->trivial_literal_context
) goto CommandInner
;
1627 s
->ringbuffer
[pos
] =
1628 (uint8_t)ReadPreloadedSymbol(s
->literal_htree
, br
, &bits
, &value
);
1631 if (!SafeReadSymbol(s
->literal_htree
, br
, &literal
)) {
1632 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1633 goto saveStateAndReturn
;
1635 s
->ringbuffer
[pos
] = (uint8_t)literal
;
1637 --s
->block_length
[0];
1638 BROTLI_LOG_ARRAY_INDEX(s
->ringbuffer
, pos
);
1640 if (PREDICT_FALSE(pos
== s
->ringbuffer_size
)) {
1641 s
->state
= BROTLI_STATE_COMMAND_INNER_WRITE
;
1643 goto saveStateAndReturn
;
1647 uint8_t p1
= s
->ringbuffer
[(pos
- 1) & s
->ringbuffer_mask
];
1648 uint8_t p2
= s
->ringbuffer
[(pos
- 2) & s
->ringbuffer_mask
];
1650 const HuffmanCode
* hc
;
1652 if (!CheckInputAmount(safe
, br
, 28)) { /* 162 bits + 7 bytes */
1653 s
->state
= BROTLI_STATE_COMMAND_INNER
;
1654 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1655 goto saveStateAndReturn
;
1657 if (PREDICT_FALSE(s
->block_length
[0] == 0)) {
1658 BROTLI_SAFE(DecodeLiteralBlockSwitch(s
));
1659 if (s
->trivial_literal_context
) goto CommandInner
;
1661 context
= s
->context_lookup1
[p1
] | s
->context_lookup2
[p2
];
1662 BROTLI_LOG_UINT(context
);
1663 hc
= s
->literal_hgroup
.htrees
[s
->context_map_slice
[context
]];
1666 p1
= (uint8_t)ReadSymbol(hc
, br
);
1669 if (!SafeReadSymbol(hc
, br
, &literal
)) {
1670 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1671 goto saveStateAndReturn
;
1673 p1
= (uint8_t)literal
;
1675 s
->ringbuffer
[pos
] = p1
;
1676 --s
->block_length
[0];
1677 BROTLI_LOG_UINT(s
->context_map_slice
[context
]);
1678 BROTLI_LOG_ARRAY_INDEX(s
->ringbuffer
, pos
& s
->ringbuffer_mask
);
1680 if (PREDICT_FALSE(pos
== s
->ringbuffer_size
)) {
1681 s
->state
= BROTLI_STATE_COMMAND_INNER_WRITE
;
1683 goto saveStateAndReturn
;
1687 BROTLI_LOG_UINT(s
->meta_block_remaining_len
);
1688 if (PREDICT_FALSE(s
->meta_block_remaining_len
<= 0)) {
1689 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
1690 goto saveStateAndReturn
;
1693 CommandPostDecodeLiterals
:
1695 s
->state
= BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
;
1697 if (s
->distance_code
>= 0) {
1699 s
->distance_code
= s
->dist_rb
[s
->dist_rb_idx
& 3];
1700 goto postReadDistance
; /* We already have the implicit distance */
1702 /* Read distance code in the command, unless it was implicitly zero. */
1703 if (PREDICT_FALSE(s
->block_length
[2] == 0)) {
1704 BROTLI_SAFE(DecodeDistanceBlockSwitch(s
));
1706 BROTLI_SAFE(ReadDistance(s
, br
));
1708 BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n",
1709 pos
, s
->distance_code
));
1710 if (s
->max_distance
!= s
->max_backward_distance
) {
1711 if (pos
< s
->max_backward_distance_minus_custom_dict_size
) {
1712 s
->max_distance
= pos
+ s
->custom_dict_size
;
1714 s
->max_distance
= s
->max_backward_distance
;
1718 /* Apply copy of LZ77 back-reference, or static dictionary reference if
1719 the distance is larger than the max LZ77 distance */
1720 if (s
->distance_code
> s
->max_distance
) {
1721 if (i
>= kBrotliMinDictionaryWordLength
&&
1722 i
<= kBrotliMaxDictionaryWordLength
) {
1723 int offset
= (int)kBrotliDictionaryOffsetsByLength
[i
];
1724 int word_id
= s
->distance_code
- s
->max_distance
- 1;
1725 uint32_t shift
= kBrotliDictionarySizeBitsByLength
[i
];
1726 int mask
= (int)BitMask(shift
);
1727 int word_idx
= word_id
& mask
;
1728 int transform_idx
= word_id
>> shift
;
1729 offset
+= word_idx
* i
;
1730 if (transform_idx
< kNumTransforms
) {
1731 const uint8_t* word
= &kBrotliDictionary
[offset
];
1733 if (transform_idx
== 0) {
1734 memcpy(&s
->ringbuffer
[pos
], word
, (size_t)len
);
1736 len
= TransformDictionaryWord(
1737 &s
->ringbuffer
[pos
], word
, len
, transform_idx
);
1740 s
->meta_block_remaining_len
-= len
;
1741 if (pos
>= s
->ringbuffer_size
) {
1742 /*s->partial_pos_rb += (size_t)s->ringbuffer_size;*/
1743 s
->state
= BROTLI_STATE_COMMAND_POST_WRITE_1
;
1744 goto saveStateAndReturn
;
1747 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
1748 "len: %d bytes left: %d\n",
1749 pos
, s
->distance_code
, i
, s
->meta_block_remaining_len
));
1750 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM
);
1753 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
1754 "len: %d bytes left: %d\n",
1755 pos
, s
->distance_code
, i
, s
->meta_block_remaining_len
));
1756 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY
);
1759 int src_start
= (pos
- s
->distance_code
) & s
->ringbuffer_mask
;
1760 uint8_t* copy_dst
= &s
->ringbuffer
[pos
];
1761 uint8_t* copy_src
= &s
->ringbuffer
[src_start
];
1762 int dst_end
= pos
+ i
;
1763 int src_end
= src_start
+ i
;
1764 /* update the recent distances cache */
1765 s
->dist_rb
[s
->dist_rb_idx
& 3] = s
->distance_code
;
1767 s
->meta_block_remaining_len
-= i
;
1768 /* There are 32+ bytes of slack in the ringbuffer allocation.
1769 Also, we have 16 short codes, that make these 16 bytes irrelevant
1770 in the ringbuffer. Let's copy over them as a first guess.
1772 memmove16(copy_dst
, copy_src
);
1773 if (src_end
> pos
&& dst_end
> src_start
) {
1774 /* Regions intersect. */
1775 goto CommandPostWrapCopy
;
1777 if (dst_end
>= s
->ringbuffer_size
|| src_end
>= s
->ringbuffer_size
) {
1778 /* At least one region wraps. */
1779 goto CommandPostWrapCopy
;
1784 memcpy(copy_dst
+ 16, copy_src
+ 16, (size_t)(i
- 16));
1786 /* This branch covers about 45% cases.
1787 Fixed size short copy allows more compiler optimizations. */
1788 memmove16(copy_dst
+ 16, copy_src
+ 16);
1792 BROTLI_LOG_UINT(s
->meta_block_remaining_len
);
1793 if (s
->meta_block_remaining_len
<= 0) {
1794 /* Next metablock, if any */
1795 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
1796 goto saveStateAndReturn
;
1800 CommandPostWrapCopy
:
1802 int wrap_guard
= s
->ringbuffer_size
- pos
;
1804 s
->ringbuffer
[pos
] =
1805 s
->ringbuffer
[(pos
- s
->distance_code
) & s
->ringbuffer_mask
];
1807 if (PREDICT_FALSE(--wrap_guard
== 0)) {
1808 s
->state
= BROTLI_STATE_COMMAND_POST_WRITE_2
;
1809 goto saveStateAndReturn
;
1813 if (s
->meta_block_remaining_len
<= 0) {
1814 /* Next metablock, if any */
1815 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
1816 goto saveStateAndReturn
;
1823 s
->loop_counter
= i
;
1829 static BROTLI_NOINLINE BrotliDecoderErrorCode
ProcessCommands(
1830 BrotliDecoderState
* s
) {
1831 return ProcessCommandsInternal(0, s
);
1834 static BROTLI_NOINLINE BrotliDecoderErrorCode
SafeProcessCommands(
1835 BrotliDecoderState
* s
) {
1836 return ProcessCommandsInternal(1, s
);
1839 BrotliDecoderResult
BrotliDecoderDecompress(
1840 size_t encoded_size
, const uint8_t* encoded_buffer
, size_t* decoded_size
,
1841 uint8_t* decoded_buffer
) {
1842 BrotliDecoderState s
;
1843 BrotliDecoderResult result
;
1844 size_t total_out
= 0;
1845 size_t available_in
= encoded_size
;
1846 const uint8_t* next_in
= encoded_buffer
;
1847 size_t available_out
= *decoded_size
;
1848 uint8_t* next_out
= decoded_buffer
;
1849 BrotliDecoderStateInit(&s
);
1850 result
= BrotliDecoderDecompressStream(
1851 &s
, &available_in
, &next_in
, &available_out
, &next_out
, &total_out
);
1852 *decoded_size
= total_out
;
1853 BrotliDecoderStateCleanup(&s
);
1854 if (result
!= BROTLI_DECODER_RESULT_SUCCESS
) {
1855 result
= BROTLI_DECODER_RESULT_ERROR
;
1860 /* Invariant: input stream is never overconsumed:
1861 * invalid input implies that the whole stream is invalid -> any amount of
1862 input could be read and discarded
1863 * when result is "needs more input", then at leat one more byte is REQUIRED
1864 to complete decoding; all input data MUST be consumed by decoder, so
1865 client could swap the input buffer
1866 * when result is "needs more output" decoder MUST ensure that it doesn't
1867 hold more than 7 bits in bit reader; this saves client from swapping input
1868 buffer ahead of time
1869 * when result is "success" decoder MUST return all unused data back to input
1870 buffer; this is possible because the invariant is hold on enter
1872 BrotliDecoderResult
BrotliDecoderDecompressStream(
1873 BrotliDecoderState
* s
, size_t* available_in
, const uint8_t** next_in
,
1874 size_t* available_out
, uint8_t** next_out
, size_t* total_out
) {
1875 BrotliDecoderErrorCode result
= BROTLI_DECODER_SUCCESS
;
1876 BrotliBitReader
* br
= &s
->br
;
1877 if (s
->buffer_length
== 0) { /* Just connect bit reader to input stream. */
1878 br
->avail_in
= *available_in
;
1879 br
->next_in
= *next_in
;
1881 /* At least one byte of input is required. More than one byte of input may
1882 be required to complete the transaction -> reading more data must be
1883 done in a loop -> do it in a main loop. */
1884 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1885 br
->next_in
= &s
->buffer
.u8
[0];
1889 if (result
!= BROTLI_DECODER_SUCCESS
) { /* Error, needs more input/output */
1890 if (result
== BROTLI_DECODER_NEEDS_MORE_INPUT
) {
1891 if (s
->ringbuffer
!= 0) { /* Proactively push output. */
1892 WriteRingBuffer(s
, available_out
, next_out
, total_out
);
1894 if (s
->buffer_length
!= 0) { /* Used with internal buffer. */
1895 if (br
->avail_in
== 0) { /* Successfully finished read transaction. */
1896 /* Accamulator contains less than 8 bits, because internal buffer
1897 is expanded byte-by-byte until it is enough to complete read. */
1898 s
->buffer_length
= 0;
1899 /* Switch to input stream and restart. */
1900 result
= BROTLI_DECODER_SUCCESS
;
1901 br
->avail_in
= *available_in
;
1902 br
->next_in
= *next_in
;
1904 } else if (*available_in
!= 0) {
1905 /* Not enough data in buffer, but can take one more byte from
1907 result
= BROTLI_DECODER_SUCCESS
;
1908 s
->buffer
.u8
[s
->buffer_length
] = **next_in
;
1910 br
->avail_in
= s
->buffer_length
;
1913 /* Retry with more data in buffer. */
1916 /* Can't finish reading and no more input.*/
1918 } else { /* Input stream doesn't contain enough input. */
1919 /* Copy tail to internal buffer and return. */
1920 *next_in
= br
->next_in
;
1921 *available_in
= br
->avail_in
;
1922 while (*available_in
) {
1923 s
->buffer
.u8
[s
->buffer_length
] = **next_in
;
1933 /* Fail or needs more output. */
1935 if (s
->buffer_length
!= 0) {
1936 /* Just consumed the buffered input and produced some output. Otherwise
1937 it would result in "needs more input". Reset internal buffer.*/
1938 s
->buffer_length
= 0;
1940 /* Using input stream in last iteration. When decoder switches to input
1941 stream it has less than 8 bits in accamulator, so it is safe to
1942 return unused accamulator bits there. */
1943 BrotliBitReaderUnload(br
);
1944 *available_in
= br
->avail_in
;
1945 *next_in
= br
->next_in
;
1950 case BROTLI_STATE_UNINITED
:
1951 /* Prepare to the first read. */
1952 if (!BrotliWarmupBitReader(br
)) {
1953 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1956 /* Decode window size. */
1957 s
->window_bits
= DecodeWindowBits(br
); /* Reads 1..7 bits. */
1958 BROTLI_LOG_UINT(s
->window_bits
);
1959 if (s
->window_bits
== 9) {
1960 /* Value 9 is reserved for future use. */
1961 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS
);
1964 /* Maximum distance, see section 9.1. of the spec. */
1965 s
->max_backward_distance
= (1 << s
->window_bits
) - 16;
1966 /* Limit custom dictionary size. */
1967 if (s
->custom_dict_size
>= s
->max_backward_distance
) {
1968 s
->custom_dict
+= s
->custom_dict_size
- s
->max_backward_distance
;
1969 s
->custom_dict_size
= s
->max_backward_distance
;
1971 s
->max_backward_distance_minus_custom_dict_size
=
1972 s
->max_backward_distance
- s
->custom_dict_size
;
1974 /* Allocate memory for both block_type_trees and block_len_trees. */
1975 s
->block_type_trees
= (HuffmanCode
*)BROTLI_ALLOC(s
,
1976 sizeof(HuffmanCode
) * 3 *
1977 (BROTLI_HUFFMAN_MAX_SIZE_258
+ BROTLI_HUFFMAN_MAX_SIZE_26
));
1978 if (s
->block_type_trees
== 0) {
1979 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES
);
1982 s
->block_len_trees
=
1983 s
->block_type_trees
+ 3 * BROTLI_HUFFMAN_MAX_SIZE_258
;
1985 s
->state
= BROTLI_STATE_METABLOCK_BEGIN
;
1986 /* No break, continue to next state */
1987 case BROTLI_STATE_METABLOCK_BEGIN
:
1988 BrotliDecoderStateMetablockBegin(s
);
1989 BROTLI_LOG_UINT(s
->pos
);
1990 s
->state
= BROTLI_STATE_METABLOCK_HEADER
;
1991 /* No break, continue to next state */
1992 case BROTLI_STATE_METABLOCK_HEADER
:
1993 result
= DecodeMetaBlockLength(s
, br
); /* Reads 2 - 31 bits. */
1994 if (result
!= BROTLI_DECODER_SUCCESS
) {
1997 BROTLI_LOG_UINT(s
->is_last_metablock
);
1998 BROTLI_LOG_UINT(s
->meta_block_remaining_len
);
1999 BROTLI_LOG_UINT(s
->is_metadata
);
2000 BROTLI_LOG_UINT(s
->is_uncompressed
);
2001 if (s
->is_metadata
|| s
->is_uncompressed
) {
2002 if (!BrotliJumpToByteBoundary(br
)) {
2003 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1
);
2007 if (s
->is_metadata
) {
2008 s
->state
= BROTLI_STATE_METADATA
;
2011 if (s
->meta_block_remaining_len
== 0) {
2012 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2015 if (!s
->ringbuffer
) {
2016 BrotliCalculateRingBufferSize(s
, br
);
2018 if (s
->is_uncompressed
) {
2019 s
->state
= BROTLI_STATE_UNCOMPRESSED
;
2022 s
->loop_counter
= 0;
2023 s
->state
= BROTLI_STATE_HUFFMAN_CODE_0
;
2025 case BROTLI_STATE_UNCOMPRESSED
: {
2026 int bytes_copied
= s
->meta_block_remaining_len
;
2027 result
= CopyUncompressedBlockToOutput(
2028 available_out
, next_out
, total_out
, s
);
2029 bytes_copied
-= s
->meta_block_remaining_len
;
2030 if (result
!= BROTLI_DECODER_SUCCESS
) {
2033 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2036 case BROTLI_STATE_METADATA
:
2037 for (; s
->meta_block_remaining_len
> 0; --s
->meta_block_remaining_len
) {
2039 /* Read one byte and ignore it. */
2040 if (!BrotliSafeReadBits(br
, 8, &bits
)) {
2041 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
2045 if (result
== BROTLI_DECODER_SUCCESS
) {
2046 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2049 case BROTLI_STATE_HUFFMAN_CODE_0
:
2050 if (s
->loop_counter
>= 3) {
2051 s
->state
= BROTLI_STATE_METABLOCK_HEADER_2
;
2054 /* Reads 1..11 bits. */
2055 result
= DecodeVarLenUint8(s
, br
, &s
->num_block_types
[s
->loop_counter
]);
2056 if (result
!= BROTLI_DECODER_SUCCESS
) {
2059 s
->num_block_types
[s
->loop_counter
]++;
2060 BROTLI_LOG_UINT(s
->num_block_types
[s
->loop_counter
]);
2061 if (s
->num_block_types
[s
->loop_counter
] < 2) {
2065 s
->state
= BROTLI_STATE_HUFFMAN_CODE_1
;
2066 /* No break, continue to next state */
2067 case BROTLI_STATE_HUFFMAN_CODE_1
: {
2068 int tree_offset
= s
->loop_counter
* BROTLI_HUFFMAN_MAX_SIZE_258
;
2069 result
= ReadHuffmanCode(s
->num_block_types
[s
->loop_counter
] + 2,
2070 &s
->block_type_trees
[tree_offset
], NULL
, s
);
2071 if (result
!= BROTLI_DECODER_SUCCESS
) break;
2072 s
->state
= BROTLI_STATE_HUFFMAN_CODE_2
;
2073 /* No break, continue to next state */
2075 case BROTLI_STATE_HUFFMAN_CODE_2
: {
2076 int tree_offset
= s
->loop_counter
* BROTLI_HUFFMAN_MAX_SIZE_26
;
2077 result
= ReadHuffmanCode(BROTLI_NUM_BLOCK_LEN_SYMBOLS
,
2078 &s
->block_len_trees
[tree_offset
], NULL
, s
);
2079 if (result
!= BROTLI_DECODER_SUCCESS
) break;
2080 s
->state
= BROTLI_STATE_HUFFMAN_CODE_3
;
2081 /* No break, continue to next state */
2083 case BROTLI_STATE_HUFFMAN_CODE_3
: {
2084 int tree_offset
= s
->loop_counter
* BROTLI_HUFFMAN_MAX_SIZE_26
;
2085 if (!SafeReadBlockLength(s
, &s
->block_length
[s
->loop_counter
],
2086 &s
->block_len_trees
[tree_offset
], br
)) {
2087 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
2090 BROTLI_LOG_UINT(s
->block_length
[s
->loop_counter
]);
2092 s
->state
= BROTLI_STATE_HUFFMAN_CODE_0
;
2095 case BROTLI_STATE_METABLOCK_HEADER_2
: {
2097 if (!BrotliSafeReadBits(br
, 6, &bits
)) {
2098 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
2101 s
->distance_postfix_bits
= bits
& BitMask(2);
2103 s
->num_direct_distance_codes
= BROTLI_NUM_DISTANCE_SHORT_CODES
+
2104 (bits
<< s
->distance_postfix_bits
);
2105 BROTLI_LOG_UINT(s
->num_direct_distance_codes
);
2106 BROTLI_LOG_UINT(s
->distance_postfix_bits
);
2107 s
->distance_postfix_mask
= (int)BitMask(s
->distance_postfix_bits
);
2109 (uint8_t*)BROTLI_ALLOC(s
, (size_t)s
->num_block_types
[0]);
2110 if (s
->context_modes
== 0) {
2111 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES
);
2114 s
->loop_counter
= 0;
2115 s
->state
= BROTLI_STATE_CONTEXT_MODES
;
2116 /* No break, continue to next state */
2118 case BROTLI_STATE_CONTEXT_MODES
:
2119 result
= ReadContextModes(s
);
2120 if (result
!= BROTLI_DECODER_SUCCESS
) {
2123 s
->state
= BROTLI_STATE_CONTEXT_MAP_1
;
2124 /* No break, continue to next state */
2125 case BROTLI_STATE_CONTEXT_MAP_1
:
2126 result
= DecodeContextMap(
2127 s
->num_block_types
[0] << BROTLI_LITERAL_CONTEXT_BITS
,
2128 &s
->num_literal_htrees
, &s
->context_map
, s
);
2129 if (result
!= BROTLI_DECODER_SUCCESS
) {
2132 DetectTrivialLiteralBlockTypes(s
);
2133 s
->state
= BROTLI_STATE_CONTEXT_MAP_2
;
2134 /* No break, continue to next state */
2135 case BROTLI_STATE_CONTEXT_MAP_2
:
2137 uint32_t num_distance_codes
=
2138 s
->num_direct_distance_codes
+ (48U << s
->distance_postfix_bits
);
2139 result
= DecodeContextMap(
2140 s
->num_block_types
[2] << BROTLI_DISTANCE_CONTEXT_BITS
,
2141 &s
->num_dist_htrees
, &s
->dist_context_map
, s
);
2142 if (result
!= BROTLI_DECODER_SUCCESS
) {
2145 BrotliDecoderHuffmanTreeGroupInit(
2146 s
, &s
->literal_hgroup
, BROTLI_NUM_LITERAL_SYMBOLS
,
2147 s
->num_literal_htrees
);
2148 BrotliDecoderHuffmanTreeGroupInit(
2149 s
, &s
->insert_copy_hgroup
, BROTLI_NUM_COMMAND_SYMBOLS
,
2150 s
->num_block_types
[1]);
2151 BrotliDecoderHuffmanTreeGroupInit(
2152 s
, &s
->distance_hgroup
, num_distance_codes
,
2153 s
->num_dist_htrees
);
2154 if (s
->literal_hgroup
.codes
== 0 ||
2155 s
->insert_copy_hgroup
.codes
== 0 ||
2156 s
->distance_hgroup
.codes
== 0) {
2157 return SaveErrorCode(s
,
2158 BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS
));
2161 s
->loop_counter
= 0;
2162 s
->state
= BROTLI_STATE_TREE_GROUP
;
2163 /* No break, continue to next state */
2164 case BROTLI_STATE_TREE_GROUP
:
2166 HuffmanTreeGroup
* hgroup
= NULL
;
2167 switch (s
->loop_counter
) {
2169 hgroup
= &s
->literal_hgroup
;
2172 hgroup
= &s
->insert_copy_hgroup
;
2175 hgroup
= &s
->distance_hgroup
;
2178 return SaveErrorCode(s
, BROTLI_FAILURE(
2179 BROTLI_DECODER_ERROR_UNREACHABLE
));
2181 result
= HuffmanTreeGroupDecode(hgroup
, s
);
2183 if (result
!= BROTLI_DECODER_SUCCESS
) break;
2185 if (s
->loop_counter
>= 3) {
2186 PrepareLiteralDecoding(s
);
2187 s
->dist_context_map_slice
= s
->dist_context_map
;
2188 s
->htree_command
= s
->insert_copy_hgroup
.htrees
[0];
2189 if (!s
->ringbuffer
&& !BrotliAllocateRingBuffer(s
)) {
2190 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2
);
2193 s
->state
= BROTLI_STATE_COMMAND_BEGIN
;
2196 case BROTLI_STATE_COMMAND_BEGIN
:
2197 case BROTLI_STATE_COMMAND_INNER
:
2198 case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
:
2199 case BROTLI_STATE_COMMAND_POST_WRAP_COPY
:
2200 result
= ProcessCommands(s
);
2201 if (result
== BROTLI_DECODER_NEEDS_MORE_INPUT
) {
2202 result
= SafeProcessCommands(s
);
2205 case BROTLI_STATE_COMMAND_INNER_WRITE
:
2206 case BROTLI_STATE_COMMAND_POST_WRITE_1
:
2207 case BROTLI_STATE_COMMAND_POST_WRITE_2
:
2208 result
= WriteRingBuffer(s
, available_out
, next_out
, total_out
);
2209 if (result
!= BROTLI_DECODER_SUCCESS
) {
2212 s
->max_distance
= s
->max_backward_distance
;
2213 if (s
->state
== BROTLI_STATE_COMMAND_POST_WRITE_1
) {
2214 if (s
->ringbuffer
!= 0) {
2215 memcpy(s
->ringbuffer
, s
->ringbuffer_end
, (size_t)s
->pos
);
2217 if (s
->meta_block_remaining_len
== 0) {
2218 /* Next metablock, if any */
2219 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2221 s
->state
= BROTLI_STATE_COMMAND_BEGIN
;
2224 } else if (s
->state
== BROTLI_STATE_COMMAND_POST_WRITE_2
) {
2225 s
->state
= BROTLI_STATE_COMMAND_POST_WRAP_COPY
;
2226 } else { /* BROTLI_STATE_COMMAND_INNER_WRITE */
2227 if (s
->loop_counter
== 0) {
2228 if (s
->meta_block_remaining_len
== 0) {
2229 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2231 s
->state
= BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
;
2235 s
->state
= BROTLI_STATE_COMMAND_INNER
;
2238 case BROTLI_STATE_METABLOCK_DONE
:
2239 if (s
->meta_block_remaining_len
< 0) {
2240 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2
);
2243 BrotliDecoderStateCleanupAfterMetablock(s
);
2244 if (!s
->is_last_metablock
) {
2245 s
->state
= BROTLI_STATE_METABLOCK_BEGIN
;
2248 if (!BrotliJumpToByteBoundary(br
)) {
2249 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2
);
2252 if (s
->buffer_length
== 0) {
2253 BrotliBitReaderUnload(br
);
2254 *available_in
= br
->avail_in
;
2255 *next_in
= br
->next_in
;
2257 s
->state
= BROTLI_STATE_DONE
;
2258 /* No break, continue to next state */
2259 case BROTLI_STATE_DONE
:
2260 if (s
->ringbuffer
!= 0) {
2261 result
= WriteRingBuffer(s
, available_out
, next_out
, total_out
);
2262 if (result
!= BROTLI_DECODER_SUCCESS
) {
2266 return SaveErrorCode(s
, result
);
2269 return SaveErrorCode(s
, result
);
2272 void BrotliDecoderSetCustomDictionary(
2273 BrotliDecoderState
* s
, size_t size
, const uint8_t* dict
) {
2274 if (size
> (1u << 24)) {
2277 s
->custom_dict
= dict
;
2278 s
->custom_dict_size
= (int)size
;
2281 BROTLI_BOOL
BrotliDecoderHasMoreOutput(const BrotliDecoderState
* s
) {
2282 return TO_BROTLI_BOOL(
2283 s
->ringbuffer
!= 0 && UnwrittenBytes(s
, BROTLI_FALSE
) != 0);
2286 BROTLI_BOOL
BrotliDecoderIsUsed(const BrotliDecoderState
* s
) {
2287 return TO_BROTLI_BOOL(s
->state
!= BROTLI_STATE_UNINITED
||
2288 BrotliGetAvailableBits(&s
->br
) != 0);
2291 BROTLI_BOOL
BrotliDecoderIsFinished(const BrotliDecoderState
* s
) {
2292 return TO_BROTLI_BOOL(s
->state
== BROTLI_STATE_DONE
);
2295 BrotliDecoderErrorCode
BrotliDecoderGetErrorCode(const BrotliDecoderState
* s
) {
2296 return (BrotliDecoderErrorCode
)s
->error_code
;
2299 const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c
) {
2301 #define _BROTLI_ERROR_CODE_CASE(PREFIX, NAME, CODE) \
2302 case BROTLI_DECODER ## PREFIX ## NAME: return #NAME;
2303 #define _BROTLI_NOTHING
2304 BROTLI_DECODER_ERROR_CODES_LIST(_BROTLI_ERROR_CODE_CASE
, _BROTLI_NOTHING
)
2305 #undef _BROTLI_ERROR_CODE_CASE
2306 #undef _BROTLI_NOTHING
2307 default: return "INVALID";
2311 /* DEPRECATED >>> */
2312 BrotliState
* BrotliCreateState(
2313 brotli_alloc_func alloc
, brotli_free_func free
, void* opaque
) {
2314 return (BrotliState
*)BrotliDecoderCreateInstance(alloc
, free
, opaque
);
2316 void BrotliDestroyState(BrotliState
* state
) {
2317 BrotliDecoderDestroyInstance((BrotliDecoderState
*)state
);
2319 BrotliResult
BrotliDecompressBuffer(
2320 size_t encoded_size
, const uint8_t* encoded_buffer
, size_t* decoded_size
,
2321 uint8_t* decoded_buffer
) {
2322 return (BrotliResult
)BrotliDecoderDecompress(
2323 encoded_size
, encoded_buffer
, decoded_size
, decoded_buffer
);
2325 BrotliResult
BrotliDecompressStream(
2326 size_t* available_in
, const uint8_t** next_in
, size_t* available_out
,
2327 uint8_t** next_out
, size_t* total_out
, BrotliState
* s
) {
2328 return (BrotliResult
)BrotliDecoderDecompressStream((BrotliDecoderState
*)s
,
2329 available_in
, next_in
, available_out
, next_out
, total_out
);
2331 void BrotliSetCustomDictionary(
2332 size_t size
, const uint8_t* dict
, BrotliState
* s
) {
2333 BrotliDecoderSetCustomDictionary((BrotliDecoderState
*)s
, size
, dict
);
2335 BROTLI_BOOL
BrotliStateIsStreamStart(const BrotliState
* s
) {
2336 return !BrotliDecoderIsUsed((const BrotliDecoderState
*)s
);
2338 BROTLI_BOOL
BrotliStateIsStreamEnd(const BrotliState
* s
) {
2339 return BrotliDecoderIsFinished((const BrotliDecoderState
*)s
);
2341 BrotliErrorCode
BrotliGetErrorCode(const BrotliState
* s
) {
2342 return (BrotliErrorCode
)BrotliDecoderGetErrorCode(
2343 (const BrotliDecoderState
*)s
);
2345 const char* BrotliErrorString(BrotliErrorCode c
) {
2346 return BrotliDecoderErrorString((BrotliDecoderErrorCode
)c
);
2348 /* <<< DEPRECATED */
2350 #if defined(__cplusplus) || defined(c_plusplus)