compress_fragment_two_pass.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. package brotli
  2. import "encoding/binary"
  3. /* Copyright 2015 Google Inc. All Rights Reserved.
  4. Distributed under MIT license.
  5. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  6. */
  7. /* Function for fast encoding of an input fragment, independently from the input
  8. history. This function uses two-pass processing: in the first pass we save
  9. the found backward matches and literal bytes into a buffer, and in the
  10. second pass we emit them into the bit stream using prefix codes built based
  11. on the actual command and literal byte histograms. */
  12. const kCompressFragmentTwoPassBlockSize uint = 1 << 17
  13. func hash1(p []byte, shift uint, length uint) uint32 {
  14. var h uint64 = (binary.LittleEndian.Uint64(p) << ((8 - length) * 8)) * uint64(kHashMul32)
  15. return uint32(h >> shift)
  16. }
  17. func hashBytesAtOffset(v uint64, offset uint, shift uint, length uint) uint32 {
  18. assert(offset <= 8-length)
  19. {
  20. var h uint64 = ((v >> (8 * offset)) << ((8 - length) * 8)) * uint64(kHashMul32)
  21. return uint32(h >> shift)
  22. }
  23. }
  24. func isMatch1(p1 []byte, p2 []byte, length uint) bool {
  25. if binary.LittleEndian.Uint32(p1) != binary.LittleEndian.Uint32(p2) {
  26. return false
  27. }
  28. if length == 4 {
  29. return true
  30. }
  31. return p1[4] == p2[4] && p1[5] == p2[5]
  32. }
  33. /*
  34. Builds a command and distance prefix code (each 64 symbols) into "depth" and
  35. "bits" based on "histogram" and stores it into the bit stream.
  36. */
  37. func buildAndStoreCommandPrefixCode(histogram []uint32, depth []byte, bits []uint16, storage_ix *uint, storage []byte) {
  38. var tree [129]huffmanTree
  39. var cmd_depth = [numCommandSymbols]byte{0}
  40. /* Tree size for building a tree over 64 symbols is 2 * 64 + 1. */
  41. var cmd_bits [64]uint16
  42. createHuffmanTree(histogram, 64, 15, tree[:], depth)
  43. createHuffmanTree(histogram[64:], 64, 14, tree[:], depth[64:])
  44. /* We have to jump through a few hoops here in order to compute
  45. the command bits because the symbols are in a different order than in
  46. the full alphabet. This looks complicated, but having the symbols
  47. in this order in the command bits saves a few branches in the Emit*
  48. functions. */
  49. copy(cmd_depth[:], depth[24:][:24])
  50. copy(cmd_depth[24:][:], depth[:8])
  51. copy(cmd_depth[32:][:], depth[48:][:8])
  52. copy(cmd_depth[40:][:], depth[8:][:8])
  53. copy(cmd_depth[48:][:], depth[56:][:8])
  54. copy(cmd_depth[56:][:], depth[16:][:8])
  55. convertBitDepthsToSymbols(cmd_depth[:], 64, cmd_bits[:])
  56. copy(bits, cmd_bits[24:][:8])
  57. copy(bits[8:], cmd_bits[40:][:8])
  58. copy(bits[16:], cmd_bits[56:][:8])
  59. copy(bits[24:], cmd_bits[:24])
  60. copy(bits[48:], cmd_bits[32:][:8])
  61. copy(bits[56:], cmd_bits[48:][:8])
  62. convertBitDepthsToSymbols(depth[64:], 64, bits[64:])
  63. {
  64. /* Create the bit length array for the full command alphabet. */
  65. var i uint
  66. for i := 0; i < int(64); i++ {
  67. cmd_depth[i] = 0
  68. } /* only 64 first values were used */
  69. copy(cmd_depth[:], depth[24:][:8])
  70. copy(cmd_depth[64:][:], depth[32:][:8])
  71. copy(cmd_depth[128:][:], depth[40:][:8])
  72. copy(cmd_depth[192:][:], depth[48:][:8])
  73. copy(cmd_depth[384:][:], depth[56:][:8])
  74. for i = 0; i < 8; i++ {
  75. cmd_depth[128+8*i] = depth[i]
  76. cmd_depth[256+8*i] = depth[8+i]
  77. cmd_depth[448+8*i] = depth[16+i]
  78. }
  79. storeHuffmanTree(cmd_depth[:], numCommandSymbols, tree[:], storage_ix, storage)
  80. }
  81. storeHuffmanTree(depth[64:], 64, tree[:], storage_ix, storage)
  82. }
  83. func emitInsertLen(insertlen uint32, commands *[]uint32) {
  84. if insertlen < 6 {
  85. (*commands)[0] = insertlen
  86. } else if insertlen < 130 {
  87. var tail uint32 = insertlen - 2
  88. var nbits uint32 = log2FloorNonZero(uint(tail)) - 1
  89. var prefix uint32 = tail >> nbits
  90. var inscode uint32 = (nbits << 1) + prefix + 2
  91. var extra uint32 = tail - (prefix << nbits)
  92. (*commands)[0] = inscode | extra<<8
  93. } else if insertlen < 2114 {
  94. var tail uint32 = insertlen - 66
  95. var nbits uint32 = log2FloorNonZero(uint(tail))
  96. var code uint32 = nbits + 10
  97. var extra uint32 = tail - (1 << nbits)
  98. (*commands)[0] = code | extra<<8
  99. } else if insertlen < 6210 {
  100. var extra uint32 = insertlen - 2114
  101. (*commands)[0] = 21 | extra<<8
  102. } else if insertlen < 22594 {
  103. var extra uint32 = insertlen - 6210
  104. (*commands)[0] = 22 | extra<<8
  105. } else {
  106. var extra uint32 = insertlen - 22594
  107. (*commands)[0] = 23 | extra<<8
  108. }
  109. *commands = (*commands)[1:]
  110. }
  111. func emitCopyLen(copylen uint, commands *[]uint32) {
  112. if copylen < 10 {
  113. (*commands)[0] = uint32(copylen + 38)
  114. } else if copylen < 134 {
  115. var tail uint = copylen - 6
  116. var nbits uint = uint(log2FloorNonZero(tail) - 1)
  117. var prefix uint = tail >> nbits
  118. var code uint = (nbits << 1) + prefix + 44
  119. var extra uint = tail - (prefix << nbits)
  120. (*commands)[0] = uint32(code | extra<<8)
  121. } else if copylen < 2118 {
  122. var tail uint = copylen - 70
  123. var nbits uint = uint(log2FloorNonZero(tail))
  124. var code uint = nbits + 52
  125. var extra uint = tail - (uint(1) << nbits)
  126. (*commands)[0] = uint32(code | extra<<8)
  127. } else {
  128. var extra uint = copylen - 2118
  129. (*commands)[0] = uint32(63 | extra<<8)
  130. }
  131. *commands = (*commands)[1:]
  132. }
  133. func emitCopyLenLastDistance(copylen uint, commands *[]uint32) {
  134. if copylen < 12 {
  135. (*commands)[0] = uint32(copylen + 20)
  136. *commands = (*commands)[1:]
  137. } else if copylen < 72 {
  138. var tail uint = copylen - 8
  139. var nbits uint = uint(log2FloorNonZero(tail) - 1)
  140. var prefix uint = tail >> nbits
  141. var code uint = (nbits << 1) + prefix + 28
  142. var extra uint = tail - (prefix << nbits)
  143. (*commands)[0] = uint32(code | extra<<8)
  144. *commands = (*commands)[1:]
  145. } else if copylen < 136 {
  146. var tail uint = copylen - 8
  147. var code uint = (tail >> 5) + 54
  148. var extra uint = tail & 31
  149. (*commands)[0] = uint32(code | extra<<8)
  150. *commands = (*commands)[1:]
  151. (*commands)[0] = 64
  152. *commands = (*commands)[1:]
  153. } else if copylen < 2120 {
  154. var tail uint = copylen - 72
  155. var nbits uint = uint(log2FloorNonZero(tail))
  156. var code uint = nbits + 52
  157. var extra uint = tail - (uint(1) << nbits)
  158. (*commands)[0] = uint32(code | extra<<8)
  159. *commands = (*commands)[1:]
  160. (*commands)[0] = 64
  161. *commands = (*commands)[1:]
  162. } else {
  163. var extra uint = copylen - 2120
  164. (*commands)[0] = uint32(63 | extra<<8)
  165. *commands = (*commands)[1:]
  166. (*commands)[0] = 64
  167. *commands = (*commands)[1:]
  168. }
  169. }
  170. func emitDistance(distance uint32, commands *[]uint32) {
  171. var d uint32 = distance + 3
  172. var nbits uint32 = log2FloorNonZero(uint(d)) - 1
  173. var prefix uint32 = (d >> nbits) & 1
  174. var offset uint32 = (2 + prefix) << nbits
  175. var distcode uint32 = 2*(nbits-1) + prefix + 80
  176. var extra uint32 = d - offset
  177. (*commands)[0] = distcode | extra<<8
  178. *commands = (*commands)[1:]
  179. }
  180. /* REQUIRES: len <= 1 << 24. */
  181. func storeMetaBlockHeader(len uint, is_uncompressed bool, storage_ix *uint, storage []byte) {
  182. var nibbles uint = 6
  183. /* ISLAST */
  184. writeBits(1, 0, storage_ix, storage)
  185. if len <= 1<<16 {
  186. nibbles = 4
  187. } else if len <= 1<<20 {
  188. nibbles = 5
  189. }
  190. writeBits(2, uint64(nibbles)-4, storage_ix, storage)
  191. writeBits(nibbles*4, uint64(len)-1, storage_ix, storage)
  192. /* ISUNCOMPRESSED */
  193. writeSingleBit(is_uncompressed, storage_ix, storage)
  194. }
  195. func storeMetaBlockHeaderBW(len uint, is_uncompressed bool, bw *bitWriter) {
  196. var nibbles uint = 6
  197. /* ISLAST */
  198. bw.writeBits(1, 0)
  199. if len <= 1<<16 {
  200. nibbles = 4
  201. } else if len <= 1<<20 {
  202. nibbles = 5
  203. }
  204. bw.writeBits(2, uint64(nibbles)-4)
  205. bw.writeBits(nibbles*4, uint64(len)-1)
  206. /* ISUNCOMPRESSED */
  207. bw.writeSingleBit(is_uncompressed)
  208. }
  209. func createCommands(input []byte, block_size uint, input_size uint, base_ip_ptr []byte, table []int, table_bits uint, min_match uint, literals *[]byte, commands *[]uint32) {
  210. var ip int = 0
  211. var shift uint = 64 - table_bits
  212. var ip_end int = int(block_size)
  213. var base_ip int = -cap(base_ip_ptr) + cap(input)
  214. var next_emit int = 0
  215. var last_distance int = -1
  216. /* "ip" is the input pointer. */
  217. const kInputMarginBytes uint = windowGap
  218. /* "next_emit" is a pointer to the first byte that is not covered by a
  219. previous copy. Bytes between "next_emit" and the start of the next copy or
  220. the end of the input will be emitted as literal bytes. */
  221. if block_size >= kInputMarginBytes {
  222. var len_limit uint = brotli_min_size_t(block_size-min_match, input_size-kInputMarginBytes)
  223. var ip_limit int = int(len_limit)
  224. /* For the last block, we need to keep a 16 bytes margin so that we can be
  225. sure that all distances are at most window size - 16.
  226. For all other blocks, we only need to keep a margin of 5 bytes so that
  227. we don't go over the block size with a copy. */
  228. var next_hash uint32
  229. ip++
  230. for next_hash = hash1(input[ip:], shift, min_match); ; {
  231. var skip uint32 = 32
  232. var next_ip int = ip
  233. /* Step 1: Scan forward in the input looking for a 6-byte-long match.
  234. If we get close to exhausting the input then goto emit_remainder.
  235. Heuristic match skipping: If 32 bytes are scanned with no matches
  236. found, start looking only at every other byte. If 32 more bytes are
  237. scanned, look at every third byte, etc.. When a match is found,
  238. immediately go back to looking at every byte. This is a small loss
  239. (~5% performance, ~0.1% density) for compressible data due to more
  240. bookkeeping, but for non-compressible data (such as JPEG) it's a huge
  241. win since the compressor quickly "realizes" the data is incompressible
  242. and doesn't bother looking for matches everywhere.
  243. The "skip" variable keeps track of how many bytes there are since the
  244. last match; dividing it by 32 (ie. right-shifting by five) gives the
  245. number of bytes to move ahead for each iteration. */
  246. var candidate int
  247. assert(next_emit < ip)
  248. trawl:
  249. for {
  250. var hash uint32 = next_hash
  251. var bytes_between_hash_lookups uint32 = skip >> 5
  252. skip++
  253. ip = next_ip
  254. assert(hash == hash1(input[ip:], shift, min_match))
  255. next_ip = int(uint32(ip) + bytes_between_hash_lookups)
  256. if next_ip > ip_limit {
  257. goto emit_remainder
  258. }
  259. next_hash = hash1(input[next_ip:], shift, min_match)
  260. candidate = ip - last_distance
  261. if isMatch1(input[ip:], base_ip_ptr[candidate-base_ip:], min_match) {
  262. if candidate < ip {
  263. table[hash] = int(ip - base_ip)
  264. break
  265. }
  266. }
  267. candidate = base_ip + table[hash]
  268. assert(candidate >= base_ip)
  269. assert(candidate < ip)
  270. table[hash] = int(ip - base_ip)
  271. if isMatch1(input[ip:], base_ip_ptr[candidate-base_ip:], min_match) {
  272. break
  273. }
  274. }
  275. /* Check copy distance. If candidate is not feasible, continue search.
  276. Checking is done outside of hot loop to reduce overhead. */
  277. if ip-candidate > maxDistance_compress_fragment {
  278. goto trawl
  279. }
  280. /* Step 2: Emit the found match together with the literal bytes from
  281. "next_emit", and then see if we can find a next match immediately
  282. afterwards. Repeat until we find no match for the input
  283. without emitting some literal bytes. */
  284. {
  285. var base int = ip
  286. /* > 0 */
  287. var matched uint = min_match + findMatchLengthWithLimit(base_ip_ptr[uint(candidate-base_ip)+min_match:], input[uint(ip)+min_match:], uint(ip_end-ip)-min_match)
  288. var distance int = int(base - candidate)
  289. /* We have a 6-byte match at ip, and we need to emit bytes in
  290. [next_emit, ip). */
  291. var insert int = int(base - next_emit)
  292. ip += int(matched)
  293. emitInsertLen(uint32(insert), commands)
  294. copy(*literals, input[next_emit:][:uint(insert)])
  295. *literals = (*literals)[insert:]
  296. if distance == last_distance {
  297. (*commands)[0] = 64
  298. *commands = (*commands)[1:]
  299. } else {
  300. emitDistance(uint32(distance), commands)
  301. last_distance = distance
  302. }
  303. emitCopyLenLastDistance(matched, commands)
  304. next_emit = ip
  305. if ip >= ip_limit {
  306. goto emit_remainder
  307. }
  308. {
  309. var input_bytes uint64
  310. var cur_hash uint32
  311. /* We could immediately start working at ip now, but to improve
  312. compression we first update "table" with the hashes of some
  313. positions within the last copy. */
  314. var prev_hash uint32
  315. if min_match == 4 {
  316. input_bytes = binary.LittleEndian.Uint64(input[ip-3:])
  317. cur_hash = hashBytesAtOffset(input_bytes, 3, shift, min_match)
  318. prev_hash = hashBytesAtOffset(input_bytes, 0, shift, min_match)
  319. table[prev_hash] = int(ip - base_ip - 3)
  320. prev_hash = hashBytesAtOffset(input_bytes, 1, shift, min_match)
  321. table[prev_hash] = int(ip - base_ip - 2)
  322. prev_hash = hashBytesAtOffset(input_bytes, 0, shift, min_match)
  323. table[prev_hash] = int(ip - base_ip - 1)
  324. } else {
  325. input_bytes = binary.LittleEndian.Uint64(input[ip-5:])
  326. prev_hash = hashBytesAtOffset(input_bytes, 0, shift, min_match)
  327. table[prev_hash] = int(ip - base_ip - 5)
  328. prev_hash = hashBytesAtOffset(input_bytes, 1, shift, min_match)
  329. table[prev_hash] = int(ip - base_ip - 4)
  330. prev_hash = hashBytesAtOffset(input_bytes, 2, shift, min_match)
  331. table[prev_hash] = int(ip - base_ip - 3)
  332. input_bytes = binary.LittleEndian.Uint64(input[ip-2:])
  333. cur_hash = hashBytesAtOffset(input_bytes, 2, shift, min_match)
  334. prev_hash = hashBytesAtOffset(input_bytes, 0, shift, min_match)
  335. table[prev_hash] = int(ip - base_ip - 2)
  336. prev_hash = hashBytesAtOffset(input_bytes, 1, shift, min_match)
  337. table[prev_hash] = int(ip - base_ip - 1)
  338. }
  339. candidate = base_ip + table[cur_hash]
  340. table[cur_hash] = int(ip - base_ip)
  341. }
  342. }
  343. for ip-candidate <= maxDistance_compress_fragment && isMatch1(input[ip:], base_ip_ptr[candidate-base_ip:], min_match) {
  344. var base int = ip
  345. /* We have a 6-byte match at ip, and no need to emit any
  346. literal bytes prior to ip. */
  347. var matched uint = min_match + findMatchLengthWithLimit(base_ip_ptr[uint(candidate-base_ip)+min_match:], input[uint(ip)+min_match:], uint(ip_end-ip)-min_match)
  348. ip += int(matched)
  349. last_distance = int(base - candidate) /* > 0 */
  350. emitCopyLen(matched, commands)
  351. emitDistance(uint32(last_distance), commands)
  352. next_emit = ip
  353. if ip >= ip_limit {
  354. goto emit_remainder
  355. }
  356. {
  357. var input_bytes uint64
  358. var cur_hash uint32
  359. /* We could immediately start working at ip now, but to improve
  360. compression we first update "table" with the hashes of some
  361. positions within the last copy. */
  362. var prev_hash uint32
  363. if min_match == 4 {
  364. input_bytes = binary.LittleEndian.Uint64(input[ip-3:])
  365. cur_hash = hashBytesAtOffset(input_bytes, 3, shift, min_match)
  366. prev_hash = hashBytesAtOffset(input_bytes, 0, shift, min_match)
  367. table[prev_hash] = int(ip - base_ip - 3)
  368. prev_hash = hashBytesAtOffset(input_bytes, 1, shift, min_match)
  369. table[prev_hash] = int(ip - base_ip - 2)
  370. prev_hash = hashBytesAtOffset(input_bytes, 2, shift, min_match)
  371. table[prev_hash] = int(ip - base_ip - 1)
  372. } else {
  373. input_bytes = binary.LittleEndian.Uint64(input[ip-5:])
  374. prev_hash = hashBytesAtOffset(input_bytes, 0, shift, min_match)
  375. table[prev_hash] = int(ip - base_ip - 5)
  376. prev_hash = hashBytesAtOffset(input_bytes, 1, shift, min_match)
  377. table[prev_hash] = int(ip - base_ip - 4)
  378. prev_hash = hashBytesAtOffset(input_bytes, 2, shift, min_match)
  379. table[prev_hash] = int(ip - base_ip - 3)
  380. input_bytes = binary.LittleEndian.Uint64(input[ip-2:])
  381. cur_hash = hashBytesAtOffset(input_bytes, 2, shift, min_match)
  382. prev_hash = hashBytesAtOffset(input_bytes, 0, shift, min_match)
  383. table[prev_hash] = int(ip - base_ip - 2)
  384. prev_hash = hashBytesAtOffset(input_bytes, 1, shift, min_match)
  385. table[prev_hash] = int(ip - base_ip - 1)
  386. }
  387. candidate = base_ip + table[cur_hash]
  388. table[cur_hash] = int(ip - base_ip)
  389. }
  390. }
  391. ip++
  392. next_hash = hash1(input[ip:], shift, min_match)
  393. }
  394. }
  395. emit_remainder:
  396. assert(next_emit <= ip_end)
  397. /* Emit the remaining bytes as literals. */
  398. if next_emit < ip_end {
  399. var insert uint32 = uint32(ip_end - next_emit)
  400. emitInsertLen(insert, commands)
  401. copy(*literals, input[next_emit:][:insert])
  402. *literals = (*literals)[insert:]
  403. }
  404. }
  405. var storeCommands_kNumExtraBits = [128]uint32{
  406. 0,
  407. 0,
  408. 0,
  409. 0,
  410. 0,
  411. 0,
  412. 1,
  413. 1,
  414. 2,
  415. 2,
  416. 3,
  417. 3,
  418. 4,
  419. 4,
  420. 5,
  421. 5,
  422. 6,
  423. 7,
  424. 8,
  425. 9,
  426. 10,
  427. 12,
  428. 14,
  429. 24,
  430. 0,
  431. 0,
  432. 0,
  433. 0,
  434. 0,
  435. 0,
  436. 0,
  437. 0,
  438. 1,
  439. 1,
  440. 2,
  441. 2,
  442. 3,
  443. 3,
  444. 4,
  445. 4,
  446. 0,
  447. 0,
  448. 0,
  449. 0,
  450. 0,
  451. 0,
  452. 0,
  453. 0,
  454. 1,
  455. 1,
  456. 2,
  457. 2,
  458. 3,
  459. 3,
  460. 4,
  461. 4,
  462. 5,
  463. 5,
  464. 6,
  465. 7,
  466. 8,
  467. 9,
  468. 10,
  469. 24,
  470. 0,
  471. 0,
  472. 0,
  473. 0,
  474. 0,
  475. 0,
  476. 0,
  477. 0,
  478. 0,
  479. 0,
  480. 0,
  481. 0,
  482. 0,
  483. 0,
  484. 0,
  485. 0,
  486. 1,
  487. 1,
  488. 2,
  489. 2,
  490. 3,
  491. 3,
  492. 4,
  493. 4,
  494. 5,
  495. 5,
  496. 6,
  497. 6,
  498. 7,
  499. 7,
  500. 8,
  501. 8,
  502. 9,
  503. 9,
  504. 10,
  505. 10,
  506. 11,
  507. 11,
  508. 12,
  509. 12,
  510. 13,
  511. 13,
  512. 14,
  513. 14,
  514. 15,
  515. 15,
  516. 16,
  517. 16,
  518. 17,
  519. 17,
  520. 18,
  521. 18,
  522. 19,
  523. 19,
  524. 20,
  525. 20,
  526. 21,
  527. 21,
  528. 22,
  529. 22,
  530. 23,
  531. 23,
  532. 24,
  533. 24,
  534. }
  535. var storeCommands_kInsertOffset = [24]uint32{
  536. 0,
  537. 1,
  538. 2,
  539. 3,
  540. 4,
  541. 5,
  542. 6,
  543. 8,
  544. 10,
  545. 14,
  546. 18,
  547. 26,
  548. 34,
  549. 50,
  550. 66,
  551. 98,
  552. 130,
  553. 194,
  554. 322,
  555. 578,
  556. 1090,
  557. 2114,
  558. 6210,
  559. 22594,
  560. }
  561. func storeCommands(literals []byte, num_literals uint, commands []uint32, num_commands uint, storage_ix *uint, storage []byte) {
  562. var lit_depths [256]byte
  563. var lit_bits [256]uint16
  564. var lit_histo = [256]uint32{0}
  565. var cmd_depths = [128]byte{0}
  566. var cmd_bits = [128]uint16{0}
  567. var cmd_histo = [128]uint32{0}
  568. var i uint
  569. for i = 0; i < num_literals; i++ {
  570. lit_histo[literals[i]]++
  571. }
  572. buildAndStoreHuffmanTreeFast(lit_histo[:], num_literals, /* max_bits = */
  573. 8, lit_depths[:], lit_bits[:], storage_ix, storage)
  574. for i = 0; i < num_commands; i++ {
  575. var code uint32 = commands[i] & 0xFF
  576. assert(code < 128)
  577. cmd_histo[code]++
  578. }
  579. cmd_histo[1] += 1
  580. cmd_histo[2] += 1
  581. cmd_histo[64] += 1
  582. cmd_histo[84] += 1
  583. buildAndStoreCommandPrefixCode(cmd_histo[:], cmd_depths[:], cmd_bits[:], storage_ix, storage)
  584. for i = 0; i < num_commands; i++ {
  585. var cmd uint32 = commands[i]
  586. var code uint32 = cmd & 0xFF
  587. var extra uint32 = cmd >> 8
  588. assert(code < 128)
  589. writeBits(uint(cmd_depths[code]), uint64(cmd_bits[code]), storage_ix, storage)
  590. writeBits(uint(storeCommands_kNumExtraBits[code]), uint64(extra), storage_ix, storage)
  591. if code < 24 {
  592. var insert uint32 = storeCommands_kInsertOffset[code] + extra
  593. var j uint32
  594. for j = 0; j < insert; j++ {
  595. var lit byte = literals[0]
  596. writeBits(uint(lit_depths[lit]), uint64(lit_bits[lit]), storage_ix, storage)
  597. literals = literals[1:]
  598. }
  599. }
  600. }
  601. }
  602. /* Acceptable loss for uncompressible speedup is 2% */
  603. const minRatio = 0.98
  604. const sampleRate = 43
  605. func shouldCompress(input []byte, input_size uint, num_literals uint) bool {
  606. var corpus_size float64 = float64(input_size)
  607. if float64(num_literals) < minRatio*corpus_size {
  608. return true
  609. } else {
  610. var literal_histo = [256]uint32{0}
  611. var max_total_bit_cost float64 = corpus_size * 8 * minRatio / sampleRate
  612. var i uint
  613. for i = 0; i < input_size; i += sampleRate {
  614. literal_histo[input[i]]++
  615. }
  616. return bitsEntropy(literal_histo[:], 256) < max_total_bit_cost
  617. }
  618. }
  619. func rewindBitPosition(new_storage_ix uint, storage_ix *uint, storage []byte) {
  620. var bitpos uint = new_storage_ix & 7
  621. var mask uint = (1 << bitpos) - 1
  622. storage[new_storage_ix>>3] &= byte(mask)
  623. *storage_ix = new_storage_ix
  624. }
  625. func emitUncompressedMetaBlock(input []byte, input_size uint, storage_ix *uint, storage []byte) {
  626. storeMetaBlockHeader(input_size, true, storage_ix, storage)
  627. *storage_ix = (*storage_ix + 7) &^ 7
  628. copy(storage[*storage_ix>>3:], input[:input_size])
  629. *storage_ix += input_size << 3
  630. storage[*storage_ix>>3] = 0
  631. }
  632. func compressFragmentTwoPassImpl(input []byte, input_size uint, is_last bool, command_buf []uint32, literal_buf []byte, table []int, table_bits uint, min_match uint, storage_ix *uint, storage []byte) {
  633. /* Save the start of the first block for position and distance computations.
  634. */
  635. var base_ip []byte = input
  636. for input_size > 0 {
  637. var block_size uint = brotli_min_size_t(input_size, kCompressFragmentTwoPassBlockSize)
  638. var commands []uint32 = command_buf
  639. var literals []byte = literal_buf
  640. var num_literals uint
  641. createCommands(input, block_size, input_size, base_ip, table, table_bits, min_match, &literals, &commands)
  642. num_literals = uint(-cap(literals) + cap(literal_buf))
  643. if shouldCompress(input, block_size, num_literals) {
  644. var num_commands uint = uint(-cap(commands) + cap(command_buf))
  645. storeMetaBlockHeader(block_size, false, storage_ix, storage)
  646. /* No block splits, no contexts. */
  647. writeBits(13, 0, storage_ix, storage)
  648. storeCommands(literal_buf, num_literals, command_buf, num_commands, storage_ix, storage)
  649. } else {
  650. /* Since we did not find many backward references and the entropy of
  651. the data is close to 8 bits, we can simply emit an uncompressed block.
  652. This makes compression speed of uncompressible data about 3x faster. */
  653. emitUncompressedMetaBlock(input, block_size, storage_ix, storage)
  654. }
  655. input = input[block_size:]
  656. input_size -= block_size
  657. }
  658. }
  659. /*
  660. Compresses "input" string to the "*storage" buffer as one or more complete
  661. meta-blocks, and updates the "*storage_ix" bit position.
  662. If "is_last" is 1, emits an additional empty last meta-block.
  663. REQUIRES: "input_size" is greater than zero, or "is_last" is 1.
  664. REQUIRES: "input_size" is less or equal to maximal metablock size (1 << 24).
  665. REQUIRES: "command_buf" and "literal_buf" point to at least
  666. kCompressFragmentTwoPassBlockSize long arrays.
  667. REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
  668. REQUIRES: "table_size" is a power of two
  669. OUTPUT: maximal copy distance <= |input_size|
  670. OUTPUT: maximal copy distance <= BROTLI_MAX_BACKWARD_LIMIT(18)
  671. */
  672. func compressFragmentTwoPass(input []byte, input_size uint, is_last bool, command_buf []uint32, literal_buf []byte, table []int, table_size uint, storage_ix *uint, storage []byte) {
  673. var initial_storage_ix uint = *storage_ix
  674. var table_bits uint = uint(log2FloorNonZero(table_size))
  675. var min_match uint
  676. if table_bits <= 15 {
  677. min_match = 4
  678. } else {
  679. min_match = 6
  680. }
  681. compressFragmentTwoPassImpl(input, input_size, is_last, command_buf, literal_buf, table, table_bits, min_match, storage_ix, storage)
  682. /* If output is larger than single uncompressed block, rewrite it. */
  683. if *storage_ix-initial_storage_ix > 31+(input_size<<3) {
  684. rewindBitPosition(initial_storage_ix, storage_ix, storage)
  685. emitUncompressedMetaBlock(input, input_size, storage_ix, storage)
  686. }
  687. if is_last {
  688. writeBits(1, 1, storage_ix, storage) /* islast */
  689. writeBits(1, 1, storage_ix, storage) /* isempty */
  690. *storage_ix = (*storage_ix + 7) &^ 7
  691. }
  692. }