decoder.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. "context"
  7. "encoding/binary"
  8. "io"
  9. "sync"
  10. "github.com/klauspost/compress/zstd/internal/xxhash"
  11. )
  12. // Decoder provides decoding of zstandard streams.
  13. // The decoder has been designed to operate without allocations after a warmup.
  14. // This means that you should store the decoder for best performance.
  15. // To re-use a stream decoder, use the Reset(r io.Reader) error to switch to another stream.
  16. // A decoder can safely be re-used even if the previous stream failed.
  17. // To release the resources, you must call the Close() function on a decoder.
  18. type Decoder struct {
  19. o decoderOptions
  20. // Unreferenced decoders, ready for use.
  21. decoders chan *blockDec
  22. // Current read position used for Reader functionality.
  23. current decoderState
  24. // sync stream decoding
  25. syncStream struct {
  26. decodedFrame uint64
  27. br readerWrapper
  28. enabled bool
  29. inFrame bool
  30. dstBuf []byte
  31. }
  32. frame *frameDec
  33. // Custom dictionaries.
  34. dicts map[uint32]*dict
  35. // streamWg is the waitgroup for all streams
  36. streamWg sync.WaitGroup
  37. }
  38. // decoderState is used for maintaining state when the decoder
  39. // is used for streaming.
  40. type decoderState struct {
  41. // current block being written to stream.
  42. decodeOutput
  43. // output in order to be written to stream.
  44. output chan decodeOutput
  45. // cancel remaining output.
  46. cancel context.CancelFunc
  47. // crc of current frame
  48. crc *xxhash.Digest
  49. flushed bool
  50. }
  51. var (
  52. // Check the interfaces we want to support.
  53. _ = io.WriterTo(&Decoder{})
  54. _ = io.Reader(&Decoder{})
  55. )
  56. // NewReader creates a new decoder.
  57. // A nil Reader can be provided in which case Reset can be used to start a decode.
  58. //
  59. // A Decoder can be used in two modes:
  60. //
  61. // 1) As a stream, or
  62. // 2) For stateless decoding using DecodeAll.
  63. //
  64. // Only a single stream can be decoded concurrently, but the same decoder
  65. // can run multiple concurrent stateless decodes. It is even possible to
  66. // use stateless decodes while a stream is being decoded.
  67. //
  68. // The Reset function can be used to initiate a new stream, which will considerably
  69. // reduce the allocations normally caused by NewReader.
  70. func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) {
  71. initPredefined()
  72. var d Decoder
  73. d.o.setDefault()
  74. for _, o := range opts {
  75. err := o(&d.o)
  76. if err != nil {
  77. return nil, err
  78. }
  79. }
  80. d.current.crc = xxhash.New()
  81. d.current.flushed = true
  82. if r == nil {
  83. d.current.err = ErrDecoderNilInput
  84. }
  85. // Transfer option dicts.
  86. d.dicts = make(map[uint32]*dict, len(d.o.dicts))
  87. for _, dc := range d.o.dicts {
  88. d.dicts[dc.id] = dc
  89. }
  90. d.o.dicts = nil
  91. // Create decoders
  92. d.decoders = make(chan *blockDec, d.o.concurrent)
  93. for i := 0; i < d.o.concurrent; i++ {
  94. dec := newBlockDec(d.o.lowMem)
  95. dec.localFrame = newFrameDec(d.o)
  96. d.decoders <- dec
  97. }
  98. if r == nil {
  99. return &d, nil
  100. }
  101. return &d, d.Reset(r)
  102. }
  103. // Read bytes from the decompressed stream into p.
  104. // Returns the number of bytes written and any error that occurred.
  105. // When the stream is done, io.EOF will be returned.
  106. func (d *Decoder) Read(p []byte) (int, error) {
  107. var n int
  108. for {
  109. if len(d.current.b) > 0 {
  110. filled := copy(p, d.current.b)
  111. p = p[filled:]
  112. d.current.b = d.current.b[filled:]
  113. n += filled
  114. }
  115. if len(p) == 0 {
  116. break
  117. }
  118. if len(d.current.b) == 0 {
  119. // We have an error and no more data
  120. if d.current.err != nil {
  121. break
  122. }
  123. if !d.nextBlock(n == 0) {
  124. return n, d.current.err
  125. }
  126. }
  127. }
  128. if len(d.current.b) > 0 {
  129. if debugDecoder {
  130. println("returning", n, "still bytes left:", len(d.current.b))
  131. }
  132. // Only return error at end of block
  133. return n, nil
  134. }
  135. if d.current.err != nil {
  136. d.drainOutput()
  137. }
  138. if debugDecoder {
  139. println("returning", n, d.current.err, len(d.decoders))
  140. }
  141. return n, d.current.err
  142. }
  143. // Reset will reset the decoder the supplied stream after the current has finished processing.
  144. // Note that this functionality cannot be used after Close has been called.
  145. // Reset can be called with a nil reader to release references to the previous reader.
  146. // After being called with a nil reader, no other operations than Reset or DecodeAll or Close
  147. // should be used.
  148. func (d *Decoder) Reset(r io.Reader) error {
  149. if d.current.err == ErrDecoderClosed {
  150. return d.current.err
  151. }
  152. d.drainOutput()
  153. d.syncStream.br.r = nil
  154. if r == nil {
  155. d.current.err = ErrDecoderNilInput
  156. if len(d.current.b) > 0 {
  157. d.current.b = d.current.b[:0]
  158. }
  159. d.current.flushed = true
  160. return nil
  161. }
  162. // If bytes buffer and < 5MB, do sync decoding anyway.
  163. if bb, ok := r.(byter); ok && bb.Len() < d.o.decodeBufsBelow && !d.o.limitToCap {
  164. bb2 := bb
  165. if debugDecoder {
  166. println("*bytes.Buffer detected, doing sync decode, len:", bb.Len())
  167. }
  168. b := bb2.Bytes()
  169. var dst []byte
  170. if cap(d.syncStream.dstBuf) > 0 {
  171. dst = d.syncStream.dstBuf[:0]
  172. }
  173. dst, err := d.DecodeAll(b, dst)
  174. if err == nil {
  175. err = io.EOF
  176. }
  177. // Save output buffer
  178. d.syncStream.dstBuf = dst
  179. d.current.b = dst
  180. d.current.err = err
  181. d.current.flushed = true
  182. if debugDecoder {
  183. println("sync decode to", len(dst), "bytes, err:", err)
  184. }
  185. return nil
  186. }
  187. // Remove current block.
  188. d.stashDecoder()
  189. d.current.decodeOutput = decodeOutput{}
  190. d.current.err = nil
  191. d.current.flushed = false
  192. d.current.d = nil
  193. d.syncStream.dstBuf = nil
  194. // Ensure no-one else is still running...
  195. d.streamWg.Wait()
  196. if d.frame == nil {
  197. d.frame = newFrameDec(d.o)
  198. }
  199. if d.o.concurrent == 1 {
  200. return d.startSyncDecoder(r)
  201. }
  202. d.current.output = make(chan decodeOutput, d.o.concurrent)
  203. ctx, cancel := context.WithCancel(context.Background())
  204. d.current.cancel = cancel
  205. d.streamWg.Add(1)
  206. go d.startStreamDecoder(ctx, r, d.current.output)
  207. return nil
  208. }
  209. // drainOutput will drain the output until errEndOfStream is sent.
  210. func (d *Decoder) drainOutput() {
  211. if d.current.cancel != nil {
  212. if debugDecoder {
  213. println("cancelling current")
  214. }
  215. d.current.cancel()
  216. d.current.cancel = nil
  217. }
  218. if d.current.d != nil {
  219. if debugDecoder {
  220. printf("re-adding current decoder %p, decoders: %d", d.current.d, len(d.decoders))
  221. }
  222. d.decoders <- d.current.d
  223. d.current.d = nil
  224. d.current.b = nil
  225. }
  226. if d.current.output == nil || d.current.flushed {
  227. println("current already flushed")
  228. return
  229. }
  230. for v := range d.current.output {
  231. if v.d != nil {
  232. if debugDecoder {
  233. printf("re-adding decoder %p", v.d)
  234. }
  235. d.decoders <- v.d
  236. }
  237. }
  238. d.current.output = nil
  239. d.current.flushed = true
  240. }
  241. // WriteTo writes data to w until there's no more data to write or when an error occurs.
  242. // The return value n is the number of bytes written.
  243. // Any error encountered during the write is also returned.
  244. func (d *Decoder) WriteTo(w io.Writer) (int64, error) {
  245. var n int64
  246. for {
  247. if len(d.current.b) > 0 {
  248. n2, err2 := w.Write(d.current.b)
  249. n += int64(n2)
  250. if err2 != nil && (d.current.err == nil || d.current.err == io.EOF) {
  251. d.current.err = err2
  252. } else if n2 != len(d.current.b) {
  253. d.current.err = io.ErrShortWrite
  254. }
  255. }
  256. if d.current.err != nil {
  257. break
  258. }
  259. d.nextBlock(true)
  260. }
  261. err := d.current.err
  262. if err != nil {
  263. d.drainOutput()
  264. }
  265. if err == io.EOF {
  266. err = nil
  267. }
  268. return n, err
  269. }
  270. // DecodeAll allows stateless decoding of a blob of bytes.
  271. // Output will be appended to dst, so if the destination size is known
  272. // you can pre-allocate the destination slice to avoid allocations.
  273. // DecodeAll can be used concurrently.
  274. // The Decoder concurrency limits will be respected.
  275. func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
  276. if d.decoders == nil {
  277. return dst, ErrDecoderClosed
  278. }
  279. // Grab a block decoder and frame decoder.
  280. block := <-d.decoders
  281. frame := block.localFrame
  282. initialSize := len(dst)
  283. defer func() {
  284. if debugDecoder {
  285. printf("re-adding decoder: %p", block)
  286. }
  287. frame.rawInput = nil
  288. frame.bBuf = nil
  289. if frame.history.decoders.br != nil {
  290. frame.history.decoders.br.in = nil
  291. }
  292. d.decoders <- block
  293. }()
  294. frame.bBuf = input
  295. for {
  296. frame.history.reset()
  297. err := frame.reset(&frame.bBuf)
  298. if err != nil {
  299. if err == io.EOF {
  300. if debugDecoder {
  301. println("frame reset return EOF")
  302. }
  303. return dst, nil
  304. }
  305. return dst, err
  306. }
  307. if err = d.setDict(frame); err != nil {
  308. return nil, err
  309. }
  310. if frame.WindowSize > d.o.maxWindowSize {
  311. if debugDecoder {
  312. println("window size exceeded:", frame.WindowSize, ">", d.o.maxWindowSize)
  313. }
  314. return dst, ErrWindowSizeExceeded
  315. }
  316. if frame.FrameContentSize != fcsUnknown {
  317. if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)-initialSize) {
  318. if debugDecoder {
  319. println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", d.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst))
  320. }
  321. return dst, ErrDecoderSizeExceeded
  322. }
  323. if d.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) {
  324. if debugDecoder {
  325. println("decoder size exceeded; fcs:", frame.FrameContentSize, "> (cap-len)", cap(dst)-len(dst))
  326. }
  327. return dst, ErrDecoderSizeExceeded
  328. }
  329. if cap(dst)-len(dst) < int(frame.FrameContentSize) {
  330. dst2 := make([]byte, len(dst), len(dst)+int(frame.FrameContentSize)+compressedBlockOverAlloc)
  331. copy(dst2, dst)
  332. dst = dst2
  333. }
  334. }
  335. if cap(dst) == 0 && !d.o.limitToCap {
  336. // Allocate len(input) * 2 by default if nothing is provided
  337. // and we didn't get frame content size.
  338. size := len(input) * 2
  339. // Cap to 1 MB.
  340. if size > 1<<20 {
  341. size = 1 << 20
  342. }
  343. if uint64(size) > d.o.maxDecodedSize {
  344. size = int(d.o.maxDecodedSize)
  345. }
  346. dst = make([]byte, 0, size)
  347. }
  348. dst, err = frame.runDecoder(dst, block)
  349. if err != nil {
  350. return dst, err
  351. }
  352. if uint64(len(dst)-initialSize) > d.o.maxDecodedSize {
  353. return dst, ErrDecoderSizeExceeded
  354. }
  355. if len(frame.bBuf) == 0 {
  356. if debugDecoder {
  357. println("frame dbuf empty")
  358. }
  359. break
  360. }
  361. }
  362. return dst, nil
  363. }
  364. // nextBlock returns the next block.
  365. // If an error occurs d.err will be set.
  366. // Optionally the function can block for new output.
  367. // If non-blocking mode is used the returned boolean will be false
  368. // if no data was available without blocking.
  369. func (d *Decoder) nextBlock(blocking bool) (ok bool) {
  370. if d.current.err != nil {
  371. // Keep error state.
  372. return false
  373. }
  374. d.current.b = d.current.b[:0]
  375. // SYNC:
  376. if d.syncStream.enabled {
  377. if !blocking {
  378. return false
  379. }
  380. ok = d.nextBlockSync()
  381. if !ok {
  382. d.stashDecoder()
  383. }
  384. return ok
  385. }
  386. //ASYNC:
  387. d.stashDecoder()
  388. if blocking {
  389. d.current.decodeOutput, ok = <-d.current.output
  390. } else {
  391. select {
  392. case d.current.decodeOutput, ok = <-d.current.output:
  393. default:
  394. return false
  395. }
  396. }
  397. if !ok {
  398. // This should not happen, so signal error state...
  399. d.current.err = io.ErrUnexpectedEOF
  400. return false
  401. }
  402. next := d.current.decodeOutput
  403. if next.d != nil && next.d.async.newHist != nil {
  404. d.current.crc.Reset()
  405. }
  406. if debugDecoder {
  407. var tmp [4]byte
  408. binary.LittleEndian.PutUint32(tmp[:], uint32(xxhash.Sum64(next.b)))
  409. println("got", len(d.current.b), "bytes, error:", d.current.err, "data crc:", tmp)
  410. }
  411. if d.o.ignoreChecksum {
  412. return true
  413. }
  414. if len(next.b) > 0 {
  415. d.current.crc.Write(next.b)
  416. }
  417. if next.err == nil && next.d != nil && next.d.hasCRC {
  418. got := uint32(d.current.crc.Sum64())
  419. if got != next.d.checkCRC {
  420. if debugDecoder {
  421. printf("CRC Check Failed: %08x (got) != %08x (on stream)\n", got, next.d.checkCRC)
  422. }
  423. d.current.err = ErrCRCMismatch
  424. } else {
  425. if debugDecoder {
  426. printf("CRC ok %08x\n", got)
  427. }
  428. }
  429. }
  430. return true
  431. }
  432. func (d *Decoder) nextBlockSync() (ok bool) {
  433. if d.current.d == nil {
  434. d.current.d = <-d.decoders
  435. }
  436. for len(d.current.b) == 0 {
  437. if !d.syncStream.inFrame {
  438. d.frame.history.reset()
  439. d.current.err = d.frame.reset(&d.syncStream.br)
  440. if d.current.err == nil {
  441. d.current.err = d.setDict(d.frame)
  442. }
  443. if d.current.err != nil {
  444. return false
  445. }
  446. if d.frame.WindowSize > d.o.maxDecodedSize || d.frame.WindowSize > d.o.maxWindowSize {
  447. d.current.err = ErrDecoderSizeExceeded
  448. return false
  449. }
  450. d.syncStream.decodedFrame = 0
  451. d.syncStream.inFrame = true
  452. }
  453. d.current.err = d.frame.next(d.current.d)
  454. if d.current.err != nil {
  455. return false
  456. }
  457. d.frame.history.ensureBlock()
  458. if debugDecoder {
  459. println("History trimmed:", len(d.frame.history.b), "decoded already:", d.syncStream.decodedFrame)
  460. }
  461. histBefore := len(d.frame.history.b)
  462. d.current.err = d.current.d.decodeBuf(&d.frame.history)
  463. if d.current.err != nil {
  464. println("error after:", d.current.err)
  465. return false
  466. }
  467. d.current.b = d.frame.history.b[histBefore:]
  468. if debugDecoder {
  469. println("history after:", len(d.frame.history.b))
  470. }
  471. // Check frame size (before CRC)
  472. d.syncStream.decodedFrame += uint64(len(d.current.b))
  473. if d.syncStream.decodedFrame > d.frame.FrameContentSize {
  474. if debugDecoder {
  475. printf("DecodedFrame (%d) > FrameContentSize (%d)\n", d.syncStream.decodedFrame, d.frame.FrameContentSize)
  476. }
  477. d.current.err = ErrFrameSizeExceeded
  478. return false
  479. }
  480. // Check FCS
  481. if d.current.d.Last && d.frame.FrameContentSize != fcsUnknown && d.syncStream.decodedFrame != d.frame.FrameContentSize {
  482. if debugDecoder {
  483. printf("DecodedFrame (%d) != FrameContentSize (%d)\n", d.syncStream.decodedFrame, d.frame.FrameContentSize)
  484. }
  485. d.current.err = ErrFrameSizeMismatch
  486. return false
  487. }
  488. // Update/Check CRC
  489. if d.frame.HasCheckSum {
  490. if !d.o.ignoreChecksum {
  491. d.frame.crc.Write(d.current.b)
  492. }
  493. if d.current.d.Last {
  494. if !d.o.ignoreChecksum {
  495. d.current.err = d.frame.checkCRC()
  496. } else {
  497. d.current.err = d.frame.consumeCRC()
  498. }
  499. if d.current.err != nil {
  500. println("CRC error:", d.current.err)
  501. return false
  502. }
  503. }
  504. }
  505. d.syncStream.inFrame = !d.current.d.Last
  506. }
  507. return true
  508. }
  509. func (d *Decoder) stashDecoder() {
  510. if d.current.d != nil {
  511. if debugDecoder {
  512. printf("re-adding current decoder %p", d.current.d)
  513. }
  514. d.decoders <- d.current.d
  515. d.current.d = nil
  516. }
  517. }
  518. // Close will release all resources.
  519. // It is NOT possible to reuse the decoder after this.
  520. func (d *Decoder) Close() {
  521. if d.current.err == ErrDecoderClosed {
  522. return
  523. }
  524. d.drainOutput()
  525. if d.current.cancel != nil {
  526. d.current.cancel()
  527. d.streamWg.Wait()
  528. d.current.cancel = nil
  529. }
  530. if d.decoders != nil {
  531. close(d.decoders)
  532. for dec := range d.decoders {
  533. dec.Close()
  534. }
  535. d.decoders = nil
  536. }
  537. if d.current.d != nil {
  538. d.current.d.Close()
  539. d.current.d = nil
  540. }
  541. d.current.err = ErrDecoderClosed
  542. }
  543. // IOReadCloser returns the decoder as an io.ReadCloser for convenience.
  544. // Any changes to the decoder will be reflected, so the returned ReadCloser
  545. // can be reused along with the decoder.
  546. // io.WriterTo is also supported by the returned ReadCloser.
  547. func (d *Decoder) IOReadCloser() io.ReadCloser {
  548. return closeWrapper{d: d}
  549. }
  550. // closeWrapper wraps a function call as a closer.
  551. type closeWrapper struct {
  552. d *Decoder
  553. }
  554. // WriteTo forwards WriteTo calls to the decoder.
  555. func (c closeWrapper) WriteTo(w io.Writer) (n int64, err error) {
  556. return c.d.WriteTo(w)
  557. }
  558. // Read forwards read calls to the decoder.
  559. func (c closeWrapper) Read(p []byte) (n int, err error) {
  560. return c.d.Read(p)
  561. }
  562. // Close closes the decoder.
  563. func (c closeWrapper) Close() error {
  564. c.d.Close()
  565. return nil
  566. }
  567. type decodeOutput struct {
  568. d *blockDec
  569. b []byte
  570. err error
  571. }
  572. func (d *Decoder) startSyncDecoder(r io.Reader) error {
  573. d.frame.history.reset()
  574. d.syncStream.br = readerWrapper{r: r}
  575. d.syncStream.inFrame = false
  576. d.syncStream.enabled = true
  577. d.syncStream.decodedFrame = 0
  578. return nil
  579. }
  580. // Create Decoder:
  581. // ASYNC:
  582. // Spawn 3 go routines.
  583. // 0: Read frames and decode block literals.
  584. // 1: Decode sequences.
  585. // 2: Execute sequences, send to output.
  586. func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output chan decodeOutput) {
  587. defer d.streamWg.Done()
  588. br := readerWrapper{r: r}
  589. var seqDecode = make(chan *blockDec, d.o.concurrent)
  590. var seqExecute = make(chan *blockDec, d.o.concurrent)
  591. // Async 1: Decode sequences...
  592. go func() {
  593. var hist history
  594. var hasErr bool
  595. for block := range seqDecode {
  596. if hasErr {
  597. if block != nil {
  598. seqExecute <- block
  599. }
  600. continue
  601. }
  602. if block.async.newHist != nil {
  603. if debugDecoder {
  604. println("Async 1: new history, recent:", block.async.newHist.recentOffsets)
  605. }
  606. hist.reset()
  607. hist.decoders = block.async.newHist.decoders
  608. hist.recentOffsets = block.async.newHist.recentOffsets
  609. hist.windowSize = block.async.newHist.windowSize
  610. if block.async.newHist.dict != nil {
  611. hist.setDict(block.async.newHist.dict)
  612. }
  613. }
  614. if block.err != nil || block.Type != blockTypeCompressed {
  615. hasErr = block.err != nil
  616. seqExecute <- block
  617. continue
  618. }
  619. hist.decoders.literals = block.async.literals
  620. block.err = block.prepareSequences(block.async.seqData, &hist)
  621. if debugDecoder && block.err != nil {
  622. println("prepareSequences returned:", block.err)
  623. }
  624. hasErr = block.err != nil
  625. if block.err == nil {
  626. block.err = block.decodeSequences(&hist)
  627. if debugDecoder && block.err != nil {
  628. println("decodeSequences returned:", block.err)
  629. }
  630. hasErr = block.err != nil
  631. // block.async.sequence = hist.decoders.seq[:hist.decoders.nSeqs]
  632. block.async.seqSize = hist.decoders.seqSize
  633. }
  634. seqExecute <- block
  635. }
  636. close(seqExecute)
  637. hist.reset()
  638. }()
  639. var wg sync.WaitGroup
  640. wg.Add(1)
  641. // Async 3: Execute sequences...
  642. frameHistCache := d.frame.history.b
  643. go func() {
  644. var hist history
  645. var decodedFrame uint64
  646. var fcs uint64
  647. var hasErr bool
  648. for block := range seqExecute {
  649. out := decodeOutput{err: block.err, d: block}
  650. if block.err != nil || hasErr {
  651. hasErr = true
  652. output <- out
  653. continue
  654. }
  655. if block.async.newHist != nil {
  656. if debugDecoder {
  657. println("Async 2: new history")
  658. }
  659. hist.reset()
  660. hist.windowSize = block.async.newHist.windowSize
  661. hist.allocFrameBuffer = block.async.newHist.allocFrameBuffer
  662. if block.async.newHist.dict != nil {
  663. hist.setDict(block.async.newHist.dict)
  664. }
  665. if cap(hist.b) < hist.allocFrameBuffer {
  666. if cap(frameHistCache) >= hist.allocFrameBuffer {
  667. hist.b = frameHistCache
  668. } else {
  669. hist.b = make([]byte, 0, hist.allocFrameBuffer)
  670. println("Alloc history sized", hist.allocFrameBuffer)
  671. }
  672. }
  673. hist.b = hist.b[:0]
  674. fcs = block.async.fcs
  675. decodedFrame = 0
  676. }
  677. do := decodeOutput{err: block.err, d: block}
  678. switch block.Type {
  679. case blockTypeRLE:
  680. if debugDecoder {
  681. println("add rle block length:", block.RLESize)
  682. }
  683. if cap(block.dst) < int(block.RLESize) {
  684. if block.lowMem {
  685. block.dst = make([]byte, block.RLESize)
  686. } else {
  687. block.dst = make([]byte, maxCompressedBlockSize)
  688. }
  689. }
  690. block.dst = block.dst[:block.RLESize]
  691. v := block.data[0]
  692. for i := range block.dst {
  693. block.dst[i] = v
  694. }
  695. hist.append(block.dst)
  696. do.b = block.dst
  697. case blockTypeRaw:
  698. if debugDecoder {
  699. println("add raw block length:", len(block.data))
  700. }
  701. hist.append(block.data)
  702. do.b = block.data
  703. case blockTypeCompressed:
  704. if debugDecoder {
  705. println("execute with history length:", len(hist.b), "window:", hist.windowSize)
  706. }
  707. hist.decoders.seqSize = block.async.seqSize
  708. hist.decoders.literals = block.async.literals
  709. do.err = block.executeSequences(&hist)
  710. hasErr = do.err != nil
  711. if debugDecoder && hasErr {
  712. println("executeSequences returned:", do.err)
  713. }
  714. do.b = block.dst
  715. }
  716. if !hasErr {
  717. decodedFrame += uint64(len(do.b))
  718. if decodedFrame > fcs {
  719. println("fcs exceeded", block.Last, fcs, decodedFrame)
  720. do.err = ErrFrameSizeExceeded
  721. hasErr = true
  722. } else if block.Last && fcs != fcsUnknown && decodedFrame != fcs {
  723. do.err = ErrFrameSizeMismatch
  724. hasErr = true
  725. } else {
  726. if debugDecoder {
  727. println("fcs ok", block.Last, fcs, decodedFrame)
  728. }
  729. }
  730. }
  731. output <- do
  732. }
  733. close(output)
  734. frameHistCache = hist.b
  735. wg.Done()
  736. if debugDecoder {
  737. println("decoder goroutines finished")
  738. }
  739. hist.reset()
  740. }()
  741. var hist history
  742. decodeStream:
  743. for {
  744. var hasErr bool
  745. hist.reset()
  746. decodeBlock := func(block *blockDec) {
  747. if hasErr {
  748. if block != nil {
  749. seqDecode <- block
  750. }
  751. return
  752. }
  753. if block.err != nil || block.Type != blockTypeCompressed {
  754. hasErr = block.err != nil
  755. seqDecode <- block
  756. return
  757. }
  758. remain, err := block.decodeLiterals(block.data, &hist)
  759. block.err = err
  760. hasErr = block.err != nil
  761. if err == nil {
  762. block.async.literals = hist.decoders.literals
  763. block.async.seqData = remain
  764. } else if debugDecoder {
  765. println("decodeLiterals error:", err)
  766. }
  767. seqDecode <- block
  768. }
  769. frame := d.frame
  770. if debugDecoder {
  771. println("New frame...")
  772. }
  773. var historySent bool
  774. frame.history.reset()
  775. err := frame.reset(&br)
  776. if debugDecoder && err != nil {
  777. println("Frame decoder returned", err)
  778. }
  779. if err == nil {
  780. err = d.setDict(frame)
  781. }
  782. if err == nil && d.frame.WindowSize > d.o.maxWindowSize {
  783. if debugDecoder {
  784. println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.o.maxWindowSize)
  785. }
  786. err = ErrDecoderSizeExceeded
  787. }
  788. if err != nil {
  789. select {
  790. case <-ctx.Done():
  791. case dec := <-d.decoders:
  792. dec.sendErr(err)
  793. decodeBlock(dec)
  794. }
  795. break decodeStream
  796. }
  797. // Go through all blocks of the frame.
  798. for {
  799. var dec *blockDec
  800. select {
  801. case <-ctx.Done():
  802. break decodeStream
  803. case dec = <-d.decoders:
  804. // Once we have a decoder, we MUST return it.
  805. }
  806. err := frame.next(dec)
  807. if !historySent {
  808. h := frame.history
  809. if debugDecoder {
  810. println("Alloc History:", h.allocFrameBuffer)
  811. }
  812. hist.reset()
  813. if h.dict != nil {
  814. hist.setDict(h.dict)
  815. }
  816. dec.async.newHist = &h
  817. dec.async.fcs = frame.FrameContentSize
  818. historySent = true
  819. } else {
  820. dec.async.newHist = nil
  821. }
  822. if debugDecoder && err != nil {
  823. println("next block returned error:", err)
  824. }
  825. dec.err = err
  826. dec.hasCRC = false
  827. if dec.Last && frame.HasCheckSum && err == nil {
  828. crc, err := frame.rawInput.readSmall(4)
  829. if len(crc) < 4 {
  830. if err == nil {
  831. err = io.ErrUnexpectedEOF
  832. }
  833. println("CRC missing?", err)
  834. dec.err = err
  835. } else {
  836. dec.checkCRC = binary.LittleEndian.Uint32(crc)
  837. dec.hasCRC = true
  838. if debugDecoder {
  839. printf("found crc to check: %08x\n", dec.checkCRC)
  840. }
  841. }
  842. }
  843. err = dec.err
  844. last := dec.Last
  845. decodeBlock(dec)
  846. if err != nil {
  847. break decodeStream
  848. }
  849. if last {
  850. break
  851. }
  852. }
  853. }
  854. close(seqDecode)
  855. wg.Wait()
  856. hist.reset()
  857. d.frame.history.b = frameHistCache
  858. }
  859. func (d *Decoder) setDict(frame *frameDec) (err error) {
  860. dict, ok := d.dicts[frame.DictionaryID]
  861. if ok {
  862. if debugDecoder {
  863. println("setting dict", frame.DictionaryID)
  864. }
  865. frame.history.setDict(dict)
  866. } else if frame.DictionaryID != 0 {
  867. // A zero or missing dictionary id is ambiguous:
  868. // either dictionary zero, or no dictionary. In particular,
  869. // zstd --patch-from uses this id for the source file,
  870. // so only return an error if the dictionary id is not zero.
  871. err = ErrUnknownDictionary
  872. }
  873. return err
  874. }