compress_fragment_two_pass.go 22 KB

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