huffman_code.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package flate
  5. import (
  6. "math"
  7. "math/bits"
  8. "sort"
  9. )
  10. // hcode is a huffman code with a bit code and bit length.
  11. type hcode struct {
  12. code, len uint16
  13. }
  14. type huffmanEncoder struct {
  15. codes []hcode
  16. freqcache []literalNode
  17. bitCount [17]int32
  18. lns byLiteral // stored to avoid repeated allocation in generate
  19. lfs byFreq // stored to avoid repeated allocation in generate
  20. }
  21. type literalNode struct {
  22. literal uint16
  23. freq int32
  24. }
  25. // A levelInfo describes the state of the constructed tree for a given depth.
  26. type levelInfo struct {
  27. // Our level. for better printing
  28. level int32
  29. // The frequency of the last node at this level
  30. lastFreq int32
  31. // The frequency of the next character to add to this level
  32. nextCharFreq int32
  33. // The frequency of the next pair (from level below) to add to this level.
  34. // Only valid if the "needed" value of the next lower level is 0.
  35. nextPairFreq int32
  36. // The number of chains remaining to generate for this level before moving
  37. // up to the next level
  38. needed int32
  39. }
  40. // set sets the code and length of an hcode.
  41. func (h *hcode) set(code uint16, length uint16) {
  42. h.len = length
  43. h.code = code
  44. }
  45. func maxNode() literalNode { return literalNode{math.MaxUint16, math.MaxInt32} }
  46. func newHuffmanEncoder(size int) *huffmanEncoder {
  47. return &huffmanEncoder{codes: make([]hcode, size)}
  48. }
  49. // Generates a HuffmanCode corresponding to the fixed literal table
  50. func generateFixedLiteralEncoding() *huffmanEncoder {
  51. h := newHuffmanEncoder(maxNumLit)
  52. codes := h.codes
  53. var ch uint16
  54. for ch = 0; ch < maxNumLit; ch++ {
  55. var bits uint16
  56. var size uint16
  57. switch {
  58. case ch < 144:
  59. // size 8, 000110000 .. 10111111
  60. bits = ch + 48
  61. size = 8
  62. case ch < 256:
  63. // size 9, 110010000 .. 111111111
  64. bits = ch + 400 - 144
  65. size = 9
  66. case ch < 280:
  67. // size 7, 0000000 .. 0010111
  68. bits = ch - 256
  69. size = 7
  70. default:
  71. // size 8, 11000000 .. 11000111
  72. bits = ch + 192 - 280
  73. size = 8
  74. }
  75. codes[ch] = hcode{code: reverseBits(bits, byte(size)), len: size}
  76. }
  77. return h
  78. }
  79. func generateFixedOffsetEncoding() *huffmanEncoder {
  80. h := newHuffmanEncoder(30)
  81. codes := h.codes
  82. for ch := range codes {
  83. codes[ch] = hcode{code: reverseBits(uint16(ch), 5), len: 5}
  84. }
  85. return h
  86. }
  87. var fixedLiteralEncoding *huffmanEncoder = generateFixedLiteralEncoding()
  88. var fixedOffsetEncoding *huffmanEncoder = generateFixedOffsetEncoding()
  89. func (h *huffmanEncoder) bitLength(freq []int32) int {
  90. var total int
  91. for i, f := range freq {
  92. if f != 0 {
  93. total += int(f) * int(h.codes[i].len)
  94. }
  95. }
  96. return total
  97. }
  98. const maxBitsLimit = 16
  99. // Return the number of literals assigned to each bit size in the Huffman encoding
  100. //
  101. // This method is only called when list.length >= 3
  102. // The cases of 0, 1, and 2 literals are handled by special case code.
  103. //
  104. // list An array of the literals with non-zero frequencies
  105. // and their associated frequencies. The array is in order of increasing
  106. // frequency, and has as its last element a special element with frequency
  107. // MaxInt32
  108. // maxBits The maximum number of bits that should be used to encode any literal.
  109. // Must be less than 16.
  110. // return An integer array in which array[i] indicates the number of literals
  111. // that should be encoded in i bits.
  112. func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
  113. if maxBits >= maxBitsLimit {
  114. panic("flate: maxBits too large")
  115. }
  116. n := int32(len(list))
  117. list = list[0 : n+1]
  118. list[n] = maxNode()
  119. // The tree can't have greater depth than n - 1, no matter what. This
  120. // saves a little bit of work in some small cases
  121. if maxBits > n-1 {
  122. maxBits = n - 1
  123. }
  124. // Create information about each of the levels.
  125. // A bogus "Level 0" whose sole purpose is so that
  126. // level1.prev.needed==0. This makes level1.nextPairFreq
  127. // be a legitimate value that never gets chosen.
  128. var levels [maxBitsLimit]levelInfo
  129. // leafCounts[i] counts the number of literals at the left
  130. // of ancestors of the rightmost node at level i.
  131. // leafCounts[i][j] is the number of literals at the left
  132. // of the level j ancestor.
  133. var leafCounts [maxBitsLimit][maxBitsLimit]int32
  134. for level := int32(1); level <= maxBits; level++ {
  135. // For every level, the first two items are the first two characters.
  136. // We initialize the levels as if we had already figured this out.
  137. levels[level] = levelInfo{
  138. level: level,
  139. lastFreq: list[1].freq,
  140. nextCharFreq: list[2].freq,
  141. nextPairFreq: list[0].freq + list[1].freq,
  142. }
  143. leafCounts[level][level] = 2
  144. if level == 1 {
  145. levels[level].nextPairFreq = math.MaxInt32
  146. }
  147. }
  148. // We need a total of 2*n - 2 items at top level and have already generated 2.
  149. levels[maxBits].needed = 2*n - 4
  150. level := maxBits
  151. for {
  152. l := &levels[level]
  153. if l.nextPairFreq == math.MaxInt32 && l.nextCharFreq == math.MaxInt32 {
  154. // We've run out of both leafs and pairs.
  155. // End all calculations for this level.
  156. // To make sure we never come back to this level or any lower level,
  157. // set nextPairFreq impossibly large.
  158. l.needed = 0
  159. levels[level+1].nextPairFreq = math.MaxInt32
  160. level++
  161. continue
  162. }
  163. prevFreq := l.lastFreq
  164. if l.nextCharFreq < l.nextPairFreq {
  165. // The next item on this row is a leaf node.
  166. n := leafCounts[level][level] + 1
  167. l.lastFreq = l.nextCharFreq
  168. // Lower leafCounts are the same of the previous node.
  169. leafCounts[level][level] = n
  170. l.nextCharFreq = list[n].freq
  171. } else {
  172. // The next item on this row is a pair from the previous row.
  173. // nextPairFreq isn't valid until we generate two
  174. // more values in the level below
  175. l.lastFreq = l.nextPairFreq
  176. // Take leaf counts from the lower level, except counts[level] remains the same.
  177. copy(leafCounts[level][:level], leafCounts[level-1][:level])
  178. levels[l.level-1].needed = 2
  179. }
  180. if l.needed--; l.needed == 0 {
  181. // We've done everything we need to do for this level.
  182. // Continue calculating one level up. Fill in nextPairFreq
  183. // of that level with the sum of the two nodes we've just calculated on
  184. // this level.
  185. if l.level == maxBits {
  186. // All done!
  187. break
  188. }
  189. levels[l.level+1].nextPairFreq = prevFreq + l.lastFreq
  190. level++
  191. } else {
  192. // If we stole from below, move down temporarily to replenish it.
  193. for levels[level-1].needed > 0 {
  194. level--
  195. }
  196. }
  197. }
  198. // Somethings is wrong if at the end, the top level is null or hasn't used
  199. // all of the leaves.
  200. if leafCounts[maxBits][maxBits] != n {
  201. panic("leafCounts[maxBits][maxBits] != n")
  202. }
  203. bitCount := h.bitCount[:maxBits+1]
  204. bits := 1
  205. counts := &leafCounts[maxBits]
  206. for level := maxBits; level > 0; level-- {
  207. // chain.leafCount gives the number of literals requiring at least "bits"
  208. // bits to encode.
  209. bitCount[bits] = counts[level] - counts[level-1]
  210. bits++
  211. }
  212. return bitCount
  213. }
  214. // Look at the leaves and assign them a bit count and an encoding as specified
  215. // in RFC 1951 3.2.2
  216. func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) {
  217. code := uint16(0)
  218. for n, bits := range bitCount {
  219. code <<= 1
  220. if n == 0 || bits == 0 {
  221. continue
  222. }
  223. // The literals list[len(list)-bits] .. list[len(list)-bits]
  224. // are encoded using "bits" bits, and get the values
  225. // code, code + 1, .... The code values are
  226. // assigned in literal order (not frequency order).
  227. chunk := list[len(list)-int(bits):]
  228. h.lns.sort(chunk)
  229. for _, node := range chunk {
  230. h.codes[node.literal] = hcode{code: reverseBits(code, uint8(n)), len: uint16(n)}
  231. code++
  232. }
  233. list = list[0 : len(list)-int(bits)]
  234. }
  235. }
  236. // Update this Huffman Code object to be the minimum code for the specified frequency count.
  237. //
  238. // freq An array of frequencies, in which frequency[i] gives the frequency of literal i.
  239. // maxBits The maximum number of bits to use for any literal.
  240. func (h *huffmanEncoder) generate(freq []int32, maxBits int32) {
  241. if h.freqcache == nil {
  242. // Allocate a reusable buffer with the longest possible frequency table.
  243. // Possible lengths are codegenCodeCount, offsetCodeCount and maxNumLit.
  244. // The largest of these is maxNumLit, so we allocate for that case.
  245. h.freqcache = make([]literalNode, maxNumLit+1)
  246. }
  247. list := h.freqcache[:len(freq)+1]
  248. // Number of non-zero literals
  249. count := 0
  250. // Set list to be the set of all non-zero literals and their frequencies
  251. for i, f := range freq {
  252. if f != 0 {
  253. list[count] = literalNode{uint16(i), f}
  254. count++
  255. } else {
  256. list[count] = literalNode{}
  257. h.codes[i].len = 0
  258. }
  259. }
  260. list[len(freq)] = literalNode{}
  261. list = list[:count]
  262. if count <= 2 {
  263. // Handle the small cases here, because they are awkward for the general case code. With
  264. // two or fewer literals, everything has bit length 1.
  265. for i, node := range list {
  266. // "list" is in order of increasing literal value.
  267. h.codes[node.literal].set(uint16(i), 1)
  268. }
  269. return
  270. }
  271. h.lfs.sort(list)
  272. // Get the number of literals for each bit count
  273. bitCount := h.bitCounts(list, maxBits)
  274. // And do the assignment
  275. h.assignEncodingAndSize(bitCount, list)
  276. }
  277. type byLiteral []literalNode
  278. func (s *byLiteral) sort(a []literalNode) {
  279. *s = byLiteral(a)
  280. sort.Sort(s)
  281. }
  282. func (s byLiteral) Len() int { return len(s) }
  283. func (s byLiteral) Less(i, j int) bool {
  284. return s[i].literal < s[j].literal
  285. }
  286. func (s byLiteral) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  287. type byFreq []literalNode
  288. func (s *byFreq) sort(a []literalNode) {
  289. *s = byFreq(a)
  290. sort.Sort(s)
  291. }
  292. func (s byFreq) Len() int { return len(s) }
  293. func (s byFreq) Less(i, j int) bool {
  294. if s[i].freq == s[j].freq {
  295. return s[i].literal < s[j].literal
  296. }
  297. return s[i].freq < s[j].freq
  298. }
  299. func (s byFreq) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  300. func reverseBits(number uint16, bitLength byte) uint16 {
  301. return bits.Reverse16(number << (16 - bitLength))
  302. }