enc_best.go 16 KB

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