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