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