brotli_bit_stream.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. package brotli
  2. import (
  3. "math"
  4. "sync"
  5. )
  6. const maxHuffmanTreeSize = (2*numCommandSymbols + 1)
  7. /* The maximum size of Huffman dictionary for distances assuming that
  8. NPOSTFIX = 0 and NDIRECT = 0. */
  9. const maxSimpleDistanceAlphabetSize = 140
  10. /* Represents the range of values belonging to a prefix code:
  11. [offset, offset + 2^nbits) */
  12. type prefixCodeRange struct {
  13. offset uint32
  14. nbits uint32
  15. }
  16. var kBlockLengthPrefixCode = [numBlockLenSymbols]prefixCodeRange{
  17. prefixCodeRange{1, 2},
  18. prefixCodeRange{5, 2},
  19. prefixCodeRange{9, 2},
  20. prefixCodeRange{13, 2},
  21. prefixCodeRange{17, 3},
  22. prefixCodeRange{25, 3},
  23. prefixCodeRange{33, 3},
  24. prefixCodeRange{41, 3},
  25. prefixCodeRange{49, 4},
  26. prefixCodeRange{65, 4},
  27. prefixCodeRange{81, 4},
  28. prefixCodeRange{97, 4},
  29. prefixCodeRange{113, 5},
  30. prefixCodeRange{145, 5},
  31. prefixCodeRange{177, 5},
  32. prefixCodeRange{209, 5},
  33. prefixCodeRange{241, 6},
  34. prefixCodeRange{305, 6},
  35. prefixCodeRange{369, 7},
  36. prefixCodeRange{497, 8},
  37. prefixCodeRange{753, 9},
  38. prefixCodeRange{1265, 10},
  39. prefixCodeRange{2289, 11},
  40. prefixCodeRange{4337, 12},
  41. prefixCodeRange{8433, 13},
  42. prefixCodeRange{16625, 24},
  43. }
  44. func blockLengthPrefixCode(len uint32) uint32 {
  45. var code uint32
  46. if len >= 177 {
  47. if len >= 753 {
  48. code = 20
  49. } else {
  50. code = 14
  51. }
  52. } else if len >= 41 {
  53. code = 7
  54. } else {
  55. code = 0
  56. }
  57. for code < (numBlockLenSymbols-1) && len >= kBlockLengthPrefixCode[code+1].offset {
  58. code++
  59. }
  60. return code
  61. }
  62. func getBlockLengthPrefixCode(len uint32, code *uint, n_extra *uint32, extra *uint32) {
  63. *code = uint(blockLengthPrefixCode(uint32(len)))
  64. *n_extra = kBlockLengthPrefixCode[*code].nbits
  65. *extra = len - kBlockLengthPrefixCode[*code].offset
  66. }
  67. type blockTypeCodeCalculator struct {
  68. last_type uint
  69. second_last_type uint
  70. }
  71. func initBlockTypeCodeCalculator(self *blockTypeCodeCalculator) {
  72. self.last_type = 1
  73. self.second_last_type = 0
  74. }
  75. func nextBlockTypeCode(calculator *blockTypeCodeCalculator, type_ byte) uint {
  76. var type_code uint
  77. if uint(type_) == calculator.last_type+1 {
  78. type_code = 1
  79. } else if uint(type_) == calculator.second_last_type {
  80. type_code = 0
  81. } else {
  82. type_code = uint(type_) + 2
  83. }
  84. calculator.second_last_type = calculator.last_type
  85. calculator.last_type = uint(type_)
  86. return type_code
  87. }
  88. /* |nibblesbits| represents the 2 bits to encode MNIBBLES (0-3)
  89. REQUIRES: length > 0
  90. REQUIRES: length <= (1 << 24) */
  91. func encodeMlen(length uint, bits *uint64, numbits *uint, nibblesbits *uint64) {
  92. var lg uint
  93. if length == 1 {
  94. lg = 1
  95. } else {
  96. lg = uint(log2FloorNonZero(uint(uint32(length-1)))) + 1
  97. }
  98. var tmp uint
  99. if lg < 16 {
  100. tmp = 16
  101. } else {
  102. tmp = (lg + 3)
  103. }
  104. var mnibbles uint = tmp / 4
  105. assert(length > 0)
  106. assert(length <= 1<<24)
  107. assert(lg <= 24)
  108. *nibblesbits = uint64(mnibbles) - 4
  109. *numbits = mnibbles * 4
  110. *bits = uint64(length) - 1
  111. }
  112. func storeCommandExtra(cmd *command, storage_ix *uint, storage []byte) {
  113. var copylen_code uint32 = commandCopyLenCode(cmd)
  114. var inscode uint16 = getInsertLengthCode(uint(cmd.insert_len_))
  115. var copycode uint16 = getCopyLengthCode(uint(copylen_code))
  116. var insnumextra uint32 = getInsertExtra(inscode)
  117. var insextraval uint64 = uint64(cmd.insert_len_) - uint64(getInsertBase(inscode))
  118. var copyextraval uint64 = uint64(copylen_code) - uint64(getCopyBase(copycode))
  119. var bits uint64 = copyextraval<<insnumextra | insextraval
  120. writeBits(uint(insnumextra+getCopyExtra(copycode)), bits, storage_ix, storage)
  121. }
  122. /* Data structure that stores almost everything that is needed to encode each
  123. block switch command. */
  124. type blockSplitCode struct {
  125. type_code_calculator blockTypeCodeCalculator
  126. type_depths [maxBlockTypeSymbols]byte
  127. type_bits [maxBlockTypeSymbols]uint16
  128. length_depths [numBlockLenSymbols]byte
  129. length_bits [numBlockLenSymbols]uint16
  130. }
  131. /* Stores a number between 0 and 255. */
  132. func storeVarLenUint8(n uint, storage_ix *uint, storage []byte) {
  133. if n == 0 {
  134. writeBits(1, 0, storage_ix, storage)
  135. } else {
  136. var nbits uint = uint(log2FloorNonZero(n))
  137. writeBits(1, 1, storage_ix, storage)
  138. writeBits(3, uint64(nbits), storage_ix, storage)
  139. writeBits(nbits, uint64(n)-(uint64(uint(1))<<nbits), storage_ix, storage)
  140. }
  141. }
  142. /* Stores the compressed meta-block header.
  143. REQUIRES: length > 0
  144. REQUIRES: length <= (1 << 24) */
  145. func storeCompressedMetaBlockHeader(is_final_block bool, length uint, storage_ix *uint, storage []byte) {
  146. var lenbits uint64
  147. var nlenbits uint
  148. var nibblesbits uint64
  149. var is_final uint64
  150. if is_final_block {
  151. is_final = 1
  152. } else {
  153. is_final = 0
  154. }
  155. /* Write ISLAST bit. */
  156. writeBits(1, is_final, storage_ix, storage)
  157. /* Write ISEMPTY bit. */
  158. if is_final_block {
  159. writeBits(1, 0, storage_ix, storage)
  160. }
  161. encodeMlen(length, &lenbits, &nlenbits, &nibblesbits)
  162. writeBits(2, nibblesbits, storage_ix, storage)
  163. writeBits(nlenbits, lenbits, storage_ix, storage)
  164. if !is_final_block {
  165. /* Write ISUNCOMPRESSED bit. */
  166. writeBits(1, 0, storage_ix, storage)
  167. }
  168. }
  169. /* Stores the uncompressed meta-block header.
  170. REQUIRES: length > 0
  171. REQUIRES: length <= (1 << 24) */
  172. func storeUncompressedMetaBlockHeader(length uint, storage_ix *uint, storage []byte) {
  173. var lenbits uint64
  174. var nlenbits uint
  175. var nibblesbits uint64
  176. /* Write ISLAST bit.
  177. Uncompressed block cannot be the last one, so set to 0. */
  178. writeBits(1, 0, storage_ix, storage)
  179. encodeMlen(length, &lenbits, &nlenbits, &nibblesbits)
  180. writeBits(2, nibblesbits, storage_ix, storage)
  181. writeBits(nlenbits, lenbits, storage_ix, storage)
  182. /* Write ISUNCOMPRESSED bit. */
  183. writeBits(1, 1, storage_ix, storage)
  184. }
  185. var storeHuffmanTreeOfHuffmanTreeToBitMask_kStorageOrder = [codeLengthCodes]byte{1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15}
  186. var storeHuffmanTreeOfHuffmanTreeToBitMask_kHuffmanBitLengthHuffmanCodeSymbols = [6]byte{0, 7, 3, 2, 1, 15}
  187. var storeHuffmanTreeOfHuffmanTreeToBitMask_kHuffmanBitLengthHuffmanCodeBitLengths = [6]byte{2, 4, 3, 2, 2, 4}
  188. func storeHuffmanTreeOfHuffmanTreeToBitMask(num_codes int, code_length_bitdepth []byte, storage_ix *uint, storage []byte) {
  189. var skip_some uint = 0
  190. var codes_to_store uint = codeLengthCodes
  191. /* The bit lengths of the Huffman code over the code length alphabet
  192. are compressed with the following static Huffman code:
  193. Symbol Code
  194. ------ ----
  195. 0 00
  196. 1 1110
  197. 2 110
  198. 3 01
  199. 4 10
  200. 5 1111 */
  201. /* Throw away trailing zeros: */
  202. if num_codes > 1 {
  203. for ; codes_to_store > 0; codes_to_store-- {
  204. if code_length_bitdepth[storeHuffmanTreeOfHuffmanTreeToBitMask_kStorageOrder[codes_to_store-1]] != 0 {
  205. break
  206. }
  207. }
  208. }
  209. if code_length_bitdepth[storeHuffmanTreeOfHuffmanTreeToBitMask_kStorageOrder[0]] == 0 && code_length_bitdepth[storeHuffmanTreeOfHuffmanTreeToBitMask_kStorageOrder[1]] == 0 {
  210. skip_some = 2 /* skips two. */
  211. if code_length_bitdepth[storeHuffmanTreeOfHuffmanTreeToBitMask_kStorageOrder[2]] == 0 {
  212. skip_some = 3 /* skips three. */
  213. }
  214. }
  215. writeBits(2, uint64(skip_some), storage_ix, storage)
  216. {
  217. var i uint
  218. for i = skip_some; i < codes_to_store; i++ {
  219. var l uint = uint(code_length_bitdepth[storeHuffmanTreeOfHuffmanTreeToBitMask_kStorageOrder[i]])
  220. writeBits(uint(storeHuffmanTreeOfHuffmanTreeToBitMask_kHuffmanBitLengthHuffmanCodeBitLengths[l]), uint64(storeHuffmanTreeOfHuffmanTreeToBitMask_kHuffmanBitLengthHuffmanCodeSymbols[l]), storage_ix, storage)
  221. }
  222. }
  223. }
  224. func storeHuffmanTreeToBitMask(huffman_tree_size uint, huffman_tree []byte, huffman_tree_extra_bits []byte, code_length_bitdepth []byte, code_length_bitdepth_symbols []uint16, storage_ix *uint, storage []byte) {
  225. var i uint
  226. for i = 0; i < huffman_tree_size; i++ {
  227. var ix uint = uint(huffman_tree[i])
  228. writeBits(uint(code_length_bitdepth[ix]), uint64(code_length_bitdepth_symbols[ix]), storage_ix, storage)
  229. /* Extra bits */
  230. switch ix {
  231. case repeatPreviousCodeLength:
  232. writeBits(2, uint64(huffman_tree_extra_bits[i]), storage_ix, storage)
  233. case repeatZeroCodeLength:
  234. writeBits(3, uint64(huffman_tree_extra_bits[i]), storage_ix, storage)
  235. }
  236. }
  237. }
  238. func storeSimpleHuffmanTree(depths []byte, symbols []uint, num_symbols uint, max_bits uint, storage_ix *uint, storage []byte) {
  239. /* value of 1 indicates a simple Huffman code */
  240. writeBits(2, 1, storage_ix, storage)
  241. writeBits(2, uint64(num_symbols)-1, storage_ix, storage) /* NSYM - 1 */
  242. {
  243. /* Sort */
  244. var i uint
  245. for i = 0; i < num_symbols; i++ {
  246. var j uint
  247. for j = i + 1; j < num_symbols; j++ {
  248. if depths[symbols[j]] < depths[symbols[i]] {
  249. var tmp uint = symbols[j]
  250. symbols[j] = symbols[i]
  251. symbols[i] = tmp
  252. }
  253. }
  254. }
  255. }
  256. if num_symbols == 2 {
  257. writeBits(max_bits, uint64(symbols[0]), storage_ix, storage)
  258. writeBits(max_bits, uint64(symbols[1]), storage_ix, storage)
  259. } else if num_symbols == 3 {
  260. writeBits(max_bits, uint64(symbols[0]), storage_ix, storage)
  261. writeBits(max_bits, uint64(symbols[1]), storage_ix, storage)
  262. writeBits(max_bits, uint64(symbols[2]), storage_ix, storage)
  263. } else {
  264. writeBits(max_bits, uint64(symbols[0]), storage_ix, storage)
  265. writeBits(max_bits, uint64(symbols[1]), storage_ix, storage)
  266. writeBits(max_bits, uint64(symbols[2]), storage_ix, storage)
  267. writeBits(max_bits, uint64(symbols[3]), storage_ix, storage)
  268. /* tree-select */
  269. var tmp int
  270. if depths[symbols[0]] == 1 {
  271. tmp = 1
  272. } else {
  273. tmp = 0
  274. }
  275. writeBits(1, uint64(tmp), storage_ix, storage)
  276. }
  277. }
  278. /* num = alphabet size
  279. depths = symbol depths */
  280. func storeHuffmanTree(depths []byte, num uint, tree []huffmanTree, storage_ix *uint, storage []byte) {
  281. var huffman_tree [numCommandSymbols]byte
  282. var huffman_tree_extra_bits [numCommandSymbols]byte
  283. var huffman_tree_size uint = 0
  284. var code_length_bitdepth = [codeLengthCodes]byte{0}
  285. var code_length_bitdepth_symbols [codeLengthCodes]uint16
  286. var huffman_tree_histogram = [codeLengthCodes]uint32{0}
  287. var i uint
  288. var num_codes int = 0
  289. /* Write the Huffman tree into the brotli-representation.
  290. The command alphabet is the largest, so this allocation will fit all
  291. alphabets. */
  292. var code uint = 0
  293. assert(num <= numCommandSymbols)
  294. writeHuffmanTree(depths, num, &huffman_tree_size, huffman_tree[:], huffman_tree_extra_bits[:])
  295. /* Calculate the statistics of the Huffman tree in brotli-representation. */
  296. for i = 0; i < huffman_tree_size; i++ {
  297. huffman_tree_histogram[huffman_tree[i]]++
  298. }
  299. for i = 0; i < codeLengthCodes; i++ {
  300. if huffman_tree_histogram[i] != 0 {
  301. if num_codes == 0 {
  302. code = i
  303. num_codes = 1
  304. } else if num_codes == 1 {
  305. num_codes = 2
  306. break
  307. }
  308. }
  309. }
  310. /* Calculate another Huffman tree to use for compressing both the
  311. earlier Huffman tree with. */
  312. createHuffmanTree(huffman_tree_histogram[:], codeLengthCodes, 5, tree, code_length_bitdepth[:])
  313. convertBitDepthsToSymbols(code_length_bitdepth[:], codeLengthCodes, code_length_bitdepth_symbols[:])
  314. /* Now, we have all the data, let's start storing it */
  315. storeHuffmanTreeOfHuffmanTreeToBitMask(num_codes, code_length_bitdepth[:], storage_ix, storage)
  316. if num_codes == 1 {
  317. code_length_bitdepth[code] = 0
  318. }
  319. /* Store the real Huffman tree now. */
  320. storeHuffmanTreeToBitMask(huffman_tree_size, huffman_tree[:], huffman_tree_extra_bits[:], code_length_bitdepth[:], code_length_bitdepth_symbols[:], storage_ix, storage)
  321. }
  322. /* Builds a Huffman tree from histogram[0:length] into depth[0:length] and
  323. bits[0:length] and stores the encoded tree to the bit stream. */
  324. func buildAndStoreHuffmanTree(histogram []uint32, histogram_length uint, alphabet_size uint, tree []huffmanTree, depth []byte, bits []uint16, storage_ix *uint, storage []byte) {
  325. var count uint = 0
  326. var s4 = [4]uint{0}
  327. var i uint
  328. var max_bits uint = 0
  329. for i = 0; i < histogram_length; i++ {
  330. if histogram[i] != 0 {
  331. if count < 4 {
  332. s4[count] = i
  333. } else if count > 4 {
  334. break
  335. }
  336. count++
  337. }
  338. }
  339. {
  340. var max_bits_counter uint = alphabet_size - 1
  341. for max_bits_counter != 0 {
  342. max_bits_counter >>= 1
  343. max_bits++
  344. }
  345. }
  346. if count <= 1 {
  347. writeBits(4, 1, storage_ix, storage)
  348. writeBits(max_bits, uint64(s4[0]), storage_ix, storage)
  349. depth[s4[0]] = 0
  350. bits[s4[0]] = 0
  351. return
  352. }
  353. for i := 0; i < int(histogram_length); i++ {
  354. depth[i] = 0
  355. }
  356. createHuffmanTree(histogram, histogram_length, 15, tree, depth)
  357. convertBitDepthsToSymbols(depth, histogram_length, bits)
  358. if count <= 4 {
  359. storeSimpleHuffmanTree(depth, s4[:], count, max_bits, storage_ix, storage)
  360. } else {
  361. storeHuffmanTree(depth, histogram_length, tree, storage_ix, storage)
  362. }
  363. }
  364. func sortHuffmanTree1(v0 huffmanTree, v1 huffmanTree) bool {
  365. return v0.total_count_ < v1.total_count_
  366. }
  367. var huffmanTreePool sync.Pool
  368. func buildAndStoreHuffmanTreeFast(histogram []uint32, histogram_total uint, max_bits uint, depth []byte, bits []uint16, storage_ix *uint, storage []byte) {
  369. var count uint = 0
  370. var symbols = [4]uint{0}
  371. var length uint = 0
  372. var total uint = histogram_total
  373. for total != 0 {
  374. if histogram[length] != 0 {
  375. if count < 4 {
  376. symbols[count] = length
  377. }
  378. count++
  379. total -= uint(histogram[length])
  380. }
  381. length++
  382. }
  383. if count <= 1 {
  384. writeBits(4, 1, storage_ix, storage)
  385. writeBits(max_bits, uint64(symbols[0]), storage_ix, storage)
  386. depth[symbols[0]] = 0
  387. bits[symbols[0]] = 0
  388. return
  389. }
  390. for i := 0; i < int(length); i++ {
  391. depth[i] = 0
  392. }
  393. {
  394. var max_tree_size uint = 2*length + 1
  395. tree, _ := huffmanTreePool.Get().(*[]huffmanTree)
  396. if tree == nil || cap(*tree) < int(max_tree_size) {
  397. tmp := make([]huffmanTree, max_tree_size)
  398. tree = &tmp
  399. } else {
  400. *tree = (*tree)[:max_tree_size]
  401. }
  402. var count_limit uint32
  403. for count_limit = 1; ; count_limit *= 2 {
  404. var node int = 0
  405. var l uint
  406. for l = length; l != 0; {
  407. l--
  408. if histogram[l] != 0 {
  409. if histogram[l] >= count_limit {
  410. initHuffmanTree(&(*tree)[node:][0], histogram[l], -1, int16(l))
  411. } else {
  412. initHuffmanTree(&(*tree)[node:][0], count_limit, -1, int16(l))
  413. }
  414. node++
  415. }
  416. }
  417. {
  418. var n int = node
  419. /* Points to the next leaf node. */ /* Points to the next non-leaf node. */
  420. var sentinel huffmanTree
  421. var i int = 0
  422. var j int = n + 1
  423. var k int
  424. sortHuffmanTreeItems(*tree, uint(n), huffmanTreeComparator(sortHuffmanTree1))
  425. /* The nodes are:
  426. [0, n): the sorted leaf nodes that we start with.
  427. [n]: we add a sentinel here.
  428. [n + 1, 2n): new parent nodes are added here, starting from
  429. (n+1). These are naturally in ascending order.
  430. [2n]: we add a sentinel at the end as well.
  431. There will be (2n+1) elements at the end. */
  432. initHuffmanTree(&sentinel, math.MaxUint32, -1, -1)
  433. (*tree)[node] = sentinel
  434. node++
  435. (*tree)[node] = sentinel
  436. node++
  437. for k = n - 1; k > 0; k-- {
  438. var left int
  439. var right int
  440. if (*tree)[i].total_count_ <= (*tree)[j].total_count_ {
  441. left = i
  442. i++
  443. } else {
  444. left = j
  445. j++
  446. }
  447. if (*tree)[i].total_count_ <= (*tree)[j].total_count_ {
  448. right = i
  449. i++
  450. } else {
  451. right = j
  452. j++
  453. }
  454. /* The sentinel node becomes the parent node. */
  455. (*tree)[node-1].total_count_ = (*tree)[left].total_count_ + (*tree)[right].total_count_
  456. (*tree)[node-1].index_left_ = int16(left)
  457. (*tree)[node-1].index_right_or_value_ = int16(right)
  458. /* Add back the last sentinel node. */
  459. (*tree)[node] = sentinel
  460. node++
  461. }
  462. if setDepth(2*n-1, *tree, depth, 14) {
  463. /* We need to pack the Huffman tree in 14 bits. If this was not
  464. successful, add fake entities to the lowest values and retry. */
  465. break
  466. }
  467. }
  468. }
  469. huffmanTreePool.Put(tree)
  470. }
  471. convertBitDepthsToSymbols(depth, length, bits)
  472. if count <= 4 {
  473. var i uint
  474. /* value of 1 indicates a simple Huffman code */
  475. writeBits(2, 1, storage_ix, storage)
  476. writeBits(2, uint64(count)-1, storage_ix, storage) /* NSYM - 1 */
  477. /* Sort */
  478. for i = 0; i < count; i++ {
  479. var j uint
  480. for j = i + 1; j < count; j++ {
  481. if depth[symbols[j]] < depth[symbols[i]] {
  482. var tmp uint = symbols[j]
  483. symbols[j] = symbols[i]
  484. symbols[i] = tmp
  485. }
  486. }
  487. }
  488. if count == 2 {
  489. writeBits(max_bits, uint64(symbols[0]), storage_ix, storage)
  490. writeBits(max_bits, uint64(symbols[1]), storage_ix, storage)
  491. } else if count == 3 {
  492. writeBits(max_bits, uint64(symbols[0]), storage_ix, storage)
  493. writeBits(max_bits, uint64(symbols[1]), storage_ix, storage)
  494. writeBits(max_bits, uint64(symbols[2]), storage_ix, storage)
  495. } else {
  496. writeBits(max_bits, uint64(symbols[0]), storage_ix, storage)
  497. writeBits(max_bits, uint64(symbols[1]), storage_ix, storage)
  498. writeBits(max_bits, uint64(symbols[2]), storage_ix, storage)
  499. writeBits(max_bits, uint64(symbols[3]), storage_ix, storage)
  500. /* tree-select */
  501. var tmp int
  502. if depth[symbols[0]] == 1 {
  503. tmp = 1
  504. } else {
  505. tmp = 0
  506. }
  507. writeBits(1, uint64(tmp), storage_ix, storage)
  508. }
  509. } else {
  510. var previous_value byte = 8
  511. var i uint
  512. /* Complex Huffman Tree */
  513. storeStaticCodeLengthCode(storage_ix, storage)
  514. /* Actual RLE coding. */
  515. for i = 0; i < length; {
  516. var value byte = depth[i]
  517. var reps uint = 1
  518. var k uint
  519. for k = i + 1; k < length && depth[k] == value; k++ {
  520. reps++
  521. }
  522. i += reps
  523. if value == 0 {
  524. writeBits(uint(kZeroRepsDepth[reps]), kZeroRepsBits[reps], storage_ix, storage)
  525. } else {
  526. if previous_value != value {
  527. writeBits(uint(kCodeLengthDepth[value]), uint64(kCodeLengthBits[value]), storage_ix, storage)
  528. reps--
  529. }
  530. if reps < 3 {
  531. for reps != 0 {
  532. reps--
  533. writeBits(uint(kCodeLengthDepth[value]), uint64(kCodeLengthBits[value]), storage_ix, storage)
  534. }
  535. } else {
  536. reps -= 3
  537. writeBits(uint(kNonZeroRepsDepth[reps]), kNonZeroRepsBits[reps], storage_ix, storage)
  538. }
  539. previous_value = value
  540. }
  541. }
  542. }
  543. }
  544. func indexOf(v []byte, v_size uint, value byte) uint {
  545. var i uint = 0
  546. for ; i < v_size; i++ {
  547. if v[i] == value {
  548. return i
  549. }
  550. }
  551. return i
  552. }
  553. func moveToFront(v []byte, index uint) {
  554. var value byte = v[index]
  555. var i uint
  556. for i = index; i != 0; i-- {
  557. v[i] = v[i-1]
  558. }
  559. v[0] = value
  560. }
  561. func moveToFrontTransform(v_in []uint32, v_size uint, v_out []uint32) {
  562. var i uint
  563. var mtf [256]byte
  564. var max_value uint32
  565. if v_size == 0 {
  566. return
  567. }
  568. max_value = v_in[0]
  569. for i = 1; i < v_size; i++ {
  570. if v_in[i] > max_value {
  571. max_value = v_in[i]
  572. }
  573. }
  574. assert(max_value < 256)
  575. for i = 0; uint32(i) <= max_value; i++ {
  576. mtf[i] = byte(i)
  577. }
  578. {
  579. var mtf_size uint = uint(max_value + 1)
  580. for i = 0; i < v_size; i++ {
  581. var index uint = indexOf(mtf[:], mtf_size, byte(v_in[i]))
  582. assert(index < mtf_size)
  583. v_out[i] = uint32(index)
  584. moveToFront(mtf[:], index)
  585. }
  586. }
  587. }
  588. /* Finds runs of zeros in v[0..in_size) and replaces them with a prefix code of
  589. the run length plus extra bits (lower 9 bits is the prefix code and the rest
  590. are the extra bits). Non-zero values in v[] are shifted by
  591. *max_length_prefix. Will not create prefix codes bigger than the initial
  592. value of *max_run_length_prefix. The prefix code of run length L is simply
  593. Log2Floor(L) and the number of extra bits is the same as the prefix code. */
  594. func runLengthCodeZeros(in_size uint, v []uint32, out_size *uint, max_run_length_prefix *uint32) {
  595. var max_reps uint32 = 0
  596. var i uint
  597. var max_prefix uint32
  598. for i = 0; i < in_size; {
  599. var reps uint32 = 0
  600. for ; i < in_size && v[i] != 0; i++ {
  601. }
  602. for ; i < in_size && v[i] == 0; i++ {
  603. reps++
  604. }
  605. max_reps = brotli_max_uint32_t(reps, max_reps)
  606. }
  607. if max_reps > 0 {
  608. max_prefix = log2FloorNonZero(uint(max_reps))
  609. } else {
  610. max_prefix = 0
  611. }
  612. max_prefix = brotli_min_uint32_t(max_prefix, *max_run_length_prefix)
  613. *max_run_length_prefix = max_prefix
  614. *out_size = 0
  615. for i = 0; i < in_size; {
  616. assert(*out_size <= i)
  617. if v[i] != 0 {
  618. v[*out_size] = v[i] + *max_run_length_prefix
  619. i++
  620. (*out_size)++
  621. } else {
  622. var reps uint32 = 1
  623. var k uint
  624. for k = i + 1; k < in_size && v[k] == 0; k++ {
  625. reps++
  626. }
  627. i += uint(reps)
  628. for reps != 0 {
  629. if reps < 2<<max_prefix {
  630. var run_length_prefix uint32 = log2FloorNonZero(uint(reps))
  631. var extra_bits uint32 = reps - (1 << run_length_prefix)
  632. v[*out_size] = run_length_prefix + (extra_bits << 9)
  633. (*out_size)++
  634. break
  635. } else {
  636. var extra_bits uint32 = (1 << max_prefix) - 1
  637. v[*out_size] = max_prefix + (extra_bits << 9)
  638. reps -= (2 << max_prefix) - 1
  639. (*out_size)++
  640. }
  641. }
  642. }
  643. }
  644. }
  645. const symbolBits = 9
  646. var encodeContextMap_kSymbolMask uint32 = (1 << symbolBits) - 1
  647. func encodeContextMap(context_map []uint32, context_map_size uint, num_clusters uint, tree []huffmanTree, storage_ix *uint, storage []byte) {
  648. var i uint
  649. var rle_symbols []uint32
  650. var max_run_length_prefix uint32 = 6
  651. var num_rle_symbols uint = 0
  652. var histogram [maxContextMapSymbols]uint32
  653. var depths [maxContextMapSymbols]byte
  654. var bits [maxContextMapSymbols]uint16
  655. storeVarLenUint8(num_clusters-1, storage_ix, storage)
  656. if num_clusters == 1 {
  657. return
  658. }
  659. rle_symbols = make([]uint32, context_map_size)
  660. moveToFrontTransform(context_map, context_map_size, rle_symbols)
  661. runLengthCodeZeros(context_map_size, rle_symbols, &num_rle_symbols, &max_run_length_prefix)
  662. histogram = [maxContextMapSymbols]uint32{}
  663. for i = 0; i < num_rle_symbols; i++ {
  664. histogram[rle_symbols[i]&encodeContextMap_kSymbolMask]++
  665. }
  666. {
  667. var use_rle bool = (max_run_length_prefix > 0)
  668. writeSingleBit(use_rle, storage_ix, storage)
  669. if use_rle {
  670. writeBits(4, uint64(max_run_length_prefix)-1, storage_ix, storage)
  671. }
  672. }
  673. buildAndStoreHuffmanTree(histogram[:], uint(uint32(num_clusters)+max_run_length_prefix), uint(uint32(num_clusters)+max_run_length_prefix), tree, depths[:], bits[:], storage_ix, storage)
  674. for i = 0; i < num_rle_symbols; i++ {
  675. var rle_symbol uint32 = rle_symbols[i] & encodeContextMap_kSymbolMask
  676. var extra_bits_val uint32 = rle_symbols[i] >> symbolBits
  677. writeBits(uint(depths[rle_symbol]), uint64(bits[rle_symbol]), storage_ix, storage)
  678. if rle_symbol > 0 && rle_symbol <= max_run_length_prefix {
  679. writeBits(uint(rle_symbol), uint64(extra_bits_val), storage_ix, storage)
  680. }
  681. }
  682. writeBits(1, 1, storage_ix, storage) /* use move-to-front */
  683. rle_symbols = nil
  684. }
  685. /* Stores the block switch command with index block_ix to the bit stream. */
  686. func storeBlockSwitch(code *blockSplitCode, block_len uint32, block_type byte, is_first_block bool, storage_ix *uint, storage []byte) {
  687. var typecode uint = nextBlockTypeCode(&code.type_code_calculator, block_type)
  688. var lencode uint
  689. var len_nextra uint32
  690. var len_extra uint32
  691. if !is_first_block {
  692. writeBits(uint(code.type_depths[typecode]), uint64(code.type_bits[typecode]), storage_ix, storage)
  693. }
  694. getBlockLengthPrefixCode(block_len, &lencode, &len_nextra, &len_extra)
  695. writeBits(uint(code.length_depths[lencode]), uint64(code.length_bits[lencode]), storage_ix, storage)
  696. writeBits(uint(len_nextra), uint64(len_extra), storage_ix, storage)
  697. }
  698. /* Builds a BlockSplitCode data structure from the block split given by the
  699. vector of block types and block lengths and stores it to the bit stream. */
  700. func buildAndStoreBlockSplitCode(types []byte, lengths []uint32, num_blocks uint, num_types uint, tree []huffmanTree, code *blockSplitCode, storage_ix *uint, storage []byte) {
  701. var type_histo [maxBlockTypeSymbols]uint32
  702. var length_histo [numBlockLenSymbols]uint32
  703. var i uint
  704. var type_code_calculator blockTypeCodeCalculator
  705. for i := 0; i < int(num_types+2); i++ {
  706. type_histo[i] = 0
  707. }
  708. length_histo = [numBlockLenSymbols]uint32{}
  709. initBlockTypeCodeCalculator(&type_code_calculator)
  710. for i = 0; i < num_blocks; i++ {
  711. var type_code uint = nextBlockTypeCode(&type_code_calculator, types[i])
  712. if i != 0 {
  713. type_histo[type_code]++
  714. }
  715. length_histo[blockLengthPrefixCode(lengths[i])]++
  716. }
  717. storeVarLenUint8(num_types-1, storage_ix, storage)
  718. if num_types > 1 { /* TODO: else? could StoreBlockSwitch occur? */
  719. buildAndStoreHuffmanTree(type_histo[0:], num_types+2, num_types+2, tree, code.type_depths[0:], code.type_bits[0:], storage_ix, storage)
  720. buildAndStoreHuffmanTree(length_histo[0:], numBlockLenSymbols, numBlockLenSymbols, tree, code.length_depths[0:], code.length_bits[0:], storage_ix, storage)
  721. storeBlockSwitch(code, lengths[0], types[0], true, storage_ix, storage)
  722. }
  723. }
  724. /* Stores a context map where the histogram type is always the block type. */
  725. func storeTrivialContextMap(num_types uint, context_bits uint, tree []huffmanTree, storage_ix *uint, storage []byte) {
  726. storeVarLenUint8(num_types-1, storage_ix, storage)
  727. if num_types > 1 {
  728. var repeat_code uint = context_bits - 1
  729. var repeat_bits uint = (1 << repeat_code) - 1
  730. var alphabet_size uint = num_types + repeat_code
  731. var histogram [maxContextMapSymbols]uint32
  732. var depths [maxContextMapSymbols]byte
  733. var bits [maxContextMapSymbols]uint16
  734. var i uint
  735. for i := 0; i < int(alphabet_size); i++ {
  736. histogram[i] = 0
  737. }
  738. /* Write RLEMAX. */
  739. writeBits(1, 1, storage_ix, storage)
  740. writeBits(4, uint64(repeat_code)-1, storage_ix, storage)
  741. histogram[repeat_code] = uint32(num_types)
  742. histogram[0] = 1
  743. for i = context_bits; i < alphabet_size; i++ {
  744. histogram[i] = 1
  745. }
  746. buildAndStoreHuffmanTree(histogram[:], alphabet_size, alphabet_size, tree, depths[:], bits[:], storage_ix, storage)
  747. for i = 0; i < num_types; i++ {
  748. var tmp uint
  749. if i == 0 {
  750. tmp = 0
  751. } else {
  752. tmp = i + context_bits - 1
  753. }
  754. var code uint = tmp
  755. writeBits(uint(depths[code]), uint64(bits[code]), storage_ix, storage)
  756. writeBits(uint(depths[repeat_code]), uint64(bits[repeat_code]), storage_ix, storage)
  757. writeBits(repeat_code, uint64(repeat_bits), storage_ix, storage)
  758. }
  759. /* Write IMTF (inverse-move-to-front) bit. */
  760. writeBits(1, 1, storage_ix, storage)
  761. }
  762. }
  763. /* Manages the encoding of one block category (literal, command or distance). */
  764. type blockEncoder struct {
  765. histogram_length_ uint
  766. num_block_types_ uint
  767. block_types_ []byte
  768. block_lengths_ []uint32
  769. num_blocks_ uint
  770. block_split_code_ blockSplitCode
  771. block_ix_ uint
  772. block_len_ uint
  773. entropy_ix_ uint
  774. depths_ []byte
  775. bits_ []uint16
  776. }
  777. var blockEncoderPool sync.Pool
  778. func getBlockEncoder(histogram_length uint, num_block_types uint, block_types []byte, block_lengths []uint32, num_blocks uint) *blockEncoder {
  779. self, _ := blockEncoderPool.Get().(*blockEncoder)
  780. if self != nil {
  781. self.block_ix_ = 0
  782. self.entropy_ix_ = 0
  783. self.depths_ = self.depths_[:0]
  784. self.bits_ = self.bits_[:0]
  785. } else {
  786. self = &blockEncoder{}
  787. }
  788. self.histogram_length_ = histogram_length
  789. self.num_block_types_ = num_block_types
  790. self.block_types_ = block_types
  791. self.block_lengths_ = block_lengths
  792. self.num_blocks_ = num_blocks
  793. initBlockTypeCodeCalculator(&self.block_split_code_.type_code_calculator)
  794. if num_blocks == 0 {
  795. self.block_len_ = 0
  796. } else {
  797. self.block_len_ = uint(block_lengths[0])
  798. }
  799. return self
  800. }
  801. func cleanupBlockEncoder(self *blockEncoder) {
  802. blockEncoderPool.Put(self)
  803. }
  804. /* Creates entropy codes of block lengths and block types and stores them
  805. to the bit stream. */
  806. func buildAndStoreBlockSwitchEntropyCodes(self *blockEncoder, tree []huffmanTree, storage_ix *uint, storage []byte) {
  807. buildAndStoreBlockSplitCode(self.block_types_, self.block_lengths_, self.num_blocks_, self.num_block_types_, tree, &self.block_split_code_, storage_ix, storage)
  808. }
  809. /* Stores the next symbol with the entropy code of the current block type.
  810. Updates the block type and block length at block boundaries. */
  811. func storeSymbol(self *blockEncoder, symbol uint, storage_ix *uint, storage []byte) {
  812. if self.block_len_ == 0 {
  813. self.block_ix_++
  814. var block_ix uint = self.block_ix_
  815. var block_len uint32 = self.block_lengths_[block_ix]
  816. var block_type byte = self.block_types_[block_ix]
  817. self.block_len_ = uint(block_len)
  818. self.entropy_ix_ = uint(block_type) * self.histogram_length_
  819. storeBlockSwitch(&self.block_split_code_, block_len, block_type, false, storage_ix, storage)
  820. }
  821. self.block_len_--
  822. {
  823. var ix uint = self.entropy_ix_ + symbol
  824. writeBits(uint(self.depths_[ix]), uint64(self.bits_[ix]), storage_ix, storage)
  825. }
  826. }
  827. /* Stores the next symbol with the entropy code of the current block type and
  828. context value.
  829. Updates the block type and block length at block boundaries. */
  830. func storeSymbolWithContext(self *blockEncoder, symbol uint, context uint, context_map []uint32, storage_ix *uint, storage []byte, context_bits uint) {
  831. if self.block_len_ == 0 {
  832. self.block_ix_++
  833. var block_ix uint = self.block_ix_
  834. var block_len uint32 = self.block_lengths_[block_ix]
  835. var block_type byte = self.block_types_[block_ix]
  836. self.block_len_ = uint(block_len)
  837. self.entropy_ix_ = uint(block_type) << context_bits
  838. storeBlockSwitch(&self.block_split_code_, block_len, block_type, false, storage_ix, storage)
  839. }
  840. self.block_len_--
  841. {
  842. var histo_ix uint = uint(context_map[self.entropy_ix_+context])
  843. var ix uint = histo_ix*self.histogram_length_ + symbol
  844. writeBits(uint(self.depths_[ix]), uint64(self.bits_[ix]), storage_ix, storage)
  845. }
  846. }
  847. func buildAndStoreEntropyCodesLiteral(self *blockEncoder, histograms []histogramLiteral, histograms_size uint, alphabet_size uint, tree []huffmanTree, storage_ix *uint, storage []byte) {
  848. var table_size uint = histograms_size * self.histogram_length_
  849. if cap(self.depths_) < int(table_size) {
  850. self.depths_ = make([]byte, table_size)
  851. } else {
  852. self.depths_ = self.depths_[:table_size]
  853. }
  854. if cap(self.bits_) < int(table_size) {
  855. self.bits_ = make([]uint16, table_size)
  856. } else {
  857. self.bits_ = self.bits_[:table_size]
  858. }
  859. {
  860. var i uint
  861. for i = 0; i < histograms_size; i++ {
  862. var ix uint = i * self.histogram_length_
  863. buildAndStoreHuffmanTree(histograms[i].data_[0:], self.histogram_length_, alphabet_size, tree, self.depths_[ix:], self.bits_[ix:], storage_ix, storage)
  864. }
  865. }
  866. }
  867. func buildAndStoreEntropyCodesCommand(self *blockEncoder, histograms []histogramCommand, histograms_size uint, alphabet_size uint, tree []huffmanTree, storage_ix *uint, storage []byte) {
  868. var table_size uint = histograms_size * self.histogram_length_
  869. if cap(self.depths_) < int(table_size) {
  870. self.depths_ = make([]byte, table_size)
  871. } else {
  872. self.depths_ = self.depths_[:table_size]
  873. }
  874. if cap(self.bits_) < int(table_size) {
  875. self.bits_ = make([]uint16, table_size)
  876. } else {
  877. self.bits_ = self.bits_[:table_size]
  878. }
  879. {
  880. var i uint
  881. for i = 0; i < histograms_size; i++ {
  882. var ix uint = i * self.histogram_length_
  883. buildAndStoreHuffmanTree(histograms[i].data_[0:], self.histogram_length_, alphabet_size, tree, self.depths_[ix:], self.bits_[ix:], storage_ix, storage)
  884. }
  885. }
  886. }
  887. func buildAndStoreEntropyCodesDistance(self *blockEncoder, histograms []histogramDistance, histograms_size uint, alphabet_size uint, tree []huffmanTree, storage_ix *uint, storage []byte) {
  888. var table_size uint = histograms_size * self.histogram_length_
  889. if cap(self.depths_) < int(table_size) {
  890. self.depths_ = make([]byte, table_size)
  891. } else {
  892. self.depths_ = self.depths_[:table_size]
  893. }
  894. if cap(self.bits_) < int(table_size) {
  895. self.bits_ = make([]uint16, table_size)
  896. } else {
  897. self.bits_ = self.bits_[:table_size]
  898. }
  899. {
  900. var i uint
  901. for i = 0; i < histograms_size; i++ {
  902. var ix uint = i * self.histogram_length_
  903. buildAndStoreHuffmanTree(histograms[i].data_[0:], self.histogram_length_, alphabet_size, tree, self.depths_[ix:], self.bits_[ix:], storage_ix, storage)
  904. }
  905. }
  906. }
  907. func jumpToByteBoundary(storage_ix *uint, storage []byte) {
  908. *storage_ix = (*storage_ix + 7) &^ 7
  909. storage[*storage_ix>>3] = 0
  910. }
  911. func storeMetaBlock(input []byte, start_pos uint, length uint, mask uint, prev_byte byte, prev_byte2 byte, is_last bool, params *encoderParams, literal_context_mode int, commands []command, mb *metaBlockSplit, storage_ix *uint, storage []byte) {
  912. var pos uint = start_pos
  913. var i uint
  914. var num_distance_symbols uint32 = params.dist.alphabet_size
  915. var num_effective_distance_symbols uint32 = num_distance_symbols
  916. var tree []huffmanTree
  917. var literal_context_lut contextLUT = getContextLUT(literal_context_mode)
  918. var dist *distanceParams = &params.dist
  919. if params.large_window && num_effective_distance_symbols > numHistogramDistanceSymbols {
  920. num_effective_distance_symbols = numHistogramDistanceSymbols
  921. }
  922. storeCompressedMetaBlockHeader(is_last, length, storage_ix, storage)
  923. tree = make([]huffmanTree, maxHuffmanTreeSize)
  924. literal_enc := getBlockEncoder(numLiteralSymbols, mb.literal_split.num_types, mb.literal_split.types, mb.literal_split.lengths, mb.literal_split.num_blocks)
  925. command_enc := getBlockEncoder(numCommandSymbols, mb.command_split.num_types, mb.command_split.types, mb.command_split.lengths, mb.command_split.num_blocks)
  926. distance_enc := getBlockEncoder(uint(num_effective_distance_symbols), mb.distance_split.num_types, mb.distance_split.types, mb.distance_split.lengths, mb.distance_split.num_blocks)
  927. buildAndStoreBlockSwitchEntropyCodes(literal_enc, tree, storage_ix, storage)
  928. buildAndStoreBlockSwitchEntropyCodes(command_enc, tree, storage_ix, storage)
  929. buildAndStoreBlockSwitchEntropyCodes(distance_enc, tree, storage_ix, storage)
  930. writeBits(2, uint64(dist.distance_postfix_bits), storage_ix, storage)
  931. writeBits(4, uint64(dist.num_direct_distance_codes)>>dist.distance_postfix_bits, storage_ix, storage)
  932. for i = 0; i < mb.literal_split.num_types; i++ {
  933. writeBits(2, uint64(literal_context_mode), storage_ix, storage)
  934. }
  935. if mb.literal_context_map_size == 0 {
  936. storeTrivialContextMap(mb.literal_histograms_size, literalContextBits, tree, storage_ix, storage)
  937. } else {
  938. encodeContextMap(mb.literal_context_map, mb.literal_context_map_size, mb.literal_histograms_size, tree, storage_ix, storage)
  939. }
  940. if mb.distance_context_map_size == 0 {
  941. storeTrivialContextMap(mb.distance_histograms_size, distanceContextBits, tree, storage_ix, storage)
  942. } else {
  943. encodeContextMap(mb.distance_context_map, mb.distance_context_map_size, mb.distance_histograms_size, tree, storage_ix, storage)
  944. }
  945. buildAndStoreEntropyCodesLiteral(literal_enc, mb.literal_histograms, mb.literal_histograms_size, numLiteralSymbols, tree, storage_ix, storage)
  946. buildAndStoreEntropyCodesCommand(command_enc, mb.command_histograms, mb.command_histograms_size, numCommandSymbols, tree, storage_ix, storage)
  947. buildAndStoreEntropyCodesDistance(distance_enc, mb.distance_histograms, mb.distance_histograms_size, uint(num_distance_symbols), tree, storage_ix, storage)
  948. tree = nil
  949. for _, cmd := range commands {
  950. var cmd_code uint = uint(cmd.cmd_prefix_)
  951. storeSymbol(command_enc, cmd_code, storage_ix, storage)
  952. storeCommandExtra(&cmd, storage_ix, storage)
  953. if mb.literal_context_map_size == 0 {
  954. var j uint
  955. for j = uint(cmd.insert_len_); j != 0; j-- {
  956. storeSymbol(literal_enc, uint(input[pos&mask]), storage_ix, storage)
  957. pos++
  958. }
  959. } else {
  960. var j uint
  961. for j = uint(cmd.insert_len_); j != 0; j-- {
  962. var context uint = uint(getContext(prev_byte, prev_byte2, literal_context_lut))
  963. var literal byte = input[pos&mask]
  964. storeSymbolWithContext(literal_enc, uint(literal), context, mb.literal_context_map, storage_ix, storage, literalContextBits)
  965. prev_byte2 = prev_byte
  966. prev_byte = literal
  967. pos++
  968. }
  969. }
  970. pos += uint(commandCopyLen(&cmd))
  971. if commandCopyLen(&cmd) != 0 {
  972. prev_byte2 = input[(pos-2)&mask]
  973. prev_byte = input[(pos-1)&mask]
  974. if cmd.cmd_prefix_ >= 128 {
  975. var dist_code uint = uint(cmd.dist_prefix_) & 0x3FF
  976. var distnumextra uint32 = uint32(cmd.dist_prefix_) >> 10
  977. var distextra uint64 = uint64(cmd.dist_extra_)
  978. if mb.distance_context_map_size == 0 {
  979. storeSymbol(distance_enc, dist_code, storage_ix, storage)
  980. } else {
  981. var context uint = uint(commandDistanceContext(&cmd))
  982. storeSymbolWithContext(distance_enc, dist_code, context, mb.distance_context_map, storage_ix, storage, distanceContextBits)
  983. }
  984. writeBits(uint(distnumextra), distextra, storage_ix, storage)
  985. }
  986. }
  987. }
  988. cleanupBlockEncoder(distance_enc)
  989. cleanupBlockEncoder(command_enc)
  990. cleanupBlockEncoder(literal_enc)
  991. if is_last {
  992. jumpToByteBoundary(storage_ix, storage)
  993. }
  994. }
  995. func buildHistograms(input []byte, start_pos uint, mask uint, commands []command, lit_histo *histogramLiteral, cmd_histo *histogramCommand, dist_histo *histogramDistance) {
  996. var pos uint = start_pos
  997. for _, cmd := range commands {
  998. var j uint
  999. histogramAddCommand(cmd_histo, uint(cmd.cmd_prefix_))
  1000. for j = uint(cmd.insert_len_); j != 0; j-- {
  1001. histogramAddLiteral(lit_histo, uint(input[pos&mask]))
  1002. pos++
  1003. }
  1004. pos += uint(commandCopyLen(&cmd))
  1005. if commandCopyLen(&cmd) != 0 && cmd.cmd_prefix_ >= 128 {
  1006. histogramAddDistance(dist_histo, uint(cmd.dist_prefix_)&0x3FF)
  1007. }
  1008. }
  1009. }
  1010. func storeDataWithHuffmanCodes(input []byte, start_pos uint, mask uint, commands []command, lit_depth []byte, lit_bits []uint16, cmd_depth []byte, cmd_bits []uint16, dist_depth []byte, dist_bits []uint16, storage_ix *uint, storage []byte) {
  1011. var pos uint = start_pos
  1012. for _, cmd := range commands {
  1013. var cmd_code uint = uint(cmd.cmd_prefix_)
  1014. var j uint
  1015. writeBits(uint(cmd_depth[cmd_code]), uint64(cmd_bits[cmd_code]), storage_ix, storage)
  1016. storeCommandExtra(&cmd, storage_ix, storage)
  1017. for j = uint(cmd.insert_len_); j != 0; j-- {
  1018. var literal byte = input[pos&mask]
  1019. writeBits(uint(lit_depth[literal]), uint64(lit_bits[literal]), storage_ix, storage)
  1020. pos++
  1021. }
  1022. pos += uint(commandCopyLen(&cmd))
  1023. if commandCopyLen(&cmd) != 0 && cmd.cmd_prefix_ >= 128 {
  1024. var dist_code uint = uint(cmd.dist_prefix_) & 0x3FF
  1025. var distnumextra uint32 = uint32(cmd.dist_prefix_) >> 10
  1026. var distextra uint32 = cmd.dist_extra_
  1027. writeBits(uint(dist_depth[dist_code]), uint64(dist_bits[dist_code]), storage_ix, storage)
  1028. writeBits(uint(distnumextra), uint64(distextra), storage_ix, storage)
  1029. }
  1030. }
  1031. }
  1032. func storeMetaBlockTrivial(input []byte, start_pos uint, length uint, mask uint, is_last bool, params *encoderParams, commands []command, storage_ix *uint, storage []byte) {
  1033. var lit_histo histogramLiteral
  1034. var cmd_histo histogramCommand
  1035. var dist_histo histogramDistance
  1036. var lit_depth [numLiteralSymbols]byte
  1037. var lit_bits [numLiteralSymbols]uint16
  1038. var cmd_depth [numCommandSymbols]byte
  1039. var cmd_bits [numCommandSymbols]uint16
  1040. var dist_depth [maxSimpleDistanceAlphabetSize]byte
  1041. var dist_bits [maxSimpleDistanceAlphabetSize]uint16
  1042. var tree []huffmanTree
  1043. var num_distance_symbols uint32 = params.dist.alphabet_size
  1044. storeCompressedMetaBlockHeader(is_last, length, storage_ix, storage)
  1045. histogramClearLiteral(&lit_histo)
  1046. histogramClearCommand(&cmd_histo)
  1047. histogramClearDistance(&dist_histo)
  1048. buildHistograms(input, start_pos, mask, commands, &lit_histo, &cmd_histo, &dist_histo)
  1049. writeBits(13, 0, storage_ix, storage)
  1050. tree = make([]huffmanTree, maxHuffmanTreeSize)
  1051. buildAndStoreHuffmanTree(lit_histo.data_[:], numLiteralSymbols, numLiteralSymbols, tree, lit_depth[:], lit_bits[:], storage_ix, storage)
  1052. buildAndStoreHuffmanTree(cmd_histo.data_[:], numCommandSymbols, numCommandSymbols, tree, cmd_depth[:], cmd_bits[:], storage_ix, storage)
  1053. buildAndStoreHuffmanTree(dist_histo.data_[:], maxSimpleDistanceAlphabetSize, uint(num_distance_symbols), tree, dist_depth[:], dist_bits[:], storage_ix, storage)
  1054. tree = nil
  1055. storeDataWithHuffmanCodes(input, start_pos, mask, commands, lit_depth[:], lit_bits[:], cmd_depth[:], cmd_bits[:], dist_depth[:], dist_bits[:], storage_ix, storage)
  1056. if is_last {
  1057. jumpToByteBoundary(storage_ix, storage)
  1058. }
  1059. }
  1060. func storeMetaBlockFast(input []byte, start_pos uint, length uint, mask uint, is_last bool, params *encoderParams, commands []command, storage_ix *uint, storage []byte) {
  1061. var num_distance_symbols uint32 = params.dist.alphabet_size
  1062. var distance_alphabet_bits uint32 = log2FloorNonZero(uint(num_distance_symbols-1)) + 1
  1063. storeCompressedMetaBlockHeader(is_last, length, storage_ix, storage)
  1064. writeBits(13, 0, storage_ix, storage)
  1065. if len(commands) <= 128 {
  1066. var histogram = [numLiteralSymbols]uint32{0}
  1067. var pos uint = start_pos
  1068. var num_literals uint = 0
  1069. var lit_depth [numLiteralSymbols]byte
  1070. var lit_bits [numLiteralSymbols]uint16
  1071. for _, cmd := range commands {
  1072. var j uint
  1073. for j = uint(cmd.insert_len_); j != 0; j-- {
  1074. histogram[input[pos&mask]]++
  1075. pos++
  1076. }
  1077. num_literals += uint(cmd.insert_len_)
  1078. pos += uint(commandCopyLen(&cmd))
  1079. }
  1080. buildAndStoreHuffmanTreeFast(histogram[:], num_literals, /* max_bits = */
  1081. 8, lit_depth[:], lit_bits[:], storage_ix, storage)
  1082. storeStaticCommandHuffmanTree(storage_ix, storage)
  1083. storeStaticDistanceHuffmanTree(storage_ix, storage)
  1084. storeDataWithHuffmanCodes(input, start_pos, mask, commands, lit_depth[:], lit_bits[:], kStaticCommandCodeDepth[:], kStaticCommandCodeBits[:], kStaticDistanceCodeDepth[:], kStaticDistanceCodeBits[:], storage_ix, storage)
  1085. } else {
  1086. var lit_histo histogramLiteral
  1087. var cmd_histo histogramCommand
  1088. var dist_histo histogramDistance
  1089. var lit_depth [numLiteralSymbols]byte
  1090. var lit_bits [numLiteralSymbols]uint16
  1091. var cmd_depth [numCommandSymbols]byte
  1092. var cmd_bits [numCommandSymbols]uint16
  1093. var dist_depth [maxSimpleDistanceAlphabetSize]byte
  1094. var dist_bits [maxSimpleDistanceAlphabetSize]uint16
  1095. histogramClearLiteral(&lit_histo)
  1096. histogramClearCommand(&cmd_histo)
  1097. histogramClearDistance(&dist_histo)
  1098. buildHistograms(input, start_pos, mask, commands, &lit_histo, &cmd_histo, &dist_histo)
  1099. buildAndStoreHuffmanTreeFast(lit_histo.data_[:], lit_histo.total_count_, /* max_bits = */
  1100. 8, lit_depth[:], lit_bits[:], storage_ix, storage)
  1101. buildAndStoreHuffmanTreeFast(cmd_histo.data_[:], cmd_histo.total_count_, /* max_bits = */
  1102. 10, cmd_depth[:], cmd_bits[:], storage_ix, storage)
  1103. buildAndStoreHuffmanTreeFast(dist_histo.data_[:], dist_histo.total_count_, /* max_bits = */
  1104. uint(distance_alphabet_bits), dist_depth[:], dist_bits[:], storage_ix, storage)
  1105. storeDataWithHuffmanCodes(input, start_pos, mask, commands, lit_depth[:], lit_bits[:], cmd_depth[:], cmd_bits[:], dist_depth[:], dist_bits[:], storage_ix, storage)
  1106. }
  1107. if is_last {
  1108. jumpToByteBoundary(storage_ix, storage)
  1109. }
  1110. }
  1111. /* This is for storing uncompressed blocks (simple raw storage of
  1112. bytes-as-bytes). */
  1113. func storeUncompressedMetaBlock(is_final_block bool, input []byte, position uint, mask uint, len uint, storage_ix *uint, storage []byte) {
  1114. var masked_pos uint = position & mask
  1115. storeUncompressedMetaBlockHeader(uint(len), storage_ix, storage)
  1116. jumpToByteBoundary(storage_ix, storage)
  1117. if masked_pos+len > mask+1 {
  1118. var len1 uint = mask + 1 - masked_pos
  1119. copy(storage[*storage_ix>>3:], input[masked_pos:][:len1])
  1120. *storage_ix += len1 << 3
  1121. len -= len1
  1122. masked_pos = 0
  1123. }
  1124. copy(storage[*storage_ix>>3:], input[masked_pos:][:len])
  1125. *storage_ix += uint(len << 3)
  1126. /* We need to clear the next 4 bytes to continue to be
  1127. compatible with BrotliWriteBits. */
  1128. writeBitsPrepareStorage(*storage_ix, storage)
  1129. /* Since the uncompressed block itself may not be the final block, add an
  1130. empty one after this. */
  1131. if is_final_block {
  1132. writeBits(1, 1, storage_ix, storage) /* islast */
  1133. writeBits(1, 1, storage_ix, storage) /* isempty */
  1134. jumpToByteBoundary(storage_ix, storage)
  1135. }
  1136. }