huffman_code.go 10 KB

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