compress_fragment_two_pass.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 two-pass processing: in the first pass we save
  7. the found backward matches and literal bytes into a buffer, and in the
  8. second pass we emit them into the bit stream using prefix codes built based
  9. on the actual command and literal byte histograms. */
  10. #include "./compress_fragment_two_pass.h"
  11. #include <string.h> /* memcmp, memcpy, memset */
  12. #include "../common/constants.h"
  13. #include "../common/platform.h"
  14. #include <brotli/types.h>
  15. #include "./bit_cost.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,
  34. size_t shift, size_t length) {
  35. const uint64_t h =
  36. (BROTLI_UNALIGNED_LOAD64LE(p) << ((8 - length) * 8)) * kHashMul32;
  37. return (uint32_t)(h >> shift);
  38. }
  39. static BROTLI_INLINE uint32_t HashBytesAtOffset(uint64_t v, size_t offset,
  40. size_t shift, size_t length) {
  41. BROTLI_DCHECK(offset <= 8 - length);
  42. {
  43. const uint64_t h = ((v >> (8 * offset)) << ((8 - length) * 8)) * kHashMul32;
  44. return (uint32_t)(h >> shift);
  45. }
  46. }
  47. static BROTLI_INLINE BROTLI_BOOL IsMatch(const uint8_t* p1, const uint8_t* p2,
  48. size_t length) {
  49. if (BrotliUnalignedRead32(p1) == BrotliUnalignedRead32(p2)) {
  50. if (length == 4) return BROTLI_TRUE;
  51. return TO_BROTLI_BOOL(p1[4] == p2[4] && p1[5] == p2[5]);
  52. }
  53. return BROTLI_FALSE;
  54. }
  55. /* Builds a command and distance prefix code (each 64 symbols) into "depth" and
  56. "bits" based on "histogram" and stores it into the bit stream. */
  57. static void BuildAndStoreCommandPrefixCode(
  58. const uint32_t histogram[128],
  59. uint8_t depth[128], uint16_t bits[128],
  60. size_t* storage_ix, uint8_t* storage) {
  61. /* Tree size for building a tree over 64 symbols is 2 * 64 + 1. */
  62. HuffmanTree tree[129];
  63. uint8_t cmd_depth[BROTLI_NUM_COMMAND_SYMBOLS] = { 0 };
  64. uint16_t cmd_bits[64];
  65. BrotliCreateHuffmanTree(histogram, 64, 15, tree, depth);
  66. BrotliCreateHuffmanTree(&histogram[64], 64, 14, tree, &depth[64]);
  67. /* We have to jump through a few hoops here in order to compute
  68. the command bits because the symbols are in a different order than in
  69. the full alphabet. This looks complicated, but having the symbols
  70. in this order in the command bits saves a few branches in the Emit*
  71. functions. */
  72. memcpy(cmd_depth, depth + 24, 24);
  73. memcpy(cmd_depth + 24, depth, 8);
  74. memcpy(cmd_depth + 32, depth + 48, 8);
  75. memcpy(cmd_depth + 40, depth + 8, 8);
  76. memcpy(cmd_depth + 48, depth + 56, 8);
  77. memcpy(cmd_depth + 56, depth + 16, 8);
  78. BrotliConvertBitDepthsToSymbols(cmd_depth, 64, cmd_bits);
  79. memcpy(bits, cmd_bits + 24, 16);
  80. memcpy(bits + 8, cmd_bits + 40, 16);
  81. memcpy(bits + 16, cmd_bits + 56, 16);
  82. memcpy(bits + 24, cmd_bits, 48);
  83. memcpy(bits + 48, cmd_bits + 32, 16);
  84. memcpy(bits + 56, cmd_bits + 48, 16);
  85. BrotliConvertBitDepthsToSymbols(&depth[64], 64, &bits[64]);
  86. {
  87. /* Create the bit length array for the full command alphabet. */
  88. size_t i;
  89. memset(cmd_depth, 0, 64); /* only 64 first values were used */
  90. memcpy(cmd_depth, depth + 24, 8);
  91. memcpy(cmd_depth + 64, depth + 32, 8);
  92. memcpy(cmd_depth + 128, depth + 40, 8);
  93. memcpy(cmd_depth + 192, depth + 48, 8);
  94. memcpy(cmd_depth + 384, depth + 56, 8);
  95. for (i = 0; i < 8; ++i) {
  96. cmd_depth[128 + 8 * i] = depth[i];
  97. cmd_depth[256 + 8 * i] = depth[8 + i];
  98. cmd_depth[448 + 8 * i] = depth[16 + i];
  99. }
  100. BrotliStoreHuffmanTree(
  101. cmd_depth, BROTLI_NUM_COMMAND_SYMBOLS, tree, storage_ix, storage);
  102. }
  103. BrotliStoreHuffmanTree(&depth[64], 64, tree, storage_ix, storage);
  104. }
  105. static BROTLI_INLINE void EmitInsertLen(
  106. uint32_t insertlen, uint32_t** commands) {
  107. if (insertlen < 6) {
  108. **commands = insertlen;
  109. } else if (insertlen < 130) {
  110. const uint32_t tail = insertlen - 2;
  111. const uint32_t nbits = Log2FloorNonZero(tail) - 1u;
  112. const uint32_t prefix = tail >> nbits;
  113. const uint32_t inscode = (nbits << 1) + prefix + 2;
  114. const uint32_t extra = tail - (prefix << nbits);
  115. **commands = inscode | (extra << 8);
  116. } else if (insertlen < 2114) {
  117. const uint32_t tail = insertlen - 66;
  118. const uint32_t nbits = Log2FloorNonZero(tail);
  119. const uint32_t code = nbits + 10;
  120. const uint32_t extra = tail - (1u << nbits);
  121. **commands = code | (extra << 8);
  122. } else if (insertlen < 6210) {
  123. const uint32_t extra = insertlen - 2114;
  124. **commands = 21 | (extra << 8);
  125. } else if (insertlen < 22594) {
  126. const uint32_t extra = insertlen - 6210;
  127. **commands = 22 | (extra << 8);
  128. } else {
  129. const uint32_t extra = insertlen - 22594;
  130. **commands = 23 | (extra << 8);
  131. }
  132. ++(*commands);
  133. }
  134. static BROTLI_INLINE void EmitCopyLen(size_t copylen, uint32_t** commands) {
  135. if (copylen < 10) {
  136. **commands = (uint32_t)(copylen + 38);
  137. } else if (copylen < 134) {
  138. const size_t tail = copylen - 6;
  139. const size_t nbits = Log2FloorNonZero(tail) - 1;
  140. const size_t prefix = tail >> nbits;
  141. const size_t code = (nbits << 1) + prefix + 44;
  142. const size_t extra = tail - (prefix << nbits);
  143. **commands = (uint32_t)(code | (extra << 8));
  144. } else if (copylen < 2118) {
  145. const size_t tail = copylen - 70;
  146. const size_t nbits = Log2FloorNonZero(tail);
  147. const size_t code = nbits + 52;
  148. const size_t extra = tail - ((size_t)1 << nbits);
  149. **commands = (uint32_t)(code | (extra << 8));
  150. } else {
  151. const size_t extra = copylen - 2118;
  152. **commands = (uint32_t)(63 | (extra << 8));
  153. }
  154. ++(*commands);
  155. }
  156. static BROTLI_INLINE void EmitCopyLenLastDistance(
  157. size_t copylen, uint32_t** commands) {
  158. if (copylen < 12) {
  159. **commands = (uint32_t)(copylen + 20);
  160. ++(*commands);
  161. } else if (copylen < 72) {
  162. const size_t tail = copylen - 8;
  163. const size_t nbits = Log2FloorNonZero(tail) - 1;
  164. const size_t prefix = tail >> nbits;
  165. const size_t code = (nbits << 1) + prefix + 28;
  166. const size_t extra = tail - (prefix << nbits);
  167. **commands = (uint32_t)(code | (extra << 8));
  168. ++(*commands);
  169. } else if (copylen < 136) {
  170. const size_t tail = copylen - 8;
  171. const size_t code = (tail >> 5) + 54;
  172. const size_t extra = tail & 31;
  173. **commands = (uint32_t)(code | (extra << 8));
  174. ++(*commands);
  175. **commands = 64;
  176. ++(*commands);
  177. } else if (copylen < 2120) {
  178. const size_t tail = copylen - 72;
  179. const size_t nbits = Log2FloorNonZero(tail);
  180. const size_t code = nbits + 52;
  181. const size_t extra = tail - ((size_t)1 << nbits);
  182. **commands = (uint32_t)(code | (extra << 8));
  183. ++(*commands);
  184. **commands = 64;
  185. ++(*commands);
  186. } else {
  187. const size_t extra = copylen - 2120;
  188. **commands = (uint32_t)(63 | (extra << 8));
  189. ++(*commands);
  190. **commands = 64;
  191. ++(*commands);
  192. }
  193. }
  194. static BROTLI_INLINE void EmitDistance(uint32_t distance, uint32_t** commands) {
  195. uint32_t d = distance + 3;
  196. uint32_t nbits = Log2FloorNonZero(d) - 1;
  197. const uint32_t prefix = (d >> nbits) & 1;
  198. const uint32_t offset = (2 + prefix) << nbits;
  199. const uint32_t distcode = 2 * (nbits - 1) + prefix + 80;
  200. uint32_t extra = d - offset;
  201. **commands = distcode | (extra << 8);
  202. ++(*commands);
  203. }
  204. /* REQUIRES: len <= 1 << 24. */
  205. static void BrotliStoreMetaBlockHeader(
  206. size_t len, BROTLI_BOOL is_uncompressed, size_t* storage_ix,
  207. uint8_t* storage) {
  208. size_t nibbles = 6;
  209. /* ISLAST */
  210. BrotliWriteBits(1, 0, storage_ix, storage);
  211. if (len <= (1U << 16)) {
  212. nibbles = 4;
  213. } else if (len <= (1U << 20)) {
  214. nibbles = 5;
  215. }
  216. BrotliWriteBits(2, nibbles - 4, storage_ix, storage);
  217. BrotliWriteBits(nibbles * 4, len - 1, storage_ix, storage);
  218. /* ISUNCOMPRESSED */
  219. BrotliWriteBits(1, (uint64_t)is_uncompressed, storage_ix, storage);
  220. }
  221. static BROTLI_INLINE void CreateCommands(const uint8_t* input,
  222. size_t block_size, size_t input_size, const uint8_t* base_ip, int* table,
  223. size_t table_bits, size_t min_match,
  224. uint8_t** literals, uint32_t** commands) {
  225. /* "ip" is the input pointer. */
  226. const uint8_t* ip = input;
  227. const size_t shift = 64u - table_bits;
  228. const uint8_t* ip_end = input + block_size;
  229. /* "next_emit" is a pointer to the first byte that is not covered by a
  230. previous copy. Bytes between "next_emit" and the start of the next copy or
  231. the end of the input will be emitted as literal bytes. */
  232. const uint8_t* next_emit = input;
  233. int last_distance = -1;
  234. const size_t kInputMarginBytes = BROTLI_WINDOW_GAP;
  235. if (BROTLI_PREDICT_TRUE(block_size >= kInputMarginBytes)) {
  236. /* For the last block, we need to keep a 16 bytes margin so that we can be
  237. sure that all distances are at most window size - 16.
  238. For all other blocks, we only need to keep a margin of 5 bytes so that
  239. we don't go over the block size with a copy. */
  240. const size_t len_limit = BROTLI_MIN(size_t, block_size - min_match,
  241. input_size - kInputMarginBytes);
  242. const uint8_t* ip_limit = input + len_limit;
  243. uint32_t next_hash;
  244. for (next_hash = Hash(++ip, shift, min_match); ; ) {
  245. /* Step 1: Scan forward in the input looking for a 6-byte-long match.
  246. If we get close to exhausting the input then goto emit_remainder.
  247. Heuristic match skipping: If 32 bytes are scanned with no matches
  248. found, start looking only at every other byte. If 32 more bytes are
  249. scanned, look at every third byte, etc.. When a match is found,
  250. immediately go back to looking at every byte. This is a small loss
  251. (~5% performance, ~0.1% density) for compressible data due to more
  252. bookkeeping, but for non-compressible data (such as JPEG) it's a huge
  253. win since the compressor quickly "realizes" the data is incompressible
  254. and doesn't bother looking for matches everywhere.
  255. The "skip" variable keeps track of how many bytes there are since the
  256. last match; dividing it by 32 (ie. right-shifting by five) gives the
  257. number of bytes to move ahead for each iteration. */
  258. uint32_t skip = 32;
  259. const uint8_t* next_ip = ip;
  260. const uint8_t* candidate;
  261. BROTLI_DCHECK(next_emit < ip);
  262. trawl:
  263. do {
  264. uint32_t hash = next_hash;
  265. uint32_t bytes_between_hash_lookups = skip++ >> 5;
  266. ip = next_ip;
  267. BROTLI_DCHECK(hash == Hash(ip, shift, min_match));
  268. next_ip = ip + bytes_between_hash_lookups;
  269. if (BROTLI_PREDICT_FALSE(next_ip > ip_limit)) {
  270. goto emit_remainder;
  271. }
  272. next_hash = Hash(next_ip, shift, min_match);
  273. candidate = ip - last_distance;
  274. if (IsMatch(ip, candidate, min_match)) {
  275. if (BROTLI_PREDICT_TRUE(candidate < ip)) {
  276. table[hash] = (int)(ip - base_ip);
  277. break;
  278. }
  279. }
  280. candidate = base_ip + table[hash];
  281. BROTLI_DCHECK(candidate >= base_ip);
  282. BROTLI_DCHECK(candidate < ip);
  283. table[hash] = (int)(ip - base_ip);
  284. } while (BROTLI_PREDICT_TRUE(!IsMatch(ip, candidate, min_match)));
  285. /* Check copy distance. If candidate is not feasible, continue search.
  286. Checking is done outside of hot loop to reduce overhead. */
  287. if (ip - candidate > MAX_DISTANCE) goto trawl;
  288. /* Step 2: Emit the found match together with the literal bytes from
  289. "next_emit", and then see if we can find a next match immediately
  290. afterwards. Repeat until we find no match for the input
  291. without emitting some literal bytes. */
  292. {
  293. /* We have a 6-byte match at ip, and we need to emit bytes in
  294. [next_emit, ip). */
  295. const uint8_t* base = ip;
  296. size_t matched = min_match + FindMatchLengthWithLimit(
  297. candidate + min_match, ip + min_match,
  298. (size_t)(ip_end - ip) - min_match);
  299. int distance = (int)(base - candidate); /* > 0 */
  300. int insert = (int)(base - next_emit);
  301. ip += matched;
  302. BROTLI_DCHECK(0 == memcmp(base, candidate, matched));
  303. EmitInsertLen((uint32_t)insert, commands);
  304. memcpy(*literals, next_emit, (size_t)insert);
  305. *literals += insert;
  306. if (distance == last_distance) {
  307. **commands = 64;
  308. ++(*commands);
  309. } else {
  310. EmitDistance((uint32_t)distance, commands);
  311. last_distance = distance;
  312. }
  313. EmitCopyLenLastDistance(matched, commands);
  314. next_emit = ip;
  315. if (BROTLI_PREDICT_FALSE(ip >= ip_limit)) {
  316. goto emit_remainder;
  317. }
  318. {
  319. /* We could immediately start working at ip now, but to improve
  320. compression we first update "table" with the hashes of some
  321. positions within the last copy. */
  322. uint64_t input_bytes;
  323. uint32_t cur_hash;
  324. uint32_t prev_hash;
  325. if (min_match == 4) {
  326. input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 3);
  327. cur_hash = HashBytesAtOffset(input_bytes, 3, shift, min_match);
  328. prev_hash = HashBytesAtOffset(input_bytes, 0, shift, min_match);
  329. table[prev_hash] = (int)(ip - base_ip - 3);
  330. prev_hash = HashBytesAtOffset(input_bytes, 1, shift, min_match);
  331. table[prev_hash] = (int)(ip - base_ip - 2);
  332. prev_hash = HashBytesAtOffset(input_bytes, 0, shift, min_match);
  333. table[prev_hash] = (int)(ip - base_ip - 1);
  334. } else {
  335. input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 5);
  336. prev_hash = HashBytesAtOffset(input_bytes, 0, shift, min_match);
  337. table[prev_hash] = (int)(ip - base_ip - 5);
  338. prev_hash = HashBytesAtOffset(input_bytes, 1, shift, min_match);
  339. table[prev_hash] = (int)(ip - base_ip - 4);
  340. prev_hash = HashBytesAtOffset(input_bytes, 2, shift, min_match);
  341. table[prev_hash] = (int)(ip - base_ip - 3);
  342. input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 2);
  343. cur_hash = HashBytesAtOffset(input_bytes, 2, shift, min_match);
  344. prev_hash = HashBytesAtOffset(input_bytes, 0, shift, min_match);
  345. table[prev_hash] = (int)(ip - base_ip - 2);
  346. prev_hash = HashBytesAtOffset(input_bytes, 1, shift, min_match);
  347. table[prev_hash] = (int)(ip - base_ip - 1);
  348. }
  349. candidate = base_ip + table[cur_hash];
  350. table[cur_hash] = (int)(ip - base_ip);
  351. }
  352. }
  353. while (ip - candidate <= MAX_DISTANCE &&
  354. IsMatch(ip, candidate, min_match)) {
  355. /* We have a 6-byte match at ip, and no need to emit any
  356. literal bytes prior to ip. */
  357. const uint8_t* base = ip;
  358. size_t matched = min_match + FindMatchLengthWithLimit(
  359. candidate + min_match, ip + min_match,
  360. (size_t)(ip_end - ip) - min_match);
  361. ip += matched;
  362. last_distance = (int)(base - candidate); /* > 0 */
  363. BROTLI_DCHECK(0 == memcmp(base, candidate, matched));
  364. EmitCopyLen(matched, commands);
  365. EmitDistance((uint32_t)last_distance, commands);
  366. next_emit = ip;
  367. if (BROTLI_PREDICT_FALSE(ip >= ip_limit)) {
  368. goto emit_remainder;
  369. }
  370. {
  371. /* We could immediately start working at ip now, but to improve
  372. compression we first update "table" with the hashes of some
  373. positions within the last copy. */
  374. uint64_t input_bytes;
  375. uint32_t cur_hash;
  376. uint32_t prev_hash;
  377. if (min_match == 4) {
  378. input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 3);
  379. cur_hash = HashBytesAtOffset(input_bytes, 3, shift, min_match);
  380. prev_hash = HashBytesAtOffset(input_bytes, 0, shift, min_match);
  381. table[prev_hash] = (int)(ip - base_ip - 3);
  382. prev_hash = HashBytesAtOffset(input_bytes, 1, shift, min_match);
  383. table[prev_hash] = (int)(ip - base_ip - 2);
  384. prev_hash = HashBytesAtOffset(input_bytes, 2, shift, min_match);
  385. table[prev_hash] = (int)(ip - base_ip - 1);
  386. } else {
  387. input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 5);
  388. prev_hash = HashBytesAtOffset(input_bytes, 0, shift, min_match);
  389. table[prev_hash] = (int)(ip - base_ip - 5);
  390. prev_hash = HashBytesAtOffset(input_bytes, 1, shift, min_match);
  391. table[prev_hash] = (int)(ip - base_ip - 4);
  392. prev_hash = HashBytesAtOffset(input_bytes, 2, shift, min_match);
  393. table[prev_hash] = (int)(ip - base_ip - 3);
  394. input_bytes = BROTLI_UNALIGNED_LOAD64LE(ip - 2);
  395. cur_hash = HashBytesAtOffset(input_bytes, 2, shift, min_match);
  396. prev_hash = HashBytesAtOffset(input_bytes, 0, shift, min_match);
  397. table[prev_hash] = (int)(ip - base_ip - 2);
  398. prev_hash = HashBytesAtOffset(input_bytes, 1, shift, min_match);
  399. table[prev_hash] = (int)(ip - base_ip - 1);
  400. }
  401. candidate = base_ip + table[cur_hash];
  402. table[cur_hash] = (int)(ip - base_ip);
  403. }
  404. }
  405. next_hash = Hash(++ip, shift, min_match);
  406. }
  407. }
  408. emit_remainder:
  409. BROTLI_DCHECK(next_emit <= ip_end);
  410. /* Emit the remaining bytes as literals. */
  411. if (next_emit < ip_end) {
  412. const uint32_t insert = (uint32_t)(ip_end - next_emit);
  413. EmitInsertLen(insert, commands);
  414. memcpy(*literals, next_emit, insert);
  415. *literals += insert;
  416. }
  417. }
  418. static void StoreCommands(MemoryManager* m,
  419. const uint8_t* literals, const size_t num_literals,
  420. const uint32_t* commands, const size_t num_commands,
  421. size_t* storage_ix, uint8_t* storage) {
  422. static const uint32_t kNumExtraBits[128] = {
  423. 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 12, 14, 24,
  424. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4,
  425. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 8, 9, 10, 24,
  426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  427. 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  428. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16,
  429. 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24,
  430. };
  431. static const uint32_t kInsertOffset[24] = {
  432. 0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 18, 26, 34, 50, 66, 98, 130, 194, 322, 578,
  433. 1090, 2114, 6210, 22594,
  434. };
  435. uint8_t lit_depths[256];
  436. uint16_t lit_bits[256];
  437. uint32_t lit_histo[256] = { 0 };
  438. uint8_t cmd_depths[128] = { 0 };
  439. uint16_t cmd_bits[128] = { 0 };
  440. uint32_t cmd_histo[128] = { 0 };
  441. size_t i;
  442. for (i = 0; i < num_literals; ++i) {
  443. ++lit_histo[literals[i]];
  444. }
  445. BrotliBuildAndStoreHuffmanTreeFast(m, lit_histo, num_literals,
  446. /* max_bits = */ 8,
  447. lit_depths, lit_bits,
  448. storage_ix, storage);
  449. if (BROTLI_IS_OOM(m)) return;
  450. for (i = 0; i < num_commands; ++i) {
  451. const uint32_t code = commands[i] & 0xFF;
  452. BROTLI_DCHECK(code < 128);
  453. ++cmd_histo[code];
  454. }
  455. cmd_histo[1] += 1;
  456. cmd_histo[2] += 1;
  457. cmd_histo[64] += 1;
  458. cmd_histo[84] += 1;
  459. BuildAndStoreCommandPrefixCode(cmd_histo, cmd_depths, cmd_bits,
  460. storage_ix, storage);
  461. for (i = 0; i < num_commands; ++i) {
  462. const uint32_t cmd = commands[i];
  463. const uint32_t code = cmd & 0xFF;
  464. const uint32_t extra = cmd >> 8;
  465. BROTLI_DCHECK(code < 128);
  466. BrotliWriteBits(cmd_depths[code], cmd_bits[code], storage_ix, storage);
  467. BrotliWriteBits(kNumExtraBits[code], extra, storage_ix, storage);
  468. if (code < 24) {
  469. const uint32_t insert = kInsertOffset[code] + extra;
  470. uint32_t j;
  471. for (j = 0; j < insert; ++j) {
  472. const uint8_t lit = *literals;
  473. BrotliWriteBits(lit_depths[lit], lit_bits[lit], storage_ix, storage);
  474. ++literals;
  475. }
  476. }
  477. }
  478. }
  479. /* Acceptable loss for uncompressible speedup is 2% */
  480. #define MIN_RATIO 0.98
  481. #define SAMPLE_RATE 43
  482. static BROTLI_BOOL ShouldCompress(
  483. const uint8_t* input, size_t input_size, size_t num_literals) {
  484. double corpus_size = (double)input_size;
  485. if (num_literals < MIN_RATIO * corpus_size) {
  486. return BROTLI_TRUE;
  487. } else {
  488. uint32_t literal_histo[256] = { 0 };
  489. const double max_total_bit_cost = corpus_size * 8 * MIN_RATIO / SAMPLE_RATE;
  490. size_t i;
  491. for (i = 0; i < input_size; i += SAMPLE_RATE) {
  492. ++literal_histo[input[i]];
  493. }
  494. return TO_BROTLI_BOOL(BitsEntropy(literal_histo, 256) < max_total_bit_cost);
  495. }
  496. }
  497. static void RewindBitPosition(const size_t new_storage_ix,
  498. size_t* storage_ix, uint8_t* storage) {
  499. const size_t bitpos = new_storage_ix & 7;
  500. const size_t mask = (1u << bitpos) - 1;
  501. storage[new_storage_ix >> 3] &= (uint8_t)mask;
  502. *storage_ix = new_storage_ix;
  503. }
  504. static void EmitUncompressedMetaBlock(const uint8_t* input, size_t input_size,
  505. size_t* storage_ix, uint8_t* storage) {
  506. BrotliStoreMetaBlockHeader(input_size, 1, storage_ix, storage);
  507. *storage_ix = (*storage_ix + 7u) & ~7u;
  508. memcpy(&storage[*storage_ix >> 3], input, input_size);
  509. *storage_ix += input_size << 3;
  510. storage[*storage_ix >> 3] = 0;
  511. }
  512. static BROTLI_INLINE void BrotliCompressFragmentTwoPassImpl(
  513. MemoryManager* m, const uint8_t* input, size_t input_size,
  514. BROTLI_BOOL is_last, uint32_t* command_buf, uint8_t* literal_buf,
  515. int* table, size_t table_bits, size_t min_match,
  516. size_t* storage_ix, uint8_t* storage) {
  517. /* Save the start of the first block for position and distance computations.
  518. */
  519. const uint8_t* base_ip = input;
  520. BROTLI_UNUSED(is_last);
  521. while (input_size > 0) {
  522. size_t block_size =
  523. BROTLI_MIN(size_t, input_size, kCompressFragmentTwoPassBlockSize);
  524. uint32_t* commands = command_buf;
  525. uint8_t* literals = literal_buf;
  526. size_t num_literals;
  527. CreateCommands(input, block_size, input_size, base_ip, table,
  528. table_bits, min_match, &literals, &commands);
  529. num_literals = (size_t)(literals - literal_buf);
  530. if (ShouldCompress(input, block_size, num_literals)) {
  531. const size_t num_commands = (size_t)(commands - command_buf);
  532. BrotliStoreMetaBlockHeader(block_size, 0, storage_ix, storage);
  533. /* No block splits, no contexts. */
  534. BrotliWriteBits(13, 0, storage_ix, storage);
  535. StoreCommands(m, literal_buf, num_literals, command_buf, num_commands,
  536. storage_ix, storage);
  537. if (BROTLI_IS_OOM(m)) return;
  538. } else {
  539. /* Since we did not find many backward references and the entropy of
  540. the data is close to 8 bits, we can simply emit an uncompressed block.
  541. This makes compression speed of uncompressible data about 3x faster. */
  542. EmitUncompressedMetaBlock(input, block_size, storage_ix, storage);
  543. }
  544. input += block_size;
  545. input_size -= block_size;
  546. }
  547. }
  548. #define FOR_TABLE_BITS_(X) \
  549. X(8) X(9) X(10) X(11) X(12) X(13) X(14) X(15) X(16) X(17)
  550. #define BAKE_METHOD_PARAM_(B) \
  551. static BROTLI_NOINLINE void BrotliCompressFragmentTwoPassImpl ## B( \
  552. MemoryManager* m, const uint8_t* input, size_t input_size, \
  553. BROTLI_BOOL is_last, uint32_t* command_buf, uint8_t* literal_buf, \
  554. int* table, size_t* storage_ix, uint8_t* storage) { \
  555. size_t min_match = (B <= 15) ? 4 : 6; \
  556. BrotliCompressFragmentTwoPassImpl(m, input, input_size, is_last, command_buf,\
  557. literal_buf, table, B, min_match, storage_ix, storage); \
  558. }
  559. FOR_TABLE_BITS_(BAKE_METHOD_PARAM_)
  560. #undef BAKE_METHOD_PARAM_
  561. void BrotliCompressFragmentTwoPass(
  562. MemoryManager* m, const uint8_t* input, size_t input_size,
  563. BROTLI_BOOL is_last, uint32_t* command_buf, uint8_t* literal_buf,
  564. int* table, size_t table_size, size_t* storage_ix, uint8_t* storage) {
  565. const size_t initial_storage_ix = *storage_ix;
  566. const size_t table_bits = Log2FloorNonZero(table_size);
  567. switch (table_bits) {
  568. #define CASE_(B) \
  569. case B: \
  570. BrotliCompressFragmentTwoPassImpl ## B( \
  571. m, input, input_size, is_last, command_buf, \
  572. literal_buf, table, storage_ix, storage); \
  573. break;
  574. FOR_TABLE_BITS_(CASE_)
  575. #undef CASE_
  576. default: BROTLI_DCHECK(0); break;
  577. }
  578. /* If output is larger than single uncompressed block, rewrite it. */
  579. if (*storage_ix - initial_storage_ix > 31 + (input_size << 3)) {
  580. RewindBitPosition(initial_storage_ix, storage_ix, storage);
  581. EmitUncompressedMetaBlock(input, input_size, storage_ix, storage);
  582. }
  583. if (is_last) {
  584. BrotliWriteBits(1, 1, storage_ix, storage); /* islast */
  585. BrotliWriteBits(1, 1, storage_ix, storage); /* isempty */
  586. *storage_ix = (*storage_ix + 7u) & ~7u;
  587. }
  588. }
  589. #undef FOR_TABLE_BITS_
  590. #if defined(__cplusplus) || defined(c_plusplus)
  591. } /* extern "C" */
  592. #endif