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