1
2
3
4
5 package flate
6
7 import (
8 "math"
9 "math/bits"
10 "sort"
11 )
12
13
14 type hcode struct {
15 code, len uint16
16 }
17
18 type huffmanEncoder struct {
19 codes []hcode
20 freqcache []literalNode
21 bitCount [17]int32
22 lns byLiteral
23 lfs byFreq
24 }
25
26 type literalNode struct {
27 literal uint16
28 freq int32
29 }
30
31
32 type levelInfo struct {
33
34 level int32
35
36
37 lastFreq int32
38
39
40 nextCharFreq int32
41
42
43
44 nextPairFreq int32
45
46
47
48 needed int32
49 }
50
51
52 func (h *hcode) set(code uint16, length uint16) {
53 h.len = length
54 h.code = code
55 }
56
57 func maxNode() literalNode { return literalNode{math.MaxUint16, math.MaxInt32} }
58
59 func newHuffmanEncoder(size int) *huffmanEncoder {
60 return &huffmanEncoder{codes: make([]hcode, size)}
61 }
62
63
64 func generateFixedLiteralEncoding() *huffmanEncoder {
65 h := newHuffmanEncoder(maxNumLit)
66 codes := h.codes
67 var ch uint16
68 for ch = 0; ch < maxNumLit; ch++ {
69 var bits uint16
70 var size uint16
71 switch {
72 case ch < 144:
73
74 bits = ch + 48
75 size = 8
76 case ch < 256:
77
78 bits = ch + 400 - 144
79 size = 9
80 case ch < 280:
81
82 bits = ch - 256
83 size = 7
84 default:
85
86 bits = ch + 192 - 280
87 size = 8
88 }
89 codes[ch] = hcode{code: reverseBits(bits, byte(size)), len: size}
90 }
91 return h
92 }
93
94 func generateFixedOffsetEncoding() *huffmanEncoder {
95 h := newHuffmanEncoder(30)
96 codes := h.codes
97 for ch := range codes {
98 codes[ch] = hcode{code: reverseBits(uint16(ch), 5), len: 5}
99 }
100 return h
101 }
102
103 var fixedLiteralEncoding *huffmanEncoder = generateFixedLiteralEncoding()
104 var fixedOffsetEncoding *huffmanEncoder = generateFixedOffsetEncoding()
105
106 func (h *huffmanEncoder) bitLength(freq []int32) int {
107 var total int
108 for i, f := range freq {
109 if f != 0 {
110 total += int(f) * int(h.codes[i].len)
111 }
112 }
113 return total
114 }
115
116 const maxBitsLimit = 16
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132 func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
133 if maxBits >= maxBitsLimit {
134 panic("flate: maxBits too large")
135 }
136 n := int32(len(list))
137 list = list[0 : n+1]
138 list[n] = maxNode()
139
140
141
142 if maxBits > n-1 {
143 maxBits = n - 1
144 }
145
146
147
148
149
150 var levels [maxBitsLimit]levelInfo
151
152
153
154
155 var leafCounts [maxBitsLimit][maxBitsLimit]int32
156
157 for level := int32(1); level <= maxBits; level++ {
158
159
160 levels[level] = levelInfo{
161 level: level,
162 lastFreq: list[1].freq,
163 nextCharFreq: list[2].freq,
164 nextPairFreq: list[0].freq + list[1].freq,
165 }
166 leafCounts[level][level] = 2
167 if level == 1 {
168 levels[level].nextPairFreq = math.MaxInt32
169 }
170 }
171
172
173 levels[maxBits].needed = 2*n - 4
174
175 level := maxBits
176 for {
177 l := &levels[level]
178 if l.nextPairFreq == math.MaxInt32 && l.nextCharFreq == math.MaxInt32 {
179
180
181
182
183 l.needed = 0
184 levels[level+1].nextPairFreq = math.MaxInt32
185 level++
186 continue
187 }
188
189 prevFreq := l.lastFreq
190 if l.nextCharFreq < l.nextPairFreq {
191
192 n := leafCounts[level][level] + 1
193 l.lastFreq = l.nextCharFreq
194
195 leafCounts[level][level] = n
196 l.nextCharFreq = list[n].freq
197 } else {
198
199
200
201 l.lastFreq = l.nextPairFreq
202
203 copy(leafCounts[level][:level], leafCounts[level-1][:level])
204 levels[l.level-1].needed = 2
205 }
206
207 if l.needed--; l.needed == 0 {
208
209
210
211
212 if l.level == maxBits {
213
214 break
215 }
216 levels[l.level+1].nextPairFreq = prevFreq + l.lastFreq
217 level++
218 } else {
219
220 for levels[level-1].needed > 0 {
221 level--
222 }
223 }
224 }
225
226
227
228 if leafCounts[maxBits][maxBits] != n {
229 panic("leafCounts[maxBits][maxBits] != n")
230 }
231
232 bitCount := h.bitCount[:maxBits+1]
233 bits := 1
234 counts := &leafCounts[maxBits]
235 for level := maxBits; level > 0; level-- {
236
237
238 bitCount[bits] = counts[level] - counts[level-1]
239 bits++
240 }
241 return bitCount
242 }
243
244
245
246 func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) {
247 code := uint16(0)
248 for n, bits := range bitCount {
249 code <<= 1
250 if n == 0 || bits == 0 {
251 continue
252 }
253
254
255
256
257 chunk := list[len(list)-int(bits):]
258
259 h.lns.sort(chunk)
260 for _, node := range chunk {
261 h.codes[node.literal] = hcode{code: reverseBits(code, uint8(n)), len: uint16(n)}
262 code++
263 }
264 list = list[0 : len(list)-int(bits)]
265 }
266 }
267
268
269
270
271
272 func (h *huffmanEncoder) generate(freq []int32, maxBits int32) {
273 if h.freqcache == nil {
274
275
276
277 h.freqcache = make([]literalNode, maxNumLit+1)
278 }
279 list := h.freqcache[:len(freq)+1]
280
281 count := 0
282
283 for i, f := range freq {
284 if f != 0 {
285 list[count] = literalNode{uint16(i), f}
286 count++
287 } else {
288 h.codes[i].len = 0
289 }
290 }
291
292 list = list[:count]
293 if count <= 2 {
294
295
296 for i, node := range list {
297
298 h.codes[node.literal].set(uint16(i), 1)
299 }
300 return
301 }
302 h.lfs.sort(list)
303
304
305 bitCount := h.bitCounts(list, maxBits)
306
307 h.assignEncodingAndSize(bitCount, list)
308 }
309
310 type byLiteral []literalNode
311
312 func (s *byLiteral) sort(a []literalNode) {
313 *s = byLiteral(a)
314 sort.Sort(s)
315 }
316
317 func (s byLiteral) Len() int { return len(s) }
318
319 func (s byLiteral) Less(i, j int) bool {
320 return s[i].literal < s[j].literal
321 }
322
323 func (s byLiteral) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
324
325 type byFreq []literalNode
326
327 func (s *byFreq) sort(a []literalNode) {
328 *s = byFreq(a)
329 sort.Sort(s)
330 }
331
332 func (s byFreq) Len() int { return len(s) }
333
334 func (s byFreq) Less(i, j int) bool {
335 if s[i].freq == s[j].freq {
336 return s[i].literal < s[j].literal
337 }
338 return s[i].freq < s[j].freq
339 }
340
341 func (s byFreq) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
342
343 func reverseBits(number uint16, bitLength byte) uint16 {
344 return bits.Reverse16(number << (16 - bitLength))
345 }
346
View as plain text