compress_fragment.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. /* Copyright 2015 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. /* Function for fast encoding of an input fragment, independently from the input
  6. history. This function uses one-pass processing: when we find a backward
  7. match, we immediately emit the corresponding command and literal codes to
  8. the bit stream.
  9. Adapted from the CompressFragment() function in
  10. https://github.com/google/snappy/blob/master/snappy.cc */
  11. #include "./compress_fragment.h"
  12. #include <string.h> /* memcmp, memcpy, memset */
  13. #include "../common/constants.h"
  14. #include "../common/platform.h"
  15. #include <brotli/types.h>
  16. #include "./brotli_bit_stream.h"
  17. #include "./entropy_encode.h"
  18. #include "./fast_log.h"
  19. #include "./find_match_length.h"
  20. #include "./memory.h"
  21. #include "./write_bits.h"
  22. #if defined(__cplusplus) || defined(c_plusplus)
  23. extern "C" {
  24. #endif
  25. #define MAX_DISTANCE (long)BROTLI_MAX_BACKWARD_LIMIT(18)
  26. /* kHashMul32 multiplier has these properties:
  27. * The multiplier must be odd. Otherwise we may lose the highest bit.
  28. * No long streaks of ones or zeros.
  29. * There is no effort to ensure that it is a prime, the oddity is enough
  30. for this use.
  31. * The number has been tuned heuristically against compression benchmarks. */
  32. static const uint32_t kHashMul32 = 0x1E35A7BD;
  33. static BROTLI_INLINE uint32_t Hash(const uint8_t* p, size_t shift) {
  34. const uint64_t h = (BROTLI_UNALIGNED_LOAD64LE(p) << 24) * kHashMul32;
  35. return (uint32_t)(h >> shift);
  36. }
  37. static BROTLI_INLINE uint32_t HashBytesAtOffset(
  38. uint64_t v, int offset, size_t shift) {
  39. BROTLI_DCHECK(offset >= 0);
  40. BROTLI_DCHECK(offset <= 3);
  41. {
  42. const uint64_t h = ((v >> (8 * offset)) << 24) * kHashMul32;
  43. return (uint32_t)(h >> shift);
  44. }
  45. }
  46. static BROTLI_INLINE BROTLI_BOOL IsMatch(const uint8_t* p1, const uint8_t* p2) {
  47. return TO_BROTLI_BOOL(
  48. BrotliUnalignedRead32(p1) == BrotliUnalignedRead32(p2) &&
  49. p1[4] == p2[4]);
  50. }
  51. /* Builds a literal prefix code into "depths" and "bits" based on the statistics
  52. of the "input" string and stores it into the bit stream.
  53. Note that the prefix code here is built from the pre-LZ77 input, therefore
  54. we can only approximate the statistics of the actual literal stream.
  55. Moreover, for long inputs we build a histogram from a sample of the input
  56. and thus have to assign a non-zero depth for each literal.
  57. Returns estimated compression ratio millibytes/char for encoding given input
  58. with generated code. */
  59. static size_t BuildAndStoreLiteralPrefixCode(MemoryManager* m,
  60. const uint8_t* input,
  61. const size_t input_size,
  62. uint8_t depths[256],
  63. uint16_t bits[256],
  64. size_t* storage_ix,
  65. uint8_t* storage) {
  66. uint32_t histogram[256] = { 0 };
  67. size_t histogram_total;
  68. size_t i;
  69. if (input_size < (1 << 15)) {
  70. for (i = 0; i < input_size; ++i) {
  71. ++histogram[input[i]];
  72. }
  73. histogram_total = input_size;
  74. for (i = 0; i < 256; ++i) {
  75. /* We weigh the first 11 samples with weight 3 to account for the
  76. balancing effect of the LZ77 phase on the histogram. */
  77. const uint32_t adjust = 2 * BROTLI_MIN(uint32_t, histogram[i], 11u);
  78. histogram[i] += adjust;
  79. histogram_total += adjust;
  80. }
  81. } else {
  82. static const size_t kSampleRate = 29;
  83. for (i = 0; i < input_size; i += kSampleRate) {
  84. ++histogram[input[i]];
  85. }
  86. histogram_total = (input_size + kSampleRate - 1) / kSampleRate;
  87. for (i = 0; i < 256; ++i) {
  88. /* We add 1 to each population count to avoid 0 bit depths (since this is
  89. only a sample and we don't know if the symbol appears or not), and we
  90. weigh the first 11 samples with weight 3 to account for the balancing
  91. effect of the LZ77 phase on the histogram (more frequent symbols are
  92. more likely to be in backward references instead as literals). */
  93. const uint32_t adjust = 1 + 2 * BROTLI_MIN(uint32_t, histogram[i], 11u);
  94. histogram[i] += adjust;
  95. histogram_total += adjust;
  96. }
  97. }
  98. BrotliBuildAndStoreHuffmanTreeFast(m, histogram, histogram_total,
  99. /* max_bits = */ 8,
  100. depths, bits, storage_ix, storage);
  101. if (BROTLI_IS_OOM(m)) return 0;
  102. {
  103. size_t literal_ratio = 0;
  104. for (i = 0; i < 256; ++i) {
  105. if (histogram[i]) literal_ratio += histogram[i] * depths[i];
  106. }
  107. /* Estimated encoding ratio, millibytes per symbol. */
  108. return (literal_ratio * 125) / histogram_total;
  109. }
  110. }
  111. /* Builds a command and distance prefix code (each 64 symbols) into "depth" and
  112. "bits" based on "histogram" and stores it into the bit stream. */
  113. static void BuildAndStoreCommandPrefixCode(const uint32_t histogram[128],
  114. uint8_t depth[128], uint16_t bits[128], size_t* storage_ix,
  115. uint8_t* storage) {
  116. /* Tree size for building a tree over 64 symbols is 2 * 64 + 1. */
  117. HuffmanTree tree[129];
  118. uint8_t cmd_depth[BROTLI_NUM_COMMAND_SYMBOLS] = { 0 };
  119. uint16_t cmd_bits[64];
  120. BrotliCreateHuffmanTree(histogram, 64, 15, tree, depth);
  121. BrotliCreateHuffmanTree(&histogram[64], 64, 14, tree, &depth[64]);
  122. /* We have to jump through a few hoops here in order to compute
  123. the command bits because the symbols are in a different order than in
  124. the full alphabet. This looks complicated, but having the symbols
  125. in this order in the command bits saves a few branches in the Emit*
  126. functions. */
  127. memcpy(cmd_depth, depth, 24);
  128. memcpy(cmd_depth + 24, depth + 40, 8);
  129. memcpy(cmd_depth + 32, depth + 24, 8);
  130. memcpy(cmd_depth + 40, depth + 48, 8);
  131. memcpy(cmd_depth + 48, depth + 32, 8);
  132. memcpy(cmd_depth + 56, depth + 56, 8);
  133. BrotliConvertBitDepthsToSymbols(cmd_depth, 64, cmd_bits);
  134. memcpy(bits, cmd_bits, 48);
  135. memcpy(bits + 24, cmd_bits + 32, 16);
  136. memcpy(bits + 32, cmd_bits + 48, 16);
  137. memcpy(bits + 40, cmd_bits + 24, 16);
  138. memcpy(bits + 48, cmd_bits + 40, 16);
  139. memcpy(bits + 56, cmd_bits + 56, 16);
  140. BrotliConvertBitDepthsToSymbols(&depth[64], 64, &bits[64]);
  141. {
  142. /* Create the bit length array for the full command alphabet. */
  143. size_t i;
  144. memset(cmd_depth, 0, 64); /* only 64 first values were used */
  145. memcpy(cmd_depth, depth, 8);
  146. memcpy(cmd_depth + 64, depth + 8, 8);
  147. memcpy(cmd_depth + 128, depth + 16, 8);
  148. memcpy(cmd_depth + 192, depth + 24, 8);
  149. memcpy(cmd_depth + 384, depth + 32, 8);
  150. for (i = 0; i < 8; ++i) {
  151. cmd_depth[128 + 8 * i] = depth[40 + i];
  152. cmd_depth[256 + 8 * i] = depth[48 + i];
  153. cmd_depth[448 + 8 * i] = depth[56 + i];
  154. }
  155. BrotliStoreHuffmanTree(
  156. cmd_depth, BROTLI_NUM_COMMAND_SYMBOLS, tree, storage_ix, storage);
  157. }
  158. BrotliStoreHuffmanTree(&depth[64], 64, tree, storage_ix, storage);
  159. }
  160. /* REQUIRES: insertlen < 6210 */
  161. static BROTLI_INLINE void EmitInsertLen(size_t insertlen,
  162. const uint8_t depth[128],
  163. const uint16_t bits[128],
  164. uint32_t histo[128],
  165. size_t* storage_ix,
  166. uint8_t* storage) {
  167. if (insertlen < 6) {
  168. const size_t code = insertlen + 40;
  169. BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
  170. ++histo[code];
  171. } else if (insertlen < 130) {
  172. const size_t tail = insertlen - 2;
  173. const uint32_t nbits = Log2FloorNonZero(tail) - 1u;
  174. const size_t prefix = tail >> nbits;
  175. const size_t inscode = (nbits << 1) + prefix + 42;
  176. BrotliWriteBits(depth[inscode], bits[inscode], storage_ix, storage);
  177. BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
  178. ++histo[inscode];
  179. } else if (insertlen < 2114) {
  180. const size_t tail = insertlen - 66;
  181. const uint32_t nbits = Log2FloorNonZero(tail);
  182. const size_t code = nbits + 50;
  183. BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
  184. BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
  185. ++histo[code];
  186. } else {
  187. BrotliWriteBits(depth[61], bits[61], storage_ix, storage);
  188. BrotliWriteBits(12, insertlen - 2114, storage_ix, storage);
  189. ++histo[61];
  190. }
  191. }
  192. static BROTLI_INLINE void EmitLongInsertLen(size_t insertlen,
  193. const uint8_t depth[128],
  194. const uint16_t bits[128],
  195. uint32_t histo[128],
  196. size_t* storage_ix,
  197. uint8_t* storage) {
  198. if (insertlen < 22594) {
  199. BrotliWriteBits(depth[62], bits[62], storage_ix, storage);
  200. BrotliWriteBits(14, insertlen - 6210, storage_ix, storage);
  201. ++histo[62];
  202. } else {
  203. BrotliWriteBits(depth[63], bits[63], storage_ix, storage);
  204. BrotliWriteBits(24, insertlen - 22594, storage_ix, storage);
  205. ++histo[63];
  206. }
  207. }
  208. static BROTLI_INLINE void EmitCopyLen(size_t copylen,
  209. const uint8_t depth[128],
  210. const uint16_t bits[128],
  211. uint32_t histo[128],
  212. size_t* storage_ix,
  213. uint8_t* storage) {
  214. if (copylen < 10) {
  215. BrotliWriteBits(
  216. depth[copylen + 14], bits[copylen + 14], storage_ix, storage);
  217. ++histo[copylen + 14];
  218. } else if (copylen < 134) {
  219. const size_t tail = copylen - 6;
  220. const uint32_t nbits = Log2FloorNonZero(tail) - 1u;
  221. const size_t prefix = tail >> nbits;
  222. const size_t code = (nbits << 1) + prefix + 20;
  223. BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
  224. BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
  225. ++histo[code];
  226. } else if (copylen < 2118) {
  227. const size_t tail = copylen - 70;
  228. const uint32_t nbits = Log2FloorNonZero(tail);
  229. const size_t code = nbits + 28;
  230. BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
  231. BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
  232. ++histo[code];
  233. } else {
  234. BrotliWriteBits(depth[39], bits[39], storage_ix, storage);
  235. BrotliWriteBits(24, copylen - 2118, storage_ix, storage);
  236. ++histo[39];
  237. }
  238. }
  239. static BROTLI_INLINE void EmitCopyLenLastDistance(size_t copylen,
  240. const uint8_t depth[128],
  241. const uint16_t bits[128],
  242. uint32_t histo[128],
  243. size_t* storage_ix,
  244. uint8_t* storage) {
  245. if (copylen < 12) {
  246. BrotliWriteBits(depth[copylen - 4], bits[copylen - 4], storage_ix, storage);
  247. ++histo[copylen - 4];
  248. } else if (copylen < 72) {
  249. const size_t tail = copylen - 8;
  250. const uint32_t nbits = Log2FloorNonZero(tail) - 1;
  251. const size_t prefix = tail >> nbits;
  252. const size_t code = (nbits << 1) + prefix + 4;
  253. BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
  254. BrotliWriteBits(nbits, tail - (prefix << nbits), storage_ix, storage);
  255. ++histo[code];
  256. } else if (copylen < 136) {
  257. const size_t tail = copylen - 8;
  258. const size_t code = (tail >> 5) + 30;
  259. BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
  260. BrotliWriteBits(5, tail & 31, storage_ix, storage);
  261. BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
  262. ++histo[code];
  263. ++histo[64];
  264. } else if (copylen < 2120) {
  265. const size_t tail = copylen - 72;
  266. const uint32_t nbits = Log2FloorNonZero(tail);
  267. const size_t code = nbits + 28;
  268. BrotliWriteBits(depth[code], bits[code], storage_ix, storage);
  269. BrotliWriteBits(nbits, tail - ((size_t)1 << nbits), storage_ix, storage);
  270. BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
  271. ++histo[code];
  272. ++histo[64];
  273. } else {
  274. BrotliWriteBits(depth[39], bits[39], storage_ix, storage);
  275. BrotliWriteBits(24, copylen - 2120, storage_ix, storage);
  276. BrotliWriteBits(depth[64], bits[64], storage_ix, storage);
  277. ++histo[39];
  278. ++histo[64];
  279. }
  280. }
  281. static BROTLI_INLINE void EmitDistance(size_t distance,
  282. const uint8_t depth[128],
  283. const uint16_t bits[128],
  284. uint32_t histo[128],
  285. size_t* storage_ix, uint8_t* storage) {
  286. const size_t d = distance + 3;
  287. const uint32_t nbits = Log2FloorNonZero(d) - 1u;
  288. const size_t prefix = (d >> nbits) & 1;
  289. const size_t offset = (2 + prefix) << nbits;
  290. const size_t distcode = 2 * (nbits - 1) + prefix + 80;
  291. BrotliWriteBits(depth[distcode], bits[distcode], storage_ix, storage);
  292. BrotliWriteBits(nbits, d - offset, storage_ix, storage);
  293. ++histo[distcode];
  294. }
  295. static BROTLI_INLINE void EmitLiterals(const uint8_t* input, const size_t len,
  296. const uint8_t depth[256],
  297. const uint16_t bits[256],
  298. size_t* storage_ix, uint8_t* storage) {
  299. size_t j;
  300. for (j = 0; j < len; j++) {
  301. const uint8_t lit = input[j];
  302. BrotliWriteBits(depth[lit], bits[lit], storage_ix, storage);
  303. }
  304. }
  305. /* REQUIRES: len <= 1 << 24. */
  306. static void BrotliStoreMetaBlockHeader(
  307. size_t len, BROTLI_BOOL is_uncompressed, size_t* storage_ix,
  308. uint8_t* storage) {
  309. size_t nibbles = 6;
  310. /* ISLAST */
  311. BrotliWriteBits(1, 0, storage_ix, storage);
  312. if (len <= (1U << 16)) {
  313. nibbles = 4;
  314. } else if (len <= (1U << 20)) {
  315. nibbles = 5;
  316. }
  317. BrotliWriteBits(2, nibbles - 4, storage_ix, storage);
  318. BrotliWriteBits(nibbles * 4, len - 1, storage_ix, storage);
  319. /* ISUNCOMPRESSED */
  320. BrotliWriteBits(1, (uint64_t)is_uncompressed, storage_ix, storage);
  321. }
  322. static void UpdateBits(size_t n_bits, uint32_t bits, size_t pos,
  323. uint8_t* array) {
  324. while (n_bits > 0) {
  325. size_t byte_pos = pos >> 3;
  326. size_t n_unchanged_bits = pos & 7;
  327. size_t n_changed_bits = BROTLI_MIN(size_t, n_bits, 8 - n_unchanged_bits);
  328. size_t total_bits = n_unchanged_bits + n_changed_bits;
  329. uint32_t mask =
  330. (~((1u << total_bits) - 1u)) | ((1u << n_unchanged_bits) - 1u);
  331. uint32_t unchanged_bits = array[byte_pos] & mask;
  332. uint32_t changed_bits = bits & ((1u << n_changed_bits) - 1u);
  333. array[byte_pos] =
  334. (uint8_t)((changed_bits << n_unchanged_bits) | unchanged_bits);
  335. n_bits -= n_changed_bits;
  336. bits >>= n_changed_bits;
  337. pos += n_changed_bits;
  338. }
  339. }
  340. static void RewindBitPosition(const size_t new_storage_ix,
  341. size_t* storage_ix, uint8_t* storage) {
  342. const size_t bitpos = new_storage_ix & 7;
  343. const size_t mask = (1u << bitpos) - 1;
  344. storage[new_storage_ix >> 3] &= (uint8_t)mask;
  345. *storage_ix = new_storage_ix;
  346. }
  347. static BROTLI_BOOL ShouldMergeBlock(
  348. const uint8_t* data, size_t len, const uint8_t* depths) {
  349. size_t histo[256] = { 0 };
  350. static const size_t kSampleRate = 43;
  351. size_t i;
  352. for (i = 0; i < len; i += kSampleRate) {
  353. ++histo[data[i]];
  354. }
  355. {
  356. const size_t total = (len + kSampleRate - 1) / kSampleRate;
  357. double r = (FastLog2(total) + 0.5) * (double)total + 200;
  358. for (i = 0; i < 256; ++i) {
  359. r -= (double)histo[i] * (depths[i] + FastLog2(histo[i]));
  360. }
  361. return TO_BROTLI_BOOL(r >= 0.0);
  362. }
  363. }
  364. /* Acceptable loss for uncompressible speedup is 2% */
  365. #define MIN_RATIO 980
  366. static BROTLI_INLINE BROTLI_BOOL ShouldUseUncompressedMode(
  367. const uint8_t* metablock_start, const uint8_t* next_emit,
  368. const size_t insertlen, const size_t literal_ratio) {
  369. const size_t compressed = (size_t)(next_emit - metablock_start);
  370. if (compressed * 50 > insertlen) {
  371. return BROTLI_FALSE;
  372. } else {
  373. return TO_BROTLI_BOOL(literal_ratio > MIN_RATIO);
  374. }
  375. }
  376. static void EmitUncompressedMetaBlock(const uint8_t* begin, const uint8_t* end,
  377. const size_t storage_ix_start,
  378. size_t* storage_ix, uint8_t* storage) {
  379. const size_t len = (size_t)(end - begin);
  380. RewindBitPosition(storage_ix_start, storage_ix, storage);
  381. BrotliStoreMetaBlockHeader(len, 1, storage_ix, storage);
  382. *storage_ix = (*storage_ix + 7u) & ~7u;
  383. memcpy(&storage[*storage_ix >> 3], begin, len);
  384. *storage_ix += len << 3;
  385. storage[*storage_ix >> 3] = 0;
  386. }
  387. static uint32_t kCmdHistoSeed[128] = {
  388. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  389. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
  390. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
  391. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  392. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  393. 1, 1, 1, 1, 0, 0, 0, 0,
  394. };
  395. static BROTLI_INLINE void BrotliCompressFragmentFastImpl(
  396. MemoryManager* m, const uint8_t* input, size_t input_size,
  397. BROTLI_BOOL is_last, int* table, size_t table_bits, uint8_t cmd_depth[128],
  398. uint16_t cmd_bits[128], size_t* cmd_code_numbits, uint8_t* cmd_code,
  399. size_t* storage_ix, uint8_t* storage) {
  400. uint32_t cmd_histo[128];
  401. const uint8_t* ip_end;
  402. /* "next_emit" is a pointer to the first byte that is not covered by a
  403. previous copy. Bytes between "next_emit" and the start of the next copy or
  404. the end of the input will be emitted as literal bytes. */
  405. const uint8_t* next_emit = input;
  406. /* Save the start of the first block for position and distance computations.
  407. */
  408. const uint8_t* base_ip = input;
  409. static const size_t kFirstBlockSize = 3 << 15;
  410. static const size_t kMergeBlockSize = 1 << 16;
  411. const size_t kInputMarginBytes = BROTLI_WINDOW_GAP;
  412. const size_t kMinMatchLen = 5;
  413. const uint8_t* metablock_start = input;
  414. size_t block_size = BROTLI_MIN(size_t, input_size, kFirstBlockSize);
  415. size_t total_block_size = block_size;
  416. /* Save the bit position of the MLEN field of the meta-block header, so that
  417. we can update it later if we decide to extend this meta-block. */
  418. size_t mlen_storage_ix = *storage_ix + 3;
  419. uint8_t lit_depth[256];
  420. uint16_t lit_bits[256];
  421. size_t literal_ratio;
  422. const uint8_t* ip;
  423. int last_distance;
  424. const size_t shift = 64u - table_bits;
  425. BrotliStoreMetaBlockHeader(block_size, 0, storage_ix, storage);
  426. /* No block splits, no contexts. */
  427. BrotliWriteBits(13, 0, storage_ix, storage);
  428. literal_ratio = BuildAndStoreLiteralPrefixCode(
  429. m, input, block_size, lit_depth, lit_bits, storage_ix, storage);
  430. if (BROTLI_IS_OOM(m)) return;
  431. {
  432. /* Store the pre-compressed command and distance prefix codes. */
  433. size_t i;
  434. for (i = 0; i + 7 < *cmd_code_numbits; i += 8) {
  435. BrotliWriteBits(8, cmd_code[i >> 3], storage_ix, storage);
  436. }
  437. }
  438. BrotliWriteBits(*cmd_code_numbits & 7, cmd_code[*cmd_code_numbits >> 3],
  439. storage_ix, storage);
  440. emit_commands:
  441. /* Initialize the command and distance histograms. We will gather
  442. statistics of command and distance codes during the processing
  443. of this block and use it to update the command and distance
  444. prefix codes for the next block. */
  445. memcpy(cmd_histo, kCmdHistoSeed, sizeof(kCmdHistoSeed));
  446. /* "ip" is the input pointer. */
  447. ip = input;
  448. last_distance = -1;
  449. ip_end = input + block_size;
  450. if (BROTLI_PREDICT_TRUE(block_size >= kInputMarginBytes)) {
  451. /* For the last block, we need to keep a 16 bytes margin so that we can be
  452. sure that all distances are at most window size - 16.
  453. For all other blocks, we only need to keep a margin of 5 bytes so that
  454. we don't go over the block size with a copy. */
  455. const size_t len_limit = BROTLI_MIN(size_t, block_size - kMinMatchLen,
  456. input_size - kInputMarginBytes);
  457. const uint8_t* ip_limit = input + len_limit;
  458. uint32_t next_hash;
  459. for (next_hash = Hash(++ip, shift); ; ) {
  460. /* Step 1: Scan forward in the input looking for a 5-byte-long match.
  461. If we get close to exhausting the input then goto emit_remainder.
  462. Heuristic match skipping: If 32 bytes are scanned with no matches
  463. found, start looking only at every other byte. If 32 more bytes are
  464. scanned, look at every third byte, etc.. When a match is found,
  465. immediately go back to looking at every byte. This is a small loss
  466. (~5% performance, ~0.1% density) for compressible data due to more
  467. bookkeeping, but for non-compressible data (such as JPEG) it's a huge
  468. win since the compressor quickly "realizes" the data is incompressible
  469. and doesn't bother looking for matches everywhere.
  470. The "skip" variable keeps track of how many bytes there are since the
  471. last match; dividing it by 32 (i.e. right-shifting by five) gives the
  472. number of bytes to move ahead for each iteration. */
  473. uint32_t skip = 32;
  474. const uint8_t* next_ip = ip;
  475. const uint8_t* candidate;
  476. BROTLI_DCHECK(next_emit < ip);
  477. trawl:
  478. do {
  479. uint32_t hash = next_hash;
  480. uint32_t bytes_between_hash_lookups = skip++ >> 5;
  481. BROTLI_DCHECK(hash == Hash(next_ip, shift));
  482. ip = next_ip;
  483. next_ip = ip + bytes_between_hash_lookups;
  484. if (BROTLI_PREDICT_FALSE(next_ip > ip_limit)) {
  485. goto emit_remainder;
  486. }
  487. next_hash = Hash(next_ip, shift);
  488. candidate = ip - last_distance;
  489. if (IsMatch(ip, candidate)) {
  490. if (BROTLI_PREDICT_TRUE(candidate < ip)) {
  491. table[hash] = (int)(ip - base_ip);
  492. break;
  493. }
  494. }
  495. candidate = base_ip + table[hash];
  496. BROTLI_DCHECK(candidate >= base_ip);
  497. BROTLI_DCHECK(candidate < ip);
  498. table[hash] = (int)(ip - base_ip);
  499. } while (BROTLI_PREDICT_TRUE(!IsMatch(ip, candidate)));
  500. /* Check copy distance. If candidate is not feasible, continue search.
  501. Checking is done outside of hot loop to reduce overhead. */
  502. if (ip - candidate > MAX_DISTANCE) goto trawl;
  503. /* Step 2: Emit the found match together with the literal bytes from
  504. "next_emit" to the bit stream, and then see if we can find a next match
  505. immediately afterwards. Repeat until we find no match for the input
  506. without emitting some literal bytes. */
  507. {
  508. /* We have a 5-byte match at ip, and we need to emit bytes in
  509. [next_emit, ip). */
  510. const uint8_t* base = ip;
  511. size_t matched = 5 + FindMatchLengthWithLimit(
  512. candidate + 5, ip + 5, (size_t)(ip_end - ip) - 5);
  513. int distance = (int)(base - candidate); /* > 0 */
  514. size_t insert = (size_t)(base - next_emit);
  515. ip += matched;
  516. BROTLI_DCHECK(0 == memcmp(base, candidate, matched));
  517. if (BROTLI_PREDICT_TRUE(insert < 6210)) {
  518. EmitInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
  519. storage_ix, storage);
  520. } else if (ShouldUseUncompressedMode(metablock_start, next_emit, insert,
  521. literal_ratio)) {
  522. EmitUncompressedMetaBlock(metablock_start, base, mlen_storage_ix - 3,
  523. storage_ix, storage);
  524. input_size -= (size_t)(base - input);
  525. input = base;
  526. next_emit = input;
  527. goto next_block;
  528. } else {
  529. EmitLongInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
  530. storage_ix, storage);
  531. }
  532. EmitLiterals(next_emit, insert, lit_depth, lit_bits,
  533. storage_ix, storage);
  534. if (distance == last_distance) {
  535. BrotliWriteBits(cmd_depth[64], cmd_bits[64], storage_ix, storage);
  536. ++cmd_histo[64];
  537. } else {
  538. EmitDistance((size_t)distance, cmd_depth, cmd_bits,
  539. cmd_histo, storage_ix, storage);
  540. last_distance = distance;
  541. }
  542. EmitCopyLenLastDistance(matched, cmd_depth, cmd_bits, cmd_histo,
  543. storage_ix, storage);
  544. next_emit = ip;
  545. if (BROTLI_PREDICT_FALSE(ip >= ip_limit)) {
  546. goto emit_remainder;
  547. }
  548. /* We could immediately start working at ip now, but to improve
  549. compression we first update "table" with the hashes of some positions
  550. within the last copy. */
  551. {
  552. uint64_t input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 3);
  553. uint32_t prev_hash = HashBytesAtOffset(input_bytes, 0, shift);
  554. uint32_t cur_hash = HashBytesAtOffset(input_bytes, 3, shift);
  555. table[prev_hash] = (int)(ip - base_ip - 3);
  556. prev_hash = HashBytesAtOffset(input_bytes, 1, shift);
  557. table[prev_hash] = (int)(ip - base_ip - 2);
  558. prev_hash = HashBytesAtOffset(input_bytes, 2, shift);
  559. table[prev_hash] = (int)(ip - base_ip - 1);
  560. candidate = base_ip + table[cur_hash];
  561. table[cur_hash] = (int)(ip - base_ip);
  562. }
  563. }
  564. while (IsMatch(ip, candidate)) {
  565. /* We have a 5-byte match at ip, and no need to emit any literal bytes
  566. prior to ip. */
  567. const uint8_t* base = ip;
  568. size_t matched = 5 + FindMatchLengthWithLimit(
  569. candidate + 5, ip + 5, (size_t)(ip_end - ip) - 5);
  570. if (ip - candidate > MAX_DISTANCE) break;
  571. ip += matched;
  572. last_distance = (int)(base - candidate); /* > 0 */
  573. BROTLI_DCHECK(0 == memcmp(base, candidate, matched));
  574. EmitCopyLen(matched, cmd_depth, cmd_bits, cmd_histo,
  575. storage_ix, storage);
  576. EmitDistance((size_t)last_distance, cmd_depth, cmd_bits,
  577. cmd_histo, storage_ix, storage);
  578. next_emit = ip;
  579. if (BROTLI_PREDICT_FALSE(ip >= ip_limit)) {
  580. goto emit_remainder;
  581. }
  582. /* We could immediately start working at ip now, but to improve
  583. compression we first update "table" with the hashes of some positions
  584. within the last copy. */
  585. {
  586. uint64_t input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 3);
  587. uint32_t prev_hash = HashBytesAtOffset(input_bytes, 0, shift);
  588. uint32_t cur_hash = HashBytesAtOffset(input_bytes, 3, shift);
  589. table[prev_hash] = (int)(ip - base_ip - 3);
  590. prev_hash = HashBytesAtOffset(input_bytes, 1, shift);
  591. table[prev_hash] = (int)(ip - base_ip - 2);
  592. prev_hash = HashBytesAtOffset(input_bytes, 2, shift);
  593. table[prev_hash] = (int)(ip - base_ip - 1);
  594. candidate = base_ip + table[cur_hash];
  595. table[cur_hash] = (int)(ip - base_ip);
  596. }
  597. }
  598. next_hash = Hash(++ip, shift);
  599. }
  600. }
  601. emit_remainder:
  602. BROTLI_DCHECK(next_emit <= ip_end);
  603. input += block_size;
  604. input_size -= block_size;
  605. block_size = BROTLI_MIN(size_t, input_size, kMergeBlockSize);
  606. /* Decide if we want to continue this meta-block instead of emitting the
  607. last insert-only command. */
  608. if (input_size > 0 &&
  609. total_block_size + block_size <= (1 << 20) &&
  610. ShouldMergeBlock(input, block_size, lit_depth)) {
  611. BROTLI_DCHECK(total_block_size > (1 << 16));
  612. /* Update the size of the current meta-block and continue emitting commands.
  613. We can do this because the current size and the new size both have 5
  614. nibbles. */
  615. total_block_size += block_size;
  616. UpdateBits(20, (uint32_t)(total_block_size - 1), mlen_storage_ix, storage);
  617. goto emit_commands;
  618. }
  619. /* Emit the remaining bytes as literals. */
  620. if (next_emit < ip_end) {
  621. const size_t insert = (size_t)(ip_end - next_emit);
  622. if (BROTLI_PREDICT_TRUE(insert < 6210)) {
  623. EmitInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
  624. storage_ix, storage);
  625. EmitLiterals(next_emit, insert, lit_depth, lit_bits, storage_ix, storage);
  626. } else if (ShouldUseUncompressedMode(metablock_start, next_emit, insert,
  627. literal_ratio)) {
  628. EmitUncompressedMetaBlock(metablock_start, ip_end, mlen_storage_ix - 3,
  629. storage_ix, storage);
  630. } else {
  631. EmitLongInsertLen(insert, cmd_depth, cmd_bits, cmd_histo,
  632. storage_ix, storage);
  633. EmitLiterals(next_emit, insert, lit_depth, lit_bits,
  634. storage_ix, storage);
  635. }
  636. }
  637. next_emit = ip_end;
  638. next_block:
  639. /* If we have more data, write a new meta-block header and prefix codes and
  640. then continue emitting commands. */
  641. if (input_size > 0) {
  642. metablock_start = input;
  643. block_size = BROTLI_MIN(size_t, input_size, kFirstBlockSize);
  644. total_block_size = block_size;
  645. /* Save the bit position of the MLEN field of the meta-block header, so that
  646. we can update it later if we decide to extend this meta-block. */
  647. mlen_storage_ix = *storage_ix + 3;
  648. BrotliStoreMetaBlockHeader(block_size, 0, storage_ix, storage);
  649. /* No block splits, no contexts. */
  650. BrotliWriteBits(13, 0, storage_ix, storage);
  651. literal_ratio = BuildAndStoreLiteralPrefixCode(
  652. m, input, block_size, lit_depth, lit_bits, storage_ix, storage);
  653. if (BROTLI_IS_OOM(m)) return;
  654. BuildAndStoreCommandPrefixCode(cmd_histo, cmd_depth, cmd_bits,
  655. storage_ix, storage);
  656. goto emit_commands;
  657. }
  658. if (!is_last) {
  659. /* If this is not the last block, update the command and distance prefix
  660. codes for the next block and store the compressed forms. */
  661. cmd_code[0] = 0;
  662. *cmd_code_numbits = 0;
  663. BuildAndStoreCommandPrefixCode(cmd_histo, cmd_depth, cmd_bits,
  664. cmd_code_numbits, cmd_code);
  665. }
  666. }
  667. #define FOR_TABLE_BITS_(X) X(9) X(11) X(13) X(15)
  668. #define BAKE_METHOD_PARAM_(B) \
  669. static BROTLI_NOINLINE void BrotliCompressFragmentFastImpl ## B( \
  670. MemoryManager* m, const uint8_t* input, size_t input_size, \
  671. BROTLI_BOOL is_last, int* table, uint8_t cmd_depth[128], \
  672. uint16_t cmd_bits[128], size_t* cmd_code_numbits, uint8_t* cmd_code, \
  673. size_t* storage_ix, uint8_t* storage) { \
  674. BrotliCompressFragmentFastImpl(m, input, input_size, is_last, table, B, \
  675. cmd_depth, cmd_bits, cmd_code_numbits, cmd_code, storage_ix, storage); \
  676. }
  677. FOR_TABLE_BITS_(BAKE_METHOD_PARAM_)
  678. #undef BAKE_METHOD_PARAM_
  679. void BrotliCompressFragmentFast(
  680. MemoryManager* m, const uint8_t* input, size_t input_size,
  681. BROTLI_BOOL is_last, int* table, size_t table_size, uint8_t cmd_depth[128],
  682. uint16_t cmd_bits[128], size_t* cmd_code_numbits, uint8_t* cmd_code,
  683. size_t* storage_ix, uint8_t* storage) {
  684. const size_t initial_storage_ix = *storage_ix;
  685. const size_t table_bits = Log2FloorNonZero(table_size);
  686. if (input_size == 0) {
  687. BROTLI_DCHECK(is_last);
  688. BrotliWriteBits(1, 1, storage_ix, storage); /* islast */
  689. BrotliWriteBits(1, 1, storage_ix, storage); /* isempty */
  690. *storage_ix = (*storage_ix + 7u) & ~7u;
  691. return;
  692. }
  693. switch (table_bits) {
  694. #define CASE_(B) \
  695. case B: \
  696. BrotliCompressFragmentFastImpl ## B( \
  697. m, input, input_size, is_last, table, cmd_depth, cmd_bits, \
  698. cmd_code_numbits, cmd_code, storage_ix, storage); \
  699. break;
  700. FOR_TABLE_BITS_(CASE_)
  701. #undef CASE_
  702. default: BROTLI_DCHECK(0); break;
  703. }
  704. /* If output is larger than single uncompressed block, rewrite it. */
  705. if (*storage_ix - initial_storage_ix > 31 + (input_size << 3)) {
  706. EmitUncompressedMetaBlock(input, input + input_size, initial_storage_ix,
  707. storage_ix, storage);
  708. }
  709. if (is_last) {
  710. BrotliWriteBits(1, 1, storage_ix, storage); /* islast */
  711. BrotliWriteBits(1, 1, storage_ix, storage); /* isempty */
  712. *storage_ix = (*storage_ix + 7u) & ~7u;
  713. }
  714. }
  715. #undef FOR_TABLE_BITS_
  716. #if defined(__cplusplus) || defined(c_plusplus)
  717. } /* extern "C" */
  718. #endif