You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_compress_superblock.c 28KB

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