zstd_compress_superblock.c 28 KB

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