huffman_bit_writer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. "github.com/andybalholm/brotli/matchfinder"
  7. )
  8. const (
  9. // The largest offset code.
  10. offsetCodeCount = 30
  11. // The special code used to mark the end of a block.
  12. endBlockMarker = 256
  13. // The first length code.
  14. lengthCodesStart = 257
  15. // The number of codegen codes.
  16. codegenCodeCount = 19
  17. badCode = 255
  18. maxNumLit = 286
  19. maxStoreBlockSize = 65535
  20. baseMatchLength = 3 // The smallest match length per the RFC section 3.2.5
  21. baseMatchOffset = 1 // The smallest match offset
  22. )
  23. // The number of extra bits needed by length code X - LENGTH_CODES_START.
  24. var lengthExtraBits = []int8{
  25. /* 257 */ 0, 0, 0,
  26. /* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
  27. /* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
  28. /* 280 */ 4, 5, 5, 5, 5, 0,
  29. }
  30. // The length indicated by length code X - LENGTH_CODES_START.
  31. var lengthBase = []int{
  32. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10,
  33. 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  34. 64, 80, 96, 112, 128, 160, 192, 224, 255,
  35. }
  36. // offset code word extra bits.
  37. var offsetExtraBits = []int8{
  38. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  39. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  40. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  41. }
  42. var offsetBase = []int{
  43. 0x000000, 0x000001, 0x000002, 0x000003, 0x000004,
  44. 0x000006, 0x000008, 0x00000c, 0x000010, 0x000018,
  45. 0x000020, 0x000030, 0x000040, 0x000060, 0x000080,
  46. 0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300,
  47. 0x000400, 0x000600, 0x000800, 0x000c00, 0x001000,
  48. 0x001800, 0x002000, 0x003000, 0x004000, 0x006000,
  49. }
  50. // The odd order in which the codegen code sizes are written.
  51. var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
  52. type huffmanBitWriter struct {
  53. dst []byte
  54. // Data waiting to be written is the low nbits of bits.
  55. bits uint64
  56. nbits uint
  57. codegenFreq [codegenCodeCount]int32
  58. literalFreq []int32
  59. offsetFreq []int32
  60. codegen []uint8
  61. literalEncoding *huffmanEncoder
  62. offsetEncoding *huffmanEncoder
  63. codegenEncoding *huffmanEncoder
  64. }
  65. func NewEncoder() matchfinder.Encoder {
  66. return &huffmanBitWriter{
  67. literalFreq: make([]int32, maxNumLit),
  68. offsetFreq: make([]int32, offsetCodeCount),
  69. codegen: make([]uint8, maxNumLit+offsetCodeCount+1),
  70. literalEncoding: newHuffmanEncoder(maxNumLit),
  71. codegenEncoding: newHuffmanEncoder(codegenCodeCount),
  72. offsetEncoding: newHuffmanEncoder(offsetCodeCount),
  73. }
  74. }
  75. func (w *huffmanBitWriter) Reset() {
  76. w.bits, w.nbits = 0, 0
  77. }
  78. func (w *huffmanBitWriter) flush() {
  79. dst := w.dst
  80. for w.nbits != 0 {
  81. dst = append(dst, byte(w.bits))
  82. w.bits >>= 8
  83. if w.nbits > 8 { // Avoid underflow
  84. w.nbits -= 8
  85. } else {
  86. w.nbits = 0
  87. }
  88. }
  89. w.bits = 0
  90. w.dst = dst
  91. }
  92. func (w *huffmanBitWriter) writeBits(b int32, nb uint) {
  93. w.bits |= uint64(b) << w.nbits
  94. w.nbits += nb
  95. if w.nbits >= 48 {
  96. bits := w.bits
  97. w.bits >>= 48
  98. w.nbits -= 48
  99. w.dst = append(w.dst,
  100. byte(bits),
  101. byte(bits>>8),
  102. byte(bits>>16),
  103. byte(bits>>24),
  104. byte(bits>>32),
  105. byte(bits>>40),
  106. )
  107. }
  108. }
  109. func (w *huffmanBitWriter) writeBytes(bytes []byte) {
  110. if w.nbits&7 != 0 {
  111. panic("writeBytes with unfinished bits")
  112. }
  113. for w.nbits != 0 {
  114. w.dst = append(w.dst, byte(w.bits))
  115. w.bits >>= 8
  116. w.nbits -= 8
  117. }
  118. w.dst = append(w.dst, bytes...)
  119. }
  120. // RFC 1951 3.2.7 specifies a special run-length encoding for specifying
  121. // the literal and offset lengths arrays (which are concatenated into a single
  122. // array). This method generates that run-length encoding.
  123. //
  124. // The result is written into the codegen array, and the frequencies
  125. // of each code is written into the codegenFreq array.
  126. // Codes 0-15 are single byte codes. Codes 16-18 are followed by additional
  127. // information. Code badCode is an end marker
  128. //
  129. // numLiterals The number of literals in literalEncoding
  130. // numOffsets The number of offsets in offsetEncoding
  131. // litenc, offenc The literal and offset encoder to use
  132. func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litEnc, offEnc *huffmanEncoder) {
  133. for i := range w.codegenFreq {
  134. w.codegenFreq[i] = 0
  135. }
  136. // Note that we are using codegen both as a temporary variable for holding
  137. // a copy of the frequencies, and as the place where we put the result.
  138. // This is fine because the output is always shorter than the input used
  139. // so far.
  140. codegen := w.codegen // cache
  141. // Copy the concatenated code sizes to codegen. Put a marker at the end.
  142. cgnl := codegen[:numLiterals]
  143. for i := range cgnl {
  144. cgnl[i] = uint8(litEnc.codes[i].len)
  145. }
  146. cgnl = codegen[numLiterals : numLiterals+numOffsets]
  147. for i := range cgnl {
  148. cgnl[i] = uint8(offEnc.codes[i].len)
  149. }
  150. codegen[numLiterals+numOffsets] = badCode
  151. size := codegen[0]
  152. count := 1
  153. outIndex := 0
  154. for inIndex := 1; size != badCode; inIndex++ {
  155. // INVARIANT: We have seen "count" copies of size that have not yet
  156. // had output generated for them.
  157. nextSize := codegen[inIndex]
  158. if nextSize == size {
  159. count++
  160. continue
  161. }
  162. // We need to generate codegen indicating "count" of size.
  163. if size != 0 {
  164. codegen[outIndex] = size
  165. outIndex++
  166. w.codegenFreq[size]++
  167. count--
  168. for count >= 3 {
  169. n := 6
  170. if n > count {
  171. n = count
  172. }
  173. codegen[outIndex] = 16
  174. outIndex++
  175. codegen[outIndex] = uint8(n - 3)
  176. outIndex++
  177. w.codegenFreq[16]++
  178. count -= n
  179. }
  180. } else {
  181. for count >= 11 {
  182. n := 138
  183. if n > count {
  184. n = count
  185. }
  186. codegen[outIndex] = 18
  187. outIndex++
  188. codegen[outIndex] = uint8(n - 11)
  189. outIndex++
  190. w.codegenFreq[18]++
  191. count -= n
  192. }
  193. if count >= 3 {
  194. // count >= 3 && count <= 10
  195. codegen[outIndex] = 17
  196. outIndex++
  197. codegen[outIndex] = uint8(count - 3)
  198. outIndex++
  199. w.codegenFreq[17]++
  200. count = 0
  201. }
  202. }
  203. count--
  204. for ; count >= 0; count-- {
  205. codegen[outIndex] = size
  206. outIndex++
  207. w.codegenFreq[size]++
  208. }
  209. // Set up invariant for next time through the loop.
  210. size = nextSize
  211. count = 1
  212. }
  213. // Marker indicating the end of the codegen.
  214. codegen[outIndex] = badCode
  215. }
  216. // dynamicSize returns the size of dynamically encoded data in bits.
  217. func (w *huffmanBitWriter) dynamicSize(litEnc, offEnc *huffmanEncoder, extraBits int) (size, numCodegens int) {
  218. numCodegens = len(w.codegenFreq)
  219. for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
  220. numCodegens--
  221. }
  222. header := 3 + 5 + 5 + 4 + (3 * numCodegens) +
  223. w.codegenEncoding.bitLength(w.codegenFreq[:]) +
  224. int(w.codegenFreq[16])*2 +
  225. int(w.codegenFreq[17])*3 +
  226. int(w.codegenFreq[18])*7
  227. size = header +
  228. litEnc.bitLength(w.literalFreq) +
  229. offEnc.bitLength(w.offsetFreq) +
  230. extraBits
  231. return size, numCodegens
  232. }
  233. // fixedSize returns the size of dynamically encoded data in bits.
  234. func (w *huffmanBitWriter) fixedSize(extraBits int) int {
  235. return 3 +
  236. fixedLiteralEncoding.bitLength(w.literalFreq) +
  237. fixedOffsetEncoding.bitLength(w.offsetFreq) +
  238. extraBits
  239. }
  240. // storedSize calculates the stored size, including header.
  241. // The function returns the size in bits and whether the block
  242. // fits inside a single block.
  243. func (w *huffmanBitWriter) storedSize(in []byte) (int, bool) {
  244. if in == nil {
  245. return 0, false
  246. }
  247. if len(in) <= maxStoreBlockSize {
  248. return (len(in) + 5) * 8, true
  249. }
  250. return 0, false
  251. }
  252. func (w *huffmanBitWriter) writeCode(c hcode) {
  253. w.bits |= uint64(c.code) << w.nbits
  254. w.nbits += uint(c.len)
  255. if w.nbits >= 48 {
  256. bits := w.bits
  257. w.bits >>= 48
  258. w.nbits -= 48
  259. w.dst = append(w.dst,
  260. byte(bits),
  261. byte(bits>>8),
  262. byte(bits>>16),
  263. byte(bits>>24),
  264. byte(bits>>32),
  265. byte(bits>>40),
  266. )
  267. }
  268. }
  269. // Write the header of a dynamic Huffman block to the output stream.
  270. //
  271. // numLiterals The number of literals specified in codegen
  272. // numOffsets The number of offsets specified in codegen
  273. // numCodegens The number of codegens used in codegen
  274. func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, numCodegens int, isEof bool) {
  275. var firstBits int32 = 4
  276. if isEof {
  277. firstBits = 5
  278. }
  279. w.writeBits(firstBits, 3)
  280. w.writeBits(int32(numLiterals-257), 5)
  281. w.writeBits(int32(numOffsets-1), 5)
  282. w.writeBits(int32(numCodegens-4), 4)
  283. for i := 0; i < numCodegens; i++ {
  284. value := uint(w.codegenEncoding.codes[codegenOrder[i]].len)
  285. w.writeBits(int32(value), 3)
  286. }
  287. i := 0
  288. for {
  289. var codeWord int = int(w.codegen[i])
  290. i++
  291. if codeWord == badCode {
  292. break
  293. }
  294. w.writeCode(w.codegenEncoding.codes[uint32(codeWord)])
  295. switch codeWord {
  296. case 16:
  297. w.writeBits(int32(w.codegen[i]), 2)
  298. i++
  299. case 17:
  300. w.writeBits(int32(w.codegen[i]), 3)
  301. i++
  302. case 18:
  303. w.writeBits(int32(w.codegen[i]), 7)
  304. i++
  305. }
  306. }
  307. }
  308. func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool) {
  309. var flag int32
  310. if isEof {
  311. flag = 1
  312. }
  313. w.writeBits(flag, 3)
  314. w.flush()
  315. w.writeBits(int32(length), 16)
  316. w.writeBits(int32(^uint16(length)), 16)
  317. }
  318. func (w *huffmanBitWriter) writeFixedHeader(isEof bool) {
  319. // Indicate that we are a fixed Huffman block
  320. var value int32 = 2
  321. if isEof {
  322. value = 3
  323. }
  324. w.writeBits(value, 3)
  325. }
  326. // writeBlock will write a block of tokens with the smallest encoding.
  327. func (w *huffmanBitWriter) writeBlock(matches []matchfinder.Match, eof bool, input []byte) {
  328. numLiterals, numOffsets := w.makeStatistics(matches, input)
  329. var extraBits int
  330. storedSize, storable := w.storedSize(input)
  331. if storable {
  332. // We only bother calculating the costs of the extra bits required by
  333. // the length of offset fields (which will be the same for both fixed
  334. // and dynamic encoding), if we need to compare those two encodings
  335. // against stored encoding.
  336. for lengthCode := lengthCodesStart + 8; lengthCode < numLiterals; lengthCode++ {
  337. // First eight length codes have extra size = 0.
  338. extraBits += int(w.literalFreq[lengthCode]) * int(lengthExtraBits[lengthCode-lengthCodesStart])
  339. }
  340. for offsetCode := 4; offsetCode < numOffsets; offsetCode++ {
  341. // First four offset codes have extra size = 0.
  342. extraBits += int(w.offsetFreq[offsetCode]) * int(offsetExtraBits[offsetCode])
  343. }
  344. }
  345. // Figure out smallest code.
  346. // Fixed Huffman baseline.
  347. var literalEncoding = fixedLiteralEncoding
  348. var offsetEncoding = fixedOffsetEncoding
  349. var size = w.fixedSize(extraBits)
  350. // Dynamic Huffman?
  351. var numCodegens int
  352. // Generate codegen and codegenFrequencies, which indicates how to encode
  353. // the literalEncoding and the offsetEncoding.
  354. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
  355. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  356. dynamicSize, numCodegens := w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits)
  357. if dynamicSize < size {
  358. size = dynamicSize
  359. literalEncoding = w.literalEncoding
  360. offsetEncoding = w.offsetEncoding
  361. }
  362. // Stored bytes?
  363. if storable && storedSize < size {
  364. w.writeStoredHeader(len(input), eof)
  365. w.writeBytes(input)
  366. return
  367. }
  368. // Huffman.
  369. if literalEncoding == fixedLiteralEncoding {
  370. w.writeFixedHeader(eof)
  371. } else {
  372. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  373. }
  374. // Write the tokens.
  375. w.writeTokens(matches, input, literalEncoding.codes, offsetEncoding.codes)
  376. w.writeCode(literalEncoding.codes[endBlockMarker])
  377. }
  378. // makeStatistics indexes a slice of tokens, and updates
  379. // literalFreq and offsetFreq, and generates literalEncoding
  380. // and offsetEncoding.
  381. // The number of literal and offset tokens is returned.
  382. func (w *huffmanBitWriter) makeStatistics(matches []matchfinder.Match, input []byte) (numLiterals, numOffsets int) {
  383. for i := range w.literalFreq {
  384. w.literalFreq[i] = 0
  385. }
  386. for i := range w.offsetFreq {
  387. w.offsetFreq[i] = 0
  388. }
  389. pos := 0
  390. for _, m := range matches {
  391. for _, c := range input[pos : pos+m.Unmatched] {
  392. w.literalFreq[c]++
  393. }
  394. pos += m.Unmatched
  395. if m.Length == 0 {
  396. continue
  397. }
  398. w.literalFreq[lengthCodesStart+lengthCode(m.Length)]++
  399. w.offsetFreq[offsetCode(m.Distance)]++
  400. pos += m.Length
  401. }
  402. w.literalFreq[endBlockMarker]++
  403. // get the number of literals
  404. numLiterals = len(w.literalFreq)
  405. for w.literalFreq[numLiterals-1] == 0 {
  406. numLiterals--
  407. }
  408. // get the number of offsets
  409. numOffsets = len(w.offsetFreq)
  410. for numOffsets > 0 && w.offsetFreq[numOffsets-1] == 0 {
  411. numOffsets--
  412. }
  413. if numOffsets == 0 {
  414. // We haven't found a single match. If we want to go with the dynamic encoding,
  415. // we should count at least one offset to be sure that the offset huffman tree could be encoded.
  416. w.offsetFreq[0] = 1
  417. numOffsets = 1
  418. }
  419. w.literalEncoding.generate(w.literalFreq, 15)
  420. w.offsetEncoding.generate(w.offsetFreq, 15)
  421. return
  422. }
  423. // writeTokens writes a slice of tokens to the output.
  424. // codes for literal and offset encoding must be supplied.
  425. func (w *huffmanBitWriter) writeTokens(matches []matchfinder.Match, input []byte, leCodes, oeCodes []hcode) {
  426. pos := 0
  427. for _, m := range matches {
  428. for _, c := range input[pos : pos+m.Unmatched] {
  429. w.writeCode(leCodes[c])
  430. }
  431. pos += m.Unmatched
  432. // Write the length
  433. length := m.Length
  434. if length == 0 {
  435. continue
  436. }
  437. lengthCode := lengthCode(length)
  438. w.writeCode(leCodes[lengthCode+lengthCodesStart])
  439. extraLengthBits := uint(lengthExtraBits[lengthCode])
  440. if extraLengthBits > 0 {
  441. extraLength := int32(length - baseMatchLength - lengthBase[lengthCode])
  442. w.writeBits(extraLength, extraLengthBits)
  443. }
  444. // Write the offset
  445. offset := m.Distance
  446. offsetCode := offsetCode(offset)
  447. w.writeCode(oeCodes[offsetCode])
  448. extraOffsetBits := uint(offsetExtraBits[offsetCode])
  449. if extraOffsetBits > 0 {
  450. extraOffset := int32(offset - baseMatchOffset - offsetBase[offsetCode])
  451. w.writeBits(extraOffset, extraOffsetBits)
  452. }
  453. pos += m.Length
  454. }
  455. }
  456. func (w *huffmanBitWriter) Encode(dst []byte, src []byte, matches []matchfinder.Match, lastBlock bool) []byte {
  457. w.dst = dst
  458. w.writeBlock(matches, lastBlock, src)
  459. if lastBlock {
  460. w.flush()
  461. }
  462. dst = w.dst
  463. w.dst = nil
  464. return dst
  465. }