enc_best.go 16 KB

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