blockenc.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. // Copyright 2019+ Klaus Post. All rights reserved.
  2. // License information can be found in the LICENSE file.
  3. // Based on work by Yann Collet, released under BSD License.
  4. package zstd
  5. import (
  6. "errors"
  7. "fmt"
  8. "math"
  9. "math/bits"
  10. "github.com/klauspost/compress/huff0"
  11. )
  12. type blockEnc struct {
  13. size int
  14. literals []byte
  15. sequences []seq
  16. coders seqCoders
  17. litEnc *huff0.Scratch
  18. dictLitEnc *huff0.Scratch
  19. wr bitWriter
  20. extraLits int
  21. output []byte
  22. recentOffsets [3]uint32
  23. prevRecentOffsets [3]uint32
  24. last bool
  25. lowMem bool
  26. }
  27. // init should be used once the block has been created.
  28. // If called more than once, the effect is the same as calling reset.
  29. func (b *blockEnc) init() {
  30. if b.lowMem {
  31. // 1K literals
  32. if cap(b.literals) < 1<<10 {
  33. b.literals = make([]byte, 0, 1<<10)
  34. }
  35. const defSeqs = 20
  36. if cap(b.sequences) < defSeqs {
  37. b.sequences = make([]seq, 0, defSeqs)
  38. }
  39. // 1K
  40. if cap(b.output) < 1<<10 {
  41. b.output = make([]byte, 0, 1<<10)
  42. }
  43. } else {
  44. if cap(b.literals) < maxCompressedBlockSize {
  45. b.literals = make([]byte, 0, maxCompressedBlockSize)
  46. }
  47. const defSeqs = 2000
  48. if cap(b.sequences) < defSeqs {
  49. b.sequences = make([]seq, 0, defSeqs)
  50. }
  51. if cap(b.output) < maxCompressedBlockSize {
  52. b.output = make([]byte, 0, maxCompressedBlockSize)
  53. }
  54. }
  55. if b.coders.mlEnc == nil {
  56. b.coders.mlEnc = &fseEncoder{}
  57. b.coders.mlPrev = &fseEncoder{}
  58. b.coders.ofEnc = &fseEncoder{}
  59. b.coders.ofPrev = &fseEncoder{}
  60. b.coders.llEnc = &fseEncoder{}
  61. b.coders.llPrev = &fseEncoder{}
  62. }
  63. b.litEnc = &huff0.Scratch{WantLogLess: 4}
  64. b.reset(nil)
  65. }
  66. // initNewEncode can be used to reset offsets and encoders to the initial state.
  67. func (b *blockEnc) initNewEncode() {
  68. b.recentOffsets = [3]uint32{1, 4, 8}
  69. b.litEnc.Reuse = huff0.ReusePolicyNone
  70. b.coders.setPrev(nil, nil, nil)
  71. }
  72. // reset will reset the block for a new encode, but in the same stream,
  73. // meaning that state will be carried over, but the block content is reset.
  74. // If a previous block is provided, the recent offsets are carried over.
  75. func (b *blockEnc) reset(prev *blockEnc) {
  76. b.extraLits = 0
  77. b.literals = b.literals[:0]
  78. b.size = 0
  79. b.sequences = b.sequences[:0]
  80. b.output = b.output[:0]
  81. b.last = false
  82. if prev != nil {
  83. b.recentOffsets = prev.prevRecentOffsets
  84. }
  85. b.dictLitEnc = nil
  86. }
  87. // reset will reset the block for a new encode, but in the same stream,
  88. // meaning that state will be carried over, but the block content is reset.
  89. // If a previous block is provided, the recent offsets are carried over.
  90. func (b *blockEnc) swapEncoders(prev *blockEnc) {
  91. b.coders.swap(&prev.coders)
  92. b.litEnc, prev.litEnc = prev.litEnc, b.litEnc
  93. }
  94. // blockHeader contains the information for a block header.
  95. type blockHeader uint32
  96. // setLast sets the 'last' indicator on a block.
  97. func (h *blockHeader) setLast(b bool) {
  98. if b {
  99. *h = *h | 1
  100. } else {
  101. const mask = (1 << 24) - 2
  102. *h = *h & mask
  103. }
  104. }
  105. // setSize will store the compressed size of a block.
  106. func (h *blockHeader) setSize(v uint32) {
  107. const mask = 7
  108. *h = (*h)&mask | blockHeader(v<<3)
  109. }
  110. // setType sets the block type.
  111. func (h *blockHeader) setType(t blockType) {
  112. const mask = 1 | (((1 << 24) - 1) ^ 7)
  113. *h = (*h & mask) | blockHeader(t<<1)
  114. }
  115. // appendTo will append the block header to a slice.
  116. func (h blockHeader) appendTo(b []byte) []byte {
  117. return append(b, uint8(h), uint8(h>>8), uint8(h>>16))
  118. }
  119. // String returns a string representation of the block.
  120. func (h blockHeader) String() string {
  121. return fmt.Sprintf("Type: %d, Size: %d, Last:%t", (h>>1)&3, h>>3, h&1 == 1)
  122. }
  123. // literalsHeader contains literals header information.
  124. type literalsHeader uint64
  125. // setType can be used to set the type of literal block.
  126. func (h *literalsHeader) setType(t literalsBlockType) {
  127. const mask = math.MaxUint64 - 3
  128. *h = (*h & mask) | literalsHeader(t)
  129. }
  130. // setSize can be used to set a single size, for uncompressed and RLE content.
  131. func (h *literalsHeader) setSize(regenLen int) {
  132. inBits := bits.Len32(uint32(regenLen))
  133. // Only retain 2 bits
  134. const mask = 3
  135. lh := uint64(*h & mask)
  136. switch {
  137. case inBits < 5:
  138. lh |= (uint64(regenLen) << 3) | (1 << 60)
  139. if debugEncoder {
  140. got := int(lh>>3) & 0xff
  141. if got != regenLen {
  142. panic(fmt.Sprint("litRegenSize = ", regenLen, "(want) != ", got, "(got)"))
  143. }
  144. }
  145. case inBits < 12:
  146. lh |= (1 << 2) | (uint64(regenLen) << 4) | (2 << 60)
  147. case inBits < 20:
  148. lh |= (3 << 2) | (uint64(regenLen) << 4) | (3 << 60)
  149. default:
  150. panic(fmt.Errorf("internal error: block too big (%d)", regenLen))
  151. }
  152. *h = literalsHeader(lh)
  153. }
  154. // setSizes will set the size of a compressed literals section and the input length.
  155. func (h *literalsHeader) setSizes(compLen, inLen int, single bool) {
  156. compBits, inBits := bits.Len32(uint32(compLen)), bits.Len32(uint32(inLen))
  157. // Only retain 2 bits
  158. const mask = 3
  159. lh := uint64(*h & mask)
  160. switch {
  161. case compBits <= 10 && inBits <= 10:
  162. if !single {
  163. lh |= 1 << 2
  164. }
  165. lh |= (uint64(inLen) << 4) | (uint64(compLen) << (10 + 4)) | (3 << 60)
  166. if debugEncoder {
  167. const mmask = (1 << 24) - 1
  168. n := (lh >> 4) & mmask
  169. if int(n&1023) != inLen {
  170. panic(fmt.Sprint("regensize:", int(n&1023), "!=", inLen, inBits))
  171. }
  172. if int(n>>10) != compLen {
  173. panic(fmt.Sprint("compsize:", int(n>>10), "!=", compLen, compBits))
  174. }
  175. }
  176. case compBits <= 14 && inBits <= 14:
  177. lh |= (2 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (14 + 4)) | (4 << 60)
  178. if single {
  179. panic("single stream used with more than 10 bits length.")
  180. }
  181. case compBits <= 18 && inBits <= 18:
  182. lh |= (3 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (18 + 4)) | (5 << 60)
  183. if single {
  184. panic("single stream used with more than 10 bits length.")
  185. }
  186. default:
  187. panic("internal error: block too big")
  188. }
  189. *h = literalsHeader(lh)
  190. }
  191. // appendTo will append the literals header to a byte slice.
  192. func (h literalsHeader) appendTo(b []byte) []byte {
  193. size := uint8(h >> 60)
  194. switch size {
  195. case 1:
  196. b = append(b, uint8(h))
  197. case 2:
  198. b = append(b, uint8(h), uint8(h>>8))
  199. case 3:
  200. b = append(b, uint8(h), uint8(h>>8), uint8(h>>16))
  201. case 4:
  202. b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24))
  203. case 5:
  204. b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24), uint8(h>>32))
  205. default:
  206. panic(fmt.Errorf("internal error: literalsHeader has invalid size (%d)", size))
  207. }
  208. return b
  209. }
  210. // size returns the output size with currently set values.
  211. func (h literalsHeader) size() int {
  212. return int(h >> 60)
  213. }
  214. func (h literalsHeader) String() string {
  215. return fmt.Sprintf("Type: %d, SizeFormat: %d, Size: 0x%d, Bytes:%d", literalsBlockType(h&3), (h>>2)&3, h&((1<<60)-1)>>4, h>>60)
  216. }
  217. // pushOffsets will push the recent offsets to the backup store.
  218. func (b *blockEnc) pushOffsets() {
  219. b.prevRecentOffsets = b.recentOffsets
  220. }
  221. // pushOffsets will push the recent offsets to the backup store.
  222. func (b *blockEnc) popOffsets() {
  223. b.recentOffsets = b.prevRecentOffsets
  224. }
  225. // matchOffset will adjust recent offsets and return the adjusted one,
  226. // if it matches a previous offset.
  227. func (b *blockEnc) matchOffset(offset, lits uint32) uint32 {
  228. // Check if offset is one of the recent offsets.
  229. // Adjusts the output offset accordingly.
  230. // Gives a tiny bit of compression, typically around 1%.
  231. if true {
  232. if lits > 0 {
  233. switch offset {
  234. case b.recentOffsets[0]:
  235. offset = 1
  236. case b.recentOffsets[1]:
  237. b.recentOffsets[1] = b.recentOffsets[0]
  238. b.recentOffsets[0] = offset
  239. offset = 2
  240. case b.recentOffsets[2]:
  241. b.recentOffsets[2] = b.recentOffsets[1]
  242. b.recentOffsets[1] = b.recentOffsets[0]
  243. b.recentOffsets[0] = offset
  244. offset = 3
  245. default:
  246. b.recentOffsets[2] = b.recentOffsets[1]
  247. b.recentOffsets[1] = b.recentOffsets[0]
  248. b.recentOffsets[0] = offset
  249. offset += 3
  250. }
  251. } else {
  252. switch offset {
  253. case b.recentOffsets[1]:
  254. b.recentOffsets[1] = b.recentOffsets[0]
  255. b.recentOffsets[0] = offset
  256. offset = 1
  257. case b.recentOffsets[2]:
  258. b.recentOffsets[2] = b.recentOffsets[1]
  259. b.recentOffsets[1] = b.recentOffsets[0]
  260. b.recentOffsets[0] = offset
  261. offset = 2
  262. case b.recentOffsets[0] - 1:
  263. b.recentOffsets[2] = b.recentOffsets[1]
  264. b.recentOffsets[1] = b.recentOffsets[0]
  265. b.recentOffsets[0] = offset
  266. offset = 3
  267. default:
  268. b.recentOffsets[2] = b.recentOffsets[1]
  269. b.recentOffsets[1] = b.recentOffsets[0]
  270. b.recentOffsets[0] = offset
  271. offset += 3
  272. }
  273. }
  274. } else {
  275. offset += 3
  276. }
  277. return offset
  278. }
  279. // encodeRaw can be used to set the output to a raw representation of supplied bytes.
  280. func (b *blockEnc) encodeRaw(a []byte) {
  281. var bh blockHeader
  282. bh.setLast(b.last)
  283. bh.setSize(uint32(len(a)))
  284. bh.setType(blockTypeRaw)
  285. b.output = bh.appendTo(b.output[:0])
  286. b.output = append(b.output, a...)
  287. if debugEncoder {
  288. println("Adding RAW block, length", len(a), "last:", b.last)
  289. }
  290. }
  291. // encodeRaw can be used to set the output to a raw representation of supplied bytes.
  292. func (b *blockEnc) encodeRawTo(dst, src []byte) []byte {
  293. var bh blockHeader
  294. bh.setLast(b.last)
  295. bh.setSize(uint32(len(src)))
  296. bh.setType(blockTypeRaw)
  297. dst = bh.appendTo(dst)
  298. dst = append(dst, src...)
  299. if debugEncoder {
  300. println("Adding RAW block, length", len(src), "last:", b.last)
  301. }
  302. return dst
  303. }
  304. // encodeLits can be used if the block is only litLen.
  305. func (b *blockEnc) encodeLits(lits []byte, raw bool) error {
  306. var bh blockHeader
  307. bh.setLast(b.last)
  308. bh.setSize(uint32(len(lits)))
  309. // Don't compress extremely small blocks
  310. if len(lits) < 8 || (len(lits) < 32 && b.dictLitEnc == nil) || raw {
  311. if debugEncoder {
  312. println("Adding RAW block, length", len(lits), "last:", b.last)
  313. }
  314. bh.setType(blockTypeRaw)
  315. b.output = bh.appendTo(b.output)
  316. b.output = append(b.output, lits...)
  317. return nil
  318. }
  319. var (
  320. out []byte
  321. reUsed, single bool
  322. err error
  323. )
  324. if b.dictLitEnc != nil {
  325. b.litEnc.TransferCTable(b.dictLitEnc)
  326. b.litEnc.Reuse = huff0.ReusePolicyAllow
  327. b.dictLitEnc = nil
  328. }
  329. if len(lits) >= 1024 {
  330. // Use 4 Streams.
  331. out, reUsed, err = huff0.Compress4X(lits, b.litEnc)
  332. } else if len(lits) > 32 {
  333. // Use 1 stream
  334. single = true
  335. out, reUsed, err = huff0.Compress1X(lits, b.litEnc)
  336. } else {
  337. err = huff0.ErrIncompressible
  338. }
  339. switch err {
  340. case huff0.ErrIncompressible:
  341. if debugEncoder {
  342. println("Adding RAW block, length", len(lits), "last:", b.last)
  343. }
  344. bh.setType(blockTypeRaw)
  345. b.output = bh.appendTo(b.output)
  346. b.output = append(b.output, lits...)
  347. return nil
  348. case huff0.ErrUseRLE:
  349. if debugEncoder {
  350. println("Adding RLE block, length", len(lits))
  351. }
  352. bh.setType(blockTypeRLE)
  353. b.output = bh.appendTo(b.output)
  354. b.output = append(b.output, lits[0])
  355. return nil
  356. case nil:
  357. default:
  358. return err
  359. }
  360. // Compressed...
  361. // Now, allow reuse
  362. b.litEnc.Reuse = huff0.ReusePolicyAllow
  363. bh.setType(blockTypeCompressed)
  364. var lh literalsHeader
  365. if reUsed {
  366. if debugEncoder {
  367. println("Reused tree, compressed to", len(out))
  368. }
  369. lh.setType(literalsBlockTreeless)
  370. } else {
  371. if debugEncoder {
  372. println("New tree, compressed to", len(out), "tree size:", len(b.litEnc.OutTable))
  373. }
  374. lh.setType(literalsBlockCompressed)
  375. }
  376. // Set sizes
  377. lh.setSizes(len(out), len(lits), single)
  378. bh.setSize(uint32(len(out) + lh.size() + 1))
  379. // Write block headers.
  380. b.output = bh.appendTo(b.output)
  381. b.output = lh.appendTo(b.output)
  382. // Add compressed data.
  383. b.output = append(b.output, out...)
  384. // No sequences.
  385. b.output = append(b.output, 0)
  386. return nil
  387. }
  388. // fuzzFseEncoder can be used to fuzz the FSE encoder.
  389. func fuzzFseEncoder(data []byte) int {
  390. if len(data) > maxSequences || len(data) < 2 {
  391. return 0
  392. }
  393. enc := fseEncoder{}
  394. hist := enc.Histogram()
  395. maxSym := uint8(0)
  396. for i, v := range data {
  397. v = v & 63
  398. data[i] = v
  399. hist[v]++
  400. if v > maxSym {
  401. maxSym = v
  402. }
  403. }
  404. if maxSym == 0 {
  405. // All 0
  406. return 0
  407. }
  408. maxCount := func(a []uint32) int {
  409. var max uint32
  410. for _, v := range a {
  411. if v > max {
  412. max = v
  413. }
  414. }
  415. return int(max)
  416. }
  417. cnt := maxCount(hist[:maxSym])
  418. if cnt == len(data) {
  419. // RLE
  420. return 0
  421. }
  422. enc.HistogramFinished(maxSym, cnt)
  423. err := enc.normalizeCount(len(data))
  424. if err != nil {
  425. return 0
  426. }
  427. _, err = enc.writeCount(nil)
  428. if err != nil {
  429. panic(err)
  430. }
  431. return 1
  432. }
  433. // encode will encode the block and append the output in b.output.
  434. // Previous offset codes must be pushed if more blocks are expected.
  435. func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error {
  436. if len(b.sequences) == 0 {
  437. return b.encodeLits(b.literals, rawAllLits)
  438. }
  439. // We want some difference to at least account for the headers.
  440. saved := b.size - len(b.literals) - (b.size >> 6)
  441. if saved < 16 {
  442. if org == nil {
  443. return errIncompressible
  444. }
  445. b.popOffsets()
  446. return b.encodeLits(org, rawAllLits)
  447. }
  448. var bh blockHeader
  449. var lh literalsHeader
  450. bh.setLast(b.last)
  451. bh.setType(blockTypeCompressed)
  452. // Store offset of the block header. Needed when we know the size.
  453. bhOffset := len(b.output)
  454. b.output = bh.appendTo(b.output)
  455. var (
  456. out []byte
  457. reUsed, single bool
  458. err error
  459. )
  460. if b.dictLitEnc != nil {
  461. b.litEnc.TransferCTable(b.dictLitEnc)
  462. b.litEnc.Reuse = huff0.ReusePolicyAllow
  463. b.dictLitEnc = nil
  464. }
  465. if len(b.literals) >= 1024 && !raw {
  466. // Use 4 Streams.
  467. out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc)
  468. } else if len(b.literals) > 32 && !raw {
  469. // Use 1 stream
  470. single = true
  471. out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc)
  472. } else {
  473. err = huff0.ErrIncompressible
  474. }
  475. switch err {
  476. case huff0.ErrIncompressible:
  477. lh.setType(literalsBlockRaw)
  478. lh.setSize(len(b.literals))
  479. b.output = lh.appendTo(b.output)
  480. b.output = append(b.output, b.literals...)
  481. if debugEncoder {
  482. println("Adding literals RAW, length", len(b.literals))
  483. }
  484. case huff0.ErrUseRLE:
  485. lh.setType(literalsBlockRLE)
  486. lh.setSize(len(b.literals))
  487. b.output = lh.appendTo(b.output)
  488. b.output = append(b.output, b.literals[0])
  489. if debugEncoder {
  490. println("Adding literals RLE")
  491. }
  492. case nil:
  493. // Compressed litLen...
  494. if reUsed {
  495. if debugEncoder {
  496. println("reused tree")
  497. }
  498. lh.setType(literalsBlockTreeless)
  499. } else {
  500. if debugEncoder {
  501. println("new tree, size:", len(b.litEnc.OutTable))
  502. }
  503. lh.setType(literalsBlockCompressed)
  504. if debugEncoder {
  505. _, _, err := huff0.ReadTable(out, nil)
  506. if err != nil {
  507. panic(err)
  508. }
  509. }
  510. }
  511. lh.setSizes(len(out), len(b.literals), single)
  512. if debugEncoder {
  513. printf("Compressed %d literals to %d bytes", len(b.literals), len(out))
  514. println("Adding literal header:", lh)
  515. }
  516. b.output = lh.appendTo(b.output)
  517. b.output = append(b.output, out...)
  518. b.litEnc.Reuse = huff0.ReusePolicyAllow
  519. if debugEncoder {
  520. println("Adding literals compressed")
  521. }
  522. default:
  523. if debugEncoder {
  524. println("Adding literals ERROR:", err)
  525. }
  526. return err
  527. }
  528. // Sequence compression
  529. // Write the number of sequences
  530. switch {
  531. case len(b.sequences) < 128:
  532. b.output = append(b.output, uint8(len(b.sequences)))
  533. case len(b.sequences) < 0x7f00: // TODO: this could be wrong
  534. n := len(b.sequences)
  535. b.output = append(b.output, 128+uint8(n>>8), uint8(n))
  536. default:
  537. n := len(b.sequences) - 0x7f00
  538. b.output = append(b.output, 255, uint8(n), uint8(n>>8))
  539. }
  540. if debugEncoder {
  541. println("Encoding", len(b.sequences), "sequences")
  542. }
  543. b.genCodes()
  544. llEnc := b.coders.llEnc
  545. ofEnc := b.coders.ofEnc
  546. mlEnc := b.coders.mlEnc
  547. err = llEnc.normalizeCount(len(b.sequences))
  548. if err != nil {
  549. return err
  550. }
  551. err = ofEnc.normalizeCount(len(b.sequences))
  552. if err != nil {
  553. return err
  554. }
  555. err = mlEnc.normalizeCount(len(b.sequences))
  556. if err != nil {
  557. return err
  558. }
  559. // Choose the best compression mode for each type.
  560. // Will evaluate the new vs predefined and previous.
  561. chooseComp := func(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) {
  562. // See if predefined/previous is better
  563. hist := cur.count[:cur.symbolLen]
  564. nSize := cur.approxSize(hist) + cur.maxHeaderSize()
  565. predefSize := preDef.approxSize(hist)
  566. prevSize := prev.approxSize(hist)
  567. // Add a small penalty for new encoders.
  568. // Don't bother with extremely small (<2 byte gains).
  569. nSize = nSize + (nSize+2*8*16)>>4
  570. switch {
  571. case predefSize <= prevSize && predefSize <= nSize || forcePreDef:
  572. if debugEncoder {
  573. println("Using predefined", predefSize>>3, "<=", nSize>>3)
  574. }
  575. return preDef, compModePredefined
  576. case prevSize <= nSize:
  577. if debugEncoder {
  578. println("Using previous", prevSize>>3, "<=", nSize>>3)
  579. }
  580. return prev, compModeRepeat
  581. default:
  582. if debugEncoder {
  583. println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes")
  584. println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen])
  585. }
  586. return cur, compModeFSE
  587. }
  588. }
  589. // Write compression mode
  590. var mode uint8
  591. if llEnc.useRLE {
  592. mode |= uint8(compModeRLE) << 6
  593. llEnc.setRLE(b.sequences[0].llCode)
  594. if debugEncoder {
  595. println("llEnc.useRLE")
  596. }
  597. } else {
  598. var m seqCompMode
  599. llEnc, m = chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths])
  600. mode |= uint8(m) << 6
  601. }
  602. if ofEnc.useRLE {
  603. mode |= uint8(compModeRLE) << 4
  604. ofEnc.setRLE(b.sequences[0].ofCode)
  605. if debugEncoder {
  606. println("ofEnc.useRLE")
  607. }
  608. } else {
  609. var m seqCompMode
  610. ofEnc, m = chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets])
  611. mode |= uint8(m) << 4
  612. }
  613. if mlEnc.useRLE {
  614. mode |= uint8(compModeRLE) << 2
  615. mlEnc.setRLE(b.sequences[0].mlCode)
  616. if debugEncoder {
  617. println("mlEnc.useRLE, code: ", b.sequences[0].mlCode, "value", b.sequences[0].matchLen)
  618. }
  619. } else {
  620. var m seqCompMode
  621. mlEnc, m = chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths])
  622. mode |= uint8(m) << 2
  623. }
  624. b.output = append(b.output, mode)
  625. if debugEncoder {
  626. printf("Compression modes: 0b%b", mode)
  627. }
  628. b.output, err = llEnc.writeCount(b.output)
  629. if err != nil {
  630. return err
  631. }
  632. start := len(b.output)
  633. b.output, err = ofEnc.writeCount(b.output)
  634. if err != nil {
  635. return err
  636. }
  637. if false {
  638. println("block:", b.output[start:], "tablelog", ofEnc.actualTableLog, "maxcount:", ofEnc.maxCount)
  639. fmt.Printf("selected TableLog: %d, Symbol length: %d\n", ofEnc.actualTableLog, ofEnc.symbolLen)
  640. for i, v := range ofEnc.norm[:ofEnc.symbolLen] {
  641. fmt.Printf("%3d: %5d -> %4d \n", i, ofEnc.count[i], v)
  642. }
  643. }
  644. b.output, err = mlEnc.writeCount(b.output)
  645. if err != nil {
  646. return err
  647. }
  648. // Maybe in block?
  649. wr := &b.wr
  650. wr.reset(b.output)
  651. var ll, of, ml cState
  652. // Current sequence
  653. seq := len(b.sequences) - 1
  654. s := b.sequences[seq]
  655. llEnc.setBits(llBitsTable[:])
  656. mlEnc.setBits(mlBitsTable[:])
  657. ofEnc.setBits(nil)
  658. llTT, ofTT, mlTT := llEnc.ct.symbolTT[:256], ofEnc.ct.symbolTT[:256], mlEnc.ct.symbolTT[:256]
  659. // We have 3 bounds checks here (and in the loop).
  660. // Since we are iterating backwards it is kinda hard to avoid.
  661. llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode]
  662. ll.init(wr, &llEnc.ct, llB)
  663. of.init(wr, &ofEnc.ct, ofB)
  664. wr.flush32()
  665. ml.init(wr, &mlEnc.ct, mlB)
  666. // Each of these lookups also generates a bounds check.
  667. wr.addBits32NC(s.litLen, llB.outBits)
  668. wr.addBits32NC(s.matchLen, mlB.outBits)
  669. wr.flush32()
  670. wr.addBits32NC(s.offset, ofB.outBits)
  671. if debugSequences {
  672. println("Encoded seq", seq, s, "codes:", s.llCode, s.mlCode, s.ofCode, "states:", ll.state, ml.state, of.state, "bits:", llB, mlB, ofB)
  673. }
  674. seq--
  675. // Store sequences in reverse...
  676. for seq >= 0 {
  677. s = b.sequences[seq]
  678. ofB := ofTT[s.ofCode]
  679. wr.flush32() // tablelog max is below 8 for each, so it will fill max 24 bits.
  680. //of.encode(ofB)
  681. nbBitsOut := (uint32(of.state) + ofB.deltaNbBits) >> 16
  682. dstState := int32(of.state>>(nbBitsOut&15)) + int32(ofB.deltaFindState)
  683. wr.addBits16NC(of.state, uint8(nbBitsOut))
  684. of.state = of.stateTable[dstState]
  685. // Accumulate extra bits.
  686. outBits := ofB.outBits & 31
  687. extraBits := uint64(s.offset & bitMask32[outBits])
  688. extraBitsN := outBits
  689. mlB := mlTT[s.mlCode]
  690. //ml.encode(mlB)
  691. nbBitsOut = (uint32(ml.state) + mlB.deltaNbBits) >> 16
  692. dstState = int32(ml.state>>(nbBitsOut&15)) + int32(mlB.deltaFindState)
  693. wr.addBits16NC(ml.state, uint8(nbBitsOut))
  694. ml.state = ml.stateTable[dstState]
  695. outBits = mlB.outBits & 31
  696. extraBits = extraBits<<outBits | uint64(s.matchLen&bitMask32[outBits])
  697. extraBitsN += outBits
  698. llB := llTT[s.llCode]
  699. //ll.encode(llB)
  700. nbBitsOut = (uint32(ll.state) + llB.deltaNbBits) >> 16
  701. dstState = int32(ll.state>>(nbBitsOut&15)) + int32(llB.deltaFindState)
  702. wr.addBits16NC(ll.state, uint8(nbBitsOut))
  703. ll.state = ll.stateTable[dstState]
  704. outBits = llB.outBits & 31
  705. extraBits = extraBits<<outBits | uint64(s.litLen&bitMask32[outBits])
  706. extraBitsN += outBits
  707. wr.flush32()
  708. wr.addBits64NC(extraBits, extraBitsN)
  709. if debugSequences {
  710. println("Encoded seq", seq, s)
  711. }
  712. seq--
  713. }
  714. ml.flush(mlEnc.actualTableLog)
  715. of.flush(ofEnc.actualTableLog)
  716. ll.flush(llEnc.actualTableLog)
  717. err = wr.close()
  718. if err != nil {
  719. return err
  720. }
  721. b.output = wr.out
  722. // Maybe even add a bigger margin.
  723. if len(b.output)-3-bhOffset >= b.size {
  724. // Discard and encode as raw block.
  725. b.output = b.encodeRawTo(b.output[:bhOffset], org)
  726. b.popOffsets()
  727. b.litEnc.Reuse = huff0.ReusePolicyNone
  728. return nil
  729. }
  730. // Size is output minus block header.
  731. bh.setSize(uint32(len(b.output)-bhOffset) - 3)
  732. if debugEncoder {
  733. println("Rewriting block header", bh)
  734. }
  735. _ = bh.appendTo(b.output[bhOffset:bhOffset])
  736. b.coders.setPrev(llEnc, mlEnc, ofEnc)
  737. return nil
  738. }
  739. var errIncompressible = errors.New("incompressible")
  740. func (b *blockEnc) genCodes() {
  741. if len(b.sequences) == 0 {
  742. // nothing to do
  743. return
  744. }
  745. if len(b.sequences) > math.MaxUint16 {
  746. panic("can only encode up to 64K sequences")
  747. }
  748. // No bounds checks after here:
  749. llH := b.coders.llEnc.Histogram()
  750. ofH := b.coders.ofEnc.Histogram()
  751. mlH := b.coders.mlEnc.Histogram()
  752. for i := range llH {
  753. llH[i] = 0
  754. }
  755. for i := range ofH {
  756. ofH[i] = 0
  757. }
  758. for i := range mlH {
  759. mlH[i] = 0
  760. }
  761. var llMax, ofMax, mlMax uint8
  762. for i := range b.sequences {
  763. seq := &b.sequences[i]
  764. v := llCode(seq.litLen)
  765. seq.llCode = v
  766. llH[v]++
  767. if v > llMax {
  768. llMax = v
  769. }
  770. v = ofCode(seq.offset)
  771. seq.ofCode = v
  772. ofH[v]++
  773. if v > ofMax {
  774. ofMax = v
  775. }
  776. v = mlCode(seq.matchLen)
  777. seq.mlCode = v
  778. mlH[v]++
  779. if v > mlMax {
  780. mlMax = v
  781. if debugAsserts && mlMax > maxMatchLengthSymbol {
  782. panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d), matchlen: %d", mlMax, seq.matchLen))
  783. }
  784. }
  785. }
  786. maxCount := func(a []uint32) int {
  787. var max uint32
  788. for _, v := range a {
  789. if v > max {
  790. max = v
  791. }
  792. }
  793. return int(max)
  794. }
  795. if debugAsserts && mlMax > maxMatchLengthSymbol {
  796. panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d)", mlMax))
  797. }
  798. if debugAsserts && ofMax > maxOffsetBits {
  799. panic(fmt.Errorf("ofMax > maxOffsetBits (%d)", ofMax))
  800. }
  801. if debugAsserts && llMax > maxLiteralLengthSymbol {
  802. panic(fmt.Errorf("llMax > maxLiteralLengthSymbol (%d)", llMax))
  803. }
  804. b.coders.mlEnc.HistogramFinished(mlMax, maxCount(mlH[:mlMax+1]))
  805. b.coders.ofEnc.HistogramFinished(ofMax, maxCount(ofH[:ofMax+1]))
  806. b.coders.llEnc.HistogramFinished(llMax, maxCount(llH[:llMax+1]))
  807. }