encode.c 70 KB

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