Path: blob/master/Utilities/cmzstd/lib/compress/zstd_compress_superblock.c
5040 views
/*1* Copyright (c) Meta Platforms, Inc. and affiliates.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910/*-*************************************11* Dependencies12***************************************/13#include "zstd_compress_superblock.h"1415#include "../common/zstd_internal.h" /* ZSTD_getSequenceLength */16#include "hist.h" /* HIST_countFast_wksp */17#include "zstd_compress_internal.h" /* ZSTD_[huf|fse|entropy]CTablesMetadata_t */18#include "zstd_compress_sequences.h"19#include "zstd_compress_literals.h"2021/** ZSTD_compressSubBlock_literal() :22* Compresses literals section for a sub-block.23* When we have to write the Huffman table we will sometimes choose a header24* size larger than necessary. This is because we have to pick the header size25* before we know the table size + compressed size, so we have a bound on the26* table size. If we guessed incorrectly, we fall back to uncompressed literals.27*28* We write the header when writeEntropy=1 and set entropyWritten=1 when we succeeded29* in writing the header, otherwise it is set to 0.30*31* hufMetadata->hType has literals block type info.32* If it is set_basic, all sub-blocks literals section will be Raw_Literals_Block.33* If it is set_rle, all sub-blocks literals section will be RLE_Literals_Block.34* If it is set_compressed, first sub-block's literals section will be Compressed_Literals_Block35* If it is set_compressed, first sub-block's literals section will be Treeless_Literals_Block36* and the following sub-blocks' literals sections will be Treeless_Literals_Block.37* @return : compressed size of literals section of a sub-block38* Or 0 if unable to compress.39* Or error code */40static size_t41ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,42const ZSTD_hufCTablesMetadata_t* hufMetadata,43const BYTE* literals, size_t litSize,44void* dst, size_t dstSize,45const int bmi2, int writeEntropy, int* entropyWritten)46{47size_t const header = writeEntropy ? 200 : 0;48size_t const lhSize = 3 + (litSize >= (1 KB - header)) + (litSize >= (16 KB - header));49BYTE* const ostart = (BYTE*)dst;50BYTE* const oend = ostart + dstSize;51BYTE* op = ostart + lhSize;52U32 const singleStream = lhSize == 3;53SymbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat;54size_t cLitSize = 0;5556DEBUGLOG(5, "ZSTD_compressSubBlock_literal (litSize=%zu, lhSize=%zu, writeEntropy=%d)", litSize, lhSize, writeEntropy);5758*entropyWritten = 0;59if (litSize == 0 || hufMetadata->hType == set_basic) {60DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal");61return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);62} else if (hufMetadata->hType == set_rle) {63DEBUGLOG(5, "ZSTD_compressSubBlock_literal using rle literal");64return ZSTD_compressRleLiteralsBlock(dst, dstSize, literals, litSize);65}6667assert(litSize > 0);68assert(hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat);6970if (writeEntropy && hufMetadata->hType == set_compressed) {71ZSTD_memcpy(op, hufMetadata->hufDesBuffer, hufMetadata->hufDesSize);72op += hufMetadata->hufDesSize;73cLitSize += hufMetadata->hufDesSize;74DEBUGLOG(5, "ZSTD_compressSubBlock_literal (hSize=%zu)", hufMetadata->hufDesSize);75}7677{ int const flags = bmi2 ? HUF_flags_bmi2 : 0;78const size_t cSize = singleStream ? HUF_compress1X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags)79: HUF_compress4X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags);80op += cSize;81cLitSize += cSize;82if (cSize == 0 || ERR_isError(cSize)) {83DEBUGLOG(5, "Failed to write entropy tables %s", ZSTD_getErrorName(cSize));84return 0;85}86/* If we expand and we aren't writing a header then emit uncompressed */87if (!writeEntropy && cLitSize >= litSize) {88DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal because uncompressible");89return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);90}91/* If we are writing headers then allow expansion that doesn't change our header size. */92if (lhSize < (size_t)(3 + (cLitSize >= 1 KB) + (cLitSize >= 16 KB))) {93assert(cLitSize > litSize);94DEBUGLOG(5, "Literals expanded beyond allowed header size");95return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize);96}97DEBUGLOG(5, "ZSTD_compressSubBlock_literal (cSize=%zu)", cSize);98}99100/* Build header */101switch(lhSize)102{103case 3: /* 2 - 2 - 10 - 10 */104{ U32 const lhc = hType + ((U32)(!singleStream) << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<14);105MEM_writeLE24(ostart, lhc);106break;107}108case 4: /* 2 - 2 - 14 - 14 */109{ U32 const lhc = hType + (2 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<18);110MEM_writeLE32(ostart, lhc);111break;112}113case 5: /* 2 - 2 - 18 - 18 */114{ U32 const lhc = hType + (3 << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<22);115MEM_writeLE32(ostart, lhc);116ostart[4] = (BYTE)(cLitSize >> 10);117break;118}119default: /* not possible : lhSize is {3,4,5} */120assert(0);121}122*entropyWritten = 1;123DEBUGLOG(5, "Compressed literals: %u -> %u", (U32)litSize, (U32)(op-ostart));124return (size_t)(op-ostart);125}126127static size_t128ZSTD_seqDecompressedSize(SeqStore_t const* seqStore,129const SeqDef* sequences, size_t nbSeqs,130size_t litSize, int lastSubBlock)131{132size_t matchLengthSum = 0;133size_t litLengthSum = 0;134size_t n;135for (n=0; n<nbSeqs; n++) {136const ZSTD_SequenceLength seqLen = ZSTD_getSequenceLength(seqStore, sequences+n);137litLengthSum += seqLen.litLength;138matchLengthSum += seqLen.matchLength;139}140DEBUGLOG(5, "ZSTD_seqDecompressedSize: %u sequences from %p: %u literals + %u matchlength",141(unsigned)nbSeqs, (const void*)sequences,142(unsigned)litLengthSum, (unsigned)matchLengthSum);143if (!lastSubBlock)144assert(litLengthSum == litSize);145else146assert(litLengthSum <= litSize);147(void)litLengthSum;148return matchLengthSum + litSize;149}150151/** ZSTD_compressSubBlock_sequences() :152* Compresses sequences section for a sub-block.153* fseMetadata->llType, fseMetadata->ofType, and fseMetadata->mlType have154* symbol compression modes for the super-block.155* The first successfully compressed block will have these in its header.156* We set entropyWritten=1 when we succeed in compressing the sequences.157* The following sub-blocks will always have repeat mode.158* @return : compressed size of sequences section of a sub-block159* Or 0 if it is unable to compress160* Or error code. */161static size_t162ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables,163const ZSTD_fseCTablesMetadata_t* fseMetadata,164const SeqDef* sequences, size_t nbSeq,165const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,166const ZSTD_CCtx_params* cctxParams,167void* dst, size_t dstCapacity,168const int bmi2, int writeEntropy, int* entropyWritten)169{170const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;171BYTE* const ostart = (BYTE*)dst;172BYTE* const oend = ostart + dstCapacity;173BYTE* op = ostart;174BYTE* seqHead;175176DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (nbSeq=%zu, writeEntropy=%d, longOffsets=%d)", nbSeq, writeEntropy, longOffsets);177178*entropyWritten = 0;179/* Sequences Header */180RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/,181dstSize_tooSmall, "");182if (nbSeq < 128)183*op++ = (BYTE)nbSeq;184else if (nbSeq < LONGNBSEQ)185op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;186else187op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;188if (nbSeq==0) {189return (size_t)(op - ostart);190}191192/* seqHead : flags for FSE encoding type */193seqHead = op++;194195DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (seqHeadSize=%u)", (unsigned)(op-ostart));196197if (writeEntropy) {198const U32 LLtype = fseMetadata->llType;199const U32 Offtype = fseMetadata->ofType;200const U32 MLtype = fseMetadata->mlType;201DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (fseTablesSize=%zu)", fseMetadata->fseTablesSize);202*seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));203ZSTD_memcpy(op, fseMetadata->fseTablesBuffer, fseMetadata->fseTablesSize);204op += fseMetadata->fseTablesSize;205} else {206const U32 repeat = set_repeat;207*seqHead = (BYTE)((repeat<<6) + (repeat<<4) + (repeat<<2));208}209210{ size_t const bitstreamSize = ZSTD_encodeSequences(211op, (size_t)(oend - op),212fseTables->matchlengthCTable, mlCode,213fseTables->offcodeCTable, ofCode,214fseTables->litlengthCTable, llCode,215sequences, nbSeq,216longOffsets, bmi2);217FORWARD_IF_ERROR(bitstreamSize, "ZSTD_encodeSequences failed");218op += bitstreamSize;219/* zstd versions <= 1.3.4 mistakenly report corruption when220* FSE_readNCount() receives a buffer < 4 bytes.221* Fixed by https://github.com/facebook/zstd/pull/1146.222* This can happen when the last set_compressed table present is 2223* bytes and the bitstream is only one byte.224* In this exceedingly rare case, we will simply emit an uncompressed225* block, since it isn't worth optimizing.226*/227#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION228if (writeEntropy && fseMetadata->lastCountSize && fseMetadata->lastCountSize + bitstreamSize < 4) {229/* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */230assert(fseMetadata->lastCountSize + bitstreamSize == 3);231DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "232"emitting an uncompressed block.");233return 0;234}235#endif236DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (bitstreamSize=%zu)", bitstreamSize);237}238239/* zstd versions <= 1.4.0 mistakenly report error when240* sequences section body size is less than 3 bytes.241* Fixed by https://github.com/facebook/zstd/pull/1664.242* This can happen when the previous sequences section block is compressed243* with rle mode and the current block's sequences section is compressed244* with repeat mode where sequences section body size can be 1 byte.245*/246#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION247if (op-seqHead < 4) {248DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.4.0 by emitting "249"an uncompressed block when sequences are < 4 bytes");250return 0;251}252#endif253254*entropyWritten = 1;255return (size_t)(op - ostart);256}257258/** ZSTD_compressSubBlock() :259* Compresses a single sub-block.260* @return : compressed size of the sub-block261* Or 0 if it failed to compress. */262static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy,263const ZSTD_entropyCTablesMetadata_t* entropyMetadata,264const SeqDef* sequences, size_t nbSeq,265const BYTE* literals, size_t litSize,266const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode,267const ZSTD_CCtx_params* cctxParams,268void* dst, size_t dstCapacity,269const int bmi2,270int writeLitEntropy, int writeSeqEntropy,271int* litEntropyWritten, int* seqEntropyWritten,272U32 lastBlock)273{274BYTE* const ostart = (BYTE*)dst;275BYTE* const oend = ostart + dstCapacity;276BYTE* op = ostart + ZSTD_blockHeaderSize;277DEBUGLOG(5, "ZSTD_compressSubBlock (litSize=%zu, nbSeq=%zu, writeLitEntropy=%d, writeSeqEntropy=%d, lastBlock=%d)",278litSize, nbSeq, writeLitEntropy, writeSeqEntropy, lastBlock);279{ size_t cLitSize = ZSTD_compressSubBlock_literal((const HUF_CElt*)entropy->huf.CTable,280&entropyMetadata->hufMetadata, literals, litSize,281op, (size_t)(oend-op),282bmi2, writeLitEntropy, litEntropyWritten);283FORWARD_IF_ERROR(cLitSize, "ZSTD_compressSubBlock_literal failed");284if (cLitSize == 0) return 0;285op += cLitSize;286}287{ size_t cSeqSize = ZSTD_compressSubBlock_sequences(&entropy->fse,288&entropyMetadata->fseMetadata,289sequences, nbSeq,290llCode, mlCode, ofCode,291cctxParams,292op, (size_t)(oend-op),293bmi2, writeSeqEntropy, seqEntropyWritten);294FORWARD_IF_ERROR(cSeqSize, "ZSTD_compressSubBlock_sequences failed");295if (cSeqSize == 0) return 0;296op += cSeqSize;297}298/* Write block header */299{ size_t cSize = (size_t)(op-ostart) - ZSTD_blockHeaderSize;300U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);301MEM_writeLE24(ostart, cBlockHeader24);302}303return (size_t)(op-ostart);304}305306static size_t ZSTD_estimateSubBlockSize_literal(const BYTE* literals, size_t litSize,307const ZSTD_hufCTables_t* huf,308const ZSTD_hufCTablesMetadata_t* hufMetadata,309void* workspace, size_t wkspSize,310int writeEntropy)311{312unsigned* const countWksp = (unsigned*)workspace;313unsigned maxSymbolValue = 255;314size_t literalSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */315316if (hufMetadata->hType == set_basic) return litSize;317else if (hufMetadata->hType == set_rle) return 1;318else if (hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat) {319size_t const largest = HIST_count_wksp (countWksp, &maxSymbolValue, (const BYTE*)literals, litSize, workspace, wkspSize);320if (ZSTD_isError(largest)) return litSize;321{ size_t cLitSizeEstimate = HUF_estimateCompressedSize((const HUF_CElt*)huf->CTable, countWksp, maxSymbolValue);322if (writeEntropy) cLitSizeEstimate += hufMetadata->hufDesSize;323return cLitSizeEstimate + literalSectionHeaderSize;324} }325assert(0); /* impossible */326return 0;327}328329static size_t ZSTD_estimateSubBlockSize_symbolType(SymbolEncodingType_e type,330const BYTE* codeTable, unsigned maxCode,331size_t nbSeq, const FSE_CTable* fseCTable,332const U8* additionalBits,333short const* defaultNorm, U32 defaultNormLog, U32 defaultMax,334void* workspace, size_t wkspSize)335{336unsigned* const countWksp = (unsigned*)workspace;337const BYTE* ctp = codeTable;338const BYTE* const ctStart = ctp;339const BYTE* const ctEnd = ctStart + nbSeq;340size_t cSymbolTypeSizeEstimateInBits = 0;341unsigned max = maxCode;342343HIST_countFast_wksp(countWksp, &max, codeTable, nbSeq, workspace, wkspSize); /* can't fail */344if (type == set_basic) {345/* We selected this encoding type, so it must be valid. */346assert(max <= defaultMax);347cSymbolTypeSizeEstimateInBits = max <= defaultMax348? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, countWksp, max)349: ERROR(GENERIC);350} else if (type == set_rle) {351cSymbolTypeSizeEstimateInBits = 0;352} else if (type == set_compressed || type == set_repeat) {353cSymbolTypeSizeEstimateInBits = ZSTD_fseBitCost(fseCTable, countWksp, max);354}355if (ZSTD_isError(cSymbolTypeSizeEstimateInBits)) return nbSeq * 10;356while (ctp < ctEnd) {357if (additionalBits) cSymbolTypeSizeEstimateInBits += additionalBits[*ctp];358else cSymbolTypeSizeEstimateInBits += *ctp; /* for offset, offset code is also the number of additional bits */359ctp++;360}361return cSymbolTypeSizeEstimateInBits / 8;362}363364static size_t ZSTD_estimateSubBlockSize_sequences(const BYTE* ofCodeTable,365const BYTE* llCodeTable,366const BYTE* mlCodeTable,367size_t nbSeq,368const ZSTD_fseCTables_t* fseTables,369const ZSTD_fseCTablesMetadata_t* fseMetadata,370void* workspace, size_t wkspSize,371int writeEntropy)372{373size_t const sequencesSectionHeaderSize = 3; /* Use hard coded size of 3 bytes */374size_t cSeqSizeEstimate = 0;375if (nbSeq == 0) return sequencesSectionHeaderSize;376cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->ofType, ofCodeTable, MaxOff,377nbSeq, fseTables->offcodeCTable, NULL,378OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,379workspace, wkspSize);380cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->llType, llCodeTable, MaxLL,381nbSeq, fseTables->litlengthCTable, LL_bits,382LL_defaultNorm, LL_defaultNormLog, MaxLL,383workspace, wkspSize);384cSeqSizeEstimate += ZSTD_estimateSubBlockSize_symbolType(fseMetadata->mlType, mlCodeTable, MaxML,385nbSeq, fseTables->matchlengthCTable, ML_bits,386ML_defaultNorm, ML_defaultNormLog, MaxML,387workspace, wkspSize);388if (writeEntropy) cSeqSizeEstimate += fseMetadata->fseTablesSize;389return cSeqSizeEstimate + sequencesSectionHeaderSize;390}391392typedef struct {393size_t estLitSize;394size_t estBlockSize;395} EstimatedBlockSize;396static EstimatedBlockSize ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,397const BYTE* ofCodeTable,398const BYTE* llCodeTable,399const BYTE* mlCodeTable,400size_t nbSeq,401const ZSTD_entropyCTables_t* entropy,402const ZSTD_entropyCTablesMetadata_t* entropyMetadata,403void* workspace, size_t wkspSize,404int writeLitEntropy, int writeSeqEntropy)405{406EstimatedBlockSize ebs;407ebs.estLitSize = ZSTD_estimateSubBlockSize_literal(literals, litSize,408&entropy->huf, &entropyMetadata->hufMetadata,409workspace, wkspSize, writeLitEntropy);410ebs.estBlockSize = ZSTD_estimateSubBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,411nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,412workspace, wkspSize, writeSeqEntropy);413ebs.estBlockSize += ebs.estLitSize + ZSTD_blockHeaderSize;414return ebs;415}416417static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMetadata)418{419if (fseMetadata->llType == set_compressed || fseMetadata->llType == set_rle)420return 1;421if (fseMetadata->mlType == set_compressed || fseMetadata->mlType == set_rle)422return 1;423if (fseMetadata->ofType == set_compressed || fseMetadata->ofType == set_rle)424return 1;425return 0;426}427428static size_t countLiterals(SeqStore_t const* seqStore, const SeqDef* sp, size_t seqCount)429{430size_t n, total = 0;431assert(sp != NULL);432for (n=0; n<seqCount; n++) {433total += ZSTD_getSequenceLength(seqStore, sp+n).litLength;434}435DEBUGLOG(6, "countLiterals for %zu sequences from %p => %zu bytes", seqCount, (const void*)sp, total);436return total;437}438439#define BYTESCALE 256440441static size_t sizeBlockSequences(const SeqDef* sp, size_t nbSeqs,442size_t targetBudget, size_t avgLitCost, size_t avgSeqCost,443int firstSubBlock)444{445size_t n, budget = 0, inSize=0;446/* entropy headers */447size_t const headerSize = (size_t)firstSubBlock * 120 * BYTESCALE; /* generous estimate */448assert(firstSubBlock==0 || firstSubBlock==1);449budget += headerSize;450451/* first sequence => at least one sequence*/452budget += sp[0].litLength * avgLitCost + avgSeqCost;453if (budget > targetBudget) return 1;454inSize = sp[0].litLength + (sp[0].mlBase+MINMATCH);455456/* loop over sequences */457for (n=1; n<nbSeqs; n++) {458size_t currentCost = sp[n].litLength * avgLitCost + avgSeqCost;459budget += currentCost;460inSize += sp[n].litLength + (sp[n].mlBase+MINMATCH);461/* stop when sub-block budget is reached */462if ( (budget > targetBudget)463/* though continue to expand until the sub-block is deemed compressible */464&& (budget < inSize * BYTESCALE) )465break;466}467468return n;469}470471/** ZSTD_compressSubBlock_multi() :472* Breaks super-block into multiple sub-blocks and compresses them.473* Entropy will be written into the first block.474* The following blocks use repeat_mode to compress.475* Sub-blocks are all compressed, except the last one when beneficial.476* @return : compressed size of the super block (which features multiple ZSTD blocks)477* or 0 if it failed to compress. */478static size_t ZSTD_compressSubBlock_multi(const SeqStore_t* seqStorePtr,479const ZSTD_compressedBlockState_t* prevCBlock,480ZSTD_compressedBlockState_t* nextCBlock,481const ZSTD_entropyCTablesMetadata_t* entropyMetadata,482const ZSTD_CCtx_params* cctxParams,483void* dst, size_t dstCapacity,484const void* src, size_t srcSize,485const int bmi2, U32 lastBlock,486void* workspace, size_t wkspSize)487{488const SeqDef* const sstart = seqStorePtr->sequencesStart;489const SeqDef* const send = seqStorePtr->sequences;490const SeqDef* sp = sstart; /* tracks progresses within seqStorePtr->sequences */491size_t const nbSeqs = (size_t)(send - sstart);492const BYTE* const lstart = seqStorePtr->litStart;493const BYTE* const lend = seqStorePtr->lit;494const BYTE* lp = lstart;495size_t const nbLiterals = (size_t)(lend - lstart);496BYTE const* ip = (BYTE const*)src;497BYTE const* const iend = ip + srcSize;498BYTE* const ostart = (BYTE*)dst;499BYTE* const oend = ostart + dstCapacity;500BYTE* op = ostart;501const BYTE* llCodePtr = seqStorePtr->llCode;502const BYTE* mlCodePtr = seqStorePtr->mlCode;503const BYTE* ofCodePtr = seqStorePtr->ofCode;504size_t const minTarget = ZSTD_TARGETCBLOCKSIZE_MIN; /* enforce minimum size, to reduce undesirable side effects */505size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);506int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed);507int writeSeqEntropy = 1;508509DEBUGLOG(5, "ZSTD_compressSubBlock_multi (srcSize=%u, litSize=%u, nbSeq=%u)",510(unsigned)srcSize, (unsigned)(lend-lstart), (unsigned)(send-sstart));511512/* let's start by a general estimation for the full block */513if (nbSeqs > 0) {514EstimatedBlockSize const ebs =515ZSTD_estimateSubBlockSize(lp, nbLiterals,516ofCodePtr, llCodePtr, mlCodePtr, nbSeqs,517&nextCBlock->entropy, entropyMetadata,518workspace, wkspSize,519writeLitEntropy, writeSeqEntropy);520/* quick estimation */521size_t const avgLitCost = nbLiterals ? (ebs.estLitSize * BYTESCALE) / nbLiterals : BYTESCALE;522size_t const avgSeqCost = ((ebs.estBlockSize - ebs.estLitSize) * BYTESCALE) / nbSeqs;523const size_t nbSubBlocks = MAX((ebs.estBlockSize + (targetCBlockSize/2)) / targetCBlockSize, 1);524size_t n, avgBlockBudget, blockBudgetSupp=0;525avgBlockBudget = (ebs.estBlockSize * BYTESCALE) / nbSubBlocks;526DEBUGLOG(5, "estimated fullblock size=%u bytes ; avgLitCost=%.2f ; avgSeqCost=%.2f ; targetCBlockSize=%u, nbSubBlocks=%u ; avgBlockBudget=%.0f bytes",527(unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,528(unsigned)targetCBlockSize, (unsigned)nbSubBlocks, (double)avgBlockBudget/BYTESCALE);529/* simplification: if estimates states that the full superblock doesn't compress, just bail out immediately530* this will result in the production of a single uncompressed block covering @srcSize.*/531if (ebs.estBlockSize > srcSize) return 0;532533/* compress and write sub-blocks */534assert(nbSubBlocks>0);535for (n=0; n < nbSubBlocks-1; n++) {536/* determine nb of sequences for current sub-block + nbLiterals from next sequence */537size_t const seqCount = sizeBlockSequences(sp, (size_t)(send-sp),538avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);539/* if reached last sequence : break to last sub-block (simplification) */540assert(seqCount <= (size_t)(send-sp));541if (sp + seqCount == send) break;542assert(seqCount > 0);543/* compress sub-block */544{ int litEntropyWritten = 0;545int seqEntropyWritten = 0;546size_t litSize = countLiterals(seqStorePtr, sp, seqCount);547const size_t decompressedSize =548ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 0);549size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,550sp, seqCount,551lp, litSize,552llCodePtr, mlCodePtr, ofCodePtr,553cctxParams,554op, (size_t)(oend-op),555bmi2, writeLitEntropy, writeSeqEntropy,556&litEntropyWritten, &seqEntropyWritten,5570);558FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");559560/* check compressibility, update state components */561if (cSize > 0 && cSize < decompressedSize) {562DEBUGLOG(5, "Committed sub-block compressing %u bytes => %u bytes",563(unsigned)decompressedSize, (unsigned)cSize);564assert(ip + decompressedSize <= iend);565ip += decompressedSize;566lp += litSize;567op += cSize;568llCodePtr += seqCount;569mlCodePtr += seqCount;570ofCodePtr += seqCount;571/* Entropy only needs to be written once */572if (litEntropyWritten) {573writeLitEntropy = 0;574}575if (seqEntropyWritten) {576writeSeqEntropy = 0;577}578sp += seqCount;579blockBudgetSupp = 0;580} }581/* otherwise : do not compress yet, coalesce current sub-block with following one */582}583} /* if (nbSeqs > 0) */584585/* write last block */586DEBUGLOG(5, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));587{ int litEntropyWritten = 0;588int seqEntropyWritten = 0;589size_t litSize = (size_t)(lend - lp);590size_t seqCount = (size_t)(send - sp);591const size_t decompressedSize =592ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 1);593size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,594sp, seqCount,595lp, litSize,596llCodePtr, mlCodePtr, ofCodePtr,597cctxParams,598op, (size_t)(oend-op),599bmi2, writeLitEntropy, writeSeqEntropy,600&litEntropyWritten, &seqEntropyWritten,601lastBlock);602FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");603604/* update pointers, the nb of literals borrowed from next sequence must be preserved */605if (cSize > 0 && cSize < decompressedSize) {606DEBUGLOG(5, "Last sub-block compressed %u bytes => %u bytes",607(unsigned)decompressedSize, (unsigned)cSize);608assert(ip + decompressedSize <= iend);609ip += decompressedSize;610lp += litSize;611op += cSize;612llCodePtr += seqCount;613mlCodePtr += seqCount;614ofCodePtr += seqCount;615/* Entropy only needs to be written once */616if (litEntropyWritten) {617writeLitEntropy = 0;618}619if (seqEntropyWritten) {620writeSeqEntropy = 0;621}622sp += seqCount;623}624}625626627if (writeLitEntropy) {628DEBUGLOG(5, "Literal entropy tables were never written");629ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));630}631if (writeSeqEntropy && ZSTD_needSequenceEntropyTables(&entropyMetadata->fseMetadata)) {632/* If we haven't written our entropy tables, then we've violated our contract and633* must emit an uncompressed block.634*/635DEBUGLOG(5, "Sequence entropy tables were never written => cancel, emit an uncompressed block");636return 0;637}638639if (ip < iend) {640/* some data left : last part of the block sent uncompressed */641size_t const rSize = (size_t)((iend - ip));642size_t const cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, rSize, lastBlock);643DEBUGLOG(5, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));644FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");645assert(cSize != 0);646op += cSize;647/* We have to regenerate the repcodes because we've skipped some sequences */648if (sp < send) {649const SeqDef* seq;650Repcodes_t rep;651ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));652for (seq = sstart; seq < sp; ++seq) {653ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);654}655ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));656}657}658659DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed all subBlocks: total compressed size = %u",660(unsigned)(op-ostart));661return (size_t)(op-ostart);662}663664size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc,665void* dst, size_t dstCapacity,666const void* src, size_t srcSize,667unsigned lastBlock)668{669ZSTD_entropyCTablesMetadata_t entropyMetadata;670671FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(&zc->seqStore,672&zc->blockState.prevCBlock->entropy,673&zc->blockState.nextCBlock->entropy,674&zc->appliedParams,675&entropyMetadata,676zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */), "");677678return ZSTD_compressSubBlock_multi(&zc->seqStore,679zc->blockState.prevCBlock,680zc->blockState.nextCBlock,681&entropyMetadata,682&zc->appliedParams,683dst, dstCapacity,684src, srcSize,685zc->bmi2, lastBlock,686zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */);687}688689690