huffman_code.go 11 KB

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