entropy_encode.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. package brotli
  2. import "math"
  3. /* Copyright 2010 Google Inc. All Rights Reserved.
  4. Distributed under MIT license.
  5. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  6. */
  7. /* Entropy encoding (Huffman) utilities. */
  8. /* A node of a Huffman tree. */
  9. type huffmanTree struct {
  10. total_count_ uint32
  11. index_left_ int16
  12. index_right_or_value_ int16
  13. }
  14. func initHuffmanTree(self *huffmanTree, count uint32, left int16, right int16) {
  15. self.total_count_ = count
  16. self.index_left_ = left
  17. self.index_right_or_value_ = right
  18. }
  19. /* Input size optimized Shell sort. */
  20. type huffmanTreeComparator func(huffmanTree, huffmanTree) bool
  21. var sortHuffmanTreeItems_gaps = []uint{132, 57, 23, 10, 4, 1}
  22. func sortHuffmanTreeItems(items []huffmanTree, n uint, comparator huffmanTreeComparator) {
  23. if n < 13 {
  24. /* Insertion sort. */
  25. var i uint
  26. for i = 1; i < n; i++ {
  27. var tmp huffmanTree = items[i]
  28. var k uint = i
  29. var j uint = i - 1
  30. for comparator(tmp, items[j]) {
  31. items[k] = items[j]
  32. k = j
  33. if j == 0 {
  34. break
  35. }
  36. j--
  37. }
  38. items[k] = tmp
  39. }
  40. return
  41. } else {
  42. var g int
  43. if n < 57 {
  44. g = 2
  45. } else {
  46. g = 0
  47. }
  48. for ; g < 6; g++ {
  49. var gap uint = sortHuffmanTreeItems_gaps[g]
  50. var i uint
  51. for i = gap; i < n; i++ {
  52. var j uint = i
  53. var tmp huffmanTree = items[i]
  54. for ; j >= gap && comparator(tmp, items[j-gap]); j -= gap {
  55. items[j] = items[j-gap]
  56. }
  57. items[j] = tmp
  58. }
  59. }
  60. }
  61. }
  62. /* Returns 1 if assignment of depths succeeded, otherwise 0. */
  63. func setDepth(p0 int, pool []huffmanTree, depth []byte, max_depth int) bool {
  64. var stack [16]int
  65. var level int = 0
  66. var p int = p0
  67. assert(max_depth <= 15)
  68. stack[0] = -1
  69. for {
  70. if pool[p].index_left_ >= 0 {
  71. level++
  72. if level > max_depth {
  73. return false
  74. }
  75. stack[level] = int(pool[p].index_right_or_value_)
  76. p = int(pool[p].index_left_)
  77. continue
  78. } else {
  79. depth[pool[p].index_right_or_value_] = byte(level)
  80. }
  81. for level >= 0 && stack[level] == -1 {
  82. level--
  83. }
  84. if level < 0 {
  85. return true
  86. }
  87. p = stack[level]
  88. stack[level] = -1
  89. }
  90. }
  91. /* Sort the root nodes, least popular first. */
  92. func sortHuffmanTree(v0 huffmanTree, v1 huffmanTree) bool {
  93. if v0.total_count_ != v1.total_count_ {
  94. return v0.total_count_ < v1.total_count_
  95. }
  96. return v0.index_right_or_value_ > v1.index_right_or_value_
  97. }
  98. /* This function will create a Huffman tree.
  99. The catch here is that the tree cannot be arbitrarily deep.
  100. Brotli specifies a maximum depth of 15 bits for "code trees"
  101. and 7 bits for "code length code trees."
  102. count_limit is the value that is to be faked as the minimum value
  103. and this minimum value is raised until the tree matches the
  104. maximum length requirement.
  105. This algorithm is not of excellent performance for very long data blocks,
  106. especially when population counts are longer than 2**tree_limit, but
  107. we are not planning to use this with extremely long blocks.
  108. See http://en.wikipedia.org/wiki/Huffman_coding */
  109. func createHuffmanTree(data []uint32, length uint, tree_limit int, tree []huffmanTree, depth []byte) {
  110. var count_limit uint32
  111. var sentinel huffmanTree
  112. initHuffmanTree(&sentinel, math.MaxUint32, -1, -1)
  113. /* For block sizes below 64 kB, we never need to do a second iteration
  114. of this loop. Probably all of our block sizes will be smaller than
  115. that, so this loop is mostly of academic interest. If we actually
  116. would need this, we would be better off with the Katajainen algorithm. */
  117. for count_limit = 1; ; count_limit *= 2 {
  118. var n uint = 0
  119. var i uint
  120. var j uint
  121. var k uint
  122. for i = length; i != 0; {
  123. i--
  124. if data[i] != 0 {
  125. var count uint32 = brotli_max_uint32_t(data[i], count_limit)
  126. initHuffmanTree(&tree[n], count, -1, int16(i))
  127. n++
  128. }
  129. }
  130. if n == 1 {
  131. depth[tree[0].index_right_or_value_] = 1 /* Only one element. */
  132. break
  133. }
  134. sortHuffmanTreeItems(tree, n, huffmanTreeComparator(sortHuffmanTree))
  135. /* The nodes are:
  136. [0, n): the sorted leaf nodes that we start with.
  137. [n]: we add a sentinel here.
  138. [n + 1, 2n): new parent nodes are added here, starting from
  139. (n+1). These are naturally in ascending order.
  140. [2n]: we add a sentinel at the end as well.
  141. There will be (2n+1) elements at the end. */
  142. tree[n] = sentinel
  143. tree[n+1] = sentinel
  144. i = 0 /* Points to the next leaf node. */
  145. j = n + 1 /* Points to the next non-leaf node. */
  146. for k = n - 1; k != 0; k-- {
  147. var left uint
  148. var right uint
  149. if tree[i].total_count_ <= tree[j].total_count_ {
  150. left = i
  151. i++
  152. } else {
  153. left = j
  154. j++
  155. }
  156. if tree[i].total_count_ <= tree[j].total_count_ {
  157. right = i
  158. i++
  159. } else {
  160. right = j
  161. j++
  162. }
  163. {
  164. /* The sentinel node becomes the parent node. */
  165. var j_end uint = 2*n - k
  166. tree[j_end].total_count_ = tree[left].total_count_ + tree[right].total_count_
  167. tree[j_end].index_left_ = int16(left)
  168. tree[j_end].index_right_or_value_ = int16(right)
  169. /* Add back the last sentinel node. */
  170. tree[j_end+1] = sentinel
  171. }
  172. }
  173. if setDepth(int(2*n-1), tree[0:], depth, tree_limit) {
  174. /* We need to pack the Huffman tree in tree_limit bits. If this was not
  175. successful, add fake entities to the lowest values and retry. */
  176. break
  177. }
  178. }
  179. }
  180. func reverse(v []byte, start uint, end uint) {
  181. end--
  182. for start < end {
  183. var tmp byte = v[start]
  184. v[start] = v[end]
  185. v[end] = tmp
  186. start++
  187. end--
  188. }
  189. }
  190. func writeHuffmanTreeRepetitions(previous_value byte, value byte, repetitions uint, tree_size *uint, tree []byte, extra_bits_data []byte) {
  191. assert(repetitions > 0)
  192. if previous_value != value {
  193. tree[*tree_size] = value
  194. extra_bits_data[*tree_size] = 0
  195. (*tree_size)++
  196. repetitions--
  197. }
  198. if repetitions == 7 {
  199. tree[*tree_size] = value
  200. extra_bits_data[*tree_size] = 0
  201. (*tree_size)++
  202. repetitions--
  203. }
  204. if repetitions < 3 {
  205. var i uint
  206. for i = 0; i < repetitions; i++ {
  207. tree[*tree_size] = value
  208. extra_bits_data[*tree_size] = 0
  209. (*tree_size)++
  210. }
  211. } else {
  212. var start uint = *tree_size
  213. repetitions -= 3
  214. for {
  215. tree[*tree_size] = repeatPreviousCodeLength
  216. extra_bits_data[*tree_size] = byte(repetitions & 0x3)
  217. (*tree_size)++
  218. repetitions >>= 2
  219. if repetitions == 0 {
  220. break
  221. }
  222. repetitions--
  223. }
  224. reverse(tree, start, *tree_size)
  225. reverse(extra_bits_data, start, *tree_size)
  226. }
  227. }
  228. func writeHuffmanTreeRepetitionsZeros(repetitions uint, tree_size *uint, tree []byte, extra_bits_data []byte) {
  229. if repetitions == 11 {
  230. tree[*tree_size] = 0
  231. extra_bits_data[*tree_size] = 0
  232. (*tree_size)++
  233. repetitions--
  234. }
  235. if repetitions < 3 {
  236. var i uint
  237. for i = 0; i < repetitions; i++ {
  238. tree[*tree_size] = 0
  239. extra_bits_data[*tree_size] = 0
  240. (*tree_size)++
  241. }
  242. } else {
  243. var start uint = *tree_size
  244. repetitions -= 3
  245. for {
  246. tree[*tree_size] = repeatZeroCodeLength
  247. extra_bits_data[*tree_size] = byte(repetitions & 0x7)
  248. (*tree_size)++
  249. repetitions >>= 3
  250. if repetitions == 0 {
  251. break
  252. }
  253. repetitions--
  254. }
  255. reverse(tree, start, *tree_size)
  256. reverse(extra_bits_data, start, *tree_size)
  257. }
  258. }
  259. /* Change the population counts in a way that the consequent
  260. Huffman tree compression, especially its RLE-part will be more
  261. likely to compress this data more efficiently.
  262. length contains the size of the histogram.
  263. counts contains the population counts.
  264. good_for_rle is a buffer of at least length size */
  265. func optimizeHuffmanCountsForRLE(length uint, counts []uint32, good_for_rle []byte) {
  266. var nonzero_count uint = 0
  267. var stride uint
  268. var limit uint
  269. var sum uint
  270. var streak_limit uint = 1240
  271. var i uint
  272. /* Let's make the Huffman code more compatible with RLE encoding. */
  273. for i = 0; i < length; i++ {
  274. if counts[i] != 0 {
  275. nonzero_count++
  276. }
  277. }
  278. if nonzero_count < 16 {
  279. return
  280. }
  281. for length != 0 && counts[length-1] == 0 {
  282. length--
  283. }
  284. if length == 0 {
  285. return /* All zeros. */
  286. }
  287. /* Now counts[0..length - 1] does not have trailing zeros. */
  288. {
  289. var nonzeros uint = 0
  290. var smallest_nonzero uint32 = 1 << 30
  291. for i = 0; i < length; i++ {
  292. if counts[i] != 0 {
  293. nonzeros++
  294. if smallest_nonzero > counts[i] {
  295. smallest_nonzero = counts[i]
  296. }
  297. }
  298. }
  299. if nonzeros < 5 {
  300. /* Small histogram will model it well. */
  301. return
  302. }
  303. if smallest_nonzero < 4 {
  304. var zeros uint = length - nonzeros
  305. if zeros < 6 {
  306. for i = 1; i < length-1; i++ {
  307. if counts[i-1] != 0 && counts[i] == 0 && counts[i+1] != 0 {
  308. counts[i] = 1
  309. }
  310. }
  311. }
  312. }
  313. if nonzeros < 28 {
  314. return
  315. }
  316. }
  317. /* 2) Let's mark all population counts that already can be encoded
  318. with an RLE code. */
  319. for i := 0; i < int(length); i++ {
  320. good_for_rle[i] = 0
  321. }
  322. {
  323. var symbol uint32 = counts[0]
  324. /* Let's not spoil any of the existing good RLE codes.
  325. Mark any seq of 0's that is longer as 5 as a good_for_rle.
  326. Mark any seq of non-0's that is longer as 7 as a good_for_rle. */
  327. var step uint = 0
  328. for i = 0; i <= length; i++ {
  329. if i == length || counts[i] != symbol {
  330. if (symbol == 0 && step >= 5) || (symbol != 0 && step >= 7) {
  331. var k uint
  332. for k = 0; k < step; k++ {
  333. good_for_rle[i-k-1] = 1
  334. }
  335. }
  336. step = 1
  337. if i != length {
  338. symbol = counts[i]
  339. }
  340. } else {
  341. step++
  342. }
  343. }
  344. }
  345. /* 3) Let's replace those population counts that lead to more RLE codes.
  346. Math here is in 24.8 fixed point representation. */
  347. stride = 0
  348. limit = uint(256*(counts[0]+counts[1]+counts[2])/3 + 420)
  349. sum = 0
  350. for i = 0; i <= length; i++ {
  351. if i == length || good_for_rle[i] != 0 || (i != 0 && good_for_rle[i-1] != 0) || (256*counts[i]-uint32(limit)+uint32(streak_limit)) >= uint32(2*streak_limit) {
  352. if stride >= 4 || (stride >= 3 && sum == 0) {
  353. var k uint
  354. var count uint = (sum + stride/2) / stride
  355. /* The stride must end, collapse what we have, if we have enough (4). */
  356. if count == 0 {
  357. count = 1
  358. }
  359. if sum == 0 {
  360. /* Don't make an all zeros stride to be upgraded to ones. */
  361. count = 0
  362. }
  363. for k = 0; k < stride; k++ {
  364. /* We don't want to change value at counts[i],
  365. that is already belonging to the next stride. Thus - 1. */
  366. counts[i-k-1] = uint32(count)
  367. }
  368. }
  369. stride = 0
  370. sum = 0
  371. if i < length-2 {
  372. /* All interesting strides have a count of at least 4, */
  373. /* at least when non-zeros. */
  374. limit = uint(256*(counts[i]+counts[i+1]+counts[i+2])/3 + 420)
  375. } else if i < length {
  376. limit = uint(256 * counts[i])
  377. } else {
  378. limit = 0
  379. }
  380. }
  381. stride++
  382. if i != length {
  383. sum += uint(counts[i])
  384. if stride >= 4 {
  385. limit = (256*sum + stride/2) / stride
  386. }
  387. if stride == 4 {
  388. limit += 120
  389. }
  390. }
  391. }
  392. }
  393. func decideOverRLEUse(depth []byte, length uint, use_rle_for_non_zero *bool, use_rle_for_zero *bool) {
  394. var total_reps_zero uint = 0
  395. var total_reps_non_zero uint = 0
  396. var count_reps_zero uint = 1
  397. var count_reps_non_zero uint = 1
  398. var i uint
  399. for i = 0; i < length; {
  400. var value byte = depth[i]
  401. var reps uint = 1
  402. var k uint
  403. for k = i + 1; k < length && depth[k] == value; k++ {
  404. reps++
  405. }
  406. if reps >= 3 && value == 0 {
  407. total_reps_zero += reps
  408. count_reps_zero++
  409. }
  410. if reps >= 4 && value != 0 {
  411. total_reps_non_zero += reps
  412. count_reps_non_zero++
  413. }
  414. i += reps
  415. }
  416. *use_rle_for_non_zero = total_reps_non_zero > count_reps_non_zero*2
  417. *use_rle_for_zero = total_reps_zero > count_reps_zero*2
  418. }
  419. /* Write a Huffman tree from bit depths into the bit-stream representation
  420. of a Huffman tree. The generated Huffman tree is to be compressed once
  421. more using a Huffman tree */
  422. func writeHuffmanTree(depth []byte, length uint, tree_size *uint, tree []byte, extra_bits_data []byte) {
  423. var previous_value byte = initialRepeatedCodeLength
  424. var i uint
  425. var use_rle_for_non_zero bool = false
  426. var use_rle_for_zero bool = false
  427. var new_length uint = length
  428. /* Throw away trailing zeros. */
  429. for i = 0; i < length; i++ {
  430. if depth[length-i-1] == 0 {
  431. new_length--
  432. } else {
  433. break
  434. }
  435. }
  436. /* First gather statistics on if it is a good idea to do RLE. */
  437. if length > 50 {
  438. /* Find RLE coding for longer codes.
  439. Shorter codes seem not to benefit from RLE. */
  440. decideOverRLEUse(depth, new_length, &use_rle_for_non_zero, &use_rle_for_zero)
  441. }
  442. /* Actual RLE coding. */
  443. for i = 0; i < new_length; {
  444. var value byte = depth[i]
  445. var reps uint = 1
  446. if (value != 0 && use_rle_for_non_zero) || (value == 0 && use_rle_for_zero) {
  447. var k uint
  448. for k = i + 1; k < new_length && depth[k] == value; k++ {
  449. reps++
  450. }
  451. }
  452. if value == 0 {
  453. writeHuffmanTreeRepetitionsZeros(reps, tree_size, tree, extra_bits_data)
  454. } else {
  455. writeHuffmanTreeRepetitions(previous_value, value, reps, tree_size, tree, extra_bits_data)
  456. previous_value = value
  457. }
  458. i += reps
  459. }
  460. }
  461. var reverseBits_kLut = [16]uint{
  462. 0x00,
  463. 0x08,
  464. 0x04,
  465. 0x0C,
  466. 0x02,
  467. 0x0A,
  468. 0x06,
  469. 0x0E,
  470. 0x01,
  471. 0x09,
  472. 0x05,
  473. 0x0D,
  474. 0x03,
  475. 0x0B,
  476. 0x07,
  477. 0x0F,
  478. }
  479. func reverseBits(num_bits uint, bits uint16) uint16 {
  480. var retval uint = reverseBits_kLut[bits&0x0F]
  481. var i uint
  482. for i = 4; i < num_bits; i += 4 {
  483. retval <<= 4
  484. bits = uint16(bits >> 4)
  485. retval |= reverseBits_kLut[bits&0x0F]
  486. }
  487. retval >>= ((0 - num_bits) & 0x03)
  488. return uint16(retval)
  489. }
  490. /* 0..15 are values for bits */
  491. const maxHuffmanBits = 16
  492. /* Get the actual bit values for a tree of bit depths. */
  493. func convertBitDepthsToSymbols(depth []byte, len uint, bits []uint16) {
  494. var bl_count = [maxHuffmanBits]uint16{0}
  495. var next_code [maxHuffmanBits]uint16
  496. var i uint
  497. /* In Brotli, all bit depths are [1..15]
  498. 0 bit depth means that the symbol does not exist. */
  499. var code int = 0
  500. for i = 0; i < len; i++ {
  501. bl_count[depth[i]]++
  502. }
  503. bl_count[0] = 0
  504. next_code[0] = 0
  505. for i = 1; i < maxHuffmanBits; i++ {
  506. code = (code + int(bl_count[i-1])) << 1
  507. next_code[i] = uint16(code)
  508. }
  509. for i = 0; i < len; i++ {
  510. if depth[i] != 0 {
  511. bits[i] = reverseBits(uint(depth[i]), next_code[depth[i]])
  512. next_code[depth[i]]++
  513. }
  514. }
  515. }