huffman_bit_writer.go 30 KB

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