126fa459cSmrg/* Copyright 2013 Google Inc. All Rights Reserved.
226fa459cSmrg
326fa459cSmrg   Distributed under MIT license.
426fa459cSmrg   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
526fa459cSmrg*/
626fa459cSmrg
726fa459cSmrg#include <brotli/decode.h>
826fa459cSmrg
926fa459cSmrg#include <stdlib.h>  /* free, malloc */
1026fa459cSmrg#include <string.h>  /* memcpy, memset */
1126fa459cSmrg
1226fa459cSmrg#include "../common/constants.h"
1326fa459cSmrg#include "../common/context.h"
1426fa459cSmrg#include "../common/dictionary.h"
1526fa459cSmrg#include "../common/platform.h"
1626fa459cSmrg#include "../common/transform.h"
1726fa459cSmrg#include "../common/version.h"
1826fa459cSmrg#include "./bit_reader.h"
1926fa459cSmrg#include "./huffman.h"
2026fa459cSmrg#include "./prefix.h"
2126fa459cSmrg#include "./state.h"
2226fa459cSmrg
2326fa459cSmrg#if defined(BROTLI_TARGET_NEON)
2426fa459cSmrg#include <arm_neon.h>
2526fa459cSmrg#endif
2626fa459cSmrg
2726fa459cSmrg#if defined(__cplusplus) || defined(c_plusplus)
2826fa459cSmrgextern "C" {
2926fa459cSmrg#endif
3026fa459cSmrg
3126fa459cSmrg#define BROTLI_FAILURE(CODE) (BROTLI_DUMP(), CODE)
3226fa459cSmrg
3326fa459cSmrg#define BROTLI_LOG_UINT(name)                                       \
3426fa459cSmrg  BROTLI_LOG(("[%s] %s = %lu\n", __func__, #name, (unsigned long)(name)))
3526fa459cSmrg#define BROTLI_LOG_ARRAY_INDEX(array_name, idx)                     \
3626fa459cSmrg  BROTLI_LOG(("[%s] %s[%lu] = %lu\n", __func__, #array_name,        \
3726fa459cSmrg         (unsigned long)(idx), (unsigned long)array_name[idx]))
3826fa459cSmrg
3926fa459cSmrg#define HUFFMAN_TABLE_BITS 8U
4026fa459cSmrg#define HUFFMAN_TABLE_MASK 0xFF
4126fa459cSmrg
4226fa459cSmrg/* We need the slack region for the following reasons:
4326fa459cSmrg    - doing up to two 16-byte copies for fast backward copying
4426fa459cSmrg    - inserting transformed dictionary word:
4526fa459cSmrg        5 prefix + 24 base + 8 suffix */
4626fa459cSmrgstatic const uint32_t kRingBufferWriteAheadSlack = 42;
4726fa459cSmrg
4826fa459cSmrgstatic const uint8_t kCodeLengthCodeOrder[BROTLI_CODE_LENGTH_CODES] = {
4926fa459cSmrg  1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15,
5026fa459cSmrg};
5126fa459cSmrg
5226fa459cSmrg/* Static prefix code for the complex code length code lengths. */
5326fa459cSmrgstatic const uint8_t kCodeLengthPrefixLength[16] = {
5426fa459cSmrg  2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4,
5526fa459cSmrg};
5626fa459cSmrg
5726fa459cSmrgstatic const uint8_t kCodeLengthPrefixValue[16] = {
5826fa459cSmrg  0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5,
5926fa459cSmrg};
6026fa459cSmrg
6126fa459cSmrgBROTLI_BOOL BrotliDecoderSetParameter(
6226fa459cSmrg    BrotliDecoderState* state, BrotliDecoderParameter p, uint32_t value) {
6326fa459cSmrg  if (state->state != BROTLI_STATE_UNINITED) return BROTLI_FALSE;
6426fa459cSmrg  switch (p) {
6526fa459cSmrg    case BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:
6626fa459cSmrg      state->canny_ringbuffer_allocation = !!value ? 0 : 1;
6726fa459cSmrg      return BROTLI_TRUE;
6826fa459cSmrg
6926fa459cSmrg    case BROTLI_DECODER_PARAM_LARGE_WINDOW:
7026fa459cSmrg      state->large_window = TO_BROTLI_BOOL(!!value);
7126fa459cSmrg      return BROTLI_TRUE;
7226fa459cSmrg
7326fa459cSmrg    default: return BROTLI_FALSE;
7426fa459cSmrg  }
7526fa459cSmrg}
7626fa459cSmrg
7726fa459cSmrgBrotliDecoderState* BrotliDecoderCreateInstance(
7826fa459cSmrg    brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
7926fa459cSmrg  BrotliDecoderState* state = 0;
8026fa459cSmrg  if (!alloc_func && !free_func) {
8126fa459cSmrg    state = (BrotliDecoderState*)malloc(sizeof(BrotliDecoderState));
8226fa459cSmrg  } else if (alloc_func && free_func) {
8326fa459cSmrg    state = (BrotliDecoderState*)alloc_func(opaque, sizeof(BrotliDecoderState));
8426fa459cSmrg  }
8526fa459cSmrg  if (state == 0) {
8626fa459cSmrg    BROTLI_DUMP();
8726fa459cSmrg    return 0;
8826fa459cSmrg  }
8926fa459cSmrg  if (!BrotliDecoderStateInit(state, alloc_func, free_func, opaque)) {
9026fa459cSmrg    BROTLI_DUMP();
9126fa459cSmrg    if (!alloc_func && !free_func) {
9226fa459cSmrg      free(state);
9326fa459cSmrg    } else if (alloc_func && free_func) {
9426fa459cSmrg      free_func(opaque, state);
9526fa459cSmrg    }
9626fa459cSmrg    return 0;
9726fa459cSmrg  }
9826fa459cSmrg  return state;
9926fa459cSmrg}
10026fa459cSmrg
10126fa459cSmrg/* Deinitializes and frees BrotliDecoderState instance. */
10226fa459cSmrgvoid BrotliDecoderDestroyInstance(BrotliDecoderState* state) {
10326fa459cSmrg  if (!state) {
10426fa459cSmrg    return;
10526fa459cSmrg  } else {
10626fa459cSmrg    brotli_free_func free_func = state->free_func;
10726fa459cSmrg    void* opaque = state->memory_manager_opaque;
10826fa459cSmrg    BrotliDecoderStateCleanup(state);
10926fa459cSmrg    free_func(opaque, state);
11026fa459cSmrg  }
11126fa459cSmrg}
11226fa459cSmrg
11326fa459cSmrg/* Saves error code and converts it to BrotliDecoderResult. */
11426fa459cSmrgstatic BROTLI_NOINLINE BrotliDecoderResult SaveErrorCode(
11526fa459cSmrg    BrotliDecoderState* s, BrotliDecoderErrorCode e) {
11626fa459cSmrg  s->error_code = (int)e;
11726fa459cSmrg  switch (e) {
11826fa459cSmrg    case BROTLI_DECODER_SUCCESS:
11926fa459cSmrg      return BROTLI_DECODER_RESULT_SUCCESS;
12026fa459cSmrg
12126fa459cSmrg    case BROTLI_DECODER_NEEDS_MORE_INPUT:
12226fa459cSmrg      return BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
12326fa459cSmrg
12426fa459cSmrg    case BROTLI_DECODER_NEEDS_MORE_OUTPUT:
12526fa459cSmrg      return BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
12626fa459cSmrg
12726fa459cSmrg    default:
12826fa459cSmrg      return BROTLI_DECODER_RESULT_ERROR;
12926fa459cSmrg  }
13026fa459cSmrg}
13126fa459cSmrg
13226fa459cSmrg/* Decodes WBITS by reading 1 - 7 bits, or 0x11 for "Large Window Brotli".
13326fa459cSmrg   Precondition: bit-reader accumulator has at least 8 bits. */
13426fa459cSmrgstatic BrotliDecoderErrorCode DecodeWindowBits(BrotliDecoderState* s,
13526fa459cSmrg                                               BrotliBitReader* br) {
13626fa459cSmrg  uint32_t n;
13726fa459cSmrg  BROTLI_BOOL large_window = s->large_window;
13826fa459cSmrg  s->large_window = BROTLI_FALSE;
13926fa459cSmrg  BrotliTakeBits(br, 1, &n);
14026fa459cSmrg  if (n == 0) {
14126fa459cSmrg    s->window_bits = 16;
14226fa459cSmrg    return BROTLI_DECODER_SUCCESS;
14326fa459cSmrg  }
14426fa459cSmrg  BrotliTakeBits(br, 3, &n);
14526fa459cSmrg  if (n != 0) {
14626fa459cSmrg    s->window_bits = 17 + n;
14726fa459cSmrg    return BROTLI_DECODER_SUCCESS;
14826fa459cSmrg  }
14926fa459cSmrg  BrotliTakeBits(br, 3, &n);
15026fa459cSmrg  if (n == 1) {
15126fa459cSmrg    if (large_window) {
15226fa459cSmrg      BrotliTakeBits(br, 1, &n);
15326fa459cSmrg      if (n == 1) {
15426fa459cSmrg        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS);
15526fa459cSmrg      }
15626fa459cSmrg      s->large_window = BROTLI_TRUE;
15726fa459cSmrg      return BROTLI_DECODER_SUCCESS;
15826fa459cSmrg    } else {
15926fa459cSmrg      return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS);
16026fa459cSmrg    }
16126fa459cSmrg  }
16226fa459cSmrg  if (n != 0) {
16326fa459cSmrg    s->window_bits = 8 + n;
16426fa459cSmrg    return BROTLI_DECODER_SUCCESS;
16526fa459cSmrg  }
16626fa459cSmrg  s->window_bits = 17;
16726fa459cSmrg  return BROTLI_DECODER_SUCCESS;
16826fa459cSmrg}
16926fa459cSmrg
17026fa459cSmrgstatic BROTLI_INLINE void memmove16(uint8_t* dst, uint8_t* src) {
17126fa459cSmrg#if defined(BROTLI_TARGET_NEON)
17226fa459cSmrg  vst1q_u8(dst, vld1q_u8(src));
17326fa459cSmrg#else
17426fa459cSmrg  uint32_t buffer[4];
17526fa459cSmrg  memcpy(buffer, src, 16);
17626fa459cSmrg  memcpy(dst, buffer, 16);
17726fa459cSmrg#endif
17826fa459cSmrg}
17926fa459cSmrg
18026fa459cSmrg/* Decodes a number in the range [0..255], by reading 1 - 11 bits. */
18126fa459cSmrgstatic BROTLI_NOINLINE BrotliDecoderErrorCode DecodeVarLenUint8(
18226fa459cSmrg    BrotliDecoderState* s, BrotliBitReader* br, uint32_t* value) {
18326fa459cSmrg  uint32_t bits;
18426fa459cSmrg  switch (s->substate_decode_uint8) {
18526fa459cSmrg    case BROTLI_STATE_DECODE_UINT8_NONE:
18626fa459cSmrg      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 1, &bits))) {
18726fa459cSmrg        return BROTLI_DECODER_NEEDS_MORE_INPUT;
18826fa459cSmrg      }
18926fa459cSmrg      if (bits == 0) {
19026fa459cSmrg        *value = 0;
19126fa459cSmrg        return BROTLI_DECODER_SUCCESS;
19226fa459cSmrg      }
19326fa459cSmrg    /* Fall through. */
19426fa459cSmrg
19526fa459cSmrg    case BROTLI_STATE_DECODE_UINT8_SHORT:
19626fa459cSmrg      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 3, &bits))) {
19726fa459cSmrg        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_SHORT;
19826fa459cSmrg        return BROTLI_DECODER_NEEDS_MORE_INPUT;
19926fa459cSmrg      }
20026fa459cSmrg      if (bits == 0) {
20126fa459cSmrg        *value = 1;
20226fa459cSmrg        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
20326fa459cSmrg        return BROTLI_DECODER_SUCCESS;
20426fa459cSmrg      }
20526fa459cSmrg      /* Use output value as a temporary storage. It MUST be persisted. */
20626fa459cSmrg      *value = bits;
20726fa459cSmrg    /* Fall through. */
20826fa459cSmrg
20926fa459cSmrg    case BROTLI_STATE_DECODE_UINT8_LONG:
21026fa459cSmrg      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, *value, &bits))) {
21126fa459cSmrg        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_LONG;
21226fa459cSmrg        return BROTLI_DECODER_NEEDS_MORE_INPUT;
21326fa459cSmrg      }
21426fa459cSmrg      *value = (1U << *value) + bits;
21526fa459cSmrg      s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
21626fa459cSmrg      return BROTLI_DECODER_SUCCESS;
21726fa459cSmrg
21826fa459cSmrg    default:
21926fa459cSmrg      return
22026fa459cSmrg          BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
22126fa459cSmrg  }
22226fa459cSmrg}
22326fa459cSmrg
22426fa459cSmrg/* Decodes a metablock length and flags by reading 2 - 31 bits. */
22526fa459cSmrgstatic BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength(
22626fa459cSmrg    BrotliDecoderState* s, BrotliBitReader* br) {
22726fa459cSmrg  uint32_t bits;
22826fa459cSmrg  int i;
22926fa459cSmrg  for (;;) {
23026fa459cSmrg    switch (s->substate_metablock_header) {
23126fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_NONE:
23226fa459cSmrg        if (!BrotliSafeReadBits(br, 1, &bits)) {
23326fa459cSmrg          return BROTLI_DECODER_NEEDS_MORE_INPUT;
23426fa459cSmrg        }
23526fa459cSmrg        s->is_last_metablock = bits ? 1 : 0;
23626fa459cSmrg        s->meta_block_remaining_len = 0;
23726fa459cSmrg        s->is_uncompressed = 0;
23826fa459cSmrg        s->is_metadata = 0;
23926fa459cSmrg        if (!s->is_last_metablock) {
24026fa459cSmrg          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
24126fa459cSmrg          break;
24226fa459cSmrg        }
24326fa459cSmrg        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_EMPTY;
24426fa459cSmrg      /* Fall through. */
24526fa459cSmrg
24626fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_EMPTY:
24726fa459cSmrg        if (!BrotliSafeReadBits(br, 1, &bits)) {
24826fa459cSmrg          return BROTLI_DECODER_NEEDS_MORE_INPUT;
24926fa459cSmrg        }
25026fa459cSmrg        if (bits) {
25126fa459cSmrg          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
25226fa459cSmrg          return BROTLI_DECODER_SUCCESS;
25326fa459cSmrg        }
25426fa459cSmrg        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
25526fa459cSmrg      /* Fall through. */
25626fa459cSmrg
25726fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_NIBBLES:
25826fa459cSmrg        if (!BrotliSafeReadBits(br, 2, &bits)) {
25926fa459cSmrg          return BROTLI_DECODER_NEEDS_MORE_INPUT;
26026fa459cSmrg        }
26126fa459cSmrg        s->size_nibbles = (uint8_t)(bits + 4);
26226fa459cSmrg        s->loop_counter = 0;
26326fa459cSmrg        if (bits == 3) {
26426fa459cSmrg          s->is_metadata = 1;
26526fa459cSmrg          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_RESERVED;
26626fa459cSmrg          break;
26726fa459cSmrg        }
26826fa459cSmrg        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_SIZE;
26926fa459cSmrg      /* Fall through. */
27026fa459cSmrg
27126fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_SIZE:
27226fa459cSmrg        i = s->loop_counter;
27326fa459cSmrg        for (; i < (int)s->size_nibbles; ++i) {
27426fa459cSmrg          if (!BrotliSafeReadBits(br, 4, &bits)) {
27526fa459cSmrg            s->loop_counter = i;
27626fa459cSmrg            return BROTLI_DECODER_NEEDS_MORE_INPUT;
27726fa459cSmrg          }
27826fa459cSmrg          if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 4 &&
27926fa459cSmrg              bits == 0) {
28026fa459cSmrg            return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE);
28126fa459cSmrg          }
28226fa459cSmrg          s->meta_block_remaining_len |= (int)(bits << (i * 4));
28326fa459cSmrg        }
28426fa459cSmrg        s->substate_metablock_header =
28526fa459cSmrg            BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED;
28626fa459cSmrg      /* Fall through. */
28726fa459cSmrg
28826fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_UNCOMPRESSED:
28926fa459cSmrg        if (!s->is_last_metablock) {
29026fa459cSmrg          if (!BrotliSafeReadBits(br, 1, &bits)) {
29126fa459cSmrg            return BROTLI_DECODER_NEEDS_MORE_INPUT;
29226fa459cSmrg          }
29326fa459cSmrg          s->is_uncompressed = bits ? 1 : 0;
29426fa459cSmrg        }
29526fa459cSmrg        ++s->meta_block_remaining_len;
29626fa459cSmrg        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
29726fa459cSmrg        return BROTLI_DECODER_SUCCESS;
29826fa459cSmrg
29926fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_RESERVED:
30026fa459cSmrg        if (!BrotliSafeReadBits(br, 1, &bits)) {
30126fa459cSmrg          return BROTLI_DECODER_NEEDS_MORE_INPUT;
30226fa459cSmrg        }
30326fa459cSmrg        if (bits != 0) {
30426fa459cSmrg          return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_RESERVED);
30526fa459cSmrg        }
30626fa459cSmrg        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_BYTES;
30726fa459cSmrg      /* Fall through. */
30826fa459cSmrg
30926fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_BYTES:
31026fa459cSmrg        if (!BrotliSafeReadBits(br, 2, &bits)) {
31126fa459cSmrg          return BROTLI_DECODER_NEEDS_MORE_INPUT;
31226fa459cSmrg        }
31326fa459cSmrg        if (bits == 0) {
31426fa459cSmrg          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
31526fa459cSmrg          return BROTLI_DECODER_SUCCESS;
31626fa459cSmrg        }
31726fa459cSmrg        s->size_nibbles = (uint8_t)bits;
31826fa459cSmrg        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_METADATA;
31926fa459cSmrg      /* Fall through. */
32026fa459cSmrg
32126fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_METADATA:
32226fa459cSmrg        i = s->loop_counter;
32326fa459cSmrg        for (; i < (int)s->size_nibbles; ++i) {
32426fa459cSmrg          if (!BrotliSafeReadBits(br, 8, &bits)) {
32526fa459cSmrg            s->loop_counter = i;
32626fa459cSmrg            return BROTLI_DECODER_NEEDS_MORE_INPUT;
32726fa459cSmrg          }
32826fa459cSmrg          if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 1 &&
32926fa459cSmrg              bits == 0) {
33026fa459cSmrg            return BROTLI_FAILURE(
33126fa459cSmrg                BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE);
33226fa459cSmrg          }
33326fa459cSmrg          s->meta_block_remaining_len |= (int)(bits << (i * 8));
33426fa459cSmrg        }
33526fa459cSmrg        ++s->meta_block_remaining_len;
33626fa459cSmrg        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
33726fa459cSmrg        return BROTLI_DECODER_SUCCESS;
33826fa459cSmrg
33926fa459cSmrg      default:
34026fa459cSmrg        return
34126fa459cSmrg            BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
34226fa459cSmrg    }
34326fa459cSmrg  }
34426fa459cSmrg}
34526fa459cSmrg
34626fa459cSmrg/* Decodes the Huffman code.
34726fa459cSmrg   This method doesn't read data from the bit reader, BUT drops the amount of
34826fa459cSmrg   bits that correspond to the decoded symbol.
34926fa459cSmrg   bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits. */
35026fa459cSmrgstatic BROTLI_INLINE uint32_t DecodeSymbol(uint32_t bits,
35126fa459cSmrg                                           const HuffmanCode* table,
35226fa459cSmrg                                           BrotliBitReader* br) {
35326fa459cSmrg  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
35426fa459cSmrg  BROTLI_HC_ADJUST_TABLE_INDEX(table, bits & HUFFMAN_TABLE_MASK);
35526fa459cSmrg  if (BROTLI_HC_FAST_LOAD_BITS(table) > HUFFMAN_TABLE_BITS) {
35626fa459cSmrg    uint32_t nbits = BROTLI_HC_FAST_LOAD_BITS(table) - HUFFMAN_TABLE_BITS;
35726fa459cSmrg    BrotliDropBits(br, HUFFMAN_TABLE_BITS);
35826fa459cSmrg    BROTLI_HC_ADJUST_TABLE_INDEX(table,
35926fa459cSmrg        BROTLI_HC_FAST_LOAD_VALUE(table) +
36026fa459cSmrg        ((bits >> HUFFMAN_TABLE_BITS) & BitMask(nbits)));
36126fa459cSmrg  }
36226fa459cSmrg  BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table));
36326fa459cSmrg  return BROTLI_HC_FAST_LOAD_VALUE(table);
36426fa459cSmrg}
36526fa459cSmrg
36626fa459cSmrg/* Reads and decodes the next Huffman code from bit-stream.
36726fa459cSmrg   This method peeks 16 bits of input and drops 0 - 15 of them. */
36826fa459cSmrgstatic BROTLI_INLINE uint32_t ReadSymbol(const HuffmanCode* table,
36926fa459cSmrg                                         BrotliBitReader* br) {
37026fa459cSmrg  return DecodeSymbol(BrotliGet16BitsUnmasked(br), table, br);
37126fa459cSmrg}
37226fa459cSmrg
37326fa459cSmrg/* Same as DecodeSymbol, but it is known that there is less than 15 bits of
37426fa459cSmrg   input are currently available. */
37526fa459cSmrgstatic BROTLI_NOINLINE BROTLI_BOOL SafeDecodeSymbol(
37626fa459cSmrg    const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) {
37726fa459cSmrg  uint32_t val;
37826fa459cSmrg  uint32_t available_bits = BrotliGetAvailableBits(br);
37926fa459cSmrg  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
38026fa459cSmrg  if (available_bits == 0) {
38126fa459cSmrg    if (BROTLI_HC_FAST_LOAD_BITS(table) == 0) {
38226fa459cSmrg      *result = BROTLI_HC_FAST_LOAD_VALUE(table);
38326fa459cSmrg      return BROTLI_TRUE;
38426fa459cSmrg    }
38526fa459cSmrg    return BROTLI_FALSE;  /* No valid bits at all. */
38626fa459cSmrg  }
38726fa459cSmrg  val = (uint32_t)BrotliGetBitsUnmasked(br);
38826fa459cSmrg  BROTLI_HC_ADJUST_TABLE_INDEX(table, val & HUFFMAN_TABLE_MASK);
38926fa459cSmrg  if (BROTLI_HC_FAST_LOAD_BITS(table) <= HUFFMAN_TABLE_BITS) {
39026fa459cSmrg    if (BROTLI_HC_FAST_LOAD_BITS(table) <= available_bits) {
39126fa459cSmrg      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table));
39226fa459cSmrg      *result = BROTLI_HC_FAST_LOAD_VALUE(table);
39326fa459cSmrg      return BROTLI_TRUE;
39426fa459cSmrg    } else {
39526fa459cSmrg      return BROTLI_FALSE;  /* Not enough bits for the first level. */
39626fa459cSmrg    }
39726fa459cSmrg  }
39826fa459cSmrg  if (available_bits <= HUFFMAN_TABLE_BITS) {
39926fa459cSmrg    return BROTLI_FALSE;  /* Not enough bits to move to the second level. */
40026fa459cSmrg  }
40126fa459cSmrg
40226fa459cSmrg  /* Speculatively drop HUFFMAN_TABLE_BITS. */
40326fa459cSmrg  val = (val & BitMask(BROTLI_HC_FAST_LOAD_BITS(table))) >> HUFFMAN_TABLE_BITS;
40426fa459cSmrg  available_bits -= HUFFMAN_TABLE_BITS;
40526fa459cSmrg  BROTLI_HC_ADJUST_TABLE_INDEX(table, BROTLI_HC_FAST_LOAD_VALUE(table) + val);
40626fa459cSmrg  if (available_bits < BROTLI_HC_FAST_LOAD_BITS(table)) {
40726fa459cSmrg    return BROTLI_FALSE;  /* Not enough bits for the second level. */
40826fa459cSmrg  }
40926fa459cSmrg
41026fa459cSmrg  BrotliDropBits(br, HUFFMAN_TABLE_BITS + BROTLI_HC_FAST_LOAD_BITS(table));
41126fa459cSmrg  *result = BROTLI_HC_FAST_LOAD_VALUE(table);
41226fa459cSmrg  return BROTLI_TRUE;
41326fa459cSmrg}
41426fa459cSmrg
41526fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL SafeReadSymbol(
41626fa459cSmrg    const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) {
41726fa459cSmrg  uint32_t val;
41826fa459cSmrg  if (BROTLI_PREDICT_TRUE(BrotliSafeGetBits(br, 15, &val))) {
41926fa459cSmrg    *result = DecodeSymbol(val, table, br);
42026fa459cSmrg    return BROTLI_TRUE;
42126fa459cSmrg  }
42226fa459cSmrg  return SafeDecodeSymbol(table, br, result);
42326fa459cSmrg}
42426fa459cSmrg
42526fa459cSmrg/* Makes a look-up in first level Huffman table. Peeks 8 bits. */
42626fa459cSmrgstatic BROTLI_INLINE void PreloadSymbol(int safe,
42726fa459cSmrg                                        const HuffmanCode* table,
42826fa459cSmrg                                        BrotliBitReader* br,
42926fa459cSmrg                                        uint32_t* bits,
43026fa459cSmrg                                        uint32_t* value) {
43126fa459cSmrg  if (safe) {
43226fa459cSmrg    return;
43326fa459cSmrg  }
43426fa459cSmrg  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
43526fa459cSmrg  BROTLI_HC_ADJUST_TABLE_INDEX(table, BrotliGetBits(br, HUFFMAN_TABLE_BITS));
43626fa459cSmrg  *bits = BROTLI_HC_FAST_LOAD_BITS(table);
43726fa459cSmrg  *value = BROTLI_HC_FAST_LOAD_VALUE(table);
43826fa459cSmrg}
43926fa459cSmrg
44026fa459cSmrg/* Decodes the next Huffman code using data prepared by PreloadSymbol.
44126fa459cSmrg   Reads 0 - 15 bits. Also peeks 8 following bits. */
44226fa459cSmrgstatic BROTLI_INLINE uint32_t ReadPreloadedSymbol(const HuffmanCode* table,
44326fa459cSmrg                                                  BrotliBitReader* br,
44426fa459cSmrg                                                  uint32_t* bits,
44526fa459cSmrg                                                  uint32_t* value) {
44626fa459cSmrg  uint32_t result = *value;
44726fa459cSmrg  if (BROTLI_PREDICT_FALSE(*bits > HUFFMAN_TABLE_BITS)) {
44826fa459cSmrg    uint32_t val = BrotliGet16BitsUnmasked(br);
44926fa459cSmrg    const HuffmanCode* ext = table + (val & HUFFMAN_TABLE_MASK) + *value;
45026fa459cSmrg    uint32_t mask = BitMask((*bits - HUFFMAN_TABLE_BITS));
45126fa459cSmrg    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(ext);
45226fa459cSmrg    BrotliDropBits(br, HUFFMAN_TABLE_BITS);
45326fa459cSmrg    BROTLI_HC_ADJUST_TABLE_INDEX(ext, (val >> HUFFMAN_TABLE_BITS) & mask);
45426fa459cSmrg    BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(ext));
45526fa459cSmrg    result = BROTLI_HC_FAST_LOAD_VALUE(ext);
45626fa459cSmrg  } else {
45726fa459cSmrg    BrotliDropBits(br, *bits);
45826fa459cSmrg  }
45926fa459cSmrg  PreloadSymbol(0, table, br, bits, value);
46026fa459cSmrg  return result;
46126fa459cSmrg}
46226fa459cSmrg
46326fa459cSmrgstatic BROTLI_INLINE uint32_t Log2Floor(uint32_t x) {
46426fa459cSmrg  uint32_t result = 0;
46526fa459cSmrg  while (x) {
46626fa459cSmrg    x >>= 1;
46726fa459cSmrg    ++result;
46826fa459cSmrg  }
46926fa459cSmrg  return result;
47026fa459cSmrg}
47126fa459cSmrg
47226fa459cSmrg/* Reads (s->symbol + 1) symbols.
47326fa459cSmrg   Totally 1..4 symbols are read, 1..11 bits each.
47426fa459cSmrg   The list of symbols MUST NOT contain duplicates. */
47526fa459cSmrgstatic BrotliDecoderErrorCode ReadSimpleHuffmanSymbols(
47626fa459cSmrg    uint32_t alphabet_size_max, uint32_t alphabet_size_limit,
47726fa459cSmrg    BrotliDecoderState* s) {
47826fa459cSmrg  /* max_bits == 1..11; symbol == 0..3; 1..44 bits will be read. */
47926fa459cSmrg  BrotliBitReader* br = &s->br;
48026fa459cSmrg  BrotliMetablockHeaderArena* h = &s->arena.header;
48126fa459cSmrg  uint32_t max_bits = Log2Floor(alphabet_size_max - 1);
48226fa459cSmrg  uint32_t i = h->sub_loop_counter;
48326fa459cSmrg  uint32_t num_symbols = h->symbol;
48426fa459cSmrg  while (i <= num_symbols) {
48526fa459cSmrg    uint32_t v;
48626fa459cSmrg    if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))) {
48726fa459cSmrg      h->sub_loop_counter = i;
48826fa459cSmrg      h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ;
48926fa459cSmrg      return BROTLI_DECODER_NEEDS_MORE_INPUT;
49026fa459cSmrg    }
49126fa459cSmrg    if (v >= alphabet_size_limit) {
49226fa459cSmrg      return
49326fa459cSmrg          BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET);
49426fa459cSmrg    }
49526fa459cSmrg    h->symbols_lists_array[i] = (uint16_t)v;
49626fa459cSmrg    BROTLI_LOG_UINT(h->symbols_lists_array[i]);
49726fa459cSmrg    ++i;
49826fa459cSmrg  }
49926fa459cSmrg
50026fa459cSmrg  for (i = 0; i < num_symbols; ++i) {
50126fa459cSmrg    uint32_t k = i + 1;
50226fa459cSmrg    for (; k <= num_symbols; ++k) {
50326fa459cSmrg      if (h->symbols_lists_array[i] == h->symbols_lists_array[k]) {
50426fa459cSmrg        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME);
50526fa459cSmrg      }
50626fa459cSmrg    }
50726fa459cSmrg  }
50826fa459cSmrg
50926fa459cSmrg  return BROTLI_DECODER_SUCCESS;
51026fa459cSmrg}
51126fa459cSmrg
51226fa459cSmrg/* Process single decoded symbol code length:
51326fa459cSmrg    A) reset the repeat variable
51426fa459cSmrg    B) remember code length (if it is not 0)
51526fa459cSmrg    C) extend corresponding index-chain
51626fa459cSmrg    D) reduce the Huffman space
51726fa459cSmrg    E) update the histogram */
51826fa459cSmrgstatic BROTLI_INLINE void ProcessSingleCodeLength(uint32_t code_len,
51926fa459cSmrg    uint32_t* symbol, uint32_t* repeat, uint32_t* space,
52026fa459cSmrg    uint32_t* prev_code_len, uint16_t* symbol_lists,
52126fa459cSmrg    uint16_t* code_length_histo, int* next_symbol) {
52226fa459cSmrg  *repeat = 0;
52326fa459cSmrg  if (code_len != 0) {  /* code_len == 1..15 */
52426fa459cSmrg    symbol_lists[next_symbol[code_len]] = (uint16_t)(*symbol);
52526fa459cSmrg    next_symbol[code_len] = (int)(*symbol);
52626fa459cSmrg    *prev_code_len = code_len;
52726fa459cSmrg    *space -= 32768U >> code_len;
52826fa459cSmrg    code_length_histo[code_len]++;
52926fa459cSmrg    BROTLI_LOG(("[ReadHuffmanCode] code_length[%d] = %d\n",
53026fa459cSmrg        (int)*symbol, (int)code_len));
53126fa459cSmrg  }
53226fa459cSmrg  (*symbol)++;
53326fa459cSmrg}
53426fa459cSmrg
53526fa459cSmrg/* Process repeated symbol code length.
53626fa459cSmrg    A) Check if it is the extension of previous repeat sequence; if the decoded
53726fa459cSmrg       value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new
53826fa459cSmrg       symbol-skip
53926fa459cSmrg    B) Update repeat variable
54026fa459cSmrg    C) Check if operation is feasible (fits alphabet)
54126fa459cSmrg    D) For each symbol do the same operations as in ProcessSingleCodeLength
54226fa459cSmrg
54326fa459cSmrg   PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or
54426fa459cSmrg                 code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH */
54526fa459cSmrgstatic BROTLI_INLINE void ProcessRepeatedCodeLength(uint32_t code_len,
54626fa459cSmrg    uint32_t repeat_delta, uint32_t alphabet_size, uint32_t* symbol,
54726fa459cSmrg    uint32_t* repeat, uint32_t* space, uint32_t* prev_code_len,
54826fa459cSmrg    uint32_t* repeat_code_len, uint16_t* symbol_lists,
54926fa459cSmrg    uint16_t* code_length_histo, int* next_symbol) {
55026fa459cSmrg  uint32_t old_repeat;
55126fa459cSmrg  uint32_t extra_bits = 3;  /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
55226fa459cSmrg  uint32_t new_len = 0;  /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
55326fa459cSmrg  if (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
55426fa459cSmrg    new_len = *prev_code_len;
55526fa459cSmrg    extra_bits = 2;
55626fa459cSmrg  }
55726fa459cSmrg  if (*repeat_code_len != new_len) {
55826fa459cSmrg    *repeat = 0;
55926fa459cSmrg    *repeat_code_len = new_len;
56026fa459cSmrg  }
56126fa459cSmrg  old_repeat = *repeat;
56226fa459cSmrg  if (*repeat > 0) {
56326fa459cSmrg    *repeat -= 2;
56426fa459cSmrg    *repeat <<= extra_bits;
56526fa459cSmrg  }
56626fa459cSmrg  *repeat += repeat_delta + 3U;
56726fa459cSmrg  repeat_delta = *repeat - old_repeat;
56826fa459cSmrg  if (*symbol + repeat_delta > alphabet_size) {
56926fa459cSmrg    BROTLI_DUMP();
57026fa459cSmrg    *symbol = alphabet_size;
57126fa459cSmrg    *space = 0xFFFFF;
57226fa459cSmrg    return;
57326fa459cSmrg  }
57426fa459cSmrg  BROTLI_LOG(("[ReadHuffmanCode] code_length[%d..%d] = %d\n",
57526fa459cSmrg      (int)*symbol, (int)(*symbol + repeat_delta - 1), (int)*repeat_code_len));
57626fa459cSmrg  if (*repeat_code_len != 0) {
57726fa459cSmrg    unsigned last = *symbol + repeat_delta;
57826fa459cSmrg    int next = next_symbol[*repeat_code_len];
57926fa459cSmrg    do {
58026fa459cSmrg      symbol_lists[next] = (uint16_t)*symbol;
58126fa459cSmrg      next = (int)*symbol;
58226fa459cSmrg    } while (++(*symbol) != last);
58326fa459cSmrg    next_symbol[*repeat_code_len] = next;
58426fa459cSmrg    *space -= repeat_delta << (15 - *repeat_code_len);
58526fa459cSmrg    code_length_histo[*repeat_code_len] =
58626fa459cSmrg        (uint16_t)(code_length_histo[*repeat_code_len] + repeat_delta);
58726fa459cSmrg  } else {
58826fa459cSmrg    *symbol += repeat_delta;
58926fa459cSmrg  }
59026fa459cSmrg}
59126fa459cSmrg
59226fa459cSmrg/* Reads and decodes symbol codelengths. */
59326fa459cSmrgstatic BrotliDecoderErrorCode ReadSymbolCodeLengths(
59426fa459cSmrg    uint32_t alphabet_size, BrotliDecoderState* s) {
59526fa459cSmrg  BrotliBitReader* br = &s->br;
59626fa459cSmrg  BrotliMetablockHeaderArena* h = &s->arena.header;
59726fa459cSmrg  uint32_t symbol = h->symbol;
59826fa459cSmrg  uint32_t repeat = h->repeat;
59926fa459cSmrg  uint32_t space = h->space;
60026fa459cSmrg  uint32_t prev_code_len = h->prev_code_len;
60126fa459cSmrg  uint32_t repeat_code_len = h->repeat_code_len;
60226fa459cSmrg  uint16_t* symbol_lists = h->symbol_lists;
60326fa459cSmrg  uint16_t* code_length_histo = h->code_length_histo;
60426fa459cSmrg  int* next_symbol = h->next_symbol;
60526fa459cSmrg  if (!BrotliWarmupBitReader(br)) {
60626fa459cSmrg    return BROTLI_DECODER_NEEDS_MORE_INPUT;
60726fa459cSmrg  }
60826fa459cSmrg  while (symbol < alphabet_size && space > 0) {
60926fa459cSmrg    const HuffmanCode* p = h->table;
61026fa459cSmrg    uint32_t code_len;
61126fa459cSmrg    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p);
61226fa459cSmrg    if (!BrotliCheckInputAmount(br, BROTLI_SHORT_FILL_BIT_WINDOW_READ)) {
61326fa459cSmrg      h->symbol = symbol;
61426fa459cSmrg      h->repeat = repeat;
61526fa459cSmrg      h->prev_code_len = prev_code_len;
61626fa459cSmrg      h->repeat_code_len = repeat_code_len;
61726fa459cSmrg      h->space = space;
61826fa459cSmrg      return BROTLI_DECODER_NEEDS_MORE_INPUT;
61926fa459cSmrg    }
62026fa459cSmrg    BrotliFillBitWindow16(br);
62126fa459cSmrg    BROTLI_HC_ADJUST_TABLE_INDEX(p, BrotliGetBitsUnmasked(br) &
62226fa459cSmrg        BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH));
62326fa459cSmrg    BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p));  /* Use 1..5 bits. */
62426fa459cSmrg    code_len = BROTLI_HC_FAST_LOAD_VALUE(p);  /* code_len == 0..17 */
62526fa459cSmrg    if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
62626fa459cSmrg      ProcessSingleCodeLength(code_len, &symbol, &repeat, &space,
62726fa459cSmrg          &prev_code_len, symbol_lists, code_length_histo, next_symbol);
62826fa459cSmrg    } else {  /* code_len == 16..17, extra_bits == 2..3 */
62926fa459cSmrg      uint32_t extra_bits =
63026fa459cSmrg          (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) ? 2 : 3;
63126fa459cSmrg      uint32_t repeat_delta =
63226fa459cSmrg          (uint32_t)BrotliGetBitsUnmasked(br) & BitMask(extra_bits);
63326fa459cSmrg      BrotliDropBits(br, extra_bits);
63426fa459cSmrg      ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
63526fa459cSmrg          &symbol, &repeat, &space, &prev_code_len, &repeat_code_len,
63626fa459cSmrg          symbol_lists, code_length_histo, next_symbol);
63726fa459cSmrg    }
63826fa459cSmrg  }
63926fa459cSmrg  h->space = space;
64026fa459cSmrg  return BROTLI_DECODER_SUCCESS;
64126fa459cSmrg}
64226fa459cSmrg
64326fa459cSmrgstatic BrotliDecoderErrorCode SafeReadSymbolCodeLengths(
64426fa459cSmrg    uint32_t alphabet_size, BrotliDecoderState* s) {
64526fa459cSmrg  BrotliBitReader* br = &s->br;
64626fa459cSmrg  BrotliMetablockHeaderArena* h = &s->arena.header;
64726fa459cSmrg  BROTLI_BOOL get_byte = BROTLI_FALSE;
64826fa459cSmrg  while (h->symbol < alphabet_size && h->space > 0) {
64926fa459cSmrg    const HuffmanCode* p = h->table;
65026fa459cSmrg    uint32_t code_len;
65126fa459cSmrg    uint32_t available_bits;
65226fa459cSmrg    uint32_t bits = 0;
65326fa459cSmrg    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p);
65426fa459cSmrg    if (get_byte && !BrotliPullByte(br)) return BROTLI_DECODER_NEEDS_MORE_INPUT;
65526fa459cSmrg    get_byte = BROTLI_FALSE;
65626fa459cSmrg    available_bits = BrotliGetAvailableBits(br);
65726fa459cSmrg    if (available_bits != 0) {
65826fa459cSmrg      bits = (uint32_t)BrotliGetBitsUnmasked(br);
65926fa459cSmrg    }
66026fa459cSmrg    BROTLI_HC_ADJUST_TABLE_INDEX(p,
66126fa459cSmrg        bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH));
66226fa459cSmrg    if (BROTLI_HC_FAST_LOAD_BITS(p) > available_bits) {
66326fa459cSmrg      get_byte = BROTLI_TRUE;
66426fa459cSmrg      continue;
66526fa459cSmrg    }
66626fa459cSmrg    code_len = BROTLI_HC_FAST_LOAD_VALUE(p);  /* code_len == 0..17 */
66726fa459cSmrg    if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
66826fa459cSmrg      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p));
66926fa459cSmrg      ProcessSingleCodeLength(code_len, &h->symbol, &h->repeat, &h->space,
67026fa459cSmrg          &h->prev_code_len, h->symbol_lists, h->code_length_histo,
67126fa459cSmrg          h->next_symbol);
67226fa459cSmrg    } else {  /* code_len == 16..17, extra_bits == 2..3 */
67326fa459cSmrg      uint32_t extra_bits = code_len - 14U;
67426fa459cSmrg      uint32_t repeat_delta = (bits >> BROTLI_HC_FAST_LOAD_BITS(p)) &
67526fa459cSmrg          BitMask(extra_bits);
67626fa459cSmrg      if (available_bits < BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits) {
67726fa459cSmrg        get_byte = BROTLI_TRUE;
67826fa459cSmrg        continue;
67926fa459cSmrg      }
68026fa459cSmrg      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits);
68126fa459cSmrg      ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
68226fa459cSmrg          &h->symbol, &h->repeat, &h->space, &h->prev_code_len,
68326fa459cSmrg          &h->repeat_code_len, h->symbol_lists, h->code_length_histo,
68426fa459cSmrg          h->next_symbol);
68526fa459cSmrg    }
68626fa459cSmrg  }
68726fa459cSmrg  return BROTLI_DECODER_SUCCESS;
68826fa459cSmrg}
68926fa459cSmrg
69026fa459cSmrg/* Reads and decodes 15..18 codes using static prefix code.
69126fa459cSmrg   Each code is 2..4 bits long. In total 30..72 bits are used. */
69226fa459cSmrgstatic BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) {
69326fa459cSmrg  BrotliBitReader* br = &s->br;
69426fa459cSmrg  BrotliMetablockHeaderArena* h = &s->arena.header;
69526fa459cSmrg  uint32_t num_codes = h->repeat;
69626fa459cSmrg  unsigned space = h->space;
69726fa459cSmrg  uint32_t i = h->sub_loop_counter;
69826fa459cSmrg  for (; i < BROTLI_CODE_LENGTH_CODES; ++i) {
69926fa459cSmrg    const uint8_t code_len_idx = kCodeLengthCodeOrder[i];
70026fa459cSmrg    uint32_t ix;
70126fa459cSmrg    uint32_t v;
70226fa459cSmrg    if (BROTLI_PREDICT_FALSE(!BrotliSafeGetBits(br, 4, &ix))) {
70326fa459cSmrg      uint32_t available_bits = BrotliGetAvailableBits(br);
70426fa459cSmrg      if (available_bits != 0) {
70526fa459cSmrg        ix = BrotliGetBitsUnmasked(br) & 0xF;
70626fa459cSmrg      } else {
70726fa459cSmrg        ix = 0;
70826fa459cSmrg      }
70926fa459cSmrg      if (kCodeLengthPrefixLength[ix] > available_bits) {
71026fa459cSmrg        h->sub_loop_counter = i;
71126fa459cSmrg        h->repeat = num_codes;
71226fa459cSmrg        h->space = space;
71326fa459cSmrg        h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
71426fa459cSmrg        return BROTLI_DECODER_NEEDS_MORE_INPUT;
71526fa459cSmrg      }
71626fa459cSmrg    }
71726fa459cSmrg    v = kCodeLengthPrefixValue[ix];
71826fa459cSmrg    BrotliDropBits(br, kCodeLengthPrefixLength[ix]);
71926fa459cSmrg    h->code_length_code_lengths[code_len_idx] = (uint8_t)v;
72026fa459cSmrg    BROTLI_LOG_ARRAY_INDEX(h->code_length_code_lengths, code_len_idx);
72126fa459cSmrg    if (v != 0) {
72226fa459cSmrg      space = space - (32U >> v);
72326fa459cSmrg      ++num_codes;
72426fa459cSmrg      ++h->code_length_histo[v];
72526fa459cSmrg      if (space - 1U >= 32U) {
72626fa459cSmrg        /* space is 0 or wrapped around. */
72726fa459cSmrg        break;
72826fa459cSmrg      }
72926fa459cSmrg    }
73026fa459cSmrg  }
73126fa459cSmrg  if (!(num_codes == 1 || space == 0)) {
73226fa459cSmrg    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CL_SPACE);
73326fa459cSmrg  }
73426fa459cSmrg  return BROTLI_DECODER_SUCCESS;
73526fa459cSmrg}
73626fa459cSmrg
73726fa459cSmrg/* Decodes the Huffman tables.
73826fa459cSmrg   There are 2 scenarios:
73926fa459cSmrg    A) Huffman code contains only few symbols (1..4). Those symbols are read
74026fa459cSmrg       directly; their code lengths are defined by the number of symbols.
74126fa459cSmrg       For this scenario 4 - 49 bits will be read.
74226fa459cSmrg
74326fa459cSmrg    B) 2-phase decoding:
74426fa459cSmrg    B.1) Small Huffman table is decoded; it is specified with code lengths
74526fa459cSmrg         encoded with predefined entropy code. 32 - 74 bits are used.
74626fa459cSmrg    B.2) Decoded table is used to decode code lengths of symbols in resulting
74726fa459cSmrg         Huffman table. In worst case 3520 bits are read. */
74826fa459cSmrgstatic BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size_max,
74926fa459cSmrg                                              uint32_t alphabet_size_limit,
75026fa459cSmrg                                              HuffmanCode* table,
75126fa459cSmrg                                              uint32_t* opt_table_size,
75226fa459cSmrg                                              BrotliDecoderState* s) {
75326fa459cSmrg  BrotliBitReader* br = &s->br;
75426fa459cSmrg  BrotliMetablockHeaderArena* h = &s->arena.header;
75526fa459cSmrg  /* State machine. */
75626fa459cSmrg  for (;;) {
75726fa459cSmrg    switch (h->substate_huffman) {
75826fa459cSmrg      case BROTLI_STATE_HUFFMAN_NONE:
75926fa459cSmrg        if (!BrotliSafeReadBits(br, 2, &h->sub_loop_counter)) {
76026fa459cSmrg          return BROTLI_DECODER_NEEDS_MORE_INPUT;
76126fa459cSmrg        }
76226fa459cSmrg        BROTLI_LOG_UINT(h->sub_loop_counter);
76326fa459cSmrg        /* The value is used as follows:
76426fa459cSmrg           1 for simple code;
76526fa459cSmrg           0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
76626fa459cSmrg        if (h->sub_loop_counter != 1) {
76726fa459cSmrg          h->space = 32;
76826fa459cSmrg          h->repeat = 0;  /* num_codes */
76926fa459cSmrg          memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo[0]) *
77026fa459cSmrg              (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1));
77126fa459cSmrg          memset(&h->code_length_code_lengths[0], 0,
77226fa459cSmrg              sizeof(h->code_length_code_lengths));
77326fa459cSmrg          h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
77426fa459cSmrg          continue;
77526fa459cSmrg        }
77626fa459cSmrg      /* Fall through. */
77726fa459cSmrg
77826fa459cSmrg      case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE:
77926fa459cSmrg        /* Read symbols, codes & code lengths directly. */
78026fa459cSmrg        if (!BrotliSafeReadBits(br, 2, &h->symbol)) {  /* num_symbols */
78126fa459cSmrg          h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
78226fa459cSmrg          return BROTLI_DECODER_NEEDS_MORE_INPUT;
78326fa459cSmrg        }
78426fa459cSmrg        h->sub_loop_counter = 0;
78526fa459cSmrg      /* Fall through. */
78626fa459cSmrg
78726fa459cSmrg      case BROTLI_STATE_HUFFMAN_SIMPLE_READ: {
78826fa459cSmrg        BrotliDecoderErrorCode result =
78926fa459cSmrg            ReadSimpleHuffmanSymbols(alphabet_size_max, alphabet_size_limit, s);
79026fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
79126fa459cSmrg          return result;
79226fa459cSmrg        }
79326fa459cSmrg      }
79426fa459cSmrg      /* Fall through. */
79526fa459cSmrg
79626fa459cSmrg      case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: {
79726fa459cSmrg        uint32_t table_size;
79826fa459cSmrg        if (h->symbol == 3) {
79926fa459cSmrg          uint32_t bits;
80026fa459cSmrg          if (!BrotliSafeReadBits(br, 1, &bits)) {
80126fa459cSmrg            h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
80226fa459cSmrg            return BROTLI_DECODER_NEEDS_MORE_INPUT;
80326fa459cSmrg          }
80426fa459cSmrg          h->symbol += bits;
80526fa459cSmrg        }
80626fa459cSmrg        BROTLI_LOG_UINT(h->symbol);
80726fa459cSmrg        table_size = BrotliBuildSimpleHuffmanTable(
80826fa459cSmrg            table, HUFFMAN_TABLE_BITS, h->symbols_lists_array, h->symbol);
80926fa459cSmrg        if (opt_table_size) {
81026fa459cSmrg          *opt_table_size = table_size;
81126fa459cSmrg        }
81226fa459cSmrg        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
81326fa459cSmrg        return BROTLI_DECODER_SUCCESS;
81426fa459cSmrg      }
81526fa459cSmrg
81626fa459cSmrg      /* Decode Huffman-coded code lengths. */
81726fa459cSmrg      case BROTLI_STATE_HUFFMAN_COMPLEX: {
81826fa459cSmrg        uint32_t i;
81926fa459cSmrg        BrotliDecoderErrorCode result = ReadCodeLengthCodeLengths(s);
82026fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
82126fa459cSmrg          return result;
82226fa459cSmrg        }
82326fa459cSmrg        BrotliBuildCodeLengthsHuffmanTable(h->table,
82426fa459cSmrg                                           h->code_length_code_lengths,
82526fa459cSmrg                                           h->code_length_histo);
82626fa459cSmrg        memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo));
82726fa459cSmrg        for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH; ++i) {
82826fa459cSmrg          h->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1);
82926fa459cSmrg          h->symbol_lists[h->next_symbol[i]] = 0xFFFF;
83026fa459cSmrg        }
83126fa459cSmrg
83226fa459cSmrg        h->symbol = 0;
83326fa459cSmrg        h->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH;
83426fa459cSmrg        h->repeat = 0;
83526fa459cSmrg        h->repeat_code_len = 0;
83626fa459cSmrg        h->space = 32768;
83726fa459cSmrg        h->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
83826fa459cSmrg      }
83926fa459cSmrg      /* Fall through. */
84026fa459cSmrg
84126fa459cSmrg      case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: {
84226fa459cSmrg        uint32_t table_size;
84326fa459cSmrg        BrotliDecoderErrorCode result = ReadSymbolCodeLengths(
84426fa459cSmrg            alphabet_size_limit, s);
84526fa459cSmrg        if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
84626fa459cSmrg          result = SafeReadSymbolCodeLengths(alphabet_size_limit, s);
84726fa459cSmrg        }
84826fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
84926fa459cSmrg          return result;
85026fa459cSmrg        }
85126fa459cSmrg
85226fa459cSmrg        if (h->space != 0) {
85326fa459cSmrg          BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", (int)h->space));
85426fa459cSmrg          return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE);
85526fa459cSmrg        }
85626fa459cSmrg        table_size = BrotliBuildHuffmanTable(
85726fa459cSmrg            table, HUFFMAN_TABLE_BITS, h->symbol_lists, h->code_length_histo);
85826fa459cSmrg        if (opt_table_size) {
85926fa459cSmrg          *opt_table_size = table_size;
86026fa459cSmrg        }
86126fa459cSmrg        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
86226fa459cSmrg        return BROTLI_DECODER_SUCCESS;
86326fa459cSmrg      }
86426fa459cSmrg
86526fa459cSmrg      default:
86626fa459cSmrg        return
86726fa459cSmrg            BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
86826fa459cSmrg    }
86926fa459cSmrg  }
87026fa459cSmrg}
87126fa459cSmrg
87226fa459cSmrg/* Decodes a block length by reading 3..39 bits. */
87326fa459cSmrgstatic BROTLI_INLINE uint32_t ReadBlockLength(const HuffmanCode* table,
87426fa459cSmrg                                              BrotliBitReader* br) {
87526fa459cSmrg  uint32_t code;
87626fa459cSmrg  uint32_t nbits;
87726fa459cSmrg  code = ReadSymbol(table, br);
87826fa459cSmrg  nbits = _kBrotliPrefixCodeRanges[code].nbits;  /* nbits == 2..24 */
87926fa459cSmrg  return _kBrotliPrefixCodeRanges[code].offset + BrotliReadBits24(br, nbits);
88026fa459cSmrg}
88126fa459cSmrg
88226fa459cSmrg/* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
88326fa459cSmrg   reading can't be continued with ReadBlockLength. */
88426fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL SafeReadBlockLength(
88526fa459cSmrg    BrotliDecoderState* s, uint32_t* result, const HuffmanCode* table,
88626fa459cSmrg    BrotliBitReader* br) {
88726fa459cSmrg  uint32_t index;
88826fa459cSmrg  if (s->substate_read_block_length == BROTLI_STATE_READ_BLOCK_LENGTH_NONE) {
88926fa459cSmrg    if (!SafeReadSymbol(table, br, &index)) {
89026fa459cSmrg      return BROTLI_FALSE;
89126fa459cSmrg    }
89226fa459cSmrg  } else {
89326fa459cSmrg    index = s->block_length_index;
89426fa459cSmrg  }
89526fa459cSmrg  {
89626fa459cSmrg    uint32_t bits;
89726fa459cSmrg    uint32_t nbits = _kBrotliPrefixCodeRanges[index].nbits;
89826fa459cSmrg    uint32_t offset = _kBrotliPrefixCodeRanges[index].offset;
89926fa459cSmrg    if (!BrotliSafeReadBits(br, nbits, &bits)) {
90026fa459cSmrg      s->block_length_index = index;
90126fa459cSmrg      s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX;
90226fa459cSmrg      return BROTLI_FALSE;
90326fa459cSmrg    }
90426fa459cSmrg    *result = offset + bits;
90526fa459cSmrg    s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
90626fa459cSmrg    return BROTLI_TRUE;
90726fa459cSmrg  }
90826fa459cSmrg}
90926fa459cSmrg
91026fa459cSmrg/* Transform:
91126fa459cSmrg    1) initialize list L with values 0, 1,... 255
91226fa459cSmrg    2) For each input element X:
91326fa459cSmrg    2.1) let Y = L[X]
91426fa459cSmrg    2.2) remove X-th element from L
91526fa459cSmrg    2.3) prepend Y to L
91626fa459cSmrg    2.4) append Y to output
91726fa459cSmrg
91826fa459cSmrg   In most cases max(Y) <= 7, so most of L remains intact.
91926fa459cSmrg   To reduce the cost of initialization, we reuse L, remember the upper bound
92026fa459cSmrg   of Y values, and reinitialize only first elements in L.
92126fa459cSmrg
92226fa459cSmrg   Most of input values are 0 and 1. To reduce number of branches, we replace
92326fa459cSmrg   inner for loop with do-while. */
92426fa459cSmrgstatic BROTLI_NOINLINE void InverseMoveToFrontTransform(
92526fa459cSmrg    uint8_t* v, uint32_t v_len, BrotliDecoderState* state) {
92626fa459cSmrg  /* Reinitialize elements that could have been changed. */
92726fa459cSmrg  uint32_t i = 1;
92826fa459cSmrg  uint32_t upper_bound = state->mtf_upper_bound;
92926fa459cSmrg  uint32_t* mtf = &state->mtf[1];  /* Make mtf[-1] addressable. */
93026fa459cSmrg  uint8_t* mtf_u8 = (uint8_t*)mtf;
93126fa459cSmrg  /* Load endian-aware constant. */
93226fa459cSmrg  const uint8_t b0123[4] = {0, 1, 2, 3};
93326fa459cSmrg  uint32_t pattern;
93426fa459cSmrg  memcpy(&pattern, &b0123, 4);
93526fa459cSmrg
93626fa459cSmrg  /* Initialize list using 4 consequent values pattern. */
93726fa459cSmrg  mtf[0] = pattern;
93826fa459cSmrg  do {
93926fa459cSmrg    pattern += 0x04040404;  /* Advance all 4 values by 4. */
94026fa459cSmrg    mtf[i] = pattern;
94126fa459cSmrg    i++;
94226fa459cSmrg  } while (i <= upper_bound);
94326fa459cSmrg
94426fa459cSmrg  /* Transform the input. */
94526fa459cSmrg  upper_bound = 0;
94626fa459cSmrg  for (i = 0; i < v_len; ++i) {
94726fa459cSmrg    int index = v[i];
94826fa459cSmrg    uint8_t value = mtf_u8[index];
94926fa459cSmrg    upper_bound |= v[i];
95026fa459cSmrg    v[i] = value;
95126fa459cSmrg    mtf_u8[-1] = value;
95226fa459cSmrg    do {
95326fa459cSmrg      index--;
95426fa459cSmrg      mtf_u8[index + 1] = mtf_u8[index];
95526fa459cSmrg    } while (index >= 0);
95626fa459cSmrg  }
95726fa459cSmrg  /* Remember amount of elements to be reinitialized. */
95826fa459cSmrg  state->mtf_upper_bound = upper_bound >> 2;
95926fa459cSmrg}
96026fa459cSmrg
96126fa459cSmrg/* Decodes a series of Huffman table using ReadHuffmanCode function. */
96226fa459cSmrgstatic BrotliDecoderErrorCode HuffmanTreeGroupDecode(
96326fa459cSmrg    HuffmanTreeGroup* group, BrotliDecoderState* s) {
96426fa459cSmrg  BrotliMetablockHeaderArena* h = &s->arena.header;
96526fa459cSmrg  if (h->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) {
96626fa459cSmrg    h->next = group->codes;
96726fa459cSmrg    h->htree_index = 0;
96826fa459cSmrg    h->substate_tree_group = BROTLI_STATE_TREE_GROUP_LOOP;
96926fa459cSmrg  }
97026fa459cSmrg  while (h->htree_index < group->num_htrees) {
97126fa459cSmrg    uint32_t table_size;
97226fa459cSmrg    BrotliDecoderErrorCode result = ReadHuffmanCode(group->alphabet_size_max,
97326fa459cSmrg        group->alphabet_size_limit, h->next, &table_size, s);
97426fa459cSmrg    if (result != BROTLI_DECODER_SUCCESS) return result;
97526fa459cSmrg    group->htrees[h->htree_index] = h->next;
97626fa459cSmrg    h->next += table_size;
97726fa459cSmrg    ++h->htree_index;
97826fa459cSmrg  }
97926fa459cSmrg  h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
98026fa459cSmrg  return BROTLI_DECODER_SUCCESS;
98126fa459cSmrg}
98226fa459cSmrg
98326fa459cSmrg/* Decodes a context map.
98426fa459cSmrg   Decoding is done in 4 phases:
98526fa459cSmrg    1) Read auxiliary information (6..16 bits) and allocate memory.
98626fa459cSmrg       In case of trivial context map, decoding is finished at this phase.
98726fa459cSmrg    2) Decode Huffman table using ReadHuffmanCode function.
98826fa459cSmrg       This table will be used for reading context map items.
98926fa459cSmrg    3) Read context map items; "0" values could be run-length encoded.
99026fa459cSmrg    4) Optionally, apply InverseMoveToFront transform to the resulting map. */
99126fa459cSmrgstatic BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size,
99226fa459cSmrg                                               uint32_t* num_htrees,
99326fa459cSmrg                                               uint8_t** context_map_arg,
99426fa459cSmrg                                               BrotliDecoderState* s) {
99526fa459cSmrg  BrotliBitReader* br = &s->br;
99626fa459cSmrg  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
99726fa459cSmrg  BrotliMetablockHeaderArena* h = &s->arena.header;
99826fa459cSmrg
99926fa459cSmrg  switch ((int)h->substate_context_map) {
100026fa459cSmrg    case BROTLI_STATE_CONTEXT_MAP_NONE:
100126fa459cSmrg      result = DecodeVarLenUint8(s, br, num_htrees);
100226fa459cSmrg      if (result != BROTLI_DECODER_SUCCESS) {
100326fa459cSmrg        return result;
100426fa459cSmrg      }
100526fa459cSmrg      (*num_htrees)++;
100626fa459cSmrg      h->context_index = 0;
100726fa459cSmrg      BROTLI_LOG_UINT(context_map_size);
100826fa459cSmrg      BROTLI_LOG_UINT(*num_htrees);
100926fa459cSmrg      *context_map_arg =
101026fa459cSmrg          (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)context_map_size);
101126fa459cSmrg      if (*context_map_arg == 0) {
101226fa459cSmrg        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP);
101326fa459cSmrg      }
101426fa459cSmrg      if (*num_htrees <= 1) {
101526fa459cSmrg        memset(*context_map_arg, 0, (size_t)context_map_size);
101626fa459cSmrg        return BROTLI_DECODER_SUCCESS;
101726fa459cSmrg      }
101826fa459cSmrg      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
101926fa459cSmrg    /* Fall through. */
102026fa459cSmrg
102126fa459cSmrg    case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: {
102226fa459cSmrg      uint32_t bits;
102326fa459cSmrg      /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe
102426fa459cSmrg         to peek 4 bits ahead. */
102526fa459cSmrg      if (!BrotliSafeGetBits(br, 5, &bits)) {
102626fa459cSmrg        return BROTLI_DECODER_NEEDS_MORE_INPUT;
102726fa459cSmrg      }
102826fa459cSmrg      if ((bits & 1) != 0) { /* Use RLE for zeros. */
102926fa459cSmrg        h->max_run_length_prefix = (bits >> 1) + 1;
103026fa459cSmrg        BrotliDropBits(br, 5);
103126fa459cSmrg      } else {
103226fa459cSmrg        h->max_run_length_prefix = 0;
103326fa459cSmrg        BrotliDropBits(br, 1);
103426fa459cSmrg      }
103526fa459cSmrg      BROTLI_LOG_UINT(h->max_run_length_prefix);
103626fa459cSmrg      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN;
103726fa459cSmrg    }
103826fa459cSmrg    /* Fall through. */
103926fa459cSmrg
104026fa459cSmrg    case BROTLI_STATE_CONTEXT_MAP_HUFFMAN: {
104126fa459cSmrg      uint32_t alphabet_size = *num_htrees + h->max_run_length_prefix;
104226fa459cSmrg      result = ReadHuffmanCode(alphabet_size, alphabet_size,
104326fa459cSmrg                               h->context_map_table, NULL, s);
104426fa459cSmrg      if (result != BROTLI_DECODER_SUCCESS) return result;
104526fa459cSmrg      h->code = 0xFFFF;
104626fa459cSmrg      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE;
104726fa459cSmrg    }
104826fa459cSmrg    /* Fall through. */
104926fa459cSmrg
105026fa459cSmrg    case BROTLI_STATE_CONTEXT_MAP_DECODE: {
105126fa459cSmrg      uint32_t context_index = h->context_index;
105226fa459cSmrg      uint32_t max_run_length_prefix = h->max_run_length_prefix;
105326fa459cSmrg      uint8_t* context_map = *context_map_arg;
105426fa459cSmrg      uint32_t code = h->code;
105526fa459cSmrg      BROTLI_BOOL skip_preamble = (code != 0xFFFF);
105626fa459cSmrg      while (context_index < context_map_size || skip_preamble) {
105726fa459cSmrg        if (!skip_preamble) {
105826fa459cSmrg          if (!SafeReadSymbol(h->context_map_table, br, &code)) {
105926fa459cSmrg            h->code = 0xFFFF;
106026fa459cSmrg            h->context_index = context_index;
106126fa459cSmrg            return BROTLI_DECODER_NEEDS_MORE_INPUT;
106226fa459cSmrg          }
106326fa459cSmrg          BROTLI_LOG_UINT(code);
106426fa459cSmrg
106526fa459cSmrg          if (code == 0) {
106626fa459cSmrg            context_map[context_index++] = 0;
106726fa459cSmrg            continue;
106826fa459cSmrg          }
106926fa459cSmrg          if (code > max_run_length_prefix) {
107026fa459cSmrg            context_map[context_index++] =
107126fa459cSmrg                (uint8_t)(code - max_run_length_prefix);
107226fa459cSmrg            continue;
107326fa459cSmrg          }
107426fa459cSmrg        } else {
107526fa459cSmrg          skip_preamble = BROTLI_FALSE;
107626fa459cSmrg        }
107726fa459cSmrg        /* RLE sub-stage. */
107826fa459cSmrg        {
107926fa459cSmrg          uint32_t reps;
108026fa459cSmrg          if (!BrotliSafeReadBits(br, code, &reps)) {
108126fa459cSmrg            h->code = code;
108226fa459cSmrg            h->context_index = context_index;
108326fa459cSmrg            return BROTLI_DECODER_NEEDS_MORE_INPUT;
108426fa459cSmrg          }
108526fa459cSmrg          reps += 1U << code;
108626fa459cSmrg          BROTLI_LOG_UINT(reps);
108726fa459cSmrg          if (context_index + reps > context_map_size) {
108826fa459cSmrg            return
108926fa459cSmrg                BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT);
109026fa459cSmrg          }
109126fa459cSmrg          do {
109226fa459cSmrg            context_map[context_index++] = 0;
109326fa459cSmrg          } while (--reps);
109426fa459cSmrg        }
109526fa459cSmrg      }
109626fa459cSmrg    }
109726fa459cSmrg    /* Fall through. */
109826fa459cSmrg
109926fa459cSmrg    case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: {
110026fa459cSmrg      uint32_t bits;
110126fa459cSmrg      if (!BrotliSafeReadBits(br, 1, &bits)) {
110226fa459cSmrg        h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
110326fa459cSmrg        return BROTLI_DECODER_NEEDS_MORE_INPUT;
110426fa459cSmrg      }
110526fa459cSmrg      if (bits != 0) {
110626fa459cSmrg        InverseMoveToFrontTransform(*context_map_arg, context_map_size, s);
110726fa459cSmrg      }
110826fa459cSmrg      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
110926fa459cSmrg      return BROTLI_DECODER_SUCCESS;
111026fa459cSmrg    }
111126fa459cSmrg
111226fa459cSmrg    default:
111326fa459cSmrg      return
111426fa459cSmrg          BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
111526fa459cSmrg  }
111626fa459cSmrg}
111726fa459cSmrg
111826fa459cSmrg/* Decodes a command or literal and updates block type ring-buffer.
111926fa459cSmrg   Reads 3..54 bits. */
112026fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength(
112126fa459cSmrg    int safe, BrotliDecoderState* s, int tree_type) {
112226fa459cSmrg  uint32_t max_block_type = s->num_block_types[tree_type];
112326fa459cSmrg  const HuffmanCode* type_tree = &s->block_type_trees[
112426fa459cSmrg      tree_type * BROTLI_HUFFMAN_MAX_SIZE_258];
112526fa459cSmrg  const HuffmanCode* len_tree = &s->block_len_trees[
112626fa459cSmrg      tree_type * BROTLI_HUFFMAN_MAX_SIZE_26];
112726fa459cSmrg  BrotliBitReader* br = &s->br;
112826fa459cSmrg  uint32_t* ringbuffer = &s->block_type_rb[tree_type * 2];
112926fa459cSmrg  uint32_t block_type;
113026fa459cSmrg  if (max_block_type <= 1) {
113126fa459cSmrg    return BROTLI_FALSE;
113226fa459cSmrg  }
113326fa459cSmrg
113426fa459cSmrg  /* Read 0..15 + 3..39 bits. */
113526fa459cSmrg  if (!safe) {
113626fa459cSmrg    block_type = ReadSymbol(type_tree, br);
113726fa459cSmrg    s->block_length[tree_type] = ReadBlockLength(len_tree, br);
113826fa459cSmrg  } else {
113926fa459cSmrg    BrotliBitReaderState memento;
114026fa459cSmrg    BrotliBitReaderSaveState(br, &memento);
114126fa459cSmrg    if (!SafeReadSymbol(type_tree, br, &block_type)) return BROTLI_FALSE;
114226fa459cSmrg    if (!SafeReadBlockLength(s, &s->block_length[tree_type], len_tree, br)) {
114326fa459cSmrg      s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
114426fa459cSmrg      BrotliBitReaderRestoreState(br, &memento);
114526fa459cSmrg      return BROTLI_FALSE;
114626fa459cSmrg    }
114726fa459cSmrg  }
114826fa459cSmrg
114926fa459cSmrg  if (block_type == 1) {
115026fa459cSmrg    block_type = ringbuffer[1] + 1;
115126fa459cSmrg  } else if (block_type == 0) {
115226fa459cSmrg    block_type = ringbuffer[0];
115326fa459cSmrg  } else {
115426fa459cSmrg    block_type -= 2;
115526fa459cSmrg  }
115626fa459cSmrg  if (block_type >= max_block_type) {
115726fa459cSmrg    block_type -= max_block_type;
115826fa459cSmrg  }
115926fa459cSmrg  ringbuffer[0] = ringbuffer[1];
116026fa459cSmrg  ringbuffer[1] = block_type;
116126fa459cSmrg  return BROTLI_TRUE;
116226fa459cSmrg}
116326fa459cSmrg
116426fa459cSmrgstatic BROTLI_INLINE void DetectTrivialLiteralBlockTypes(
116526fa459cSmrg    BrotliDecoderState* s) {
116626fa459cSmrg  size_t i;
116726fa459cSmrg  for (i = 0; i < 8; ++i) s->trivial_literal_contexts[i] = 0;
116826fa459cSmrg  for (i = 0; i < s->num_block_types[0]; i++) {
116926fa459cSmrg    size_t offset = i << BROTLI_LITERAL_CONTEXT_BITS;
117026fa459cSmrg    size_t error = 0;
117126fa459cSmrg    size_t sample = s->context_map[offset];
117226fa459cSmrg    size_t j;
117326fa459cSmrg    for (j = 0; j < (1u << BROTLI_LITERAL_CONTEXT_BITS);) {
117426fa459cSmrg      BROTLI_REPEAT(4, error |= s->context_map[offset + j++] ^ sample;)
117526fa459cSmrg    }
117626fa459cSmrg    if (error == 0) {
117726fa459cSmrg      s->trivial_literal_contexts[i >> 5] |= 1u << (i & 31);
117826fa459cSmrg    }
117926fa459cSmrg  }
118026fa459cSmrg}
118126fa459cSmrg
118226fa459cSmrgstatic BROTLI_INLINE void PrepareLiteralDecoding(BrotliDecoderState* s) {
118326fa459cSmrg  uint8_t context_mode;
118426fa459cSmrg  size_t trivial;
118526fa459cSmrg  uint32_t block_type = s->block_type_rb[1];
118626fa459cSmrg  uint32_t context_offset = block_type << BROTLI_LITERAL_CONTEXT_BITS;
118726fa459cSmrg  s->context_map_slice = s->context_map + context_offset;
118826fa459cSmrg  trivial = s->trivial_literal_contexts[block_type >> 5];
118926fa459cSmrg  s->trivial_literal_context = (trivial >> (block_type & 31)) & 1;
119026fa459cSmrg  s->literal_htree = s->literal_hgroup.htrees[s->context_map_slice[0]];
119126fa459cSmrg  context_mode = s->context_modes[block_type] & 3;
119226fa459cSmrg  s->context_lookup = BROTLI_CONTEXT_LUT(context_mode);
119326fa459cSmrg}
119426fa459cSmrg
119526fa459cSmrg/* Decodes the block type and updates the state for literal context.
119626fa459cSmrg   Reads 3..54 bits. */
119726fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL DecodeLiteralBlockSwitchInternal(
119826fa459cSmrg    int safe, BrotliDecoderState* s) {
119926fa459cSmrg  if (!DecodeBlockTypeAndLength(safe, s, 0)) {
120026fa459cSmrg    return BROTLI_FALSE;
120126fa459cSmrg  }
120226fa459cSmrg  PrepareLiteralDecoding(s);
120326fa459cSmrg  return BROTLI_TRUE;
120426fa459cSmrg}
120526fa459cSmrg
120626fa459cSmrgstatic void BROTLI_NOINLINE DecodeLiteralBlockSwitch(BrotliDecoderState* s) {
120726fa459cSmrg  DecodeLiteralBlockSwitchInternal(0, s);
120826fa459cSmrg}
120926fa459cSmrg
121026fa459cSmrgstatic BROTLI_BOOL BROTLI_NOINLINE SafeDecodeLiteralBlockSwitch(
121126fa459cSmrg    BrotliDecoderState* s) {
121226fa459cSmrg  return DecodeLiteralBlockSwitchInternal(1, s);
121326fa459cSmrg}
121426fa459cSmrg
121526fa459cSmrg/* Block switch for insert/copy length.
121626fa459cSmrg   Reads 3..54 bits. */
121726fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL DecodeCommandBlockSwitchInternal(
121826fa459cSmrg    int safe, BrotliDecoderState* s) {
121926fa459cSmrg  if (!DecodeBlockTypeAndLength(safe, s, 1)) {
122026fa459cSmrg    return BROTLI_FALSE;
122126fa459cSmrg  }
122226fa459cSmrg  s->htree_command = s->insert_copy_hgroup.htrees[s->block_type_rb[3]];
122326fa459cSmrg  return BROTLI_TRUE;
122426fa459cSmrg}
122526fa459cSmrg
122626fa459cSmrgstatic void BROTLI_NOINLINE DecodeCommandBlockSwitch(BrotliDecoderState* s) {
122726fa459cSmrg  DecodeCommandBlockSwitchInternal(0, s);
122826fa459cSmrg}
122926fa459cSmrg
123026fa459cSmrgstatic BROTLI_BOOL BROTLI_NOINLINE SafeDecodeCommandBlockSwitch(
123126fa459cSmrg    BrotliDecoderState* s) {
123226fa459cSmrg  return DecodeCommandBlockSwitchInternal(1, s);
123326fa459cSmrg}
123426fa459cSmrg
123526fa459cSmrg/* Block switch for distance codes.
123626fa459cSmrg   Reads 3..54 bits. */
123726fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL DecodeDistanceBlockSwitchInternal(
123826fa459cSmrg    int safe, BrotliDecoderState* s) {
123926fa459cSmrg  if (!DecodeBlockTypeAndLength(safe, s, 2)) {
124026fa459cSmrg    return BROTLI_FALSE;
124126fa459cSmrg  }
124226fa459cSmrg  s->dist_context_map_slice = s->dist_context_map +
124326fa459cSmrg      (s->block_type_rb[5] << BROTLI_DISTANCE_CONTEXT_BITS);
124426fa459cSmrg  s->dist_htree_index = s->dist_context_map_slice[s->distance_context];
124526fa459cSmrg  return BROTLI_TRUE;
124626fa459cSmrg}
124726fa459cSmrg
124826fa459cSmrgstatic void BROTLI_NOINLINE DecodeDistanceBlockSwitch(BrotliDecoderState* s) {
124926fa459cSmrg  DecodeDistanceBlockSwitchInternal(0, s);
125026fa459cSmrg}
125126fa459cSmrg
125226fa459cSmrgstatic BROTLI_BOOL BROTLI_NOINLINE SafeDecodeDistanceBlockSwitch(
125326fa459cSmrg    BrotliDecoderState* s) {
125426fa459cSmrg  return DecodeDistanceBlockSwitchInternal(1, s);
125526fa459cSmrg}
125626fa459cSmrg
125726fa459cSmrgstatic size_t UnwrittenBytes(const BrotliDecoderState* s, BROTLI_BOOL wrap) {
125826fa459cSmrg  size_t pos = wrap && s->pos > s->ringbuffer_size ?
125926fa459cSmrg      (size_t)s->ringbuffer_size : (size_t)(s->pos);
126026fa459cSmrg  size_t partial_pos_rb = (s->rb_roundtrips * (size_t)s->ringbuffer_size) + pos;
126126fa459cSmrg  return partial_pos_rb - s->partial_pos_out;
126226fa459cSmrg}
126326fa459cSmrg
126426fa459cSmrg/* Dumps output.
126526fa459cSmrg   Returns BROTLI_DECODER_NEEDS_MORE_OUTPUT only if there is more output to push
126626fa459cSmrg   and either ring-buffer is as big as window size, or |force| is true. */
126726fa459cSmrgstatic BrotliDecoderErrorCode BROTLI_NOINLINE WriteRingBuffer(
126826fa459cSmrg    BrotliDecoderState* s, size_t* available_out, uint8_t** next_out,
126926fa459cSmrg    size_t* total_out, BROTLI_BOOL force) {
127026fa459cSmrg  uint8_t* start =
127126fa459cSmrg      s->ringbuffer + (s->partial_pos_out & (size_t)s->ringbuffer_mask);
127226fa459cSmrg  size_t to_write = UnwrittenBytes(s, BROTLI_TRUE);
127326fa459cSmrg  size_t num_written = *available_out;
127426fa459cSmrg  if (num_written > to_write) {
127526fa459cSmrg    num_written = to_write;
127626fa459cSmrg  }
127726fa459cSmrg  if (s->meta_block_remaining_len < 0) {
127826fa459cSmrg    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1);
127926fa459cSmrg  }
128026fa459cSmrg  if (next_out && !*next_out) {
128126fa459cSmrg    *next_out = start;
128226fa459cSmrg  } else {
128326fa459cSmrg    if (next_out) {
128426fa459cSmrg      memcpy(*next_out, start, num_written);
128526fa459cSmrg      *next_out += num_written;
128626fa459cSmrg    }
128726fa459cSmrg  }
128826fa459cSmrg  *available_out -= num_written;
128926fa459cSmrg  BROTLI_LOG_UINT(to_write);
129026fa459cSmrg  BROTLI_LOG_UINT(num_written);
129126fa459cSmrg  s->partial_pos_out += num_written;
129226fa459cSmrg  if (total_out) {
129326fa459cSmrg    *total_out = s->partial_pos_out;
129426fa459cSmrg  }
129526fa459cSmrg  if (num_written < to_write) {
129626fa459cSmrg    if (s->ringbuffer_size == (1 << s->window_bits) || force) {
129726fa459cSmrg      return BROTLI_DECODER_NEEDS_MORE_OUTPUT;
129826fa459cSmrg    } else {
129926fa459cSmrg      return BROTLI_DECODER_SUCCESS;
130026fa459cSmrg    }
130126fa459cSmrg  }
130226fa459cSmrg  /* Wrap ring buffer only if it has reached its maximal size. */
130326fa459cSmrg  if (s->ringbuffer_size == (1 << s->window_bits) &&
130426fa459cSmrg      s->pos >= s->ringbuffer_size) {
130526fa459cSmrg    s->pos -= s->ringbuffer_size;
130626fa459cSmrg    s->rb_roundtrips++;
130726fa459cSmrg    s->should_wrap_ringbuffer = (size_t)s->pos != 0 ? 1 : 0;
130826fa459cSmrg  }
130926fa459cSmrg  return BROTLI_DECODER_SUCCESS;
131026fa459cSmrg}
131126fa459cSmrg
131226fa459cSmrgstatic void BROTLI_NOINLINE WrapRingBuffer(BrotliDecoderState* s) {
131326fa459cSmrg  if (s->should_wrap_ringbuffer) {
131426fa459cSmrg    memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos);
131526fa459cSmrg    s->should_wrap_ringbuffer = 0;
131626fa459cSmrg  }
131726fa459cSmrg}
131826fa459cSmrg
131926fa459cSmrg/* Allocates ring-buffer.
132026fa459cSmrg
132126fa459cSmrg   s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
132226fa459cSmrg   this function is called.
132326fa459cSmrg
132426fa459cSmrg   Last two bytes of ring-buffer are initialized to 0, so context calculation
132526fa459cSmrg   could be done uniformly for the first two and all other positions. */
132626fa459cSmrgstatic BROTLI_BOOL BROTLI_NOINLINE BrotliEnsureRingBuffer(
132726fa459cSmrg    BrotliDecoderState* s) {
132826fa459cSmrg  uint8_t* old_ringbuffer = s->ringbuffer;
132926fa459cSmrg  if (s->ringbuffer_size == s->new_ringbuffer_size) {
133026fa459cSmrg    return BROTLI_TRUE;
133126fa459cSmrg  }
133226fa459cSmrg
133326fa459cSmrg  s->ringbuffer = (uint8_t*)BROTLI_DECODER_ALLOC(s,
133426fa459cSmrg      (size_t)(s->new_ringbuffer_size) + kRingBufferWriteAheadSlack);
133526fa459cSmrg  if (s->ringbuffer == 0) {
133626fa459cSmrg    /* Restore previous value. */
133726fa459cSmrg    s->ringbuffer = old_ringbuffer;
133826fa459cSmrg    return BROTLI_FALSE;
133926fa459cSmrg  }
134026fa459cSmrg  s->ringbuffer[s->new_ringbuffer_size - 2] = 0;
134126fa459cSmrg  s->ringbuffer[s->new_ringbuffer_size - 1] = 0;
134226fa459cSmrg
134326fa459cSmrg  if (!!old_ringbuffer) {
134426fa459cSmrg    memcpy(s->ringbuffer, old_ringbuffer, (size_t)s->pos);
134526fa459cSmrg    BROTLI_DECODER_FREE(s, old_ringbuffer);
134626fa459cSmrg  }
134726fa459cSmrg
134826fa459cSmrg  s->ringbuffer_size = s->new_ringbuffer_size;
134926fa459cSmrg  s->ringbuffer_mask = s->new_ringbuffer_size - 1;
135026fa459cSmrg  s->ringbuffer_end = s->ringbuffer + s->ringbuffer_size;
135126fa459cSmrg
135226fa459cSmrg  return BROTLI_TRUE;
135326fa459cSmrg}
135426fa459cSmrg
135526fa459cSmrgstatic BrotliDecoderErrorCode BROTLI_NOINLINE CopyUncompressedBlockToOutput(
135626fa459cSmrg    size_t* available_out, uint8_t** next_out, size_t* total_out,
135726fa459cSmrg    BrotliDecoderState* s) {
135826fa459cSmrg  /* TODO: avoid allocation for single uncompressed block. */
135926fa459cSmrg  if (!BrotliEnsureRingBuffer(s)) {
136026fa459cSmrg    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1);
136126fa459cSmrg  }
136226fa459cSmrg
136326fa459cSmrg  /* State machine */
136426fa459cSmrg  for (;;) {
136526fa459cSmrg    switch (s->substate_uncompressed) {
136626fa459cSmrg      case BROTLI_STATE_UNCOMPRESSED_NONE: {
136726fa459cSmrg        int nbytes = (int)BrotliGetRemainingBytes(&s->br);
136826fa459cSmrg        if (nbytes > s->meta_block_remaining_len) {
136926fa459cSmrg          nbytes = s->meta_block_remaining_len;
137026fa459cSmrg        }
137126fa459cSmrg        if (s->pos + nbytes > s->ringbuffer_size) {
137226fa459cSmrg          nbytes = s->ringbuffer_size - s->pos;
137326fa459cSmrg        }
137426fa459cSmrg        /* Copy remaining bytes from s->br.buf_ to ring-buffer. */
137526fa459cSmrg        BrotliCopyBytes(&s->ringbuffer[s->pos], &s->br, (size_t)nbytes);
137626fa459cSmrg        s->pos += nbytes;
137726fa459cSmrg        s->meta_block_remaining_len -= nbytes;
137826fa459cSmrg        if (s->pos < 1 << s->window_bits) {
137926fa459cSmrg          if (s->meta_block_remaining_len == 0) {
138026fa459cSmrg            return BROTLI_DECODER_SUCCESS;
138126fa459cSmrg          }
138226fa459cSmrg          return BROTLI_DECODER_NEEDS_MORE_INPUT;
138326fa459cSmrg        }
138426fa459cSmrg        s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_WRITE;
138526fa459cSmrg      }
138626fa459cSmrg      /* Fall through. */
138726fa459cSmrg
138826fa459cSmrg      case BROTLI_STATE_UNCOMPRESSED_WRITE: {
138926fa459cSmrg        BrotliDecoderErrorCode result;
139026fa459cSmrg        result = WriteRingBuffer(
139126fa459cSmrg            s, available_out, next_out, total_out, BROTLI_FALSE);
139226fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
139326fa459cSmrg          return result;
139426fa459cSmrg        }
139526fa459cSmrg        if (s->ringbuffer_size == 1 << s->window_bits) {
139626fa459cSmrg          s->max_distance = s->max_backward_distance;
139726fa459cSmrg        }
139826fa459cSmrg        s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE;
139926fa459cSmrg        break;
140026fa459cSmrg      }
140126fa459cSmrg    }
140226fa459cSmrg  }
140326fa459cSmrg  BROTLI_DCHECK(0);  /* Unreachable */
140426fa459cSmrg}
140526fa459cSmrg
140626fa459cSmrg/* Calculates the smallest feasible ring buffer.
140726fa459cSmrg
140826fa459cSmrg   If we know the data size is small, do not allocate more ring buffer
140926fa459cSmrg   size than needed to reduce memory usage.
141026fa459cSmrg
141126fa459cSmrg   When this method is called, metablock size and flags MUST be decoded. */
141226fa459cSmrgstatic void BROTLI_NOINLINE BrotliCalculateRingBufferSize(
141326fa459cSmrg    BrotliDecoderState* s) {
141426fa459cSmrg  int window_size = 1 << s->window_bits;
141526fa459cSmrg  int new_ringbuffer_size = window_size;
141626fa459cSmrg  /* We need at least 2 bytes of ring buffer size to get the last two
141726fa459cSmrg     bytes for context from there */
141826fa459cSmrg  int min_size = s->ringbuffer_size ? s->ringbuffer_size : 1024;
141926fa459cSmrg  int output_size;
142026fa459cSmrg
142126fa459cSmrg  /* If maximum is already reached, no further extension is retired. */
142226fa459cSmrg  if (s->ringbuffer_size == window_size) {
142326fa459cSmrg    return;
142426fa459cSmrg  }
142526fa459cSmrg
142626fa459cSmrg  /* Metadata blocks does not touch ring buffer. */
142726fa459cSmrg  if (s->is_metadata) {
142826fa459cSmrg    return;
142926fa459cSmrg  }
143026fa459cSmrg
143126fa459cSmrg  if (!s->ringbuffer) {
143226fa459cSmrg    output_size = 0;
143326fa459cSmrg  } else {
143426fa459cSmrg    output_size = s->pos;
143526fa459cSmrg  }
143626fa459cSmrg  output_size += s->meta_block_remaining_len;
143726fa459cSmrg  min_size = min_size < output_size ? output_size : min_size;
143826fa459cSmrg
143926fa459cSmrg  if (!!s->canny_ringbuffer_allocation) {
144026fa459cSmrg    /* Reduce ring buffer size to save memory when server is unscrupulous.
144126fa459cSmrg       In worst case memory usage might be 1.5x bigger for a short period of
144226fa459cSmrg       ring buffer reallocation. */
144326fa459cSmrg    while ((new_ringbuffer_size >> 1) >= min_size) {
144426fa459cSmrg      new_ringbuffer_size >>= 1;
144526fa459cSmrg    }
144626fa459cSmrg  }
144726fa459cSmrg
144826fa459cSmrg  s->new_ringbuffer_size = new_ringbuffer_size;
144926fa459cSmrg}
145026fa459cSmrg
145126fa459cSmrg/* Reads 1..256 2-bit context modes. */
145226fa459cSmrgstatic BrotliDecoderErrorCode ReadContextModes(BrotliDecoderState* s) {
145326fa459cSmrg  BrotliBitReader* br = &s->br;
145426fa459cSmrg  int i = s->loop_counter;
145526fa459cSmrg
145626fa459cSmrg  while (i < (int)s->num_block_types[0]) {
145726fa459cSmrg    uint32_t bits;
145826fa459cSmrg    if (!BrotliSafeReadBits(br, 2, &bits)) {
145926fa459cSmrg      s->loop_counter = i;
146026fa459cSmrg      return BROTLI_DECODER_NEEDS_MORE_INPUT;
146126fa459cSmrg    }
146226fa459cSmrg    s->context_modes[i] = (uint8_t)bits;
146326fa459cSmrg    BROTLI_LOG_ARRAY_INDEX(s->context_modes, i);
146426fa459cSmrg    i++;
146526fa459cSmrg  }
146626fa459cSmrg  return BROTLI_DECODER_SUCCESS;
146726fa459cSmrg}
146826fa459cSmrg
146926fa459cSmrgstatic BROTLI_INLINE void TakeDistanceFromRingBuffer(BrotliDecoderState* s) {
147026fa459cSmrg  int offset = s->distance_code - 3;
147126fa459cSmrg  if (s->distance_code <= 3) {
147226fa459cSmrg    /* Compensate double distance-ring-buffer roll for dictionary items. */
147326fa459cSmrg    s->distance_context = 1 >> s->distance_code;
147426fa459cSmrg    s->distance_code = s->dist_rb[(s->dist_rb_idx - offset) & 3];
147526fa459cSmrg    s->dist_rb_idx -= s->distance_context;
147626fa459cSmrg  } else {
147726fa459cSmrg    int index_delta = 3;
147826fa459cSmrg    int delta;
147926fa459cSmrg    int base = s->distance_code - 10;
148026fa459cSmrg    if (s->distance_code < 10) {
148126fa459cSmrg      base = s->distance_code - 4;
148226fa459cSmrg    } else {
148326fa459cSmrg      index_delta = 2;
148426fa459cSmrg    }
148526fa459cSmrg    /* Unpack one of six 4-bit values. */
148626fa459cSmrg    delta = ((0x605142 >> (4 * base)) & 0xF) - 3;
148726fa459cSmrg    s->distance_code = s->dist_rb[(s->dist_rb_idx + index_delta) & 0x3] + delta;
148826fa459cSmrg    if (s->distance_code <= 0) {
148926fa459cSmrg      /* A huge distance will cause a BROTLI_FAILURE() soon.
149026fa459cSmrg         This is a little faster than failing here. */
149126fa459cSmrg      s->distance_code = 0x7FFFFFFF;
149226fa459cSmrg    }
149326fa459cSmrg  }
149426fa459cSmrg}
149526fa459cSmrg
149626fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL SafeReadBits(
149726fa459cSmrg    BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
149826fa459cSmrg  if (n_bits != 0) {
149926fa459cSmrg    return BrotliSafeReadBits(br, n_bits, val);
150026fa459cSmrg  } else {
150126fa459cSmrg    *val = 0;
150226fa459cSmrg    return BROTLI_TRUE;
150326fa459cSmrg  }
150426fa459cSmrg}
150526fa459cSmrg
150626fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL SafeReadBits32(
150726fa459cSmrg    BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
150826fa459cSmrg  if (n_bits != 0) {
150926fa459cSmrg    return BrotliSafeReadBits32(br, n_bits, val);
151026fa459cSmrg  } else {
151126fa459cSmrg    *val = 0;
151226fa459cSmrg    return BROTLI_TRUE;
151326fa459cSmrg  }
151426fa459cSmrg}
151526fa459cSmrg
151626fa459cSmrg/*
151726fa459cSmrg   RFC 7932 Section 4 with "..." shortenings and "[]" emendations.
151826fa459cSmrg
151926fa459cSmrg   Each distance ... is represented with a pair <distance code, extra bits>...
152026fa459cSmrg   The distance code is encoded using a prefix code... The number of extra bits
152126fa459cSmrg   can be 0..24... Two additional parameters: NPOSTFIX (0..3), and ...
152226fa459cSmrg   NDIRECT (0..120) ... are encoded in the meta-block header...
152326fa459cSmrg
152426fa459cSmrg   The first 16 distance symbols ... reference past distances... ring buffer ...
152526fa459cSmrg   Next NDIRECT distance symbols ... represent distances from 1 to NDIRECT...
152626fa459cSmrg   [For] distance symbols 16 + NDIRECT and greater ... the number of extra bits
152726fa459cSmrg   ... is given by the following formula:
152826fa459cSmrg
152926fa459cSmrg   [ xcode = dcode - NDIRECT - 16 ]
153026fa459cSmrg   ndistbits = 1 + [ xcode ] >> (NPOSTFIX + 1)
153126fa459cSmrg
153226fa459cSmrg   ...
153326fa459cSmrg*/
153426fa459cSmrg
153526fa459cSmrg/*
153626fa459cSmrg   RFC 7932 Section 9.2 with "..." shortenings and "[]" emendations.
153726fa459cSmrg
153826fa459cSmrg   ... to get the actual value of the parameter NDIRECT, left-shift this
153926fa459cSmrg   four-bit number by NPOSTFIX bits ...
154026fa459cSmrg*/
154126fa459cSmrg
154226fa459cSmrg/* Remaining formulas from RFC 7932 Section 4 could be rewritten as following:
154326fa459cSmrg
154426fa459cSmrg     alphabet_size = 16 + NDIRECT + (max_distbits << (NPOSTFIX + 1))
154526fa459cSmrg
154626fa459cSmrg     half = ((xcode >> NPOSTFIX) & 1) << ndistbits
154726fa459cSmrg     postfix = xcode & ((1 << NPOSTFIX) - 1)
154826fa459cSmrg     range_start = 2 * (1 << ndistbits - 1 - 1)
154926fa459cSmrg
155026fa459cSmrg     distance = (range_start + half + extra) << NPOSTFIX + postfix + NDIRECT + 1
155126fa459cSmrg
155226fa459cSmrg   NB: ndistbits >= 1 -> range_start >= 0
155326fa459cSmrg   NB: range_start has factor 2, as the range is covered by 2 "halves"
155426fa459cSmrg   NB: extra -1 offset in range_start formula covers the absence of
155526fa459cSmrg       ndistbits = 0 case
155626fa459cSmrg   NB: when NPOSTFIX = 0, NDIRECT is not greater than 15
155726fa459cSmrg
155826fa459cSmrg   In other words, xcode has the following binary structure - XXXHPPP:
155926fa459cSmrg    - XXX represent the number of extra distance bits
156026fa459cSmrg    - H selects upper / lower range of distances
156126fa459cSmrg    - PPP represent "postfix"
156226fa459cSmrg
156326fa459cSmrg  "Regular" distance encoding has NPOSTFIX = 0; omitting the postfix part
156426fa459cSmrg  simplifies distance calculation.
156526fa459cSmrg
156626fa459cSmrg  Using NPOSTFIX > 0 allows cheaper encoding of regular structures, e.g. where
156726fa459cSmrg  most of distances have the same reminder of division by 2/4/8. For example,
156826fa459cSmrg  the table of int32_t values that come from different sources; if it is likely
156926fa459cSmrg  that 3 highest bytes of values from the same source are the same, then
157026fa459cSmrg  copy distance often looks like 4x + y.
157126fa459cSmrg
157226fa459cSmrg  Distance calculation could be rewritten to:
157326fa459cSmrg
157426fa459cSmrg    ndistbits = NDISTBITS(NDIRECT, NPOSTFIX)[dcode]
157526fa459cSmrg    distance = OFFSET(NDIRECT, NPOSTFIX)[dcode] + extra << NPOSTFIX
157626fa459cSmrg
157726fa459cSmrg  NDISTBITS and OFFSET could be pre-calculated, as NDIRECT and NPOSTFIX could
157826fa459cSmrg  change only once per meta-block.
157926fa459cSmrg*/
158026fa459cSmrg
158126fa459cSmrg/* Calculates distance lookup table.
158226fa459cSmrg   NB: it is possible to have all 64 tables precalculated. */
158326fa459cSmrgstatic void CalculateDistanceLut(BrotliDecoderState* s) {
158426fa459cSmrg  BrotliMetablockBodyArena* b = &s->arena.body;
158526fa459cSmrg  uint32_t npostfix = s->distance_postfix_bits;
158626fa459cSmrg  uint32_t ndirect = s->num_direct_distance_codes;
158726fa459cSmrg  uint32_t alphabet_size_limit = s->distance_hgroup.alphabet_size_limit;
158826fa459cSmrg  uint32_t postfix = 1u << npostfix;
158926fa459cSmrg  uint32_t j;
159026fa459cSmrg  uint32_t bits = 1;
159126fa459cSmrg  uint32_t half = 0;
159226fa459cSmrg
159326fa459cSmrg  /* Skip short codes. */
159426fa459cSmrg  uint32_t i = BROTLI_NUM_DISTANCE_SHORT_CODES;
159526fa459cSmrg
159626fa459cSmrg  /* Fill direct codes. */
159726fa459cSmrg  for (j = 0; j < ndirect; ++j) {
159826fa459cSmrg    b->dist_extra_bits[i] = 0;
159926fa459cSmrg    b->dist_offset[i] = j + 1;
160026fa459cSmrg    ++i;
160126fa459cSmrg  }
160226fa459cSmrg
160326fa459cSmrg  /* Fill regular distance codes. */
160426fa459cSmrg  while (i < alphabet_size_limit) {
160526fa459cSmrg    uint32_t base = ndirect + ((((2 + half) << bits) - 4) << npostfix) + 1;
160626fa459cSmrg    /* Always fill the complete group. */
160726fa459cSmrg    for (j = 0; j < postfix; ++j) {
160826fa459cSmrg      b->dist_extra_bits[i] = (uint8_t)bits;
160926fa459cSmrg      b->dist_offset[i] = base + j;
161026fa459cSmrg      ++i;
161126fa459cSmrg    }
161226fa459cSmrg    bits = bits + half;
161326fa459cSmrg    half = half ^ 1;
161426fa459cSmrg  }
161526fa459cSmrg}
161626fa459cSmrg
161726fa459cSmrg/* Precondition: s->distance_code < 0. */
161826fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL ReadDistanceInternal(
161926fa459cSmrg    int safe, BrotliDecoderState* s, BrotliBitReader* br) {
162026fa459cSmrg  BrotliMetablockBodyArena* b = &s->arena.body;
162126fa459cSmrg  uint32_t code;
162226fa459cSmrg  uint32_t bits;
162326fa459cSmrg  BrotliBitReaderState memento;
162426fa459cSmrg  HuffmanCode* distance_tree = s->distance_hgroup.htrees[s->dist_htree_index];
162526fa459cSmrg  if (!safe) {
162626fa459cSmrg    code = ReadSymbol(distance_tree, br);
162726fa459cSmrg  } else {
162826fa459cSmrg    BrotliBitReaderSaveState(br, &memento);
162926fa459cSmrg    if (!SafeReadSymbol(distance_tree, br, &code)) {
163026fa459cSmrg      return BROTLI_FALSE;
163126fa459cSmrg    }
163226fa459cSmrg  }
163326fa459cSmrg  --s->block_length[2];
163426fa459cSmrg  /* Convert the distance code to the actual distance by possibly
163526fa459cSmrg     looking up past distances from the s->dist_rb. */
163626fa459cSmrg  s->distance_context = 0;
163726fa459cSmrg  if ((code & ~0xFu) == 0) {
163826fa459cSmrg    s->distance_code = (int)code;
163926fa459cSmrg    TakeDistanceFromRingBuffer(s);
164026fa459cSmrg    return BROTLI_TRUE;
164126fa459cSmrg  }
164226fa459cSmrg  if (!safe) {
164326fa459cSmrg    bits = BrotliReadBits32(br, b->dist_extra_bits[code]);
164426fa459cSmrg  } else {
164526fa459cSmrg    if (!SafeReadBits32(br, b->dist_extra_bits[code], &bits)) {
164626fa459cSmrg      ++s->block_length[2];
164726fa459cSmrg      BrotliBitReaderRestoreState(br, &memento);
164826fa459cSmrg      return BROTLI_FALSE;
164926fa459cSmrg    }
165026fa459cSmrg  }
165126fa459cSmrg  s->distance_code =
165226fa459cSmrg      (int)(b->dist_offset[code] + (bits << s->distance_postfix_bits));
165326fa459cSmrg  return BROTLI_TRUE;
165426fa459cSmrg}
165526fa459cSmrg
165626fa459cSmrgstatic BROTLI_INLINE void ReadDistance(
165726fa459cSmrg    BrotliDecoderState* s, BrotliBitReader* br) {
165826fa459cSmrg  ReadDistanceInternal(0, s, br);
165926fa459cSmrg}
166026fa459cSmrg
166126fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL SafeReadDistance(
166226fa459cSmrg    BrotliDecoderState* s, BrotliBitReader* br) {
166326fa459cSmrg  return ReadDistanceInternal(1, s, br);
166426fa459cSmrg}
166526fa459cSmrg
166626fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL ReadCommandInternal(
166726fa459cSmrg    int safe, BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
166826fa459cSmrg  uint32_t cmd_code;
166926fa459cSmrg  uint32_t insert_len_extra = 0;
167026fa459cSmrg  uint32_t copy_length;
167126fa459cSmrg  CmdLutElement v;
167226fa459cSmrg  BrotliBitReaderState memento;
167326fa459cSmrg  if (!safe) {
167426fa459cSmrg    cmd_code = ReadSymbol(s->htree_command, br);
167526fa459cSmrg  } else {
167626fa459cSmrg    BrotliBitReaderSaveState(br, &memento);
167726fa459cSmrg    if (!SafeReadSymbol(s->htree_command, br, &cmd_code)) {
167826fa459cSmrg      return BROTLI_FALSE;
167926fa459cSmrg    }
168026fa459cSmrg  }
168126fa459cSmrg  v = kCmdLut[cmd_code];
168226fa459cSmrg  s->distance_code = v.distance_code;
168326fa459cSmrg  s->distance_context = v.context;
168426fa459cSmrg  s->dist_htree_index = s->dist_context_map_slice[s->distance_context];
168526fa459cSmrg  *insert_length = v.insert_len_offset;
168626fa459cSmrg  if (!safe) {
168726fa459cSmrg    if (BROTLI_PREDICT_FALSE(v.insert_len_extra_bits != 0)) {
168826fa459cSmrg      insert_len_extra = BrotliReadBits24(br, v.insert_len_extra_bits);
168926fa459cSmrg    }
169026fa459cSmrg    copy_length = BrotliReadBits24(br, v.copy_len_extra_bits);
169126fa459cSmrg  } else {
169226fa459cSmrg    if (!SafeReadBits(br, v.insert_len_extra_bits, &insert_len_extra) ||
169326fa459cSmrg        !SafeReadBits(br, v.copy_len_extra_bits, &copy_length)) {
169426fa459cSmrg      BrotliBitReaderRestoreState(br, &memento);
169526fa459cSmrg      return BROTLI_FALSE;
169626fa459cSmrg    }
169726fa459cSmrg  }
169826fa459cSmrg  s->copy_length = (int)copy_length + v.copy_len_offset;
169926fa459cSmrg  --s->block_length[1];
170026fa459cSmrg  *insert_length += (int)insert_len_extra;
170126fa459cSmrg  return BROTLI_TRUE;
170226fa459cSmrg}
170326fa459cSmrg
170426fa459cSmrgstatic BROTLI_INLINE void ReadCommand(
170526fa459cSmrg    BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
170626fa459cSmrg  ReadCommandInternal(0, s, br, insert_length);
170726fa459cSmrg}
170826fa459cSmrg
170926fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL SafeReadCommand(
171026fa459cSmrg    BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
171126fa459cSmrg  return ReadCommandInternal(1, s, br, insert_length);
171226fa459cSmrg}
171326fa459cSmrg
171426fa459cSmrgstatic BROTLI_INLINE BROTLI_BOOL CheckInputAmount(
171526fa459cSmrg    int safe, BrotliBitReader* const br, size_t num) {
171626fa459cSmrg  if (safe) {
171726fa459cSmrg    return BROTLI_TRUE;
171826fa459cSmrg  }
171926fa459cSmrg  return BrotliCheckInputAmount(br, num);
172026fa459cSmrg}
172126fa459cSmrg
172226fa459cSmrg#define BROTLI_SAFE(METHOD)                       \
172326fa459cSmrg  {                                               \
172426fa459cSmrg    if (safe) {                                   \
172526fa459cSmrg      if (!Safe##METHOD) {                        \
172626fa459cSmrg        result = BROTLI_DECODER_NEEDS_MORE_INPUT; \
172726fa459cSmrg        goto saveStateAndReturn;                  \
172826fa459cSmrg      }                                           \
172926fa459cSmrg    } else {                                      \
173026fa459cSmrg      METHOD;                                     \
173126fa459cSmrg    }                                             \
173226fa459cSmrg  }
173326fa459cSmrg
173426fa459cSmrgstatic BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal(
173526fa459cSmrg    int safe, BrotliDecoderState* s) {
173626fa459cSmrg  int pos = s->pos;
173726fa459cSmrg  int i = s->loop_counter;
173826fa459cSmrg  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
173926fa459cSmrg  BrotliBitReader* br = &s->br;
174026fa459cSmrg
174126fa459cSmrg  if (!CheckInputAmount(safe, br, 28)) {
174226fa459cSmrg    result = BROTLI_DECODER_NEEDS_MORE_INPUT;
174326fa459cSmrg    goto saveStateAndReturn;
174426fa459cSmrg  }
174526fa459cSmrg  if (!safe) {
174626fa459cSmrg    BROTLI_UNUSED(BrotliWarmupBitReader(br));
174726fa459cSmrg  }
174826fa459cSmrg
174926fa459cSmrg  /* Jump into state machine. */
175026fa459cSmrg  if (s->state == BROTLI_STATE_COMMAND_BEGIN) {
175126fa459cSmrg    goto CommandBegin;
175226fa459cSmrg  } else if (s->state == BROTLI_STATE_COMMAND_INNER) {
175326fa459cSmrg    goto CommandInner;
175426fa459cSmrg  } else if (s->state == BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) {
175526fa459cSmrg    goto CommandPostDecodeLiterals;
175626fa459cSmrg  } else if (s->state == BROTLI_STATE_COMMAND_POST_WRAP_COPY) {
175726fa459cSmrg    goto CommandPostWrapCopy;
175826fa459cSmrg  } else {
175926fa459cSmrg    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
176026fa459cSmrg  }
176126fa459cSmrg
176226fa459cSmrgCommandBegin:
176326fa459cSmrg  if (safe) {
176426fa459cSmrg    s->state = BROTLI_STATE_COMMAND_BEGIN;
176526fa459cSmrg  }
176626fa459cSmrg  if (!CheckInputAmount(safe, br, 28)) {  /* 156 bits + 7 bytes */
176726fa459cSmrg    s->state = BROTLI_STATE_COMMAND_BEGIN;
176826fa459cSmrg    result = BROTLI_DECODER_NEEDS_MORE_INPUT;
176926fa459cSmrg    goto saveStateAndReturn;
177026fa459cSmrg  }
177126fa459cSmrg  if (BROTLI_PREDICT_FALSE(s->block_length[1] == 0)) {
177226fa459cSmrg    BROTLI_SAFE(DecodeCommandBlockSwitch(s));
177326fa459cSmrg    goto CommandBegin;
177426fa459cSmrg  }
177526fa459cSmrg  /* Read the insert/copy length in the command. */
177626fa459cSmrg  BROTLI_SAFE(ReadCommand(s, br, &i));
177726fa459cSmrg  BROTLI_LOG(("[ProcessCommandsInternal] pos = %d insert = %d copy = %d\n",
177826fa459cSmrg              pos, i, s->copy_length));
177926fa459cSmrg  if (i == 0) {
178026fa459cSmrg    goto CommandPostDecodeLiterals;
178126fa459cSmrg  }
178226fa459cSmrg  s->meta_block_remaining_len -= i;
178326fa459cSmrg
178426fa459cSmrgCommandInner:
178526fa459cSmrg  if (safe) {
178626fa459cSmrg    s->state = BROTLI_STATE_COMMAND_INNER;
178726fa459cSmrg  }
178826fa459cSmrg  /* Read the literals in the command. */
178926fa459cSmrg  if (s->trivial_literal_context) {
179026fa459cSmrg    uint32_t bits;
179126fa459cSmrg    uint32_t value;
179226fa459cSmrg    PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
179326fa459cSmrg    do {
179426fa459cSmrg      if (!CheckInputAmount(safe, br, 28)) {  /* 162 bits + 7 bytes */
179526fa459cSmrg        s->state = BROTLI_STATE_COMMAND_INNER;
179626fa459cSmrg        result = BROTLI_DECODER_NEEDS_MORE_INPUT;
179726fa459cSmrg        goto saveStateAndReturn;
179826fa459cSmrg      }
179926fa459cSmrg      if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) {
180026fa459cSmrg        BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
180126fa459cSmrg        PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
180226fa459cSmrg        if (!s->trivial_literal_context) goto CommandInner;
180326fa459cSmrg      }
180426fa459cSmrg      if (!safe) {
180526fa459cSmrg        s->ringbuffer[pos] =
180626fa459cSmrg            (uint8_t)ReadPreloadedSymbol(s->literal_htree, br, &bits, &value);
180726fa459cSmrg      } else {
180826fa459cSmrg        uint32_t literal;
180926fa459cSmrg        if (!SafeReadSymbol(s->literal_htree, br, &literal)) {
181026fa459cSmrg          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
181126fa459cSmrg          goto saveStateAndReturn;
181226fa459cSmrg        }
181326fa459cSmrg        s->ringbuffer[pos] = (uint8_t)literal;
181426fa459cSmrg      }
181526fa459cSmrg      --s->block_length[0];
181626fa459cSmrg      BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
181726fa459cSmrg      ++pos;
181826fa459cSmrg      if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) {
181926fa459cSmrg        s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
182026fa459cSmrg        --i;
182126fa459cSmrg        goto saveStateAndReturn;
182226fa459cSmrg      }
182326fa459cSmrg    } while (--i != 0);
182426fa459cSmrg  } else {
182526fa459cSmrg    uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask];
182626fa459cSmrg    uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask];
182726fa459cSmrg    do {
182826fa459cSmrg      const HuffmanCode* hc;
182926fa459cSmrg      uint8_t context;
183026fa459cSmrg      if (!CheckInputAmount(safe, br, 28)) {  /* 162 bits + 7 bytes */
183126fa459cSmrg        s->state = BROTLI_STATE_COMMAND_INNER;
183226fa459cSmrg        result = BROTLI_DECODER_NEEDS_MORE_INPUT;
183326fa459cSmrg        goto saveStateAndReturn;
183426fa459cSmrg      }
183526fa459cSmrg      if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) {
183626fa459cSmrg        BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
183726fa459cSmrg        if (s->trivial_literal_context) goto CommandInner;
183826fa459cSmrg      }
183926fa459cSmrg      context = BROTLI_CONTEXT(p1, p2, s->context_lookup);
184026fa459cSmrg      BROTLI_LOG_UINT(context);
184126fa459cSmrg      hc = s->literal_hgroup.htrees[s->context_map_slice[context]];
184226fa459cSmrg      p2 = p1;
184326fa459cSmrg      if (!safe) {
184426fa459cSmrg        p1 = (uint8_t)ReadSymbol(hc, br);
184526fa459cSmrg      } else {
184626fa459cSmrg        uint32_t literal;
184726fa459cSmrg        if (!SafeReadSymbol(hc, br, &literal)) {
184826fa459cSmrg          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
184926fa459cSmrg          goto saveStateAndReturn;
185026fa459cSmrg        }
185126fa459cSmrg        p1 = (uint8_t)literal;
185226fa459cSmrg      }
185326fa459cSmrg      s->ringbuffer[pos] = p1;
185426fa459cSmrg      --s->block_length[0];
185526fa459cSmrg      BROTLI_LOG_UINT(s->context_map_slice[context]);
185626fa459cSmrg      BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask);
185726fa459cSmrg      ++pos;
185826fa459cSmrg      if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) {
185926fa459cSmrg        s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
186026fa459cSmrg        --i;
186126fa459cSmrg        goto saveStateAndReturn;
186226fa459cSmrg      }
186326fa459cSmrg    } while (--i != 0);
186426fa459cSmrg  }
186526fa459cSmrg  BROTLI_LOG_UINT(s->meta_block_remaining_len);
186626fa459cSmrg  if (BROTLI_PREDICT_FALSE(s->meta_block_remaining_len <= 0)) {
186726fa459cSmrg    s->state = BROTLI_STATE_METABLOCK_DONE;
186826fa459cSmrg    goto saveStateAndReturn;
186926fa459cSmrg  }
187026fa459cSmrg
187126fa459cSmrgCommandPostDecodeLiterals:
187226fa459cSmrg  if (safe) {
187326fa459cSmrg    s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
187426fa459cSmrg  }
187526fa459cSmrg  if (s->distance_code >= 0) {
187626fa459cSmrg    /* Implicit distance case. */
187726fa459cSmrg    s->distance_context = s->distance_code ? 0 : 1;
187826fa459cSmrg    --s->dist_rb_idx;
187926fa459cSmrg    s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
188026fa459cSmrg  } else {
188126fa459cSmrg    /* Read distance code in the command, unless it was implicitly zero. */
188226fa459cSmrg    if (BROTLI_PREDICT_FALSE(s->block_length[2] == 0)) {
188326fa459cSmrg      BROTLI_SAFE(DecodeDistanceBlockSwitch(s));
188426fa459cSmrg    }
188526fa459cSmrg    BROTLI_SAFE(ReadDistance(s, br));
188626fa459cSmrg  }
188726fa459cSmrg  BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n",
188826fa459cSmrg              pos, s->distance_code));
188926fa459cSmrg  if (s->max_distance != s->max_backward_distance) {
189026fa459cSmrg    s->max_distance =
189126fa459cSmrg        (pos < s->max_backward_distance) ? pos : s->max_backward_distance;
189226fa459cSmrg  }
189326fa459cSmrg  i = s->copy_length;
189426fa459cSmrg  /* Apply copy of LZ77 back-reference, or static dictionary reference if
189526fa459cSmrg     the distance is larger than the max LZ77 distance */
189626fa459cSmrg  if (s->distance_code > s->max_distance) {
189726fa459cSmrg    /* The maximum allowed distance is BROTLI_MAX_ALLOWED_DISTANCE = 0x7FFFFFFC.
189826fa459cSmrg       With this choice, no signed overflow can occur after decoding
189926fa459cSmrg       a special distance code (e.g., after adding 3 to the last distance). */
190026fa459cSmrg    if (s->distance_code > BROTLI_MAX_ALLOWED_DISTANCE) {
190126fa459cSmrg      BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
190226fa459cSmrg          "len: %d bytes left: %d\n",
190326fa459cSmrg          pos, s->distance_code, i, s->meta_block_remaining_len));
190426fa459cSmrg      return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DISTANCE);
190526fa459cSmrg    }
190626fa459cSmrg    if (i >= BROTLI_MIN_DICTIONARY_WORD_LENGTH &&
190726fa459cSmrg        i <= BROTLI_MAX_DICTIONARY_WORD_LENGTH) {
190826fa459cSmrg      int address = s->distance_code - s->max_distance - 1;
190926fa459cSmrg      const BrotliDictionary* words = s->dictionary;
191026fa459cSmrg      const BrotliTransforms* transforms = s->transforms;
191126fa459cSmrg      int offset = (int)s->dictionary->offsets_by_length[i];
191226fa459cSmrg      uint32_t shift = s->dictionary->size_bits_by_length[i];
191326fa459cSmrg
191426fa459cSmrg      int mask = (int)BitMask(shift);
191526fa459cSmrg      int word_idx = address & mask;
191626fa459cSmrg      int transform_idx = address >> shift;
191726fa459cSmrg      /* Compensate double distance-ring-buffer roll. */
191826fa459cSmrg      s->dist_rb_idx += s->distance_context;
191926fa459cSmrg      offset += word_idx * i;
192026fa459cSmrg      if (BROTLI_PREDICT_FALSE(!words->data)) {
192126fa459cSmrg        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET);
192226fa459cSmrg      }
192326fa459cSmrg      if (transform_idx < (int)transforms->num_transforms) {
192426fa459cSmrg        const uint8_t* word = &words->data[offset];
192526fa459cSmrg        int len = i;
192626fa459cSmrg        if (transform_idx == transforms->cutOffTransforms[0]) {
192726fa459cSmrg          memcpy(&s->ringbuffer[pos], word, (size_t)len);
192826fa459cSmrg          BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s]\n",
192926fa459cSmrg                      len, word));
193026fa459cSmrg        } else {
193126fa459cSmrg          len = BrotliTransformDictionaryWord(&s->ringbuffer[pos], word, len,
193226fa459cSmrg              transforms, transform_idx);
193326fa459cSmrg          BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s],"
193426fa459cSmrg                      " transform_idx = %d, transformed: [%.*s]\n",
193526fa459cSmrg                      i, word, transform_idx, len, &s->ringbuffer[pos]));
193626fa459cSmrg        }
193726fa459cSmrg        pos += len;
193826fa459cSmrg        s->meta_block_remaining_len -= len;
193926fa459cSmrg        if (pos >= s->ringbuffer_size) {
194026fa459cSmrg          s->state = BROTLI_STATE_COMMAND_POST_WRITE_1;
194126fa459cSmrg          goto saveStateAndReturn;
194226fa459cSmrg        }
194326fa459cSmrg      } else {
194426fa459cSmrg        BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
194526fa459cSmrg            "len: %d bytes left: %d\n",
194626fa459cSmrg            pos, s->distance_code, i, s->meta_block_remaining_len));
194726fa459cSmrg        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
194826fa459cSmrg      }
194926fa459cSmrg    } else {
195026fa459cSmrg      BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
195126fa459cSmrg          "len: %d bytes left: %d\n",
195226fa459cSmrg          pos, s->distance_code, i, s->meta_block_remaining_len));
195326fa459cSmrg      return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY);
195426fa459cSmrg    }
195526fa459cSmrg  } else {
195626fa459cSmrg    int src_start = (pos - s->distance_code) & s->ringbuffer_mask;
195726fa459cSmrg    uint8_t* copy_dst = &s->ringbuffer[pos];
195826fa459cSmrg    uint8_t* copy_src = &s->ringbuffer[src_start];
195926fa459cSmrg    int dst_end = pos + i;
196026fa459cSmrg    int src_end = src_start + i;
196126fa459cSmrg    /* Update the recent distances cache. */
196226fa459cSmrg    s->dist_rb[s->dist_rb_idx & 3] = s->distance_code;
196326fa459cSmrg    ++s->dist_rb_idx;
196426fa459cSmrg    s->meta_block_remaining_len -= i;
196526fa459cSmrg    /* There are 32+ bytes of slack in the ring-buffer allocation.
196626fa459cSmrg       Also, we have 16 short codes, that make these 16 bytes irrelevant
196726fa459cSmrg       in the ring-buffer. Let's copy over them as a first guess. */
196826fa459cSmrg    memmove16(copy_dst, copy_src);
196926fa459cSmrg    if (src_end > pos && dst_end > src_start) {
197026fa459cSmrg      /* Regions intersect. */
197126fa459cSmrg      goto CommandPostWrapCopy;
197226fa459cSmrg    }
197326fa459cSmrg    if (dst_end >= s->ringbuffer_size || src_end >= s->ringbuffer_size) {
197426fa459cSmrg      /* At least one region wraps. */
197526fa459cSmrg      goto CommandPostWrapCopy;
197626fa459cSmrg    }
197726fa459cSmrg    pos += i;
197826fa459cSmrg    if (i > 16) {
197926fa459cSmrg      if (i > 32) {
198026fa459cSmrg        memcpy(copy_dst + 16, copy_src + 16, (size_t)(i - 16));
198126fa459cSmrg      } else {
198226fa459cSmrg        /* This branch covers about 45% cases.
198326fa459cSmrg           Fixed size short copy allows more compiler optimizations. */
198426fa459cSmrg        memmove16(copy_dst + 16, copy_src + 16);
198526fa459cSmrg      }
198626fa459cSmrg    }
198726fa459cSmrg  }
198826fa459cSmrg  BROTLI_LOG_UINT(s->meta_block_remaining_len);
198926fa459cSmrg  if (s->meta_block_remaining_len <= 0) {
199026fa459cSmrg    /* Next metablock, if any. */
199126fa459cSmrg    s->state = BROTLI_STATE_METABLOCK_DONE;
199226fa459cSmrg    goto saveStateAndReturn;
199326fa459cSmrg  } else {
199426fa459cSmrg    goto CommandBegin;
199526fa459cSmrg  }
199626fa459cSmrgCommandPostWrapCopy:
199726fa459cSmrg  {
199826fa459cSmrg    int wrap_guard = s->ringbuffer_size - pos;
199926fa459cSmrg    while (--i >= 0) {
200026fa459cSmrg      s->ringbuffer[pos] =
200126fa459cSmrg          s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
200226fa459cSmrg      ++pos;
200326fa459cSmrg      if (BROTLI_PREDICT_FALSE(--wrap_guard == 0)) {
200426fa459cSmrg        s->state = BROTLI_STATE_COMMAND_POST_WRITE_2;
200526fa459cSmrg        goto saveStateAndReturn;
200626fa459cSmrg      }
200726fa459cSmrg    }
200826fa459cSmrg  }
200926fa459cSmrg  if (s->meta_block_remaining_len <= 0) {
201026fa459cSmrg    /* Next metablock, if any. */
201126fa459cSmrg    s->state = BROTLI_STATE_METABLOCK_DONE;
201226fa459cSmrg    goto saveStateAndReturn;
201326fa459cSmrg  } else {
201426fa459cSmrg    goto CommandBegin;
201526fa459cSmrg  }
201626fa459cSmrg
201726fa459cSmrgsaveStateAndReturn:
201826fa459cSmrg  s->pos = pos;
201926fa459cSmrg  s->loop_counter = i;
202026fa459cSmrg  return result;
202126fa459cSmrg}
202226fa459cSmrg
202326fa459cSmrg#undef BROTLI_SAFE
202426fa459cSmrg
202526fa459cSmrgstatic BROTLI_NOINLINE BrotliDecoderErrorCode ProcessCommands(
202626fa459cSmrg    BrotliDecoderState* s) {
202726fa459cSmrg  return ProcessCommandsInternal(0, s);
202826fa459cSmrg}
202926fa459cSmrg
203026fa459cSmrgstatic BROTLI_NOINLINE BrotliDecoderErrorCode SafeProcessCommands(
203126fa459cSmrg    BrotliDecoderState* s) {
203226fa459cSmrg  return ProcessCommandsInternal(1, s);
203326fa459cSmrg}
203426fa459cSmrg
203526fa459cSmrgBrotliDecoderResult BrotliDecoderDecompress(
203626fa459cSmrg    size_t encoded_size, const uint8_t* encoded_buffer, size_t* decoded_size,
203726fa459cSmrg    uint8_t* decoded_buffer) {
203826fa459cSmrg  BrotliDecoderState s;
203926fa459cSmrg  BrotliDecoderResult result;
204026fa459cSmrg  size_t total_out = 0;
204126fa459cSmrg  size_t available_in = encoded_size;
204226fa459cSmrg  const uint8_t* next_in = encoded_buffer;
204326fa459cSmrg  size_t available_out = *decoded_size;
204426fa459cSmrg  uint8_t* next_out = decoded_buffer;
204526fa459cSmrg  if (!BrotliDecoderStateInit(&s, 0, 0, 0)) {
204626fa459cSmrg    return BROTLI_DECODER_RESULT_ERROR;
204726fa459cSmrg  }
204826fa459cSmrg  result = BrotliDecoderDecompressStream(
204926fa459cSmrg      &s, &available_in, &next_in, &available_out, &next_out, &total_out);
205026fa459cSmrg  *decoded_size = total_out;
205126fa459cSmrg  BrotliDecoderStateCleanup(&s);
205226fa459cSmrg  if (result != BROTLI_DECODER_RESULT_SUCCESS) {
205326fa459cSmrg    result = BROTLI_DECODER_RESULT_ERROR;
205426fa459cSmrg  }
205526fa459cSmrg  return result;
205626fa459cSmrg}
205726fa459cSmrg
205826fa459cSmrg/* Invariant: input stream is never overconsumed:
205926fa459cSmrg    - invalid input implies that the whole stream is invalid -> any amount of
206026fa459cSmrg      input could be read and discarded
206126fa459cSmrg    - when result is "needs more input", then at least one more byte is REQUIRED
206226fa459cSmrg      to complete decoding; all input data MUST be consumed by decoder, so
206326fa459cSmrg      client could swap the input buffer
206426fa459cSmrg    - when result is "needs more output" decoder MUST ensure that it doesn't
206526fa459cSmrg      hold more than 7 bits in bit reader; this saves client from swapping input
206626fa459cSmrg      buffer ahead of time
206726fa459cSmrg    - when result is "success" decoder MUST return all unused data back to input
206826fa459cSmrg      buffer; this is possible because the invariant is held on enter */
206926fa459cSmrgBrotliDecoderResult BrotliDecoderDecompressStream(
207026fa459cSmrg    BrotliDecoderState* s, size_t* available_in, const uint8_t** next_in,
207126fa459cSmrg    size_t* available_out, uint8_t** next_out, size_t* total_out) {
207226fa459cSmrg  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
207326fa459cSmrg  BrotliBitReader* br = &s->br;
207426fa459cSmrg  /* Ensure that |total_out| is set, even if no data will ever be pushed out. */
207526fa459cSmrg  if (total_out) {
207626fa459cSmrg    *total_out = s->partial_pos_out;
207726fa459cSmrg  }
207826fa459cSmrg  /* Do not try to process further in a case of unrecoverable error. */
207926fa459cSmrg  if ((int)s->error_code < 0) {
208026fa459cSmrg    return BROTLI_DECODER_RESULT_ERROR;
208126fa459cSmrg  }
208226fa459cSmrg  if (*available_out && (!next_out || !*next_out)) {
208326fa459cSmrg    return SaveErrorCode(
208426fa459cSmrg        s, BROTLI_FAILURE(BROTLI_DECODER_ERROR_INVALID_ARGUMENTS));
208526fa459cSmrg  }
208626fa459cSmrg  if (!*available_out) next_out = 0;
208726fa459cSmrg  if (s->buffer_length == 0) {  /* Just connect bit reader to input stream. */
208826fa459cSmrg    br->avail_in = *available_in;
208926fa459cSmrg    br->next_in = *next_in;
209026fa459cSmrg  } else {
209126fa459cSmrg    /* At least one byte of input is required. More than one byte of input may
209226fa459cSmrg       be required to complete the transaction -> reading more data must be
209326fa459cSmrg       done in a loop -> do it in a main loop. */
209426fa459cSmrg    result = BROTLI_DECODER_NEEDS_MORE_INPUT;
209526fa459cSmrg    br->next_in = &s->buffer.u8[0];
209626fa459cSmrg  }
209726fa459cSmrg  /* State machine */
209826fa459cSmrg  for (;;) {
209926fa459cSmrg    if (result != BROTLI_DECODER_SUCCESS) {
210026fa459cSmrg      /* Error, needs more input/output. */
210126fa459cSmrg      if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
210226fa459cSmrg        if (s->ringbuffer != 0) {  /* Pro-actively push output. */
210326fa459cSmrg          BrotliDecoderErrorCode intermediate_result = WriteRingBuffer(s,
210426fa459cSmrg              available_out, next_out, total_out, BROTLI_TRUE);
210526fa459cSmrg          /* WriteRingBuffer checks s->meta_block_remaining_len validity. */
210626fa459cSmrg          if ((int)intermediate_result < 0) {
210726fa459cSmrg            result = intermediate_result;
210826fa459cSmrg            break;
210926fa459cSmrg          }
211026fa459cSmrg        }
211126fa459cSmrg        if (s->buffer_length != 0) {  /* Used with internal buffer. */
211226fa459cSmrg          if (br->avail_in == 0) {
211326fa459cSmrg            /* Successfully finished read transaction.
211426fa459cSmrg               Accumulator contains less than 8 bits, because internal buffer
211526fa459cSmrg               is expanded byte-by-byte until it is enough to complete read. */
211626fa459cSmrg            s->buffer_length = 0;
211726fa459cSmrg            /* Switch to input stream and restart. */
211826fa459cSmrg            result = BROTLI_DECODER_SUCCESS;
211926fa459cSmrg            br->avail_in = *available_in;
212026fa459cSmrg            br->next_in = *next_in;
212126fa459cSmrg            continue;
212226fa459cSmrg          } else if (*available_in != 0) {
212326fa459cSmrg            /* Not enough data in buffer, but can take one more byte from
212426fa459cSmrg               input stream. */
212526fa459cSmrg            result = BROTLI_DECODER_SUCCESS;
212626fa459cSmrg            s->buffer.u8[s->buffer_length] = **next_in;
212726fa459cSmrg            s->buffer_length++;
212826fa459cSmrg            br->avail_in = s->buffer_length;
212926fa459cSmrg            (*next_in)++;
213026fa459cSmrg            (*available_in)--;
213126fa459cSmrg            /* Retry with more data in buffer. */
213226fa459cSmrg            continue;
213326fa459cSmrg          }
213426fa459cSmrg          /* Can't finish reading and no more input. */
213526fa459cSmrg          break;
213626fa459cSmrg        } else {  /* Input stream doesn't contain enough input. */
213726fa459cSmrg          /* Copy tail to internal buffer and return. */
213826fa459cSmrg          *next_in = br->next_in;
213926fa459cSmrg          *available_in = br->avail_in;
214026fa459cSmrg          while (*available_in) {
214126fa459cSmrg            s->buffer.u8[s->buffer_length] = **next_in;
214226fa459cSmrg            s->buffer_length++;
214326fa459cSmrg            (*next_in)++;
214426fa459cSmrg            (*available_in)--;
214526fa459cSmrg          }
214626fa459cSmrg          break;
214726fa459cSmrg        }
214826fa459cSmrg        /* Unreachable. */
214926fa459cSmrg      }
215026fa459cSmrg
215126fa459cSmrg      /* Fail or needs more output. */
215226fa459cSmrg
215326fa459cSmrg      if (s->buffer_length != 0) {
215426fa459cSmrg        /* Just consumed the buffered input and produced some output. Otherwise
215526fa459cSmrg           it would result in "needs more input". Reset internal buffer. */
215626fa459cSmrg        s->buffer_length = 0;
215726fa459cSmrg      } else {
215826fa459cSmrg        /* Using input stream in last iteration. When decoder switches to input
215926fa459cSmrg           stream it has less than 8 bits in accumulator, so it is safe to
216026fa459cSmrg           return unused accumulator bits there. */
216126fa459cSmrg        BrotliBitReaderUnload(br);
216226fa459cSmrg        *available_in = br->avail_in;
216326fa459cSmrg        *next_in = br->next_in;
216426fa459cSmrg      }
216526fa459cSmrg      break;
216626fa459cSmrg    }
216726fa459cSmrg    switch (s->state) {
216826fa459cSmrg      case BROTLI_STATE_UNINITED:
216926fa459cSmrg        /* Prepare to the first read. */
217026fa459cSmrg        if (!BrotliWarmupBitReader(br)) {
217126fa459cSmrg          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
217226fa459cSmrg          break;
217326fa459cSmrg        }
217426fa459cSmrg        /* Decode window size. */
217526fa459cSmrg        result = DecodeWindowBits(s, br);  /* Reads 1..8 bits. */
217626fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
217726fa459cSmrg          break;
217826fa459cSmrg        }
217926fa459cSmrg        if (s->large_window) {
218026fa459cSmrg          s->state = BROTLI_STATE_LARGE_WINDOW_BITS;
218126fa459cSmrg          break;
218226fa459cSmrg        }
218326fa459cSmrg        s->state = BROTLI_STATE_INITIALIZE;
218426fa459cSmrg        break;
218526fa459cSmrg
218626fa459cSmrg      case BROTLI_STATE_LARGE_WINDOW_BITS:
218726fa459cSmrg        if (!BrotliSafeReadBits(br, 6, &s->window_bits)) {
218826fa459cSmrg          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
218926fa459cSmrg          break;
219026fa459cSmrg        }
219126fa459cSmrg        if (s->window_bits < BROTLI_LARGE_MIN_WBITS ||
219226fa459cSmrg            s->window_bits > BROTLI_LARGE_MAX_WBITS) {
219326fa459cSmrg          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS);
219426fa459cSmrg          break;
219526fa459cSmrg        }
219626fa459cSmrg        s->state = BROTLI_STATE_INITIALIZE;
219726fa459cSmrg      /* Fall through. */
219826fa459cSmrg
219926fa459cSmrg      case BROTLI_STATE_INITIALIZE:
220026fa459cSmrg        BROTLI_LOG_UINT(s->window_bits);
220126fa459cSmrg        /* Maximum distance, see section 9.1. of the spec. */
220226fa459cSmrg        s->max_backward_distance = (1 << s->window_bits) - BROTLI_WINDOW_GAP;
220326fa459cSmrg
220426fa459cSmrg        /* Allocate memory for both block_type_trees and block_len_trees. */
220526fa459cSmrg        s->block_type_trees = (HuffmanCode*)BROTLI_DECODER_ALLOC(s,
220626fa459cSmrg            sizeof(HuffmanCode) * 3 *
220726fa459cSmrg                (BROTLI_HUFFMAN_MAX_SIZE_258 + BROTLI_HUFFMAN_MAX_SIZE_26));
220826fa459cSmrg        if (s->block_type_trees == 0) {
220926fa459cSmrg          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES);
221026fa459cSmrg          break;
221126fa459cSmrg        }
221226fa459cSmrg        s->block_len_trees =
221326fa459cSmrg            s->block_type_trees + 3 * BROTLI_HUFFMAN_MAX_SIZE_258;
221426fa459cSmrg
221526fa459cSmrg        s->state = BROTLI_STATE_METABLOCK_BEGIN;
221626fa459cSmrg      /* Fall through. */
221726fa459cSmrg
221826fa459cSmrg      case BROTLI_STATE_METABLOCK_BEGIN:
221926fa459cSmrg        BrotliDecoderStateMetablockBegin(s);
222026fa459cSmrg        BROTLI_LOG_UINT(s->pos);
222126fa459cSmrg        s->state = BROTLI_STATE_METABLOCK_HEADER;
222226fa459cSmrg      /* Fall through. */
222326fa459cSmrg
222426fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER:
222526fa459cSmrg        result = DecodeMetaBlockLength(s, br);  /* Reads 2 - 31 bits. */
222626fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
222726fa459cSmrg          break;
222826fa459cSmrg        }
222926fa459cSmrg        BROTLI_LOG_UINT(s->is_last_metablock);
223026fa459cSmrg        BROTLI_LOG_UINT(s->meta_block_remaining_len);
223126fa459cSmrg        BROTLI_LOG_UINT(s->is_metadata);
223226fa459cSmrg        BROTLI_LOG_UINT(s->is_uncompressed);
223326fa459cSmrg        if (s->is_metadata || s->is_uncompressed) {
223426fa459cSmrg          if (!BrotliJumpToByteBoundary(br)) {
223526fa459cSmrg            result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1);
223626fa459cSmrg            break;
223726fa459cSmrg          }
223826fa459cSmrg        }
223926fa459cSmrg        if (s->is_metadata) {
224026fa459cSmrg          s->state = BROTLI_STATE_METADATA;
224126fa459cSmrg          break;
224226fa459cSmrg        }
224326fa459cSmrg        if (s->meta_block_remaining_len == 0) {
224426fa459cSmrg          s->state = BROTLI_STATE_METABLOCK_DONE;
224526fa459cSmrg          break;
224626fa459cSmrg        }
224726fa459cSmrg        BrotliCalculateRingBufferSize(s);
224826fa459cSmrg        if (s->is_uncompressed) {
224926fa459cSmrg          s->state = BROTLI_STATE_UNCOMPRESSED;
225026fa459cSmrg          break;
225126fa459cSmrg        }
225226fa459cSmrg        s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER;
225326fa459cSmrg      /* Fall through. */
225426fa459cSmrg
225526fa459cSmrg      case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER: {
225626fa459cSmrg        BrotliMetablockHeaderArena* h = &s->arena.header;
225726fa459cSmrg        s->loop_counter = 0;
225826fa459cSmrg        /* Initialize compressed metablock header arena. */
225926fa459cSmrg        h->sub_loop_counter = 0;
226026fa459cSmrg        /* Make small negative indexes addressable. */
226126fa459cSmrg        h->symbol_lists =
226226fa459cSmrg            &h->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1];
226326fa459cSmrg        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
226426fa459cSmrg        h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
226526fa459cSmrg        h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
226626fa459cSmrg        s->state = BROTLI_STATE_HUFFMAN_CODE_0;
226726fa459cSmrg      }
226826fa459cSmrg      /* Fall through. */
226926fa459cSmrg
227026fa459cSmrg      case BROTLI_STATE_HUFFMAN_CODE_0:
227126fa459cSmrg        if (s->loop_counter >= 3) {
227226fa459cSmrg          s->state = BROTLI_STATE_METABLOCK_HEADER_2;
227326fa459cSmrg          break;
227426fa459cSmrg        }
227526fa459cSmrg        /* Reads 1..11 bits. */
227626fa459cSmrg        result = DecodeVarLenUint8(s, br, &s->num_block_types[s->loop_counter]);
227726fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
227826fa459cSmrg          break;
227926fa459cSmrg        }
228026fa459cSmrg        s->num_block_types[s->loop_counter]++;
228126fa459cSmrg        BROTLI_LOG_UINT(s->num_block_types[s->loop_counter]);
228226fa459cSmrg        if (s->num_block_types[s->loop_counter] < 2) {
228326fa459cSmrg          s->loop_counter++;
228426fa459cSmrg          break;
228526fa459cSmrg        }
228626fa459cSmrg        s->state = BROTLI_STATE_HUFFMAN_CODE_1;
228726fa459cSmrg      /* Fall through. */
228826fa459cSmrg
228926fa459cSmrg      case BROTLI_STATE_HUFFMAN_CODE_1: {
229026fa459cSmrg        uint32_t alphabet_size = s->num_block_types[s->loop_counter] + 2;
229126fa459cSmrg        int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_258;
229226fa459cSmrg        result = ReadHuffmanCode(alphabet_size, alphabet_size,
229326fa459cSmrg            &s->block_type_trees[tree_offset], NULL, s);
229426fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) break;
229526fa459cSmrg        s->state = BROTLI_STATE_HUFFMAN_CODE_2;
229626fa459cSmrg      }
229726fa459cSmrg      /* Fall through. */
229826fa459cSmrg
229926fa459cSmrg      case BROTLI_STATE_HUFFMAN_CODE_2: {
230026fa459cSmrg        uint32_t alphabet_size = BROTLI_NUM_BLOCK_LEN_SYMBOLS;
230126fa459cSmrg        int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26;
230226fa459cSmrg        result = ReadHuffmanCode(alphabet_size, alphabet_size,
230326fa459cSmrg            &s->block_len_trees[tree_offset], NULL, s);
230426fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) break;
230526fa459cSmrg        s->state = BROTLI_STATE_HUFFMAN_CODE_3;
230626fa459cSmrg      }
230726fa459cSmrg      /* Fall through. */
230826fa459cSmrg
230926fa459cSmrg      case BROTLI_STATE_HUFFMAN_CODE_3: {
231026fa459cSmrg        int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26;
231126fa459cSmrg        if (!SafeReadBlockLength(s, &s->block_length[s->loop_counter],
231226fa459cSmrg            &s->block_len_trees[tree_offset], br)) {
231326fa459cSmrg          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
231426fa459cSmrg          break;
231526fa459cSmrg        }
231626fa459cSmrg        BROTLI_LOG_UINT(s->block_length[s->loop_counter]);
231726fa459cSmrg        s->loop_counter++;
231826fa459cSmrg        s->state = BROTLI_STATE_HUFFMAN_CODE_0;
231926fa459cSmrg        break;
232026fa459cSmrg      }
232126fa459cSmrg
232226fa459cSmrg      case BROTLI_STATE_UNCOMPRESSED: {
232326fa459cSmrg        result = CopyUncompressedBlockToOutput(
232426fa459cSmrg            available_out, next_out, total_out, s);
232526fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
232626fa459cSmrg          break;
232726fa459cSmrg        }
232826fa459cSmrg        s->state = BROTLI_STATE_METABLOCK_DONE;
232926fa459cSmrg        break;
233026fa459cSmrg      }
233126fa459cSmrg
233226fa459cSmrg      case BROTLI_STATE_METADATA:
233326fa459cSmrg        for (; s->meta_block_remaining_len > 0; --s->meta_block_remaining_len) {
233426fa459cSmrg          uint32_t bits;
233526fa459cSmrg          /* Read one byte and ignore it. */
233626fa459cSmrg          if (!BrotliSafeReadBits(br, 8, &bits)) {
233726fa459cSmrg            result = BROTLI_DECODER_NEEDS_MORE_INPUT;
233826fa459cSmrg            break;
233926fa459cSmrg          }
234026fa459cSmrg        }
234126fa459cSmrg        if (result == BROTLI_DECODER_SUCCESS) {
234226fa459cSmrg          s->state = BROTLI_STATE_METABLOCK_DONE;
234326fa459cSmrg        }
234426fa459cSmrg        break;
234526fa459cSmrg
234626fa459cSmrg      case BROTLI_STATE_METABLOCK_HEADER_2: {
234726fa459cSmrg        uint32_t bits;
234826fa459cSmrg        if (!BrotliSafeReadBits(br, 6, &bits)) {
234926fa459cSmrg          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
235026fa459cSmrg          break;
235126fa459cSmrg        }
235226fa459cSmrg        s->distance_postfix_bits = bits & BitMask(2);
235326fa459cSmrg        bits >>= 2;
235426fa459cSmrg        s->num_direct_distance_codes = bits << s->distance_postfix_bits;
235526fa459cSmrg        BROTLI_LOG_UINT(s->num_direct_distance_codes);
235626fa459cSmrg        BROTLI_LOG_UINT(s->distance_postfix_bits);
235726fa459cSmrg        s->context_modes =
235826fa459cSmrg            (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)s->num_block_types[0]);
235926fa459cSmrg        if (s->context_modes == 0) {
236026fa459cSmrg          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES);
236126fa459cSmrg          break;
236226fa459cSmrg        }
236326fa459cSmrg        s->loop_counter = 0;
236426fa459cSmrg        s->state = BROTLI_STATE_CONTEXT_MODES;
236526fa459cSmrg      }
236626fa459cSmrg      /* Fall through. */
236726fa459cSmrg
236826fa459cSmrg      case BROTLI_STATE_CONTEXT_MODES:
236926fa459cSmrg        result = ReadContextModes(s);
237026fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
237126fa459cSmrg          break;
237226fa459cSmrg        }
237326fa459cSmrg        s->state = BROTLI_STATE_CONTEXT_MAP_1;
237426fa459cSmrg      /* Fall through. */
237526fa459cSmrg
237626fa459cSmrg      case BROTLI_STATE_CONTEXT_MAP_1:
237726fa459cSmrg        result = DecodeContextMap(
237826fa459cSmrg            s->num_block_types[0] << BROTLI_LITERAL_CONTEXT_BITS,
237926fa459cSmrg            &s->num_literal_htrees, &s->context_map, s);
238026fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
238126fa459cSmrg          break;
238226fa459cSmrg        }
238326fa459cSmrg        DetectTrivialLiteralBlockTypes(s);
238426fa459cSmrg        s->state = BROTLI_STATE_CONTEXT_MAP_2;
238526fa459cSmrg      /* Fall through. */
238626fa459cSmrg
238726fa459cSmrg      case BROTLI_STATE_CONTEXT_MAP_2: {
238826fa459cSmrg        uint32_t npostfix = s->distance_postfix_bits;
238926fa459cSmrg        uint32_t ndirect = s->num_direct_distance_codes;
239026fa459cSmrg        uint32_t distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE(
239126fa459cSmrg            npostfix, ndirect, BROTLI_MAX_DISTANCE_BITS);
239226fa459cSmrg        uint32_t distance_alphabet_size_limit = distance_alphabet_size_max;
239326fa459cSmrg        BROTLI_BOOL allocation_success = BROTLI_TRUE;
239426fa459cSmrg        if (s->large_window) {
239526fa459cSmrg          BrotliDistanceCodeLimit limit = BrotliCalculateDistanceCodeLimit(
239626fa459cSmrg              BROTLI_MAX_ALLOWED_DISTANCE, npostfix, ndirect);
239726fa459cSmrg          distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE(
239826fa459cSmrg              npostfix, ndirect, BROTLI_LARGE_MAX_DISTANCE_BITS);
239926fa459cSmrg          distance_alphabet_size_limit = limit.max_alphabet_size;
240026fa459cSmrg        }
240126fa459cSmrg        result = DecodeContextMap(
240226fa459cSmrg            s->num_block_types[2] << BROTLI_DISTANCE_CONTEXT_BITS,
240326fa459cSmrg            &s->num_dist_htrees, &s->dist_context_map, s);
240426fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
240526fa459cSmrg          break;
240626fa459cSmrg        }
240726fa459cSmrg        allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
240826fa459cSmrg            s, &s->literal_hgroup, BROTLI_NUM_LITERAL_SYMBOLS,
240926fa459cSmrg            BROTLI_NUM_LITERAL_SYMBOLS, s->num_literal_htrees);
241026fa459cSmrg        allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
241126fa459cSmrg            s, &s->insert_copy_hgroup, BROTLI_NUM_COMMAND_SYMBOLS,
241226fa459cSmrg            BROTLI_NUM_COMMAND_SYMBOLS, s->num_block_types[1]);
241326fa459cSmrg        allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
241426fa459cSmrg            s, &s->distance_hgroup, distance_alphabet_size_max,
241526fa459cSmrg            distance_alphabet_size_limit, s->num_dist_htrees);
241626fa459cSmrg        if (!allocation_success) {
241726fa459cSmrg          return SaveErrorCode(s,
241826fa459cSmrg              BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS));
241926fa459cSmrg        }
242026fa459cSmrg        s->loop_counter = 0;
242126fa459cSmrg        s->state = BROTLI_STATE_TREE_GROUP;
242226fa459cSmrg      }
242326fa459cSmrg      /* Fall through. */
242426fa459cSmrg
242526fa459cSmrg      case BROTLI_STATE_TREE_GROUP: {
242626fa459cSmrg        HuffmanTreeGroup* hgroup = NULL;
242726fa459cSmrg        switch (s->loop_counter) {
242826fa459cSmrg          case 0: hgroup = &s->literal_hgroup; break;
242926fa459cSmrg          case 1: hgroup = &s->insert_copy_hgroup; break;
243026fa459cSmrg          case 2: hgroup = &s->distance_hgroup; break;
243126fa459cSmrg          default: return SaveErrorCode(s, BROTLI_FAILURE(
243226fa459cSmrg              BROTLI_DECODER_ERROR_UNREACHABLE));
243326fa459cSmrg        }
243426fa459cSmrg        result = HuffmanTreeGroupDecode(hgroup, s);
243526fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) break;
243626fa459cSmrg        s->loop_counter++;
243726fa459cSmrg        if (s->loop_counter < 3) {
243826fa459cSmrg          break;
243926fa459cSmrg        }
244026fa459cSmrg        s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY;
244126fa459cSmrg      }
244226fa459cSmrg      /* Fall through. */
244326fa459cSmrg
244426fa459cSmrg      case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY:
244526fa459cSmrg        PrepareLiteralDecoding(s);
244626fa459cSmrg        s->dist_context_map_slice = s->dist_context_map;
244726fa459cSmrg        s->htree_command = s->insert_copy_hgroup.htrees[0];
244826fa459cSmrg        if (!BrotliEnsureRingBuffer(s)) {
244926fa459cSmrg          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
245026fa459cSmrg          break;
245126fa459cSmrg        }
245226fa459cSmrg        CalculateDistanceLut(s);
245326fa459cSmrg        s->state = BROTLI_STATE_COMMAND_BEGIN;
245426fa459cSmrg      /* Fall through. */
245526fa459cSmrg
245626fa459cSmrg      case BROTLI_STATE_COMMAND_BEGIN:
245726fa459cSmrg      /* Fall through. */
245826fa459cSmrg      case BROTLI_STATE_COMMAND_INNER:
245926fa459cSmrg      /* Fall through. */
246026fa459cSmrg      case BROTLI_STATE_COMMAND_POST_DECODE_LITERALS:
246126fa459cSmrg      /* Fall through. */
246226fa459cSmrg      case BROTLI_STATE_COMMAND_POST_WRAP_COPY:
246326fa459cSmrg        result = ProcessCommands(s);
246426fa459cSmrg        if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
246526fa459cSmrg          result = SafeProcessCommands(s);
246626fa459cSmrg        }
246726fa459cSmrg        break;
246826fa459cSmrg
246926fa459cSmrg      case BROTLI_STATE_COMMAND_INNER_WRITE:
247026fa459cSmrg      /* Fall through. */
247126fa459cSmrg      case BROTLI_STATE_COMMAND_POST_WRITE_1:
247226fa459cSmrg      /* Fall through. */
247326fa459cSmrg      case BROTLI_STATE_COMMAND_POST_WRITE_2:
247426fa459cSmrg        result = WriteRingBuffer(
247526fa459cSmrg            s, available_out, next_out, total_out, BROTLI_FALSE);
247626fa459cSmrg        if (result != BROTLI_DECODER_SUCCESS) {
247726fa459cSmrg          break;
247826fa459cSmrg        }
247926fa459cSmrg        WrapRingBuffer(s);
248026fa459cSmrg        if (s->ringbuffer_size == 1 << s->window_bits) {
248126fa459cSmrg          s->max_distance = s->max_backward_distance;
248226fa459cSmrg        }
248326fa459cSmrg        if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) {
248426fa459cSmrg          if (s->meta_block_remaining_len == 0) {
248526fa459cSmrg            /* Next metablock, if any. */
248626fa459cSmrg            s->state = BROTLI_STATE_METABLOCK_DONE;
248726fa459cSmrg          } else {
248826fa459cSmrg            s->state = BROTLI_STATE_COMMAND_BEGIN;
248926fa459cSmrg          }
249026fa459cSmrg          break;
249126fa459cSmrg        } else if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_2) {
249226fa459cSmrg          s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY;
249326fa459cSmrg        } else {  /* BROTLI_STATE_COMMAND_INNER_WRITE */
249426fa459cSmrg          if (s->loop_counter == 0) {
249526fa459cSmrg            if (s->meta_block_remaining_len == 0) {
249626fa459cSmrg              s->state = BROTLI_STATE_METABLOCK_DONE;
249726fa459cSmrg            } else {
249826fa459cSmrg              s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
249926fa459cSmrg            }
250026fa459cSmrg            break;
250126fa459cSmrg          }
250226fa459cSmrg          s->state = BROTLI_STATE_COMMAND_INNER;
250326fa459cSmrg        }
250426fa459cSmrg        break;
250526fa459cSmrg
250626fa459cSmrg      case BROTLI_STATE_METABLOCK_DONE:
250726fa459cSmrg        if (s->meta_block_remaining_len < 0) {
250826fa459cSmrg          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2);
250926fa459cSmrg          break;
251026fa459cSmrg        }
251126fa459cSmrg        BrotliDecoderStateCleanupAfterMetablock(s);
251226fa459cSmrg        if (!s->is_last_metablock) {
251326fa459cSmrg          s->state = BROTLI_STATE_METABLOCK_BEGIN;
251426fa459cSmrg          break;
251526fa459cSmrg        }
251626fa459cSmrg        if (!BrotliJumpToByteBoundary(br)) {
251726fa459cSmrg          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2);
251826fa459cSmrg          break;
251926fa459cSmrg        }
252026fa459cSmrg        if (s->buffer_length == 0) {
252126fa459cSmrg          BrotliBitReaderUnload(br);
252226fa459cSmrg          *available_in = br->avail_in;
252326fa459cSmrg          *next_in = br->next_in;
252426fa459cSmrg        }
252526fa459cSmrg        s->state = BROTLI_STATE_DONE;
252626fa459cSmrg      /* Fall through. */
252726fa459cSmrg
252826fa459cSmrg      case BROTLI_STATE_DONE:
252926fa459cSmrg        if (s->ringbuffer != 0) {
253026fa459cSmrg          result = WriteRingBuffer(
253126fa459cSmrg              s, available_out, next_out, total_out, BROTLI_TRUE);
253226fa459cSmrg          if (result != BROTLI_DECODER_SUCCESS) {
253326fa459cSmrg            break;
253426fa459cSmrg          }
253526fa459cSmrg        }
253626fa459cSmrg        return SaveErrorCode(s, result);
253726fa459cSmrg    }
253826fa459cSmrg  }
253926fa459cSmrg  return SaveErrorCode(s, result);
254026fa459cSmrg}
254126fa459cSmrg
254226fa459cSmrgBROTLI_BOOL BrotliDecoderHasMoreOutput(const BrotliDecoderState* s) {
254326fa459cSmrg  /* After unrecoverable error remaining output is considered nonsensical. */
254426fa459cSmrg  if ((int)s->error_code < 0) {
254526fa459cSmrg    return BROTLI_FALSE;
254626fa459cSmrg  }
254726fa459cSmrg  return TO_BROTLI_BOOL(
254826fa459cSmrg      s->ringbuffer != 0 && UnwrittenBytes(s, BROTLI_FALSE) != 0);
254926fa459cSmrg}
255026fa459cSmrg
255126fa459cSmrgconst uint8_t* BrotliDecoderTakeOutput(BrotliDecoderState* s, size_t* size) {
255226fa459cSmrg  uint8_t* result = 0;
255326fa459cSmrg  size_t available_out = *size ? *size : 1u << 24;
255426fa459cSmrg  size_t requested_out = available_out;
255526fa459cSmrg  BrotliDecoderErrorCode status;
255626fa459cSmrg  if ((s->ringbuffer == 0) || ((int)s->error_code < 0)) {
255726fa459cSmrg    *size = 0;
255826fa459cSmrg    return 0;
255926fa459cSmrg  }
256026fa459cSmrg  WrapRingBuffer(s);
256126fa459cSmrg  status = WriteRingBuffer(s, &available_out, &result, 0, BROTLI_TRUE);
256226fa459cSmrg  /* Either WriteRingBuffer returns those "success" codes... */
256326fa459cSmrg  if (status == BROTLI_DECODER_SUCCESS ||
256426fa459cSmrg      status == BROTLI_DECODER_NEEDS_MORE_OUTPUT) {
256526fa459cSmrg    *size = requested_out - available_out;
256626fa459cSmrg  } else {
256726fa459cSmrg    /* ... or stream is broken. Normally this should be caught by
256826fa459cSmrg       BrotliDecoderDecompressStream, this is just a safeguard. */
256926fa459cSmrg    if ((int)status < 0) SaveErrorCode(s, status);
257026fa459cSmrg    *size = 0;
257126fa459cSmrg    result = 0;
257226fa459cSmrg  }
257326fa459cSmrg  return result;
257426fa459cSmrg}
257526fa459cSmrg
257626fa459cSmrgBROTLI_BOOL BrotliDecoderIsUsed(const BrotliDecoderState* s) {
257726fa459cSmrg  return TO_BROTLI_BOOL(s->state != BROTLI_STATE_UNINITED ||
257826fa459cSmrg      BrotliGetAvailableBits(&s->br) != 0);
257926fa459cSmrg}
258026fa459cSmrg
258126fa459cSmrgBROTLI_BOOL BrotliDecoderIsFinished(const BrotliDecoderState* s) {
258226fa459cSmrg  return TO_BROTLI_BOOL(s->state == BROTLI_STATE_DONE) &&
258326fa459cSmrg      !BrotliDecoderHasMoreOutput(s);
258426fa459cSmrg}
258526fa459cSmrg
258626fa459cSmrgBrotliDecoderErrorCode BrotliDecoderGetErrorCode(const BrotliDecoderState* s) {
258726fa459cSmrg  return (BrotliDecoderErrorCode)s->error_code;
258826fa459cSmrg}
258926fa459cSmrg
259026fa459cSmrgconst char* BrotliDecoderErrorString(BrotliDecoderErrorCode c) {
259126fa459cSmrg  switch (c) {
259226fa459cSmrg#define BROTLI_ERROR_CODE_CASE_(PREFIX, NAME, CODE) \
259326fa459cSmrg    case BROTLI_DECODER ## PREFIX ## NAME: return #NAME;
259426fa459cSmrg#define BROTLI_NOTHING_
259526fa459cSmrg    BROTLI_DECODER_ERROR_CODES_LIST(BROTLI_ERROR_CODE_CASE_, BROTLI_NOTHING_)
259626fa459cSmrg#undef BROTLI_ERROR_CODE_CASE_
259726fa459cSmrg#undef BROTLI_NOTHING_
259826fa459cSmrg    default: return "INVALID";
259926fa459cSmrg  }
260026fa459cSmrg}
260126fa459cSmrg
260226fa459cSmrguint32_t BrotliDecoderVersion() {
260326fa459cSmrg  return BROTLI_VERSION;
260426fa459cSmrg}
260526fa459cSmrg
260626fa459cSmrg#if defined(__cplusplus) || defined(c_plusplus)
260726fa459cSmrg}  /* extern "C" */
260826fa459cSmrg#endif
2609