Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

413 righe
11 KiB

  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. // and their associated frequencies. The array is in order of increasing
  145. // frequency, and has as its last element a special element with frequency
  146. // MaxInt32
  147. // maxBits The maximum number of bits that should be used to encode any literal.
  148. // Must be less than 16.
  149. // return An integer array in which array[i] indicates the number of literals
  150. // that should be encoded in i bits.
  151. func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
  152. if maxBits >= maxBitsLimit {
  153. panic("flate: maxBits too large")
  154. }
  155. n := int32(len(list))
  156. list = list[0 : n+1]
  157. list[n] = maxNode()
  158. // The tree can't have greater depth than n - 1, no matter what. This
  159. // saves a little bit of work in some small cases
  160. if maxBits > n-1 {
  161. maxBits = n - 1
  162. }
  163. // Create information about each of the levels.
  164. // A bogus "Level 0" whose sole purpose is so that
  165. // level1.prev.needed==0. This makes level1.nextPairFreq
  166. // be a legitimate value that never gets chosen.
  167. var levels [maxBitsLimit]levelInfo
  168. // leafCounts[i] counts the number of literals at the left
  169. // of ancestors of the rightmost node at level i.
  170. // leafCounts[i][j] is the number of literals at the left
  171. // of the level j ancestor.
  172. var leafCounts [maxBitsLimit][maxBitsLimit]int32
  173. // Descending to only have 1 bounds check.
  174. l2f := int32(list[2].freq)
  175. l1f := int32(list[1].freq)
  176. l0f := int32(list[0].freq) + int32(list[1].freq)
  177. for level := int32(1); level <= maxBits; level++ {
  178. // For every level, the first two items are the first two characters.
  179. // We initialize the levels as if we had already figured this out.
  180. levels[level] = levelInfo{
  181. level: level,
  182. lastFreq: l1f,
  183. nextCharFreq: l2f,
  184. nextPairFreq: l0f,
  185. }
  186. leafCounts[level][level] = 2
  187. if level == 1 {
  188. levels[level].nextPairFreq = math.MaxInt32
  189. }
  190. }
  191. // We need a total of 2*n - 2 items at top level and have already generated 2.
  192. levels[maxBits].needed = 2*n - 4
  193. level := uint32(maxBits)
  194. for level < 16 {
  195. l := &levels[level]
  196. if l.nextPairFreq == math.MaxInt32 && l.nextCharFreq == math.MaxInt32 {
  197. // We've run out of both leafs and pairs.
  198. // End all calculations for this level.
  199. // To make sure we never come back to this level or any lower level,
  200. // set nextPairFreq impossibly large.
  201. l.needed = 0
  202. levels[level+1].nextPairFreq = math.MaxInt32
  203. level++
  204. continue
  205. }
  206. prevFreq := l.lastFreq
  207. if l.nextCharFreq < l.nextPairFreq {
  208. // The next item on this row is a leaf node.
  209. n := leafCounts[level][level] + 1
  210. l.lastFreq = l.nextCharFreq
  211. // Lower leafCounts are the same of the previous node.
  212. leafCounts[level][level] = n
  213. e := list[n]
  214. if e.literal < math.MaxUint16 {
  215. l.nextCharFreq = int32(e.freq)
  216. } else {
  217. l.nextCharFreq = math.MaxInt32
  218. }
  219. } else {
  220. // The next item on this row is a pair from the previous row.
  221. // nextPairFreq isn't valid until we generate two
  222. // more values in the level below
  223. l.lastFreq = l.nextPairFreq
  224. // Take leaf counts from the lower level, except counts[level] remains the same.
  225. if true {
  226. save := leafCounts[level][level]
  227. leafCounts[level] = leafCounts[level-1]
  228. leafCounts[level][level] = save
  229. } else {
  230. copy(leafCounts[level][:level], leafCounts[level-1][:level])
  231. }
  232. levels[l.level-1].needed = 2
  233. }
  234. if l.needed--; l.needed == 0 {
  235. // We've done everything we need to do for this level.
  236. // Continue calculating one level up. Fill in nextPairFreq
  237. // of that level with the sum of the two nodes we've just calculated on
  238. // this level.
  239. if l.level == maxBits {
  240. // All done!
  241. break
  242. }
  243. levels[l.level+1].nextPairFreq = prevFreq + l.lastFreq
  244. level++
  245. } else {
  246. // If we stole from below, move down temporarily to replenish it.
  247. for levels[level-1].needed > 0 {
  248. level--
  249. }
  250. }
  251. }
  252. // Somethings is wrong if at the end, the top level is null or hasn't used
  253. // all of the leaves.
  254. if leafCounts[maxBits][maxBits] != n {
  255. panic("leafCounts[maxBits][maxBits] != n")
  256. }
  257. bitCount := h.bitCount[:maxBits+1]
  258. bits := 1
  259. counts := &leafCounts[maxBits]
  260. for level := maxBits; level > 0; level-- {
  261. // chain.leafCount gives the number of literals requiring at least "bits"
  262. // bits to encode.
  263. bitCount[bits] = counts[level] - counts[level-1]
  264. bits++
  265. }
  266. return bitCount
  267. }
  268. // Look at the leaves and assign them a bit count and an encoding as specified
  269. // in RFC 1951 3.2.2
  270. func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) {
  271. code := uint16(0)
  272. for n, bits := range bitCount {
  273. code <<= 1
  274. if n == 0 || bits == 0 {
  275. continue
  276. }
  277. // The literals list[len(list)-bits] .. list[len(list)-bits]
  278. // are encoded using "bits" bits, and get the values
  279. // code, code + 1, .... The code values are
  280. // assigned in literal order (not frequency order).
  281. chunk := list[len(list)-int(bits):]
  282. sortByLiteral(chunk)
  283. for _, node := range chunk {
  284. h.codes[node.literal] = newhcode(reverseBits(code, uint8(n)), uint8(n))
  285. code++
  286. }
  287. list = list[0 : len(list)-int(bits)]
  288. }
  289. }
  290. // Update this Huffman Code object to be the minimum code for the specified frequency count.
  291. //
  292. // freq An array of frequencies, in which frequency[i] gives the frequency of literal i.
  293. // maxBits The maximum number of bits to use for any literal.
  294. func (h *huffmanEncoder) generate(freq []uint16, maxBits int32) {
  295. list := h.freqcache[:len(freq)+1]
  296. codes := h.codes[:len(freq)]
  297. // Number of non-zero literals
  298. count := 0
  299. // Set list to be the set of all non-zero literals and their frequencies
  300. for i, f := range freq {
  301. if f != 0 {
  302. list[count] = literalNode{uint16(i), f}
  303. count++
  304. } else {
  305. codes[i] = 0
  306. }
  307. }
  308. list[count] = literalNode{}
  309. list = list[:count]
  310. if count <= 2 {
  311. // Handle the small cases here, because they are awkward for the general case code. With
  312. // two or fewer literals, everything has bit length 1.
  313. for i, node := range list {
  314. // "list" is in order of increasing literal value.
  315. h.codes[node.literal].set(uint16(i), 1)
  316. }
  317. return
  318. }
  319. sortByFreq(list)
  320. // Get the number of literals for each bit count
  321. bitCount := h.bitCounts(list, maxBits)
  322. // And do the assignment
  323. h.assignEncodingAndSize(bitCount, list)
  324. }
  325. // atLeastOne clamps the result between 1 and 15.
  326. func atLeastOne(v float32) float32 {
  327. if v < 1 {
  328. return 1
  329. }
  330. if v > 15 {
  331. return 15
  332. }
  333. return v
  334. }
  335. func histogram(b []byte, h []uint16) {
  336. if true && len(b) >= 8<<10 {
  337. // Split for bigger inputs
  338. histogramSplit(b, h)
  339. } else {
  340. h = h[:256]
  341. for _, t := range b {
  342. h[t]++
  343. }
  344. }
  345. }
  346. func histogramSplit(b []byte, h []uint16) {
  347. // Tested, and slightly faster than 2-way.
  348. // Writing to separate arrays and combining is also slightly slower.
  349. h = h[:256]
  350. for len(b)&3 != 0 {
  351. h[b[0]]++
  352. b = b[1:]
  353. }
  354. n := len(b) / 4
  355. x, y, z, w := b[:n], b[n:], b[n+n:], b[n+n+n:]
  356. y, z, w = y[:len(x)], z[:len(x)], w[:len(x)]
  357. for i, t := range x {
  358. v0 := &h[t]
  359. v1 := &h[y[i]]
  360. v3 := &h[w[i]]
  361. v2 := &h[z[i]]
  362. *v0++
  363. *v1++
  364. *v2++
  365. *v3++
  366. }
  367. }