zstd_compress_superblock.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  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.
  9. */
  10. /*-*************************************
  11. * Dependencies
  12. ***************************************/
  13. #include "zstd_compress_superblock.h"
  14. #include "../common/zstd_internal.h" /* ZSTD_getSequenceLength */
  15. #include "hist.h" /* HIST_countFast_wksp */
  16. #include "zstd_compress_internal.h" /* ZSTD_[huf|fse|entropy]CTablesMetadata_t */
  17. #include "zstd_compress_sequences.h"
  18. #include "zstd_compress_literals.h"
  19. /** ZSTD_compressSubBlock_literal() :
  20. * Compresses literals section for a sub-block.
  21. * When we have to write the Huffman table we will sometimes choose a header
  22. * size larger than necessary. This is because we have to pick the header size
  23. * before we know the table size + compressed size, so we have a bound on the
  24. * table size. If we guessed incorrectly, we fall back to uncompressed literals.
  25. *
  26. * We write the header when writeEntropy=1 and set entropyWritten=1 when we succeeded
  27. * in writing the header, otherwise it is set to 0.
  28. *
  29. * hufMetadata->hType has literals block type info.
  30. * If it is set_basic, all sub-blocks literals section will be Raw_Literals_Block.
  31. * If it is set_rle, all sub-blocks literals section will be RLE_Literals_Block.
  32. * If it is set_compressed, first sub-block's literals section will be Compressed_Literals_Block
  33. * If it is set_compressed, first sub-block's literals section will be Treeless_Literals_Block
  34. * and the following sub-blocks' literals sections will be Treeless_Literals_Block.
  35. * @return : compressed size of literals section of a sub-block
  36. * Or 0 if it unable to compress.
  37. * Or error code */
  38. static size_t ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
  39. const ZSTD_hufCTablesMetadata_t* hufMetadata,
  40. const BYTE* literals, size_t litSize,
  41. void* dst, size_t dstSize,
  42. const int bmi2, int writeEntropy, int* entropyWritten)
  43. {
  44. size_t const header = writeEntropy ? 200 : 0;
  45. size_t const lhSize = 3 + (litSize >= (1 KB - header)) + (litSize >= (16 KB - header));
  46. BYTE* const ostart = (BYTE*)dst;
  47. BYTE* const oend = ostart + dstSize;
  48. BYTE* op = ostart + lhSize;
  49. U32 const singleStream = lhSize == 3;
  50. symbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat;
  51. size_t cLitSize = 0;
  52. (void)bmi2; /* TODO bmi2... */
  53. DEBUGLOG(5, "ZSTD_compressSubBlock_literal (litSize=%zu, lhSize=%zu, writeEntropy=%d)", litSize, lhSize, writeEntropy);
  54. *entropyWritten = 0;
  55. if (litSize == 0 || hufMetadata->hType == set_basic) {
  56. DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal");
  57. return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
  58. } else if (hufMetadata->hType == set_rle) {
  59. DEBUGLOG(5, "ZSTD_compressSubBlock_literal using rle literal");
  60. return ZSTD_compressRleLiteralsBlock(dst, dstSize, literals, litSize);
  61. }
  62. assert(litSize > 0);
  63. assert(hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat);
  64. if (writeEntropy && hufMetadata->hType == set_compressed) {
  65. ZSTD_memcpy(op, hufMetadata->hufDesBuffer, hufMetadata->hufDesSize);
  66. op += hufMetadata->hufDesSize;
  67. cLitSize += hufMetadata->hufDesSize;
  68. DEBUGLOG(5, "ZSTD_compressSubBlock_literal (hSize=%zu)", hufMetadata->hufDesSize);
  69. }
  70. /* TODO bmi2 */
  71. { const size_t cSize = singleStream ? HUF_compress1X_usingCTable(op, oend-op, literals, litSize, hufTable)
  72. : HUF_compress4X_usingCTable(op, oend-op, literals, litSize, hufTable);
  73. op += cSize;
  74. cLitSize += cSize;
  75. if (cSize == 0 || ERR_isError(cSize)) {
  76. DEBUGLOG(5, "Failed to write entropy tables %s", ZSTD_getErrorName(cSize));
  77. return 0;
  78. }
  79. /* If we expand and we aren't writing a header then emit uncompressed */
  80. if (!writeEntropy && cLitSize >= litSize) {
  81. DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal because uncompressible");
  82. return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
  83. }
  84. /* If we are writing headers then allow expansion that doesn't change our header size. */
  85. if (lhSize < (size_t)(3 + (cLitSize >= 1 KB) + (cLitSize >= 16 KB))) {
  86. assert(cLitSize > litSize);
  87. DEBUGLOG(5, "Literals expanded beyond allowed header size");
  88. return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);
  89. }
  90. DEBUGLOG(5, "ZSTD_compressSubBlock_literal (cSize=%zu)", cSize);
  91. }
  92. /* Build header */
  93. switch(lhSize)
  94. {
  95. case 3: /* 2 - 2 - 10 - 10 */
  96. { U32 const lhc = hType + ((!singleStream) << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<14);
  97. MEM_writeLE24(ostart, lhc);
  98. break;
  99. }
  100. case 4: /* 2 - 2 - 14 - 14 */
  101. { U32 const lhc = hType + (2 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<18);
  102. MEM_writeLE32(ostart, lhc);
  103. break;
  104. }
  105. case 5: /* 2 - 2 - 18 - 18 */
  106. { U32 const lhc = hType + (3 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<22);
  107. MEM_writeLE32(ostart, lhc);
  108. ostart[4] = (BYTE)(cLitSize >> 10);
  109. break;
  110. }
  111. default: /* not possible : lhSize is {3,4,5} */
  112. assert(0);
  113. }
  114. *entropyWritten = 1;
  115. DEBUGLOG(5, "Compressed literals: %u -> %u", (U32)litSize, (U32)(op-ostart));
  116. return op-ostart;
  117. }
  118. static size_t ZSTD_seqDecompressedSize(seqStore_t const* seqStore, const seqDef* sequences, size_t nbSeq, size_t litSize, int lastSequence) {
  119. const seqDef* const sstart = sequences;
  120. const seqDef* const send = sequences + nbSeq;
  121. const seqDef* sp = sstart;
  122. size_t matchLengthSum = 0;
  123. size_t litLengthSum = 0;
  124. while (send-sp > 0) {
  125. ZSTD_sequenceLength const seqLen = ZSTD_getSequenceLength(seqStore, sp);
  126. litLengthSum += seqLen.litLength;
  127. matchLengthSum += seqLen.matchLength;
  128. sp++;
  129. }
  130. assert(litLengthSum <= litSize);
  131. if (!lastSequence) {
  132. assert(litLengthSum == litSize);
  133. }
  134. return matchLengthSum + litSize;
  135. }
  136. /** ZSTD_compressSubBlock_sequences() :
  137. * Compresses sequences section for a sub-block.
  138. * fseMetadata->llType, fseMetadata->ofType, and fseMetadata->mlType have
  139. * symbol compression modes for the super-block.
  140. * The first successfully compressed block will have these in its header.
  141. * We set entropyWritten=1 when we succeed in compressing the sequences.
  142. * The following sub-blocks will always have repeat mode.
  143. * @return : compressed size of sequences section of a sub-block
  144. * Or 0 if it is unable to compress
  145. * Or error code. */
  146. static size_t ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables,
  147. const ZSTD_fseCTablesMetadata_t* fseMetadata,
  148. const seqDef* sequences, size_t nbSeq,
  149. const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
  150. const ZSTD_CCtx_params* cctxParams,
  151. void* dst, size_t dstCapacity,
  152. const int bmi2, int writeEntropy, int* entropyWritten)
  153. {
  154. const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
  155. BYTE* const ostart = (BYTE*)dst;
  156. BYTE* const oend = ostart + dstCapacity;
  157. BYTE* op = ostart;
  158. BYTE* seqHead;
  159. DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (nbSeq=%zu, writeEntropy=%d, longOffsets=%d)", nbSeq, writeEntropy, longOffsets);
  160. *entropyWritten = 0;
  161. /* Sequences Header */
  162. RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,
  163. dstSize_tooSmall, "");
  164. if (nbSeq < 0x7F)
  165. *op++ = (BYTE)nbSeq;
  166. else if (nbSeq < LONGNBSEQ)
  167. op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
  168. else
  169. op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
  170. if (nbSeq==0) {
  171. return op - ostart;
  172. }
  173. /* seqHead : flags for FSE encoding type */
  174. seqHead = op++;
  175. DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (seqHeadSize=%u)", (unsigned)(op-ostart));
  176. if (writeEntropy) {
  177. const U32 LLtype = fseMetadata->llType;
  178. const U32 Offtype = fseMetadata->ofType;
  179. const U32 MLtype = fseMetadata->mlType;
  180. DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (fseTablesSize=%zu)", fseMetadata->fseTablesSize);
  181. *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
  182. ZSTD_memcpy(op, fseMetadata->fseTablesBuffer, fseMetadata->fseTablesSize);
  183. op += fseMetadata->fseTablesSize;
  184. } else {
  185. const U32 repeat = set_repeat;
  186. *seqHead = (BYTE)((repeat<<6) + (repeat<<4) + (repeat<<2));
  187. }
  188. { size_t const bitstreamSize = ZSTD_encodeSequences(
  189. op, oend - op,
  190. fseTables->matchlengthCTable, mlCode,
  191. fseTables->offcodeCTable, ofCode,
  192. fseTables->litlengthCTable, llCode,
  193. sequences, nbSeq,
  194. longOffsets, bmi2);
  195. FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");
  196. op += bitstreamSize;
  197. /* zstd versions <= 1.3.4 mistakenly report corruption when
  198. * FSE_readNCount() receives a buffer < 4 bytes.
  199. * Fixed by https://github.com/facebook/zstd/pull/1146.
  200. * This can happen when the last set_compressed table present is 2
  201. * bytes and the bitstream is only one byte.
  202. * In this exceedingly rare case, we will simply emit an uncompressed
  203. * block, since it isn't worth optimizing.
  204. */
  205. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  206. if (writeEntropy && fseMetadata->lastCountSize && fseMetadata->lastCountSize + bitstreamSize < 4) {
  207. /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
  208. assert(fseMetadata->lastCountSize + bitstreamSize == 3);
  209. DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
  210. "emitting an uncompressed block.");
  211. return 0;
  212. }
  213. #endif
  214. DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (bitstreamSize=%zu)", bitstreamSize);
  215. }
  216. /* zstd versions <= 1.4.0 mistakenly report error when
  217. * sequences section body size is less than 3 bytes.
  218. * Fixed by https://github.com/facebook/zstd/pull/1664.
  219. * This can happen when the previous sequences section block is compressed
  220. * with rle mode and the current block's sequences section is compressed
  221. * with repeat mode where sequences section body size can be 1 byte.
  222. */
  223. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  224. if (op-seqHead < 4) {
  225. DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.4.0 by emitting "
  226. "an uncompressed block when sequences are < 4 bytes");
  227. return 0;
  228. }
  229. #endif
  230. *entropyWritten = 1;
  231. return op - ostart;
  232. }
  233. /** ZSTD_compressSubBlock() :
  234. * Compresses a single sub-block.
  235. * @return : compressed size of the sub-block
  236. * Or 0 if it failed to compress. */
  237. static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy,
  238. const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
  239. const seqDef* sequences, size_t nbSeq,
  240. const BYTE* literals, size_t litSize,
  241. const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,
  242. const ZSTD_CCtx_params* cctxParams,
  243. void* dst, size_t dstCapacity,
  244. const int bmi2,
  245. int writeLitEntropy, int writeSeqEntropy,
  246. int* litEntropyWritten, int* seqEntropyWritten,
  247. U32 lastBlock)
  248. {
  249. BYTE* const ostart = (BYTE*)dst;
  250. BYTE* const oend = ostart + dstCapacity;
  251. BYTE* op = ostart + ZSTD_blockHeaderSize;
  252. DEBUGLOG(5, "ZSTD_compressSubBlock (litSize=%zu, nbSeq=%zu, writeLitEntropy=%d, writeSeqEntropy=%d, lastBlock=%d)",
  253. litSize, nbSeq, writeLitEntropy, writeSeqEntropy, lastBlock);
  254. { size_t cLitSize = ZSTD_compressSubBlock_literal((const HUF_CElt*)entropy->huf.CTable,
  255. &entropyMetadata->hufMetadata, literals, litSize,
  256. op, oend-op, bmi2, writeLitEntropy, litEntropyWritten);
  257. FORWARD_IF_ERROR(cLitSize, "ZSTD_compressSubBlock_literal failed");
  258. if (cLitSize == 0) return 0;
  259. op += cLitSize;
  260. }
  261. { size_t cSeqSize = ZSTD_compressSubBlock_sequences(&entropy->fse,
  262. &entropyMetadata->fseMetadata,
  263. sequences, nbSeq,
  264. llCode, mlCode, ofCode,
  265. cctxParams,
  266. op, oend-op,
  267. bmi2, writeSeqEntropy, seqEntropyWritten);
  268. FORWARD_IF_ERROR(cSeqSize, "ZSTD_compressSubBlock_sequences failed");
  269. if (cSeqSize == 0) return 0;
  270. op += cSeqSize;
  271. }
  272. /* Write block header */
  273. { size_t cSize = (op-ostart)-ZSTD_blockHeaderSize;
  274. U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
  275. MEM_writeLE24(ostart, cBlockHeader24);
  276. }
  277. return op-ostart;
  278. }
  279. static size_t ZSTD_estimateSubBlockSize_literal(const BYTE* literals, size_t litSize,
  280. const ZSTD_hufCTables_t* huf,
  281. const ZSTD_hufCTablesMetadata_t* hufMetadata,
  282. void* workspace, size_t wkspSize,
  283. int writeEntropy)
  284. {
  285. unsigned* const countWksp = (unsigned*)workspace;
  286. unsigned maxSymbolValue = 255;
  287. size_t literalSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
  288. if (hufMetadata->hType == set_basic) return litSize;
  289. else if (hufMetadata->hType == set_rle) return 1;
  290. else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {
  291. size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);
  292. if (ZSTD_isError(largest)) return litSize;
  293. { size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);
  294. if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;
  295. return cLitSizeEstimate + literalSectionHeaderSize;
  296. } }
  297. assert(0); /* impossible */
  298. return 0;
  299. }
  300. static size_t ZSTD_estimateSubBlockSize_symbolType(symbolEncodingType_e type,
  301. const BYTE* codeTable, unsigned maxCode,
  302. size_t nbSeq, const FSE_CTable* fseCTable,
  303. const U32* additionalBits,
  304. short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,
  305. void* workspace, size_t wkspSize)
  306. {
  307. unsigned* const countWksp = (unsigned*)workspace;
  308. const BYTE* ctp = codeTable;
  309. const BYTE* const ctStart = ctp;
  310. const BYTE* const ctEnd = ctStart + nbSeq;
  311. size_t cSymbolTypeSizeEstimateInBits = 0;
  312. unsigned max = maxCode;
  313. HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize); /* can't fail */
  314. if (type == set_basic) {
  315. /* We selected this encoding type, so it must be valid. */
  316. assert(max <= defaultMax);
  317. cSymbolTypeSizeEstimateInBits = max <= defaultMax
  318. ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max)
  319. : ERROR(GENERIC);
  320. } else if (type == set_rle) {
  321. cSymbolTypeSizeEstimateInBits = 0;
  322. } else if (type == set_compressed || type == set_repeat) {
  323. cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);
  324. }
  325. if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) return nbSeq * 10;
  326. while (ctp < ctEnd) {
  327. if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];
  328. else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */
  329. ctp++;
  330. }
  331. return cSymbolTypeSizeEstimateInBits / 8;
  332. }
  333. static size_t ZSTD_estimateSubBlockSize_sequences(const BYTE* ofCodeTable,
  334. const BYTE* llCodeTable,
  335. const BYTE* mlCodeTable,
  336. size_t nbSeq,
  337. const ZSTD_fseCTables_t* fseTables,
  338. const ZSTD_fseCTablesMetadata_t* fseMetadata,
  339. void* workspace, size_t wkspSize,
  340. int writeEntropy)
  341. {
  342. size_t const sequencesSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */
  343. size_t cSeqSizeEstimate = 0;
  344. if (nbSeq == 0) return sequencesSectionHeaderSize;
  345. cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, MaxOff,
  346. nbSeq, fseTables->offcodeCTable, NULL,
  347. OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
  348. workspace, wkspSize);
  349. cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->llType, llCodeTable, MaxLL,
  350. nbSeq, fseTables->litlengthCTable, LL_bits,
  351. LL_defaultNorm, LL_defaultNormLog, MaxLL,
  352. workspace, wkspSize);
  353. cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, MaxML,
  354. nbSeq, fseTables->matchlengthCTable, ML_bits,
  355. ML_defaultNorm, ML_defaultNormLog, MaxML,
  356. workspace, wkspSize);
  357. if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;
  358. return cSeqSizeEstimate + sequencesSectionHeaderSize;
  359. }
  360. static size_t ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,
  361. const BYTE* ofCodeTable,
  362. const BYTE* llCodeTable,
  363. const BYTE* mlCodeTable,
  364. size_t nbSeq,
  365. const ZSTD_entropyCTables_t* entropy,
  366. const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
  367. void* workspace, size_t wkspSize,
  368. int writeLitEntropy, int writeSeqEntropy) {
  369. size_t cSizeEstimate = 0;
  370. cSizeEstimate += ZSTD_estimateSubBlockSize_literal(literals, litSize,
  371. &entropy->huf, &entropyMetadata->hufMetadata,
  372. workspace, wkspSize, writeLitEntropy);
  373. cSizeEstimate += ZSTD_estimateSubBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
  374. nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
  375. workspace, wkspSize, writeSeqEntropy);
  376. return cSizeEstimate + ZSTD_blockHeaderSize;
  377. }
  378. static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMetadata)
  379. {
  380. if (fseMetadata->llType == set_compressed || fseMetadata->llType == set_rle)
  381. return 1;
  382. if (fseMetadata->mlType == set_compressed || fseMetadata->mlType == set_rle)
  383. return 1;
  384. if (fseMetadata->ofType == set_compressed || fseMetadata->ofType == set_rle)
  385. return 1;
  386. return 0;
  387. }
  388. /** ZSTD_compressSubBlock_multi() :
  389. * Breaks super-block into multiple sub-blocks and compresses them.
  390. * Entropy will be written to the first block.
  391. * The following blocks will use repeat mode to compress.
  392. * All sub-blocks are compressed blocks (no raw or rle blocks).
  393. * @return : compressed size of the super block (which is multiple ZSTD blocks)
  394. * Or 0 if it failed to compress. */
  395. static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
  396. const ZSTD_compressedBlockState_t* prevCBlock,
  397. ZSTD_compressedBlockState_t* nextCBlock,
  398. const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
  399. const ZSTD_CCtx_params* cctxParams,
  400. void* dst, size_t dstCapacity,
  401. const void* src, size_t srcSize,
  402. const int bmi2, U32 lastBlock,
  403. void* workspace, size_t wkspSize)
  404. {
  405. const seqDef* const sstart = seqStorePtr->sequencesStart;
  406. const seqDef* const send = seqStorePtr->sequences;
  407. const seqDef* sp = sstart;
  408. const BYTE* const lstart = seqStorePtr->litStart;
  409. const BYTE* const lend = seqStorePtr->lit;
  410. const BYTE* lp = lstart;
  411. BYTE const* ip = (BYTE const*)src;
  412. BYTE const* const iend = ip + srcSize;
  413. BYTE* const ostart = (BYTE*)dst;
  414. BYTE* const oend = ostart + dstCapacity;
  415. BYTE* op = ostart;
  416. const BYTE* llCodePtr = seqStorePtr->llCode;
  417. const BYTE* mlCodePtr = seqStorePtr->mlCode;
  418. const BYTE* ofCodePtr = seqStorePtr->ofCode;
  419. size_t targetCBlockSize = cctxParams->targetCBlockSize;
  420. size_t litSize, seqCount;
  421. int writeLitEntropy = entropyMetadata->hufMetadata.hType == set_compressed;
  422. int writeSeqEntropy = 1;
  423. int lastSequence = 0;
  424. DEBUGLOG(5, "ZSTD_compressSubBlock_multi (litSize=%u, nbSeq=%u)",
  425. (unsigned)(lend-lp), (unsigned)(send-sstart));
  426. litSize = 0;
  427. seqCount = 0;
  428. do {
  429. size_t cBlockSizeEstimate = 0;
  430. if (sstart == send) {
  431. lastSequence = 1;
  432. } else {
  433. const seqDef* const sequence = sp + seqCount;
  434. lastSequence = sequence == send - 1;
  435. litSize += ZSTD_getSequenceLength(seqStorePtr, sequence).litLength;
  436. seqCount++;
  437. }
  438. if (lastSequence) {
  439. assert(lp <= lend);
  440. assert(litSize <= (size_t)(lend - lp));
  441. litSize = (size_t)(lend - lp);
  442. }
  443. /* I think there is an optimization opportunity here.
  444. * Calling ZSTD_estimateSubBlockSize for every sequence can be wasteful
  445. * since it recalculates estimate from scratch.
  446. * For example, it would recount literal distribution and symbol codes everytime.
  447. */
  448. cBlockSizeEstimate = ZSTD_estimateSubBlockSize(lp, litSize, ofCodePtr, llCodePtr, mlCodePtr, seqCount,
  449. &nextCBlock->entropy, entropyMetadata,
  450. workspace, wkspSize, writeLitEntropy, writeSeqEntropy);
  451. if (cBlockSizeEstimate > targetCBlockSize || lastSequence) {
  452. int litEntropyWritten = 0;
  453. int seqEntropyWritten = 0;
  454. const size_t decompressedSize = ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, lastSequence);
  455. const size_t cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
  456. sp, seqCount,
  457. lp, litSize,
  458. llCodePtr, mlCodePtr, ofCodePtr,
  459. cctxParams,
  460. op, oend-op,
  461. bmi2, writeLitEntropy, writeSeqEntropy,
  462. &litEntropyWritten, &seqEntropyWritten,
  463. lastBlock && lastSequence);
  464. FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
  465. if (cSize > 0 && cSize < decompressedSize) {
  466. DEBUGLOG(5, "Committed the sub-block");
  467. assert(ip + decompressedSize <= iend);
  468. ip += decompressedSize;
  469. sp += seqCount;
  470. lp += litSize;
  471. op += cSize;
  472. llCodePtr += seqCount;
  473. mlCodePtr += seqCount;
  474. ofCodePtr += seqCount;
  475. litSize = 0;
  476. seqCount = 0;
  477. /* Entropy only needs to be written once */
  478. if (litEntropyWritten) {
  479. writeLitEntropy = 0;
  480. }
  481. if (seqEntropyWritten) {
  482. writeSeqEntropy = 0;
  483. }
  484. }
  485. }
  486. } while (!lastSequence);
  487. if (writeLitEntropy) {
  488. DEBUGLOG(5, "ZSTD_compressSubBlock_multi has literal entropy tables unwritten");
  489. ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));
  490. }
  491. if (writeSeqEntropy && ZSTD_needSequenceEntropyTables(&entropyMetadata->fseMetadata)) {
  492. /* If we haven't written our entropy tables, then we've violated our contract and
  493. * must emit an uncompressed block.
  494. */
  495. DEBUGLOG(5, "ZSTD_compressSubBlock_multi has sequence entropy tables unwritten");
  496. return 0;
  497. }
  498. if (ip < iend) {
  499. size_t const cSize = ZSTD_noCompressBlock(op, oend - op, ip, iend - ip, lastBlock);
  500. DEBUGLOG(5, "ZSTD_compressSubBlock_multi last sub-block uncompressed, %zu bytes", (size_t)(iend - ip));
  501. FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
  502. assert(cSize != 0);
  503. op += cSize;
  504. /* We have to regenerate the repcodes because we've skipped some sequences */
  505. if (sp < send) {
  506. seqDef const* seq;
  507. repcodes_t rep;
  508. ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
  509. for (seq = sstart; seq < sp; ++seq) {
  510. rep = ZSTD_updateRep(rep.rep, seq->offset - 1, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
  511. }
  512. ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
  513. }
  514. }
  515. DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed");
  516. return op-ostart;
  517. }
  518. size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc,
  519. void* dst, size_t dstCapacity,
  520. void const* src, size_t srcSize,
  521. unsigned lastBlock) {
  522. ZSTD_entropyCTablesMetadata_t entropyMetadata;
  523. FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(&zc->seqStore,
  524. &zc->blockState.prevCBlock->entropy,
  525. &zc->blockState.nextCBlock->entropy,
  526. &zc->appliedParams,
  527. &entropyMetadata,
  528. zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */), "");
  529. return ZSTD_compressSubBlock_multi(&zc->seqStore,
  530. zc->blockState.prevCBlock,
  531. zc->blockState.nextCBlock,
  532. &entropyMetadata,
  533. &zc->appliedParams,
  534. dst, dstCapacity,
  535. src, srcSize,
  536. zc->bmi2, lastBlock,
  537. zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */);
  538. }