enc_best.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. "bytes"
  7. "fmt"
  8. "github.com/klauspost/compress"
  9. )
  10. const (
  11. bestLongTableBits = 22 // Bits used in the long match table
  12. bestLongTableSize = 1 << bestLongTableBits // Size of the table
  13. bestLongLen = 8 // Bytes used for table hash
  14. // Note: Increasing the short table bits or making the hash shorter
  15. // can actually lead to compression degradation since it will 'steal' more from the
  16. // long match table and match offsets are quite big.
  17. // This greatly depends on the type of input.
  18. bestShortTableBits = 18 // Bits used in the short match table
  19. bestShortTableSize = 1 << bestShortTableBits // Size of the table
  20. bestShortLen = 4 // Bytes used for table hash
  21. )
  22. type match struct {
  23. offset int32
  24. s int32
  25. length int32
  26. rep int32
  27. est int32
  28. }
  29. const highScore = 25000
  30. // estBits will estimate output bits from predefined tables.
  31. func (m *match) estBits(bitsPerByte int32) {
  32. mlc := mlCode(uint32(m.length - zstdMinMatch))
  33. var ofc uint8
  34. if m.rep < 0 {
  35. ofc = ofCode(uint32(m.s-m.offset) + 3)
  36. } else {
  37. ofc = ofCode(uint32(m.rep))
  38. }
  39. // Cost, excluding
  40. ofTT, mlTT := fsePredefEnc[tableOffsets].ct.symbolTT[ofc], fsePredefEnc[tableMatchLengths].ct.symbolTT[mlc]
  41. // Add cost of match encoding...
  42. m.est = int32(ofTT.outBits + mlTT.outBits)
  43. m.est += int32(ofTT.deltaNbBits>>16 + mlTT.deltaNbBits>>16)
  44. // Subtract savings compared to literal encoding...
  45. m.est -= (m.length * bitsPerByte) >> 10
  46. if m.est > 0 {
  47. // Unlikely gain..
  48. m.length = 0
  49. m.est = highScore
  50. }
  51. }
  52. // bestFastEncoder uses 2 tables, one for short matches (5 bytes) and one for long matches.
  53. // The long match table contains the previous entry with the same hash,
  54. // effectively making it a "chain" of length 2.
  55. // When we find a long match we choose between the two values and select the longest.
  56. // When we find a short match, after checking the long, we check if we can find a long at n+1
  57. // and that it is longer (lazy matching).
  58. type bestFastEncoder struct {
  59. fastBase
  60. table [bestShortTableSize]prevEntry
  61. longTable [bestLongTableSize]prevEntry
  62. dictTable []prevEntry
  63. dictLongTable []prevEntry
  64. }
  65. // Encode improves compression...
  66. func (e *bestFastEncoder) Encode(blk *blockEnc, src []byte) {
  67. const (
  68. // Input margin is the number of bytes we read (8)
  69. // and the maximum we will read ahead (2)
  70. inputMargin = 8 + 4
  71. minNonLiteralBlockSize = 16
  72. )
  73. // Protect against e.cur wraparound.
  74. for e.cur >= e.bufferReset-int32(len(e.hist)) {
  75. if len(e.hist) == 0 {
  76. e.table = [bestShortTableSize]prevEntry{}
  77. e.longTable = [bestLongTableSize]prevEntry{}
  78. e.cur = e.maxMatchOff
  79. break
  80. }
  81. // Shift down everything in the table that isn't already too far away.
  82. minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff
  83. for i := range e.table[:] {
  84. v := e.table[i].offset
  85. v2 := e.table[i].prev
  86. if v < minOff {
  87. v = 0
  88. v2 = 0
  89. } else {
  90. v = v - e.cur + e.maxMatchOff
  91. if v2 < minOff {
  92. v2 = 0
  93. } else {
  94. v2 = v2 - e.cur + e.maxMatchOff
  95. }
  96. }
  97. e.table[i] = prevEntry{
  98. offset: v,
  99. prev: v2,
  100. }
  101. }
  102. for i := range e.longTable[:] {
  103. v := e.longTable[i].offset
  104. v2 := e.longTable[i].prev
  105. if v < minOff {
  106. v = 0
  107. v2 = 0
  108. } else {
  109. v = v - e.cur + e.maxMatchOff
  110. if v2 < minOff {
  111. v2 = 0
  112. } else {
  113. v2 = v2 - e.cur + e.maxMatchOff
  114. }
  115. }
  116. e.longTable[i] = prevEntry{
  117. offset: v,
  118. prev: v2,
  119. }
  120. }
  121. e.cur = e.maxMatchOff
  122. break
  123. }
  124. s := e.addBlock(src)
  125. blk.size = len(src)
  126. if len(src) < minNonLiteralBlockSize {
  127. blk.extraLits = len(src)
  128. blk.literals = blk.literals[:len(src)]
  129. copy(blk.literals, src)
  130. return
  131. }
  132. // Use this to estimate literal cost.
  133. // Scaled by 10 bits.
  134. bitsPerByte := int32((compress.ShannonEntropyBits(src) * 1024) / len(src))
  135. // Huffman can never go < 1 bit/byte
  136. if bitsPerByte < 1024 {
  137. bitsPerByte = 1024
  138. }
  139. // Override src
  140. src = e.hist
  141. sLimit := int32(len(src)) - inputMargin
  142. const kSearchStrength = 10
  143. // nextEmit is where in src the next emitLiteral should start from.
  144. nextEmit := s
  145. cv := load6432(src, s)
  146. // Relative offsets
  147. offset1 := int32(blk.recentOffsets[0])
  148. offset2 := int32(blk.recentOffsets[1])
  149. offset3 := int32(blk.recentOffsets[2])
  150. addLiterals := func(s *seq, until int32) {
  151. if until == nextEmit {
  152. return
  153. }
  154. blk.literals = append(blk.literals, src[nextEmit:until]...)
  155. s.litLen = uint32(until - nextEmit)
  156. }
  157. _ = addLiterals
  158. if debugEncoder {
  159. println("recent offsets:", blk.recentOffsets)
  160. }
  161. encodeLoop:
  162. for {
  163. // We allow the encoder to optionally turn off repeat offsets across blocks
  164. canRepeat := len(blk.sequences) > 2
  165. if debugAsserts && canRepeat && offset1 == 0 {
  166. panic("offset0 was 0")
  167. }
  168. const goodEnough = 100
  169. nextHashL := hashLen(cv, bestLongTableBits, bestLongLen)
  170. nextHashS := hashLen(cv, bestShortTableBits, bestShortLen)
  171. candidateL := e.longTable[nextHashL]
  172. candidateS := e.table[nextHashS]
  173. // Set m to a match at offset if it looks like that will improve compression.
  174. improve := func(m *match, offset int32, s int32, first uint32, rep int32) {
  175. if s-offset >= e.maxMatchOff || load3232(src, offset) != first {
  176. return
  177. }
  178. if debugAsserts {
  179. if !bytes.Equal(src[s:s+4], src[offset:offset+4]) {
  180. panic(fmt.Sprintf("first match mismatch: %v != %v, first: %08x", src[s:s+4], src[offset:offset+4], first))
  181. }
  182. }
  183. cand := match{offset: offset, s: s, length: 4 + e.matchlen(s+4, offset+4, src), rep: rep}
  184. cand.estBits(bitsPerByte)
  185. if m.est >= highScore || cand.est-m.est+(cand.s-m.s)*bitsPerByte>>10 < 0 {
  186. *m = cand
  187. }
  188. }
  189. best := match{s: s, est: highScore}
  190. improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1)
  191. improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1)
  192. improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1)
  193. improve(&best, candidateS.prev-e.cur, s, uint32(cv), -1)
  194. if canRepeat && best.length < goodEnough {
  195. cv32 := uint32(cv >> 8)
  196. spp := s + 1
  197. improve(&best, spp-offset1, spp, cv32, 1)
  198. improve(&best, spp-offset2, spp, cv32, 2)
  199. improve(&best, spp-offset3, spp, cv32, 3)
  200. if best.length > 0 {
  201. cv32 = uint32(cv >> 24)
  202. spp += 2
  203. improve(&best, spp-offset1, spp, cv32, 1)
  204. improve(&best, spp-offset2, spp, cv32, 2)
  205. improve(&best, spp-offset3, spp, cv32, 3)
  206. }
  207. }
  208. // Load next and check...
  209. e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: candidateL.offset}
  210. e.table[nextHashS] = prevEntry{offset: s + e.cur, prev: candidateS.offset}
  211. // Look far ahead, unless we have a really long match already...
  212. if best.length < goodEnough {
  213. // No match found, move forward on input, no need to check forward...
  214. if best.length < 4 {
  215. s += 1 + (s-nextEmit)>>(kSearchStrength-1)
  216. if s >= sLimit {
  217. break encodeLoop
  218. }
  219. cv = load6432(src, s)
  220. continue
  221. }
  222. s++
  223. candidateS = e.table[hashLen(cv>>8, bestShortTableBits, bestShortLen)]
  224. cv = load6432(src, s)
  225. cv2 := load6432(src, s+1)
  226. candidateL = e.longTable[hashLen(cv, bestLongTableBits, bestLongLen)]
  227. candidateL2 := e.longTable[hashLen(cv2, bestLongTableBits, bestLongLen)]
  228. // Short at s+1
  229. improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1)
  230. // Long at s+1, s+2
  231. improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1)
  232. improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1)
  233. improve(&best, candidateL2.offset-e.cur, s+1, uint32(cv2), -1)
  234. improve(&best, candidateL2.prev-e.cur, s+1, uint32(cv2), -1)
  235. if false {
  236. // Short at s+3.
  237. // Too often worse...
  238. improve(&best, e.table[hashLen(cv2>>8, bestShortTableBits, bestShortLen)].offset-e.cur, s+2, uint32(cv2>>8), -1)
  239. }
  240. // See if we can find a better match by checking where the current best ends.
  241. // Use that offset to see if we can find a better full match.
  242. if sAt := best.s + best.length; sAt < sLimit {
  243. nextHashL := hashLen(load6432(src, sAt), bestLongTableBits, bestLongLen)
  244. candidateEnd := e.longTable[nextHashL]
  245. // Start check at a fixed offset to allow for a few mismatches.
  246. // For this compression level 2 yields the best results.
  247. const skipBeginning = 2
  248. if pos := candidateEnd.offset - e.cur - best.length + skipBeginning; pos >= 0 {
  249. improve(&best, pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1)
  250. if pos := candidateEnd.prev - e.cur - best.length + skipBeginning; pos >= 0 {
  251. improve(&best, pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1)
  252. }
  253. }
  254. }
  255. }
  256. if debugAsserts {
  257. if !bytes.Equal(src[best.s:best.s+best.length], src[best.offset:best.offset+best.length]) {
  258. panic(fmt.Sprintf("match mismatch: %v != %v", src[best.s:best.s+best.length], src[best.offset:best.offset+best.length]))
  259. }
  260. }
  261. // We have a match, we can store the forward value
  262. if best.rep > 0 {
  263. s = best.s
  264. var seq seq
  265. seq.matchLen = uint32(best.length - zstdMinMatch)
  266. // We might be able to match backwards.
  267. // Extend as long as we can.
  268. start := best.s
  269. // We end the search early, so we don't risk 0 literals
  270. // and have to do special offset treatment.
  271. startLimit := nextEmit + 1
  272. tMin := s - e.maxMatchOff
  273. if tMin < 0 {
  274. tMin = 0
  275. }
  276. repIndex := best.offset
  277. for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 {
  278. repIndex--
  279. start--
  280. seq.matchLen++
  281. }
  282. addLiterals(&seq, start)
  283. // rep 0
  284. seq.offset = uint32(best.rep)
  285. if debugSequences {
  286. println("repeat sequence", seq, "next s:", s)
  287. }
  288. blk.sequences = append(blk.sequences, seq)
  289. // Index match start+1 (long) -> s - 1
  290. index0 := s
  291. s = best.s + best.length
  292. nextEmit = s
  293. if s >= sLimit {
  294. if debugEncoder {
  295. println("repeat ended", s, best.length)
  296. }
  297. break encodeLoop
  298. }
  299. // Index skipped...
  300. off := index0 + e.cur
  301. for index0 < s-1 {
  302. cv0 := load6432(src, index0)
  303. h0 := hashLen(cv0, bestLongTableBits, bestLongLen)
  304. h1 := hashLen(cv0, bestShortTableBits, bestShortLen)
  305. e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset}
  306. e.table[h1] = prevEntry{offset: off, prev: e.table[h1].offset}
  307. off++
  308. index0++
  309. }
  310. switch best.rep {
  311. case 2:
  312. offset1, offset2 = offset2, offset1
  313. case 3:
  314. offset1, offset2, offset3 = offset3, offset1, offset2
  315. }
  316. cv = load6432(src, s)
  317. continue
  318. }
  319. // A 4-byte match has been found. Update recent offsets.
  320. // We'll later see if more than 4 bytes.
  321. s = best.s
  322. t := best.offset
  323. offset1, offset2, offset3 = s-t, offset1, offset2
  324. if debugAsserts && s <= t {
  325. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  326. }
  327. if debugAsserts && int(offset1) > len(src) {
  328. panic("invalid offset")
  329. }
  330. // Extend the n-byte match as long as possible.
  331. l := best.length
  332. // Extend backwards
  333. tMin := s - e.maxMatchOff
  334. if tMin < 0 {
  335. tMin = 0
  336. }
  337. for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength {
  338. s--
  339. t--
  340. l++
  341. }
  342. // Write our sequence
  343. var seq seq
  344. seq.litLen = uint32(s - nextEmit)
  345. seq.matchLen = uint32(l - zstdMinMatch)
  346. if seq.litLen > 0 {
  347. blk.literals = append(blk.literals, src[nextEmit:s]...)
  348. }
  349. seq.offset = uint32(s-t) + 3
  350. s += l
  351. if debugSequences {
  352. println("sequence", seq, "next s:", s)
  353. }
  354. blk.sequences = append(blk.sequences, seq)
  355. nextEmit = s
  356. if s >= sLimit {
  357. break encodeLoop
  358. }
  359. // Index match start+1 (long) -> s - 1
  360. index0 := s - l + 1
  361. // every entry
  362. for index0 < s-1 {
  363. cv0 := load6432(src, index0)
  364. h0 := hashLen(cv0, bestLongTableBits, bestLongLen)
  365. h1 := hashLen(cv0, bestShortTableBits, bestShortLen)
  366. off := index0 + e.cur
  367. e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset}
  368. e.table[h1] = prevEntry{offset: off, prev: e.table[h1].offset}
  369. index0++
  370. }
  371. cv = load6432(src, s)
  372. if !canRepeat {
  373. continue
  374. }
  375. // Check offset 2
  376. for {
  377. o2 := s - offset2
  378. if load3232(src, o2) != uint32(cv) {
  379. // Do regular search
  380. break
  381. }
  382. // Store this, since we have it.
  383. nextHashS := hashLen(cv, bestShortTableBits, bestShortLen)
  384. nextHashL := hashLen(cv, bestLongTableBits, bestLongLen)
  385. // We have at least 4 byte match.
  386. // No need to check backwards. We come straight from a match
  387. l := 4 + e.matchlen(s+4, o2+4, src)
  388. e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset}
  389. e.table[nextHashS] = prevEntry{offset: s + e.cur, prev: e.table[nextHashS].offset}
  390. seq.matchLen = uint32(l) - zstdMinMatch
  391. seq.litLen = 0
  392. // Since litlen is always 0, this is offset 1.
  393. seq.offset = 1
  394. s += l
  395. nextEmit = s
  396. if debugSequences {
  397. println("sequence", seq, "next s:", s)
  398. }
  399. blk.sequences = append(blk.sequences, seq)
  400. // Swap offset 1 and 2.
  401. offset1, offset2 = offset2, offset1
  402. if s >= sLimit {
  403. // Finished
  404. break encodeLoop
  405. }
  406. cv = load6432(src, s)
  407. }
  408. }
  409. if int(nextEmit) < len(src) {
  410. blk.literals = append(blk.literals, src[nextEmit:]...)
  411. blk.extraLits = len(src) - int(nextEmit)
  412. }
  413. blk.recentOffsets[0] = uint32(offset1)
  414. blk.recentOffsets[1] = uint32(offset2)
  415. blk.recentOffsets[2] = uint32(offset3)
  416. if debugEncoder {
  417. println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits)
  418. }
  419. }
  420. // EncodeNoHist will encode a block with no history and no following blocks.
  421. // Most notable difference is that src will not be copied for history and
  422. // we do not need to check for max match length.
  423. func (e *bestFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) {
  424. e.ensureHist(len(src))
  425. e.Encode(blk, src)
  426. }
  427. // Reset will reset and set a dictionary if not nil
  428. func (e *bestFastEncoder) Reset(d *dict, singleBlock bool) {
  429. e.resetBase(d, singleBlock)
  430. if d == nil {
  431. return
  432. }
  433. // Init or copy dict table
  434. if len(e.dictTable) != len(e.table) || d.id != e.lastDictID {
  435. if len(e.dictTable) != len(e.table) {
  436. e.dictTable = make([]prevEntry, len(e.table))
  437. }
  438. end := int32(len(d.content)) - 8 + e.maxMatchOff
  439. for i := e.maxMatchOff; i < end; i += 4 {
  440. const hashLog = bestShortTableBits
  441. cv := load6432(d.content, i-e.maxMatchOff)
  442. nextHash := hashLen(cv, hashLog, bestShortLen) // 0 -> 4
  443. nextHash1 := hashLen(cv>>8, hashLog, bestShortLen) // 1 -> 5
  444. nextHash2 := hashLen(cv>>16, hashLog, bestShortLen) // 2 -> 6
  445. nextHash3 := hashLen(cv>>24, hashLog, bestShortLen) // 3 -> 7
  446. e.dictTable[nextHash] = prevEntry{
  447. prev: e.dictTable[nextHash].offset,
  448. offset: i,
  449. }
  450. e.dictTable[nextHash1] = prevEntry{
  451. prev: e.dictTable[nextHash1].offset,
  452. offset: i + 1,
  453. }
  454. e.dictTable[nextHash2] = prevEntry{
  455. prev: e.dictTable[nextHash2].offset,
  456. offset: i + 2,
  457. }
  458. e.dictTable[nextHash3] = prevEntry{
  459. prev: e.dictTable[nextHash3].offset,
  460. offset: i + 3,
  461. }
  462. }
  463. e.lastDictID = d.id
  464. }
  465. // Init or copy dict table
  466. if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID {
  467. if len(e.dictLongTable) != len(e.longTable) {
  468. e.dictLongTable = make([]prevEntry, len(e.longTable))
  469. }
  470. if len(d.content) >= 8 {
  471. cv := load6432(d.content, 0)
  472. h := hashLen(cv, bestLongTableBits, bestLongLen)
  473. e.dictLongTable[h] = prevEntry{
  474. offset: e.maxMatchOff,
  475. prev: e.dictLongTable[h].offset,
  476. }
  477. end := int32(len(d.content)) - 8 + e.maxMatchOff
  478. off := 8 // First to read
  479. for i := e.maxMatchOff + 1; i < end; i++ {
  480. cv = cv>>8 | (uint64(d.content[off]) << 56)
  481. h := hashLen(cv, bestLongTableBits, bestLongLen)
  482. e.dictLongTable[h] = prevEntry{
  483. offset: i,
  484. prev: e.dictLongTable[h].offset,
  485. }
  486. off++
  487. }
  488. }
  489. e.lastDictID = d.id
  490. }
  491. // Reset table to initial state
  492. copy(e.longTable[:], e.dictLongTable)
  493. e.cur = e.maxMatchOff
  494. // Reset table to initial state
  495. copy(e.table[:], e.dictTable)
  496. }