xref: /aosp_15_r20/external/brotli/c/enc/encode.c (revision f4ee7fba7774faf2a30f13154332c0a06550dbc4)
1*f4ee7fbaSAndroid Build Coastguard Worker /* Copyright 2013 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 /* Implementation of Brotli compressor. */
8*f4ee7fbaSAndroid Build Coastguard Worker 
9*f4ee7fbaSAndroid Build Coastguard Worker #include <brotli/encode.h>
10*f4ee7fbaSAndroid Build Coastguard Worker 
11*f4ee7fbaSAndroid Build Coastguard Worker #include <stdlib.h>  /* free, malloc */
12*f4ee7fbaSAndroid Build Coastguard Worker #include <string.h>  /* memcpy, memset */
13*f4ee7fbaSAndroid Build Coastguard Worker 
14*f4ee7fbaSAndroid Build Coastguard Worker #include "../common/constants.h"
15*f4ee7fbaSAndroid Build Coastguard Worker #include "../common/context.h"
16*f4ee7fbaSAndroid Build Coastguard Worker #include "../common/platform.h"
17*f4ee7fbaSAndroid Build Coastguard Worker #include "../common/version.h"
18*f4ee7fbaSAndroid Build Coastguard Worker #include "./backward_references.h"
19*f4ee7fbaSAndroid Build Coastguard Worker #include "./backward_references_hq.h"
20*f4ee7fbaSAndroid Build Coastguard Worker #include "./bit_cost.h"
21*f4ee7fbaSAndroid Build Coastguard Worker #include "./brotli_bit_stream.h"
22*f4ee7fbaSAndroid Build Coastguard Worker #include "./compress_fragment.h"
23*f4ee7fbaSAndroid Build Coastguard Worker #include "./compress_fragment_two_pass.h"
24*f4ee7fbaSAndroid Build Coastguard Worker #include "./encoder_dict.h"
25*f4ee7fbaSAndroid Build Coastguard Worker #include "./entropy_encode.h"
26*f4ee7fbaSAndroid Build Coastguard Worker #include "./fast_log.h"
27*f4ee7fbaSAndroid Build Coastguard Worker #include "./hash.h"
28*f4ee7fbaSAndroid Build Coastguard Worker #include "./histogram.h"
29*f4ee7fbaSAndroid Build Coastguard Worker #include "./memory.h"
30*f4ee7fbaSAndroid Build Coastguard Worker #include "./metablock.h"
31*f4ee7fbaSAndroid Build Coastguard Worker #include "./prefix.h"
32*f4ee7fbaSAndroid Build Coastguard Worker #include "./quality.h"
33*f4ee7fbaSAndroid Build Coastguard Worker #include "./ringbuffer.h"
34*f4ee7fbaSAndroid Build Coastguard Worker #include "./utf8_util.h"
35*f4ee7fbaSAndroid Build Coastguard Worker #include "./write_bits.h"
36*f4ee7fbaSAndroid Build Coastguard Worker 
37*f4ee7fbaSAndroid Build Coastguard Worker #if defined(__cplusplus) || defined(c_plusplus)
38*f4ee7fbaSAndroid Build Coastguard Worker extern "C" {
39*f4ee7fbaSAndroid Build Coastguard Worker #endif
40*f4ee7fbaSAndroid Build Coastguard Worker 
41*f4ee7fbaSAndroid Build Coastguard Worker #define COPY_ARRAY(dst, src) memcpy(dst, src, sizeof(src));
42*f4ee7fbaSAndroid Build Coastguard Worker 
43*f4ee7fbaSAndroid Build Coastguard Worker typedef enum BrotliEncoderStreamState {
44*f4ee7fbaSAndroid Build Coastguard Worker   /* Default state. */
45*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_STREAM_PROCESSING = 0,
46*f4ee7fbaSAndroid Build Coastguard Worker   /* Intermediate state; after next block is emitted, byte-padding should be
47*f4ee7fbaSAndroid Build Coastguard Worker      performed before getting back to default state. */
48*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_STREAM_FLUSH_REQUESTED = 1,
49*f4ee7fbaSAndroid Build Coastguard Worker   /* Last metablock was produced; no more input is acceptable. */
50*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_STREAM_FINISHED = 2,
51*f4ee7fbaSAndroid Build Coastguard Worker   /* Flushing compressed block and writing meta-data block header. */
52*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_STREAM_METADATA_HEAD = 3,
53*f4ee7fbaSAndroid Build Coastguard Worker   /* Writing metadata block body. */
54*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_STREAM_METADATA_BODY = 4
55*f4ee7fbaSAndroid Build Coastguard Worker } BrotliEncoderStreamState;
56*f4ee7fbaSAndroid Build Coastguard Worker 
57*f4ee7fbaSAndroid Build Coastguard Worker typedef enum BrotliEncoderFlintState {
58*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FLINT_NEEDS_2_BYTES = 2,
59*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FLINT_NEEDS_1_BYTE = 1,
60*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FLINT_WAITING_FOR_PROCESSING = 0,
61*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FLINT_WAITING_FOR_FLUSHING = -1,
62*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FLINT_DONE = -2
63*f4ee7fbaSAndroid Build Coastguard Worker } BrotliEncoderFlintState;
64*f4ee7fbaSAndroid Build Coastguard Worker 
65*f4ee7fbaSAndroid Build Coastguard Worker typedef struct BrotliEncoderStateStruct {
66*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderParams params;
67*f4ee7fbaSAndroid Build Coastguard Worker 
68*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager memory_manager_;
69*f4ee7fbaSAndroid Build Coastguard Worker 
70*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t input_pos_;
71*f4ee7fbaSAndroid Build Coastguard Worker   RingBuffer ringbuffer_;
72*f4ee7fbaSAndroid Build Coastguard Worker   size_t cmd_alloc_size_;
73*f4ee7fbaSAndroid Build Coastguard Worker   Command* commands_;
74*f4ee7fbaSAndroid Build Coastguard Worker   size_t num_commands_;
75*f4ee7fbaSAndroid Build Coastguard Worker   size_t num_literals_;
76*f4ee7fbaSAndroid Build Coastguard Worker   size_t last_insert_len_;
77*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t last_flush_pos_;
78*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t last_processed_pos_;
79*f4ee7fbaSAndroid Build Coastguard Worker   int dist_cache_[BROTLI_NUM_DISTANCE_SHORT_CODES];
80*f4ee7fbaSAndroid Build Coastguard Worker   int saved_dist_cache_[4];
81*f4ee7fbaSAndroid Build Coastguard Worker   uint16_t last_bytes_;
82*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t last_bytes_bits_;
83*f4ee7fbaSAndroid Build Coastguard Worker   /* "Flint" is a tiny uncompressed block emitted before the continuation
84*f4ee7fbaSAndroid Build Coastguard Worker      block to unwire literal context from previous data. Despite being int8_t,
85*f4ee7fbaSAndroid Build Coastguard Worker      field is actually BrotliEncoderFlintState enum. */
86*f4ee7fbaSAndroid Build Coastguard Worker   int8_t flint_;
87*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t prev_byte_;
88*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t prev_byte2_;
89*f4ee7fbaSAndroid Build Coastguard Worker   size_t storage_size_;
90*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* storage_;
91*f4ee7fbaSAndroid Build Coastguard Worker 
92*f4ee7fbaSAndroid Build Coastguard Worker   Hasher hasher_;
93*f4ee7fbaSAndroid Build Coastguard Worker 
94*f4ee7fbaSAndroid Build Coastguard Worker   /* Hash table for FAST_ONE_PASS_COMPRESSION_QUALITY mode. */
95*f4ee7fbaSAndroid Build Coastguard Worker   int small_table_[1 << 10];  /* 4KiB */
96*f4ee7fbaSAndroid Build Coastguard Worker   int* large_table_;          /* Allocated only when needed */
97*f4ee7fbaSAndroid Build Coastguard Worker   size_t large_table_size_;
98*f4ee7fbaSAndroid Build Coastguard Worker   /* Command and distance prefix codes (each 64 symbols, stored back-to-back)
99*f4ee7fbaSAndroid Build Coastguard Worker      used for the next block in FAST_ONE_PASS_COMPRESSION_QUALITY. The command
100*f4ee7fbaSAndroid Build Coastguard Worker      prefix code is over a smaller alphabet with the following 64 symbols:
101*f4ee7fbaSAndroid Build Coastguard Worker         0 - 15: insert length code 0, copy length code 0 - 15, same distance
102*f4ee7fbaSAndroid Build Coastguard Worker        16 - 39: insert length code 0, copy length code 0 - 23
103*f4ee7fbaSAndroid Build Coastguard Worker        40 - 63: insert length code 0 - 23, copy length code 0
104*f4ee7fbaSAndroid Build Coastguard Worker      Note that symbols 16 and 40 represent the same code in the full alphabet,
105*f4ee7fbaSAndroid Build Coastguard Worker      but we do not use either of them in FAST_ONE_PASS_COMPRESSION_QUALITY. */
106*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t cmd_depths_[128];
107*f4ee7fbaSAndroid Build Coastguard Worker   uint16_t cmd_bits_[128];
108*f4ee7fbaSAndroid Build Coastguard Worker   /* The compressed form of the command and distance prefix codes for the next
109*f4ee7fbaSAndroid Build Coastguard Worker      block in FAST_ONE_PASS_COMPRESSION_QUALITY. */
110*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t cmd_code_[512];
111*f4ee7fbaSAndroid Build Coastguard Worker   size_t cmd_code_numbits_;
112*f4ee7fbaSAndroid Build Coastguard Worker   /* Command and literal buffers for FAST_TWO_PASS_COMPRESSION_QUALITY. */
113*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t* command_buf_;
114*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* literal_buf_;
115*f4ee7fbaSAndroid Build Coastguard Worker 
116*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* next_out_;
117*f4ee7fbaSAndroid Build Coastguard Worker   size_t available_out_;
118*f4ee7fbaSAndroid Build Coastguard Worker   size_t total_out_;
119*f4ee7fbaSAndroid Build Coastguard Worker   /* Temporary buffer for padding flush bits or metadata block header / body. */
120*f4ee7fbaSAndroid Build Coastguard Worker   union {
121*f4ee7fbaSAndroid Build Coastguard Worker     uint64_t u64[2];
122*f4ee7fbaSAndroid Build Coastguard Worker     uint8_t u8[16];
123*f4ee7fbaSAndroid Build Coastguard Worker   } tiny_buf_;
124*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t remaining_metadata_bytes_;
125*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderStreamState stream_state_;
126*f4ee7fbaSAndroid Build Coastguard Worker 
127*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_BOOL is_last_block_emitted_;
128*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_BOOL is_initialized_;
129*f4ee7fbaSAndroid Build Coastguard Worker } BrotliEncoderStateStruct;
130*f4ee7fbaSAndroid Build Coastguard Worker 
InputBlockSize(BrotliEncoderState * s)131*f4ee7fbaSAndroid Build Coastguard Worker static size_t InputBlockSize(BrotliEncoderState* s) {
132*f4ee7fbaSAndroid Build Coastguard Worker   return (size_t)1 << s->params.lgblock;
133*f4ee7fbaSAndroid Build Coastguard Worker }
134*f4ee7fbaSAndroid Build Coastguard Worker 
UnprocessedInputSize(BrotliEncoderState * s)135*f4ee7fbaSAndroid Build Coastguard Worker static uint64_t UnprocessedInputSize(BrotliEncoderState* s) {
136*f4ee7fbaSAndroid Build Coastguard Worker   return s->input_pos_ - s->last_processed_pos_;
137*f4ee7fbaSAndroid Build Coastguard Worker }
138*f4ee7fbaSAndroid Build Coastguard Worker 
RemainingInputBlockSize(BrotliEncoderState * s)139*f4ee7fbaSAndroid Build Coastguard Worker static size_t RemainingInputBlockSize(BrotliEncoderState* s) {
140*f4ee7fbaSAndroid Build Coastguard Worker   const uint64_t delta = UnprocessedInputSize(s);
141*f4ee7fbaSAndroid Build Coastguard Worker   size_t block_size = InputBlockSize(s);
142*f4ee7fbaSAndroid Build Coastguard Worker   if (delta >= block_size) return 0;
143*f4ee7fbaSAndroid Build Coastguard Worker   return block_size - (size_t)delta;
144*f4ee7fbaSAndroid Build Coastguard Worker }
145*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderSetParameter(BrotliEncoderState * state,BrotliEncoderParameter p,uint32_t value)146*f4ee7fbaSAndroid Build Coastguard Worker BROTLI_BOOL BrotliEncoderSetParameter(
147*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderState* state, BrotliEncoderParameter p, uint32_t value) {
148*f4ee7fbaSAndroid Build Coastguard Worker   /* Changing parameters on the fly is not implemented yet. */
149*f4ee7fbaSAndroid Build Coastguard Worker   if (state->is_initialized_) return BROTLI_FALSE;
150*f4ee7fbaSAndroid Build Coastguard Worker   /* TODO: Validate/clamp parameters here. */
151*f4ee7fbaSAndroid Build Coastguard Worker   switch (p) {
152*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_MODE:
153*f4ee7fbaSAndroid Build Coastguard Worker       state->params.mode = (BrotliEncoderMode)value;
154*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
155*f4ee7fbaSAndroid Build Coastguard Worker 
156*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_QUALITY:
157*f4ee7fbaSAndroid Build Coastguard Worker       state->params.quality = (int)value;
158*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
159*f4ee7fbaSAndroid Build Coastguard Worker 
160*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_LGWIN:
161*f4ee7fbaSAndroid Build Coastguard Worker       state->params.lgwin = (int)value;
162*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
163*f4ee7fbaSAndroid Build Coastguard Worker 
164*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_LGBLOCK:
165*f4ee7fbaSAndroid Build Coastguard Worker       state->params.lgblock = (int)value;
166*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
167*f4ee7fbaSAndroid Build Coastguard Worker 
168*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:
169*f4ee7fbaSAndroid Build Coastguard Worker       if ((value != 0) && (value != 1)) return BROTLI_FALSE;
170*f4ee7fbaSAndroid Build Coastguard Worker       state->params.disable_literal_context_modeling = TO_BROTLI_BOOL(!!value);
171*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
172*f4ee7fbaSAndroid Build Coastguard Worker 
173*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_SIZE_HINT:
174*f4ee7fbaSAndroid Build Coastguard Worker       state->params.size_hint = value;
175*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
176*f4ee7fbaSAndroid Build Coastguard Worker 
177*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_LARGE_WINDOW:
178*f4ee7fbaSAndroid Build Coastguard Worker       state->params.large_window = TO_BROTLI_BOOL(!!value);
179*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
180*f4ee7fbaSAndroid Build Coastguard Worker 
181*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_NPOSTFIX:
182*f4ee7fbaSAndroid Build Coastguard Worker       state->params.dist.distance_postfix_bits = value;
183*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
184*f4ee7fbaSAndroid Build Coastguard Worker 
185*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_NDIRECT:
186*f4ee7fbaSAndroid Build Coastguard Worker       state->params.dist.num_direct_distance_codes = value;
187*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
188*f4ee7fbaSAndroid Build Coastguard Worker 
189*f4ee7fbaSAndroid Build Coastguard Worker     case BROTLI_PARAM_STREAM_OFFSET:
190*f4ee7fbaSAndroid Build Coastguard Worker       if (value > (1u << 30)) return BROTLI_FALSE;
191*f4ee7fbaSAndroid Build Coastguard Worker       state->params.stream_offset = value;
192*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
193*f4ee7fbaSAndroid Build Coastguard Worker 
194*f4ee7fbaSAndroid Build Coastguard Worker     default: return BROTLI_FALSE;
195*f4ee7fbaSAndroid Build Coastguard Worker   }
196*f4ee7fbaSAndroid Build Coastguard Worker }
197*f4ee7fbaSAndroid Build Coastguard Worker 
198*f4ee7fbaSAndroid Build Coastguard Worker /* Wraps 64-bit input position to 32-bit ring-buffer position preserving
199*f4ee7fbaSAndroid Build Coastguard Worker    "not-a-first-lap" feature. */
WrapPosition(uint64_t position)200*f4ee7fbaSAndroid Build Coastguard Worker static uint32_t WrapPosition(uint64_t position) {
201*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t result = (uint32_t)position;
202*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t gb = position >> 30;
203*f4ee7fbaSAndroid Build Coastguard Worker   if (gb > 2) {
204*f4ee7fbaSAndroid Build Coastguard Worker     /* Wrap every 2GiB; The first 3GB are continuous. */
205*f4ee7fbaSAndroid Build Coastguard Worker     result = (result & ((1u << 30) - 1)) | ((uint32_t)((gb - 1) & 1) + 1) << 30;
206*f4ee7fbaSAndroid Build Coastguard Worker   }
207*f4ee7fbaSAndroid Build Coastguard Worker   return result;
208*f4ee7fbaSAndroid Build Coastguard Worker }
209*f4ee7fbaSAndroid Build Coastguard Worker 
GetBrotliStorage(BrotliEncoderState * s,size_t size)210*f4ee7fbaSAndroid Build Coastguard Worker static uint8_t* GetBrotliStorage(BrotliEncoderState* s, size_t size) {
211*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager* m = &s->memory_manager_;
212*f4ee7fbaSAndroid Build Coastguard Worker   if (s->storage_size_ < size) {
213*f4ee7fbaSAndroid Build Coastguard Worker     BROTLI_FREE(m, s->storage_);
214*f4ee7fbaSAndroid Build Coastguard Worker     s->storage_ = BROTLI_ALLOC(m, uint8_t, size);
215*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(s->storage_)) return NULL;
216*f4ee7fbaSAndroid Build Coastguard Worker     s->storage_size_ = size;
217*f4ee7fbaSAndroid Build Coastguard Worker   }
218*f4ee7fbaSAndroid Build Coastguard Worker   return s->storage_;
219*f4ee7fbaSAndroid Build Coastguard Worker }
220*f4ee7fbaSAndroid Build Coastguard Worker 
HashTableSize(size_t max_table_size,size_t input_size)221*f4ee7fbaSAndroid Build Coastguard Worker static size_t HashTableSize(size_t max_table_size, size_t input_size) {
222*f4ee7fbaSAndroid Build Coastguard Worker   size_t htsize = 256;
223*f4ee7fbaSAndroid Build Coastguard Worker   while (htsize < max_table_size && htsize < input_size) {
224*f4ee7fbaSAndroid Build Coastguard Worker     htsize <<= 1;
225*f4ee7fbaSAndroid Build Coastguard Worker   }
226*f4ee7fbaSAndroid Build Coastguard Worker   return htsize;
227*f4ee7fbaSAndroid Build Coastguard Worker }
228*f4ee7fbaSAndroid Build Coastguard Worker 
GetHashTable(BrotliEncoderState * s,int quality,size_t input_size,size_t * table_size)229*f4ee7fbaSAndroid Build Coastguard Worker static int* GetHashTable(BrotliEncoderState* s, int quality,
230*f4ee7fbaSAndroid Build Coastguard Worker                          size_t input_size, size_t* table_size) {
231*f4ee7fbaSAndroid Build Coastguard Worker   /* Use smaller hash table when input.size() is smaller, since we
232*f4ee7fbaSAndroid Build Coastguard Worker      fill the table, incurring O(hash table size) overhead for
233*f4ee7fbaSAndroid Build Coastguard Worker      compression, and if the input is short, we won't need that
234*f4ee7fbaSAndroid Build Coastguard Worker      many hash table entries anyway. */
235*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager* m = &s->memory_manager_;
236*f4ee7fbaSAndroid Build Coastguard Worker   const size_t max_table_size = MaxHashTableSize(quality);
237*f4ee7fbaSAndroid Build Coastguard Worker   size_t htsize = HashTableSize(max_table_size, input_size);
238*f4ee7fbaSAndroid Build Coastguard Worker   int* table;
239*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_DCHECK(max_table_size >= 256);
240*f4ee7fbaSAndroid Build Coastguard Worker   if (quality == FAST_ONE_PASS_COMPRESSION_QUALITY) {
241*f4ee7fbaSAndroid Build Coastguard Worker     /* Only odd shifts are supported by fast-one-pass. */
242*f4ee7fbaSAndroid Build Coastguard Worker     if ((htsize & 0xAAAAA) == 0) {
243*f4ee7fbaSAndroid Build Coastguard Worker       htsize <<= 1;
244*f4ee7fbaSAndroid Build Coastguard Worker     }
245*f4ee7fbaSAndroid Build Coastguard Worker   }
246*f4ee7fbaSAndroid Build Coastguard Worker 
247*f4ee7fbaSAndroid Build Coastguard Worker   if (htsize <= sizeof(s->small_table_) / sizeof(s->small_table_[0])) {
248*f4ee7fbaSAndroid Build Coastguard Worker     table = s->small_table_;
249*f4ee7fbaSAndroid Build Coastguard Worker   } else {
250*f4ee7fbaSAndroid Build Coastguard Worker     if (htsize > s->large_table_size_) {
251*f4ee7fbaSAndroid Build Coastguard Worker       s->large_table_size_ = htsize;
252*f4ee7fbaSAndroid Build Coastguard Worker       BROTLI_FREE(m, s->large_table_);
253*f4ee7fbaSAndroid Build Coastguard Worker       s->large_table_ = BROTLI_ALLOC(m, int, htsize);
254*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(s->large_table_)) return 0;
255*f4ee7fbaSAndroid Build Coastguard Worker     }
256*f4ee7fbaSAndroid Build Coastguard Worker     table = s->large_table_;
257*f4ee7fbaSAndroid Build Coastguard Worker   }
258*f4ee7fbaSAndroid Build Coastguard Worker 
259*f4ee7fbaSAndroid Build Coastguard Worker   *table_size = htsize;
260*f4ee7fbaSAndroid Build Coastguard Worker   memset(table, 0, htsize * sizeof(*table));
261*f4ee7fbaSAndroid Build Coastguard Worker   return table;
262*f4ee7fbaSAndroid Build Coastguard Worker }
263*f4ee7fbaSAndroid Build Coastguard Worker 
EncodeWindowBits(int lgwin,BROTLI_BOOL large_window,uint16_t * last_bytes,uint8_t * last_bytes_bits)264*f4ee7fbaSAndroid Build Coastguard Worker static void EncodeWindowBits(int lgwin, BROTLI_BOOL large_window,
265*f4ee7fbaSAndroid Build Coastguard Worker     uint16_t* last_bytes, uint8_t* last_bytes_bits) {
266*f4ee7fbaSAndroid Build Coastguard Worker   if (large_window) {
267*f4ee7fbaSAndroid Build Coastguard Worker     *last_bytes = (uint16_t)(((lgwin & 0x3F) << 8) | 0x11);
268*f4ee7fbaSAndroid Build Coastguard Worker     *last_bytes_bits = 14;
269*f4ee7fbaSAndroid Build Coastguard Worker   } else {
270*f4ee7fbaSAndroid Build Coastguard Worker     if (lgwin == 16) {
271*f4ee7fbaSAndroid Build Coastguard Worker       *last_bytes = 0;
272*f4ee7fbaSAndroid Build Coastguard Worker       *last_bytes_bits = 1;
273*f4ee7fbaSAndroid Build Coastguard Worker     } else if (lgwin == 17) {
274*f4ee7fbaSAndroid Build Coastguard Worker       *last_bytes = 1;
275*f4ee7fbaSAndroid Build Coastguard Worker       *last_bytes_bits = 7;
276*f4ee7fbaSAndroid Build Coastguard Worker     } else if (lgwin > 17) {
277*f4ee7fbaSAndroid Build Coastguard Worker       *last_bytes = (uint16_t)(((lgwin - 17) << 1) | 0x01);
278*f4ee7fbaSAndroid Build Coastguard Worker       *last_bytes_bits = 4;
279*f4ee7fbaSAndroid Build Coastguard Worker     } else {
280*f4ee7fbaSAndroid Build Coastguard Worker       *last_bytes = (uint16_t)(((lgwin - 8) << 4) | 0x01);
281*f4ee7fbaSAndroid Build Coastguard Worker       *last_bytes_bits = 7;
282*f4ee7fbaSAndroid Build Coastguard Worker     }
283*f4ee7fbaSAndroid Build Coastguard Worker   }
284*f4ee7fbaSAndroid Build Coastguard Worker }
285*f4ee7fbaSAndroid Build Coastguard Worker 
286*f4ee7fbaSAndroid Build Coastguard Worker /* Initializes the command and distance prefix codes for the first block. */
InitCommandPrefixCodes(uint8_t cmd_depths[128],uint16_t cmd_bits[128],uint8_t cmd_code[512],size_t * cmd_code_numbits)287*f4ee7fbaSAndroid Build Coastguard Worker static void InitCommandPrefixCodes(uint8_t cmd_depths[128],
288*f4ee7fbaSAndroid Build Coastguard Worker                                    uint16_t cmd_bits[128],
289*f4ee7fbaSAndroid Build Coastguard Worker                                    uint8_t cmd_code[512],
290*f4ee7fbaSAndroid Build Coastguard Worker                                    size_t* cmd_code_numbits) {
291*f4ee7fbaSAndroid Build Coastguard Worker   static const uint8_t kDefaultCommandDepths[128] = {
292*f4ee7fbaSAndroid Build Coastguard Worker     0, 4, 4, 5, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
293*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 0, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7,
294*f4ee7fbaSAndroid Build Coastguard Worker     7, 7, 10, 10, 10, 10, 10, 10, 0, 4, 4, 5, 5, 5, 6, 6,
295*f4ee7fbaSAndroid Build Coastguard Worker     7, 8, 8, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
296*f4ee7fbaSAndroid Build Coastguard Worker     5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
297*f4ee7fbaSAndroid Build Coastguard Worker     6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4,
298*f4ee7fbaSAndroid Build Coastguard Worker     4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 10,
299*f4ee7fbaSAndroid Build Coastguard Worker     12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
300*f4ee7fbaSAndroid Build Coastguard Worker   };
301*f4ee7fbaSAndroid Build Coastguard Worker   static const uint16_t kDefaultCommandBits[128] = {
302*f4ee7fbaSAndroid Build Coastguard Worker     0,   0,   8,   9,   3,  35,   7,   71,
303*f4ee7fbaSAndroid Build Coastguard Worker     39, 103,  23,  47, 175, 111, 239,   31,
304*f4ee7fbaSAndroid Build Coastguard Worker     0,   0,   0,   4,  12,   2,  10,    6,
305*f4ee7fbaSAndroid Build Coastguard Worker     13,  29,  11,  43,  27,  59,  87,   55,
306*f4ee7fbaSAndroid Build Coastguard Worker     15,  79, 319, 831, 191, 703, 447,  959,
307*f4ee7fbaSAndroid Build Coastguard Worker     0,  14,   1,  25,   5,  21,  19,   51,
308*f4ee7fbaSAndroid Build Coastguard Worker     119, 159,  95, 223, 479, 991,  63,  575,
309*f4ee7fbaSAndroid Build Coastguard Worker     127, 639, 383, 895, 255, 767, 511, 1023,
310*f4ee7fbaSAndroid Build Coastguard Worker     14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
311*f4ee7fbaSAndroid Build Coastguard Worker     27, 59, 7, 39, 23, 55, 30, 1, 17, 9, 25, 5, 0, 8, 4, 12,
312*f4ee7fbaSAndroid Build Coastguard Worker     2, 10, 6, 21, 13, 29, 3, 19, 11, 15, 47, 31, 95, 63, 127, 255,
313*f4ee7fbaSAndroid Build Coastguard Worker     767, 2815, 1791, 3839, 511, 2559, 1535, 3583, 1023, 3071, 2047, 4095,
314*f4ee7fbaSAndroid Build Coastguard Worker   };
315*f4ee7fbaSAndroid Build Coastguard Worker   static const uint8_t kDefaultCommandCode[] = {
316*f4ee7fbaSAndroid Build Coastguard Worker     0xff, 0x77, 0xd5, 0xbf, 0xe7, 0xde, 0xea, 0x9e, 0x51, 0x5d, 0xde, 0xc6,
317*f4ee7fbaSAndroid Build Coastguard Worker     0x70, 0x57, 0xbc, 0x58, 0x58, 0x58, 0xd8, 0xd8, 0x58, 0xd5, 0xcb, 0x8c,
318*f4ee7fbaSAndroid Build Coastguard Worker     0xea, 0xe0, 0xc3, 0x87, 0x1f, 0x83, 0xc1, 0x60, 0x1c, 0x67, 0xb2, 0xaa,
319*f4ee7fbaSAndroid Build Coastguard Worker     0x06, 0x83, 0xc1, 0x60, 0x30, 0x18, 0xcc, 0xa1, 0xce, 0x88, 0x54, 0x94,
320*f4ee7fbaSAndroid Build Coastguard Worker     0x46, 0xe1, 0xb0, 0xd0, 0x4e, 0xb2, 0xf7, 0x04, 0x00,
321*f4ee7fbaSAndroid Build Coastguard Worker   };
322*f4ee7fbaSAndroid Build Coastguard Worker   static const size_t kDefaultCommandCodeNumBits = 448;
323*f4ee7fbaSAndroid Build Coastguard Worker   COPY_ARRAY(cmd_depths, kDefaultCommandDepths);
324*f4ee7fbaSAndroid Build Coastguard Worker   COPY_ARRAY(cmd_bits, kDefaultCommandBits);
325*f4ee7fbaSAndroid Build Coastguard Worker 
326*f4ee7fbaSAndroid Build Coastguard Worker   /* Initialize the pre-compressed form of the command and distance prefix
327*f4ee7fbaSAndroid Build Coastguard Worker      codes. */
328*f4ee7fbaSAndroid Build Coastguard Worker   COPY_ARRAY(cmd_code, kDefaultCommandCode);
329*f4ee7fbaSAndroid Build Coastguard Worker   *cmd_code_numbits = kDefaultCommandCodeNumBits;
330*f4ee7fbaSAndroid Build Coastguard Worker }
331*f4ee7fbaSAndroid Build Coastguard Worker 
332*f4ee7fbaSAndroid Build Coastguard Worker /* Decide about the context map based on the ability of the prediction
333*f4ee7fbaSAndroid Build Coastguard Worker    ability of the previous byte UTF8-prefix on the next byte. The
334*f4ee7fbaSAndroid Build Coastguard Worker    prediction ability is calculated as Shannon entropy. Here we need
335*f4ee7fbaSAndroid Build Coastguard Worker    Shannon entropy instead of 'BitsEntropy' since the prefix will be
336*f4ee7fbaSAndroid Build Coastguard Worker    encoded with the remaining 6 bits of the following byte, and
337*f4ee7fbaSAndroid Build Coastguard Worker    BitsEntropy will assume that symbol to be stored alone using Huffman
338*f4ee7fbaSAndroid Build Coastguard Worker    coding. */
ChooseContextMap(int quality,uint32_t * bigram_histo,size_t * num_literal_contexts,const uint32_t ** literal_context_map)339*f4ee7fbaSAndroid Build Coastguard Worker static void ChooseContextMap(int quality,
340*f4ee7fbaSAndroid Build Coastguard Worker                              uint32_t* bigram_histo,
341*f4ee7fbaSAndroid Build Coastguard Worker                              size_t* num_literal_contexts,
342*f4ee7fbaSAndroid Build Coastguard Worker                              const uint32_t** literal_context_map) {
343*f4ee7fbaSAndroid Build Coastguard Worker   static const uint32_t kStaticContextMapContinuation[64] = {
344*f4ee7fbaSAndroid Build Coastguard Worker     1, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
345*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
346*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
347*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
348*f4ee7fbaSAndroid Build Coastguard Worker   };
349*f4ee7fbaSAndroid Build Coastguard Worker   static const uint32_t kStaticContextMapSimpleUTF8[64] = {
350*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
351*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
352*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
353*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
354*f4ee7fbaSAndroid Build Coastguard Worker   };
355*f4ee7fbaSAndroid Build Coastguard Worker 
356*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t monogram_histo[3] = { 0 };
357*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t two_prefix_histo[6] = { 0 };
358*f4ee7fbaSAndroid Build Coastguard Worker   size_t total;
359*f4ee7fbaSAndroid Build Coastguard Worker   size_t i;
360*f4ee7fbaSAndroid Build Coastguard Worker   size_t dummy;
361*f4ee7fbaSAndroid Build Coastguard Worker   double entropy[4];
362*f4ee7fbaSAndroid Build Coastguard Worker   for (i = 0; i < 9; ++i) {
363*f4ee7fbaSAndroid Build Coastguard Worker     monogram_histo[i % 3] += bigram_histo[i];
364*f4ee7fbaSAndroid Build Coastguard Worker     two_prefix_histo[i % 6] += bigram_histo[i];
365*f4ee7fbaSAndroid Build Coastguard Worker   }
366*f4ee7fbaSAndroid Build Coastguard Worker   entropy[1] = ShannonEntropy(monogram_histo, 3, &dummy);
367*f4ee7fbaSAndroid Build Coastguard Worker   entropy[2] = (ShannonEntropy(two_prefix_histo, 3, &dummy) +
368*f4ee7fbaSAndroid Build Coastguard Worker                 ShannonEntropy(two_prefix_histo + 3, 3, &dummy));
369*f4ee7fbaSAndroid Build Coastguard Worker   entropy[3] = 0;
370*f4ee7fbaSAndroid Build Coastguard Worker   for (i = 0; i < 3; ++i) {
371*f4ee7fbaSAndroid Build Coastguard Worker     entropy[3] += ShannonEntropy(bigram_histo + 3 * i, 3, &dummy);
372*f4ee7fbaSAndroid Build Coastguard Worker   }
373*f4ee7fbaSAndroid Build Coastguard Worker 
374*f4ee7fbaSAndroid Build Coastguard Worker   total = monogram_histo[0] + monogram_histo[1] + monogram_histo[2];
375*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_DCHECK(total != 0);
376*f4ee7fbaSAndroid Build Coastguard Worker   entropy[0] = 1.0 / (double)total;
377*f4ee7fbaSAndroid Build Coastguard Worker   entropy[1] *= entropy[0];
378*f4ee7fbaSAndroid Build Coastguard Worker   entropy[2] *= entropy[0];
379*f4ee7fbaSAndroid Build Coastguard Worker   entropy[3] *= entropy[0];
380*f4ee7fbaSAndroid Build Coastguard Worker 
381*f4ee7fbaSAndroid Build Coastguard Worker   if (quality < MIN_QUALITY_FOR_HQ_CONTEXT_MODELING) {
382*f4ee7fbaSAndroid Build Coastguard Worker     /* 3 context models is a bit slower, don't use it at lower qualities. */
383*f4ee7fbaSAndroid Build Coastguard Worker     entropy[3] = entropy[1] * 10;
384*f4ee7fbaSAndroid Build Coastguard Worker   }
385*f4ee7fbaSAndroid Build Coastguard Worker   /* If expected savings by symbol are less than 0.2 bits, skip the
386*f4ee7fbaSAndroid Build Coastguard Worker      context modeling -- in exchange for faster decoding speed. */
387*f4ee7fbaSAndroid Build Coastguard Worker   if (entropy[1] - entropy[2] < 0.2 &&
388*f4ee7fbaSAndroid Build Coastguard Worker       entropy[1] - entropy[3] < 0.2) {
389*f4ee7fbaSAndroid Build Coastguard Worker     *num_literal_contexts = 1;
390*f4ee7fbaSAndroid Build Coastguard Worker   } else if (entropy[2] - entropy[3] < 0.02) {
391*f4ee7fbaSAndroid Build Coastguard Worker     *num_literal_contexts = 2;
392*f4ee7fbaSAndroid Build Coastguard Worker     *literal_context_map = kStaticContextMapSimpleUTF8;
393*f4ee7fbaSAndroid Build Coastguard Worker   } else {
394*f4ee7fbaSAndroid Build Coastguard Worker     *num_literal_contexts = 3;
395*f4ee7fbaSAndroid Build Coastguard Worker     *literal_context_map = kStaticContextMapContinuation;
396*f4ee7fbaSAndroid Build Coastguard Worker   }
397*f4ee7fbaSAndroid Build Coastguard Worker }
398*f4ee7fbaSAndroid Build Coastguard Worker 
399*f4ee7fbaSAndroid Build Coastguard Worker /* Decide if we want to use a more complex static context map containing 13
400*f4ee7fbaSAndroid Build Coastguard Worker    context values, based on the entropy reduction of histograms over the
401*f4ee7fbaSAndroid Build Coastguard Worker    first 5 bits of literals. */
ShouldUseComplexStaticContextMap(const uint8_t * input,size_t start_pos,size_t length,size_t mask,int quality,size_t size_hint,size_t * num_literal_contexts,const uint32_t ** literal_context_map)402*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL ShouldUseComplexStaticContextMap(const uint8_t* input,
403*f4ee7fbaSAndroid Build Coastguard Worker     size_t start_pos, size_t length, size_t mask, int quality, size_t size_hint,
404*f4ee7fbaSAndroid Build Coastguard Worker     size_t* num_literal_contexts, const uint32_t** literal_context_map) {
405*f4ee7fbaSAndroid Build Coastguard Worker   static const uint32_t kStaticContextMapComplexUTF8[64] = {
406*f4ee7fbaSAndroid Build Coastguard Worker     11, 11, 12, 12, /* 0 special */
407*f4ee7fbaSAndroid Build Coastguard Worker     0, 0, 0, 0, /* 4 lf */
408*f4ee7fbaSAndroid Build Coastguard Worker     1, 1, 9, 9, /* 8 space */
409*f4ee7fbaSAndroid Build Coastguard Worker     2, 2, 2, 2, /* !, first after space/lf and after something else. */
410*f4ee7fbaSAndroid Build Coastguard Worker     1, 1, 1, 1, /* " */
411*f4ee7fbaSAndroid Build Coastguard Worker     8, 3, 3, 3, /* % */
412*f4ee7fbaSAndroid Build Coastguard Worker     1, 1, 1, 1, /* ({[ */
413*f4ee7fbaSAndroid Build Coastguard Worker     2, 2, 2, 2, /* }]) */
414*f4ee7fbaSAndroid Build Coastguard Worker     8, 4, 4, 4, /* :; */
415*f4ee7fbaSAndroid Build Coastguard Worker     8, 7, 4, 4, /* . */
416*f4ee7fbaSAndroid Build Coastguard Worker     8, 0, 0, 0, /* > */
417*f4ee7fbaSAndroid Build Coastguard Worker     3, 3, 3, 3, /* [0..9] */
418*f4ee7fbaSAndroid Build Coastguard Worker     5, 5, 10, 5, /* [A-Z] */
419*f4ee7fbaSAndroid Build Coastguard Worker     5, 5, 10, 5,
420*f4ee7fbaSAndroid Build Coastguard Worker     6, 6, 6, 6, /* [a-z] */
421*f4ee7fbaSAndroid Build Coastguard Worker     6, 6, 6, 6,
422*f4ee7fbaSAndroid Build Coastguard Worker   };
423*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_UNUSED(quality);
424*f4ee7fbaSAndroid Build Coastguard Worker   /* Try the more complex static context map only for long data. */
425*f4ee7fbaSAndroid Build Coastguard Worker   if (size_hint < (1 << 20)) {
426*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_FALSE;
427*f4ee7fbaSAndroid Build Coastguard Worker   } else {
428*f4ee7fbaSAndroid Build Coastguard Worker     const size_t end_pos = start_pos + length;
429*f4ee7fbaSAndroid Build Coastguard Worker     /* To make entropy calculations faster and to fit on the stack, we collect
430*f4ee7fbaSAndroid Build Coastguard Worker        histograms over the 5 most significant bits of literals. One histogram
431*f4ee7fbaSAndroid Build Coastguard Worker        without context and 13 additional histograms for each context value. */
432*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t combined_histo[32] = { 0 };
433*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t context_histo[13][32] = { { 0 } };
434*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t total = 0;
435*f4ee7fbaSAndroid Build Coastguard Worker     double entropy[3];
436*f4ee7fbaSAndroid Build Coastguard Worker     size_t dummy;
437*f4ee7fbaSAndroid Build Coastguard Worker     size_t i;
438*f4ee7fbaSAndroid Build Coastguard Worker     ContextLut utf8_lut = BROTLI_CONTEXT_LUT(CONTEXT_UTF8);
439*f4ee7fbaSAndroid Build Coastguard Worker     for (; start_pos + 64 <= end_pos; start_pos += 4096) {
440*f4ee7fbaSAndroid Build Coastguard Worker       const size_t stride_end_pos = start_pos + 64;
441*f4ee7fbaSAndroid Build Coastguard Worker       uint8_t prev2 = input[start_pos & mask];
442*f4ee7fbaSAndroid Build Coastguard Worker       uint8_t prev1 = input[(start_pos + 1) & mask];
443*f4ee7fbaSAndroid Build Coastguard Worker       size_t pos;
444*f4ee7fbaSAndroid Build Coastguard Worker       /* To make the analysis of the data faster we only examine 64 byte long
445*f4ee7fbaSAndroid Build Coastguard Worker          strides at every 4kB intervals. */
446*f4ee7fbaSAndroid Build Coastguard Worker       for (pos = start_pos + 2; pos < stride_end_pos; ++pos) {
447*f4ee7fbaSAndroid Build Coastguard Worker         const uint8_t literal = input[pos & mask];
448*f4ee7fbaSAndroid Build Coastguard Worker         const uint8_t context = (uint8_t)kStaticContextMapComplexUTF8[
449*f4ee7fbaSAndroid Build Coastguard Worker             BROTLI_CONTEXT(prev1, prev2, utf8_lut)];
450*f4ee7fbaSAndroid Build Coastguard Worker         ++total;
451*f4ee7fbaSAndroid Build Coastguard Worker         ++combined_histo[literal >> 3];
452*f4ee7fbaSAndroid Build Coastguard Worker         ++context_histo[context][literal >> 3];
453*f4ee7fbaSAndroid Build Coastguard Worker         prev2 = prev1;
454*f4ee7fbaSAndroid Build Coastguard Worker         prev1 = literal;
455*f4ee7fbaSAndroid Build Coastguard Worker       }
456*f4ee7fbaSAndroid Build Coastguard Worker     }
457*f4ee7fbaSAndroid Build Coastguard Worker     entropy[1] = ShannonEntropy(combined_histo, 32, &dummy);
458*f4ee7fbaSAndroid Build Coastguard Worker     entropy[2] = 0;
459*f4ee7fbaSAndroid Build Coastguard Worker     for (i = 0; i < 13; ++i) {
460*f4ee7fbaSAndroid Build Coastguard Worker       entropy[2] += ShannonEntropy(&context_histo[i][0], 32, &dummy);
461*f4ee7fbaSAndroid Build Coastguard Worker     }
462*f4ee7fbaSAndroid Build Coastguard Worker     entropy[0] = 1.0 / (double)total;
463*f4ee7fbaSAndroid Build Coastguard Worker     entropy[1] *= entropy[0];
464*f4ee7fbaSAndroid Build Coastguard Worker     entropy[2] *= entropy[0];
465*f4ee7fbaSAndroid Build Coastguard Worker     /* The triggering heuristics below were tuned by compressing the individual
466*f4ee7fbaSAndroid Build Coastguard Worker        files of the silesia corpus. If we skip this kind of context modeling
467*f4ee7fbaSAndroid Build Coastguard Worker        for not very well compressible input (i.e. entropy using context modeling
468*f4ee7fbaSAndroid Build Coastguard Worker        is 60% of maximal entropy) or if expected savings by symbol are less
469*f4ee7fbaSAndroid Build Coastguard Worker        than 0.2 bits, then in every case when it triggers, the final compression
470*f4ee7fbaSAndroid Build Coastguard Worker        ratio is improved. Note however that this heuristics might be too strict
471*f4ee7fbaSAndroid Build Coastguard Worker        for some cases and could be tuned further. */
472*f4ee7fbaSAndroid Build Coastguard Worker     if (entropy[2] > 3.0 || entropy[1] - entropy[2] < 0.2) {
473*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_FALSE;
474*f4ee7fbaSAndroid Build Coastguard Worker     } else {
475*f4ee7fbaSAndroid Build Coastguard Worker       *num_literal_contexts = 13;
476*f4ee7fbaSAndroid Build Coastguard Worker       *literal_context_map = kStaticContextMapComplexUTF8;
477*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
478*f4ee7fbaSAndroid Build Coastguard Worker     }
479*f4ee7fbaSAndroid Build Coastguard Worker   }
480*f4ee7fbaSAndroid Build Coastguard Worker }
481*f4ee7fbaSAndroid Build Coastguard Worker 
DecideOverLiteralContextModeling(const uint8_t * input,size_t start_pos,size_t length,size_t mask,int quality,size_t size_hint,size_t * num_literal_contexts,const uint32_t ** literal_context_map)482*f4ee7fbaSAndroid Build Coastguard Worker static void DecideOverLiteralContextModeling(const uint8_t* input,
483*f4ee7fbaSAndroid Build Coastguard Worker     size_t start_pos, size_t length, size_t mask, int quality, size_t size_hint,
484*f4ee7fbaSAndroid Build Coastguard Worker     size_t* num_literal_contexts, const uint32_t** literal_context_map) {
485*f4ee7fbaSAndroid Build Coastguard Worker   if (quality < MIN_QUALITY_FOR_CONTEXT_MODELING || length < 64) {
486*f4ee7fbaSAndroid Build Coastguard Worker     return;
487*f4ee7fbaSAndroid Build Coastguard Worker   } else if (ShouldUseComplexStaticContextMap(
488*f4ee7fbaSAndroid Build Coastguard Worker       input, start_pos, length, mask, quality, size_hint,
489*f4ee7fbaSAndroid Build Coastguard Worker       num_literal_contexts, literal_context_map)) {
490*f4ee7fbaSAndroid Build Coastguard Worker     /* Context map was already set, nothing else to do. */
491*f4ee7fbaSAndroid Build Coastguard Worker   } else {
492*f4ee7fbaSAndroid Build Coastguard Worker     /* Gather bi-gram data of the UTF8 byte prefixes. To make the analysis of
493*f4ee7fbaSAndroid Build Coastguard Worker        UTF8 data faster we only examine 64 byte long strides at every 4kB
494*f4ee7fbaSAndroid Build Coastguard Worker        intervals. */
495*f4ee7fbaSAndroid Build Coastguard Worker     const size_t end_pos = start_pos + length;
496*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t bigram_prefix_histo[9] = { 0 };
497*f4ee7fbaSAndroid Build Coastguard Worker     for (; start_pos + 64 <= end_pos; start_pos += 4096) {
498*f4ee7fbaSAndroid Build Coastguard Worker       static const int lut[4] = { 0, 0, 1, 2 };
499*f4ee7fbaSAndroid Build Coastguard Worker       const size_t stride_end_pos = start_pos + 64;
500*f4ee7fbaSAndroid Build Coastguard Worker       int prev = lut[input[start_pos & mask] >> 6] * 3;
501*f4ee7fbaSAndroid Build Coastguard Worker       size_t pos;
502*f4ee7fbaSAndroid Build Coastguard Worker       for (pos = start_pos + 1; pos < stride_end_pos; ++pos) {
503*f4ee7fbaSAndroid Build Coastguard Worker         const uint8_t literal = input[pos & mask];
504*f4ee7fbaSAndroid Build Coastguard Worker         ++bigram_prefix_histo[prev + lut[literal >> 6]];
505*f4ee7fbaSAndroid Build Coastguard Worker         prev = lut[literal >> 6] * 3;
506*f4ee7fbaSAndroid Build Coastguard Worker       }
507*f4ee7fbaSAndroid Build Coastguard Worker     }
508*f4ee7fbaSAndroid Build Coastguard Worker     ChooseContextMap(quality, &bigram_prefix_histo[0], num_literal_contexts,
509*f4ee7fbaSAndroid Build Coastguard Worker                      literal_context_map);
510*f4ee7fbaSAndroid Build Coastguard Worker   }
511*f4ee7fbaSAndroid Build Coastguard Worker }
512*f4ee7fbaSAndroid Build Coastguard Worker 
ShouldCompress(const uint8_t * data,const size_t mask,const uint64_t last_flush_pos,const size_t bytes,const size_t num_literals,const size_t num_commands)513*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL ShouldCompress(
514*f4ee7fbaSAndroid Build Coastguard Worker     const uint8_t* data, const size_t mask, const uint64_t last_flush_pos,
515*f4ee7fbaSAndroid Build Coastguard Worker     const size_t bytes, const size_t num_literals, const size_t num_commands) {
516*f4ee7fbaSAndroid Build Coastguard Worker   /* TODO: find more precise minimal block overhead. */
517*f4ee7fbaSAndroid Build Coastguard Worker   if (bytes <= 2) return BROTLI_FALSE;
518*f4ee7fbaSAndroid Build Coastguard Worker   if (num_commands < (bytes >> 8) + 2) {
519*f4ee7fbaSAndroid Build Coastguard Worker     if ((double)num_literals > 0.99 * (double)bytes) {
520*f4ee7fbaSAndroid Build Coastguard Worker       uint32_t literal_histo[256] = { 0 };
521*f4ee7fbaSAndroid Build Coastguard Worker       static const uint32_t kSampleRate = 13;
522*f4ee7fbaSAndroid Build Coastguard Worker       static const double kMinEntropy = 7.92;
523*f4ee7fbaSAndroid Build Coastguard Worker       const double bit_cost_threshold =
524*f4ee7fbaSAndroid Build Coastguard Worker           (double)bytes * kMinEntropy / kSampleRate;
525*f4ee7fbaSAndroid Build Coastguard Worker       size_t t = (bytes + kSampleRate - 1) / kSampleRate;
526*f4ee7fbaSAndroid Build Coastguard Worker       uint32_t pos = (uint32_t)last_flush_pos;
527*f4ee7fbaSAndroid Build Coastguard Worker       size_t i;
528*f4ee7fbaSAndroid Build Coastguard Worker       for (i = 0; i < t; i++) {
529*f4ee7fbaSAndroid Build Coastguard Worker         ++literal_histo[data[pos & mask]];
530*f4ee7fbaSAndroid Build Coastguard Worker         pos += kSampleRate;
531*f4ee7fbaSAndroid Build Coastguard Worker       }
532*f4ee7fbaSAndroid Build Coastguard Worker       if (BitsEntropy(literal_histo, 256) > bit_cost_threshold) {
533*f4ee7fbaSAndroid Build Coastguard Worker         return BROTLI_FALSE;
534*f4ee7fbaSAndroid Build Coastguard Worker       }
535*f4ee7fbaSAndroid Build Coastguard Worker     }
536*f4ee7fbaSAndroid Build Coastguard Worker   }
537*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_TRUE;
538*f4ee7fbaSAndroid Build Coastguard Worker }
539*f4ee7fbaSAndroid Build Coastguard Worker 
540*f4ee7fbaSAndroid Build Coastguard Worker /* Chooses the literal context mode for a metablock */
ChooseContextMode(const BrotliEncoderParams * params,const uint8_t * data,const size_t pos,const size_t mask,const size_t length)541*f4ee7fbaSAndroid Build Coastguard Worker static ContextType ChooseContextMode(const BrotliEncoderParams* params,
542*f4ee7fbaSAndroid Build Coastguard Worker     const uint8_t* data, const size_t pos, const size_t mask,
543*f4ee7fbaSAndroid Build Coastguard Worker     const size_t length) {
544*f4ee7fbaSAndroid Build Coastguard Worker   /* We only do the computation for the option of something else than
545*f4ee7fbaSAndroid Build Coastguard Worker      CONTEXT_UTF8 for the highest qualities */
546*f4ee7fbaSAndroid Build Coastguard Worker   if (params->quality >= MIN_QUALITY_FOR_HQ_BLOCK_SPLITTING &&
547*f4ee7fbaSAndroid Build Coastguard Worker       !BrotliIsMostlyUTF8(data, pos, mask, length, kMinUTF8Ratio)) {
548*f4ee7fbaSAndroid Build Coastguard Worker     return CONTEXT_SIGNED;
549*f4ee7fbaSAndroid Build Coastguard Worker   }
550*f4ee7fbaSAndroid Build Coastguard Worker   return CONTEXT_UTF8;
551*f4ee7fbaSAndroid Build Coastguard Worker }
552*f4ee7fbaSAndroid Build Coastguard Worker 
WriteMetaBlockInternal(MemoryManager * m,const uint8_t * data,const size_t mask,const uint64_t last_flush_pos,const size_t bytes,const BROTLI_BOOL is_last,ContextType literal_context_mode,const BrotliEncoderParams * params,const uint8_t prev_byte,const uint8_t prev_byte2,const size_t num_literals,const size_t num_commands,Command * commands,const int * saved_dist_cache,int * dist_cache,size_t * storage_ix,uint8_t * storage)553*f4ee7fbaSAndroid Build Coastguard Worker static void WriteMetaBlockInternal(MemoryManager* m,
554*f4ee7fbaSAndroid Build Coastguard Worker                                    const uint8_t* data,
555*f4ee7fbaSAndroid Build Coastguard Worker                                    const size_t mask,
556*f4ee7fbaSAndroid Build Coastguard Worker                                    const uint64_t last_flush_pos,
557*f4ee7fbaSAndroid Build Coastguard Worker                                    const size_t bytes,
558*f4ee7fbaSAndroid Build Coastguard Worker                                    const BROTLI_BOOL is_last,
559*f4ee7fbaSAndroid Build Coastguard Worker                                    ContextType literal_context_mode,
560*f4ee7fbaSAndroid Build Coastguard Worker                                    const BrotliEncoderParams* params,
561*f4ee7fbaSAndroid Build Coastguard Worker                                    const uint8_t prev_byte,
562*f4ee7fbaSAndroid Build Coastguard Worker                                    const uint8_t prev_byte2,
563*f4ee7fbaSAndroid Build Coastguard Worker                                    const size_t num_literals,
564*f4ee7fbaSAndroid Build Coastguard Worker                                    const size_t num_commands,
565*f4ee7fbaSAndroid Build Coastguard Worker                                    Command* commands,
566*f4ee7fbaSAndroid Build Coastguard Worker                                    const int* saved_dist_cache,
567*f4ee7fbaSAndroid Build Coastguard Worker                                    int* dist_cache,
568*f4ee7fbaSAndroid Build Coastguard Worker                                    size_t* storage_ix,
569*f4ee7fbaSAndroid Build Coastguard Worker                                    uint8_t* storage) {
570*f4ee7fbaSAndroid Build Coastguard Worker   const uint32_t wrapped_last_flush_pos = WrapPosition(last_flush_pos);
571*f4ee7fbaSAndroid Build Coastguard Worker   uint16_t last_bytes;
572*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t last_bytes_bits;
573*f4ee7fbaSAndroid Build Coastguard Worker   ContextLut literal_context_lut = BROTLI_CONTEXT_LUT(literal_context_mode);
574*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderParams block_params = *params;
575*f4ee7fbaSAndroid Build Coastguard Worker 
576*f4ee7fbaSAndroid Build Coastguard Worker   if (bytes == 0) {
577*f4ee7fbaSAndroid Build Coastguard Worker     /* Write the ISLAST and ISEMPTY bits. */
578*f4ee7fbaSAndroid Build Coastguard Worker     BrotliWriteBits(2, 3, storage_ix, storage);
579*f4ee7fbaSAndroid Build Coastguard Worker     *storage_ix = (*storage_ix + 7u) & ~7u;
580*f4ee7fbaSAndroid Build Coastguard Worker     return;
581*f4ee7fbaSAndroid Build Coastguard Worker   }
582*f4ee7fbaSAndroid Build Coastguard Worker 
583*f4ee7fbaSAndroid Build Coastguard Worker   if (!ShouldCompress(data, mask, last_flush_pos, bytes,
584*f4ee7fbaSAndroid Build Coastguard Worker                       num_literals, num_commands)) {
585*f4ee7fbaSAndroid Build Coastguard Worker     /* Restore the distance cache, as its last update by
586*f4ee7fbaSAndroid Build Coastguard Worker        CreateBackwardReferences is now unused. */
587*f4ee7fbaSAndroid Build Coastguard Worker     memcpy(dist_cache, saved_dist_cache, 4 * sizeof(dist_cache[0]));
588*f4ee7fbaSAndroid Build Coastguard Worker     BrotliStoreUncompressedMetaBlock(is_last, data,
589*f4ee7fbaSAndroid Build Coastguard Worker                                      wrapped_last_flush_pos, mask, bytes,
590*f4ee7fbaSAndroid Build Coastguard Worker                                      storage_ix, storage);
591*f4ee7fbaSAndroid Build Coastguard Worker     return;
592*f4ee7fbaSAndroid Build Coastguard Worker   }
593*f4ee7fbaSAndroid Build Coastguard Worker 
594*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_DCHECK(*storage_ix <= 14);
595*f4ee7fbaSAndroid Build Coastguard Worker   last_bytes = (uint16_t)((storage[1] << 8) | storage[0]);
596*f4ee7fbaSAndroid Build Coastguard Worker   last_bytes_bits = (uint8_t)(*storage_ix);
597*f4ee7fbaSAndroid Build Coastguard Worker   if (params->quality <= MAX_QUALITY_FOR_STATIC_ENTROPY_CODES) {
598*f4ee7fbaSAndroid Build Coastguard Worker     BrotliStoreMetaBlockFast(m, data, wrapped_last_flush_pos,
599*f4ee7fbaSAndroid Build Coastguard Worker                              bytes, mask, is_last, params,
600*f4ee7fbaSAndroid Build Coastguard Worker                              commands, num_commands,
601*f4ee7fbaSAndroid Build Coastguard Worker                              storage_ix, storage);
602*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return;
603*f4ee7fbaSAndroid Build Coastguard Worker   } else if (params->quality < MIN_QUALITY_FOR_BLOCK_SPLIT) {
604*f4ee7fbaSAndroid Build Coastguard Worker     BrotliStoreMetaBlockTrivial(m, data, wrapped_last_flush_pos,
605*f4ee7fbaSAndroid Build Coastguard Worker                                 bytes, mask, is_last, params,
606*f4ee7fbaSAndroid Build Coastguard Worker                                 commands, num_commands,
607*f4ee7fbaSAndroid Build Coastguard Worker                                 storage_ix, storage);
608*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return;
609*f4ee7fbaSAndroid Build Coastguard Worker   } else {
610*f4ee7fbaSAndroid Build Coastguard Worker     MetaBlockSplit mb;
611*f4ee7fbaSAndroid Build Coastguard Worker     InitMetaBlockSplit(&mb);
612*f4ee7fbaSAndroid Build Coastguard Worker     if (params->quality < MIN_QUALITY_FOR_HQ_BLOCK_SPLITTING) {
613*f4ee7fbaSAndroid Build Coastguard Worker       size_t num_literal_contexts = 1;
614*f4ee7fbaSAndroid Build Coastguard Worker       const uint32_t* literal_context_map = NULL;
615*f4ee7fbaSAndroid Build Coastguard Worker       if (!params->disable_literal_context_modeling) {
616*f4ee7fbaSAndroid Build Coastguard Worker         DecideOverLiteralContextModeling(
617*f4ee7fbaSAndroid Build Coastguard Worker             data, wrapped_last_flush_pos, bytes, mask, params->quality,
618*f4ee7fbaSAndroid Build Coastguard Worker             params->size_hint, &num_literal_contexts,
619*f4ee7fbaSAndroid Build Coastguard Worker             &literal_context_map);
620*f4ee7fbaSAndroid Build Coastguard Worker       }
621*f4ee7fbaSAndroid Build Coastguard Worker       BrotliBuildMetaBlockGreedy(m, data, wrapped_last_flush_pos, mask,
622*f4ee7fbaSAndroid Build Coastguard Worker           prev_byte, prev_byte2, literal_context_lut, num_literal_contexts,
623*f4ee7fbaSAndroid Build Coastguard Worker           literal_context_map, commands, num_commands, &mb);
624*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m)) return;
625*f4ee7fbaSAndroid Build Coastguard Worker     } else {
626*f4ee7fbaSAndroid Build Coastguard Worker       BrotliBuildMetaBlock(m, data, wrapped_last_flush_pos, mask, &block_params,
627*f4ee7fbaSAndroid Build Coastguard Worker                            prev_byte, prev_byte2,
628*f4ee7fbaSAndroid Build Coastguard Worker                            commands, num_commands,
629*f4ee7fbaSAndroid Build Coastguard Worker                            literal_context_mode,
630*f4ee7fbaSAndroid Build Coastguard Worker                            &mb);
631*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m)) return;
632*f4ee7fbaSAndroid Build Coastguard Worker     }
633*f4ee7fbaSAndroid Build Coastguard Worker     if (params->quality >= MIN_QUALITY_FOR_OPTIMIZE_HISTOGRAMS) {
634*f4ee7fbaSAndroid Build Coastguard Worker       /* The number of distance symbols effectively used for distance
635*f4ee7fbaSAndroid Build Coastguard Worker          histograms. It might be less than distance alphabet size
636*f4ee7fbaSAndroid Build Coastguard Worker          for "Large Window Brotli" (32-bit). */
637*f4ee7fbaSAndroid Build Coastguard Worker       BrotliOptimizeHistograms(block_params.dist.alphabet_size_limit, &mb);
638*f4ee7fbaSAndroid Build Coastguard Worker     }
639*f4ee7fbaSAndroid Build Coastguard Worker     BrotliStoreMetaBlock(m, data, wrapped_last_flush_pos, bytes, mask,
640*f4ee7fbaSAndroid Build Coastguard Worker                          prev_byte, prev_byte2,
641*f4ee7fbaSAndroid Build Coastguard Worker                          is_last,
642*f4ee7fbaSAndroid Build Coastguard Worker                          &block_params,
643*f4ee7fbaSAndroid Build Coastguard Worker                          literal_context_mode,
644*f4ee7fbaSAndroid Build Coastguard Worker                          commands, num_commands,
645*f4ee7fbaSAndroid Build Coastguard Worker                          &mb,
646*f4ee7fbaSAndroid Build Coastguard Worker                          storage_ix, storage);
647*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return;
648*f4ee7fbaSAndroid Build Coastguard Worker     DestroyMetaBlockSplit(m, &mb);
649*f4ee7fbaSAndroid Build Coastguard Worker   }
650*f4ee7fbaSAndroid Build Coastguard Worker   if (bytes + 4 < (*storage_ix >> 3)) {
651*f4ee7fbaSAndroid Build Coastguard Worker     /* Restore the distance cache and last byte. */
652*f4ee7fbaSAndroid Build Coastguard Worker     memcpy(dist_cache, saved_dist_cache, 4 * sizeof(dist_cache[0]));
653*f4ee7fbaSAndroid Build Coastguard Worker     storage[0] = (uint8_t)last_bytes;
654*f4ee7fbaSAndroid Build Coastguard Worker     storage[1] = (uint8_t)(last_bytes >> 8);
655*f4ee7fbaSAndroid Build Coastguard Worker     *storage_ix = last_bytes_bits;
656*f4ee7fbaSAndroid Build Coastguard Worker     BrotliStoreUncompressedMetaBlock(is_last, data,
657*f4ee7fbaSAndroid Build Coastguard Worker                                      wrapped_last_flush_pos, mask,
658*f4ee7fbaSAndroid Build Coastguard Worker                                      bytes, storage_ix, storage);
659*f4ee7fbaSAndroid Build Coastguard Worker   }
660*f4ee7fbaSAndroid Build Coastguard Worker }
661*f4ee7fbaSAndroid Build Coastguard Worker 
ChooseDistanceParams(BrotliEncoderParams * params)662*f4ee7fbaSAndroid Build Coastguard Worker static void ChooseDistanceParams(BrotliEncoderParams* params) {
663*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t distance_postfix_bits = 0;
664*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t num_direct_distance_codes = 0;
665*f4ee7fbaSAndroid Build Coastguard Worker 
666*f4ee7fbaSAndroid Build Coastguard Worker   if (params->quality >= MIN_QUALITY_FOR_NONZERO_DISTANCE_PARAMS) {
667*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t ndirect_msb;
668*f4ee7fbaSAndroid Build Coastguard Worker     if (params->mode == BROTLI_MODE_FONT) {
669*f4ee7fbaSAndroid Build Coastguard Worker       distance_postfix_bits = 1;
670*f4ee7fbaSAndroid Build Coastguard Worker       num_direct_distance_codes = 12;
671*f4ee7fbaSAndroid Build Coastguard Worker     } else {
672*f4ee7fbaSAndroid Build Coastguard Worker       distance_postfix_bits = params->dist.distance_postfix_bits;
673*f4ee7fbaSAndroid Build Coastguard Worker       num_direct_distance_codes = params->dist.num_direct_distance_codes;
674*f4ee7fbaSAndroid Build Coastguard Worker     }
675*f4ee7fbaSAndroid Build Coastguard Worker     ndirect_msb = (num_direct_distance_codes >> distance_postfix_bits) & 0x0F;
676*f4ee7fbaSAndroid Build Coastguard Worker     if (distance_postfix_bits > BROTLI_MAX_NPOSTFIX ||
677*f4ee7fbaSAndroid Build Coastguard Worker         num_direct_distance_codes > BROTLI_MAX_NDIRECT ||
678*f4ee7fbaSAndroid Build Coastguard Worker         (ndirect_msb << distance_postfix_bits) != num_direct_distance_codes) {
679*f4ee7fbaSAndroid Build Coastguard Worker       distance_postfix_bits = 0;
680*f4ee7fbaSAndroid Build Coastguard Worker       num_direct_distance_codes = 0;
681*f4ee7fbaSAndroid Build Coastguard Worker     }
682*f4ee7fbaSAndroid Build Coastguard Worker   }
683*f4ee7fbaSAndroid Build Coastguard Worker 
684*f4ee7fbaSAndroid Build Coastguard Worker   BrotliInitDistanceParams(
685*f4ee7fbaSAndroid Build Coastguard Worker       params, distance_postfix_bits, num_direct_distance_codes);
686*f4ee7fbaSAndroid Build Coastguard Worker }
687*f4ee7fbaSAndroid Build Coastguard Worker 
EnsureInitialized(BrotliEncoderState * s)688*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL EnsureInitialized(BrotliEncoderState* s) {
689*f4ee7fbaSAndroid Build Coastguard Worker   if (BROTLI_IS_OOM(&s->memory_manager_)) return BROTLI_FALSE;
690*f4ee7fbaSAndroid Build Coastguard Worker   if (s->is_initialized_) return BROTLI_TRUE;
691*f4ee7fbaSAndroid Build Coastguard Worker 
692*f4ee7fbaSAndroid Build Coastguard Worker   s->last_bytes_bits_ = 0;
693*f4ee7fbaSAndroid Build Coastguard Worker   s->last_bytes_ = 0;
694*f4ee7fbaSAndroid Build Coastguard Worker   s->flint_ = BROTLI_FLINT_DONE;
695*f4ee7fbaSAndroid Build Coastguard Worker   s->remaining_metadata_bytes_ = BROTLI_UINT32_MAX;
696*f4ee7fbaSAndroid Build Coastguard Worker 
697*f4ee7fbaSAndroid Build Coastguard Worker   SanitizeParams(&s->params);
698*f4ee7fbaSAndroid Build Coastguard Worker   s->params.lgblock = ComputeLgBlock(&s->params);
699*f4ee7fbaSAndroid Build Coastguard Worker   ChooseDistanceParams(&s->params);
700*f4ee7fbaSAndroid Build Coastguard Worker 
701*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.stream_offset != 0) {
702*f4ee7fbaSAndroid Build Coastguard Worker     s->flint_ = BROTLI_FLINT_NEEDS_2_BYTES;
703*f4ee7fbaSAndroid Build Coastguard Worker     /* Poison the distance cache. -16 +- 3 is still less than zero (invalid). */
704*f4ee7fbaSAndroid Build Coastguard Worker     s->dist_cache_[0] = -16;
705*f4ee7fbaSAndroid Build Coastguard Worker     s->dist_cache_[1] = -16;
706*f4ee7fbaSAndroid Build Coastguard Worker     s->dist_cache_[2] = -16;
707*f4ee7fbaSAndroid Build Coastguard Worker     s->dist_cache_[3] = -16;
708*f4ee7fbaSAndroid Build Coastguard Worker     memcpy(s->saved_dist_cache_, s->dist_cache_, sizeof(s->saved_dist_cache_));
709*f4ee7fbaSAndroid Build Coastguard Worker   }
710*f4ee7fbaSAndroid Build Coastguard Worker 
711*f4ee7fbaSAndroid Build Coastguard Worker   RingBufferSetup(&s->params, &s->ringbuffer_);
712*f4ee7fbaSAndroid Build Coastguard Worker 
713*f4ee7fbaSAndroid Build Coastguard Worker   /* Initialize last byte with stream header. */
714*f4ee7fbaSAndroid Build Coastguard Worker   {
715*f4ee7fbaSAndroid Build Coastguard Worker     int lgwin = s->params.lgwin;
716*f4ee7fbaSAndroid Build Coastguard Worker     if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY ||
717*f4ee7fbaSAndroid Build Coastguard Worker         s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY) {
718*f4ee7fbaSAndroid Build Coastguard Worker       lgwin = BROTLI_MAX(int, lgwin, 18);
719*f4ee7fbaSAndroid Build Coastguard Worker     }
720*f4ee7fbaSAndroid Build Coastguard Worker     if (s->params.stream_offset == 0) {
721*f4ee7fbaSAndroid Build Coastguard Worker       EncodeWindowBits(lgwin, s->params.large_window,
722*f4ee7fbaSAndroid Build Coastguard Worker                        &s->last_bytes_, &s->last_bytes_bits_);
723*f4ee7fbaSAndroid Build Coastguard Worker     } else {
724*f4ee7fbaSAndroid Build Coastguard Worker       /* Bigger values have the same effect, but could cause overflows. */
725*f4ee7fbaSAndroid Build Coastguard Worker       s->params.stream_offset = BROTLI_MIN(size_t,
726*f4ee7fbaSAndroid Build Coastguard Worker           s->params.stream_offset, BROTLI_MAX_BACKWARD_LIMIT(lgwin));
727*f4ee7fbaSAndroid Build Coastguard Worker     }
728*f4ee7fbaSAndroid Build Coastguard Worker   }
729*f4ee7fbaSAndroid Build Coastguard Worker 
730*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY) {
731*f4ee7fbaSAndroid Build Coastguard Worker     InitCommandPrefixCodes(s->cmd_depths_, s->cmd_bits_,
732*f4ee7fbaSAndroid Build Coastguard Worker                            s->cmd_code_, &s->cmd_code_numbits_);
733*f4ee7fbaSAndroid Build Coastguard Worker   }
734*f4ee7fbaSAndroid Build Coastguard Worker 
735*f4ee7fbaSAndroid Build Coastguard Worker   s->is_initialized_ = BROTLI_TRUE;
736*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_TRUE;
737*f4ee7fbaSAndroid Build Coastguard Worker }
738*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderInitParams(BrotliEncoderParams * params)739*f4ee7fbaSAndroid Build Coastguard Worker static void BrotliEncoderInitParams(BrotliEncoderParams* params) {
740*f4ee7fbaSAndroid Build Coastguard Worker   params->mode = BROTLI_DEFAULT_MODE;
741*f4ee7fbaSAndroid Build Coastguard Worker   params->large_window = BROTLI_FALSE;
742*f4ee7fbaSAndroid Build Coastguard Worker   params->quality = BROTLI_DEFAULT_QUALITY;
743*f4ee7fbaSAndroid Build Coastguard Worker   params->lgwin = BROTLI_DEFAULT_WINDOW;
744*f4ee7fbaSAndroid Build Coastguard Worker   params->lgblock = 0;
745*f4ee7fbaSAndroid Build Coastguard Worker   params->stream_offset = 0;
746*f4ee7fbaSAndroid Build Coastguard Worker   params->size_hint = 0;
747*f4ee7fbaSAndroid Build Coastguard Worker   params->disable_literal_context_modeling = BROTLI_FALSE;
748*f4ee7fbaSAndroid Build Coastguard Worker   BrotliInitEncoderDictionary(&params->dictionary);
749*f4ee7fbaSAndroid Build Coastguard Worker   params->dist.distance_postfix_bits = 0;
750*f4ee7fbaSAndroid Build Coastguard Worker   params->dist.num_direct_distance_codes = 0;
751*f4ee7fbaSAndroid Build Coastguard Worker   params->dist.alphabet_size_max =
752*f4ee7fbaSAndroid Build Coastguard Worker       BROTLI_DISTANCE_ALPHABET_SIZE(0, 0, BROTLI_MAX_DISTANCE_BITS);
753*f4ee7fbaSAndroid Build Coastguard Worker   params->dist.alphabet_size_limit = params->dist.alphabet_size_max;
754*f4ee7fbaSAndroid Build Coastguard Worker   params->dist.max_distance = BROTLI_MAX_DISTANCE;
755*f4ee7fbaSAndroid Build Coastguard Worker }
756*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderInitState(BrotliEncoderState * s)757*f4ee7fbaSAndroid Build Coastguard Worker static void BrotliEncoderInitState(BrotliEncoderState* s) {
758*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderInitParams(&s->params);
759*f4ee7fbaSAndroid Build Coastguard Worker   s->input_pos_ = 0;
760*f4ee7fbaSAndroid Build Coastguard Worker   s->num_commands_ = 0;
761*f4ee7fbaSAndroid Build Coastguard Worker   s->num_literals_ = 0;
762*f4ee7fbaSAndroid Build Coastguard Worker   s->last_insert_len_ = 0;
763*f4ee7fbaSAndroid Build Coastguard Worker   s->last_flush_pos_ = 0;
764*f4ee7fbaSAndroid Build Coastguard Worker   s->last_processed_pos_ = 0;
765*f4ee7fbaSAndroid Build Coastguard Worker   s->prev_byte_ = 0;
766*f4ee7fbaSAndroid Build Coastguard Worker   s->prev_byte2_ = 0;
767*f4ee7fbaSAndroid Build Coastguard Worker   s->storage_size_ = 0;
768*f4ee7fbaSAndroid Build Coastguard Worker   s->storage_ = 0;
769*f4ee7fbaSAndroid Build Coastguard Worker   HasherInit(&s->hasher_);
770*f4ee7fbaSAndroid Build Coastguard Worker   s->large_table_ = NULL;
771*f4ee7fbaSAndroid Build Coastguard Worker   s->large_table_size_ = 0;
772*f4ee7fbaSAndroid Build Coastguard Worker   s->cmd_code_numbits_ = 0;
773*f4ee7fbaSAndroid Build Coastguard Worker   s->command_buf_ = NULL;
774*f4ee7fbaSAndroid Build Coastguard Worker   s->literal_buf_ = NULL;
775*f4ee7fbaSAndroid Build Coastguard Worker   s->next_out_ = NULL;
776*f4ee7fbaSAndroid Build Coastguard Worker   s->available_out_ = 0;
777*f4ee7fbaSAndroid Build Coastguard Worker   s->total_out_ = 0;
778*f4ee7fbaSAndroid Build Coastguard Worker   s->stream_state_ = BROTLI_STREAM_PROCESSING;
779*f4ee7fbaSAndroid Build Coastguard Worker   s->is_last_block_emitted_ = BROTLI_FALSE;
780*f4ee7fbaSAndroid Build Coastguard Worker   s->is_initialized_ = BROTLI_FALSE;
781*f4ee7fbaSAndroid Build Coastguard Worker 
782*f4ee7fbaSAndroid Build Coastguard Worker   RingBufferInit(&s->ringbuffer_);
783*f4ee7fbaSAndroid Build Coastguard Worker 
784*f4ee7fbaSAndroid Build Coastguard Worker   s->commands_ = 0;
785*f4ee7fbaSAndroid Build Coastguard Worker   s->cmd_alloc_size_ = 0;
786*f4ee7fbaSAndroid Build Coastguard Worker 
787*f4ee7fbaSAndroid Build Coastguard Worker   /* Initialize distance cache. */
788*f4ee7fbaSAndroid Build Coastguard Worker   s->dist_cache_[0] = 4;
789*f4ee7fbaSAndroid Build Coastguard Worker   s->dist_cache_[1] = 11;
790*f4ee7fbaSAndroid Build Coastguard Worker   s->dist_cache_[2] = 15;
791*f4ee7fbaSAndroid Build Coastguard Worker   s->dist_cache_[3] = 16;
792*f4ee7fbaSAndroid Build Coastguard Worker   /* Save the state of the distance cache in case we need to restore it for
793*f4ee7fbaSAndroid Build Coastguard Worker      emitting an uncompressed block. */
794*f4ee7fbaSAndroid Build Coastguard Worker   memcpy(s->saved_dist_cache_, s->dist_cache_, sizeof(s->saved_dist_cache_));
795*f4ee7fbaSAndroid Build Coastguard Worker }
796*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderCreateInstance(brotli_alloc_func alloc_func,brotli_free_func free_func,void * opaque)797*f4ee7fbaSAndroid Build Coastguard Worker BrotliEncoderState* BrotliEncoderCreateInstance(
798*f4ee7fbaSAndroid Build Coastguard Worker     brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
799*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderState* state = 0;
800*f4ee7fbaSAndroid Build Coastguard Worker   if (!alloc_func && !free_func) {
801*f4ee7fbaSAndroid Build Coastguard Worker     state = (BrotliEncoderState*)malloc(sizeof(BrotliEncoderState));
802*f4ee7fbaSAndroid Build Coastguard Worker   } else if (alloc_func && free_func) {
803*f4ee7fbaSAndroid Build Coastguard Worker     state = (BrotliEncoderState*)alloc_func(opaque, sizeof(BrotliEncoderState));
804*f4ee7fbaSAndroid Build Coastguard Worker   }
805*f4ee7fbaSAndroid Build Coastguard Worker   if (state == 0) {
806*f4ee7fbaSAndroid Build Coastguard Worker     /* BROTLI_DUMP(); */
807*f4ee7fbaSAndroid Build Coastguard Worker     return 0;
808*f4ee7fbaSAndroid Build Coastguard Worker   }
809*f4ee7fbaSAndroid Build Coastguard Worker   BrotliInitMemoryManager(
810*f4ee7fbaSAndroid Build Coastguard Worker       &state->memory_manager_, alloc_func, free_func, opaque);
811*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderInitState(state);
812*f4ee7fbaSAndroid Build Coastguard Worker   return state;
813*f4ee7fbaSAndroid Build Coastguard Worker }
814*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderCleanupState(BrotliEncoderState * s)815*f4ee7fbaSAndroid Build Coastguard Worker static void BrotliEncoderCleanupState(BrotliEncoderState* s) {
816*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager* m = &s->memory_manager_;
817*f4ee7fbaSAndroid Build Coastguard Worker   if (BROTLI_IS_OOM(m)) {
818*f4ee7fbaSAndroid Build Coastguard Worker     BrotliWipeOutMemoryManager(m);
819*f4ee7fbaSAndroid Build Coastguard Worker     return;
820*f4ee7fbaSAndroid Build Coastguard Worker   }
821*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FREE(m, s->storage_);
822*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FREE(m, s->commands_);
823*f4ee7fbaSAndroid Build Coastguard Worker   RingBufferFree(m, &s->ringbuffer_);
824*f4ee7fbaSAndroid Build Coastguard Worker   DestroyHasher(m, &s->hasher_);
825*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FREE(m, s->large_table_);
826*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FREE(m, s->command_buf_);
827*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FREE(m, s->literal_buf_);
828*f4ee7fbaSAndroid Build Coastguard Worker }
829*f4ee7fbaSAndroid Build Coastguard Worker 
830*f4ee7fbaSAndroid Build Coastguard Worker /* Deinitializes and frees BrotliEncoderState instance. */
BrotliEncoderDestroyInstance(BrotliEncoderState * state)831*f4ee7fbaSAndroid Build Coastguard Worker void BrotliEncoderDestroyInstance(BrotliEncoderState* state) {
832*f4ee7fbaSAndroid Build Coastguard Worker   if (!state) {
833*f4ee7fbaSAndroid Build Coastguard Worker     return;
834*f4ee7fbaSAndroid Build Coastguard Worker   } else {
835*f4ee7fbaSAndroid Build Coastguard Worker     MemoryManager* m = &state->memory_manager_;
836*f4ee7fbaSAndroid Build Coastguard Worker     brotli_free_func free_func = m->free_func;
837*f4ee7fbaSAndroid Build Coastguard Worker     void* opaque = m->opaque;
838*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderCleanupState(state);
839*f4ee7fbaSAndroid Build Coastguard Worker     free_func(opaque, state);
840*f4ee7fbaSAndroid Build Coastguard Worker   }
841*f4ee7fbaSAndroid Build Coastguard Worker }
842*f4ee7fbaSAndroid Build Coastguard Worker 
843*f4ee7fbaSAndroid Build Coastguard Worker /*
844*f4ee7fbaSAndroid Build Coastguard Worker    Copies the given input data to the internal ring buffer of the compressor.
845*f4ee7fbaSAndroid Build Coastguard Worker    No processing of the data occurs at this time and this function can be
846*f4ee7fbaSAndroid Build Coastguard Worker    called multiple times before calling WriteBrotliData() to process the
847*f4ee7fbaSAndroid Build Coastguard Worker    accumulated input. At most input_block_size() bytes of input data can be
848*f4ee7fbaSAndroid Build Coastguard Worker    copied to the ring buffer, otherwise the next WriteBrotliData() will fail.
849*f4ee7fbaSAndroid Build Coastguard Worker  */
CopyInputToRingBuffer(BrotliEncoderState * s,const size_t input_size,const uint8_t * input_buffer)850*f4ee7fbaSAndroid Build Coastguard Worker static void CopyInputToRingBuffer(BrotliEncoderState* s,
851*f4ee7fbaSAndroid Build Coastguard Worker                                   const size_t input_size,
852*f4ee7fbaSAndroid Build Coastguard Worker                                   const uint8_t* input_buffer) {
853*f4ee7fbaSAndroid Build Coastguard Worker   RingBuffer* ringbuffer_ = &s->ringbuffer_;
854*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager* m = &s->memory_manager_;
855*f4ee7fbaSAndroid Build Coastguard Worker   RingBufferWrite(m, input_buffer, input_size, ringbuffer_);
856*f4ee7fbaSAndroid Build Coastguard Worker   if (BROTLI_IS_OOM(m)) return;
857*f4ee7fbaSAndroid Build Coastguard Worker   s->input_pos_ += input_size;
858*f4ee7fbaSAndroid Build Coastguard Worker 
859*f4ee7fbaSAndroid Build Coastguard Worker   /* TL;DR: If needed, initialize 7 more bytes in the ring buffer to make the
860*f4ee7fbaSAndroid Build Coastguard Worker      hashing not depend on uninitialized data. This makes compression
861*f4ee7fbaSAndroid Build Coastguard Worker      deterministic and it prevents uninitialized memory warnings in Valgrind.
862*f4ee7fbaSAndroid Build Coastguard Worker      Even without erasing, the output would be valid (but nondeterministic).
863*f4ee7fbaSAndroid Build Coastguard Worker 
864*f4ee7fbaSAndroid Build Coastguard Worker      Background information: The compressor stores short (at most 8 bytes)
865*f4ee7fbaSAndroid Build Coastguard Worker      substrings of the input already read in a hash table, and detects
866*f4ee7fbaSAndroid Build Coastguard Worker      repetitions by looking up such substrings in the hash table. If it
867*f4ee7fbaSAndroid Build Coastguard Worker      can find a substring, it checks whether the substring is really there
868*f4ee7fbaSAndroid Build Coastguard Worker      in the ring buffer (or it's just a hash collision). Should the hash
869*f4ee7fbaSAndroid Build Coastguard Worker      table become corrupt, this check makes sure that the output is
870*f4ee7fbaSAndroid Build Coastguard Worker      still valid, albeit the compression ratio would be bad.
871*f4ee7fbaSAndroid Build Coastguard Worker 
872*f4ee7fbaSAndroid Build Coastguard Worker      The compressor populates the hash table from the ring buffer as it's
873*f4ee7fbaSAndroid Build Coastguard Worker      reading new bytes from the input. However, at the last few indexes of
874*f4ee7fbaSAndroid Build Coastguard Worker      the ring buffer, there are not enough bytes to build full-length
875*f4ee7fbaSAndroid Build Coastguard Worker      substrings from. Since the hash table always contains full-length
876*f4ee7fbaSAndroid Build Coastguard Worker      substrings, we erase with dummy zeros here to make sure that those
877*f4ee7fbaSAndroid Build Coastguard Worker      substrings will contain zeros at the end instead of uninitialized
878*f4ee7fbaSAndroid Build Coastguard Worker      data.
879*f4ee7fbaSAndroid Build Coastguard Worker 
880*f4ee7fbaSAndroid Build Coastguard Worker      Please note that erasing is not necessary (because the
881*f4ee7fbaSAndroid Build Coastguard Worker      memory region is already initialized since he ring buffer
882*f4ee7fbaSAndroid Build Coastguard Worker      has a `tail' that holds a copy of the beginning,) so we
883*f4ee7fbaSAndroid Build Coastguard Worker      skip erasing if we have already gone around at least once in
884*f4ee7fbaSAndroid Build Coastguard Worker      the ring buffer.
885*f4ee7fbaSAndroid Build Coastguard Worker 
886*f4ee7fbaSAndroid Build Coastguard Worker      Only clear during the first round of ring-buffer writes. On
887*f4ee7fbaSAndroid Build Coastguard Worker      subsequent rounds data in the ring-buffer would be affected. */
888*f4ee7fbaSAndroid Build Coastguard Worker   if (ringbuffer_->pos_ <= ringbuffer_->mask_) {
889*f4ee7fbaSAndroid Build Coastguard Worker     /* This is the first time when the ring buffer is being written.
890*f4ee7fbaSAndroid Build Coastguard Worker        We clear 7 bytes just after the bytes that have been copied from
891*f4ee7fbaSAndroid Build Coastguard Worker        the input buffer.
892*f4ee7fbaSAndroid Build Coastguard Worker 
893*f4ee7fbaSAndroid Build Coastguard Worker        The ring-buffer has a "tail" that holds a copy of the beginning,
894*f4ee7fbaSAndroid Build Coastguard Worker        but only once the ring buffer has been fully written once, i.e.,
895*f4ee7fbaSAndroid Build Coastguard Worker        pos <= mask. For the first time, we need to write values
896*f4ee7fbaSAndroid Build Coastguard Worker        in this tail (where index may be larger than mask), so that
897*f4ee7fbaSAndroid Build Coastguard Worker        we have exactly defined behavior and don't read uninitialized
898*f4ee7fbaSAndroid Build Coastguard Worker        memory. Due to performance reasons, hashing reads data using a
899*f4ee7fbaSAndroid Build Coastguard Worker        LOAD64, which can go 7 bytes beyond the bytes written in the
900*f4ee7fbaSAndroid Build Coastguard Worker        ring-buffer. */
901*f4ee7fbaSAndroid Build Coastguard Worker     memset(ringbuffer_->buffer_ + ringbuffer_->pos_, 0, 7);
902*f4ee7fbaSAndroid Build Coastguard Worker   }
903*f4ee7fbaSAndroid Build Coastguard Worker }
904*f4ee7fbaSAndroid Build Coastguard Worker 
905*f4ee7fbaSAndroid Build Coastguard Worker /* Marks all input as processed.
906*f4ee7fbaSAndroid Build Coastguard Worker    Returns true if position wrapping occurs. */
UpdateLastProcessedPos(BrotliEncoderState * s)907*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL UpdateLastProcessedPos(BrotliEncoderState* s) {
908*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t wrapped_last_processed_pos = WrapPosition(s->last_processed_pos_);
909*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t wrapped_input_pos = WrapPosition(s->input_pos_);
910*f4ee7fbaSAndroid Build Coastguard Worker   s->last_processed_pos_ = s->input_pos_;
911*f4ee7fbaSAndroid Build Coastguard Worker   return TO_BROTLI_BOOL(wrapped_input_pos < wrapped_last_processed_pos);
912*f4ee7fbaSAndroid Build Coastguard Worker }
913*f4ee7fbaSAndroid Build Coastguard Worker 
ExtendLastCommand(BrotliEncoderState * s,uint32_t * bytes,uint32_t * wrapped_last_processed_pos)914*f4ee7fbaSAndroid Build Coastguard Worker static void ExtendLastCommand(BrotliEncoderState* s, uint32_t* bytes,
915*f4ee7fbaSAndroid Build Coastguard Worker                               uint32_t* wrapped_last_processed_pos) {
916*f4ee7fbaSAndroid Build Coastguard Worker   Command* last_command = &s->commands_[s->num_commands_ - 1];
917*f4ee7fbaSAndroid Build Coastguard Worker   const uint8_t* data = s->ringbuffer_.buffer_;
918*f4ee7fbaSAndroid Build Coastguard Worker   const uint32_t mask = s->ringbuffer_.mask_;
919*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t max_backward_distance =
920*f4ee7fbaSAndroid Build Coastguard Worker       (((uint64_t)1) << s->params.lgwin) - BROTLI_WINDOW_GAP;
921*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t last_copy_len = last_command->copy_len_ & 0x1FFFFFF;
922*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t last_processed_pos = s->last_processed_pos_ - last_copy_len;
923*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t max_distance = last_processed_pos < max_backward_distance ?
924*f4ee7fbaSAndroid Build Coastguard Worker       last_processed_pos : max_backward_distance;
925*f4ee7fbaSAndroid Build Coastguard Worker   uint64_t cmd_dist = (uint64_t)s->dist_cache_[0];
926*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t distance_code = CommandRestoreDistanceCode(last_command,
927*f4ee7fbaSAndroid Build Coastguard Worker                                                       &s->params.dist);
928*f4ee7fbaSAndroid Build Coastguard Worker   if (distance_code < BROTLI_NUM_DISTANCE_SHORT_CODES ||
929*f4ee7fbaSAndroid Build Coastguard Worker       distance_code - (BROTLI_NUM_DISTANCE_SHORT_CODES - 1) == cmd_dist) {
930*f4ee7fbaSAndroid Build Coastguard Worker     if (cmd_dist <= max_distance) {
931*f4ee7fbaSAndroid Build Coastguard Worker       while (*bytes != 0 && data[*wrapped_last_processed_pos & mask] ==
932*f4ee7fbaSAndroid Build Coastguard Worker              data[(*wrapped_last_processed_pos - cmd_dist) & mask]) {
933*f4ee7fbaSAndroid Build Coastguard Worker         last_command->copy_len_++;
934*f4ee7fbaSAndroid Build Coastguard Worker         (*bytes)--;
935*f4ee7fbaSAndroid Build Coastguard Worker         (*wrapped_last_processed_pos)++;
936*f4ee7fbaSAndroid Build Coastguard Worker       }
937*f4ee7fbaSAndroid Build Coastguard Worker     } else {
938*f4ee7fbaSAndroid Build Coastguard Worker     }
939*f4ee7fbaSAndroid Build Coastguard Worker     /* The copy length is at most the metablock size, and thus expressible. */
940*f4ee7fbaSAndroid Build Coastguard Worker     GetLengthCode(last_command->insert_len_,
941*f4ee7fbaSAndroid Build Coastguard Worker                   (size_t)((int)(last_command->copy_len_ & 0x1FFFFFF) +
942*f4ee7fbaSAndroid Build Coastguard Worker                            (int)(last_command->copy_len_ >> 25)),
943*f4ee7fbaSAndroid Build Coastguard Worker                   TO_BROTLI_BOOL((last_command->dist_prefix_ & 0x3FF) == 0),
944*f4ee7fbaSAndroid Build Coastguard Worker                   &last_command->cmd_prefix_);
945*f4ee7fbaSAndroid Build Coastguard Worker   }
946*f4ee7fbaSAndroid Build Coastguard Worker }
947*f4ee7fbaSAndroid Build Coastguard Worker 
948*f4ee7fbaSAndroid Build Coastguard Worker /*
949*f4ee7fbaSAndroid Build Coastguard Worker    Processes the accumulated input data and sets |*out_size| to the length of
950*f4ee7fbaSAndroid Build Coastguard Worker    the new output meta-block, or to zero if no new output meta-block has been
951*f4ee7fbaSAndroid Build Coastguard Worker    created (in this case the processed input data is buffered internally).
952*f4ee7fbaSAndroid Build Coastguard Worker    If |*out_size| is positive, |*output| points to the start of the output
953*f4ee7fbaSAndroid Build Coastguard Worker    data. If |is_last| or |force_flush| is BROTLI_TRUE, an output meta-block is
954*f4ee7fbaSAndroid Build Coastguard Worker    always created. However, until |is_last| is BROTLI_TRUE encoder may retain up
955*f4ee7fbaSAndroid Build Coastguard Worker    to 7 bits of the last byte of output. To force encoder to dump the remaining
956*f4ee7fbaSAndroid Build Coastguard Worker    bits use WriteMetadata() to append an empty meta-data block.
957*f4ee7fbaSAndroid Build Coastguard Worker    Returns BROTLI_FALSE if the size of the input data is larger than
958*f4ee7fbaSAndroid Build Coastguard Worker    input_block_size().
959*f4ee7fbaSAndroid Build Coastguard Worker  */
EncodeData(BrotliEncoderState * s,const BROTLI_BOOL is_last,const BROTLI_BOOL force_flush,size_t * out_size,uint8_t ** output)960*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL EncodeData(
961*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderState* s, const BROTLI_BOOL is_last,
962*f4ee7fbaSAndroid Build Coastguard Worker     const BROTLI_BOOL force_flush, size_t* out_size, uint8_t** output) {
963*f4ee7fbaSAndroid Build Coastguard Worker   const uint64_t delta = UnprocessedInputSize(s);
964*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t bytes = (uint32_t)delta;
965*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t wrapped_last_processed_pos = WrapPosition(s->last_processed_pos_);
966*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* data;
967*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t mask;
968*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager* m = &s->memory_manager_;
969*f4ee7fbaSAndroid Build Coastguard Worker   ContextType literal_context_mode;
970*f4ee7fbaSAndroid Build Coastguard Worker   ContextLut literal_context_lut;
971*f4ee7fbaSAndroid Build Coastguard Worker 
972*f4ee7fbaSAndroid Build Coastguard Worker   data = s->ringbuffer_.buffer_;
973*f4ee7fbaSAndroid Build Coastguard Worker   mask = s->ringbuffer_.mask_;
974*f4ee7fbaSAndroid Build Coastguard Worker 
975*f4ee7fbaSAndroid Build Coastguard Worker   /* Adding more blocks after "last" block is forbidden. */
976*f4ee7fbaSAndroid Build Coastguard Worker   if (s->is_last_block_emitted_) return BROTLI_FALSE;
977*f4ee7fbaSAndroid Build Coastguard Worker   if (is_last) s->is_last_block_emitted_ = BROTLI_TRUE;
978*f4ee7fbaSAndroid Build Coastguard Worker 
979*f4ee7fbaSAndroid Build Coastguard Worker   if (delta > InputBlockSize(s)) {
980*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_FALSE;
981*f4ee7fbaSAndroid Build Coastguard Worker   }
982*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY &&
983*f4ee7fbaSAndroid Build Coastguard Worker       !s->command_buf_) {
984*f4ee7fbaSAndroid Build Coastguard Worker     s->command_buf_ =
985*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_ALLOC(m, uint32_t, kCompressFragmentTwoPassBlockSize);
986*f4ee7fbaSAndroid Build Coastguard Worker     s->literal_buf_ =
987*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_ALLOC(m, uint8_t, kCompressFragmentTwoPassBlockSize);
988*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(s->command_buf_) ||
989*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_IS_NULL(s->literal_buf_)) {
990*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_FALSE;
991*f4ee7fbaSAndroid Build Coastguard Worker     }
992*f4ee7fbaSAndroid Build Coastguard Worker   }
993*f4ee7fbaSAndroid Build Coastguard Worker 
994*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY ||
995*f4ee7fbaSAndroid Build Coastguard Worker       s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY) {
996*f4ee7fbaSAndroid Build Coastguard Worker     uint8_t* storage;
997*f4ee7fbaSAndroid Build Coastguard Worker     size_t storage_ix = s->last_bytes_bits_;
998*f4ee7fbaSAndroid Build Coastguard Worker     size_t table_size;
999*f4ee7fbaSAndroid Build Coastguard Worker     int* table;
1000*f4ee7fbaSAndroid Build Coastguard Worker 
1001*f4ee7fbaSAndroid Build Coastguard Worker     if (delta == 0 && !is_last) {
1002*f4ee7fbaSAndroid Build Coastguard Worker       /* We have no new input data and we don't have to finish the stream, so
1003*f4ee7fbaSAndroid Build Coastguard Worker          nothing to do. */
1004*f4ee7fbaSAndroid Build Coastguard Worker       *out_size = 0;
1005*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
1006*f4ee7fbaSAndroid Build Coastguard Worker     }
1007*f4ee7fbaSAndroid Build Coastguard Worker     storage = GetBrotliStorage(s, 2 * bytes + 503);
1008*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1009*f4ee7fbaSAndroid Build Coastguard Worker     storage[0] = (uint8_t)s->last_bytes_;
1010*f4ee7fbaSAndroid Build Coastguard Worker     storage[1] = (uint8_t)(s->last_bytes_ >> 8);
1011*f4ee7fbaSAndroid Build Coastguard Worker     table = GetHashTable(s, s->params.quality, bytes, &table_size);
1012*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1013*f4ee7fbaSAndroid Build Coastguard Worker     if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY) {
1014*f4ee7fbaSAndroid Build Coastguard Worker       BrotliCompressFragmentFast(
1015*f4ee7fbaSAndroid Build Coastguard Worker           m, &data[wrapped_last_processed_pos & mask],
1016*f4ee7fbaSAndroid Build Coastguard Worker           bytes, is_last,
1017*f4ee7fbaSAndroid Build Coastguard Worker           table, table_size,
1018*f4ee7fbaSAndroid Build Coastguard Worker           s->cmd_depths_, s->cmd_bits_,
1019*f4ee7fbaSAndroid Build Coastguard Worker           &s->cmd_code_numbits_, s->cmd_code_,
1020*f4ee7fbaSAndroid Build Coastguard Worker           &storage_ix, storage);
1021*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1022*f4ee7fbaSAndroid Build Coastguard Worker     } else {
1023*f4ee7fbaSAndroid Build Coastguard Worker       BrotliCompressFragmentTwoPass(
1024*f4ee7fbaSAndroid Build Coastguard Worker           m, &data[wrapped_last_processed_pos & mask],
1025*f4ee7fbaSAndroid Build Coastguard Worker           bytes, is_last,
1026*f4ee7fbaSAndroid Build Coastguard Worker           s->command_buf_, s->literal_buf_,
1027*f4ee7fbaSAndroid Build Coastguard Worker           table, table_size,
1028*f4ee7fbaSAndroid Build Coastguard Worker           &storage_ix, storage);
1029*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1030*f4ee7fbaSAndroid Build Coastguard Worker     }
1031*f4ee7fbaSAndroid Build Coastguard Worker     s->last_bytes_ = (uint16_t)(storage[storage_ix >> 3]);
1032*f4ee7fbaSAndroid Build Coastguard Worker     s->last_bytes_bits_ = storage_ix & 7u;
1033*f4ee7fbaSAndroid Build Coastguard Worker     UpdateLastProcessedPos(s);
1034*f4ee7fbaSAndroid Build Coastguard Worker     *output = &storage[0];
1035*f4ee7fbaSAndroid Build Coastguard Worker     *out_size = storage_ix >> 3;
1036*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1037*f4ee7fbaSAndroid Build Coastguard Worker   }
1038*f4ee7fbaSAndroid Build Coastguard Worker 
1039*f4ee7fbaSAndroid Build Coastguard Worker   {
1040*f4ee7fbaSAndroid Build Coastguard Worker     /* Theoretical max number of commands is 1 per 2 bytes. */
1041*f4ee7fbaSAndroid Build Coastguard Worker     size_t newsize = s->num_commands_ + bytes / 2 + 1;
1042*f4ee7fbaSAndroid Build Coastguard Worker     if (newsize > s->cmd_alloc_size_) {
1043*f4ee7fbaSAndroid Build Coastguard Worker       Command* new_commands;
1044*f4ee7fbaSAndroid Build Coastguard Worker       /* Reserve a bit more memory to allow merging with a next block
1045*f4ee7fbaSAndroid Build Coastguard Worker          without reallocation: that would impact speed. */
1046*f4ee7fbaSAndroid Build Coastguard Worker       newsize += (bytes / 4) + 16;
1047*f4ee7fbaSAndroid Build Coastguard Worker       s->cmd_alloc_size_ = newsize;
1048*f4ee7fbaSAndroid Build Coastguard Worker       new_commands = BROTLI_ALLOC(m, Command, newsize);
1049*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(new_commands)) return BROTLI_FALSE;
1050*f4ee7fbaSAndroid Build Coastguard Worker       if (s->commands_) {
1051*f4ee7fbaSAndroid Build Coastguard Worker         memcpy(new_commands, s->commands_, sizeof(Command) * s->num_commands_);
1052*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_FREE(m, s->commands_);
1053*f4ee7fbaSAndroid Build Coastguard Worker       }
1054*f4ee7fbaSAndroid Build Coastguard Worker       s->commands_ = new_commands;
1055*f4ee7fbaSAndroid Build Coastguard Worker     }
1056*f4ee7fbaSAndroid Build Coastguard Worker   }
1057*f4ee7fbaSAndroid Build Coastguard Worker 
1058*f4ee7fbaSAndroid Build Coastguard Worker   InitOrStitchToPreviousBlock(m, &s->hasher_, data, mask, &s->params,
1059*f4ee7fbaSAndroid Build Coastguard Worker       wrapped_last_processed_pos, bytes, is_last);
1060*f4ee7fbaSAndroid Build Coastguard Worker 
1061*f4ee7fbaSAndroid Build Coastguard Worker   literal_context_mode = ChooseContextMode(
1062*f4ee7fbaSAndroid Build Coastguard Worker       &s->params, data, WrapPosition(s->last_flush_pos_),
1063*f4ee7fbaSAndroid Build Coastguard Worker       mask, (size_t)(s->input_pos_ - s->last_flush_pos_));
1064*f4ee7fbaSAndroid Build Coastguard Worker   literal_context_lut = BROTLI_CONTEXT_LUT(literal_context_mode);
1065*f4ee7fbaSAndroid Build Coastguard Worker 
1066*f4ee7fbaSAndroid Build Coastguard Worker   if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1067*f4ee7fbaSAndroid Build Coastguard Worker 
1068*f4ee7fbaSAndroid Build Coastguard Worker   if (s->num_commands_ && s->last_insert_len_ == 0) {
1069*f4ee7fbaSAndroid Build Coastguard Worker     ExtendLastCommand(s, &bytes, &wrapped_last_processed_pos);
1070*f4ee7fbaSAndroid Build Coastguard Worker   }
1071*f4ee7fbaSAndroid Build Coastguard Worker 
1072*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.quality == ZOPFLIFICATION_QUALITY) {
1073*f4ee7fbaSAndroid Build Coastguard Worker     BROTLI_DCHECK(s->params.hasher.type == 10);
1074*f4ee7fbaSAndroid Build Coastguard Worker     BrotliCreateZopfliBackwardReferences(m, bytes, wrapped_last_processed_pos,
1075*f4ee7fbaSAndroid Build Coastguard Worker         data, mask, literal_context_lut, &s->params,
1076*f4ee7fbaSAndroid Build Coastguard Worker         &s->hasher_, s->dist_cache_,
1077*f4ee7fbaSAndroid Build Coastguard Worker         &s->last_insert_len_, &s->commands_[s->num_commands_],
1078*f4ee7fbaSAndroid Build Coastguard Worker         &s->num_commands_, &s->num_literals_);
1079*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1080*f4ee7fbaSAndroid Build Coastguard Worker   } else if (s->params.quality == HQ_ZOPFLIFICATION_QUALITY) {
1081*f4ee7fbaSAndroid Build Coastguard Worker     BROTLI_DCHECK(s->params.hasher.type == 10);
1082*f4ee7fbaSAndroid Build Coastguard Worker     BrotliCreateHqZopfliBackwardReferences(m, bytes, wrapped_last_processed_pos,
1083*f4ee7fbaSAndroid Build Coastguard Worker         data, mask, literal_context_lut, &s->params,
1084*f4ee7fbaSAndroid Build Coastguard Worker         &s->hasher_, s->dist_cache_,
1085*f4ee7fbaSAndroid Build Coastguard Worker         &s->last_insert_len_, &s->commands_[s->num_commands_],
1086*f4ee7fbaSAndroid Build Coastguard Worker         &s->num_commands_, &s->num_literals_);
1087*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1088*f4ee7fbaSAndroid Build Coastguard Worker   } else {
1089*f4ee7fbaSAndroid Build Coastguard Worker     BrotliCreateBackwardReferences(bytes, wrapped_last_processed_pos,
1090*f4ee7fbaSAndroid Build Coastguard Worker         data, mask, literal_context_lut, &s->params,
1091*f4ee7fbaSAndroid Build Coastguard Worker         &s->hasher_, s->dist_cache_,
1092*f4ee7fbaSAndroid Build Coastguard Worker         &s->last_insert_len_, &s->commands_[s->num_commands_],
1093*f4ee7fbaSAndroid Build Coastguard Worker         &s->num_commands_, &s->num_literals_);
1094*f4ee7fbaSAndroid Build Coastguard Worker   }
1095*f4ee7fbaSAndroid Build Coastguard Worker 
1096*f4ee7fbaSAndroid Build Coastguard Worker   {
1097*f4ee7fbaSAndroid Build Coastguard Worker     const size_t max_length = MaxMetablockSize(&s->params);
1098*f4ee7fbaSAndroid Build Coastguard Worker     const size_t max_literals = max_length / 8;
1099*f4ee7fbaSAndroid Build Coastguard Worker     const size_t max_commands = max_length / 8;
1100*f4ee7fbaSAndroid Build Coastguard Worker     const size_t processed_bytes = (size_t)(s->input_pos_ - s->last_flush_pos_);
1101*f4ee7fbaSAndroid Build Coastguard Worker     /* If maximal possible additional block doesn't fit metablock, flush now. */
1102*f4ee7fbaSAndroid Build Coastguard Worker     /* TODO: Postpone decision until next block arrives? */
1103*f4ee7fbaSAndroid Build Coastguard Worker     const BROTLI_BOOL next_input_fits_metablock = TO_BROTLI_BOOL(
1104*f4ee7fbaSAndroid Build Coastguard Worker         processed_bytes + InputBlockSize(s) <= max_length);
1105*f4ee7fbaSAndroid Build Coastguard Worker     /* If block splitting is not used, then flush as soon as there is some
1106*f4ee7fbaSAndroid Build Coastguard Worker        amount of commands / literals produced. */
1107*f4ee7fbaSAndroid Build Coastguard Worker     const BROTLI_BOOL should_flush = TO_BROTLI_BOOL(
1108*f4ee7fbaSAndroid Build Coastguard Worker         s->params.quality < MIN_QUALITY_FOR_BLOCK_SPLIT &&
1109*f4ee7fbaSAndroid Build Coastguard Worker         s->num_literals_ + s->num_commands_ >= MAX_NUM_DELAYED_SYMBOLS);
1110*f4ee7fbaSAndroid Build Coastguard Worker     if (!is_last && !force_flush && !should_flush &&
1111*f4ee7fbaSAndroid Build Coastguard Worker         next_input_fits_metablock &&
1112*f4ee7fbaSAndroid Build Coastguard Worker         s->num_literals_ < max_literals &&
1113*f4ee7fbaSAndroid Build Coastguard Worker         s->num_commands_ < max_commands) {
1114*f4ee7fbaSAndroid Build Coastguard Worker       /* Merge with next input block. Everything will happen later. */
1115*f4ee7fbaSAndroid Build Coastguard Worker       if (UpdateLastProcessedPos(s)) {
1116*f4ee7fbaSAndroid Build Coastguard Worker         HasherReset(&s->hasher_);
1117*f4ee7fbaSAndroid Build Coastguard Worker       }
1118*f4ee7fbaSAndroid Build Coastguard Worker       *out_size = 0;
1119*f4ee7fbaSAndroid Build Coastguard Worker       return BROTLI_TRUE;
1120*f4ee7fbaSAndroid Build Coastguard Worker     }
1121*f4ee7fbaSAndroid Build Coastguard Worker   }
1122*f4ee7fbaSAndroid Build Coastguard Worker 
1123*f4ee7fbaSAndroid Build Coastguard Worker   /* Create the last insert-only command. */
1124*f4ee7fbaSAndroid Build Coastguard Worker   if (s->last_insert_len_ > 0) {
1125*f4ee7fbaSAndroid Build Coastguard Worker     InitInsertCommand(&s->commands_[s->num_commands_++], s->last_insert_len_);
1126*f4ee7fbaSAndroid Build Coastguard Worker     s->num_literals_ += s->last_insert_len_;
1127*f4ee7fbaSAndroid Build Coastguard Worker     s->last_insert_len_ = 0;
1128*f4ee7fbaSAndroid Build Coastguard Worker   }
1129*f4ee7fbaSAndroid Build Coastguard Worker 
1130*f4ee7fbaSAndroid Build Coastguard Worker   if (!is_last && s->input_pos_ == s->last_flush_pos_) {
1131*f4ee7fbaSAndroid Build Coastguard Worker     /* We have no new input data and we don't have to finish the stream, so
1132*f4ee7fbaSAndroid Build Coastguard Worker        nothing to do. */
1133*f4ee7fbaSAndroid Build Coastguard Worker     *out_size = 0;
1134*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1135*f4ee7fbaSAndroid Build Coastguard Worker   }
1136*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_DCHECK(s->input_pos_ >= s->last_flush_pos_);
1137*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_DCHECK(s->input_pos_ > s->last_flush_pos_ || is_last);
1138*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_DCHECK(s->input_pos_ - s->last_flush_pos_ <= 1u << 24);
1139*f4ee7fbaSAndroid Build Coastguard Worker   {
1140*f4ee7fbaSAndroid Build Coastguard Worker     const uint32_t metablock_size =
1141*f4ee7fbaSAndroid Build Coastguard Worker         (uint32_t)(s->input_pos_ - s->last_flush_pos_);
1142*f4ee7fbaSAndroid Build Coastguard Worker     uint8_t* storage = GetBrotliStorage(s, 2 * metablock_size + 503);
1143*f4ee7fbaSAndroid Build Coastguard Worker     size_t storage_ix = s->last_bytes_bits_;
1144*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1145*f4ee7fbaSAndroid Build Coastguard Worker     storage[0] = (uint8_t)s->last_bytes_;
1146*f4ee7fbaSAndroid Build Coastguard Worker     storage[1] = (uint8_t)(s->last_bytes_ >> 8);
1147*f4ee7fbaSAndroid Build Coastguard Worker     WriteMetaBlockInternal(
1148*f4ee7fbaSAndroid Build Coastguard Worker         m, data, mask, s->last_flush_pos_, metablock_size, is_last,
1149*f4ee7fbaSAndroid Build Coastguard Worker         literal_context_mode, &s->params, s->prev_byte_, s->prev_byte2_,
1150*f4ee7fbaSAndroid Build Coastguard Worker         s->num_literals_, s->num_commands_, s->commands_, s->saved_dist_cache_,
1151*f4ee7fbaSAndroid Build Coastguard Worker         s->dist_cache_, &storage_ix, storage);
1152*f4ee7fbaSAndroid Build Coastguard Worker     if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1153*f4ee7fbaSAndroid Build Coastguard Worker     s->last_bytes_ = (uint16_t)(storage[storage_ix >> 3]);
1154*f4ee7fbaSAndroid Build Coastguard Worker     s->last_bytes_bits_ = storage_ix & 7u;
1155*f4ee7fbaSAndroid Build Coastguard Worker     s->last_flush_pos_ = s->input_pos_;
1156*f4ee7fbaSAndroid Build Coastguard Worker     if (UpdateLastProcessedPos(s)) {
1157*f4ee7fbaSAndroid Build Coastguard Worker       HasherReset(&s->hasher_);
1158*f4ee7fbaSAndroid Build Coastguard Worker     }
1159*f4ee7fbaSAndroid Build Coastguard Worker     if (s->last_flush_pos_ > 0) {
1160*f4ee7fbaSAndroid Build Coastguard Worker       s->prev_byte_ = data[((uint32_t)s->last_flush_pos_ - 1) & mask];
1161*f4ee7fbaSAndroid Build Coastguard Worker     }
1162*f4ee7fbaSAndroid Build Coastguard Worker     if (s->last_flush_pos_ > 1) {
1163*f4ee7fbaSAndroid Build Coastguard Worker       s->prev_byte2_ = data[(uint32_t)(s->last_flush_pos_ - 2) & mask];
1164*f4ee7fbaSAndroid Build Coastguard Worker     }
1165*f4ee7fbaSAndroid Build Coastguard Worker     s->num_commands_ = 0;
1166*f4ee7fbaSAndroid Build Coastguard Worker     s->num_literals_ = 0;
1167*f4ee7fbaSAndroid Build Coastguard Worker     /* Save the state of the distance cache in case we need to restore it for
1168*f4ee7fbaSAndroid Build Coastguard Worker        emitting an uncompressed block. */
1169*f4ee7fbaSAndroid Build Coastguard Worker     memcpy(s->saved_dist_cache_, s->dist_cache_, sizeof(s->saved_dist_cache_));
1170*f4ee7fbaSAndroid Build Coastguard Worker     *output = &storage[0];
1171*f4ee7fbaSAndroid Build Coastguard Worker     *out_size = storage_ix >> 3;
1172*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1173*f4ee7fbaSAndroid Build Coastguard Worker   }
1174*f4ee7fbaSAndroid Build Coastguard Worker }
1175*f4ee7fbaSAndroid Build Coastguard Worker 
1176*f4ee7fbaSAndroid Build Coastguard Worker /* Dumps remaining output bits and metadata header to |header|.
1177*f4ee7fbaSAndroid Build Coastguard Worker    Returns number of produced bytes.
1178*f4ee7fbaSAndroid Build Coastguard Worker    REQUIRED: |header| should be 8-byte aligned and at least 16 bytes long.
1179*f4ee7fbaSAndroid Build Coastguard Worker    REQUIRED: |block_size| <= (1 << 24). */
WriteMetadataHeader(BrotliEncoderState * s,const size_t block_size,uint8_t * header)1180*f4ee7fbaSAndroid Build Coastguard Worker static size_t WriteMetadataHeader(
1181*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderState* s, const size_t block_size, uint8_t* header) {
1182*f4ee7fbaSAndroid Build Coastguard Worker   size_t storage_ix;
1183*f4ee7fbaSAndroid Build Coastguard Worker   storage_ix = s->last_bytes_bits_;
1184*f4ee7fbaSAndroid Build Coastguard Worker   header[0] = (uint8_t)s->last_bytes_;
1185*f4ee7fbaSAndroid Build Coastguard Worker   header[1] = (uint8_t)(s->last_bytes_ >> 8);
1186*f4ee7fbaSAndroid Build Coastguard Worker   s->last_bytes_ = 0;
1187*f4ee7fbaSAndroid Build Coastguard Worker   s->last_bytes_bits_ = 0;
1188*f4ee7fbaSAndroid Build Coastguard Worker 
1189*f4ee7fbaSAndroid Build Coastguard Worker   BrotliWriteBits(1, 0, &storage_ix, header);
1190*f4ee7fbaSAndroid Build Coastguard Worker   BrotliWriteBits(2, 3, &storage_ix, header);
1191*f4ee7fbaSAndroid Build Coastguard Worker   BrotliWriteBits(1, 0, &storage_ix, header);
1192*f4ee7fbaSAndroid Build Coastguard Worker   if (block_size == 0) {
1193*f4ee7fbaSAndroid Build Coastguard Worker     BrotliWriteBits(2, 0, &storage_ix, header);
1194*f4ee7fbaSAndroid Build Coastguard Worker   } else {
1195*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t nbits = (block_size == 1) ? 0 :
1196*f4ee7fbaSAndroid Build Coastguard Worker         (Log2FloorNonZero((uint32_t)block_size - 1) + 1);
1197*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t nbytes = (nbits + 7) / 8;
1198*f4ee7fbaSAndroid Build Coastguard Worker     BrotliWriteBits(2, nbytes, &storage_ix, header);
1199*f4ee7fbaSAndroid Build Coastguard Worker     BrotliWriteBits(8 * nbytes, block_size - 1, &storage_ix, header);
1200*f4ee7fbaSAndroid Build Coastguard Worker   }
1201*f4ee7fbaSAndroid Build Coastguard Worker   return (storage_ix + 7u) >> 3;
1202*f4ee7fbaSAndroid Build Coastguard Worker }
1203*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliCompressBufferQuality10(int lgwin,size_t input_size,const uint8_t * input_buffer,size_t * encoded_size,uint8_t * encoded_buffer)1204*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL BrotliCompressBufferQuality10(
1205*f4ee7fbaSAndroid Build Coastguard Worker     int lgwin, size_t input_size, const uint8_t* input_buffer,
1206*f4ee7fbaSAndroid Build Coastguard Worker     size_t* encoded_size, uint8_t* encoded_buffer) {
1207*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager memory_manager;
1208*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager* m = &memory_manager;
1209*f4ee7fbaSAndroid Build Coastguard Worker 
1210*f4ee7fbaSAndroid Build Coastguard Worker   const size_t mask = BROTLI_SIZE_MAX >> 1;
1211*f4ee7fbaSAndroid Build Coastguard Worker   int dist_cache[4] = { 4, 11, 15, 16 };
1212*f4ee7fbaSAndroid Build Coastguard Worker   int saved_dist_cache[4] = { 4, 11, 15, 16 };
1213*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_BOOL ok = BROTLI_TRUE;
1214*f4ee7fbaSAndroid Build Coastguard Worker   const size_t max_out_size = *encoded_size;
1215*f4ee7fbaSAndroid Build Coastguard Worker   size_t total_out_size = 0;
1216*f4ee7fbaSAndroid Build Coastguard Worker   uint16_t last_bytes;
1217*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t last_bytes_bits;
1218*f4ee7fbaSAndroid Build Coastguard Worker 
1219*f4ee7fbaSAndroid Build Coastguard Worker   const size_t hasher_eff_size = BROTLI_MIN(size_t,
1220*f4ee7fbaSAndroid Build Coastguard Worker       input_size, BROTLI_MAX_BACKWARD_LIMIT(lgwin) + BROTLI_WINDOW_GAP);
1221*f4ee7fbaSAndroid Build Coastguard Worker 
1222*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderParams params;
1223*f4ee7fbaSAndroid Build Coastguard Worker 
1224*f4ee7fbaSAndroid Build Coastguard Worker   const int lgmetablock = BROTLI_MIN(int, 24, lgwin + 1);
1225*f4ee7fbaSAndroid Build Coastguard Worker   size_t max_block_size;
1226*f4ee7fbaSAndroid Build Coastguard Worker   const size_t max_metablock_size = (size_t)1 << lgmetablock;
1227*f4ee7fbaSAndroid Build Coastguard Worker   const size_t max_literals_per_metablock = max_metablock_size / 8;
1228*f4ee7fbaSAndroid Build Coastguard Worker   const size_t max_commands_per_metablock = max_metablock_size / 8;
1229*f4ee7fbaSAndroid Build Coastguard Worker   size_t metablock_start = 0;
1230*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t prev_byte = 0;
1231*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t prev_byte2 = 0;
1232*f4ee7fbaSAndroid Build Coastguard Worker 
1233*f4ee7fbaSAndroid Build Coastguard Worker   Hasher hasher;
1234*f4ee7fbaSAndroid Build Coastguard Worker   HasherInit(&hasher);
1235*f4ee7fbaSAndroid Build Coastguard Worker 
1236*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderInitParams(&params);
1237*f4ee7fbaSAndroid Build Coastguard Worker   params.quality = 10;
1238*f4ee7fbaSAndroid Build Coastguard Worker   params.lgwin = lgwin;
1239*f4ee7fbaSAndroid Build Coastguard Worker   if (lgwin > BROTLI_MAX_WINDOW_BITS) {
1240*f4ee7fbaSAndroid Build Coastguard Worker     params.large_window = BROTLI_TRUE;
1241*f4ee7fbaSAndroid Build Coastguard Worker   }
1242*f4ee7fbaSAndroid Build Coastguard Worker   SanitizeParams(&params);
1243*f4ee7fbaSAndroid Build Coastguard Worker   params.lgblock = ComputeLgBlock(&params);
1244*f4ee7fbaSAndroid Build Coastguard Worker   ChooseDistanceParams(&params);
1245*f4ee7fbaSAndroid Build Coastguard Worker   max_block_size = (size_t)1 << params.lgblock;
1246*f4ee7fbaSAndroid Build Coastguard Worker 
1247*f4ee7fbaSAndroid Build Coastguard Worker   BrotliInitMemoryManager(m, 0, 0, 0);
1248*f4ee7fbaSAndroid Build Coastguard Worker 
1249*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_DCHECK(input_size <= mask + 1);
1250*f4ee7fbaSAndroid Build Coastguard Worker   EncodeWindowBits(lgwin, params.large_window, &last_bytes, &last_bytes_bits);
1251*f4ee7fbaSAndroid Build Coastguard Worker   InitOrStitchToPreviousBlock(m, &hasher, input_buffer, mask, &params,
1252*f4ee7fbaSAndroid Build Coastguard Worker       0, hasher_eff_size, BROTLI_TRUE);
1253*f4ee7fbaSAndroid Build Coastguard Worker   if (BROTLI_IS_OOM(m)) goto oom;
1254*f4ee7fbaSAndroid Build Coastguard Worker 
1255*f4ee7fbaSAndroid Build Coastguard Worker   while (ok && metablock_start < input_size) {
1256*f4ee7fbaSAndroid Build Coastguard Worker     const size_t metablock_end =
1257*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_MIN(size_t, input_size, metablock_start + max_metablock_size);
1258*f4ee7fbaSAndroid Build Coastguard Worker     const size_t expected_num_commands =
1259*f4ee7fbaSAndroid Build Coastguard Worker         (metablock_end - metablock_start) / 12 + 16;
1260*f4ee7fbaSAndroid Build Coastguard Worker     Command* commands = 0;
1261*f4ee7fbaSAndroid Build Coastguard Worker     size_t num_commands = 0;
1262*f4ee7fbaSAndroid Build Coastguard Worker     size_t last_insert_len = 0;
1263*f4ee7fbaSAndroid Build Coastguard Worker     size_t num_literals = 0;
1264*f4ee7fbaSAndroid Build Coastguard Worker     size_t metablock_size = 0;
1265*f4ee7fbaSAndroid Build Coastguard Worker     size_t cmd_alloc_size = 0;
1266*f4ee7fbaSAndroid Build Coastguard Worker     BROTLI_BOOL is_last;
1267*f4ee7fbaSAndroid Build Coastguard Worker     uint8_t* storage;
1268*f4ee7fbaSAndroid Build Coastguard Worker     size_t storage_ix;
1269*f4ee7fbaSAndroid Build Coastguard Worker 
1270*f4ee7fbaSAndroid Build Coastguard Worker     ContextType literal_context_mode = ChooseContextMode(&params,
1271*f4ee7fbaSAndroid Build Coastguard Worker         input_buffer, metablock_start, mask, metablock_end - metablock_start);
1272*f4ee7fbaSAndroid Build Coastguard Worker     ContextLut literal_context_lut = BROTLI_CONTEXT_LUT(literal_context_mode);
1273*f4ee7fbaSAndroid Build Coastguard Worker 
1274*f4ee7fbaSAndroid Build Coastguard Worker     size_t block_start;
1275*f4ee7fbaSAndroid Build Coastguard Worker     for (block_start = metablock_start; block_start < metablock_end; ) {
1276*f4ee7fbaSAndroid Build Coastguard Worker       size_t block_size =
1277*f4ee7fbaSAndroid Build Coastguard Worker           BROTLI_MIN(size_t, metablock_end - block_start, max_block_size);
1278*f4ee7fbaSAndroid Build Coastguard Worker       ZopfliNode* nodes = BROTLI_ALLOC(m, ZopfliNode, block_size + 1);
1279*f4ee7fbaSAndroid Build Coastguard Worker       size_t path_size;
1280*f4ee7fbaSAndroid Build Coastguard Worker       size_t new_cmd_alloc_size;
1281*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(nodes)) goto oom;
1282*f4ee7fbaSAndroid Build Coastguard Worker       BrotliInitZopfliNodes(nodes, block_size + 1);
1283*f4ee7fbaSAndroid Build Coastguard Worker       StitchToPreviousBlockH10(&hasher.privat._H10, block_size, block_start,
1284*f4ee7fbaSAndroid Build Coastguard Worker                                input_buffer, mask);
1285*f4ee7fbaSAndroid Build Coastguard Worker       path_size = BrotliZopfliComputeShortestPath(m, block_size, block_start,
1286*f4ee7fbaSAndroid Build Coastguard Worker           input_buffer, mask, literal_context_lut, &params, dist_cache, &hasher,
1287*f4ee7fbaSAndroid Build Coastguard Worker           nodes);
1288*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m)) goto oom;
1289*f4ee7fbaSAndroid Build Coastguard Worker       /* We allocate a command buffer in the first iteration of this loop that
1290*f4ee7fbaSAndroid Build Coastguard Worker          will be likely big enough for the whole metablock, so that for most
1291*f4ee7fbaSAndroid Build Coastguard Worker          inputs we will not have to reallocate in later iterations. We do the
1292*f4ee7fbaSAndroid Build Coastguard Worker          allocation here and not before the loop, because if the input is small,
1293*f4ee7fbaSAndroid Build Coastguard Worker          this will be allocated after the Zopfli cost model is freed, so this
1294*f4ee7fbaSAndroid Build Coastguard Worker          will not increase peak memory usage.
1295*f4ee7fbaSAndroid Build Coastguard Worker          TODO: If the first allocation is too small, increase command
1296*f4ee7fbaSAndroid Build Coastguard Worker          buffer size exponentially. */
1297*f4ee7fbaSAndroid Build Coastguard Worker       new_cmd_alloc_size = BROTLI_MAX(size_t, expected_num_commands,
1298*f4ee7fbaSAndroid Build Coastguard Worker                                       num_commands + path_size + 1);
1299*f4ee7fbaSAndroid Build Coastguard Worker       if (cmd_alloc_size != new_cmd_alloc_size) {
1300*f4ee7fbaSAndroid Build Coastguard Worker         Command* new_commands = BROTLI_ALLOC(m, Command, new_cmd_alloc_size);
1301*f4ee7fbaSAndroid Build Coastguard Worker         if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(new_commands)) goto oom;
1302*f4ee7fbaSAndroid Build Coastguard Worker         cmd_alloc_size = new_cmd_alloc_size;
1303*f4ee7fbaSAndroid Build Coastguard Worker         if (commands) {
1304*f4ee7fbaSAndroid Build Coastguard Worker           memcpy(new_commands, commands, sizeof(Command) * num_commands);
1305*f4ee7fbaSAndroid Build Coastguard Worker           BROTLI_FREE(m, commands);
1306*f4ee7fbaSAndroid Build Coastguard Worker         }
1307*f4ee7fbaSAndroid Build Coastguard Worker         commands = new_commands;
1308*f4ee7fbaSAndroid Build Coastguard Worker       }
1309*f4ee7fbaSAndroid Build Coastguard Worker       BrotliZopfliCreateCommands(block_size, block_start, &nodes[0], dist_cache,
1310*f4ee7fbaSAndroid Build Coastguard Worker           &last_insert_len, &params, &commands[num_commands], &num_literals);
1311*f4ee7fbaSAndroid Build Coastguard Worker       num_commands += path_size;
1312*f4ee7fbaSAndroid Build Coastguard Worker       block_start += block_size;
1313*f4ee7fbaSAndroid Build Coastguard Worker       metablock_size += block_size;
1314*f4ee7fbaSAndroid Build Coastguard Worker       BROTLI_FREE(m, nodes);
1315*f4ee7fbaSAndroid Build Coastguard Worker       if (num_literals > max_literals_per_metablock ||
1316*f4ee7fbaSAndroid Build Coastguard Worker           num_commands > max_commands_per_metablock) {
1317*f4ee7fbaSAndroid Build Coastguard Worker         break;
1318*f4ee7fbaSAndroid Build Coastguard Worker       }
1319*f4ee7fbaSAndroid Build Coastguard Worker     }
1320*f4ee7fbaSAndroid Build Coastguard Worker 
1321*f4ee7fbaSAndroid Build Coastguard Worker     if (last_insert_len > 0) {
1322*f4ee7fbaSAndroid Build Coastguard Worker       InitInsertCommand(&commands[num_commands++], last_insert_len);
1323*f4ee7fbaSAndroid Build Coastguard Worker       num_literals += last_insert_len;
1324*f4ee7fbaSAndroid Build Coastguard Worker     }
1325*f4ee7fbaSAndroid Build Coastguard Worker 
1326*f4ee7fbaSAndroid Build Coastguard Worker     is_last = TO_BROTLI_BOOL(metablock_start + metablock_size == input_size);
1327*f4ee7fbaSAndroid Build Coastguard Worker     storage = NULL;
1328*f4ee7fbaSAndroid Build Coastguard Worker     storage_ix = last_bytes_bits;
1329*f4ee7fbaSAndroid Build Coastguard Worker 
1330*f4ee7fbaSAndroid Build Coastguard Worker     if (metablock_size == 0) {
1331*f4ee7fbaSAndroid Build Coastguard Worker       /* Write the ISLAST and ISEMPTY bits. */
1332*f4ee7fbaSAndroid Build Coastguard Worker       storage = BROTLI_ALLOC(m, uint8_t, 16);
1333*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(storage)) goto oom;
1334*f4ee7fbaSAndroid Build Coastguard Worker       storage[0] = (uint8_t)last_bytes;
1335*f4ee7fbaSAndroid Build Coastguard Worker       storage[1] = (uint8_t)(last_bytes >> 8);
1336*f4ee7fbaSAndroid Build Coastguard Worker       BrotliWriteBits(2, 3, &storage_ix, storage);
1337*f4ee7fbaSAndroid Build Coastguard Worker       storage_ix = (storage_ix + 7u) & ~7u;
1338*f4ee7fbaSAndroid Build Coastguard Worker     } else if (!ShouldCompress(input_buffer, mask, metablock_start,
1339*f4ee7fbaSAndroid Build Coastguard Worker                                metablock_size, num_literals, num_commands)) {
1340*f4ee7fbaSAndroid Build Coastguard Worker       /* Restore the distance cache, as its last update by
1341*f4ee7fbaSAndroid Build Coastguard Worker          CreateBackwardReferences is now unused. */
1342*f4ee7fbaSAndroid Build Coastguard Worker       memcpy(dist_cache, saved_dist_cache, 4 * sizeof(dist_cache[0]));
1343*f4ee7fbaSAndroid Build Coastguard Worker       storage = BROTLI_ALLOC(m, uint8_t, metablock_size + 16);
1344*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(storage)) goto oom;
1345*f4ee7fbaSAndroid Build Coastguard Worker       storage[0] = (uint8_t)last_bytes;
1346*f4ee7fbaSAndroid Build Coastguard Worker       storage[1] = (uint8_t)(last_bytes >> 8);
1347*f4ee7fbaSAndroid Build Coastguard Worker       BrotliStoreUncompressedMetaBlock(is_last, input_buffer,
1348*f4ee7fbaSAndroid Build Coastguard Worker                                        metablock_start, mask, metablock_size,
1349*f4ee7fbaSAndroid Build Coastguard Worker                                        &storage_ix, storage);
1350*f4ee7fbaSAndroid Build Coastguard Worker     } else {
1351*f4ee7fbaSAndroid Build Coastguard Worker       MetaBlockSplit mb;
1352*f4ee7fbaSAndroid Build Coastguard Worker       BrotliEncoderParams block_params = params;
1353*f4ee7fbaSAndroid Build Coastguard Worker       InitMetaBlockSplit(&mb);
1354*f4ee7fbaSAndroid Build Coastguard Worker       BrotliBuildMetaBlock(m, input_buffer, metablock_start, mask,
1355*f4ee7fbaSAndroid Build Coastguard Worker                            &block_params,
1356*f4ee7fbaSAndroid Build Coastguard Worker                            prev_byte, prev_byte2,
1357*f4ee7fbaSAndroid Build Coastguard Worker                            commands, num_commands,
1358*f4ee7fbaSAndroid Build Coastguard Worker                            literal_context_mode,
1359*f4ee7fbaSAndroid Build Coastguard Worker                            &mb);
1360*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m)) goto oom;
1361*f4ee7fbaSAndroid Build Coastguard Worker       {
1362*f4ee7fbaSAndroid Build Coastguard Worker         /* The number of distance symbols effectively used for distance
1363*f4ee7fbaSAndroid Build Coastguard Worker            histograms. It might be less than distance alphabet size
1364*f4ee7fbaSAndroid Build Coastguard Worker            for "Large Window Brotli" (32-bit). */
1365*f4ee7fbaSAndroid Build Coastguard Worker         BrotliOptimizeHistograms(block_params.dist.alphabet_size_limit, &mb);
1366*f4ee7fbaSAndroid Build Coastguard Worker       }
1367*f4ee7fbaSAndroid Build Coastguard Worker       storage = BROTLI_ALLOC(m, uint8_t, 2 * metablock_size + 503);
1368*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(storage)) goto oom;
1369*f4ee7fbaSAndroid Build Coastguard Worker       storage[0] = (uint8_t)last_bytes;
1370*f4ee7fbaSAndroid Build Coastguard Worker       storage[1] = (uint8_t)(last_bytes >> 8);
1371*f4ee7fbaSAndroid Build Coastguard Worker       BrotliStoreMetaBlock(m, input_buffer, metablock_start, metablock_size,
1372*f4ee7fbaSAndroid Build Coastguard Worker                            mask, prev_byte, prev_byte2,
1373*f4ee7fbaSAndroid Build Coastguard Worker                            is_last,
1374*f4ee7fbaSAndroid Build Coastguard Worker                            &block_params,
1375*f4ee7fbaSAndroid Build Coastguard Worker                            literal_context_mode,
1376*f4ee7fbaSAndroid Build Coastguard Worker                            commands, num_commands,
1377*f4ee7fbaSAndroid Build Coastguard Worker                            &mb,
1378*f4ee7fbaSAndroid Build Coastguard Worker                            &storage_ix, storage);
1379*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m)) goto oom;
1380*f4ee7fbaSAndroid Build Coastguard Worker       if (metablock_size + 4 < (storage_ix >> 3)) {
1381*f4ee7fbaSAndroid Build Coastguard Worker         /* Restore the distance cache and last byte. */
1382*f4ee7fbaSAndroid Build Coastguard Worker         memcpy(dist_cache, saved_dist_cache, 4 * sizeof(dist_cache[0]));
1383*f4ee7fbaSAndroid Build Coastguard Worker         storage[0] = (uint8_t)last_bytes;
1384*f4ee7fbaSAndroid Build Coastguard Worker         storage[1] = (uint8_t)(last_bytes >> 8);
1385*f4ee7fbaSAndroid Build Coastguard Worker         storage_ix = last_bytes_bits;
1386*f4ee7fbaSAndroid Build Coastguard Worker         BrotliStoreUncompressedMetaBlock(is_last, input_buffer,
1387*f4ee7fbaSAndroid Build Coastguard Worker                                          metablock_start, mask,
1388*f4ee7fbaSAndroid Build Coastguard Worker                                          metablock_size, &storage_ix, storage);
1389*f4ee7fbaSAndroid Build Coastguard Worker       }
1390*f4ee7fbaSAndroid Build Coastguard Worker       DestroyMetaBlockSplit(m, &mb);
1391*f4ee7fbaSAndroid Build Coastguard Worker     }
1392*f4ee7fbaSAndroid Build Coastguard Worker     last_bytes = (uint16_t)(storage[storage_ix >> 3]);
1393*f4ee7fbaSAndroid Build Coastguard Worker     last_bytes_bits = storage_ix & 7u;
1394*f4ee7fbaSAndroid Build Coastguard Worker     metablock_start += metablock_size;
1395*f4ee7fbaSAndroid Build Coastguard Worker     if (metablock_start < input_size) {
1396*f4ee7fbaSAndroid Build Coastguard Worker       prev_byte = input_buffer[metablock_start - 1];
1397*f4ee7fbaSAndroid Build Coastguard Worker       prev_byte2 = input_buffer[metablock_start - 2];
1398*f4ee7fbaSAndroid Build Coastguard Worker     }
1399*f4ee7fbaSAndroid Build Coastguard Worker     /* Save the state of the distance cache in case we need to restore it for
1400*f4ee7fbaSAndroid Build Coastguard Worker        emitting an uncompressed block. */
1401*f4ee7fbaSAndroid Build Coastguard Worker     memcpy(saved_dist_cache, dist_cache, 4 * sizeof(dist_cache[0]));
1402*f4ee7fbaSAndroid Build Coastguard Worker 
1403*f4ee7fbaSAndroid Build Coastguard Worker     {
1404*f4ee7fbaSAndroid Build Coastguard Worker       const size_t out_size = storage_ix >> 3;
1405*f4ee7fbaSAndroid Build Coastguard Worker       total_out_size += out_size;
1406*f4ee7fbaSAndroid Build Coastguard Worker       if (total_out_size <= max_out_size) {
1407*f4ee7fbaSAndroid Build Coastguard Worker         memcpy(encoded_buffer, storage, out_size);
1408*f4ee7fbaSAndroid Build Coastguard Worker         encoded_buffer += out_size;
1409*f4ee7fbaSAndroid Build Coastguard Worker       } else {
1410*f4ee7fbaSAndroid Build Coastguard Worker         ok = BROTLI_FALSE;
1411*f4ee7fbaSAndroid Build Coastguard Worker       }
1412*f4ee7fbaSAndroid Build Coastguard Worker     }
1413*f4ee7fbaSAndroid Build Coastguard Worker     BROTLI_FREE(m, storage);
1414*f4ee7fbaSAndroid Build Coastguard Worker     BROTLI_FREE(m, commands);
1415*f4ee7fbaSAndroid Build Coastguard Worker   }
1416*f4ee7fbaSAndroid Build Coastguard Worker 
1417*f4ee7fbaSAndroid Build Coastguard Worker   *encoded_size = total_out_size;
1418*f4ee7fbaSAndroid Build Coastguard Worker   DestroyHasher(m, &hasher);
1419*f4ee7fbaSAndroid Build Coastguard Worker   return ok;
1420*f4ee7fbaSAndroid Build Coastguard Worker 
1421*f4ee7fbaSAndroid Build Coastguard Worker oom:
1422*f4ee7fbaSAndroid Build Coastguard Worker   BrotliWipeOutMemoryManager(m);
1423*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_FALSE;
1424*f4ee7fbaSAndroid Build Coastguard Worker }
1425*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderMaxCompressedSize(size_t input_size)1426*f4ee7fbaSAndroid Build Coastguard Worker size_t BrotliEncoderMaxCompressedSize(size_t input_size) {
1427*f4ee7fbaSAndroid Build Coastguard Worker   /* [window bits / empty metadata] + N * [uncompressed] + [last empty] */
1428*f4ee7fbaSAndroid Build Coastguard Worker   size_t num_large_blocks = input_size >> 14;
1429*f4ee7fbaSAndroid Build Coastguard Worker   size_t overhead = 2 + (4 * num_large_blocks) + 3 + 1;
1430*f4ee7fbaSAndroid Build Coastguard Worker   size_t result = input_size + overhead;
1431*f4ee7fbaSAndroid Build Coastguard Worker   if (input_size == 0) return 2;
1432*f4ee7fbaSAndroid Build Coastguard Worker   return (result < input_size) ? 0 : result;
1433*f4ee7fbaSAndroid Build Coastguard Worker }
1434*f4ee7fbaSAndroid Build Coastguard Worker 
1435*f4ee7fbaSAndroid Build Coastguard Worker /* Wraps data to uncompressed brotli stream with minimal window size.
1436*f4ee7fbaSAndroid Build Coastguard Worker    |output| should point at region with at least BrotliEncoderMaxCompressedSize
1437*f4ee7fbaSAndroid Build Coastguard Worker    addressable bytes.
1438*f4ee7fbaSAndroid Build Coastguard Worker    Returns the length of stream. */
MakeUncompressedStream(const uint8_t * input,size_t input_size,uint8_t * output)1439*f4ee7fbaSAndroid Build Coastguard Worker static size_t MakeUncompressedStream(
1440*f4ee7fbaSAndroid Build Coastguard Worker     const uint8_t* input, size_t input_size, uint8_t* output) {
1441*f4ee7fbaSAndroid Build Coastguard Worker   size_t size = input_size;
1442*f4ee7fbaSAndroid Build Coastguard Worker   size_t result = 0;
1443*f4ee7fbaSAndroid Build Coastguard Worker   size_t offset = 0;
1444*f4ee7fbaSAndroid Build Coastguard Worker   if (input_size == 0) {
1445*f4ee7fbaSAndroid Build Coastguard Worker     output[0] = 6;
1446*f4ee7fbaSAndroid Build Coastguard Worker     return 1;
1447*f4ee7fbaSAndroid Build Coastguard Worker   }
1448*f4ee7fbaSAndroid Build Coastguard Worker   output[result++] = 0x21;  /* window bits = 10, is_last = false */
1449*f4ee7fbaSAndroid Build Coastguard Worker   output[result++] = 0x03;  /* empty metadata, padding */
1450*f4ee7fbaSAndroid Build Coastguard Worker   while (size > 0) {
1451*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t nibbles = 0;
1452*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t chunk_size;
1453*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t bits;
1454*f4ee7fbaSAndroid Build Coastguard Worker     chunk_size = (size > (1u << 24)) ? (1u << 24) : (uint32_t)size;
1455*f4ee7fbaSAndroid Build Coastguard Worker     if (chunk_size > (1u << 16)) nibbles = (chunk_size > (1u << 20)) ? 2 : 1;
1456*f4ee7fbaSAndroid Build Coastguard Worker     bits =
1457*f4ee7fbaSAndroid Build Coastguard Worker         (nibbles << 1) | ((chunk_size - 1) << 3) | (1u << (19 + 4 * nibbles));
1458*f4ee7fbaSAndroid Build Coastguard Worker     output[result++] = (uint8_t)bits;
1459*f4ee7fbaSAndroid Build Coastguard Worker     output[result++] = (uint8_t)(bits >> 8);
1460*f4ee7fbaSAndroid Build Coastguard Worker     output[result++] = (uint8_t)(bits >> 16);
1461*f4ee7fbaSAndroid Build Coastguard Worker     if (nibbles == 2) output[result++] = (uint8_t)(bits >> 24);
1462*f4ee7fbaSAndroid Build Coastguard Worker     memcpy(&output[result], &input[offset], chunk_size);
1463*f4ee7fbaSAndroid Build Coastguard Worker     result += chunk_size;
1464*f4ee7fbaSAndroid Build Coastguard Worker     offset += chunk_size;
1465*f4ee7fbaSAndroid Build Coastguard Worker     size -= chunk_size;
1466*f4ee7fbaSAndroid Build Coastguard Worker   }
1467*f4ee7fbaSAndroid Build Coastguard Worker   output[result++] = 3;
1468*f4ee7fbaSAndroid Build Coastguard Worker   return result;
1469*f4ee7fbaSAndroid Build Coastguard Worker }
1470*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderCompress(int quality,int lgwin,BrotliEncoderMode mode,size_t input_size,const uint8_t * input_buffer,size_t * encoded_size,uint8_t * encoded_buffer)1471*f4ee7fbaSAndroid Build Coastguard Worker BROTLI_BOOL BrotliEncoderCompress(
1472*f4ee7fbaSAndroid Build Coastguard Worker     int quality, int lgwin, BrotliEncoderMode mode, size_t input_size,
1473*f4ee7fbaSAndroid Build Coastguard Worker     const uint8_t* input_buffer, size_t* encoded_size,
1474*f4ee7fbaSAndroid Build Coastguard Worker     uint8_t* encoded_buffer) {
1475*f4ee7fbaSAndroid Build Coastguard Worker   BrotliEncoderState* s;
1476*f4ee7fbaSAndroid Build Coastguard Worker   size_t out_size = *encoded_size;
1477*f4ee7fbaSAndroid Build Coastguard Worker   const uint8_t* input_start = input_buffer;
1478*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* output_start = encoded_buffer;
1479*f4ee7fbaSAndroid Build Coastguard Worker   size_t max_out_size = BrotliEncoderMaxCompressedSize(input_size);
1480*f4ee7fbaSAndroid Build Coastguard Worker   if (out_size == 0) {
1481*f4ee7fbaSAndroid Build Coastguard Worker     /* Output buffer needs at least one byte. */
1482*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_FALSE;
1483*f4ee7fbaSAndroid Build Coastguard Worker   }
1484*f4ee7fbaSAndroid Build Coastguard Worker   if (input_size == 0) {
1485*f4ee7fbaSAndroid Build Coastguard Worker     /* Handle the special case of empty input. */
1486*f4ee7fbaSAndroid Build Coastguard Worker     *encoded_size = 1;
1487*f4ee7fbaSAndroid Build Coastguard Worker     *encoded_buffer = 6;
1488*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1489*f4ee7fbaSAndroid Build Coastguard Worker   }
1490*f4ee7fbaSAndroid Build Coastguard Worker   if (quality == 10) {
1491*f4ee7fbaSAndroid Build Coastguard Worker     /* TODO: Implement this direct path for all quality levels. */
1492*f4ee7fbaSAndroid Build Coastguard Worker     const int lg_win = BROTLI_MIN(int, BROTLI_LARGE_MAX_WINDOW_BITS,
1493*f4ee7fbaSAndroid Build Coastguard Worker                                        BROTLI_MAX(int, 16, lgwin));
1494*f4ee7fbaSAndroid Build Coastguard Worker     int ok = BrotliCompressBufferQuality10(lg_win, input_size, input_buffer,
1495*f4ee7fbaSAndroid Build Coastguard Worker                                            encoded_size, encoded_buffer);
1496*f4ee7fbaSAndroid Build Coastguard Worker     if (!ok || (max_out_size && *encoded_size > max_out_size)) {
1497*f4ee7fbaSAndroid Build Coastguard Worker       goto fallback;
1498*f4ee7fbaSAndroid Build Coastguard Worker     }
1499*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1500*f4ee7fbaSAndroid Build Coastguard Worker   }
1501*f4ee7fbaSAndroid Build Coastguard Worker 
1502*f4ee7fbaSAndroid Build Coastguard Worker   s = BrotliEncoderCreateInstance(0, 0, 0);
1503*f4ee7fbaSAndroid Build Coastguard Worker   if (!s) {
1504*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_FALSE;
1505*f4ee7fbaSAndroid Build Coastguard Worker   } else {
1506*f4ee7fbaSAndroid Build Coastguard Worker     size_t available_in = input_size;
1507*f4ee7fbaSAndroid Build Coastguard Worker     const uint8_t* next_in = input_buffer;
1508*f4ee7fbaSAndroid Build Coastguard Worker     size_t available_out = *encoded_size;
1509*f4ee7fbaSAndroid Build Coastguard Worker     uint8_t* next_out = encoded_buffer;
1510*f4ee7fbaSAndroid Build Coastguard Worker     size_t total_out = 0;
1511*f4ee7fbaSAndroid Build Coastguard Worker     BROTLI_BOOL result = BROTLI_FALSE;
1512*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderSetParameter(s, BROTLI_PARAM_QUALITY, (uint32_t)quality);
1513*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, (uint32_t)lgwin);
1514*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderSetParameter(s, BROTLI_PARAM_MODE, (uint32_t)mode);
1515*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderSetParameter(s, BROTLI_PARAM_SIZE_HINT, (uint32_t)input_size);
1516*f4ee7fbaSAndroid Build Coastguard Worker     if (lgwin > BROTLI_MAX_WINDOW_BITS) {
1517*f4ee7fbaSAndroid Build Coastguard Worker       BrotliEncoderSetParameter(s, BROTLI_PARAM_LARGE_WINDOW, BROTLI_TRUE);
1518*f4ee7fbaSAndroid Build Coastguard Worker     }
1519*f4ee7fbaSAndroid Build Coastguard Worker     result = BrotliEncoderCompressStream(s, BROTLI_OPERATION_FINISH,
1520*f4ee7fbaSAndroid Build Coastguard Worker         &available_in, &next_in, &available_out, &next_out, &total_out);
1521*f4ee7fbaSAndroid Build Coastguard Worker     if (!BrotliEncoderIsFinished(s)) result = 0;
1522*f4ee7fbaSAndroid Build Coastguard Worker     *encoded_size = total_out;
1523*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderDestroyInstance(s);
1524*f4ee7fbaSAndroid Build Coastguard Worker     if (!result || (max_out_size && *encoded_size > max_out_size)) {
1525*f4ee7fbaSAndroid Build Coastguard Worker       goto fallback;
1526*f4ee7fbaSAndroid Build Coastguard Worker     }
1527*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1528*f4ee7fbaSAndroid Build Coastguard Worker   }
1529*f4ee7fbaSAndroid Build Coastguard Worker fallback:
1530*f4ee7fbaSAndroid Build Coastguard Worker   *encoded_size = 0;
1531*f4ee7fbaSAndroid Build Coastguard Worker   if (!max_out_size) return BROTLI_FALSE;
1532*f4ee7fbaSAndroid Build Coastguard Worker   if (out_size >= max_out_size) {
1533*f4ee7fbaSAndroid Build Coastguard Worker     *encoded_size =
1534*f4ee7fbaSAndroid Build Coastguard Worker         MakeUncompressedStream(input_start, input_size, output_start);
1535*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1536*f4ee7fbaSAndroid Build Coastguard Worker   }
1537*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_FALSE;
1538*f4ee7fbaSAndroid Build Coastguard Worker }
1539*f4ee7fbaSAndroid Build Coastguard Worker 
InjectBytePaddingBlock(BrotliEncoderState * s)1540*f4ee7fbaSAndroid Build Coastguard Worker static void InjectBytePaddingBlock(BrotliEncoderState* s) {
1541*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t seal = s->last_bytes_;
1542*f4ee7fbaSAndroid Build Coastguard Worker   size_t seal_bits = s->last_bytes_bits_;
1543*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* destination;
1544*f4ee7fbaSAndroid Build Coastguard Worker   s->last_bytes_ = 0;
1545*f4ee7fbaSAndroid Build Coastguard Worker   s->last_bytes_bits_ = 0;
1546*f4ee7fbaSAndroid Build Coastguard Worker   /* is_last = 0, data_nibbles = 11, reserved = 0, meta_nibbles = 00 */
1547*f4ee7fbaSAndroid Build Coastguard Worker   seal |= 0x6u << seal_bits;
1548*f4ee7fbaSAndroid Build Coastguard Worker   seal_bits += 6;
1549*f4ee7fbaSAndroid Build Coastguard Worker   /* If we have already created storage, then append to it.
1550*f4ee7fbaSAndroid Build Coastguard Worker      Storage is valid until next block is being compressed. */
1551*f4ee7fbaSAndroid Build Coastguard Worker   if (s->next_out_) {
1552*f4ee7fbaSAndroid Build Coastguard Worker     destination = s->next_out_ + s->available_out_;
1553*f4ee7fbaSAndroid Build Coastguard Worker   } else {
1554*f4ee7fbaSAndroid Build Coastguard Worker     destination = s->tiny_buf_.u8;
1555*f4ee7fbaSAndroid Build Coastguard Worker     s->next_out_ = destination;
1556*f4ee7fbaSAndroid Build Coastguard Worker   }
1557*f4ee7fbaSAndroid Build Coastguard Worker   destination[0] = (uint8_t)seal;
1558*f4ee7fbaSAndroid Build Coastguard Worker   if (seal_bits > 8) destination[1] = (uint8_t)(seal >> 8);
1559*f4ee7fbaSAndroid Build Coastguard Worker   if (seal_bits > 16) destination[2] = (uint8_t)(seal >> 16);
1560*f4ee7fbaSAndroid Build Coastguard Worker   s->available_out_ += (seal_bits + 7) >> 3;
1561*f4ee7fbaSAndroid Build Coastguard Worker }
1562*f4ee7fbaSAndroid Build Coastguard Worker 
1563*f4ee7fbaSAndroid Build Coastguard Worker /* Injects padding bits or pushes compressed data to output.
1564*f4ee7fbaSAndroid Build Coastguard Worker    Returns false if nothing is done. */
InjectFlushOrPushOutput(BrotliEncoderState * s,size_t * available_out,uint8_t ** next_out,size_t * total_out)1565*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL InjectFlushOrPushOutput(BrotliEncoderState* s,
1566*f4ee7fbaSAndroid Build Coastguard Worker     size_t* available_out, uint8_t** next_out, size_t* total_out) {
1567*f4ee7fbaSAndroid Build Coastguard Worker   if (s->stream_state_ == BROTLI_STREAM_FLUSH_REQUESTED &&
1568*f4ee7fbaSAndroid Build Coastguard Worker       s->last_bytes_bits_ != 0) {
1569*f4ee7fbaSAndroid Build Coastguard Worker     InjectBytePaddingBlock(s);
1570*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1571*f4ee7fbaSAndroid Build Coastguard Worker   }
1572*f4ee7fbaSAndroid Build Coastguard Worker 
1573*f4ee7fbaSAndroid Build Coastguard Worker   if (s->available_out_ != 0 && *available_out != 0) {
1574*f4ee7fbaSAndroid Build Coastguard Worker     size_t copy_output_size =
1575*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_MIN(size_t, s->available_out_, *available_out);
1576*f4ee7fbaSAndroid Build Coastguard Worker     memcpy(*next_out, s->next_out_, copy_output_size);
1577*f4ee7fbaSAndroid Build Coastguard Worker     *next_out += copy_output_size;
1578*f4ee7fbaSAndroid Build Coastguard Worker     *available_out -= copy_output_size;
1579*f4ee7fbaSAndroid Build Coastguard Worker     s->next_out_ += copy_output_size;
1580*f4ee7fbaSAndroid Build Coastguard Worker     s->available_out_ -= copy_output_size;
1581*f4ee7fbaSAndroid Build Coastguard Worker     s->total_out_ += copy_output_size;
1582*f4ee7fbaSAndroid Build Coastguard Worker     if (total_out) *total_out = s->total_out_;
1583*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_TRUE;
1584*f4ee7fbaSAndroid Build Coastguard Worker   }
1585*f4ee7fbaSAndroid Build Coastguard Worker 
1586*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_FALSE;
1587*f4ee7fbaSAndroid Build Coastguard Worker }
1588*f4ee7fbaSAndroid Build Coastguard Worker 
CheckFlushComplete(BrotliEncoderState * s)1589*f4ee7fbaSAndroid Build Coastguard Worker static void CheckFlushComplete(BrotliEncoderState* s) {
1590*f4ee7fbaSAndroid Build Coastguard Worker   if (s->stream_state_ == BROTLI_STREAM_FLUSH_REQUESTED &&
1591*f4ee7fbaSAndroid Build Coastguard Worker       s->available_out_ == 0) {
1592*f4ee7fbaSAndroid Build Coastguard Worker     s->stream_state_ = BROTLI_STREAM_PROCESSING;
1593*f4ee7fbaSAndroid Build Coastguard Worker     s->next_out_ = 0;
1594*f4ee7fbaSAndroid Build Coastguard Worker   }
1595*f4ee7fbaSAndroid Build Coastguard Worker }
1596*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderCompressStreamFast(BrotliEncoderState * s,BrotliEncoderOperation op,size_t * available_in,const uint8_t ** next_in,size_t * available_out,uint8_t ** next_out,size_t * total_out)1597*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL BrotliEncoderCompressStreamFast(
1598*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderState* s, BrotliEncoderOperation op, size_t* available_in,
1599*f4ee7fbaSAndroid Build Coastguard Worker     const uint8_t** next_in, size_t* available_out, uint8_t** next_out,
1600*f4ee7fbaSAndroid Build Coastguard Worker     size_t* total_out) {
1601*f4ee7fbaSAndroid Build Coastguard Worker   const size_t block_size_limit = (size_t)1 << s->params.lgwin;
1602*f4ee7fbaSAndroid Build Coastguard Worker   const size_t buf_size = BROTLI_MIN(size_t, kCompressFragmentTwoPassBlockSize,
1603*f4ee7fbaSAndroid Build Coastguard Worker       BROTLI_MIN(size_t, *available_in, block_size_limit));
1604*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t* tmp_command_buf = NULL;
1605*f4ee7fbaSAndroid Build Coastguard Worker   uint32_t* command_buf = NULL;
1606*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* tmp_literal_buf = NULL;
1607*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* literal_buf = NULL;
1608*f4ee7fbaSAndroid Build Coastguard Worker   MemoryManager* m = &s->memory_manager_;
1609*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.quality != FAST_ONE_PASS_COMPRESSION_QUALITY &&
1610*f4ee7fbaSAndroid Build Coastguard Worker       s->params.quality != FAST_TWO_PASS_COMPRESSION_QUALITY) {
1611*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_FALSE;
1612*f4ee7fbaSAndroid Build Coastguard Worker   }
1613*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY) {
1614*f4ee7fbaSAndroid Build Coastguard Worker     if (!s->command_buf_ && buf_size == kCompressFragmentTwoPassBlockSize) {
1615*f4ee7fbaSAndroid Build Coastguard Worker       s->command_buf_ =
1616*f4ee7fbaSAndroid Build Coastguard Worker           BROTLI_ALLOC(m, uint32_t, kCompressFragmentTwoPassBlockSize);
1617*f4ee7fbaSAndroid Build Coastguard Worker       s->literal_buf_ =
1618*f4ee7fbaSAndroid Build Coastguard Worker           BROTLI_ALLOC(m, uint8_t, kCompressFragmentTwoPassBlockSize);
1619*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(s->command_buf_) ||
1620*f4ee7fbaSAndroid Build Coastguard Worker           BROTLI_IS_NULL(s->literal_buf_)) {
1621*f4ee7fbaSAndroid Build Coastguard Worker         return BROTLI_FALSE;
1622*f4ee7fbaSAndroid Build Coastguard Worker       }
1623*f4ee7fbaSAndroid Build Coastguard Worker     }
1624*f4ee7fbaSAndroid Build Coastguard Worker     if (s->command_buf_) {
1625*f4ee7fbaSAndroid Build Coastguard Worker       command_buf = s->command_buf_;
1626*f4ee7fbaSAndroid Build Coastguard Worker       literal_buf = s->literal_buf_;
1627*f4ee7fbaSAndroid Build Coastguard Worker     } else {
1628*f4ee7fbaSAndroid Build Coastguard Worker       tmp_command_buf = BROTLI_ALLOC(m, uint32_t, buf_size);
1629*f4ee7fbaSAndroid Build Coastguard Worker       tmp_literal_buf = BROTLI_ALLOC(m, uint8_t, buf_size);
1630*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(tmp_command_buf) ||
1631*f4ee7fbaSAndroid Build Coastguard Worker           BROTLI_IS_NULL(tmp_literal_buf)) {
1632*f4ee7fbaSAndroid Build Coastguard Worker         return BROTLI_FALSE;
1633*f4ee7fbaSAndroid Build Coastguard Worker       }
1634*f4ee7fbaSAndroid Build Coastguard Worker       command_buf = tmp_command_buf;
1635*f4ee7fbaSAndroid Build Coastguard Worker       literal_buf = tmp_literal_buf;
1636*f4ee7fbaSAndroid Build Coastguard Worker     }
1637*f4ee7fbaSAndroid Build Coastguard Worker   }
1638*f4ee7fbaSAndroid Build Coastguard Worker 
1639*f4ee7fbaSAndroid Build Coastguard Worker   while (BROTLI_TRUE) {
1640*f4ee7fbaSAndroid Build Coastguard Worker     if (InjectFlushOrPushOutput(s, available_out, next_out, total_out)) {
1641*f4ee7fbaSAndroid Build Coastguard Worker       continue;
1642*f4ee7fbaSAndroid Build Coastguard Worker     }
1643*f4ee7fbaSAndroid Build Coastguard Worker 
1644*f4ee7fbaSAndroid Build Coastguard Worker     /* Compress block only when internal output buffer is empty, stream is not
1645*f4ee7fbaSAndroid Build Coastguard Worker        finished, there is no pending flush request, and there is either
1646*f4ee7fbaSAndroid Build Coastguard Worker        additional input or pending operation. */
1647*f4ee7fbaSAndroid Build Coastguard Worker     if (s->available_out_ == 0 &&
1648*f4ee7fbaSAndroid Build Coastguard Worker         s->stream_state_ == BROTLI_STREAM_PROCESSING &&
1649*f4ee7fbaSAndroid Build Coastguard Worker         (*available_in != 0 || op != BROTLI_OPERATION_PROCESS)) {
1650*f4ee7fbaSAndroid Build Coastguard Worker       size_t block_size = BROTLI_MIN(size_t, block_size_limit, *available_in);
1651*f4ee7fbaSAndroid Build Coastguard Worker       BROTLI_BOOL is_last =
1652*f4ee7fbaSAndroid Build Coastguard Worker           (*available_in == block_size) && (op == BROTLI_OPERATION_FINISH);
1653*f4ee7fbaSAndroid Build Coastguard Worker       BROTLI_BOOL force_flush =
1654*f4ee7fbaSAndroid Build Coastguard Worker           (*available_in == block_size) && (op == BROTLI_OPERATION_FLUSH);
1655*f4ee7fbaSAndroid Build Coastguard Worker       size_t max_out_size = 2 * block_size + 503;
1656*f4ee7fbaSAndroid Build Coastguard Worker       BROTLI_BOOL inplace = BROTLI_TRUE;
1657*f4ee7fbaSAndroid Build Coastguard Worker       uint8_t* storage = NULL;
1658*f4ee7fbaSAndroid Build Coastguard Worker       size_t storage_ix = s->last_bytes_bits_;
1659*f4ee7fbaSAndroid Build Coastguard Worker       size_t table_size;
1660*f4ee7fbaSAndroid Build Coastguard Worker       int* table;
1661*f4ee7fbaSAndroid Build Coastguard Worker 
1662*f4ee7fbaSAndroid Build Coastguard Worker       if (force_flush && block_size == 0) {
1663*f4ee7fbaSAndroid Build Coastguard Worker         s->stream_state_ = BROTLI_STREAM_FLUSH_REQUESTED;
1664*f4ee7fbaSAndroid Build Coastguard Worker         continue;
1665*f4ee7fbaSAndroid Build Coastguard Worker       }
1666*f4ee7fbaSAndroid Build Coastguard Worker       if (max_out_size <= *available_out) {
1667*f4ee7fbaSAndroid Build Coastguard Worker         storage = *next_out;
1668*f4ee7fbaSAndroid Build Coastguard Worker       } else {
1669*f4ee7fbaSAndroid Build Coastguard Worker         inplace = BROTLI_FALSE;
1670*f4ee7fbaSAndroid Build Coastguard Worker         storage = GetBrotliStorage(s, max_out_size);
1671*f4ee7fbaSAndroid Build Coastguard Worker         if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1672*f4ee7fbaSAndroid Build Coastguard Worker       }
1673*f4ee7fbaSAndroid Build Coastguard Worker       storage[0] = (uint8_t)s->last_bytes_;
1674*f4ee7fbaSAndroid Build Coastguard Worker       storage[1] = (uint8_t)(s->last_bytes_ >> 8);
1675*f4ee7fbaSAndroid Build Coastguard Worker       table = GetHashTable(s, s->params.quality, block_size, &table_size);
1676*f4ee7fbaSAndroid Build Coastguard Worker       if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1677*f4ee7fbaSAndroid Build Coastguard Worker 
1678*f4ee7fbaSAndroid Build Coastguard Worker       if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY) {
1679*f4ee7fbaSAndroid Build Coastguard Worker         BrotliCompressFragmentFast(m, *next_in, block_size, is_last, table,
1680*f4ee7fbaSAndroid Build Coastguard Worker             table_size, s->cmd_depths_, s->cmd_bits_, &s->cmd_code_numbits_,
1681*f4ee7fbaSAndroid Build Coastguard Worker             s->cmd_code_, &storage_ix, storage);
1682*f4ee7fbaSAndroid Build Coastguard Worker         if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1683*f4ee7fbaSAndroid Build Coastguard Worker       } else {
1684*f4ee7fbaSAndroid Build Coastguard Worker         BrotliCompressFragmentTwoPass(m, *next_in, block_size, is_last,
1685*f4ee7fbaSAndroid Build Coastguard Worker             command_buf, literal_buf, table, table_size,
1686*f4ee7fbaSAndroid Build Coastguard Worker             &storage_ix, storage);
1687*f4ee7fbaSAndroid Build Coastguard Worker         if (BROTLI_IS_OOM(m)) return BROTLI_FALSE;
1688*f4ee7fbaSAndroid Build Coastguard Worker       }
1689*f4ee7fbaSAndroid Build Coastguard Worker       if (block_size != 0) {
1690*f4ee7fbaSAndroid Build Coastguard Worker         *next_in += block_size;
1691*f4ee7fbaSAndroid Build Coastguard Worker         *available_in -= block_size;
1692*f4ee7fbaSAndroid Build Coastguard Worker       }
1693*f4ee7fbaSAndroid Build Coastguard Worker       if (inplace) {
1694*f4ee7fbaSAndroid Build Coastguard Worker         size_t out_bytes = storage_ix >> 3;
1695*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_DCHECK(out_bytes <= *available_out);
1696*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_DCHECK((storage_ix & 7) == 0 || out_bytes < *available_out);
1697*f4ee7fbaSAndroid Build Coastguard Worker         *next_out += out_bytes;
1698*f4ee7fbaSAndroid Build Coastguard Worker         *available_out -= out_bytes;
1699*f4ee7fbaSAndroid Build Coastguard Worker         s->total_out_ += out_bytes;
1700*f4ee7fbaSAndroid Build Coastguard Worker         if (total_out) *total_out = s->total_out_;
1701*f4ee7fbaSAndroid Build Coastguard Worker       } else {
1702*f4ee7fbaSAndroid Build Coastguard Worker         size_t out_bytes = storage_ix >> 3;
1703*f4ee7fbaSAndroid Build Coastguard Worker         s->next_out_ = storage;
1704*f4ee7fbaSAndroid Build Coastguard Worker         s->available_out_ = out_bytes;
1705*f4ee7fbaSAndroid Build Coastguard Worker       }
1706*f4ee7fbaSAndroid Build Coastguard Worker       s->last_bytes_ = (uint16_t)(storage[storage_ix >> 3]);
1707*f4ee7fbaSAndroid Build Coastguard Worker       s->last_bytes_bits_ = storage_ix & 7u;
1708*f4ee7fbaSAndroid Build Coastguard Worker 
1709*f4ee7fbaSAndroid Build Coastguard Worker       if (force_flush) s->stream_state_ = BROTLI_STREAM_FLUSH_REQUESTED;
1710*f4ee7fbaSAndroid Build Coastguard Worker       if (is_last) s->stream_state_ = BROTLI_STREAM_FINISHED;
1711*f4ee7fbaSAndroid Build Coastguard Worker       continue;
1712*f4ee7fbaSAndroid Build Coastguard Worker     }
1713*f4ee7fbaSAndroid Build Coastguard Worker     break;
1714*f4ee7fbaSAndroid Build Coastguard Worker   }
1715*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FREE(m, tmp_command_buf);
1716*f4ee7fbaSAndroid Build Coastguard Worker   BROTLI_FREE(m, tmp_literal_buf);
1717*f4ee7fbaSAndroid Build Coastguard Worker   CheckFlushComplete(s);
1718*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_TRUE;
1719*f4ee7fbaSAndroid Build Coastguard Worker }
1720*f4ee7fbaSAndroid Build Coastguard Worker 
ProcessMetadata(BrotliEncoderState * s,size_t * available_in,const uint8_t ** next_in,size_t * available_out,uint8_t ** next_out,size_t * total_out)1721*f4ee7fbaSAndroid Build Coastguard Worker static BROTLI_BOOL ProcessMetadata(
1722*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderState* s, size_t* available_in, const uint8_t** next_in,
1723*f4ee7fbaSAndroid Build Coastguard Worker     size_t* available_out, uint8_t** next_out, size_t* total_out) {
1724*f4ee7fbaSAndroid Build Coastguard Worker   if (*available_in > (1u << 24)) return BROTLI_FALSE;
1725*f4ee7fbaSAndroid Build Coastguard Worker   /* Switch to metadata block workflow, if required. */
1726*f4ee7fbaSAndroid Build Coastguard Worker   if (s->stream_state_ == BROTLI_STREAM_PROCESSING) {
1727*f4ee7fbaSAndroid Build Coastguard Worker     s->remaining_metadata_bytes_ = (uint32_t)*available_in;
1728*f4ee7fbaSAndroid Build Coastguard Worker     s->stream_state_ = BROTLI_STREAM_METADATA_HEAD;
1729*f4ee7fbaSAndroid Build Coastguard Worker   }
1730*f4ee7fbaSAndroid Build Coastguard Worker   if (s->stream_state_ != BROTLI_STREAM_METADATA_HEAD &&
1731*f4ee7fbaSAndroid Build Coastguard Worker       s->stream_state_ != BROTLI_STREAM_METADATA_BODY) {
1732*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_FALSE;
1733*f4ee7fbaSAndroid Build Coastguard Worker   }
1734*f4ee7fbaSAndroid Build Coastguard Worker 
1735*f4ee7fbaSAndroid Build Coastguard Worker   while (BROTLI_TRUE) {
1736*f4ee7fbaSAndroid Build Coastguard Worker     if (InjectFlushOrPushOutput(s, available_out, next_out, total_out)) {
1737*f4ee7fbaSAndroid Build Coastguard Worker       continue;
1738*f4ee7fbaSAndroid Build Coastguard Worker     }
1739*f4ee7fbaSAndroid Build Coastguard Worker     if (s->available_out_ != 0) break;
1740*f4ee7fbaSAndroid Build Coastguard Worker 
1741*f4ee7fbaSAndroid Build Coastguard Worker     if (s->input_pos_ != s->last_flush_pos_) {
1742*f4ee7fbaSAndroid Build Coastguard Worker       BROTLI_BOOL result = EncodeData(s, BROTLI_FALSE, BROTLI_TRUE,
1743*f4ee7fbaSAndroid Build Coastguard Worker           &s->available_out_, &s->next_out_);
1744*f4ee7fbaSAndroid Build Coastguard Worker       if (!result) return BROTLI_FALSE;
1745*f4ee7fbaSAndroid Build Coastguard Worker       continue;
1746*f4ee7fbaSAndroid Build Coastguard Worker     }
1747*f4ee7fbaSAndroid Build Coastguard Worker 
1748*f4ee7fbaSAndroid Build Coastguard Worker     if (s->stream_state_ == BROTLI_STREAM_METADATA_HEAD) {
1749*f4ee7fbaSAndroid Build Coastguard Worker       s->next_out_ = s->tiny_buf_.u8;
1750*f4ee7fbaSAndroid Build Coastguard Worker       s->available_out_ =
1751*f4ee7fbaSAndroid Build Coastguard Worker           WriteMetadataHeader(s, s->remaining_metadata_bytes_, s->next_out_);
1752*f4ee7fbaSAndroid Build Coastguard Worker       s->stream_state_ = BROTLI_STREAM_METADATA_BODY;
1753*f4ee7fbaSAndroid Build Coastguard Worker       continue;
1754*f4ee7fbaSAndroid Build Coastguard Worker     } else {
1755*f4ee7fbaSAndroid Build Coastguard Worker       /* Exit workflow only when there is no more input and no more output.
1756*f4ee7fbaSAndroid Build Coastguard Worker          Otherwise client may continue producing empty metadata blocks. */
1757*f4ee7fbaSAndroid Build Coastguard Worker       if (s->remaining_metadata_bytes_ == 0) {
1758*f4ee7fbaSAndroid Build Coastguard Worker         s->remaining_metadata_bytes_ = BROTLI_UINT32_MAX;
1759*f4ee7fbaSAndroid Build Coastguard Worker         s->stream_state_ = BROTLI_STREAM_PROCESSING;
1760*f4ee7fbaSAndroid Build Coastguard Worker         break;
1761*f4ee7fbaSAndroid Build Coastguard Worker       }
1762*f4ee7fbaSAndroid Build Coastguard Worker       if (*available_out) {
1763*f4ee7fbaSAndroid Build Coastguard Worker         /* Directly copy input to output. */
1764*f4ee7fbaSAndroid Build Coastguard Worker         uint32_t copy = (uint32_t)BROTLI_MIN(
1765*f4ee7fbaSAndroid Build Coastguard Worker             size_t, s->remaining_metadata_bytes_, *available_out);
1766*f4ee7fbaSAndroid Build Coastguard Worker         memcpy(*next_out, *next_in, copy);
1767*f4ee7fbaSAndroid Build Coastguard Worker         *next_in += copy;
1768*f4ee7fbaSAndroid Build Coastguard Worker         *available_in -= copy;
1769*f4ee7fbaSAndroid Build Coastguard Worker         s->remaining_metadata_bytes_ -= copy;
1770*f4ee7fbaSAndroid Build Coastguard Worker         *next_out += copy;
1771*f4ee7fbaSAndroid Build Coastguard Worker         *available_out -= copy;
1772*f4ee7fbaSAndroid Build Coastguard Worker       } else {
1773*f4ee7fbaSAndroid Build Coastguard Worker         /* This guarantees progress in "TakeOutput" workflow. */
1774*f4ee7fbaSAndroid Build Coastguard Worker         uint32_t copy = BROTLI_MIN(uint32_t, s->remaining_metadata_bytes_, 16);
1775*f4ee7fbaSAndroid Build Coastguard Worker         s->next_out_ = s->tiny_buf_.u8;
1776*f4ee7fbaSAndroid Build Coastguard Worker         memcpy(s->next_out_, *next_in, copy);
1777*f4ee7fbaSAndroid Build Coastguard Worker         *next_in += copy;
1778*f4ee7fbaSAndroid Build Coastguard Worker         *available_in -= copy;
1779*f4ee7fbaSAndroid Build Coastguard Worker         s->remaining_metadata_bytes_ -= copy;
1780*f4ee7fbaSAndroid Build Coastguard Worker         s->available_out_ = copy;
1781*f4ee7fbaSAndroid Build Coastguard Worker       }
1782*f4ee7fbaSAndroid Build Coastguard Worker       continue;
1783*f4ee7fbaSAndroid Build Coastguard Worker     }
1784*f4ee7fbaSAndroid Build Coastguard Worker   }
1785*f4ee7fbaSAndroid Build Coastguard Worker 
1786*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_TRUE;
1787*f4ee7fbaSAndroid Build Coastguard Worker }
1788*f4ee7fbaSAndroid Build Coastguard Worker 
UpdateSizeHint(BrotliEncoderState * s,size_t available_in)1789*f4ee7fbaSAndroid Build Coastguard Worker static void UpdateSizeHint(BrotliEncoderState* s, size_t available_in) {
1790*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.size_hint == 0) {
1791*f4ee7fbaSAndroid Build Coastguard Worker     uint64_t delta = UnprocessedInputSize(s);
1792*f4ee7fbaSAndroid Build Coastguard Worker     uint64_t tail = available_in;
1793*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t limit = 1u << 30;
1794*f4ee7fbaSAndroid Build Coastguard Worker     uint32_t total;
1795*f4ee7fbaSAndroid Build Coastguard Worker     if ((delta >= limit) || (tail >= limit) || ((delta + tail) >= limit)) {
1796*f4ee7fbaSAndroid Build Coastguard Worker       total = limit;
1797*f4ee7fbaSAndroid Build Coastguard Worker     } else {
1798*f4ee7fbaSAndroid Build Coastguard Worker       total = (uint32_t)(delta + tail);
1799*f4ee7fbaSAndroid Build Coastguard Worker     }
1800*f4ee7fbaSAndroid Build Coastguard Worker     s->params.size_hint = total;
1801*f4ee7fbaSAndroid Build Coastguard Worker   }
1802*f4ee7fbaSAndroid Build Coastguard Worker }
1803*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderCompressStream(BrotliEncoderState * s,BrotliEncoderOperation op,size_t * available_in,const uint8_t ** next_in,size_t * available_out,uint8_t ** next_out,size_t * total_out)1804*f4ee7fbaSAndroid Build Coastguard Worker BROTLI_BOOL BrotliEncoderCompressStream(
1805*f4ee7fbaSAndroid Build Coastguard Worker     BrotliEncoderState* s, BrotliEncoderOperation op, size_t* available_in,
1806*f4ee7fbaSAndroid Build Coastguard Worker     const uint8_t** next_in, size_t* available_out,uint8_t** next_out,
1807*f4ee7fbaSAndroid Build Coastguard Worker     size_t* total_out) {
1808*f4ee7fbaSAndroid Build Coastguard Worker   if (!EnsureInitialized(s)) return BROTLI_FALSE;
1809*f4ee7fbaSAndroid Build Coastguard Worker 
1810*f4ee7fbaSAndroid Build Coastguard Worker   /* Unfinished metadata block; check requirements. */
1811*f4ee7fbaSAndroid Build Coastguard Worker   if (s->remaining_metadata_bytes_ != BROTLI_UINT32_MAX) {
1812*f4ee7fbaSAndroid Build Coastguard Worker     if (*available_in != s->remaining_metadata_bytes_) return BROTLI_FALSE;
1813*f4ee7fbaSAndroid Build Coastguard Worker     if (op != BROTLI_OPERATION_EMIT_METADATA) return BROTLI_FALSE;
1814*f4ee7fbaSAndroid Build Coastguard Worker   }
1815*f4ee7fbaSAndroid Build Coastguard Worker 
1816*f4ee7fbaSAndroid Build Coastguard Worker   if (op == BROTLI_OPERATION_EMIT_METADATA) {
1817*f4ee7fbaSAndroid Build Coastguard Worker     UpdateSizeHint(s, 0);  /* First data metablock might be emitted here. */
1818*f4ee7fbaSAndroid Build Coastguard Worker     return ProcessMetadata(
1819*f4ee7fbaSAndroid Build Coastguard Worker         s, available_in, next_in, available_out, next_out, total_out);
1820*f4ee7fbaSAndroid Build Coastguard Worker   }
1821*f4ee7fbaSAndroid Build Coastguard Worker 
1822*f4ee7fbaSAndroid Build Coastguard Worker   if (s->stream_state_ == BROTLI_STREAM_METADATA_HEAD ||
1823*f4ee7fbaSAndroid Build Coastguard Worker       s->stream_state_ == BROTLI_STREAM_METADATA_BODY) {
1824*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_FALSE;
1825*f4ee7fbaSAndroid Build Coastguard Worker   }
1826*f4ee7fbaSAndroid Build Coastguard Worker 
1827*f4ee7fbaSAndroid Build Coastguard Worker   if (s->stream_state_ != BROTLI_STREAM_PROCESSING && *available_in != 0) {
1828*f4ee7fbaSAndroid Build Coastguard Worker     return BROTLI_FALSE;
1829*f4ee7fbaSAndroid Build Coastguard Worker   }
1830*f4ee7fbaSAndroid Build Coastguard Worker   if (s->params.quality == FAST_ONE_PASS_COMPRESSION_QUALITY ||
1831*f4ee7fbaSAndroid Build Coastguard Worker       s->params.quality == FAST_TWO_PASS_COMPRESSION_QUALITY) {
1832*f4ee7fbaSAndroid Build Coastguard Worker     return BrotliEncoderCompressStreamFast(s, op, available_in, next_in,
1833*f4ee7fbaSAndroid Build Coastguard Worker         available_out, next_out, total_out);
1834*f4ee7fbaSAndroid Build Coastguard Worker   }
1835*f4ee7fbaSAndroid Build Coastguard Worker   while (BROTLI_TRUE) {
1836*f4ee7fbaSAndroid Build Coastguard Worker     size_t remaining_block_size = RemainingInputBlockSize(s);
1837*f4ee7fbaSAndroid Build Coastguard Worker     /* Shorten input to flint size. */
1838*f4ee7fbaSAndroid Build Coastguard Worker     if (s->flint_ >= 0 && remaining_block_size > (size_t)s->flint_) {
1839*f4ee7fbaSAndroid Build Coastguard Worker       remaining_block_size = (size_t)s->flint_;
1840*f4ee7fbaSAndroid Build Coastguard Worker     }
1841*f4ee7fbaSAndroid Build Coastguard Worker 
1842*f4ee7fbaSAndroid Build Coastguard Worker     if (remaining_block_size != 0 && *available_in != 0) {
1843*f4ee7fbaSAndroid Build Coastguard Worker       size_t copy_input_size =
1844*f4ee7fbaSAndroid Build Coastguard Worker           BROTLI_MIN(size_t, remaining_block_size, *available_in);
1845*f4ee7fbaSAndroid Build Coastguard Worker       CopyInputToRingBuffer(s, copy_input_size, *next_in);
1846*f4ee7fbaSAndroid Build Coastguard Worker       *next_in += copy_input_size;
1847*f4ee7fbaSAndroid Build Coastguard Worker       *available_in -= copy_input_size;
1848*f4ee7fbaSAndroid Build Coastguard Worker       if (s->flint_ > 0) s->flint_ = (int8_t)(s->flint_ - (int)copy_input_size);
1849*f4ee7fbaSAndroid Build Coastguard Worker       continue;
1850*f4ee7fbaSAndroid Build Coastguard Worker     }
1851*f4ee7fbaSAndroid Build Coastguard Worker 
1852*f4ee7fbaSAndroid Build Coastguard Worker     if (InjectFlushOrPushOutput(s, available_out, next_out, total_out)) {
1853*f4ee7fbaSAndroid Build Coastguard Worker       /* Exit the "emit flint" workflow. */
1854*f4ee7fbaSAndroid Build Coastguard Worker       if (s->flint_ == BROTLI_FLINT_WAITING_FOR_FLUSHING) {
1855*f4ee7fbaSAndroid Build Coastguard Worker         CheckFlushComplete(s);
1856*f4ee7fbaSAndroid Build Coastguard Worker         if (s->stream_state_ == BROTLI_STREAM_PROCESSING) {
1857*f4ee7fbaSAndroid Build Coastguard Worker           s->flint_ = BROTLI_FLINT_DONE;
1858*f4ee7fbaSAndroid Build Coastguard Worker         }
1859*f4ee7fbaSAndroid Build Coastguard Worker       }
1860*f4ee7fbaSAndroid Build Coastguard Worker       continue;
1861*f4ee7fbaSAndroid Build Coastguard Worker     }
1862*f4ee7fbaSAndroid Build Coastguard Worker 
1863*f4ee7fbaSAndroid Build Coastguard Worker     /* Compress data only when internal output buffer is empty, stream is not
1864*f4ee7fbaSAndroid Build Coastguard Worker        finished and there is no pending flush request. */
1865*f4ee7fbaSAndroid Build Coastguard Worker     if (s->available_out_ == 0 &&
1866*f4ee7fbaSAndroid Build Coastguard Worker         s->stream_state_ == BROTLI_STREAM_PROCESSING) {
1867*f4ee7fbaSAndroid Build Coastguard Worker       if (remaining_block_size == 0 || op != BROTLI_OPERATION_PROCESS) {
1868*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_BOOL is_last = TO_BROTLI_BOOL(
1869*f4ee7fbaSAndroid Build Coastguard Worker             (*available_in == 0) && op == BROTLI_OPERATION_FINISH);
1870*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_BOOL force_flush = TO_BROTLI_BOOL(
1871*f4ee7fbaSAndroid Build Coastguard Worker             (*available_in == 0) && op == BROTLI_OPERATION_FLUSH);
1872*f4ee7fbaSAndroid Build Coastguard Worker         BROTLI_BOOL result;
1873*f4ee7fbaSAndroid Build Coastguard Worker         /* Force emitting (uncompressed) piece containing flint. */
1874*f4ee7fbaSAndroid Build Coastguard Worker         if (!is_last && s->flint_ == 0) {
1875*f4ee7fbaSAndroid Build Coastguard Worker           s->flint_ = BROTLI_FLINT_WAITING_FOR_FLUSHING;
1876*f4ee7fbaSAndroid Build Coastguard Worker           force_flush = BROTLI_TRUE;
1877*f4ee7fbaSAndroid Build Coastguard Worker         }
1878*f4ee7fbaSAndroid Build Coastguard Worker         UpdateSizeHint(s, *available_in);
1879*f4ee7fbaSAndroid Build Coastguard Worker         result = EncodeData(s, is_last, force_flush,
1880*f4ee7fbaSAndroid Build Coastguard Worker             &s->available_out_, &s->next_out_);
1881*f4ee7fbaSAndroid Build Coastguard Worker         if (!result) return BROTLI_FALSE;
1882*f4ee7fbaSAndroid Build Coastguard Worker         if (force_flush) s->stream_state_ = BROTLI_STREAM_FLUSH_REQUESTED;
1883*f4ee7fbaSAndroid Build Coastguard Worker         if (is_last) s->stream_state_ = BROTLI_STREAM_FINISHED;
1884*f4ee7fbaSAndroid Build Coastguard Worker         continue;
1885*f4ee7fbaSAndroid Build Coastguard Worker       }
1886*f4ee7fbaSAndroid Build Coastguard Worker     }
1887*f4ee7fbaSAndroid Build Coastguard Worker     break;
1888*f4ee7fbaSAndroid Build Coastguard Worker   }
1889*f4ee7fbaSAndroid Build Coastguard Worker   CheckFlushComplete(s);
1890*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_TRUE;
1891*f4ee7fbaSAndroid Build Coastguard Worker }
1892*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderIsFinished(BrotliEncoderState * s)1893*f4ee7fbaSAndroid Build Coastguard Worker BROTLI_BOOL BrotliEncoderIsFinished(BrotliEncoderState* s) {
1894*f4ee7fbaSAndroid Build Coastguard Worker   return TO_BROTLI_BOOL(s->stream_state_ == BROTLI_STREAM_FINISHED &&
1895*f4ee7fbaSAndroid Build Coastguard Worker       !BrotliEncoderHasMoreOutput(s));
1896*f4ee7fbaSAndroid Build Coastguard Worker }
1897*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderHasMoreOutput(BrotliEncoderState * s)1898*f4ee7fbaSAndroid Build Coastguard Worker BROTLI_BOOL BrotliEncoderHasMoreOutput(BrotliEncoderState* s) {
1899*f4ee7fbaSAndroid Build Coastguard Worker   return TO_BROTLI_BOOL(s->available_out_ != 0);
1900*f4ee7fbaSAndroid Build Coastguard Worker }
1901*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderTakeOutput(BrotliEncoderState * s,size_t * size)1902*f4ee7fbaSAndroid Build Coastguard Worker const uint8_t* BrotliEncoderTakeOutput(BrotliEncoderState* s, size_t* size) {
1903*f4ee7fbaSAndroid Build Coastguard Worker   size_t consumed_size = s->available_out_;
1904*f4ee7fbaSAndroid Build Coastguard Worker   uint8_t* result = s->next_out_;
1905*f4ee7fbaSAndroid Build Coastguard Worker   if (*size) {
1906*f4ee7fbaSAndroid Build Coastguard Worker     consumed_size = BROTLI_MIN(size_t, *size, s->available_out_);
1907*f4ee7fbaSAndroid Build Coastguard Worker   }
1908*f4ee7fbaSAndroid Build Coastguard Worker   if (consumed_size) {
1909*f4ee7fbaSAndroid Build Coastguard Worker     s->next_out_ += consumed_size;
1910*f4ee7fbaSAndroid Build Coastguard Worker     s->available_out_ -= consumed_size;
1911*f4ee7fbaSAndroid Build Coastguard Worker     s->total_out_ += consumed_size;
1912*f4ee7fbaSAndroid Build Coastguard Worker     CheckFlushComplete(s);
1913*f4ee7fbaSAndroid Build Coastguard Worker     *size = consumed_size;
1914*f4ee7fbaSAndroid Build Coastguard Worker   } else {
1915*f4ee7fbaSAndroid Build Coastguard Worker     *size = 0;
1916*f4ee7fbaSAndroid Build Coastguard Worker     result = 0;
1917*f4ee7fbaSAndroid Build Coastguard Worker   }
1918*f4ee7fbaSAndroid Build Coastguard Worker   return result;
1919*f4ee7fbaSAndroid Build Coastguard Worker }
1920*f4ee7fbaSAndroid Build Coastguard Worker 
BrotliEncoderVersion(void)1921*f4ee7fbaSAndroid Build Coastguard Worker uint32_t BrotliEncoderVersion(void) {
1922*f4ee7fbaSAndroid Build Coastguard Worker   return BROTLI_VERSION;
1923*f4ee7fbaSAndroid Build Coastguard Worker }
1924*f4ee7fbaSAndroid Build Coastguard Worker 
1925*f4ee7fbaSAndroid Build Coastguard Worker #if defined(__cplusplus) || defined(c_plusplus)
1926*f4ee7fbaSAndroid Build Coastguard Worker }  /* extern "C" */
1927*f4ee7fbaSAndroid Build Coastguard Worker #endif
1928