brotli_bit_stream.go 47 KB

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