fse_decoder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 = tablelogAbsoluteMax + 2
  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.Uint32NC()
  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. // The check above should make sure we can read 32 bits
  72. bitStream = b.Uint32NC() >> bitCount
  73. } else {
  74. // end of bit stream
  75. bitStream >>= 16
  76. bitCount += 16
  77. }
  78. }
  79. //printf("bitstream: %d, 0b%b", bitStream&3, bitStream)
  80. for (bitStream & 3) == 3 {
  81. n0 += 3
  82. bitStream >>= 2
  83. bitCount += 2
  84. }
  85. n0 += uint16(bitStream & 3)
  86. bitCount += 2
  87. if n0 > maxSymbolValue {
  88. return errors.New("maxSymbolValue too small")
  89. }
  90. //println("inserting ", n0-charnum, "zeroes from idx", charnum, "ending before", n0)
  91. for charnum < n0 {
  92. s.norm[uint8(charnum)] = 0
  93. charnum++
  94. }
  95. if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 {
  96. b.advance(bitCount >> 3)
  97. bitCount &= 7
  98. // The check above should make sure we can read 32 bits
  99. bitStream = b.Uint32NC() >> bitCount
  100. } else {
  101. bitStream >>= 2
  102. }
  103. }
  104. max := (2*threshold - 1) - remaining
  105. var count int32
  106. if int32(bitStream)&(threshold-1) < max {
  107. count = int32(bitStream) & (threshold - 1)
  108. if debugAsserts && nbBits < 1 {
  109. panic("nbBits underflow")
  110. }
  111. bitCount += nbBits - 1
  112. } else {
  113. count = int32(bitStream) & (2*threshold - 1)
  114. if count >= threshold {
  115. count -= max
  116. }
  117. bitCount += nbBits
  118. }
  119. // extra accuracy
  120. count--
  121. if count < 0 {
  122. // -1 means +1
  123. remaining += count
  124. gotTotal -= count
  125. } else {
  126. remaining -= count
  127. gotTotal += count
  128. }
  129. s.norm[charnum&0xff] = int16(count)
  130. charnum++
  131. previous0 = count == 0
  132. for remaining < threshold {
  133. nbBits--
  134. threshold >>= 1
  135. }
  136. if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 {
  137. b.advance(bitCount >> 3)
  138. bitCount &= 7
  139. // The check above should make sure we can read 32 bits
  140. bitStream = b.Uint32NC() >> (bitCount & 31)
  141. } else {
  142. bitCount -= (uint)(8 * (len(b.b) - 4 - b.off))
  143. b.off = len(b.b) - 4
  144. bitStream = b.Uint32() >> (bitCount & 31)
  145. }
  146. }
  147. s.symbolLen = charnum
  148. if s.symbolLen <= 1 {
  149. return fmt.Errorf("symbolLen (%d) too small", s.symbolLen)
  150. }
  151. if s.symbolLen > maxSymbolValue+1 {
  152. return fmt.Errorf("symbolLen (%d) too big", s.symbolLen)
  153. }
  154. if remaining != 1 {
  155. return fmt.Errorf("corruption detected (remaining %d != 1)", remaining)
  156. }
  157. if bitCount > 32 {
  158. return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount)
  159. }
  160. if gotTotal != 1<<s.actualTableLog {
  161. return fmt.Errorf("corruption detected (total %d != %d)", gotTotal, 1<<s.actualTableLog)
  162. }
  163. b.advance((bitCount + 7) >> 3)
  164. // println(s.norm[:s.symbolLen], s.symbolLen)
  165. return s.buildDtable()
  166. }
  167. // decSymbol contains information about a state entry,
  168. // Including the state offset base, the output symbol and
  169. // the number of bits to read for the low part of the destination state.
  170. // Using a composite uint64 is faster than a struct with separate members.
  171. type decSymbol uint64
  172. func newDecSymbol(nbits, addBits uint8, newState uint16, baseline uint32) decSymbol {
  173. return decSymbol(nbits) | (decSymbol(addBits) << 8) | (decSymbol(newState) << 16) | (decSymbol(baseline) << 32)
  174. }
  175. func (d decSymbol) nbBits() uint8 {
  176. return uint8(d)
  177. }
  178. func (d decSymbol) addBits() uint8 {
  179. return uint8(d >> 8)
  180. }
  181. func (d decSymbol) newState() uint16 {
  182. return uint16(d >> 16)
  183. }
  184. func (d decSymbol) baseline() uint32 {
  185. return uint32(d >> 32)
  186. }
  187. func (d decSymbol) baselineInt() int {
  188. return int(d >> 32)
  189. }
  190. func (d *decSymbol) set(nbits, addBits uint8, newState uint16, baseline uint32) {
  191. *d = decSymbol(nbits) | (decSymbol(addBits) << 8) | (decSymbol(newState) << 16) | (decSymbol(baseline) << 32)
  192. }
  193. func (d *decSymbol) setNBits(nBits uint8) {
  194. const mask = 0xffffffffffffff00
  195. *d = (*d & mask) | decSymbol(nBits)
  196. }
  197. func (d *decSymbol) setAddBits(addBits uint8) {
  198. const mask = 0xffffffffffff00ff
  199. *d = (*d & mask) | (decSymbol(addBits) << 8)
  200. }
  201. func (d *decSymbol) setNewState(state uint16) {
  202. const mask = 0xffffffff0000ffff
  203. *d = (*d & mask) | decSymbol(state)<<16
  204. }
  205. func (d *decSymbol) setBaseline(baseline uint32) {
  206. const mask = 0xffffffff
  207. *d = (*d & mask) | decSymbol(baseline)<<32
  208. }
  209. func (d *decSymbol) setExt(addBits uint8, baseline uint32) {
  210. const mask = 0xffff00ff
  211. *d = (*d & mask) | (decSymbol(addBits) << 8) | (decSymbol(baseline) << 32)
  212. }
  213. // decSymbolValue returns the transformed decSymbol for the given symbol.
  214. func decSymbolValue(symb uint8, t []baseOffset) (decSymbol, error) {
  215. if int(symb) >= len(t) {
  216. return 0, fmt.Errorf("rle symbol %d >= max %d", symb, len(t))
  217. }
  218. lu := t[symb]
  219. return newDecSymbol(0, lu.addBits, 0, lu.baseLine), nil
  220. }
  221. // setRLE will set the decoder til RLE mode.
  222. func (s *fseDecoder) setRLE(symbol decSymbol) {
  223. s.actualTableLog = 0
  224. s.maxBits = symbol.addBits()
  225. s.dt[0] = symbol
  226. }
  227. // buildDtable will build the decoding table.
  228. func (s *fseDecoder) buildDtable() error {
  229. tableSize := uint32(1 << s.actualTableLog)
  230. highThreshold := tableSize - 1
  231. symbolNext := s.stateTable[:256]
  232. // Init, lay down lowprob symbols
  233. {
  234. for i, v := range s.norm[:s.symbolLen] {
  235. if v == -1 {
  236. s.dt[highThreshold].setAddBits(uint8(i))
  237. highThreshold--
  238. symbolNext[i] = 1
  239. } else {
  240. symbolNext[i] = uint16(v)
  241. }
  242. }
  243. }
  244. // Spread symbols
  245. {
  246. tableMask := tableSize - 1
  247. step := tableStep(tableSize)
  248. position := uint32(0)
  249. for ss, v := range s.norm[:s.symbolLen] {
  250. for i := 0; i < int(v); i++ {
  251. s.dt[position].setAddBits(uint8(ss))
  252. position = (position + step) & tableMask
  253. for position > highThreshold {
  254. // lowprob area
  255. position = (position + step) & tableMask
  256. }
  257. }
  258. }
  259. if position != 0 {
  260. // position must reach all cells once, otherwise normalizedCounter is incorrect
  261. return errors.New("corrupted input (position != 0)")
  262. }
  263. }
  264. // Build Decoding table
  265. {
  266. tableSize := uint16(1 << s.actualTableLog)
  267. for u, v := range s.dt[:tableSize] {
  268. symbol := v.addBits()
  269. nextState := symbolNext[symbol]
  270. symbolNext[symbol] = nextState + 1
  271. nBits := s.actualTableLog - byte(highBits(uint32(nextState)))
  272. s.dt[u&maxTableMask].setNBits(nBits)
  273. newState := (nextState << nBits) - tableSize
  274. if newState > tableSize {
  275. return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize)
  276. }
  277. if newState == uint16(u) && nBits == 0 {
  278. // Seems weird that this is possible with nbits > 0.
  279. return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u)
  280. }
  281. s.dt[u&maxTableMask].setNewState(newState)
  282. }
  283. }
  284. return nil
  285. }
  286. // transform will transform the decoder table into a table usable for
  287. // decoding without having to apply the transformation while decoding.
  288. // The state will contain the base value and the number of bits to read.
  289. func (s *fseDecoder) transform(t []baseOffset) error {
  290. tableSize := uint16(1 << s.actualTableLog)
  291. s.maxBits = 0
  292. for i, v := range s.dt[:tableSize] {
  293. add := v.addBits()
  294. if int(add) >= len(t) {
  295. return fmt.Errorf("invalid decoding table entry %d, symbol %d >= max (%d)", i, v.addBits(), len(t))
  296. }
  297. lu := t[add]
  298. if lu.addBits > s.maxBits {
  299. s.maxBits = lu.addBits
  300. }
  301. v.setExt(lu.addBits, lu.baseLine)
  302. s.dt[i] = v
  303. }
  304. return nil
  305. }
  306. type fseState struct {
  307. dt []decSymbol
  308. state decSymbol
  309. }
  310. // Initialize and decodeAsync first state and symbol.
  311. func (s *fseState) init(br *bitReader, tableLog uint8, dt []decSymbol) {
  312. s.dt = dt
  313. br.fill()
  314. s.state = dt[br.getBits(tableLog)]
  315. }
  316. // next returns the current symbol and sets the next state.
  317. // At least tablelog bits must be available in the bit reader.
  318. func (s *fseState) next(br *bitReader) {
  319. lowBits := uint16(br.getBits(s.state.nbBits()))
  320. s.state = s.dt[s.state.newState()+lowBits]
  321. }
  322. // finished returns true if all bits have been read from the bitstream
  323. // and the next state would require reading bits from the input.
  324. func (s *fseState) finished(br *bitReader) bool {
  325. return br.finished() && s.state.nbBits() > 0
  326. }
  327. // final returns the current state symbol without decoding the next.
  328. func (s *fseState) final() (int, uint8) {
  329. return s.state.baselineInt(), s.state.addBits()
  330. }
  331. // final returns the current state symbol without decoding the next.
  332. func (s decSymbol) final() (int, uint8) {
  333. return s.baselineInt(), s.addBits()
  334. }
  335. // nextFast returns the next symbol and sets the next state.
  336. // This can only be used if no symbols are 0 bits.
  337. // At least tablelog bits must be available in the bit reader.
  338. func (s *fseState) nextFast(br *bitReader) (uint32, uint8) {
  339. lowBits := uint16(br.getBitsFast(s.state.nbBits()))
  340. s.state = s.dt[s.state.newState()+lowBits]
  341. return s.state.baseline(), s.state.addBits()
  342. }