huffman_bit_writer.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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. "fmt"
  7. "io"
  8. "math"
  9. "github.com/klauspost/compress/internal/le"
  10. )
  11. const (
  12. // The largest offset code.
  13. offsetCodeCount = 30
  14. // The special code used to mark the end of a block.
  15. endBlockMarker = 256
  16. // The first length code.
  17. lengthCodesStart = 257
  18. // The number of codegen codes.
  19. codegenCodeCount = 19
  20. badCode = 255
  21. // maxPredefinedTokens is the maximum number of tokens
  22. // where we check if fixed size is smaller.
  23. maxPredefinedTokens = 250
  24. // bufferFlushSize indicates the buffer size
  25. // after which bytes are flushed to the writer.
  26. // Should preferably be a multiple of 6, since
  27. // we accumulate 6 bytes between writes to the buffer.
  28. bufferFlushSize = 246
  29. )
  30. // Minimum length code that emits bits.
  31. const lengthExtraBitsMinCode = 8
  32. // The number of extra bits needed by length code X - LENGTH_CODES_START.
  33. var lengthExtraBits = [32]uint8{
  34. /* 257 */ 0, 0, 0,
  35. /* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
  36. /* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
  37. /* 280 */ 4, 5, 5, 5, 5, 0,
  38. }
  39. // The length indicated by length code X - LENGTH_CODES_START.
  40. var lengthBase = [32]uint8{
  41. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10,
  42. 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  43. 64, 80, 96, 112, 128, 160, 192, 224, 255,
  44. }
  45. // Minimum offset code that emits bits.
  46. const offsetExtraBitsMinCode = 4
  47. // offset code word extra bits.
  48. var offsetExtraBits = [32]int8{
  49. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  50. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  51. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  52. /* extended window */
  53. 14, 14,
  54. }
  55. var offsetCombined = [32]uint32{}
  56. func init() {
  57. var offsetBase = [32]uint32{
  58. /* normal deflate */
  59. 0x000000, 0x000001, 0x000002, 0x000003, 0x000004,
  60. 0x000006, 0x000008, 0x00000c, 0x000010, 0x000018,
  61. 0x000020, 0x000030, 0x000040, 0x000060, 0x000080,
  62. 0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300,
  63. 0x000400, 0x000600, 0x000800, 0x000c00, 0x001000,
  64. 0x001800, 0x002000, 0x003000, 0x004000, 0x006000,
  65. /* extended window */
  66. 0x008000, 0x00c000,
  67. }
  68. for i := range offsetCombined[:] {
  69. // Don't use extended window values...
  70. if offsetExtraBits[i] == 0 || offsetBase[i] > 0x006000 {
  71. continue
  72. }
  73. offsetCombined[i] = uint32(offsetExtraBits[i]) | (offsetBase[i] << 8)
  74. }
  75. }
  76. // The odd order in which the codegen code sizes are written.
  77. var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
  78. type huffmanBitWriter struct {
  79. // writer is the underlying writer.
  80. // Do not use it directly; use the write method, which ensures
  81. // that Write errors are sticky.
  82. writer io.Writer
  83. // Data waiting to be written is bytes[0:nbytes]
  84. // and then the low nbits of bits.
  85. bits uint64
  86. nbits uint8
  87. nbytes uint8
  88. lastHuffMan bool
  89. literalEncoding *huffmanEncoder
  90. tmpLitEncoding *huffmanEncoder
  91. offsetEncoding *huffmanEncoder
  92. codegenEncoding *huffmanEncoder
  93. err error
  94. lastHeader int
  95. // Set between 0 (reused block can be up to 2x the size)
  96. logNewTablePenalty uint
  97. bytes [256 + 8]byte
  98. literalFreq [lengthCodesStart + 32]uint16
  99. offsetFreq [32]uint16
  100. codegenFreq [codegenCodeCount]uint16
  101. // codegen must have an extra space for the final symbol.
  102. codegen [literalCount + offsetCodeCount + 1]uint8
  103. }
  104. // Huffman reuse.
  105. //
  106. // The huffmanBitWriter supports reusing huffman tables and thereby combining block sections.
  107. //
  108. // This is controlled by several variables:
  109. //
  110. // If lastHeader is non-zero the Huffman table can be reused.
  111. // This also indicates that a Huffman table has been generated that can output all
  112. // possible symbols.
  113. // It also indicates that an EOB has not yet been emitted, so if a new tabel is generated
  114. // an EOB with the previous table must be written.
  115. //
  116. // If lastHuffMan is set, a table for outputting literals has been generated and offsets are invalid.
  117. //
  118. // An incoming block estimates the output size of a new table using a 'fresh' by calculating the
  119. // optimal size and adding a penalty in 'logNewTablePenalty'.
  120. // A Huffman table is not optimal, which is why we add a penalty, and generating a new table
  121. // is slower both for compression and decompression.
  122. func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter {
  123. return &huffmanBitWriter{
  124. writer: w,
  125. literalEncoding: newHuffmanEncoder(literalCount),
  126. tmpLitEncoding: newHuffmanEncoder(literalCount),
  127. codegenEncoding: newHuffmanEncoder(codegenCodeCount),
  128. offsetEncoding: newHuffmanEncoder(offsetCodeCount),
  129. }
  130. }
  131. func (w *huffmanBitWriter) reset(writer io.Writer) {
  132. w.writer = writer
  133. w.bits, w.nbits, w.nbytes, w.err = 0, 0, 0, nil
  134. w.lastHeader = 0
  135. w.lastHuffMan = false
  136. }
  137. func (w *huffmanBitWriter) canReuse(t *tokens) (ok bool) {
  138. a := t.offHist[:offsetCodeCount]
  139. b := w.offsetEncoding.codes
  140. b = b[:len(a)]
  141. for i, v := range a {
  142. if v != 0 && b[i].zero() {
  143. return false
  144. }
  145. }
  146. a = t.extraHist[:literalCount-256]
  147. b = w.literalEncoding.codes[256:literalCount]
  148. b = b[:len(a)]
  149. for i, v := range a {
  150. if v != 0 && b[i].zero() {
  151. return false
  152. }
  153. }
  154. a = t.litHist[:256]
  155. b = w.literalEncoding.codes[:len(a)]
  156. for i, v := range a {
  157. if v != 0 && b[i].zero() {
  158. return false
  159. }
  160. }
  161. return true
  162. }
  163. func (w *huffmanBitWriter) flush() {
  164. if w.err != nil {
  165. w.nbits = 0
  166. return
  167. }
  168. if w.lastHeader > 0 {
  169. // We owe an EOB
  170. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  171. w.lastHeader = 0
  172. }
  173. n := w.nbytes
  174. for w.nbits != 0 {
  175. w.bytes[n] = byte(w.bits)
  176. w.bits >>= 8
  177. if w.nbits > 8 { // Avoid underflow
  178. w.nbits -= 8
  179. } else {
  180. w.nbits = 0
  181. }
  182. n++
  183. }
  184. w.bits = 0
  185. if n > 0 {
  186. w.write(w.bytes[:n])
  187. }
  188. w.nbytes = 0
  189. }
  190. func (w *huffmanBitWriter) write(b []byte) {
  191. if w.err != nil {
  192. return
  193. }
  194. _, w.err = w.writer.Write(b)
  195. }
  196. func (w *huffmanBitWriter) writeBits(b int32, nb uint8) {
  197. w.bits |= uint64(b) << (w.nbits & 63)
  198. w.nbits += nb
  199. if w.nbits >= 48 {
  200. w.writeOutBits()
  201. }
  202. }
  203. func (w *huffmanBitWriter) writeBytes(bytes []byte) {
  204. if w.err != nil {
  205. return
  206. }
  207. n := w.nbytes
  208. if w.nbits&7 != 0 {
  209. w.err = InternalError("writeBytes with unfinished bits")
  210. return
  211. }
  212. for w.nbits != 0 {
  213. w.bytes[n] = byte(w.bits)
  214. w.bits >>= 8
  215. w.nbits -= 8
  216. n++
  217. }
  218. if n != 0 {
  219. w.write(w.bytes[:n])
  220. }
  221. w.nbytes = 0
  222. w.write(bytes)
  223. }
  224. // RFC 1951 3.2.7 specifies a special run-length encoding for specifying
  225. // the literal and offset lengths arrays (which are concatenated into a single
  226. // array). This method generates that run-length encoding.
  227. //
  228. // The result is written into the codegen array, and the frequencies
  229. // of each code is written into the codegenFreq array.
  230. // Codes 0-15 are single byte codes. Codes 16-18 are followed by additional
  231. // information. Code badCode is an end marker
  232. //
  233. // numLiterals The number of literals in literalEncoding
  234. // numOffsets The number of offsets in offsetEncoding
  235. // litenc, offenc The literal and offset encoder to use
  236. func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litEnc, offEnc *huffmanEncoder) {
  237. for i := range w.codegenFreq {
  238. w.codegenFreq[i] = 0
  239. }
  240. // Note that we are using codegen both as a temporary variable for holding
  241. // a copy of the frequencies, and as the place where we put the result.
  242. // This is fine because the output is always shorter than the input used
  243. // so far.
  244. codegen := w.codegen[:] // cache
  245. // Copy the concatenated code sizes to codegen. Put a marker at the end.
  246. cgnl := codegen[:numLiterals]
  247. for i := range cgnl {
  248. cgnl[i] = litEnc.codes[i].len()
  249. }
  250. cgnl = codegen[numLiterals : numLiterals+numOffsets]
  251. for i := range cgnl {
  252. cgnl[i] = offEnc.codes[i].len()
  253. }
  254. codegen[numLiterals+numOffsets] = badCode
  255. size := codegen[0]
  256. count := 1
  257. outIndex := 0
  258. for inIndex := 1; size != badCode; inIndex++ {
  259. // INVARIANT: We have seen "count" copies of size that have not yet
  260. // had output generated for them.
  261. nextSize := codegen[inIndex]
  262. if nextSize == size {
  263. count++
  264. continue
  265. }
  266. // We need to generate codegen indicating "count" of size.
  267. if size != 0 {
  268. codegen[outIndex] = size
  269. outIndex++
  270. w.codegenFreq[size]++
  271. count--
  272. for count >= 3 {
  273. n := min(6, count)
  274. codegen[outIndex] = 16
  275. outIndex++
  276. codegen[outIndex] = uint8(n - 3)
  277. outIndex++
  278. w.codegenFreq[16]++
  279. count -= n
  280. }
  281. } else {
  282. for count >= 11 {
  283. n := min(138, count)
  284. codegen[outIndex] = 18
  285. outIndex++
  286. codegen[outIndex] = uint8(n - 11)
  287. outIndex++
  288. w.codegenFreq[18]++
  289. count -= n
  290. }
  291. if count >= 3 {
  292. // count >= 3 && count <= 10
  293. codegen[outIndex] = 17
  294. outIndex++
  295. codegen[outIndex] = uint8(count - 3)
  296. outIndex++
  297. w.codegenFreq[17]++
  298. count = 0
  299. }
  300. }
  301. count--
  302. for ; count >= 0; count-- {
  303. codegen[outIndex] = size
  304. outIndex++
  305. w.codegenFreq[size]++
  306. }
  307. // Set up invariant for next time through the loop.
  308. size = nextSize
  309. count = 1
  310. }
  311. // Marker indicating the end of the codegen.
  312. codegen[outIndex] = badCode
  313. }
  314. func (w *huffmanBitWriter) codegens() int {
  315. numCodegens := len(w.codegenFreq)
  316. for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
  317. numCodegens--
  318. }
  319. return numCodegens
  320. }
  321. func (w *huffmanBitWriter) headerSize() (size, numCodegens int) {
  322. numCodegens = len(w.codegenFreq)
  323. for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
  324. numCodegens--
  325. }
  326. return 3 + 5 + 5 + 4 + (3 * numCodegens) +
  327. w.codegenEncoding.bitLength(w.codegenFreq[:]) +
  328. int(w.codegenFreq[16])*2 +
  329. int(w.codegenFreq[17])*3 +
  330. int(w.codegenFreq[18])*7, numCodegens
  331. }
  332. // dynamicSize returns the size of dynamically encoded data in bits.
  333. func (w *huffmanBitWriter) dynamicReuseSize(litEnc, offEnc *huffmanEncoder) (size int) {
  334. size = litEnc.bitLength(w.literalFreq[:]) +
  335. offEnc.bitLength(w.offsetFreq[:])
  336. return size
  337. }
  338. // dynamicSize returns the size of dynamically encoded data in bits.
  339. func (w *huffmanBitWriter) dynamicSize(litEnc, offEnc *huffmanEncoder, extraBits int) (size, numCodegens int) {
  340. header, numCodegens := w.headerSize()
  341. size = header +
  342. litEnc.bitLength(w.literalFreq[:]) +
  343. offEnc.bitLength(w.offsetFreq[:]) +
  344. extraBits
  345. return size, numCodegens
  346. }
  347. // extraBitSize will return the number of bits that will be written
  348. // as "extra" bits on matches.
  349. func (w *huffmanBitWriter) extraBitSize() int {
  350. total := 0
  351. for i, n := range w.literalFreq[257:literalCount] {
  352. total += int(n) * int(lengthExtraBits[i&31])
  353. }
  354. for i, n := range w.offsetFreq[:offsetCodeCount] {
  355. total += int(n) * int(offsetExtraBits[i&31])
  356. }
  357. return total
  358. }
  359. // fixedSize returns the size of dynamically encoded data in bits.
  360. func (w *huffmanBitWriter) fixedSize(extraBits int) int {
  361. return 3 +
  362. fixedLiteralEncoding.bitLength(w.literalFreq[:]) +
  363. fixedOffsetEncoding.bitLength(w.offsetFreq[:]) +
  364. extraBits
  365. }
  366. // storedSize calculates the stored size, including header.
  367. // The function returns the size in bits and whether the block
  368. // fits inside a single block.
  369. func (w *huffmanBitWriter) storedSize(in []byte) (int, bool) {
  370. if in == nil {
  371. return 0, false
  372. }
  373. if len(in) <= maxStoreBlockSize {
  374. return (len(in) + 5) * 8, true
  375. }
  376. return 0, false
  377. }
  378. func (w *huffmanBitWriter) writeCode(c hcode) {
  379. // The function does not get inlined if we "& 63" the shift.
  380. w.bits |= c.code64() << (w.nbits & 63)
  381. w.nbits += c.len()
  382. if w.nbits >= 48 {
  383. w.writeOutBits()
  384. }
  385. }
  386. // writeOutBits will write bits to the buffer.
  387. func (w *huffmanBitWriter) writeOutBits() {
  388. bits := w.bits
  389. w.bits >>= 48
  390. w.nbits -= 48
  391. n := w.nbytes
  392. // We overwrite, but faster...
  393. le.Store64(w.bytes[:], n, bits)
  394. n += 6
  395. if n >= bufferFlushSize {
  396. if w.err != nil {
  397. n = 0
  398. return
  399. }
  400. w.write(w.bytes[:n])
  401. n = 0
  402. }
  403. w.nbytes = n
  404. }
  405. // Write the header of a dynamic Huffman block to the output stream.
  406. //
  407. // numLiterals The number of literals specified in codegen
  408. // numOffsets The number of offsets specified in codegen
  409. // numCodegens The number of codegens used in codegen
  410. func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, numCodegens int, isEof bool) {
  411. if w.err != nil {
  412. return
  413. }
  414. var firstBits int32 = 4
  415. if isEof {
  416. firstBits = 5
  417. }
  418. w.writeBits(firstBits, 3)
  419. w.writeBits(int32(numLiterals-257), 5)
  420. w.writeBits(int32(numOffsets-1), 5)
  421. w.writeBits(int32(numCodegens-4), 4)
  422. for i := range numCodegens {
  423. value := uint(w.codegenEncoding.codes[codegenOrder[i]].len())
  424. w.writeBits(int32(value), 3)
  425. }
  426. i := 0
  427. for {
  428. var codeWord = uint32(w.codegen[i])
  429. i++
  430. if codeWord == badCode {
  431. break
  432. }
  433. w.writeCode(w.codegenEncoding.codes[codeWord])
  434. switch codeWord {
  435. case 16:
  436. w.writeBits(int32(w.codegen[i]), 2)
  437. i++
  438. case 17:
  439. w.writeBits(int32(w.codegen[i]), 3)
  440. i++
  441. case 18:
  442. w.writeBits(int32(w.codegen[i]), 7)
  443. i++
  444. }
  445. }
  446. }
  447. // writeStoredHeader will write a stored header.
  448. // If the stored block is only used for EOF,
  449. // it is replaced with a fixed huffman block.
  450. func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool) {
  451. if w.err != nil {
  452. return
  453. }
  454. if w.lastHeader > 0 {
  455. // We owe an EOB
  456. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  457. w.lastHeader = 0
  458. }
  459. // To write EOF, use a fixed encoding block. 10 bits instead of 5 bytes.
  460. if length == 0 && isEof {
  461. w.writeFixedHeader(isEof)
  462. // EOB: 7 bits, value: 0
  463. w.writeBits(0, 7)
  464. w.flush()
  465. return
  466. }
  467. var flag int32
  468. if isEof {
  469. flag = 1
  470. }
  471. w.writeBits(flag, 3)
  472. w.flush()
  473. w.writeBits(int32(length), 16)
  474. w.writeBits(int32(^uint16(length)), 16)
  475. }
  476. func (w *huffmanBitWriter) writeFixedHeader(isEof bool) {
  477. if w.err != nil {
  478. return
  479. }
  480. if w.lastHeader > 0 {
  481. // We owe an EOB
  482. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  483. w.lastHeader = 0
  484. }
  485. // Indicate that we are a fixed Huffman block
  486. var value int32 = 2
  487. if isEof {
  488. value = 3
  489. }
  490. w.writeBits(value, 3)
  491. }
  492. // writeBlock will write a block of tokens with the smallest encoding.
  493. // The original input can be supplied, and if the huffman encoded data
  494. // is larger than the original bytes, the data will be written as a
  495. // stored block.
  496. // If the input is nil, the tokens will always be Huffman encoded.
  497. func (w *huffmanBitWriter) writeBlock(tokens *tokens, eof bool, input []byte) {
  498. if w.err != nil {
  499. return
  500. }
  501. tokens.AddEOB()
  502. if w.lastHeader > 0 {
  503. // We owe an EOB
  504. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  505. w.lastHeader = 0
  506. }
  507. numLiterals, numOffsets := w.indexTokens(tokens, false)
  508. w.generate()
  509. var extraBits int
  510. storedSize, storable := w.storedSize(input)
  511. if storable {
  512. extraBits = w.extraBitSize()
  513. }
  514. // Figure out smallest code.
  515. // Fixed Huffman baseline.
  516. var literalEncoding = fixedLiteralEncoding
  517. var offsetEncoding = fixedOffsetEncoding
  518. var size = math.MaxInt32
  519. if tokens.n < maxPredefinedTokens {
  520. size = w.fixedSize(extraBits)
  521. }
  522. // Dynamic Huffman?
  523. var numCodegens int
  524. // Generate codegen and codegenFrequencies, which indicates how to encode
  525. // the literalEncoding and the offsetEncoding.
  526. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
  527. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  528. dynamicSize, numCodegens := w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits)
  529. if dynamicSize < size {
  530. size = dynamicSize
  531. literalEncoding = w.literalEncoding
  532. offsetEncoding = w.offsetEncoding
  533. }
  534. // Stored bytes?
  535. if storable && storedSize <= size {
  536. w.writeStoredHeader(len(input), eof)
  537. w.writeBytes(input)
  538. return
  539. }
  540. // Huffman.
  541. if literalEncoding == fixedLiteralEncoding {
  542. w.writeFixedHeader(eof)
  543. } else {
  544. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  545. }
  546. // Write the tokens.
  547. w.writeTokens(tokens.Slice(), literalEncoding.codes, offsetEncoding.codes)
  548. }
  549. // writeBlockDynamic encodes a block using a dynamic Huffman table.
  550. // This should be used if the symbols used have a disproportionate
  551. // histogram distribution.
  552. // If input is supplied and the compression savings are below 1/16th of the
  553. // input size the block is stored.
  554. func (w *huffmanBitWriter) writeBlockDynamic(tokens *tokens, eof bool, input []byte, sync bool) {
  555. if w.err != nil {
  556. return
  557. }
  558. sync = sync || eof
  559. if sync {
  560. tokens.AddEOB()
  561. }
  562. // We cannot reuse pure huffman table, and must mark as EOF.
  563. if (w.lastHuffMan || eof) && w.lastHeader > 0 {
  564. // We will not try to reuse.
  565. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  566. w.lastHeader = 0
  567. w.lastHuffMan = false
  568. }
  569. // fillReuse enables filling of empty values.
  570. // This will make encodings always reusable without testing.
  571. // However, this does not appear to benefit on most cases.
  572. const fillReuse = false
  573. // Check if we can reuse...
  574. if !fillReuse && w.lastHeader > 0 && !w.canReuse(tokens) {
  575. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  576. w.lastHeader = 0
  577. }
  578. numLiterals, numOffsets := w.indexTokens(tokens, true)
  579. extraBits := 0
  580. ssize, storable := w.storedSize(input)
  581. const usePrefs = true
  582. if storable || w.lastHeader > 0 {
  583. extraBits = w.extraBitSize()
  584. }
  585. var size int
  586. // Check if we should reuse.
  587. if w.lastHeader > 0 {
  588. // Estimate size for using a new table.
  589. // Use the previous header size as the best estimate.
  590. newSize := w.lastHeader + tokens.EstimatedBits()
  591. newSize += int(w.literalEncoding.codes[endBlockMarker].len()) + newSize>>w.logNewTablePenalty
  592. // The estimated size is calculated as an optimal table.
  593. // We add a penalty to make it more realistic and re-use a bit more.
  594. reuseSize := w.dynamicReuseSize(w.literalEncoding, w.offsetEncoding) + extraBits
  595. // Check if a new table is better.
  596. if newSize < reuseSize {
  597. // Write the EOB we owe.
  598. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  599. size = newSize
  600. w.lastHeader = 0
  601. } else {
  602. size = reuseSize
  603. }
  604. if tokens.n < maxPredefinedTokens {
  605. if preSize := w.fixedSize(extraBits) + 7; usePrefs && preSize < size {
  606. // Check if we get a reasonable size decrease.
  607. if storable && ssize <= size {
  608. w.writeStoredHeader(len(input), eof)
  609. w.writeBytes(input)
  610. return
  611. }
  612. w.writeFixedHeader(eof)
  613. if !sync {
  614. tokens.AddEOB()
  615. }
  616. w.writeTokens(tokens.Slice(), fixedLiteralEncoding.codes, fixedOffsetEncoding.codes)
  617. return
  618. }
  619. }
  620. // Check if we get a reasonable size decrease.
  621. if storable && ssize <= size {
  622. w.writeStoredHeader(len(input), eof)
  623. w.writeBytes(input)
  624. return
  625. }
  626. }
  627. // We want a new block/table
  628. if w.lastHeader == 0 {
  629. if fillReuse && !sync {
  630. w.fillTokens()
  631. numLiterals, numOffsets = maxNumLit, maxNumDist
  632. } else {
  633. w.literalFreq[endBlockMarker] = 1
  634. }
  635. w.generate()
  636. // Generate codegen and codegenFrequencies, which indicates how to encode
  637. // the literalEncoding and the offsetEncoding.
  638. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
  639. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  640. var numCodegens int
  641. if fillReuse && !sync {
  642. // Reindex for accurate size...
  643. w.indexTokens(tokens, true)
  644. }
  645. size, numCodegens = w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits)
  646. // Store predefined, if we don't get a reasonable improvement.
  647. if tokens.n < maxPredefinedTokens {
  648. if preSize := w.fixedSize(extraBits); usePrefs && preSize <= size {
  649. // Store bytes, if we don't get an improvement.
  650. if storable && ssize <= preSize {
  651. w.writeStoredHeader(len(input), eof)
  652. w.writeBytes(input)
  653. return
  654. }
  655. w.writeFixedHeader(eof)
  656. if !sync {
  657. tokens.AddEOB()
  658. }
  659. w.writeTokens(tokens.Slice(), fixedLiteralEncoding.codes, fixedOffsetEncoding.codes)
  660. return
  661. }
  662. }
  663. if storable && ssize <= size {
  664. // Store bytes, if we don't get an improvement.
  665. w.writeStoredHeader(len(input), eof)
  666. w.writeBytes(input)
  667. return
  668. }
  669. // Write Huffman table.
  670. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  671. if !sync {
  672. w.lastHeader, _ = w.headerSize()
  673. }
  674. w.lastHuffMan = false
  675. }
  676. if sync {
  677. w.lastHeader = 0
  678. }
  679. // Write the tokens.
  680. w.writeTokens(tokens.Slice(), w.literalEncoding.codes, w.offsetEncoding.codes)
  681. }
  682. func (w *huffmanBitWriter) fillTokens() {
  683. for i, v := range w.literalFreq[:literalCount] {
  684. if v == 0 {
  685. w.literalFreq[i] = 1
  686. }
  687. }
  688. for i, v := range w.offsetFreq[:offsetCodeCount] {
  689. if v == 0 {
  690. w.offsetFreq[i] = 1
  691. }
  692. }
  693. }
  694. // indexTokens indexes a slice of tokens, and updates
  695. // literalFreq and offsetFreq, and generates literalEncoding
  696. // and offsetEncoding.
  697. // The number of literal and offset tokens is returned.
  698. func (w *huffmanBitWriter) indexTokens(t *tokens, alwaysEOB bool) (numLiterals, numOffsets int) {
  699. //copy(w.literalFreq[:], t.litHist[:])
  700. *(*[256]uint16)(w.literalFreq[:]) = t.litHist
  701. //copy(w.literalFreq[256:], t.extraHist[:])
  702. *(*[32]uint16)(w.literalFreq[256:]) = t.extraHist
  703. w.offsetFreq = t.offHist
  704. if t.n == 0 {
  705. return
  706. }
  707. if alwaysEOB {
  708. w.literalFreq[endBlockMarker] = 1
  709. }
  710. // get the number of literals
  711. numLiterals = len(w.literalFreq)
  712. for w.literalFreq[numLiterals-1] == 0 {
  713. numLiterals--
  714. }
  715. // get the number of offsets
  716. numOffsets = len(w.offsetFreq)
  717. for numOffsets > 0 && w.offsetFreq[numOffsets-1] == 0 {
  718. numOffsets--
  719. }
  720. if numOffsets == 0 {
  721. // We haven't found a single match. If we want to go with the dynamic encoding,
  722. // we should count at least one offset to be sure that the offset huffman tree could be encoded.
  723. w.offsetFreq[0] = 1
  724. numOffsets = 1
  725. }
  726. return
  727. }
  728. func (w *huffmanBitWriter) generate() {
  729. w.literalEncoding.generate(w.literalFreq[:literalCount], 15)
  730. w.offsetEncoding.generate(w.offsetFreq[:offsetCodeCount], 15)
  731. }
  732. // writeTokens writes a slice of tokens to the output.
  733. // codes for literal and offset encoding must be supplied.
  734. func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) {
  735. if w.err != nil {
  736. return
  737. }
  738. if len(tokens) == 0 {
  739. return
  740. }
  741. // Only last token should be endBlockMarker.
  742. var deferEOB bool
  743. if tokens[len(tokens)-1] == endBlockMarker {
  744. tokens = tokens[:len(tokens)-1]
  745. deferEOB = true
  746. }
  747. // Create slices up to the next power of two to avoid bounds checks.
  748. lits := leCodes[:256]
  749. offs := oeCodes[:32]
  750. lengths := leCodes[lengthCodesStart:]
  751. lengths = lengths[:32]
  752. // Go 1.16 LOVES having these on stack.
  753. bits, nbits, nbytes := w.bits, w.nbits, w.nbytes
  754. for _, t := range tokens {
  755. if t < 256 {
  756. //w.writeCode(lits[t.literal()])
  757. c := lits[t]
  758. bits |= c.code64() << (nbits & 63)
  759. nbits += c.len()
  760. if nbits >= 48 {
  761. le.Store64(w.bytes[:], nbytes, bits)
  762. bits >>= 48
  763. nbits -= 48
  764. nbytes += 6
  765. if nbytes >= bufferFlushSize {
  766. if w.err != nil {
  767. nbytes = 0
  768. return
  769. }
  770. _, w.err = w.writer.Write(w.bytes[:nbytes])
  771. nbytes = 0
  772. }
  773. }
  774. continue
  775. }
  776. // Write the length
  777. length := t.length()
  778. lengthCode := lengthCode(length) & 31
  779. if false {
  780. w.writeCode(lengths[lengthCode])
  781. } else {
  782. // inlined
  783. c := lengths[lengthCode]
  784. bits |= c.code64() << (nbits & 63)
  785. nbits += c.len()
  786. if nbits >= 48 {
  787. le.Store64(w.bytes[:], nbytes, bits)
  788. bits >>= 48
  789. nbits -= 48
  790. nbytes += 6
  791. if nbytes >= bufferFlushSize {
  792. if w.err != nil {
  793. nbytes = 0
  794. return
  795. }
  796. _, w.err = w.writer.Write(w.bytes[:nbytes])
  797. nbytes = 0
  798. }
  799. }
  800. }
  801. if lengthCode >= lengthExtraBitsMinCode {
  802. extraLengthBits := lengthExtraBits[lengthCode]
  803. //w.writeBits(extraLength, extraLengthBits)
  804. extraLength := int32(length - lengthBase[lengthCode])
  805. bits |= uint64(extraLength) << (nbits & 63)
  806. nbits += extraLengthBits
  807. if nbits >= 48 {
  808. le.Store64(w.bytes[:], nbytes, bits)
  809. bits >>= 48
  810. nbits -= 48
  811. nbytes += 6
  812. if nbytes >= bufferFlushSize {
  813. if w.err != nil {
  814. nbytes = 0
  815. return
  816. }
  817. _, w.err = w.writer.Write(w.bytes[:nbytes])
  818. nbytes = 0
  819. }
  820. }
  821. }
  822. // Write the offset
  823. offset := t.offset()
  824. offsetCode := (offset >> 16) & 31
  825. if false {
  826. w.writeCode(offs[offsetCode])
  827. } else {
  828. // inlined
  829. c := offs[offsetCode]
  830. bits |= c.code64() << (nbits & 63)
  831. nbits += c.len()
  832. if nbits >= 48 {
  833. le.Store64(w.bytes[:], nbytes, bits)
  834. bits >>= 48
  835. nbits -= 48
  836. nbytes += 6
  837. if nbytes >= bufferFlushSize {
  838. if w.err != nil {
  839. nbytes = 0
  840. return
  841. }
  842. _, w.err = w.writer.Write(w.bytes[:nbytes])
  843. nbytes = 0
  844. }
  845. }
  846. }
  847. if offsetCode >= offsetExtraBitsMinCode {
  848. offsetComb := offsetCombined[offsetCode]
  849. //w.writeBits(extraOffset, extraOffsetBits)
  850. bits |= uint64((offset-(offsetComb>>8))&matchOffsetOnlyMask) << (nbits & 63)
  851. nbits += uint8(offsetComb)
  852. if nbits >= 48 {
  853. le.Store64(w.bytes[:], nbytes, bits)
  854. bits >>= 48
  855. nbits -= 48
  856. nbytes += 6
  857. if nbytes >= bufferFlushSize {
  858. if w.err != nil {
  859. nbytes = 0
  860. return
  861. }
  862. _, w.err = w.writer.Write(w.bytes[:nbytes])
  863. nbytes = 0
  864. }
  865. }
  866. }
  867. }
  868. // Restore...
  869. w.bits, w.nbits, w.nbytes = bits, nbits, nbytes
  870. if deferEOB {
  871. w.writeCode(leCodes[endBlockMarker])
  872. }
  873. }
  874. // huffOffset is a static offset encoder used for huffman only encoding.
  875. // It can be reused since we will not be encoding offset values.
  876. var huffOffset *huffmanEncoder
  877. func init() {
  878. w := newHuffmanBitWriter(nil)
  879. w.offsetFreq[0] = 1
  880. huffOffset = newHuffmanEncoder(offsetCodeCount)
  881. huffOffset.generate(w.offsetFreq[:offsetCodeCount], 15)
  882. }
  883. // writeBlockHuff encodes a block of bytes as either
  884. // Huffman encoded literals or uncompressed bytes if the
  885. // results only gains very little from compression.
  886. func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
  887. if w.err != nil {
  888. return
  889. }
  890. // Clear histogram
  891. for i := range w.literalFreq[:] {
  892. w.literalFreq[i] = 0
  893. }
  894. if !w.lastHuffMan {
  895. for i := range w.offsetFreq[:] {
  896. w.offsetFreq[i] = 0
  897. }
  898. }
  899. const numLiterals = endBlockMarker + 1
  900. const numOffsets = 1
  901. // Add everything as literals
  902. // We have to estimate the header size.
  903. // Assume header is around 70 bytes:
  904. // https://stackoverflow.com/a/25454430
  905. const guessHeaderSizeBits = 70 * 8
  906. histogram(input, w.literalFreq[:numLiterals])
  907. ssize, storable := w.storedSize(input)
  908. if storable && len(input) > 1024 {
  909. // Quick check for incompressible content.
  910. abs := float64(0)
  911. avg := float64(len(input)) / 256
  912. max := float64(len(input) * 2)
  913. for _, v := range w.literalFreq[:256] {
  914. diff := float64(v) - avg
  915. abs += diff * diff
  916. if abs > max {
  917. break
  918. }
  919. }
  920. if abs < max {
  921. if debugDeflate {
  922. fmt.Println("stored", abs, "<", max)
  923. }
  924. // No chance we can compress this...
  925. w.writeStoredHeader(len(input), eof)
  926. w.writeBytes(input)
  927. return
  928. }
  929. }
  930. w.literalFreq[endBlockMarker] = 1
  931. w.tmpLitEncoding.generate(w.literalFreq[:numLiterals], 15)
  932. estBits := w.tmpLitEncoding.canReuseBits(w.literalFreq[:numLiterals])
  933. if estBits < math.MaxInt32 {
  934. estBits += w.lastHeader
  935. if w.lastHeader == 0 {
  936. estBits += guessHeaderSizeBits
  937. }
  938. estBits += estBits >> w.logNewTablePenalty
  939. }
  940. // Store bytes, if we don't get a reasonable improvement.
  941. if storable && ssize <= estBits {
  942. if debugDeflate {
  943. fmt.Println("stored,", ssize, "<=", estBits)
  944. }
  945. w.writeStoredHeader(len(input), eof)
  946. w.writeBytes(input)
  947. return
  948. }
  949. if w.lastHeader > 0 {
  950. reuseSize := w.literalEncoding.canReuseBits(w.literalFreq[:256])
  951. if estBits < reuseSize {
  952. if debugDeflate {
  953. fmt.Println("NOT reusing, reuse:", reuseSize/8, "> new:", estBits/8, "header est:", w.lastHeader/8, "bytes")
  954. }
  955. // We owe an EOB
  956. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  957. w.lastHeader = 0
  958. } else if debugDeflate {
  959. fmt.Println("reusing, reuse:", reuseSize/8, "> new:", estBits/8, "- header est:", w.lastHeader/8)
  960. }
  961. }
  962. count := 0
  963. if w.lastHeader == 0 {
  964. // Use the temp encoding, so swap.
  965. w.literalEncoding, w.tmpLitEncoding = w.tmpLitEncoding, w.literalEncoding
  966. // Generate codegen and codegenFrequencies, which indicates how to encode
  967. // the literalEncoding and the offsetEncoding.
  968. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, huffOffset)
  969. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  970. numCodegens := w.codegens()
  971. // Huffman.
  972. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  973. w.lastHuffMan = true
  974. w.lastHeader, _ = w.headerSize()
  975. if debugDeflate {
  976. count += w.lastHeader
  977. fmt.Println("header:", count/8)
  978. }
  979. }
  980. encoding := w.literalEncoding.codes[:256]
  981. // Go 1.16 LOVES having these on stack. At least 1.5x the speed.
  982. bits, nbits, nbytes := w.bits, w.nbits, w.nbytes
  983. if debugDeflate {
  984. count -= int(nbytes)*8 + int(nbits)
  985. }
  986. // Unroll, write 3 codes/loop.
  987. // Fastest number of unrolls.
  988. for len(input) > 3 {
  989. // We must have at least 48 bits free.
  990. if nbits >= 8 {
  991. n := nbits >> 3
  992. le.Store64(w.bytes[:], nbytes, bits)
  993. bits >>= (n * 8) & 63
  994. nbits -= n * 8
  995. nbytes += n
  996. }
  997. if nbytes >= bufferFlushSize {
  998. if w.err != nil {
  999. nbytes = 0
  1000. return
  1001. }
  1002. if debugDeflate {
  1003. count += int(nbytes) * 8
  1004. }
  1005. _, w.err = w.writer.Write(w.bytes[:nbytes])
  1006. nbytes = 0
  1007. }
  1008. a, b := encoding[input[0]], encoding[input[1]]
  1009. bits |= a.code64() << (nbits & 63)
  1010. bits |= b.code64() << ((nbits + a.len()) & 63)
  1011. c := encoding[input[2]]
  1012. nbits += b.len() + a.len()
  1013. bits |= c.code64() << (nbits & 63)
  1014. nbits += c.len()
  1015. input = input[3:]
  1016. }
  1017. // Remaining...
  1018. for _, t := range input {
  1019. if nbits >= 48 {
  1020. le.Store64(w.bytes[:], nbytes, bits)
  1021. bits >>= 48
  1022. nbits -= 48
  1023. nbytes += 6
  1024. if nbytes >= bufferFlushSize {
  1025. if w.err != nil {
  1026. nbytes = 0
  1027. return
  1028. }
  1029. if debugDeflate {
  1030. count += int(nbytes) * 8
  1031. }
  1032. _, w.err = w.writer.Write(w.bytes[:nbytes])
  1033. nbytes = 0
  1034. }
  1035. }
  1036. // Bitwriting inlined, ~30% speedup
  1037. c := encoding[t]
  1038. bits |= c.code64() << (nbits & 63)
  1039. nbits += c.len()
  1040. if debugDeflate {
  1041. count += int(c.len())
  1042. }
  1043. }
  1044. // Restore...
  1045. w.bits, w.nbits, w.nbytes = bits, nbits, nbytes
  1046. if debugDeflate {
  1047. nb := count + int(nbytes)*8 + int(nbits)
  1048. fmt.Println("wrote", nb, "bits,", nb/8, "bytes.")
  1049. }
  1050. // Flush if needed to have space.
  1051. if w.nbits >= 48 {
  1052. w.writeOutBits()
  1053. }
  1054. if eof || sync {
  1055. w.writeCode(w.literalEncoding.codes[endBlockMarker])
  1056. w.lastHeader = 0
  1057. w.lastHuffMan = false
  1058. }
  1059. }