2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 * You may select, at your option, one of the above-listed licenses.
12 /* ***************************************************************
14 *****************************************************************/
17 * Select how default decompression function ZSTD_decompress() allocates its context,
18 * on stack (0), or into heap (1, default; requires malloc()).
19 * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected.
22 # define ZSTD_HEAPMODE 1
27 * if set to 1+, ZSTD_decompress() can decode older formats (v0.1+)
29 #ifndef ZSTD_LEGACY_SUPPORT
30 # define ZSTD_LEGACY_SUPPORT 0
34 * MAXWINDOWSIZE_DEFAULT :
35 * maximum window size accepted by DStream __by default__.
36 * Frames requiring more memory will be rejected.
37 * It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize().
39 #ifndef ZSTD_MAXWINDOWSIZE_DEFAULT
40 # define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1)
44 * NO_FORWARD_PROGRESS_MAX :
45 * maximum allowed nb of calls to ZSTD_decompressStream()
46 * without any forward progress
47 * (defined as: no byte read from input, and no byte flushed to output)
48 * before triggering an error.
50 #ifndef ZSTD_NO_FORWARD_PROGRESS_MAX
51 # define ZSTD_NO_FORWARD_PROGRESS_MAX 16
55 /*-*******************************************************
57 *********************************************************/
58 #include <string.h> /* memcpy, memmove, memset */
59 #include "cpu.h" /* bmi2 */
60 #include "mem.h" /* low level memory routines */
61 #define FSE_STATIC_LINKING_ONLY
63 #define HUF_STATIC_LINKING_ONLY
65 #include "zstd_internal.h" /* blockProperties_t */
66 #include "zstd_decompress_internal.h" /* ZSTD_DCtx */
67 #include "zstd_ddict.h" /* ZSTD_DDictDictContent */
68 #include "zstd_decompress_block.h" /* ZSTD_decompressBlock_internal */
70 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
71 # include "zstd_legacy.h"
75 /*-*************************************************************
77 ***************************************************************/
78 size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx)
80 if (dctx==NULL) return 0; /* support sizeof NULL */
82 + ZSTD_sizeof_DDict(dctx->ddictLocal)
83 + dctx->inBuffSize + dctx->outBuffSize;
86 size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); }
89 static size_t ZSTD_startingInputLength(ZSTD_format_e format)
91 size_t const startingInputLength = (format==ZSTD_f_zstd1_magicless) ?
92 ZSTD_FRAMEHEADERSIZE_PREFIX - ZSTD_FRAMEIDSIZE :
93 ZSTD_FRAMEHEADERSIZE_PREFIX;
94 ZSTD_STATIC_ASSERT(ZSTD_FRAMEHEADERSIZE_PREFIX >= ZSTD_FRAMEIDSIZE);
95 /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */
96 assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) );
97 return startingInputLength;
100 static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx)
102 dctx->format = ZSTD_f_zstd1; /* ZSTD_decompressBegin() invokes ZSTD_startingInputLength() with argument dctx->format */
103 dctx->staticSize = 0;
104 dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
106 dctx->ddictLocal = NULL;
107 dctx->dictEnd = NULL;
108 dctx->ddictIsCold = 0;
110 dctx->inBuffSize = 0;
111 dctx->outBuffSize = 0;
112 dctx->streamStage = zdss_init;
113 dctx->legacyContext = NULL;
114 dctx->previousLegacyVersion = 0;
115 dctx->noForwardProgress = 0;
116 dctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
119 ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize)
121 ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace;
123 if ((size_t)workspace & 7) return NULL; /* 8-aligned */
124 if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */
126 ZSTD_initDCtx_internal(dctx);
127 dctx->staticSize = workspaceSize;
128 dctx->inBuff = (char*)(dctx+1);
132 ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem)
134 if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
136 { ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_malloc(sizeof(*dctx), customMem);
137 if (!dctx) return NULL;
138 dctx->customMem = customMem;
139 ZSTD_initDCtx_internal(dctx);
144 ZSTD_DCtx* ZSTD_createDCtx(void)
146 DEBUGLOG(3, "ZSTD_createDCtx");
147 return ZSTD_createDCtx_advanced(ZSTD_defaultCMem);
150 size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
152 if (dctx==NULL) return 0; /* support free on NULL */
153 if (dctx->staticSize) return ERROR(memory_allocation); /* not compatible with static DCtx */
154 { ZSTD_customMem const cMem = dctx->customMem;
155 ZSTD_freeDDict(dctx->ddictLocal);
156 dctx->ddictLocal = NULL;
157 ZSTD_free(dctx->inBuff, cMem);
159 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
160 if (dctx->legacyContext)
161 ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion);
163 ZSTD_free(dctx, cMem);
168 /* no longer useful */
169 void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx)
171 size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx);
172 memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */
176 /*-*************************************************************
177 * Frame header decoding
178 ***************************************************************/
181 * Tells if the content of `buffer` starts with a valid Frame Identifier.
182 * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
183 * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
184 * Note 3 : Skippable Frame Identifiers are considered valid. */
185 unsigned ZSTD_isFrame(const void* buffer, size_t size)
187 if (size < ZSTD_FRAMEIDSIZE) return 0;
188 { U32 const magic = MEM_readLE32(buffer);
189 if (magic == ZSTD_MAGICNUMBER) return 1;
190 if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1;
192 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
193 if (ZSTD_isLegacy(buffer, size)) return 1;
198 /** ZSTD_frameHeaderSize_internal() :
199 * srcSize must be large enough to reach header size fields.
200 * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless.
201 * @return : size of the Frame Header
202 * or an error code, which can be tested with ZSTD_isError() */
203 static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format)
205 size_t const minInputSize = ZSTD_startingInputLength(format);
206 if (srcSize < minInputSize) return ERROR(srcSize_wrong);
208 { BYTE const fhd = ((const BYTE*)src)[minInputSize-1];
209 U32 const dictID= fhd & 3;
210 U32 const singleSegment = (fhd >> 5) & 1;
211 U32 const fcsId = fhd >> 6;
212 return minInputSize + !singleSegment
213 + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId]
214 + (singleSegment && !fcsId);
218 /** ZSTD_frameHeaderSize() :
219 * srcSize must be >= ZSTD_frameHeaderSize_prefix.
220 * @return : size of the Frame Header,
221 * or an error code (if srcSize is too small) */
222 size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize)
224 return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1);
228 /** ZSTD_getFrameHeader_advanced() :
229 * decode Frame Header, or require larger `srcSize`.
230 * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless
231 * @return : 0, `zfhPtr` is correctly filled,
232 * >0, `srcSize` is too small, value is wanted `srcSize` amount,
233 * or an error code, which can be tested using ZSTD_isError() */
234 size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format)
236 const BYTE* ip = (const BYTE*)src;
237 size_t const minInputSize = ZSTD_startingInputLength(format);
239 memset(zfhPtr, 0, sizeof(*zfhPtr)); /* not strictly necessary, but static analyzer do not understand that zfhPtr is only going to be read only if return value is zero, since they are 2 different signals */
240 if (srcSize < minInputSize) return minInputSize;
241 if (src==NULL) return ERROR(GENERIC); /* invalid parameter */
243 if ( (format != ZSTD_f_zstd1_magicless)
244 && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) {
245 if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
246 /* skippable frame */
247 if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)
248 return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */
249 memset(zfhPtr, 0, sizeof(*zfhPtr));
250 zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE);
251 zfhPtr->frameType = ZSTD_skippableFrame;
254 return ERROR(prefix_unknown);
257 /* ensure there is enough `srcSize` to fully read/decode frame header */
258 { size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format);
259 if (srcSize < fhsize) return fhsize;
260 zfhPtr->headerSize = (U32)fhsize;
263 { BYTE const fhdByte = ip[minInputSize-1];
264 size_t pos = minInputSize;
265 U32 const dictIDSizeCode = fhdByte&3;
266 U32 const checksumFlag = (fhdByte>>2)&1;
267 U32 const singleSegment = (fhdByte>>5)&1;
268 U32 const fcsID = fhdByte>>6;
271 U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN;
272 if ((fhdByte & 0x08) != 0)
273 return ERROR(frameParameter_unsupported); /* reserved bits, must be zero */
275 if (!singleSegment) {
276 BYTE const wlByte = ip[pos++];
277 U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN;
278 if (windowLog > ZSTD_WINDOWLOG_MAX)
279 return ERROR(frameParameter_windowTooLarge);
280 windowSize = (1ULL << windowLog);
281 windowSize += (windowSize >> 3) * (wlByte&7);
283 switch(dictIDSizeCode)
285 default: assert(0); /* impossible */
287 case 1 : dictID = ip[pos]; pos++; break;
288 case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break;
289 case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break;
293 default: assert(0); /* impossible */
294 case 0 : if (singleSegment) frameContentSize = ip[pos]; break;
295 case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break;
296 case 2 : frameContentSize = MEM_readLE32(ip+pos); break;
297 case 3 : frameContentSize = MEM_readLE64(ip+pos); break;
299 if (singleSegment) windowSize = frameContentSize;
301 zfhPtr->frameType = ZSTD_frame;
302 zfhPtr->frameContentSize = frameContentSize;
303 zfhPtr->windowSize = windowSize;
304 zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
305 zfhPtr->dictID = dictID;
306 zfhPtr->checksumFlag = checksumFlag;
311 /** ZSTD_getFrameHeader() :
312 * decode Frame Header, or require larger `srcSize`.
313 * note : this function does not consume input, it only reads it.
314 * @return : 0, `zfhPtr` is correctly filled,
315 * >0, `srcSize` is too small, value is wanted `srcSize` amount,
316 * or an error code, which can be tested using ZSTD_isError() */
317 size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize)
319 return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1);
323 /** ZSTD_getFrameContentSize() :
324 * compatible with legacy mode
325 * @return : decompressed size of the single frame pointed to be `src` if known, otherwise
326 * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
327 * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */
328 unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize)
330 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
331 if (ZSTD_isLegacy(src, srcSize)) {
332 unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize);
333 return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret;
336 { ZSTD_frameHeader zfh;
337 if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0)
338 return ZSTD_CONTENTSIZE_ERROR;
339 if (zfh.frameType == ZSTD_skippableFrame) {
342 return zfh.frameContentSize;
346 static size_t readSkippableFrameSize(void const* src, size_t srcSize)
348 size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE;
351 if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)
352 return ERROR(srcSize_wrong);
354 sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE);
355 if ((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32)
356 return ERROR(frameParameter_unsupported);
358 return skippableHeaderSize + sizeU32;
361 /** ZSTD_findDecompressedSize() :
362 * compatible with legacy mode
363 * `srcSize` must be the exact length of some number of ZSTD compressed and/or
365 * @return : decompressed size of the frames contained */
366 unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize)
368 unsigned long long totalDstSize = 0;
370 while (srcSize >= ZSTD_FRAMEHEADERSIZE_PREFIX) {
371 U32 const magicNumber = MEM_readLE32(src);
373 if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
374 size_t const skippableSize = readSkippableFrameSize(src, srcSize);
375 if (ZSTD_isError(skippableSize))
376 return skippableSize;
377 if (srcSize < skippableSize) {
378 return ZSTD_CONTENTSIZE_ERROR;
381 src = (const BYTE *)src + skippableSize;
382 srcSize -= skippableSize;
386 { unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
387 if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret;
389 /* check for overflow */
390 if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR;
393 { size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize);
394 if (ZSTD_isError(frameSrcSize)) {
395 return ZSTD_CONTENTSIZE_ERROR;
398 src = (const BYTE *)src + frameSrcSize;
399 srcSize -= frameSrcSize;
401 } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
403 if (srcSize) return ZSTD_CONTENTSIZE_ERROR;
408 /** ZSTD_getDecompressedSize() :
409 * compatible with legacy mode
410 * @return : decompressed size if known, 0 otherwise
411 note : 0 can mean any of the following :
412 - frame content is empty
413 - decompressed size field is not present in frame header
414 - frame header unknown / not supported
415 - frame header not complete (`srcSize` too small) */
416 unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize)
418 unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
419 ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN);
420 return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret;
424 /** ZSTD_decodeFrameHeader() :
425 * `headerSize` must be the size provided by ZSTD_frameHeaderSize().
426 * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */
427 static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize)
429 size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format);
430 if (ZSTD_isError(result)) return result; /* invalid header */
431 if (result>0) return ERROR(srcSize_wrong); /* headerSize too small */
432 if (dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID))
433 return ERROR(dictionary_wrong);
434 if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0);
439 /** ZSTD_findFrameCompressedSize() :
440 * compatible with legacy mode
441 * `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame
442 * `srcSize` must be at least as large as the frame contained
443 * @return : the compressed size of the frame starting at `src` */
444 size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)
446 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
447 if (ZSTD_isLegacy(src, srcSize))
448 return ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
450 if ( (srcSize >= ZSTD_SKIPPABLEHEADERSIZE)
451 && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START ) {
452 return readSkippableFrameSize(src, srcSize);
454 const BYTE* ip = (const BYTE*)src;
455 const BYTE* const ipstart = ip;
456 size_t remainingSize = srcSize;
457 ZSTD_frameHeader zfh;
459 /* Extract Frame Header */
460 { size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize);
461 if (ZSTD_isError(ret)) return ret;
462 if (ret > 0) return ERROR(srcSize_wrong);
465 ip += zfh.headerSize;
466 remainingSize -= zfh.headerSize;
468 /* Loop on each block */
470 blockProperties_t blockProperties;
471 size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
472 if (ZSTD_isError(cBlockSize)) return cBlockSize;
474 if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)
475 return ERROR(srcSize_wrong);
477 ip += ZSTD_blockHeaderSize + cBlockSize;
478 remainingSize -= ZSTD_blockHeaderSize + cBlockSize;
480 if (blockProperties.lastBlock) break;
483 if (zfh.checksumFlag) { /* Final frame content checksum */
484 if (remainingSize < 4) return ERROR(srcSize_wrong);
494 /*-*************************************************************
496 ***************************************************************/
499 void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst)
501 if (dst != dctx->previousDstEnd) { /* not contiguous */
502 dctx->dictEnd = dctx->previousDstEnd;
503 dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
504 dctx->prefixStart = dst;
505 dctx->previousDstEnd = dst;
509 /** ZSTD_insertBlock() :
510 insert `src` block into `dctx` history. Useful to track uncompressed blocks. */
511 size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize)
513 ZSTD_checkContinuity(dctx, blockStart);
514 dctx->previousDstEnd = (const char*)blockStart + blockSize;
519 static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity,
520 const void* src, size_t srcSize)
522 DEBUGLOG(5, "ZSTD_copyRawBlock");
524 if (srcSize == 0) return 0;
525 return ERROR(dstBuffer_null);
527 if (srcSize > dstCapacity) return ERROR(dstSize_tooSmall);
528 memcpy(dst, src, srcSize);
532 static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity,
537 if (regenSize == 0) return 0;
538 return ERROR(dstBuffer_null);
540 if (regenSize > dstCapacity) return ERROR(dstSize_tooSmall);
541 memset(dst, b, regenSize);
546 /*! ZSTD_decompressFrame() :
547 * @dctx must be properly initialized
548 * will update *srcPtr and *srcSizePtr,
549 * to make *srcPtr progress by one frame. */
550 static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,
551 void* dst, size_t dstCapacity,
552 const void** srcPtr, size_t *srcSizePtr)
554 const BYTE* ip = (const BYTE*)(*srcPtr);
555 BYTE* const ostart = (BYTE* const)dst;
556 BYTE* const oend = ostart + dstCapacity;
558 size_t remainingSrcSize = *srcSizePtr;
560 DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr);
563 if (remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN+ZSTD_blockHeaderSize)
564 return ERROR(srcSize_wrong);
567 { size_t const frameHeaderSize = ZSTD_frameHeaderSize(ip, ZSTD_FRAMEHEADERSIZE_PREFIX);
568 if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
569 if (remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize)
570 return ERROR(srcSize_wrong);
571 CHECK_F( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) );
572 ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize;
575 /* Loop on each block */
578 blockProperties_t blockProperties;
579 size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties);
580 if (ZSTD_isError(cBlockSize)) return cBlockSize;
582 ip += ZSTD_blockHeaderSize;
583 remainingSrcSize -= ZSTD_blockHeaderSize;
584 if (cBlockSize > remainingSrcSize) return ERROR(srcSize_wrong);
586 switch(blockProperties.blockType)
589 decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize, /* frame */ 1);
592 decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize);
595 decodedSize = ZSTD_setRleBlock(op, oend-op, *ip, blockProperties.origSize);
599 return ERROR(corruption_detected);
602 if (ZSTD_isError(decodedSize)) return decodedSize;
603 if (dctx->fParams.checksumFlag)
604 XXH64_update(&dctx->xxhState, op, decodedSize);
607 remainingSrcSize -= cBlockSize;
608 if (blockProperties.lastBlock) break;
611 if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
612 if ((U64)(op-ostart) != dctx->fParams.frameContentSize) {
613 return ERROR(corruption_detected);
615 if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */
616 U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState);
618 if (remainingSrcSize<4) return ERROR(checksum_wrong);
619 checkRead = MEM_readLE32(ip);
620 if (checkRead != checkCalc) return ERROR(checksum_wrong);
622 remainingSrcSize -= 4;
625 /* Allow caller to get size read */
627 *srcSizePtr = remainingSrcSize;
631 static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
632 void* dst, size_t dstCapacity,
633 const void* src, size_t srcSize,
634 const void* dict, size_t dictSize,
635 const ZSTD_DDict* ddict)
637 void* const dststart = dst;
638 int moreThan1Frame = 0;
640 DEBUGLOG(5, "ZSTD_decompressMultiFrame");
641 assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */
644 dict = ZSTD_DDict_dictContent(ddict);
645 dictSize = ZSTD_DDict_dictSize(ddict);
648 while (srcSize >= ZSTD_FRAMEHEADERSIZE_PREFIX) {
650 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
651 if (ZSTD_isLegacy(src, srcSize)) {
653 size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
654 if (ZSTD_isError(frameSize)) return frameSize;
655 /* legacy support is not compatible with static dctx */
656 if (dctx->staticSize) return ERROR(memory_allocation);
658 decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
659 if (ZSTD_isError(decodedSize)) return decodedSize;
661 assert(decodedSize <=- dstCapacity);
662 dst = (BYTE*)dst + decodedSize;
663 dstCapacity -= decodedSize;
665 src = (const BYTE*)src + frameSize;
666 srcSize -= frameSize;
672 { U32 const magicNumber = MEM_readLE32(src);
673 DEBUGLOG(4, "reading magic number %08X (expecting %08X)",
674 (unsigned)magicNumber, ZSTD_MAGICNUMBER);
675 if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
676 size_t const skippableSize = readSkippableFrameSize(src, srcSize);
677 if (ZSTD_isError(skippableSize))
678 return skippableSize;
679 if (srcSize < skippableSize) return ERROR(srcSize_wrong);
681 src = (const BYTE *)src + skippableSize;
682 srcSize -= skippableSize;
687 /* we were called from ZSTD_decompress_usingDDict */
688 CHECK_F(ZSTD_decompressBegin_usingDDict(dctx, ddict));
690 /* this will initialize correctly with no dict if dict == NULL, so
691 * use this in all cases but ddict */
692 CHECK_F(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize));
694 ZSTD_checkContinuity(dctx, dst);
696 { const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity,
698 if ( (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown)
699 && (moreThan1Frame==1) ) {
700 /* at least one frame successfully completed,
701 * but following bytes are garbage :
702 * it's more likely to be a srcSize error,
703 * specifying more bytes than compressed size of frame(s).
704 * This error message replaces ERROR(prefix_unknown),
705 * which would be confusing, as the first header is actually correct.
706 * Note that one could be unlucky, it might be a corruption error instead,
707 * happening right at the place where we expect zstd magic bytes.
708 * But this is _much_ less likely than a srcSize field error. */
709 return ERROR(srcSize_wrong);
711 if (ZSTD_isError(res)) return res;
712 assert(res <= dstCapacity);
713 dst = (BYTE*)dst + res;
717 } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
719 if (srcSize) return ERROR(srcSize_wrong); /* input not entirely consumed */
721 return (BYTE*)dst - (BYTE*)dststart;
724 size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
725 void* dst, size_t dstCapacity,
726 const void* src, size_t srcSize,
727 const void* dict, size_t dictSize)
729 return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);
733 size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
735 return ZSTD_decompress_usingDict(dctx, dst, dstCapacity, src, srcSize, NULL, 0);
739 size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
741 #if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1)
743 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
744 if (dctx==NULL) return ERROR(memory_allocation);
745 regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
748 #else /* stack mode */
750 ZSTD_initDCtx_internal(&dctx);
751 return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);
756 /*-**************************************
757 * Advanced Streaming Decompression API
758 * Bufferless and synchronous
759 ****************************************/
760 size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; }
762 ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) {
765 default: /* should not happen */
767 case ZSTDds_getFrameHeaderSize:
768 case ZSTDds_decodeFrameHeader:
769 return ZSTDnit_frameHeader;
770 case ZSTDds_decodeBlockHeader:
771 return ZSTDnit_blockHeader;
772 case ZSTDds_decompressBlock:
773 return ZSTDnit_block;
774 case ZSTDds_decompressLastBlock:
775 return ZSTDnit_lastBlock;
776 case ZSTDds_checkChecksum:
777 return ZSTDnit_checksum;
778 case ZSTDds_decodeSkippableHeader:
779 case ZSTDds_skipFrame:
780 return ZSTDnit_skippableFrame;
784 static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; }
786 /** ZSTD_decompressContinue() :
787 * srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress())
788 * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)
789 * or an error code, which can be tested using ZSTD_isError() */
790 size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
792 DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize);
794 if (srcSize != dctx->expected)
795 return ERROR(srcSize_wrong); /* not allowed */
796 if (dstCapacity) ZSTD_checkContinuity(dctx, dst);
800 case ZSTDds_getFrameHeaderSize :
802 if (dctx->format == ZSTD_f_zstd1) { /* allows header */
803 assert(srcSize >= ZSTD_FRAMEIDSIZE); /* to read skippable magic number */
804 if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */
805 memcpy(dctx->headerBuffer, src, srcSize);
806 dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize; /* remaining to load to get full skippable frame header */
807 dctx->stage = ZSTDds_decodeSkippableHeader;
810 dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format);
811 if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize;
812 memcpy(dctx->headerBuffer, src, srcSize);
813 dctx->expected = dctx->headerSize - srcSize;
814 dctx->stage = ZSTDds_decodeFrameHeader;
817 case ZSTDds_decodeFrameHeader:
819 memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize);
820 CHECK_F(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize));
821 dctx->expected = ZSTD_blockHeaderSize;
822 dctx->stage = ZSTDds_decodeBlockHeader;
825 case ZSTDds_decodeBlockHeader:
826 { blockProperties_t bp;
827 size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
828 if (ZSTD_isError(cBlockSize)) return cBlockSize;
829 dctx->expected = cBlockSize;
830 dctx->bType = bp.blockType;
831 dctx->rleSize = bp.origSize;
833 dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;
838 if (dctx->fParams.checksumFlag) {
840 dctx->stage = ZSTDds_checkChecksum;
842 dctx->expected = 0; /* end of frame */
843 dctx->stage = ZSTDds_getFrameHeaderSize;
846 dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */
847 dctx->stage = ZSTDds_decodeBlockHeader;
852 case ZSTDds_decompressLastBlock:
853 case ZSTDds_decompressBlock:
854 DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock");
859 DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed");
860 rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1);
863 rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);
866 rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize);
868 case bt_reserved : /* should never happen */
870 return ERROR(corruption_detected);
872 if (ZSTD_isError(rSize)) return rSize;
873 DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize);
874 dctx->decodedSize += rSize;
875 if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize);
877 if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */
878 DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize);
879 if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
880 if (dctx->decodedSize != dctx->fParams.frameContentSize) {
881 return ERROR(corruption_detected);
883 if (dctx->fParams.checksumFlag) { /* another round for frame checksum */
885 dctx->stage = ZSTDds_checkChecksum;
887 dctx->expected = 0; /* ends here */
888 dctx->stage = ZSTDds_getFrameHeaderSize;
891 dctx->stage = ZSTDds_decodeBlockHeader;
892 dctx->expected = ZSTD_blockHeaderSize;
893 dctx->previousDstEnd = (char*)dst + rSize;
898 case ZSTDds_checkChecksum:
899 assert(srcSize == 4); /* guaranteed by dctx->expected */
900 { U32 const h32 = (U32)XXH64_digest(&dctx->xxhState);
901 U32 const check32 = MEM_readLE32(src);
902 DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32);
903 if (check32 != h32) return ERROR(checksum_wrong);
905 dctx->stage = ZSTDds_getFrameHeaderSize;
909 case ZSTDds_decodeSkippableHeader:
911 assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE);
912 memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */
913 dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */
914 dctx->stage = ZSTDds_skipFrame;
917 case ZSTDds_skipFrame:
919 dctx->stage = ZSTDds_getFrameHeaderSize;
923 assert(0); /* impossible */
924 return ERROR(GENERIC); /* some compiler require default to do something */
929 static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
931 dctx->dictEnd = dctx->previousDstEnd;
932 dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
933 dctx->prefixStart = dict;
934 dctx->previousDstEnd = (const char*)dict + dictSize;
938 /*! ZSTD_loadDEntropy() :
939 * dict : must point at beginning of a valid zstd dictionary.
940 * @return : size of entropy tables read */
942 ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,
943 const void* const dict, size_t const dictSize)
945 const BYTE* dictPtr = (const BYTE*)dict;
946 const BYTE* const dictEnd = dictPtr + dictSize;
948 if (dictSize <= 8) return ERROR(dictionary_corrupted);
949 assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY); /* dict must be valid */
950 dictPtr += 8; /* skip header = magic + dictID */
952 ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable));
953 ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable));
954 ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE);
955 { void* const workspace = &entropy->LLTable; /* use fse tables as temporary workspace; implies fse tables are grouped together */
956 size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable);
957 #ifdef HUF_FORCE_DECOMPRESS_X1
958 /* in minimal huffman, we always use X1 variants */
959 size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable,
960 dictPtr, dictEnd - dictPtr,
961 workspace, workspaceSize);
963 size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable,
964 dictPtr, dictEnd - dictPtr,
965 workspace, workspaceSize);
967 if (HUF_isError(hSize)) return ERROR(dictionary_corrupted);
971 { short offcodeNCount[MaxOff+1];
972 unsigned offcodeMaxValue = MaxOff, offcodeLog;
973 size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
974 if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
975 if (offcodeMaxValue > MaxOff) return ERROR(dictionary_corrupted);
976 if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
977 ZSTD_buildFSETable( entropy->OFTable,
978 offcodeNCount, offcodeMaxValue,
981 dictPtr += offcodeHeaderSize;
984 { short matchlengthNCount[MaxML+1];
985 unsigned matchlengthMaxValue = MaxML, matchlengthLog;
986 size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
987 if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
988 if (matchlengthMaxValue > MaxML) return ERROR(dictionary_corrupted);
989 if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
990 ZSTD_buildFSETable( entropy->MLTable,
991 matchlengthNCount, matchlengthMaxValue,
994 dictPtr += matchlengthHeaderSize;
997 { short litlengthNCount[MaxLL+1];
998 unsigned litlengthMaxValue = MaxLL, litlengthLog;
999 size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
1000 if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
1001 if (litlengthMaxValue > MaxLL) return ERROR(dictionary_corrupted);
1002 if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
1003 ZSTD_buildFSETable( entropy->LLTable,
1004 litlengthNCount, litlengthMaxValue,
1007 dictPtr += litlengthHeaderSize;
1010 if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
1012 size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12));
1013 for (i=0; i<3; i++) {
1014 U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4;
1015 if (rep==0 || rep >= dictContentSize) return ERROR(dictionary_corrupted);
1016 entropy->rep[i] = rep;
1019 return dictPtr - (const BYTE*)dict;
1022 static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1024 if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize);
1025 { U32 const magic = MEM_readLE32(dict);
1026 if (magic != ZSTD_MAGIC_DICTIONARY) {
1027 return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */
1029 dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
1031 /* load entropy tables */
1032 { size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize);
1033 if (ZSTD_isError(eSize)) return ERROR(dictionary_corrupted);
1034 dict = (const char*)dict + eSize;
1037 dctx->litEntropy = dctx->fseEntropy = 1;
1039 /* reference dictionary content */
1040 return ZSTD_refDictContent(dctx, dict, dictSize);
1043 size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx)
1045 assert(dctx != NULL);
1046 dctx->expected = ZSTD_startingInputLength(dctx->format); /* dctx->format must be properly set */
1047 dctx->stage = ZSTDds_getFrameHeaderSize;
1048 dctx->decodedSize = 0;
1049 dctx->previousDstEnd = NULL;
1050 dctx->prefixStart = NULL;
1051 dctx->virtualStart = NULL;
1052 dctx->dictEnd = NULL;
1053 dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */
1054 dctx->litEntropy = dctx->fseEntropy = 0;
1056 ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue));
1057 memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */
1058 dctx->LLTptr = dctx->entropy.LLTable;
1059 dctx->MLTptr = dctx->entropy.MLTable;
1060 dctx->OFTptr = dctx->entropy.OFTable;
1061 dctx->HUFptr = dctx->entropy.hufTable;
1065 size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1067 CHECK_F( ZSTD_decompressBegin(dctx) );
1068 if (dict && dictSize)
1069 CHECK_E(ZSTD_decompress_insertDictionary(dctx, dict, dictSize), dictionary_corrupted);
1074 /* ====== ZSTD_DDict ====== */
1076 size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
1078 DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict");
1079 assert(dctx != NULL);
1081 const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict);
1082 size_t const dictSize = ZSTD_DDict_dictSize(ddict);
1083 const void* const dictEnd = dictStart + dictSize;
1084 dctx->ddictIsCold = (dctx->dictEnd != dictEnd);
1085 DEBUGLOG(4, "DDict is %s",
1086 dctx->ddictIsCold ? "~cold~" : "hot!");
1088 CHECK_F( ZSTD_decompressBegin(dctx) );
1089 if (ddict) { /* NULL ddict is equivalent to no dictionary */
1090 ZSTD_copyDDictParameters(dctx, ddict);
1095 /*! ZSTD_getDictID_fromDict() :
1096 * Provides the dictID stored within dictionary.
1097 * if @return == 0, the dictionary is not conformant with Zstandard specification.
1098 * It can still be loaded, but as a content-only dictionary. */
1099 unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize)
1101 if (dictSize < 8) return 0;
1102 if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0;
1103 return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
1106 /*! ZSTD_getDictID_fromFrame() :
1107 * Provides the dictID required to decompresse frame stored within `src`.
1108 * If @return == 0, the dictID could not be decoded.
1109 * This could for one of the following reasons :
1110 * - The frame does not require a dictionary (most common case).
1111 * - The frame was built with dictID intentionally removed.
1112 * Needed dictionary is a hidden information.
1113 * Note : this use case also happens when using a non-conformant dictionary.
1114 * - `srcSize` is too small, and as a result, frame header could not be decoded.
1115 * Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`.
1116 * - This is not a Zstandard frame.
1117 * When identifying the exact failure cause, it's possible to use
1118 * ZSTD_getFrameHeader(), which will provide a more precise error code. */
1119 unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize)
1121 ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 };
1122 size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize);
1123 if (ZSTD_isError(hError)) return 0;
1128 /*! ZSTD_decompress_usingDDict() :
1129 * Decompression using a pre-digested Dictionary
1130 * Use dictionary without significant overhead. */
1131 size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
1132 void* dst, size_t dstCapacity,
1133 const void* src, size_t srcSize,
1134 const ZSTD_DDict* ddict)
1136 /* pass content and size in case legacy frames are encountered */
1137 return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize,
1143 /*=====================================
1144 * Streaming decompression
1145 *====================================*/
1147 ZSTD_DStream* ZSTD_createDStream(void)
1149 DEBUGLOG(3, "ZSTD_createDStream");
1150 return ZSTD_createDStream_advanced(ZSTD_defaultCMem);
1153 ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize)
1155 return ZSTD_initStaticDCtx(workspace, workspaceSize);
1158 ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem)
1160 return ZSTD_createDCtx_advanced(customMem);
1163 size_t ZSTD_freeDStream(ZSTD_DStream* zds)
1165 return ZSTD_freeDCtx(zds);
1169 /* *** Initialization *** */
1171 size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; }
1172 size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; }
1174 size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx,
1175 const void* dict, size_t dictSize,
1176 ZSTD_dictLoadMethod_e dictLoadMethod,
1177 ZSTD_dictContentType_e dictContentType)
1179 if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
1180 ZSTD_freeDDict(dctx->ddictLocal);
1181 if (dict && dictSize >= 8) {
1182 dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem);
1183 if (dctx->ddictLocal == NULL) return ERROR(memory_allocation);
1185 dctx->ddictLocal = NULL;
1187 dctx->ddict = dctx->ddictLocal;
1191 size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1193 return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
1196 size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
1198 return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
1201 size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
1203 return ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType);
1206 size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize)
1208 return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent);
1212 /* ZSTD_initDStream_usingDict() :
1213 * return : expected size, aka ZSTD_FRAMEHEADERSIZE_PREFIX.
1214 * this function cannot fail */
1215 size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize)
1217 DEBUGLOG(4, "ZSTD_initDStream_usingDict");
1218 zds->streamStage = zdss_init;
1219 zds->noForwardProgress = 0;
1220 CHECK_F( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) );
1221 return ZSTD_FRAMEHEADERSIZE_PREFIX;
1224 /* note : this variant can't fail */
1225 size_t ZSTD_initDStream(ZSTD_DStream* zds)
1227 DEBUGLOG(4, "ZSTD_initDStream");
1228 return ZSTD_initDStream_usingDict(zds, NULL, 0);
1231 /* ZSTD_initDStream_usingDDict() :
1232 * ddict will just be referenced, and must outlive decompression session
1233 * this function cannot fail */
1234 size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict)
1236 size_t const initResult = ZSTD_initDStream(dctx);
1237 dctx->ddict = ddict;
1241 /* ZSTD_resetDStream() :
1242 * return : expected size, aka ZSTD_FRAMEHEADERSIZE_PREFIX.
1243 * this function cannot fail */
1244 size_t ZSTD_resetDStream(ZSTD_DStream* dctx)
1246 DEBUGLOG(4, "ZSTD_resetDStream");
1247 dctx->streamStage = zdss_loadHeader;
1248 dctx->lhSize = dctx->inPos = dctx->outStart = dctx->outEnd = 0;
1249 dctx->legacyVersion = 0;
1250 dctx->hostageByte = 0;
1251 return ZSTD_FRAMEHEADERSIZE_PREFIX;
1255 size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
1257 if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
1258 dctx->ddict = ddict;
1262 /* ZSTD_DCtx_setMaxWindowSize() :
1263 * note : no direct equivalence in ZSTD_DCtx_setParameter,
1264 * since this version sets windowSize, and the other sets windowLog */
1265 size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize)
1267 ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);
1268 size_t const min = (size_t)1 << bounds.lowerBound;
1269 size_t const max = (size_t)1 << bounds.upperBound;
1270 if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
1271 if (maxWindowSize < min) return ERROR(parameter_outOfBound);
1272 if (maxWindowSize > max) return ERROR(parameter_outOfBound);
1273 dctx->maxWindowSize = maxWindowSize;
1277 size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format)
1279 return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, format);
1282 ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam)
1284 ZSTD_bounds bounds = { 0, 0, 0 };
1286 case ZSTD_d_windowLogMax:
1287 bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN;
1288 bounds.upperBound = ZSTD_WINDOWLOG_MAX;
1291 bounds.lowerBound = (int)ZSTD_f_zstd1;
1292 bounds.upperBound = (int)ZSTD_f_zstd1_magicless;
1293 ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
1297 bounds.error = ERROR(parameter_unsupported);
1301 /* ZSTD_dParam_withinBounds:
1302 * @return 1 if value is within dParam bounds,
1304 static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value)
1306 ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam);
1307 if (ZSTD_isError(bounds.error)) return 0;
1308 if (value < bounds.lowerBound) return 0;
1309 if (value > bounds.upperBound) return 0;
1313 #define CHECK_DBOUNDS(p,v) { \
1314 if (!ZSTD_dParam_withinBounds(p, v)) \
1315 return ERROR(parameter_outOfBound); \
1318 size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value)
1320 if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
1322 case ZSTD_d_windowLogMax:
1323 CHECK_DBOUNDS(ZSTD_d_windowLogMax, value);
1324 dctx->maxWindowSize = ((size_t)1) << value;
1327 CHECK_DBOUNDS(ZSTD_d_format, value);
1328 dctx->format = (ZSTD_format_e)value;
1332 return ERROR(parameter_unsupported);
1335 size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset)
1337 if ( (reset == ZSTD_reset_session_only)
1338 || (reset == ZSTD_reset_session_and_parameters) ) {
1339 (void)ZSTD_initDStream(dctx);
1341 if ( (reset == ZSTD_reset_parameters)
1342 || (reset == ZSTD_reset_session_and_parameters) ) {
1343 if (dctx->streamStage != zdss_init)
1344 return ERROR(stage_wrong);
1345 dctx->format = ZSTD_f_zstd1;
1346 dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
1352 size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx)
1354 return ZSTD_sizeof_DCtx(dctx);
1357 size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize)
1359 size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
1360 unsigned long long const neededRBSize = windowSize + blockSize + (WILDCOPY_OVERLENGTH * 2);
1361 unsigned long long const neededSize = MIN(frameContentSize, neededRBSize);
1362 size_t const minRBSize = (size_t) neededSize;
1363 if ((unsigned long long)minRBSize != neededSize) return ERROR(frameParameter_windowTooLarge);
1367 size_t ZSTD_estimateDStreamSize(size_t windowSize)
1369 size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
1370 size_t const inBuffSize = blockSize; /* no block can be larger */
1371 size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN);
1372 return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize;
1375 size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize)
1377 U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable, but requires an additional parameter (or a dctx) */
1378 ZSTD_frameHeader zfh;
1379 size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize);
1380 if (ZSTD_isError(err)) return err;
1381 if (err>0) return ERROR(srcSize_wrong);
1382 if (zfh.windowSize > windowSizeMax)
1383 return ERROR(frameParameter_windowTooLarge);
1384 return ZSTD_estimateDStreamSize((size_t)zfh.windowSize);
1388 /* ***** Decompression ***** */
1390 MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
1392 size_t const length = MIN(dstCapacity, srcSize);
1393 memcpy(dst, src, length);
1398 size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
1400 const char* const istart = (const char*)(input->src) + input->pos;
1401 const char* const iend = (const char*)(input->src) + input->size;
1402 const char* ip = istart;
1403 char* const ostart = (char*)(output->dst) + output->pos;
1404 char* const oend = (char*)(output->dst) + output->size;
1406 U32 someMoreWork = 1;
1408 DEBUGLOG(5, "ZSTD_decompressStream");
1409 if (input->pos > input->size) { /* forbidden */
1410 DEBUGLOG(5, "in: pos: %u vs size: %u",
1411 (U32)input->pos, (U32)input->size);
1412 return ERROR(srcSize_wrong);
1414 if (output->pos > output->size) { /* forbidden */
1415 DEBUGLOG(5, "out: pos: %u vs size: %u",
1416 (U32)output->pos, (U32)output->size);
1417 return ERROR(dstSize_tooSmall);
1419 DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos));
1421 while (someMoreWork) {
1422 switch(zds->streamStage)
1425 DEBUGLOG(5, "stage zdss_init => transparent reset ");
1426 ZSTD_resetDStream(zds); /* transparent reset on starting decoding a new frame */
1429 case zdss_loadHeader :
1430 DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip));
1431 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
1432 if (zds->legacyVersion) {
1433 /* legacy support is incompatible with static dctx */
1434 if (zds->staticSize) return ERROR(memory_allocation);
1435 { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input);
1436 if (hint==0) zds->streamStage = zdss_init;
1440 { size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format);
1441 DEBUGLOG(5, "header size : %u", (U32)hSize);
1442 if (ZSTD_isError(hSize)) {
1443 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
1444 U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart);
1445 if (legacyVersion) {
1446 const void* const dict = zds->ddict ? ZSTD_DDict_dictContent(zds->ddict) : NULL;
1447 size_t const dictSize = zds->ddict ? ZSTD_DDict_dictSize(zds->ddict) : 0;
1448 DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion);
1449 /* legacy support is incompatible with static dctx */
1450 if (zds->staticSize) return ERROR(memory_allocation);
1451 CHECK_F(ZSTD_initLegacyStream(&zds->legacyContext,
1452 zds->previousLegacyVersion, legacyVersion,
1454 zds->legacyVersion = zds->previousLegacyVersion = legacyVersion;
1455 { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input);
1456 if (hint==0) zds->streamStage = zdss_init; /* or stay in stage zdss_loadHeader */
1460 return hSize; /* error */
1462 if (hSize != 0) { /* need more input */
1463 size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */
1464 size_t const remainingInput = (size_t)(iend-ip);
1466 if (toLoad > remainingInput) { /* not enough input to load full header */
1467 if (remainingInput > 0) {
1468 memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput);
1469 zds->lhSize += remainingInput;
1471 input->pos = input->size;
1472 return (MAX(ZSTD_FRAMEHEADERSIZE_MIN, hSize) - zds->lhSize) + ZSTD_blockHeaderSize; /* remaining header bytes + next block header */
1475 memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad;
1479 /* check for single-pass mode opportunity */
1480 if (zds->fParams.frameContentSize && zds->fParams.windowSize /* skippable frame if == 0 */
1481 && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) {
1482 size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend-istart);
1483 if (cSize <= (size_t)(iend-istart)) {
1484 /* shortcut : using single-pass mode */
1485 size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, oend-op, istart, cSize, zds->ddict);
1486 if (ZSTD_isError(decompressedSize)) return decompressedSize;
1487 DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()")
1488 ip = istart + cSize;
1489 op += decompressedSize;
1491 zds->streamStage = zdss_init;
1496 /* Consume header (see ZSTDds_decodeFrameHeader) */
1497 DEBUGLOG(4, "Consume header");
1498 CHECK_F(ZSTD_decompressBegin_usingDDict(zds, zds->ddict));
1500 if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */
1501 zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE);
1502 zds->stage = ZSTDds_skipFrame;
1504 CHECK_F(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize));
1505 zds->expected = ZSTD_blockHeaderSize;
1506 zds->stage = ZSTDds_decodeBlockHeader;
1509 /* control buffer memory usage */
1510 DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)",
1511 (U32)(zds->fParams.windowSize >>10),
1512 (U32)(zds->maxWindowSize >> 10) );
1513 zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN);
1514 if (zds->fParams.windowSize > zds->maxWindowSize) return ERROR(frameParameter_windowTooLarge);
1516 /* Adapt buffer sizes to frame header instructions */
1517 { size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */);
1518 size_t const neededOutBuffSize = ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize);
1519 if ((zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize)) {
1520 size_t const bufferSize = neededInBuffSize + neededOutBuffSize;
1521 DEBUGLOG(4, "inBuff : from %u to %u",
1522 (U32)zds->inBuffSize, (U32)neededInBuffSize);
1523 DEBUGLOG(4, "outBuff : from %u to %u",
1524 (U32)zds->outBuffSize, (U32)neededOutBuffSize);
1525 if (zds->staticSize) { /* static DCtx */
1526 DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize);
1527 assert(zds->staticSize >= sizeof(ZSTD_DCtx)); /* controlled at init */
1528 if (bufferSize > zds->staticSize - sizeof(ZSTD_DCtx))
1529 return ERROR(memory_allocation);
1531 ZSTD_free(zds->inBuff, zds->customMem);
1532 zds->inBuffSize = 0;
1533 zds->outBuffSize = 0;
1534 zds->inBuff = (char*)ZSTD_malloc(bufferSize, zds->customMem);
1535 if (zds->inBuff == NULL) return ERROR(memory_allocation);
1537 zds->inBuffSize = neededInBuffSize;
1538 zds->outBuff = zds->inBuff + zds->inBuffSize;
1539 zds->outBuffSize = neededOutBuffSize;
1541 zds->streamStage = zdss_read;
1545 DEBUGLOG(5, "stage zdss_read");
1546 { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
1547 DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize);
1548 if (neededInSize==0) { /* end of frame */
1549 zds->streamStage = zdss_init;
1553 if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */
1554 int const isSkipFrame = ZSTD_isSkipFrame(zds);
1555 size_t const decodedSize = ZSTD_decompressContinue(zds,
1556 zds->outBuff + zds->outStart, (isSkipFrame ? 0 : zds->outBuffSize - zds->outStart),
1558 if (ZSTD_isError(decodedSize)) return decodedSize;
1560 if (!decodedSize && !isSkipFrame) break; /* this was just a header */
1561 zds->outEnd = zds->outStart + decodedSize;
1562 zds->streamStage = zdss_flush;
1565 if (ip==iend) { someMoreWork = 0; break; } /* no more input */
1566 zds->streamStage = zdss_load;
1570 { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
1571 size_t const toLoad = neededInSize - zds->inPos;
1572 int const isSkipFrame = ZSTD_isSkipFrame(zds);
1575 loadedSize = MIN(toLoad, (size_t)(iend-ip));
1577 if (toLoad > zds->inBuffSize - zds->inPos) return ERROR(corruption_detected); /* should never happen */
1578 loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend-ip);
1581 zds->inPos += loadedSize;
1582 if (loadedSize < toLoad) { someMoreWork = 0; break; } /* not enough input, wait for more */
1584 /* decode loaded input */
1585 { size_t const decodedSize = ZSTD_decompressContinue(zds,
1586 zds->outBuff + zds->outStart, zds->outBuffSize - zds->outStart,
1587 zds->inBuff, neededInSize);
1588 if (ZSTD_isError(decodedSize)) return decodedSize;
1589 zds->inPos = 0; /* input is consumed */
1590 if (!decodedSize && !isSkipFrame) { zds->streamStage = zdss_read; break; } /* this was just a header */
1591 zds->outEnd = zds->outStart + decodedSize;
1593 zds->streamStage = zdss_flush;
1597 { size_t const toFlushSize = zds->outEnd - zds->outStart;
1598 size_t const flushedSize = ZSTD_limitCopy(op, oend-op, zds->outBuff + zds->outStart, toFlushSize);
1600 zds->outStart += flushedSize;
1601 if (flushedSize == toFlushSize) { /* flush completed */
1602 zds->streamStage = zdss_read;
1603 if ( (zds->outBuffSize < zds->fParams.frameContentSize)
1604 && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) {
1605 DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)",
1606 (int)(zds->outBuffSize - zds->outStart),
1607 (U32)zds->fParams.blockSizeMax);
1608 zds->outStart = zds->outEnd = 0;
1612 /* cannot complete flush */
1617 assert(0); /* impossible */
1618 return ERROR(GENERIC); /* some compiler require default to do something */
1622 input->pos = (size_t)(ip - (const char*)(input->src));
1623 output->pos = (size_t)(op - (char*)(output->dst));
1624 if ((ip==istart) && (op==ostart)) { /* no forward progress */
1625 zds->noForwardProgress ++;
1626 if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) {
1627 if (op==oend) return ERROR(dstSize_tooSmall);
1628 if (ip==iend) return ERROR(srcSize_wrong);
1632 zds->noForwardProgress = 0;
1634 { size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds);
1635 if (!nextSrcSizeHint) { /* frame fully decoded */
1636 if (zds->outEnd == zds->outStart) { /* output fully flushed */
1637 if (zds->hostageByte) {
1638 if (input->pos >= input->size) {
1639 /* can't release hostage (not present) */
1640 zds->streamStage = zdss_read;
1643 input->pos++; /* release hostage */
1644 } /* zds->hostageByte */
1646 } /* zds->outEnd == zds->outStart */
1647 if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */
1648 input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */
1652 } /* nextSrcSizeHint==0 */
1653 nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block); /* preload header of next block */
1654 assert(zds->inPos <= nextSrcSizeHint);
1655 nextSrcSizeHint -= zds->inPos; /* part already loaded*/
1656 return nextSrcSizeHint;
1660 size_t ZSTD_decompressStream_simpleArgs (
1662 void* dst, size_t dstCapacity, size_t* dstPos,
1663 const void* src, size_t srcSize, size_t* srcPos)
1665 ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
1666 ZSTD_inBuffer input = { src, srcSize, *srcPos };
1667 /* ZSTD_compress_generic() will check validity of dstPos and srcPos */
1668 size_t const cErr = ZSTD_decompressStream(dctx, &output, &input);
1669 *dstPos = output.pos;
1670 *srcPos = input.pos;