enc_best.go 16 KB

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