fse_decoder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. "errors"
  7. "fmt"
  8. )
  9. const (
  10. tablelogAbsoluteMax = 9
  11. )
  12. const (
  13. /*!MEMORY_USAGE :
  14. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  15. * Increasing memory usage improves compression ratio
  16. * Reduced memory usage can improve speed, due to cache effect
  17. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  18. maxMemoryUsage = 11
  19. maxTableLog = maxMemoryUsage - 2
  20. maxTablesize = 1 << maxTableLog
  21. maxTableMask = (1 << maxTableLog) - 1
  22. minTablelog = 5
  23. maxSymbolValue = 255
  24. )
  25. // fseDecoder provides temporary storage for compression and decompression.
  26. type fseDecoder struct {
  27. dt [maxTablesize]decSymbol // Decompression table.
  28. symbolLen uint16 // Length of active part of the symbol table.
  29. actualTableLog uint8 // Selected tablelog.
  30. maxBits uint8 // Maximum number of additional bits
  31. // used for table creation to avoid allocations.
  32. stateTable [256]uint16
  33. norm [maxSymbolValue + 1]int16
  34. preDefined bool
  35. }
  36. // tableStep returns the next table index.
  37. func tableStep(tableSize uint32) uint32 {
  38. return (tableSize >> 1) + (tableSize >> 3) + 3
  39. }
  40. // readNCount will read the symbol distribution so decoding tables can be constructed.
  41. func (s *fseDecoder) readNCount(b *byteReader, maxSymbol uint16) error {
  42. var (
  43. charnum uint16
  44. previous0 bool
  45. )
  46. if b.remain() < 4 {
  47. return errors.New("input too small")
  48. }
  49. bitStream := b.Uint32()
  50. nbBits := uint((bitStream & 0xF) + minTablelog) // extract tableLog
  51. if nbBits > tablelogAbsoluteMax {
  52. println("Invalid tablelog:", nbBits)
  53. return errors.New("tableLog too large")
  54. }
  55. bitStream >>= 4
  56. bitCount := uint(4)
  57. s.actualTableLog = uint8(nbBits)
  58. remaining := int32((1 << nbBits) + 1)
  59. threshold := int32(1 << nbBits)
  60. gotTotal := int32(0)
  61. nbBits++
  62. for remaining > 1 && charnum <= maxSymbol {
  63. if previous0 {
  64. //println("prev0")
  65. n0 := charnum
  66. for (bitStream & 0xFFFF) == 0xFFFF {
  67. //println("24 x 0")
  68. n0 += 24
  69. if r := b.remain(); r > 5 {
  70. b.advance(2)
  71. bitStream = b.Uint32() >> bitCount
  72. } else {
  73. // end of bit stream
  74. bitStream >>= 16
  75. bitCount += 16
  76. }
  77. }
  78. //printf("bitstream: %d, 0b%b", bitStream&3, bitStream)
  79. for (bitStream & 3) == 3 {
  80. n0 += 3
  81. bitStream >>= 2
  82. bitCount += 2
  83. }
  84. n0 += uint16(bitStream & 3)
  85. bitCount += 2
  86. if n0 > maxSymbolValue {
  87. return errors.New("maxSymbolValue too small")
  88. }
  89. //println("inserting ", n0-charnum, "zeroes from idx", charnum, "ending before", n0)
  90. for charnum < n0 {
  91. s.norm[uint8(charnum)] = 0
  92. charnum++
  93. }
  94. if r := b.remain(); r >= 7 || r+int(bitCount>>3) >= 4 {
  95. b.advance(bitCount >> 3)
  96. bitCount &= 7
  97. bitStream = b.Uint32() >> bitCount
  98. } else {
  99. bitStream >>= 2
  100. }
  101. }
  102. max := (2*threshold - 1) - remaining
  103. var count int32
  104. if int32(bitStream)&(threshold-1) < max {
  105. count = int32(bitStream) & (threshold - 1)
  106. if debug && nbBits < 1 {
  107. panic("nbBits underflow")
  108. }
  109. bitCount += nbBits - 1
  110. } else {
  111. count = int32(bitStream) & (2*threshold - 1)
  112. if count >= threshold {
  113. count -= max
  114. }
  115. bitCount += nbBits
  116. }
  117. // extra accuracy
  118. count--
  119. if count < 0 {
  120. // -1 means +1
  121. remaining += count
  122. gotTotal -= count
  123. } else {
  124. remaining -= count
  125. gotTotal += count
  126. }
  127. s.norm[charnum&0xff] = int16(count)
  128. charnum++
  129. previous0 = count == 0
  130. for remaining < threshold {
  131. nbBits--
  132. threshold >>= 1
  133. }
  134. //println("b.off:", b.off, "len:", len(b.b), "bc:", bitCount, "remain:", b.remain())
  135. if r := b.remain(); r >= 7 || r+int(bitCount>>3) >= 4 {
  136. b.advance(bitCount >> 3)
  137. bitCount &= 7
  138. } else {
  139. bitCount -= (uint)(8 * (len(b.b) - 4 - b.off))
  140. b.off = len(b.b) - 4
  141. //println("b.off:", b.off, "len:", len(b.b), "bc:", bitCount, "iend", iend)
  142. }
  143. bitStream = b.Uint32() >> (bitCount & 31)
  144. //printf("bitstream is now: 0b%b", bitStream)
  145. }
  146. s.symbolLen = charnum
  147. if s.symbolLen <= 1 {
  148. return fmt.Errorf("symbolLen (%d) too small", s.symbolLen)
  149. }
  150. if s.symbolLen > maxSymbolValue+1 {
  151. return fmt.Errorf("symbolLen (%d) too big", s.symbolLen)
  152. }
  153. if remaining != 1 {
  154. return fmt.Errorf("corruption detected (remaining %d != 1)", remaining)
  155. }
  156. if bitCount > 32 {
  157. return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount)
  158. }
  159. if gotTotal != 1<<s.actualTableLog {
  160. return fmt.Errorf("corruption detected (total %d != %d)", gotTotal, 1<<s.actualTableLog)
  161. }
  162. b.advance((bitCount + 7) >> 3)
  163. // println(s.norm[:s.symbolLen], s.symbolLen)
  164. return s.buildDtable()
  165. }
  166. // decSymbol contains information about a state entry,
  167. // Including the state offset base, the output symbol and
  168. // the number of bits to read for the low part of the destination state.
  169. // Using a composite uint64 is faster than a struct with separate members.
  170. type decSymbol uint64
  171. func newDecSymbol(nbits, addBits uint8, newState uint16, baseline uint32) decSymbol {
  172. return decSymbol(nbits) | (decSymbol(addBits) << 8) | (decSymbol(newState) << 16) | (decSymbol(baseline) << 32)
  173. }
  174. func (d decSymbol) nbBits() uint8 {
  175. return uint8(d)
  176. }
  177. func (d decSymbol) addBits() uint8 {
  178. return uint8(d >> 8)
  179. }
  180. func (d decSymbol) newState() uint16 {
  181. return uint16(d >> 16)
  182. }
  183. func (d decSymbol) baseline() uint32 {
  184. return uint32(d >> 32)
  185. }
  186. func (d decSymbol) baselineInt() int {
  187. return int(d >> 32)
  188. }
  189. func (d *decSymbol) set(nbits, addBits uint8, newState uint16, baseline uint32) {
  190. *d = decSymbol(nbits) | (decSymbol(addBits) << 8) | (decSymbol(newState) << 16) | (decSymbol(baseline) << 32)
  191. }
  192. func (d *decSymbol) setNBits(nBits uint8) {
  193. const mask = 0xffffffffffffff00
  194. *d = (*d & mask) | decSymbol(nBits)
  195. }
  196. func (d *decSymbol) setAddBits(addBits uint8) {
  197. const mask = 0xffffffffffff00ff
  198. *d = (*d & mask) | (decSymbol(addBits) << 8)
  199. }
  200. func (d *decSymbol) setNewState(state uint16) {
  201. const mask = 0xffffffff0000ffff
  202. *d = (*d & mask) | decSymbol(state)<<16
  203. }
  204. func (d *decSymbol) setBaseline(baseline uint32) {
  205. const mask = 0xffffffff
  206. *d = (*d & mask) | decSymbol(baseline)<<32
  207. }
  208. func (d *decSymbol) setExt(addBits uint8, baseline uint32) {
  209. const mask = 0xffff00ff
  210. *d = (*d & mask) | (decSymbol(addBits) << 8) | (decSymbol(baseline) << 32)
  211. }
  212. // decSymbolValue returns the transformed decSymbol for the given symbol.
  213. func decSymbolValue(symb uint8, t []baseOffset) (decSymbol, error) {
  214. if int(symb) >= len(t) {
  215. return 0, fmt.Errorf("rle symbol %d >= max %d", symb, len(t))
  216. }
  217. lu := t[symb]
  218. return newDecSymbol(0, lu.addBits, 0, lu.baseLine), nil
  219. }
  220. // setRLE will set the decoder til RLE mode.
  221. func (s *fseDecoder) setRLE(symbol decSymbol) {
  222. s.actualTableLog = 0
  223. s.maxBits = symbol.addBits()
  224. s.dt[0] = symbol
  225. }
  226. // buildDtable will build the decoding table.
  227. func (s *fseDecoder) buildDtable() error {
  228. tableSize := uint32(1 << s.actualTableLog)
  229. highThreshold := tableSize - 1
  230. symbolNext := s.stateTable[:256]
  231. // Init, lay down lowprob symbols
  232. {
  233. for i, v := range s.norm[:s.symbolLen] {
  234. if v == -1 {
  235. s.dt[highThreshold].setAddBits(uint8(i))
  236. highThreshold--
  237. symbolNext[i] = 1
  238. } else {
  239. symbolNext[i] = uint16(v)
  240. }
  241. }
  242. }
  243. // Spread symbols
  244. {
  245. tableMask := tableSize - 1
  246. step := tableStep(tableSize)
  247. position := uint32(0)
  248. for ss, v := range s.norm[:s.symbolLen] {
  249. for i := 0; i < int(v); i++ {
  250. s.dt[position].setAddBits(uint8(ss))
  251. position = (position + step) & tableMask
  252. for position > highThreshold {
  253. // lowprob area
  254. position = (position + step) & tableMask
  255. }
  256. }
  257. }
  258. if position != 0 {
  259. // position must reach all cells once, otherwise normalizedCounter is incorrect
  260. return errors.New("corrupted input (position != 0)")
  261. }
  262. }
  263. // Build Decoding table
  264. {
  265. tableSize := uint16(1 << s.actualTableLog)
  266. for u, v := range s.dt[:tableSize] {
  267. symbol := v.addBits()
  268. nextState := symbolNext[symbol]
  269. symbolNext[symbol] = nextState + 1
  270. nBits := s.actualTableLog - byte(highBits(uint32(nextState)))
  271. s.dt[u&maxTableMask].setNBits(nBits)
  272. newState := (nextState << nBits) - tableSize
  273. if newState > tableSize {
  274. return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize)
  275. }
  276. if newState == uint16(u) && nBits == 0 {
  277. // Seems weird that this is possible with nbits > 0.
  278. return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u)
  279. }
  280. s.dt[u&maxTableMask].setNewState(newState)
  281. }
  282. }
  283. return nil
  284. }
  285. // transform will transform the decoder table into a table usable for
  286. // decoding without having to apply the transformation while decoding.
  287. // The state will contain the base value and the number of bits to read.
  288. func (s *fseDecoder) transform(t []baseOffset) error {
  289. tableSize := uint16(1 << s.actualTableLog)
  290. s.maxBits = 0
  291. for i, v := range s.dt[:tableSize] {
  292. add := v.addBits()
  293. if int(add) >= len(t) {
  294. return fmt.Errorf("invalid decoding table entry %d, symbol %d >= max (%d)", i, v.addBits(), len(t))
  295. }
  296. lu := t[add]
  297. if lu.addBits > s.maxBits {
  298. s.maxBits = lu.addBits
  299. }
  300. v.setExt(lu.addBits, lu.baseLine)
  301. s.dt[i] = v
  302. }
  303. return nil
  304. }
  305. type fseState struct {
  306. dt []decSymbol
  307. state decSymbol
  308. }
  309. // Initialize and decodeAsync first state and symbol.
  310. func (s *fseState) init(br *bitReader, tableLog uint8, dt []decSymbol) {
  311. s.dt = dt
  312. br.fill()
  313. s.state = dt[br.getBits(tableLog)]
  314. }
  315. // next returns the current symbol and sets the next state.
  316. // At least tablelog bits must be available in the bit reader.
  317. func (s *fseState) next(br *bitReader) {
  318. lowBits := uint16(br.getBits(s.state.nbBits()))
  319. s.state = s.dt[s.state.newState()+lowBits]
  320. }
  321. // finished returns true if all bits have been read from the bitstream
  322. // and the next state would require reading bits from the input.
  323. func (s *fseState) finished(br *bitReader) bool {
  324. return br.finished() && s.state.nbBits() > 0
  325. }
  326. // final returns the current state symbol without decoding the next.
  327. func (s *fseState) final() (int, uint8) {
  328. return s.state.baselineInt(), s.state.addBits()
  329. }
  330. // final returns the current state symbol without decoding the next.
  331. func (s decSymbol) final() (int, uint8) {
  332. return s.baselineInt(), s.addBits()
  333. }
  334. // nextFast returns the next symbol and sets the next state.
  335. // This can only be used if no symbols are 0 bits.
  336. // At least tablelog bits must be available in the bit reader.
  337. func (s *fseState) nextFast(br *bitReader) (uint32, uint8) {
  338. lowBits := uint16(br.getBitsFast(s.state.nbBits()))
  339. s.state = s.dt[s.state.newState()+lowBits]
  340. return s.state.baseline(), s.state.addBits()
  341. }