huffman_bit_writer.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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. "io"
  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. // bufferFlushSize indicates the buffer size
  19. // after which bytes are flushed to the writer.
  20. // Should preferably be a multiple of 6, since
  21. // we accumulate 6 bytes between writes to the buffer.
  22. bufferFlushSize = 240
  23. // bufferSize is the actual output byte buffer size.
  24. // It must have additional headroom for a flush
  25. // which can contain up to 8 bytes.
  26. bufferSize = bufferFlushSize + 8
  27. )
  28. // The number of extra bits needed by length code X - LENGTH_CODES_START.
  29. var lengthExtraBits = [32]int8{
  30. /* 257 */ 0, 0, 0,
  31. /* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
  32. /* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
  33. /* 280 */ 4, 5, 5, 5, 5, 0,
  34. }
  35. // The length indicated by length code X - LENGTH_CODES_START.
  36. var lengthBase = [32]uint8{
  37. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10,
  38. 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  39. 64, 80, 96, 112, 128, 160, 192, 224, 255,
  40. }
  41. // offset code word extra bits.
  42. var offsetExtraBits = [64]int8{
  43. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  44. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  45. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  46. /* extended window */
  47. 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20,
  48. }
  49. var offsetBase = [64]uint32{
  50. /* normal deflate */
  51. 0x000000, 0x000001, 0x000002, 0x000003, 0x000004,
  52. 0x000006, 0x000008, 0x00000c, 0x000010, 0x000018,
  53. 0x000020, 0x000030, 0x000040, 0x000060, 0x000080,
  54. 0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300,
  55. 0x000400, 0x000600, 0x000800, 0x000c00, 0x001000,
  56. 0x001800, 0x002000, 0x003000, 0x004000, 0x006000,
  57. /* extended window */
  58. 0x008000, 0x00c000, 0x010000, 0x018000, 0x020000,
  59. 0x030000, 0x040000, 0x060000, 0x080000, 0x0c0000,
  60. 0x100000, 0x180000, 0x200000, 0x300000,
  61. }
  62. // The odd order in which the codegen code sizes are written.
  63. var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
  64. type huffmanBitWriter struct {
  65. // writer is the underlying writer.
  66. // Do not use it directly; use the write method, which ensures
  67. // that Write errors are sticky.
  68. writer io.Writer
  69. // Data waiting to be written is bytes[0:nbytes]
  70. // and then the low nbits of bits.
  71. bits uint64
  72. nbits uint16
  73. nbytes uint8
  74. literalEncoding *huffmanEncoder
  75. offsetEncoding *huffmanEncoder
  76. codegenEncoding *huffmanEncoder
  77. err error
  78. lastHeader int
  79. // Set between 0 (reused block can be up to 2x the size)
  80. logNewTablePenalty uint
  81. lastHuffMan bool
  82. bytes [256]byte
  83. literalFreq [lengthCodesStart + 32]uint16
  84. offsetFreq [32]uint16
  85. codegenFreq [codegenCodeCount]uint16
  86. // codegen must have an extra space for the final symbol.
  87. codegen [literalCount + offsetCodeCount + 1]uint8
  88. }
  89. // Huffman reuse.
  90. //
  91. // The huffmanBitWriter supports reusing huffman tables and thereby combining block sections.
  92. //
  93. // This is controlled by several variables:
  94. //
  95. // If lastHeader is non-zero the Huffman table can be reused.
  96. // This also indicates that a Huffman table has been generated that can output all
  97. // possible symbols.
  98. // It also indicates that an EOB has not yet been emitted, so if a new tabel is generated
  99. // an EOB with the previous table must be written.
  100. //
  101. // If lastHuffMan is set, a table for outputting literals has been generated and offsets are invalid.
  102. //
  103. // An incoming block estimates the output size of a new table using a 'fresh' by calculating the
  104. // optimal size and adding a penalty in 'logNewTablePenalty'.
  105. // A Huffman table is not optimal, which is why we add a penalty, and generating a new table
  106. // is slower both for compression and decompression.
  107. func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter {
  108. return &huffmanBitWriter{
  109. writer: w,
  110. literalEncoding: newHuffmanEncoder(literalCount),
  111. codegenEncoding: newHuffmanEncoder(codegenCodeCount),
  112. offsetEncoding: newHuffmanEncoder(offsetCodeCount),
  113. }
  114. }
  115. func (w *huffmanBitWriter) reset(writer io.Writer) {
  116. w.writer = writer
  117. w.bits, w.nbits, w.nbytes, w.err = 0, 0, 0, nil
  118. w.lastHeader = 0
  119. w.lastHuffMan = false
  120. }
  121. func (w *huffmanBitWriter) canReuse(t *tokens) (offsets, lits bool) {
  122. offsets, lits = true, true
  123. a := t.offHist[:offsetCodeCount]
  124. b := w.offsetFreq[:len(a)]
  125. for i := range a {
  126. if b[i] == 0 && a[i] != 0 {
  127. offsets = false
  128. break
  129. }
  130. }
  131. a = t.extraHist[:literalCount-256]
  132. b = w.literalFreq[256:literalCount]
  133. b = b[:len(a)]
  134. for i := range a {
  135. if b[i] == 0 && a[i] != 0 {
  136. lits = false
  137. break
  138. }
  139. }
  140. if lits {
  141. a = t.litHist[:]
  142. b = w.literalFreq[:len(a)]
  143. for i := range a {
  144. if b[i] == 0 && a[i] != 0 {
  145. lits = false
  146. break
  147. }
  148. }
  149. }
  150. return
  151. }
  152. func (w *huffmanBitWriter) flush() {
  153. if w.err != nil {
  154. w.nbits = 0
  155. return
  156. }
  157. if w.lastHeader > 0 {
  158. // We owe an EOB
  159. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  160. w.lastHeader = 0
  161. }
  162. n := w.nbytes
  163. for w.nbits != 0 {
  164. w.bytes[n] = byte(w.bits)
  165. w.bits >>= 8
  166. if w.nbits > 8 { // Avoid underflow
  167. w.nbits -= 8
  168. } else {
  169. w.nbits = 0
  170. }
  171. n++
  172. }
  173. w.bits = 0
  174. w.write(w.bytes[:n])
  175. w.nbytes = 0
  176. }
  177. func (w *huffmanBitWriter) write(b []byte) {
  178. if w.err != nil {
  179. return
  180. }
  181. _, w.err = w.writer.Write(b)
  182. }
  183. func (w *huffmanBitWriter) writeBits(b int32, nb uint16) {
  184. w.bits |= uint64(b) << (w.nbits & 63)
  185. w.nbits += nb
  186. if w.nbits >= 48 {
  187. w.writeOutBits()
  188. }
  189. }
  190. func (w *huffmanBitWriter) writeBytes(bytes []byte) {
  191. if w.err != nil {
  192. return
  193. }
  194. n := w.nbytes
  195. if w.nbits&7 != 0 {
  196. w.err = InternalError("writeBytes with unfinished bits")
  197. return
  198. }
  199. for w.nbits != 0 {
  200. w.bytes[n] = byte(w.bits)
  201. w.bits >>= 8
  202. w.nbits -= 8
  203. n++
  204. }
  205. if n != 0 {
  206. w.write(w.bytes[:n])
  207. }
  208. w.nbytes = 0
  209. w.write(bytes)
  210. }
  211. // RFC 1951 3.2.7 specifies a special run-length encoding for specifying
  212. // the literal and offset lengths arrays (which are concatenated into a single
  213. // array). This method generates that run-length encoding.
  214. //
  215. // The result is written into the codegen array, and the frequencies
  216. // of each code is written into the codegenFreq array.
  217. // Codes 0-15 are single byte codes. Codes 16-18 are followed by additional
  218. // information. Code badCode is an end marker
  219. //
  220. // numLiterals The number of literals in literalEncoding
  221. // numOffsets The number of offsets in offsetEncoding
  222. // litenc, offenc The literal and offset encoder to use
  223. func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litEnc, offEnc *huffmanEncoder) {
  224. for i := range w.codegenFreq {
  225. w.codegenFreq[i] = 0
  226. }
  227. // Note that we are using codegen both as a temporary variable for holding
  228. // a copy of the frequencies, and as the place where we put the result.
  229. // This is fine because the output is always shorter than the input used
  230. // so far.
  231. codegen := w.codegen[:] // cache
  232. // Copy the concatenated code sizes to codegen. Put a marker at the end.
  233. cgnl := codegen[:numLiterals]
  234. for i := range cgnl {
  235. cgnl[i] = uint8(litEnc.codes[i].len)
  236. }
  237. cgnl = codegen[numLiterals : numLiterals+numOffsets]
  238. for i := range cgnl {
  239. cgnl[i] = uint8(offEnc.codes[i].len)
  240. }
  241. codegen[numLiterals+numOffsets] = badCode
  242. size := codegen[0]
  243. count := 1
  244. outIndex := 0
  245. for inIndex := 1; size != badCode; inIndex++ {
  246. // INVARIANT: We have seen "count" copies of size that have not yet
  247. // had output generated for them.
  248. nextSize := codegen[inIndex]
  249. if nextSize == size {
  250. count++
  251. continue
  252. }
  253. // We need to generate codegen indicating "count" of size.
  254. if size != 0 {
  255. codegen[outIndex] = size
  256. outIndex++
  257. w.codegenFreq[size]++
  258. count--
  259. for count >= 3 {
  260. n := 6
  261. if n > count {
  262. n = count
  263. }
  264. codegen[outIndex] = 16
  265. outIndex++
  266. codegen[outIndex] = uint8(n - 3)
  267. outIndex++
  268. w.codegenFreq[16]++
  269. count -= n
  270. }
  271. } else {
  272. for count >= 11 {
  273. n := 138
  274. if n > count {
  275. n = count
  276. }
  277. codegen[outIndex] = 18
  278. outIndex++
  279. codegen[outIndex] = uint8(n - 11)
  280. outIndex++
  281. w.codegenFreq[18]++
  282. count -= n
  283. }
  284. if count >= 3 {
  285. // count >= 3 && count <= 10
  286. codegen[outIndex] = 17
  287. outIndex++
  288. codegen[outIndex] = uint8(count - 3)
  289. outIndex++
  290. w.codegenFreq[17]++
  291. count = 0
  292. }
  293. }
  294. count--
  295. for ; count >= 0; count-- {
  296. codegen[outIndex] = size
  297. outIndex++
  298. w.codegenFreq[size]++
  299. }
  300. // Set up invariant for next time through the loop.
  301. size = nextSize
  302. count = 1
  303. }
  304. // Marker indicating the end of the codegen.
  305. codegen[outIndex] = badCode
  306. }
  307. func (w *huffmanBitWriter) codegens() int {
  308. numCodegens := len(w.codegenFreq)
  309. for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
  310. numCodegens--
  311. }
  312. return numCodegens
  313. }
  314. func (w *huffmanBitWriter) headerSize() (size, numCodegens int) {
  315. numCodegens = len(w.codegenFreq)
  316. for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
  317. numCodegens--
  318. }
  319. return 3 + 5 + 5 + 4 + (3 * numCodegens) +
  320. w.codegenEncoding.bitLength(w.codegenFreq[:]) +
  321. int(w.codegenFreq[16])*2 +
  322. int(w.codegenFreq[17])*3 +
  323. int(w.codegenFreq[18])*7, numCodegens
  324. }
  325. // dynamicSize returns the size of dynamically encoded data in bits.
  326. func (w *huffmanBitWriter) dynamicReuseSize(litEnc, offEnc *huffmanEncoder) (size int) {
  327. size = litEnc.bitLength(w.literalFreq[:]) +
  328. offEnc.bitLength(w.offsetFreq[:])
  329. return size
  330. }
  331. // dynamicSize returns the size of dynamically encoded data in bits.
  332. func (w *huffmanBitWriter) dynamicSize(litEnc, offEnc *huffmanEncoder, extraBits int) (size, numCodegens int) {
  333. header, numCodegens := w.headerSize()
  334. size = header +
  335. litEnc.bitLength(w.literalFreq[:]) +
  336. offEnc.bitLength(w.offsetFreq[:]) +
  337. extraBits
  338. return size, numCodegens
  339. }
  340. // extraBitSize will return the number of bits that will be written
  341. // as "extra" bits on matches.
  342. func (w *huffmanBitWriter) extraBitSize() int {
  343. total := 0
  344. for i, n := range w.literalFreq[257:literalCount] {
  345. total += int(n) * int(lengthExtraBits[i&31])
  346. }
  347. for i, n := range w.offsetFreq[:offsetCodeCount] {
  348. total += int(n) * int(offsetExtraBits[i&31])
  349. }
  350. return total
  351. }
  352. // fixedSize returns the size of dynamically encoded data in bits.
  353. func (w *huffmanBitWriter) fixedSize(extraBits int) int {
  354. return 3 +
  355. fixedLiteralEncoding.bitLength(w.literalFreq[:]) +
  356. fixedOffsetEncoding.bitLength(w.offsetFreq[:]) +
  357. extraBits
  358. }
  359. // storedSize calculates the stored size, including header.
  360. // The function returns the size in bits and whether the block
  361. // fits inside a single block.
  362. func (w *huffmanBitWriter) storedSize(in []byte) (int, bool) {
  363. if in == nil {
  364. return 0, false
  365. }
  366. if len(in) <= maxStoreBlockSize {
  367. return (len(in) + 5) * 8, true
  368. }
  369. return 0, false
  370. }
  371. func (w *huffmanBitWriter) writeCode(c hcode) {
  372. // The function does not get inlined if we "& 63" the shift.
  373. w.bits |= uint64(c.code) << w.nbits
  374. w.nbits += c.len
  375. if w.nbits >= 48 {
  376. w.writeOutBits()
  377. }
  378. }
  379. // writeOutBits will write bits to the buffer.
  380. func (w *huffmanBitWriter) writeOutBits() {
  381. bits := w.bits
  382. w.bits >>= 48
  383. w.nbits -= 48
  384. n := w.nbytes
  385. w.bytes[n] = byte(bits)
  386. w.bytes[n+1] = byte(bits >> 8)
  387. w.bytes[n+2] = byte(bits >> 16)
  388. w.bytes[n+3] = byte(bits >> 24)
  389. w.bytes[n+4] = byte(bits >> 32)
  390. w.bytes[n+5] = byte(bits >> 40)
  391. n += 6
  392. if n >= bufferFlushSize {
  393. if w.err != nil {
  394. n = 0
  395. return
  396. }
  397. w.write(w.bytes[:n])
  398. n = 0
  399. }
  400. w.nbytes = n
  401. }
  402. // Write the header of a dynamic Huffman block to the output stream.
  403. //
  404. // numLiterals The number of literals specified in codegen
  405. // numOffsets The number of offsets specified in codegen
  406. // numCodegens The number of codegens used in codegen
  407. func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, numCodegens int, isEof bool) {
  408. if w.err != nil {
  409. return
  410. }
  411. var firstBits int32 = 4
  412. if isEof {
  413. firstBits = 5
  414. }
  415. w.writeBits(firstBits, 3)
  416. w.writeBits(int32(numLiterals-257), 5)
  417. w.writeBits(int32(numOffsets-1), 5)
  418. w.writeBits(int32(numCodegens-4), 4)
  419. for i := 0; i < numCodegens; i++ {
  420. value := uint(w.codegenEncoding.codes[codegenOrder[i]].len)
  421. w.writeBits(int32(value), 3)
  422. }
  423. i := 0
  424. for {
  425. var codeWord = uint32(w.codegen[i])
  426. i++
  427. if codeWord == badCode {
  428. break
  429. }
  430. w.writeCode(w.codegenEncoding.codes[codeWord])
  431. switch codeWord {
  432. case 16:
  433. w.writeBits(int32(w.codegen[i]), 2)
  434. i++
  435. case 17:
  436. w.writeBits(int32(w.codegen[i]), 3)
  437. i++
  438. case 18:
  439. w.writeBits(int32(w.codegen[i]), 7)
  440. i++
  441. }
  442. }
  443. }
  444. // writeStoredHeader will write a stored header.
  445. // If the stored block is only used for EOF,
  446. // it is replaced with a fixed huffman block.
  447. func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool) {
  448. if w.err != nil {
  449. return
  450. }
  451. if w.lastHeader > 0 {
  452. // We owe an EOB
  453. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  454. w.lastHeader = 0
  455. }
  456. // To write EOF, use a fixed encoding block. 10 bits instead of 5 bytes.
  457. if length == 0 && isEof {
  458. w.writeFixedHeader(isEof)
  459. // EOB: 7 bits, value: 0
  460. w.writeBits(0, 7)
  461. w.flush()
  462. return
  463. }
  464. var flag int32
  465. if isEof {
  466. flag = 1
  467. }
  468. w.writeBits(flag, 3)
  469. w.flush()
  470. w.writeBits(int32(length), 16)
  471. w.writeBits(int32(^uint16(length)), 16)
  472. }
  473. func (w *huffmanBitWriter) writeFixedHeader(isEof bool) {
  474. if w.err != nil {
  475. return
  476. }
  477. if w.lastHeader > 0 {
  478. // We owe an EOB
  479. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  480. w.lastHeader = 0
  481. }
  482. // Indicate that we are a fixed Huffman block
  483. var value int32 = 2
  484. if isEof {
  485. value = 3
  486. }
  487. w.writeBits(value, 3)
  488. }
  489. // writeBlock will write a block of tokens with the smallest encoding.
  490. // The original input can be supplied, and if the huffman encoded data
  491. // is larger than the original bytes, the data will be written as a
  492. // stored block.
  493. // If the input is nil, the tokens will always be Huffman encoded.
  494. func (w *huffmanBitWriter) writeBlock(tokens *tokens, eof bool, input []byte) {
  495. if w.err != nil {
  496. return
  497. }
  498. tokens.AddEOB()
  499. if w.lastHeader > 0 {
  500. // We owe an EOB
  501. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  502. w.lastHeader = 0
  503. }
  504. numLiterals, numOffsets := w.indexTokens(tokens, false)
  505. w.generate(tokens)
  506. var extraBits int
  507. storedSize, storable := w.storedSize(input)
  508. if storable {
  509. extraBits = w.extraBitSize()
  510. }
  511. // Figure out smallest code.
  512. // Fixed Huffman baseline.
  513. var literalEncoding = fixedLiteralEncoding
  514. var offsetEncoding = fixedOffsetEncoding
  515. var size = w.fixedSize(extraBits)
  516. // Dynamic Huffman?
  517. var numCodegens int
  518. // Generate codegen and codegenFrequencies, which indicates how to encode
  519. // the literalEncoding and the offsetEncoding.
  520. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
  521. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  522. dynamicSize, numCodegens := w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits)
  523. if dynamicSize < size {
  524. size = dynamicSize
  525. literalEncoding = w.literalEncoding
  526. offsetEncoding = w.offsetEncoding
  527. }
  528. // Stored bytes?
  529. if storable && storedSize < size {
  530. w.writeStoredHeader(len(input), eof)
  531. w.writeBytes(input)
  532. return
  533. }
  534. // Huffman.
  535. if literalEncoding == fixedLiteralEncoding {
  536. w.writeFixedHeader(eof)
  537. } else {
  538. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  539. }
  540. // Write the tokens.
  541. w.writeTokens(tokens.Slice(), literalEncoding.codes, offsetEncoding.codes)
  542. }
  543. // writeBlockDynamic encodes a block using a dynamic Huffman table.
  544. // This should be used if the symbols used have a disproportionate
  545. // histogram distribution.
  546. // If input is supplied and the compression savings are below 1/16th of the
  547. // input size the block is stored.
  548. func (w *huffmanBitWriter) writeBlockDynamic(tokens *tokens, eof bool, input []byte, sync bool) {
  549. if w.err != nil {
  550. return
  551. }
  552. sync = sync || eof
  553. if sync {
  554. tokens.AddEOB()
  555. }
  556. // We cannot reuse pure huffman table, and must mark as EOF.
  557. if (w.lastHuffMan || eof) && w.lastHeader > 0 {
  558. // We will not try to reuse.
  559. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  560. w.lastHeader = 0
  561. w.lastHuffMan = false
  562. }
  563. if !sync {
  564. tokens.Fill()
  565. }
  566. numLiterals, numOffsets := w.indexTokens(tokens, !sync)
  567. var size int
  568. // Check if we should reuse.
  569. if w.lastHeader > 0 {
  570. // Estimate size for using a new table.
  571. // Use the previous header size as the best estimate.
  572. newSize := w.lastHeader + tokens.EstimatedBits()
  573. newSize += newSize >> w.logNewTablePenalty
  574. // The estimated size is calculated as an optimal table.
  575. // We add a penalty to make it more realistic and re-use a bit more.
  576. reuseSize := w.dynamicReuseSize(w.literalEncoding, w.offsetEncoding) + w.extraBitSize()
  577. // Check if a new table is better.
  578. if newSize < reuseSize {
  579. // Write the EOB we owe.
  580. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  581. size = newSize
  582. w.lastHeader = 0
  583. } else {
  584. size = reuseSize
  585. }
  586. // Check if we get a reasonable size decrease.
  587. if ssize, storable := w.storedSize(input); storable && ssize < (size+size>>4) {
  588. w.writeStoredHeader(len(input), eof)
  589. w.writeBytes(input)
  590. w.lastHeader = 0
  591. return
  592. }
  593. }
  594. // We want a new block/table
  595. if w.lastHeader == 0 {
  596. w.generate(tokens)
  597. // Generate codegen and codegenFrequencies, which indicates how to encode
  598. // the literalEncoding and the offsetEncoding.
  599. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
  600. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  601. var numCodegens int
  602. size, numCodegens = w.dynamicSize(w.literalEncoding, w.offsetEncoding, w.extraBitSize())
  603. // Store bytes, if we don't get a reasonable improvement.
  604. if ssize, storable := w.storedSize(input); storable && ssize < (size+size>>4) {
  605. w.writeStoredHeader(len(input), eof)
  606. w.writeBytes(input)
  607. w.lastHeader = 0
  608. return
  609. }
  610. // Write Huffman table.
  611. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  612. w.lastHeader, _ = w.headerSize()
  613. w.lastHuffMan = false
  614. }
  615. if sync {
  616. w.lastHeader = 0
  617. }
  618. // Write the tokens.
  619. w.writeTokens(tokens.Slice(), w.literalEncoding.codes, w.offsetEncoding.codes)
  620. }
  621. // indexTokens indexes a slice of tokens, and updates
  622. // literalFreq and offsetFreq, and generates literalEncoding
  623. // and offsetEncoding.
  624. // The number of literal and offset tokens is returned.
  625. func (w *huffmanBitWriter) indexTokens(t *tokens, filled bool) (numLiterals, numOffsets int) {
  626. copy(w.literalFreq[:], t.litHist[:])
  627. copy(w.literalFreq[256:], t.extraHist[:])
  628. copy(w.offsetFreq[:], t.offHist[:offsetCodeCount])
  629. if t.n == 0 {
  630. return
  631. }
  632. if filled {
  633. return maxNumLit, maxNumDist
  634. }
  635. // get the number of literals
  636. numLiterals = len(w.literalFreq)
  637. for w.literalFreq[numLiterals-1] == 0 {
  638. numLiterals--
  639. }
  640. // get the number of offsets
  641. numOffsets = len(w.offsetFreq)
  642. for numOffsets > 0 && w.offsetFreq[numOffsets-1] == 0 {
  643. numOffsets--
  644. }
  645. if numOffsets == 0 {
  646. // We haven't found a single match. If we want to go with the dynamic encoding,
  647. // we should count at least one offset to be sure that the offset huffman tree could be encoded.
  648. w.offsetFreq[0] = 1
  649. numOffsets = 1
  650. }
  651. return
  652. }
  653. func (w *huffmanBitWriter) generate(t *tokens) {
  654. w.literalEncoding.generate(w.literalFreq[:literalCount], 15)
  655. w.offsetEncoding.generate(w.offsetFreq[:offsetCodeCount], 15)
  656. }
  657. // writeTokens writes a slice of tokens to the output.
  658. // codes for literal and offset encoding must be supplied.
  659. func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) {
  660. if w.err != nil {
  661. return
  662. }
  663. if len(tokens) == 0 {
  664. return
  665. }
  666. // Only last token should be endBlockMarker.
  667. var deferEOB bool
  668. if tokens[len(tokens)-1] == endBlockMarker {
  669. tokens = tokens[:len(tokens)-1]
  670. deferEOB = true
  671. }
  672. // Create slices up to the next power of two to avoid bounds checks.
  673. lits := leCodes[:256]
  674. offs := oeCodes[:32]
  675. lengths := leCodes[lengthCodesStart:]
  676. lengths = lengths[:32]
  677. for _, t := range tokens {
  678. if t < matchType {
  679. w.writeCode(lits[t.literal()])
  680. continue
  681. }
  682. // Write the length
  683. length := t.length()
  684. lengthCode := lengthCode(length)
  685. if false {
  686. w.writeCode(lengths[lengthCode&31])
  687. } else {
  688. // inlined
  689. c := lengths[lengthCode&31]
  690. w.bits |= uint64(c.code) << (w.nbits & 63)
  691. w.nbits += c.len
  692. if w.nbits >= 48 {
  693. w.writeOutBits()
  694. }
  695. }
  696. extraLengthBits := uint16(lengthExtraBits[lengthCode&31])
  697. if extraLengthBits > 0 {
  698. extraLength := int32(length - lengthBase[lengthCode&31])
  699. w.writeBits(extraLength, extraLengthBits)
  700. }
  701. // Write the offset
  702. offset := t.offset()
  703. offsetCode := offsetCode(offset)
  704. if false {
  705. w.writeCode(offs[offsetCode&31])
  706. } else {
  707. // inlined
  708. c := offs[offsetCode&31]
  709. w.bits |= uint64(c.code) << (w.nbits & 63)
  710. w.nbits += c.len
  711. if w.nbits >= 48 {
  712. w.writeOutBits()
  713. }
  714. }
  715. extraOffsetBits := uint16(offsetExtraBits[offsetCode&63])
  716. if extraOffsetBits > 0 {
  717. extraOffset := int32(offset - offsetBase[offsetCode&63])
  718. w.writeBits(extraOffset, extraOffsetBits)
  719. }
  720. }
  721. if deferEOB {
  722. w.writeCode(leCodes[endBlockMarker])
  723. }
  724. }
  725. // huffOffset is a static offset encoder used for huffman only encoding.
  726. // It can be reused since we will not be encoding offset values.
  727. var huffOffset *huffmanEncoder
  728. func init() {
  729. w := newHuffmanBitWriter(nil)
  730. w.offsetFreq[0] = 1
  731. huffOffset = newHuffmanEncoder(offsetCodeCount)
  732. huffOffset.generate(w.offsetFreq[:offsetCodeCount], 15)
  733. }
  734. // writeBlockHuff encodes a block of bytes as either
  735. // Huffman encoded literals or uncompressed bytes if the
  736. // results only gains very little from compression.
  737. func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
  738. if w.err != nil {
  739. return
  740. }
  741. // Clear histogram
  742. for i := range w.literalFreq[:] {
  743. w.literalFreq[i] = 0
  744. }
  745. if !w.lastHuffMan {
  746. for i := range w.offsetFreq[:] {
  747. w.offsetFreq[i] = 0
  748. }
  749. }
  750. // Add everything as literals
  751. // We have to estimate the header size.
  752. // Assume header is around 70 bytes:
  753. // https://stackoverflow.com/a/25454430
  754. const guessHeaderSizeBits = 70 * 8
  755. estBits, estExtra := histogramSize(input, w.literalFreq[:], !eof && !sync)
  756. estBits += w.lastHeader + 15
  757. if w.lastHeader == 0 {
  758. estBits += guessHeaderSizeBits
  759. }
  760. estBits += estBits >> w.logNewTablePenalty
  761. // Store bytes, if we don't get a reasonable improvement.
  762. ssize, storable := w.storedSize(input)
  763. if storable && ssize < estBits {
  764. w.writeStoredHeader(len(input), eof)
  765. w.writeBytes(input)
  766. return
  767. }
  768. if w.lastHeader > 0 {
  769. reuseSize := w.literalEncoding.bitLength(w.literalFreq[:256])
  770. estBits += estExtra
  771. if estBits < reuseSize {
  772. // We owe an EOB
  773. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  774. w.lastHeader = 0
  775. }
  776. }
  777. const numLiterals = endBlockMarker + 1
  778. const numOffsets = 1
  779. if w.lastHeader == 0 {
  780. w.literalFreq[endBlockMarker] = 1
  781. w.literalEncoding.generate(w.literalFreq[:numLiterals], 15)
  782. // Generate codegen and codegenFrequencies, which indicates how to encode
  783. // the literalEncoding and the offsetEncoding.
  784. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, huffOffset)
  785. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  786. numCodegens := w.codegens()
  787. // Huffman.
  788. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  789. w.lastHuffMan = true
  790. w.lastHeader, _ = w.headerSize()
  791. }
  792. encoding := w.literalEncoding.codes[:257]
  793. for _, t := range input {
  794. // Bitwriting inlined, ~30% speedup
  795. c := encoding[t]
  796. w.bits |= uint64(c.code) << ((w.nbits) & 63)
  797. w.nbits += c.len
  798. if w.nbits >= 48 {
  799. bits := w.bits
  800. w.bits >>= 48
  801. w.nbits -= 48
  802. n := w.nbytes
  803. w.bytes[n] = byte(bits)
  804. w.bytes[n+1] = byte(bits >> 8)
  805. w.bytes[n+2] = byte(bits >> 16)
  806. w.bytes[n+3] = byte(bits >> 24)
  807. w.bytes[n+4] = byte(bits >> 32)
  808. w.bytes[n+5] = byte(bits >> 40)
  809. n += 6
  810. if n >= bufferFlushSize {
  811. if w.err != nil {
  812. n = 0
  813. return
  814. }
  815. w.write(w.bytes[:n])
  816. n = 0
  817. }
  818. w.nbytes = n
  819. }
  820. }
  821. if eof || sync {
  822. w.writeCode(encoding[endBlockMarker])
  823. w.lastHeader = 0
  824. w.lastHuffMan = false
  825. }
  826. }