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 uint8_t* mtft
= &state
->mtf
[3];
859 /* Load endian-aware constant. */
860 const uint8_t b0123
[4] = {0, 1, 2, 3};
862 memcpy(&pattern
, &b0123
, 4);
864 /* Initialize list using 4 consequent values pattern. */
865 *(uint32_t*)mtf
= pattern
;
867 pattern
+= 0x04040404; /* Advance all 4 values by 4. */
868 *(uint32_t*)(mtf
+ i
) = pattern
;
870 } while (i
<= upper_bound
);
872 /* Transform the input. */
874 for (i
= 0; i
< v_len
; ++i
) {
876 uint8_t value
= mtf
[index
];
877 upper_bound
|= (uint32_t)v
[i
];
881 mtft
[index
+ 1] = mtft
[index
];
885 /* Remember amount of elements to be reinitialized. */
886 state
->mtf_upper_bound
= upper_bound
;
889 /* Decodes a series of Huffman table using ReadHuffmanCode function. */
890 static BrotliDecoderErrorCode
HuffmanTreeGroupDecode(
891 HuffmanTreeGroup
* group
, BrotliDecoderState
* s
) {
892 if (s
->substate_tree_group
!= BROTLI_STATE_TREE_GROUP_LOOP
) {
893 s
->next
= group
->codes
;
895 s
->substate_tree_group
= BROTLI_STATE_TREE_GROUP_LOOP
;
897 while (s
->htree_index
< group
->num_htrees
) {
899 BrotliDecoderErrorCode result
=
900 ReadHuffmanCode(group
->alphabet_size
, s
->next
, &table_size
, s
);
901 if (result
!= BROTLI_DECODER_SUCCESS
) return result
;
902 group
->htrees
[s
->htree_index
] = s
->next
;
903 s
->next
+= table_size
;
906 s
->substate_tree_group
= BROTLI_STATE_TREE_GROUP_NONE
;
907 return BROTLI_DECODER_SUCCESS
;
910 /* Decodes a context map.
911 Decoding is done in 4 phases:
912 1) Read auxiliary information (6..16 bits) and allocate memory.
913 In case of trivial context map, decoding is finished at this phase.
914 2) Decode Huffman table using ReadHuffmanCode function.
915 This table will be used for reading context map items.
916 3) Read context map items; "0" values could be run-length encoded.
917 4) Optionally, apply InverseMoveToFront transform to the resulting map.
919 static BrotliDecoderErrorCode
DecodeContextMap(uint32_t context_map_size
,
920 uint32_t* num_htrees
,
921 uint8_t** context_map_arg
,
922 BrotliDecoderState
* s
) {
923 BrotliBitReader
* br
= &s
->br
;
924 BrotliDecoderErrorCode result
= BROTLI_DECODER_SUCCESS
;
926 switch ((int)s
->substate_context_map
) {
927 case BROTLI_STATE_CONTEXT_MAP_NONE
:
928 result
= DecodeVarLenUint8(s
, br
, num_htrees
);
929 if (result
!= BROTLI_DECODER_SUCCESS
) {
933 s
->context_index
= 0;
934 BROTLI_LOG_UINT(context_map_size
);
935 BROTLI_LOG_UINT(*num_htrees
);
936 *context_map_arg
= (uint8_t*)BROTLI_ALLOC(s
, (size_t)context_map_size
);
937 if (*context_map_arg
== 0) {
938 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP
);
940 if (*num_htrees
<= 1) {
941 memset(*context_map_arg
, 0, (size_t)context_map_size
);
942 return BROTLI_DECODER_SUCCESS
;
944 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_READ_PREFIX
;
945 /* No break, continue to next state. */
946 case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX
: {
948 /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe
949 to peek 4 bits ahead. */
950 if (!BrotliSafeGetBits(br
, 5, &bits
)) {
951 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
953 if ((bits
& 1) != 0) { /* Use RLE for zeroes. */
954 s
->max_run_length_prefix
= (bits
>> 1) + 1;
955 BrotliDropBits(br
, 5);
957 s
->max_run_length_prefix
= 0;
958 BrotliDropBits(br
, 1);
960 BROTLI_LOG_UINT(s
->max_run_length_prefix
);
961 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_HUFFMAN
;
962 /* No break, continue to next state. */
964 case BROTLI_STATE_CONTEXT_MAP_HUFFMAN
:
965 result
= ReadHuffmanCode(*num_htrees
+ s
->max_run_length_prefix
,
966 s
->context_map_table
, NULL
, s
);
967 if (result
!= BROTLI_DECODER_SUCCESS
) return result
;
969 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_DECODE
;
970 /* No break, continue to next state. */
971 case BROTLI_STATE_CONTEXT_MAP_DECODE
: {
972 uint32_t context_index
= s
->context_index
;
973 uint32_t max_run_length_prefix
= s
->max_run_length_prefix
;
974 uint8_t* context_map
= *context_map_arg
;
975 uint32_t code
= s
->code
;
976 if (code
!= 0xFFFF) {
979 while (context_index
< context_map_size
) {
980 if (!SafeReadSymbol(s
->context_map_table
, br
, &code
)) {
982 s
->context_index
= context_index
;
983 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
985 BROTLI_LOG_UINT(code
);
988 context_map
[context_index
++] = 0;
991 if (code
> max_run_length_prefix
) {
992 context_map
[context_index
++] =
993 (uint8_t)(code
- max_run_length_prefix
);
999 if (!BrotliSafeReadBits(br
, code
, &reps
)) {
1001 s
->context_index
= context_index
;
1002 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
1005 BROTLI_LOG_UINT(reps
);
1006 if (context_index
+ reps
> context_map_size
) {
1008 BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT
);
1011 context_map
[context_index
++] = 0;
1015 /* No break, continue to next state. */
1017 case BROTLI_STATE_CONTEXT_MAP_TRANSFORM
: {
1019 if (!BrotliSafeReadBits(br
, 1, &bits
)) {
1020 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_TRANSFORM
;
1021 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
1024 InverseMoveToFrontTransform(*context_map_arg
, context_map_size
, s
);
1026 s
->substate_context_map
= BROTLI_STATE_CONTEXT_MAP_NONE
;
1027 return BROTLI_DECODER_SUCCESS
;
1031 BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE
);
1035 /* Decodes a command or literal and updates block type ringbuffer.
1036 Reads 3..54 bits. */
1037 static BROTLI_INLINE BROTLI_BOOL
DecodeBlockTypeAndLength(
1038 int safe
, BrotliDecoderState
* s
, int tree_type
) {
1039 uint32_t max_block_type
= s
->num_block_types
[tree_type
];
1040 const HuffmanCode
* type_tree
= &s
->block_type_trees
[
1041 tree_type
* BROTLI_HUFFMAN_MAX_SIZE_258
];
1042 const HuffmanCode
* len_tree
= &s
->block_len_trees
[
1043 tree_type
* BROTLI_HUFFMAN_MAX_SIZE_26
];
1044 BrotliBitReader
* br
= &s
->br
;
1045 uint32_t* ringbuffer
= &s
->block_type_rb
[tree_type
* 2];
1046 uint32_t block_type
;
1048 /* Read 0..15 + 3..39 bits */
1050 block_type
= ReadSymbol(type_tree
, br
);
1051 s
->block_length
[tree_type
] = ReadBlockLength(len_tree
, br
);
1053 BrotliBitReaderState memento
;
1054 BrotliBitReaderSaveState(br
, &memento
);
1055 if (!SafeReadSymbol(type_tree
, br
, &block_type
)) return BROTLI_FALSE
;
1056 if (!SafeReadBlockLength(s
, &s
->block_length
[tree_type
], len_tree
, br
)) {
1057 s
->substate_read_block_length
= BROTLI_STATE_READ_BLOCK_LENGTH_NONE
;
1058 BrotliBitReaderRestoreState(br
, &memento
);
1059 return BROTLI_FALSE
;
1063 if (block_type
== 1) {
1064 block_type
= ringbuffer
[1] + 1;
1065 } else if (block_type
== 0) {
1066 block_type
= ringbuffer
[0];
1070 if (block_type
>= max_block_type
) {
1071 block_type
-= max_block_type
;
1073 ringbuffer
[0] = ringbuffer
[1];
1074 ringbuffer
[1] = block_type
;
1078 static BROTLI_INLINE
void DetectTrivialLiteralBlockTypes(
1079 BrotliDecoderState
* s
) {
1081 for (i
= 0; i
< 8; ++i
) s
->trivial_literal_contexts
[i
] = 0;
1082 for (i
= 0; i
< s
->num_block_types
[0]; i
++) {
1083 size_t offset
= i
<< BROTLI_LITERAL_CONTEXT_BITS
;
1085 size_t sample
= s
->context_map
[offset
];
1087 for (j
= 0; j
< (1u << BROTLI_LITERAL_CONTEXT_BITS
);) {
1088 BROTLI_REPEAT(4, error
|= s
->context_map
[offset
+ j
++] ^ sample
;)
1091 s
->trivial_literal_contexts
[i
>> 5] |= 1u << (i
& 31);
1096 static BROTLI_INLINE
void PrepareLiteralDecoding(BrotliDecoderState
* s
) {
1097 uint8_t context_mode
;
1099 uint32_t block_type
= s
->block_type_rb
[1];
1100 uint32_t context_offset
= block_type
<< BROTLI_LITERAL_CONTEXT_BITS
;
1101 s
->context_map_slice
= s
->context_map
+ context_offset
;
1102 trivial
= s
->trivial_literal_contexts
[block_type
>> 5];
1103 s
->trivial_literal_context
= (trivial
>> (block_type
& 31)) & 1;
1104 s
->literal_htree
= s
->literal_hgroup
.htrees
[s
->context_map_slice
[0]];
1105 context_mode
= s
->context_modes
[block_type
];
1106 s
->context_lookup1
= &kContextLookup
[kContextLookupOffsets
[context_mode
]];
1107 s
->context_lookup2
= &kContextLookup
[kContextLookupOffsets
[context_mode
+ 1]];
1110 /* Decodes the block type and updates the state for literal context.
1111 Reads 3..54 bits. */
1112 static BROTLI_INLINE BROTLI_BOOL
DecodeLiteralBlockSwitchInternal(
1113 int safe
, BrotliDecoderState
* s
) {
1114 if (!DecodeBlockTypeAndLength(safe
, s
, 0)) {
1115 return BROTLI_FALSE
;
1117 PrepareLiteralDecoding(s
);
1121 static void BROTLI_NOINLINE
DecodeLiteralBlockSwitch(BrotliDecoderState
* s
) {
1122 DecodeLiteralBlockSwitchInternal(0, s
);
1125 static BROTLI_BOOL BROTLI_NOINLINE
SafeDecodeLiteralBlockSwitch(
1126 BrotliDecoderState
* s
) {
1127 return DecodeLiteralBlockSwitchInternal(1, s
);
1130 /* Block switch for insert/copy length.
1131 Reads 3..54 bits. */
1132 static BROTLI_INLINE BROTLI_BOOL
DecodeCommandBlockSwitchInternal(
1133 int safe
, BrotliDecoderState
* s
) {
1134 if (!DecodeBlockTypeAndLength(safe
, s
, 1)) {
1135 return BROTLI_FALSE
;
1137 s
->htree_command
= s
->insert_copy_hgroup
.htrees
[s
->block_type_rb
[3]];
1141 static void BROTLI_NOINLINE
DecodeCommandBlockSwitch(BrotliDecoderState
* s
) {
1142 DecodeCommandBlockSwitchInternal(0, s
);
1144 static BROTLI_BOOL BROTLI_NOINLINE
SafeDecodeCommandBlockSwitch(
1145 BrotliDecoderState
* s
) {
1146 return DecodeCommandBlockSwitchInternal(1, s
);
1149 /* Block switch for distance codes.
1150 Reads 3..54 bits. */
1151 static BROTLI_INLINE BROTLI_BOOL
DecodeDistanceBlockSwitchInternal(
1152 int safe
, BrotliDecoderState
* s
) {
1153 if (!DecodeBlockTypeAndLength(safe
, s
, 2)) {
1154 return BROTLI_FALSE
;
1156 s
->dist_context_map_slice
= s
->dist_context_map
+
1157 (s
->block_type_rb
[5] << BROTLI_DISTANCE_CONTEXT_BITS
);
1158 s
->dist_htree_index
= s
->dist_context_map_slice
[s
->distance_context
];
1162 static void BROTLI_NOINLINE
DecodeDistanceBlockSwitch(BrotliDecoderState
* s
) {
1163 DecodeDistanceBlockSwitchInternal(0, s
);
1166 static BROTLI_BOOL BROTLI_NOINLINE
SafeDecodeDistanceBlockSwitch(
1167 BrotliDecoderState
* s
) {
1168 return DecodeDistanceBlockSwitchInternal(1, s
);
1171 static size_t UnwrittenBytes(const BrotliDecoderState
* s
, BROTLI_BOOL wrap
) {
1172 size_t pos
= wrap
&& s
->pos
> s
->ringbuffer_size
?
1173 (size_t)s
->ringbuffer_size
: (size_t)(s
->pos
);
1174 size_t partial_pos_rb
= (s
->rb_roundtrips
* (size_t)s
->ringbuffer_size
) + pos
;
1175 return partial_pos_rb
- s
->partial_pos_out
;
1178 static BrotliDecoderErrorCode BROTLI_NOINLINE
WriteRingBuffer(
1179 BrotliDecoderState
* s
, size_t* available_out
, uint8_t** next_out
,
1180 size_t* total_out
) {
1182 s
->ringbuffer
+ (s
->partial_pos_out
& (size_t)s
->ringbuffer_mask
);
1183 size_t to_write
= UnwrittenBytes(s
, BROTLI_TRUE
);
1184 size_t num_written
= *available_out
;
1185 if (num_written
> to_write
) {
1186 num_written
= to_write
;
1188 if (s
->meta_block_remaining_len
< 0) {
1189 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1
);
1191 memcpy(*next_out
, start
, num_written
);
1192 *next_out
+= num_written
;
1193 *available_out
-= num_written
;
1194 BROTLI_LOG_UINT(to_write
);
1195 BROTLI_LOG_UINT(num_written
);
1196 s
->partial_pos_out
+= num_written
;
1197 if (total_out
) *total_out
= s
->partial_pos_out
;
1198 if (num_written
< to_write
) {
1199 return BROTLI_DECODER_NEEDS_MORE_OUTPUT
;
1202 if (s
->pos
>= s
->ringbuffer_size
) {
1203 s
->pos
-= s
->ringbuffer_size
;
1206 return BROTLI_DECODER_SUCCESS
;
1209 /* Allocates ringbuffer.
1211 s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
1212 this function is called.
1214 Last two bytes of ringbuffer are initialized to 0, so context calculation
1215 could be done uniformly for the first two and all other positions.
1217 Custom dictionary, if any, is copied to the end of ringbuffer.
1219 static BROTLI_BOOL BROTLI_NOINLINE
BrotliAllocateRingBuffer(
1220 BrotliDecoderState
* s
) {
1221 /* We need the slack region for the following reasons:
1222 - doing up to two 16-byte copies for fast backward copying
1223 - inserting transformed dictionary word (5 prefix + 24 base + 8 suffix) */
1224 static const int kRingBufferWriteAheadSlack
= 42;
1225 s
->ringbuffer
= (uint8_t*)BROTLI_ALLOC(s
, (size_t)(s
->ringbuffer_size
+
1226 kRingBufferWriteAheadSlack
));
1227 if (s
->ringbuffer
== 0) {
1228 return BROTLI_FALSE
;
1231 s
->ringbuffer_end
= s
->ringbuffer
+ s
->ringbuffer_size
;
1233 s
->ringbuffer
[s
->ringbuffer_size
- 2] = 0;
1234 s
->ringbuffer
[s
->ringbuffer_size
- 1] = 0;
1236 if (s
->custom_dict
) {
1237 memcpy(&s
->ringbuffer
[(-s
->custom_dict_size
) & s
->ringbuffer_mask
],
1238 s
->custom_dict
, (size_t)s
->custom_dict_size
);
1244 static BrotliDecoderErrorCode BROTLI_NOINLINE
CopyUncompressedBlockToOutput(
1245 size_t* available_out
, uint8_t** next_out
, size_t* total_out
,
1246 BrotliDecoderState
* s
) {
1247 /* TODO: avoid allocation for single uncompressed block. */
1248 if (!s
->ringbuffer
&& !BrotliAllocateRingBuffer(s
)) {
1249 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1
);
1254 switch (s
->substate_uncompressed
) {
1255 case BROTLI_STATE_UNCOMPRESSED_NONE
: {
1256 int nbytes
= (int)BrotliGetRemainingBytes(&s
->br
);
1257 if (nbytes
> s
->meta_block_remaining_len
) {
1258 nbytes
= s
->meta_block_remaining_len
;
1260 if (s
->pos
+ nbytes
> s
->ringbuffer_size
) {
1261 nbytes
= s
->ringbuffer_size
- s
->pos
;
1263 /* Copy remaining bytes from s->br.buf_ to ringbuffer. */
1264 BrotliCopyBytes(&s
->ringbuffer
[s
->pos
], &s
->br
, (size_t)nbytes
);
1266 s
->meta_block_remaining_len
-= nbytes
;
1267 if (s
->pos
< s
->ringbuffer_size
) {
1268 if (s
->meta_block_remaining_len
== 0) {
1269 return BROTLI_DECODER_SUCCESS
;
1271 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
1273 s
->substate_uncompressed
= BROTLI_STATE_UNCOMPRESSED_WRITE
;
1274 /* No break, continue to next state */
1276 case BROTLI_STATE_UNCOMPRESSED_WRITE
: {
1277 BrotliDecoderErrorCode result
=
1278 WriteRingBuffer(s
, available_out
, next_out
, total_out
);
1279 if (result
!= BROTLI_DECODER_SUCCESS
) {
1282 s
->max_distance
= s
->max_backward_distance
;
1283 s
->substate_uncompressed
= BROTLI_STATE_UNCOMPRESSED_NONE
;
1288 BROTLI_DCHECK(0); /* Unreachable */
1291 BROTLI_BOOL
BrotliDecompressedSize(size_t encoded_size
,
1292 const uint8_t* encoded_buffer
,
1293 size_t* decoded_size
) {
1294 size_t total_size
= 0;
1295 BrotliDecoderState s
;
1296 BrotliBitReader
* br
;
1297 BrotliDecoderStateInit(&s
);
1300 br
->next_in
= encoded_buffer
;
1301 br
->avail_in
= encoded_size
;
1302 if (!BrotliWarmupBitReader(br
)) return BROTLI_FALSE
;
1303 DecodeWindowBits(br
);
1306 if (DecodeMetaBlockLength(&s
, br
) != BROTLI_DECODER_SUCCESS
) {
1307 return BROTLI_FALSE
;
1309 block_size
= (size_t)s
.meta_block_remaining_len
;
1310 if (!s
.is_metadata
) {
1311 if ((block_size
+ total_size
) < total_size
) return BROTLI_FALSE
;
1312 total_size
+= block_size
;
1314 if (s
.is_last_metablock
) {
1315 *decoded_size
= total_size
;
1318 if (!s
.is_uncompressed
&& !s
.is_metadata
) return BROTLI_FALSE
;
1319 if (!BrotliJumpToByteBoundary(br
)) return BROTLI_FALSE
;
1320 BrotliBitReaderUnload(br
);
1321 if (br
->avail_in
< block_size
) return BROTLI_FALSE
;
1322 br
->avail_in
-= block_size
;
1323 br
->next_in
+= block_size
;
1324 if (!BrotliWarmupBitReader(br
)) return BROTLI_FALSE
;
1328 /* Calculates the smallest feasible ring buffer.
1330 If we know the data size is small, do not allocate more ringbuffer
1331 size than needed to reduce memory usage.
1333 When this method is called, metablock size and flags MUST be decoded.
1335 static void BROTLI_NOINLINE
BrotliCalculateRingBufferSize(
1336 BrotliDecoderState
* s
, BrotliBitReader
* br
) {
1337 BROTLI_BOOL is_last
= TO_BROTLI_BOOL(s
->is_last_metablock
);
1338 int window_size
= 1 << s
->window_bits
;
1339 s
->ringbuffer_size
= window_size
;
1341 if (s
->is_uncompressed
) {
1342 int next_block_header
=
1343 BrotliPeekByte(br
, (size_t)s
->meta_block_remaining_len
);
1344 if (next_block_header
!= -1) { /* Peek succeeded */
1345 if ((next_block_header
& 3) == 3) { /* ISLAST and ISEMPTY */
1346 is_last
= BROTLI_TRUE
;
1351 /* We need at least 2 bytes of ring buffer size to get the last two
1352 bytes for context from there */
1354 int min_size_x2
= (s
->meta_block_remaining_len
+ s
->custom_dict_size
) * 2;
1355 while (s
->ringbuffer_size
>= min_size_x2
&& s
->ringbuffer_size
> 32) {
1356 s
->ringbuffer_size
>>= 1;
1360 s
->ringbuffer_mask
= s
->ringbuffer_size
- 1;
1363 /* Reads 1..256 2-bit context modes. */
1364 static BrotliDecoderErrorCode
ReadContextModes(BrotliDecoderState
* s
) {
1365 BrotliBitReader
* br
= &s
->br
;
1366 int i
= s
->loop_counter
;
1368 while (i
< (int)s
->num_block_types
[0]) {
1370 if (!BrotliSafeReadBits(br
, 2, &bits
)) {
1371 s
->loop_counter
= i
;
1372 return BROTLI_DECODER_NEEDS_MORE_INPUT
;
1374 s
->context_modes
[i
] = (uint8_t)(bits
<< 1);
1375 BROTLI_LOG_ARRAY_INDEX(s
->context_modes
, i
);
1378 return BROTLI_DECODER_SUCCESS
;
1381 static BROTLI_INLINE
void TakeDistanceFromRingBuffer(BrotliDecoderState
* s
) {
1382 if (s
->distance_code
== 0) {
1384 s
->distance_code
= s
->dist_rb
[s
->dist_rb_idx
& 3];
1386 int distance_code
= s
->distance_code
<< 1;
1387 /* kDistanceShortCodeIndexOffset has 2-bit values from LSB: */
1388 /* 3, 2, 1, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2 */
1389 const uint32_t kDistanceShortCodeIndexOffset
= 0xaaafff1b;
1390 /* kDistanceShortCodeValueOffset has 2-bit values from LSB: */
1391 /*-0, 0,-0, 0,-1, 1,-2, 2,-3, 3,-1, 1,-2, 2,-3, 3 */
1392 const uint32_t kDistanceShortCodeValueOffset
= 0xfa5fa500;
1393 int v
= (s
->dist_rb_idx
+
1394 (int)(kDistanceShortCodeIndexOffset
>> distance_code
)) & 0x3;
1395 s
->distance_code
= s
->dist_rb
[v
];
1396 v
= (int)(kDistanceShortCodeValueOffset
>> distance_code
) & 0x3;
1397 if ((distance_code
& 0x3) != 0) {
1398 s
->distance_code
+= v
;
1400 s
->distance_code
-= v
;
1401 if (s
->distance_code
<= 0) {
1402 /* A huge distance will cause a BROTLI_FAILURE() soon. */
1403 /* This is a little faster than failing here. */
1404 s
->distance_code
= 0x0fffffff;
1410 static BROTLI_INLINE BROTLI_BOOL
SafeReadBits(
1411 BrotliBitReader
* const br
, uint32_t n_bits
, uint32_t* val
) {
1413 return BrotliSafeReadBits(br
, n_bits
, val
);
1420 /* Precondition: s->distance_code < 0 */
1421 static BROTLI_INLINE BROTLI_BOOL
ReadDistanceInternal(
1422 int safe
, BrotliDecoderState
* s
, BrotliBitReader
* br
) {
1424 BrotliBitReaderState memento
;
1425 HuffmanCode
* distance_tree
= s
->distance_hgroup
.htrees
[s
->dist_htree_index
];
1427 s
->distance_code
= (int)ReadSymbol(distance_tree
, br
);
1430 BrotliBitReaderSaveState(br
, &memento
);
1431 if (!SafeReadSymbol(distance_tree
, br
, &code
)) {
1432 return BROTLI_FALSE
;
1434 s
->distance_code
= (int)code
;
1436 /* Convert the distance code to the actual distance by possibly */
1437 /* looking up past distances from the s->ringbuffer. */
1438 if ((s
->distance_code
& ~0xf) == 0) {
1439 TakeDistanceFromRingBuffer(s
);
1440 --s
->block_length
[2];
1443 distval
= s
->distance_code
- (int)s
->num_direct_distance_codes
;
1448 if (!safe
&& (s
->distance_postfix_bits
== 0)) {
1449 nbits
= ((uint32_t)distval
>> 1) + 1;
1450 offset
= ((2 + (distval
& 1)) << nbits
) - 4;
1451 s
->distance_code
= (int)s
->num_direct_distance_codes
+ offset
+
1452 (int)BrotliReadBits(br
, nbits
);
1454 /* This branch also works well when s->distance_postfix_bits == 0 */
1456 postfix
= distval
& s
->distance_postfix_mask
;
1457 distval
>>= s
->distance_postfix_bits
;
1458 nbits
= ((uint32_t)distval
>> 1) + 1;
1460 if (!SafeReadBits(br
, nbits
, &bits
)) {
1461 s
->distance_code
= -1; /* Restore precondition. */
1462 BrotliBitReaderRestoreState(br
, &memento
);
1463 return BROTLI_FALSE
;
1466 bits
= BrotliReadBits(br
, nbits
);
1468 offset
= ((2 + (distval
& 1)) << nbits
) - 4;
1469 s
->distance_code
= (int)s
->num_direct_distance_codes
+
1470 ((offset
+ (int)bits
) << s
->distance_postfix_bits
) + postfix
;
1473 s
->distance_code
= s
->distance_code
- BROTLI_NUM_DISTANCE_SHORT_CODES
+ 1;
1474 --s
->block_length
[2];
1478 static BROTLI_INLINE
void ReadDistance(
1479 BrotliDecoderState
* s
, BrotliBitReader
* br
) {
1480 ReadDistanceInternal(0, s
, br
);
1483 static BROTLI_INLINE BROTLI_BOOL
SafeReadDistance(
1484 BrotliDecoderState
* s
, BrotliBitReader
* br
) {
1485 return ReadDistanceInternal(1, s
, br
);
1488 static BROTLI_INLINE BROTLI_BOOL
ReadCommandInternal(
1489 int safe
, BrotliDecoderState
* s
, BrotliBitReader
* br
, int* insert_length
) {
1491 uint32_t insert_len_extra
= 0;
1492 uint32_t copy_length
;
1494 BrotliBitReaderState memento
;
1496 cmd_code
= ReadSymbol(s
->htree_command
, br
);
1498 BrotliBitReaderSaveState(br
, &memento
);
1499 if (!SafeReadSymbol(s
->htree_command
, br
, &cmd_code
)) {
1500 return BROTLI_FALSE
;
1503 if (cmd_code
>= BROTLI_NUM_COMMAND_SYMBOLS
) cmd_code
= BROTLI_NUM_COMMAND_SYMBOLS
- 1;
1504 v
= kCmdLut
[cmd_code
];
1505 s
->distance_code
= v
.distance_code
;
1506 s
->distance_context
= v
.context
;
1507 s
->dist_htree_index
= s
->dist_context_map_slice
[s
->distance_context
];
1508 *insert_length
= v
.insert_len_offset
;
1510 if (PREDICT_FALSE(v
.insert_len_extra_bits
!= 0)) {
1511 insert_len_extra
= BrotliReadBits(br
, v
.insert_len_extra_bits
);
1513 copy_length
= BrotliReadBits(br
, v
.copy_len_extra_bits
);
1515 if (!SafeReadBits(br
, v
.insert_len_extra_bits
, &insert_len_extra
) ||
1516 !SafeReadBits(br
, v
.copy_len_extra_bits
, ©_length
)) {
1517 BrotliBitReaderRestoreState(br
, &memento
);
1518 return BROTLI_FALSE
;
1521 s
->copy_length
= (int)copy_length
+ v
.copy_len_offset
;
1522 --s
->block_length
[1];
1523 *insert_length
+= (int)insert_len_extra
;
1527 static BROTLI_INLINE
void ReadCommand(
1528 BrotliDecoderState
* s
, BrotliBitReader
* br
, int* insert_length
) {
1529 ReadCommandInternal(0, s
, br
, insert_length
);
1532 static BROTLI_INLINE BROTLI_BOOL
SafeReadCommand(
1533 BrotliDecoderState
* s
, BrotliBitReader
* br
, int* insert_length
) {
1534 return ReadCommandInternal(1, s
, br
, insert_length
);
1537 static BROTLI_INLINE BROTLI_BOOL
CheckInputAmount(
1538 int safe
, BrotliBitReader
* const br
, size_t num
) {
1542 return BrotliCheckInputAmount(br
, num
);
1545 #define BROTLI_SAFE(METHOD) \
1548 if (!Safe##METHOD) { \
1549 result = BROTLI_DECODER_NEEDS_MORE_INPUT; \
1550 goto saveStateAndReturn; \
1557 static BROTLI_INLINE BrotliDecoderErrorCode
ProcessCommandsInternal(
1558 int safe
, BrotliDecoderState
* s
) {
1560 int i
= s
->loop_counter
;
1561 BrotliDecoderErrorCode result
= BROTLI_DECODER_SUCCESS
;
1562 BrotliBitReader
* br
= &s
->br
;
1564 if (!CheckInputAmount(safe
, br
, 28)) {
1565 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1566 goto saveStateAndReturn
;
1569 BROTLI_UNUSED(BrotliWarmupBitReader(br
));
1572 /* Jump into state machine. */
1573 if (s
->state
== BROTLI_STATE_COMMAND_BEGIN
) {
1575 } else if (s
->state
== BROTLI_STATE_COMMAND_INNER
) {
1577 } else if (s
->state
== BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
) {
1578 goto CommandPostDecodeLiterals
;
1579 } else if (s
->state
== BROTLI_STATE_COMMAND_POST_WRAP_COPY
) {
1580 goto CommandPostWrapCopy
;
1582 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE
);
1587 s
->state
= BROTLI_STATE_COMMAND_BEGIN
;
1589 if (!CheckInputAmount(safe
, br
, 28)) { /* 156 bits + 7 bytes */
1590 s
->state
= BROTLI_STATE_COMMAND_BEGIN
;
1591 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1592 goto saveStateAndReturn
;
1594 if (PREDICT_FALSE(s
->block_length
[1] == 0)) {
1595 BROTLI_SAFE(DecodeCommandBlockSwitch(s
));
1598 /* Read the insert/copy length in the command */
1599 BROTLI_SAFE(ReadCommand(s
, br
, &i
));
1600 BROTLI_LOG(("[ProcessCommandsInternal] pos = %d insert = %d copy = %d\n",
1601 pos
, i
, s
->copy_length
));
1603 goto CommandPostDecodeLiterals
;
1605 s
->meta_block_remaining_len
-= i
;
1609 s
->state
= BROTLI_STATE_COMMAND_INNER
;
1611 /* Read the literals in the command */
1612 if (s
->trivial_literal_context
) {
1615 PreloadSymbol(safe
, s
->literal_htree
, br
, &bits
, &value
);
1617 if (!CheckInputAmount(safe
, br
, 28)) { /* 162 bits + 7 bytes */
1618 s
->state
= BROTLI_STATE_COMMAND_INNER
;
1619 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1620 goto saveStateAndReturn
;
1622 if (PREDICT_FALSE(s
->block_length
[0] == 0)) {
1623 BROTLI_SAFE(DecodeLiteralBlockSwitch(s
));
1624 PreloadSymbol(safe
, s
->literal_htree
, br
, &bits
, &value
);
1625 if (!s
->trivial_literal_context
) goto CommandInner
;
1628 s
->ringbuffer
[pos
] =
1629 (uint8_t)ReadPreloadedSymbol(s
->literal_htree
, br
, &bits
, &value
);
1632 if (!SafeReadSymbol(s
->literal_htree
, br
, &literal
)) {
1633 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1634 goto saveStateAndReturn
;
1636 s
->ringbuffer
[pos
] = (uint8_t)literal
;
1638 --s
->block_length
[0];
1639 BROTLI_LOG_ARRAY_INDEX(s
->ringbuffer
, pos
);
1641 if (PREDICT_FALSE(pos
== s
->ringbuffer_size
)) {
1642 s
->state
= BROTLI_STATE_COMMAND_INNER_WRITE
;
1644 goto saveStateAndReturn
;
1648 uint8_t p1
= s
->ringbuffer
[(pos
- 1) & s
->ringbuffer_mask
];
1649 uint8_t p2
= s
->ringbuffer
[(pos
- 2) & s
->ringbuffer_mask
];
1651 const HuffmanCode
* hc
;
1653 if (!CheckInputAmount(safe
, br
, 28)) { /* 162 bits + 7 bytes */
1654 s
->state
= BROTLI_STATE_COMMAND_INNER
;
1655 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1656 goto saveStateAndReturn
;
1658 if (PREDICT_FALSE(s
->block_length
[0] == 0)) {
1659 BROTLI_SAFE(DecodeLiteralBlockSwitch(s
));
1660 if (s
->trivial_literal_context
) goto CommandInner
;
1662 context
= s
->context_lookup1
[p1
] | s
->context_lookup2
[p2
];
1663 BROTLI_LOG_UINT(context
);
1664 hc
= s
->literal_hgroup
.htrees
[s
->context_map_slice
[context
]];
1667 p1
= (uint8_t)ReadSymbol(hc
, br
);
1670 if (!SafeReadSymbol(hc
, br
, &literal
)) {
1671 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1672 goto saveStateAndReturn
;
1674 p1
= (uint8_t)literal
;
1676 s
->ringbuffer
[pos
] = p1
;
1677 --s
->block_length
[0];
1678 BROTLI_LOG_UINT(s
->context_map_slice
[context
]);
1679 BROTLI_LOG_ARRAY_INDEX(s
->ringbuffer
, pos
& s
->ringbuffer_mask
);
1681 if (PREDICT_FALSE(pos
== s
->ringbuffer_size
)) {
1682 s
->state
= BROTLI_STATE_COMMAND_INNER_WRITE
;
1684 goto saveStateAndReturn
;
1688 BROTLI_LOG_UINT(s
->meta_block_remaining_len
);
1689 if (PREDICT_FALSE(s
->meta_block_remaining_len
<= 0)) {
1690 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
1691 goto saveStateAndReturn
;
1694 CommandPostDecodeLiterals
:
1696 s
->state
= BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
;
1698 if (s
->distance_code
>= 0) {
1700 s
->distance_code
= s
->dist_rb
[s
->dist_rb_idx
& 3];
1701 goto postReadDistance
; /* We already have the implicit distance */
1703 /* Read distance code in the command, unless it was implicitly zero. */
1704 if (PREDICT_FALSE(s
->block_length
[2] == 0)) {
1705 BROTLI_SAFE(DecodeDistanceBlockSwitch(s
));
1707 BROTLI_SAFE(ReadDistance(s
, br
));
1709 BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n",
1710 pos
, s
->distance_code
));
1711 if (s
->max_distance
!= s
->max_backward_distance
) {
1712 if (pos
< s
->max_backward_distance_minus_custom_dict_size
) {
1713 s
->max_distance
= pos
+ s
->custom_dict_size
;
1715 s
->max_distance
= s
->max_backward_distance
;
1719 /* Apply copy of LZ77 back-reference, or static dictionary reference if
1720 the distance is larger than the max LZ77 distance */
1721 if (s
->distance_code
> s
->max_distance
) {
1722 if (i
>= kBrotliMinDictionaryWordLength
&&
1723 i
<= kBrotliMaxDictionaryWordLength
) {
1724 int offset
= (int)kBrotliDictionaryOffsetsByLength
[i
];
1725 int word_id
= s
->distance_code
- s
->max_distance
- 1;
1726 uint32_t shift
= kBrotliDictionarySizeBitsByLength
[i
];
1727 int mask
= (int)BitMask(shift
);
1728 int word_idx
= word_id
& mask
;
1729 int transform_idx
= word_id
>> shift
;
1730 offset
+= word_idx
* i
;
1731 if (transform_idx
< kNumTransforms
) {
1732 const uint8_t* word
= &kBrotliDictionary
[offset
];
1734 if (transform_idx
== 0) {
1735 memcpy(&s
->ringbuffer
[pos
], word
, (size_t)len
);
1737 len
= TransformDictionaryWord(
1738 &s
->ringbuffer
[pos
], word
, len
, transform_idx
);
1741 s
->meta_block_remaining_len
-= len
;
1742 if (pos
>= s
->ringbuffer_size
) {
1743 /*s->partial_pos_rb += (size_t)s->ringbuffer_size;*/
1744 s
->state
= BROTLI_STATE_COMMAND_POST_WRITE_1
;
1745 goto saveStateAndReturn
;
1748 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
1749 "len: %d bytes left: %d\n",
1750 pos
, s
->distance_code
, i
, s
->meta_block_remaining_len
));
1751 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM
);
1754 BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
1755 "len: %d bytes left: %d\n",
1756 pos
, s
->distance_code
, i
, s
->meta_block_remaining_len
));
1757 return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY
);
1760 int src_start
= (pos
- s
->distance_code
) & s
->ringbuffer_mask
;
1761 uint8_t* copy_dst
= &s
->ringbuffer
[pos
];
1762 uint8_t* copy_src
= &s
->ringbuffer
[src_start
];
1763 int dst_end
= pos
+ i
;
1764 int src_end
= src_start
+ i
;
1765 /* update the recent distances cache */
1766 s
->dist_rb
[s
->dist_rb_idx
& 3] = s
->distance_code
;
1768 s
->meta_block_remaining_len
-= i
;
1769 /* There are 32+ bytes of slack in the ringbuffer allocation.
1770 Also, we have 16 short codes, that make these 16 bytes irrelevant
1771 in the ringbuffer. Let's copy over them as a first guess.
1773 memmove16(copy_dst
, copy_src
);
1774 if (src_end
> pos
&& dst_end
> src_start
) {
1775 /* Regions intersect. */
1776 goto CommandPostWrapCopy
;
1778 if (dst_end
>= s
->ringbuffer_size
|| src_end
>= s
->ringbuffer_size
) {
1779 /* At least one region wraps. */
1780 goto CommandPostWrapCopy
;
1785 memcpy(copy_dst
+ 16, copy_src
+ 16, (size_t)(i
- 16));
1787 /* This branch covers about 45% cases.
1788 Fixed size short copy allows more compiler optimizations. */
1789 memmove16(copy_dst
+ 16, copy_src
+ 16);
1793 BROTLI_LOG_UINT(s
->meta_block_remaining_len
);
1794 if (s
->meta_block_remaining_len
<= 0) {
1795 /* Next metablock, if any */
1796 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
1797 goto saveStateAndReturn
;
1801 CommandPostWrapCopy
:
1803 int wrap_guard
= s
->ringbuffer_size
- pos
;
1805 s
->ringbuffer
[pos
] =
1806 s
->ringbuffer
[(pos
- s
->distance_code
) & s
->ringbuffer_mask
];
1808 if (PREDICT_FALSE(--wrap_guard
== 0)) {
1809 s
->state
= BROTLI_STATE_COMMAND_POST_WRITE_2
;
1810 goto saveStateAndReturn
;
1814 if (s
->meta_block_remaining_len
<= 0) {
1815 /* Next metablock, if any */
1816 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
1817 goto saveStateAndReturn
;
1824 s
->loop_counter
= i
;
1830 static BROTLI_NOINLINE BrotliDecoderErrorCode
ProcessCommands(
1831 BrotliDecoderState
* s
) {
1832 return ProcessCommandsInternal(0, s
);
1835 static BROTLI_NOINLINE BrotliDecoderErrorCode
SafeProcessCommands(
1836 BrotliDecoderState
* s
) {
1837 return ProcessCommandsInternal(1, s
);
1840 BrotliDecoderResult
BrotliDecoderDecompress(
1841 size_t encoded_size
, const uint8_t* encoded_buffer
, size_t* decoded_size
,
1842 uint8_t* decoded_buffer
) {
1843 BrotliDecoderState s
;
1844 BrotliDecoderResult result
;
1845 size_t total_out
= 0;
1846 size_t available_in
= encoded_size
;
1847 const uint8_t* next_in
= encoded_buffer
;
1848 size_t available_out
= *decoded_size
;
1849 uint8_t* next_out
= decoded_buffer
;
1850 BrotliDecoderStateInit(&s
);
1851 result
= BrotliDecoderDecompressStream(
1852 &s
, &available_in
, &next_in
, &available_out
, &next_out
, &total_out
);
1853 *decoded_size
= total_out
;
1854 BrotliDecoderStateCleanup(&s
);
1855 if (result
!= BROTLI_DECODER_RESULT_SUCCESS
) {
1856 result
= BROTLI_DECODER_RESULT_ERROR
;
1861 /* Invariant: input stream is never overconsumed:
1862 * invalid input implies that the whole stream is invalid -> any amount of
1863 input could be read and discarded
1864 * when result is "needs more input", then at leat one more byte is REQUIRED
1865 to complete decoding; all input data MUST be consumed by decoder, so
1866 client could swap the input buffer
1867 * when result is "needs more output" decoder MUST ensure that it doesn't
1868 hold more than 7 bits in bit reader; this saves client from swapping input
1869 buffer ahead of time
1870 * when result is "success" decoder MUST return all unused data back to input
1871 buffer; this is possible because the invariant is hold on enter
1873 BrotliDecoderResult
BrotliDecoderDecompressStream(
1874 BrotliDecoderState
* s
, size_t* available_in
, const uint8_t** next_in
,
1875 size_t* available_out
, uint8_t** next_out
, size_t* total_out
) {
1876 BrotliDecoderErrorCode result
= BROTLI_DECODER_SUCCESS
;
1877 BrotliBitReader
* br
= &s
->br
;
1878 if (s
->buffer_length
== 0) { /* Just connect bit reader to input stream. */
1879 br
->avail_in
= *available_in
;
1880 br
->next_in
= *next_in
;
1882 /* At least one byte of input is required. More than one byte of input may
1883 be required to complete the transaction -> reading more data must be
1884 done in a loop -> do it in a main loop. */
1885 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1886 br
->next_in
= &s
->buffer
.u8
[0];
1890 if (result
!= BROTLI_DECODER_SUCCESS
) { /* Error, needs more input/output */
1891 if (result
== BROTLI_DECODER_NEEDS_MORE_INPUT
) {
1892 if (s
->ringbuffer
!= 0) { /* Proactively push output. */
1893 WriteRingBuffer(s
, available_out
, next_out
, total_out
);
1895 if (s
->buffer_length
!= 0) { /* Used with internal buffer. */
1896 if (br
->avail_in
== 0) { /* Successfully finished read transaction. */
1897 /* Accamulator contains less than 8 bits, because internal buffer
1898 is expanded byte-by-byte until it is enough to complete read. */
1899 s
->buffer_length
= 0;
1900 /* Switch to input stream and restart. */
1901 result
= BROTLI_DECODER_SUCCESS
;
1902 br
->avail_in
= *available_in
;
1903 br
->next_in
= *next_in
;
1905 } else if (*available_in
!= 0) {
1906 /* Not enough data in buffer, but can take one more byte from
1908 result
= BROTLI_DECODER_SUCCESS
;
1909 s
->buffer
.u8
[s
->buffer_length
] = **next_in
;
1911 br
->avail_in
= s
->buffer_length
;
1914 /* Retry with more data in buffer. */
1917 /* Can't finish reading and no more input.*/
1919 } else { /* Input stream doesn't contain enough input. */
1920 /* Copy tail to internal buffer and return. */
1921 *next_in
= br
->next_in
;
1922 *available_in
= br
->avail_in
;
1923 while (*available_in
) {
1924 s
->buffer
.u8
[s
->buffer_length
] = **next_in
;
1934 /* Fail or needs more output. */
1936 if (s
->buffer_length
!= 0) {
1937 /* Just consumed the buffered input and produced some output. Otherwise
1938 it would result in "needs more input". Reset internal buffer.*/
1939 s
->buffer_length
= 0;
1941 /* Using input stream in last iteration. When decoder switches to input
1942 stream it has less than 8 bits in accamulator, so it is safe to
1943 return unused accamulator bits there. */
1944 BrotliBitReaderUnload(br
);
1945 *available_in
= br
->avail_in
;
1946 *next_in
= br
->next_in
;
1951 case BROTLI_STATE_UNINITED
:
1952 /* Prepare to the first read. */
1953 if (!BrotliWarmupBitReader(br
)) {
1954 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
1957 /* Decode window size. */
1958 s
->window_bits
= DecodeWindowBits(br
); /* Reads 1..7 bits. */
1959 BROTLI_LOG_UINT(s
->window_bits
);
1960 if (s
->window_bits
== 9) {
1961 /* Value 9 is reserved for future use. */
1962 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS
);
1965 /* Maximum distance, see section 9.1. of the spec. */
1966 s
->max_backward_distance
= (1 << s
->window_bits
) - 16;
1967 /* Limit custom dictionary size. */
1968 if (s
->custom_dict_size
>= s
->max_backward_distance
) {
1969 s
->custom_dict
+= s
->custom_dict_size
- s
->max_backward_distance
;
1970 s
->custom_dict_size
= s
->max_backward_distance
;
1972 s
->max_backward_distance_minus_custom_dict_size
=
1973 s
->max_backward_distance
- s
->custom_dict_size
;
1975 /* Allocate memory for both block_type_trees and block_len_trees. */
1976 s
->block_type_trees
= (HuffmanCode
*)BROTLI_ALLOC(s
,
1977 sizeof(HuffmanCode
) * 3 *
1978 (BROTLI_HUFFMAN_MAX_SIZE_258
+ BROTLI_HUFFMAN_MAX_SIZE_26
));
1979 if (s
->block_type_trees
== 0) {
1980 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES
);
1983 s
->block_len_trees
=
1984 s
->block_type_trees
+ 3 * BROTLI_HUFFMAN_MAX_SIZE_258
;
1986 s
->state
= BROTLI_STATE_METABLOCK_BEGIN
;
1987 /* No break, continue to next state */
1988 case BROTLI_STATE_METABLOCK_BEGIN
:
1989 BrotliDecoderStateMetablockBegin(s
);
1990 BROTLI_LOG_UINT(s
->pos
);
1991 s
->state
= BROTLI_STATE_METABLOCK_HEADER
;
1992 /* No break, continue to next state */
1993 case BROTLI_STATE_METABLOCK_HEADER
:
1994 result
= DecodeMetaBlockLength(s
, br
); /* Reads 2 - 31 bits. */
1995 if (result
!= BROTLI_DECODER_SUCCESS
) {
1998 BROTLI_LOG_UINT(s
->is_last_metablock
);
1999 BROTLI_LOG_UINT(s
->meta_block_remaining_len
);
2000 BROTLI_LOG_UINT(s
->is_metadata
);
2001 BROTLI_LOG_UINT(s
->is_uncompressed
);
2002 if (s
->is_metadata
|| s
->is_uncompressed
) {
2003 if (!BrotliJumpToByteBoundary(br
)) {
2004 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1
);
2008 if (s
->is_metadata
) {
2009 s
->state
= BROTLI_STATE_METADATA
;
2012 if (s
->meta_block_remaining_len
== 0) {
2013 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2016 if (!s
->ringbuffer
) {
2017 BrotliCalculateRingBufferSize(s
, br
);
2019 if (s
->is_uncompressed
) {
2020 s
->state
= BROTLI_STATE_UNCOMPRESSED
;
2023 s
->loop_counter
= 0;
2024 s
->state
= BROTLI_STATE_HUFFMAN_CODE_0
;
2026 case BROTLI_STATE_UNCOMPRESSED
: {
2027 int bytes_copied
= s
->meta_block_remaining_len
;
2028 result
= CopyUncompressedBlockToOutput(
2029 available_out
, next_out
, total_out
, s
);
2030 bytes_copied
-= s
->meta_block_remaining_len
;
2031 if (result
!= BROTLI_DECODER_SUCCESS
) {
2034 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2037 case BROTLI_STATE_METADATA
:
2038 for (; s
->meta_block_remaining_len
> 0; --s
->meta_block_remaining_len
) {
2040 /* Read one byte and ignore it. */
2041 if (!BrotliSafeReadBits(br
, 8, &bits
)) {
2042 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
2046 if (result
== BROTLI_DECODER_SUCCESS
) {
2047 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2050 case BROTLI_STATE_HUFFMAN_CODE_0
:
2051 if (s
->loop_counter
>= 3) {
2052 s
->state
= BROTLI_STATE_METABLOCK_HEADER_2
;
2055 /* Reads 1..11 bits. */
2056 result
= DecodeVarLenUint8(s
, br
, &s
->num_block_types
[s
->loop_counter
]);
2057 if (result
!= BROTLI_DECODER_SUCCESS
) {
2060 s
->num_block_types
[s
->loop_counter
]++;
2061 BROTLI_LOG_UINT(s
->num_block_types
[s
->loop_counter
]);
2062 if (s
->num_block_types
[s
->loop_counter
] < 2) {
2066 s
->state
= BROTLI_STATE_HUFFMAN_CODE_1
;
2067 /* No break, continue to next state */
2068 case BROTLI_STATE_HUFFMAN_CODE_1
: {
2069 int tree_offset
= s
->loop_counter
* BROTLI_HUFFMAN_MAX_SIZE_258
;
2070 result
= ReadHuffmanCode(s
->num_block_types
[s
->loop_counter
] + 2,
2071 &s
->block_type_trees
[tree_offset
], NULL
, s
);
2072 if (result
!= BROTLI_DECODER_SUCCESS
) break;
2073 s
->state
= BROTLI_STATE_HUFFMAN_CODE_2
;
2074 /* No break, continue to next state */
2076 case BROTLI_STATE_HUFFMAN_CODE_2
: {
2077 int tree_offset
= s
->loop_counter
* BROTLI_HUFFMAN_MAX_SIZE_26
;
2078 result
= ReadHuffmanCode(BROTLI_NUM_BLOCK_LEN_SYMBOLS
,
2079 &s
->block_len_trees
[tree_offset
], NULL
, s
);
2080 if (result
!= BROTLI_DECODER_SUCCESS
) break;
2081 s
->state
= BROTLI_STATE_HUFFMAN_CODE_3
;
2082 /* No break, continue to next state */
2084 case BROTLI_STATE_HUFFMAN_CODE_3
: {
2085 int tree_offset
= s
->loop_counter
* BROTLI_HUFFMAN_MAX_SIZE_26
;
2086 if (!SafeReadBlockLength(s
, &s
->block_length
[s
->loop_counter
],
2087 &s
->block_len_trees
[tree_offset
], br
)) {
2088 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
2091 BROTLI_LOG_UINT(s
->block_length
[s
->loop_counter
]);
2093 s
->state
= BROTLI_STATE_HUFFMAN_CODE_0
;
2096 case BROTLI_STATE_METABLOCK_HEADER_2
: {
2098 if (!BrotliSafeReadBits(br
, 6, &bits
)) {
2099 result
= BROTLI_DECODER_NEEDS_MORE_INPUT
;
2102 s
->distance_postfix_bits
= bits
& BitMask(2);
2104 s
->num_direct_distance_codes
= BROTLI_NUM_DISTANCE_SHORT_CODES
+
2105 (bits
<< s
->distance_postfix_bits
);
2106 BROTLI_LOG_UINT(s
->num_direct_distance_codes
);
2107 BROTLI_LOG_UINT(s
->distance_postfix_bits
);
2108 s
->distance_postfix_mask
= (int)BitMask(s
->distance_postfix_bits
);
2110 (uint8_t*)BROTLI_ALLOC(s
, (size_t)s
->num_block_types
[0]);
2111 if (s
->context_modes
== 0) {
2112 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES
);
2115 s
->loop_counter
= 0;
2116 s
->state
= BROTLI_STATE_CONTEXT_MODES
;
2117 /* No break, continue to next state */
2119 case BROTLI_STATE_CONTEXT_MODES
:
2120 result
= ReadContextModes(s
);
2121 if (result
!= BROTLI_DECODER_SUCCESS
) {
2124 s
->state
= BROTLI_STATE_CONTEXT_MAP_1
;
2125 /* No break, continue to next state */
2126 case BROTLI_STATE_CONTEXT_MAP_1
:
2127 result
= DecodeContextMap(
2128 s
->num_block_types
[0] << BROTLI_LITERAL_CONTEXT_BITS
,
2129 &s
->num_literal_htrees
, &s
->context_map
, s
);
2130 if (result
!= BROTLI_DECODER_SUCCESS
) {
2133 DetectTrivialLiteralBlockTypes(s
);
2134 s
->state
= BROTLI_STATE_CONTEXT_MAP_2
;
2135 /* No break, continue to next state */
2136 case BROTLI_STATE_CONTEXT_MAP_2
:
2138 uint32_t num_distance_codes
=
2139 s
->num_direct_distance_codes
+ (48U << s
->distance_postfix_bits
);
2140 result
= DecodeContextMap(
2141 s
->num_block_types
[2] << BROTLI_DISTANCE_CONTEXT_BITS
,
2142 &s
->num_dist_htrees
, &s
->dist_context_map
, s
);
2143 if (result
!= BROTLI_DECODER_SUCCESS
) {
2146 BrotliDecoderHuffmanTreeGroupInit(
2147 s
, &s
->literal_hgroup
, BROTLI_NUM_LITERAL_SYMBOLS
,
2148 s
->num_literal_htrees
);
2149 BrotliDecoderHuffmanTreeGroupInit(
2150 s
, &s
->insert_copy_hgroup
, BROTLI_NUM_COMMAND_SYMBOLS
,
2151 s
->num_block_types
[1]);
2152 BrotliDecoderHuffmanTreeGroupInit(
2153 s
, &s
->distance_hgroup
, num_distance_codes
,
2154 s
->num_dist_htrees
);
2155 if (s
->literal_hgroup
.codes
== 0 ||
2156 s
->insert_copy_hgroup
.codes
== 0 ||
2157 s
->distance_hgroup
.codes
== 0) {
2158 return SaveErrorCode(s
,
2159 BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS
));
2162 s
->loop_counter
= 0;
2163 s
->state
= BROTLI_STATE_TREE_GROUP
;
2164 /* No break, continue to next state */
2165 case BROTLI_STATE_TREE_GROUP
:
2167 HuffmanTreeGroup
* hgroup
= NULL
;
2168 switch (s
->loop_counter
) {
2170 hgroup
= &s
->literal_hgroup
;
2173 hgroup
= &s
->insert_copy_hgroup
;
2176 hgroup
= &s
->distance_hgroup
;
2179 return SaveErrorCode(s
, BROTLI_FAILURE(
2180 BROTLI_DECODER_ERROR_UNREACHABLE
));
2182 result
= HuffmanTreeGroupDecode(hgroup
, s
);
2184 if (result
!= BROTLI_DECODER_SUCCESS
) break;
2186 if (s
->loop_counter
>= 3) {
2187 PrepareLiteralDecoding(s
);
2188 s
->dist_context_map_slice
= s
->dist_context_map
;
2189 s
->htree_command
= s
->insert_copy_hgroup
.htrees
[0];
2190 if (!s
->ringbuffer
&& !BrotliAllocateRingBuffer(s
)) {
2191 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2
);
2194 s
->state
= BROTLI_STATE_COMMAND_BEGIN
;
2197 case BROTLI_STATE_COMMAND_BEGIN
:
2198 case BROTLI_STATE_COMMAND_INNER
:
2199 case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
:
2200 case BROTLI_STATE_COMMAND_POST_WRAP_COPY
:
2201 result
= ProcessCommands(s
);
2202 if (result
== BROTLI_DECODER_NEEDS_MORE_INPUT
) {
2203 result
= SafeProcessCommands(s
);
2206 case BROTLI_STATE_COMMAND_INNER_WRITE
:
2207 case BROTLI_STATE_COMMAND_POST_WRITE_1
:
2208 case BROTLI_STATE_COMMAND_POST_WRITE_2
:
2209 result
= WriteRingBuffer(s
, available_out
, next_out
, total_out
);
2210 if (result
!= BROTLI_DECODER_SUCCESS
) {
2213 s
->max_distance
= s
->max_backward_distance
;
2214 if (s
->state
== BROTLI_STATE_COMMAND_POST_WRITE_1
) {
2215 if (s
->ringbuffer
!= 0) {
2216 memcpy(s
->ringbuffer
, s
->ringbuffer_end
, (size_t)s
->pos
);
2218 if (s
->meta_block_remaining_len
== 0) {
2219 /* Next metablock, if any */
2220 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2222 s
->state
= BROTLI_STATE_COMMAND_BEGIN
;
2225 } else if (s
->state
== BROTLI_STATE_COMMAND_POST_WRITE_2
) {
2226 s
->state
= BROTLI_STATE_COMMAND_POST_WRAP_COPY
;
2227 } else { /* BROTLI_STATE_COMMAND_INNER_WRITE */
2228 if (s
->loop_counter
== 0) {
2229 if (s
->meta_block_remaining_len
== 0) {
2230 s
->state
= BROTLI_STATE_METABLOCK_DONE
;
2232 s
->state
= BROTLI_STATE_COMMAND_POST_DECODE_LITERALS
;
2236 s
->state
= BROTLI_STATE_COMMAND_INNER
;
2239 case BROTLI_STATE_METABLOCK_DONE
:
2240 if (s
->meta_block_remaining_len
< 0) {
2241 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2
);
2244 BrotliDecoderStateCleanupAfterMetablock(s
);
2245 if (!s
->is_last_metablock
) {
2246 s
->state
= BROTLI_STATE_METABLOCK_BEGIN
;
2249 if (!BrotliJumpToByteBoundary(br
)) {
2250 result
= BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2
);
2253 if (s
->buffer_length
== 0) {
2254 BrotliBitReaderUnload(br
);
2255 *available_in
= br
->avail_in
;
2256 *next_in
= br
->next_in
;
2258 s
->state
= BROTLI_STATE_DONE
;
2259 /* No break, continue to next state */
2260 case BROTLI_STATE_DONE
:
2261 if (s
->ringbuffer
!= 0) {
2262 result
= WriteRingBuffer(s
, available_out
, next_out
, total_out
);
2263 if (result
!= BROTLI_DECODER_SUCCESS
) {
2267 return SaveErrorCode(s
, result
);
2270 return SaveErrorCode(s
, result
);
2273 void BrotliDecoderSetCustomDictionary(
2274 BrotliDecoderState
* s
, size_t size
, const uint8_t* dict
) {
2275 if (size
> (1u << 24)) {
2278 s
->custom_dict
= dict
;
2279 s
->custom_dict_size
= (int)size
;
2282 BROTLI_BOOL
BrotliDecoderHasMoreOutput(const BrotliDecoderState
* s
) {
2283 return TO_BROTLI_BOOL(
2284 s
->ringbuffer
!= 0 && UnwrittenBytes(s
, BROTLI_FALSE
) != 0);
2287 BROTLI_BOOL
BrotliDecoderIsUsed(const BrotliDecoderState
* s
) {
2288 return TO_BROTLI_BOOL(s
->state
!= BROTLI_STATE_UNINITED
||
2289 BrotliGetAvailableBits(&s
->br
) != 0);
2292 BROTLI_BOOL
BrotliDecoderIsFinished(const BrotliDecoderState
* s
) {
2293 return TO_BROTLI_BOOL(s
->state
== BROTLI_STATE_DONE
);
2296 BrotliDecoderErrorCode
BrotliDecoderGetErrorCode(const BrotliDecoderState
* s
) {
2297 return (BrotliDecoderErrorCode
)s
->error_code
;
2300 const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c
) {
2302 #define _BROTLI_ERROR_CODE_CASE(PREFIX, NAME, CODE) \
2303 case BROTLI_DECODER ## PREFIX ## NAME: return #NAME;
2304 #define _BROTLI_NOTHING
2305 BROTLI_DECODER_ERROR_CODES_LIST(_BROTLI_ERROR_CODE_CASE
, _BROTLI_NOTHING
)
2306 #undef _BROTLI_ERROR_CODE_CASE
2307 #undef _BROTLI_NOTHING
2308 default: return "INVALID";
2312 /* DEPRECATED >>> */
2313 BrotliState
* BrotliCreateState(
2314 brotli_alloc_func alloc
, brotli_free_func free
, void* opaque
) {
2315 return (BrotliState
*)BrotliDecoderCreateInstance(alloc
, free
, opaque
);
2317 void BrotliDestroyState(BrotliState
* state
) {
2318 BrotliDecoderDestroyInstance((BrotliDecoderState
*)state
);
2320 BrotliResult
BrotliDecompressBuffer(
2321 size_t encoded_size
, const uint8_t* encoded_buffer
, size_t* decoded_size
,
2322 uint8_t* decoded_buffer
) {
2323 return (BrotliResult
)BrotliDecoderDecompress(
2324 encoded_size
, encoded_buffer
, decoded_size
, decoded_buffer
);
2326 BrotliResult
BrotliDecompressStream(
2327 size_t* available_in
, const uint8_t** next_in
, size_t* available_out
,
2328 uint8_t** next_out
, size_t* total_out
, BrotliState
* s
) {
2329 return (BrotliResult
)BrotliDecoderDecompressStream((BrotliDecoderState
*)s
,
2330 available_in
, next_in
, available_out
, next_out
, total_out
);
2332 void BrotliSetCustomDictionary(
2333 size_t size
, const uint8_t* dict
, BrotliState
* s
) {
2334 BrotliDecoderSetCustomDictionary((BrotliDecoderState
*)s
, size
, dict
);
2336 BROTLI_BOOL
BrotliStateIsStreamStart(const BrotliState
* s
) {
2337 return !BrotliDecoderIsUsed((const BrotliDecoderState
*)s
);
2339 BROTLI_BOOL
BrotliStateIsStreamEnd(const BrotliState
* s
) {
2340 return BrotliDecoderIsFinished((const BrotliDecoderState
*)s
);
2342 BrotliErrorCode
BrotliGetErrorCode(const BrotliState
* s
) {
2343 return (BrotliErrorCode
)BrotliDecoderGetErrorCode(
2344 (const BrotliDecoderState
*)s
);
2346 const char* BrotliErrorString(BrotliErrorCode c
) {
2347 return BrotliDecoderErrorString((BrotliDecoderErrorCode
)c
);
2349 /* <<< DEPRECATED */
2351 #if defined(__cplusplus) || defined(c_plusplus)