enc_best.go 16 KB

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