xref: /aosp_15_r20/external/zstd/lib/compress/fse_compress.c (revision 01826a4963a0d8a59bc3812d29bdf0fb76416722)
1*01826a49SYabin Cui /* ******************************************************************
2*01826a49SYabin Cui  * FSE : Finite State Entropy encoder
3*01826a49SYabin Cui  * Copyright (c) Meta Platforms, Inc. and affiliates.
4*01826a49SYabin Cui  *
5*01826a49SYabin Cui  *  You can contact the author at :
6*01826a49SYabin Cui  *  - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
7*01826a49SYabin Cui  *  - Public forum : https://groups.google.com/forum/#!forum/lz4c
8*01826a49SYabin Cui  *
9*01826a49SYabin Cui  * This source code is licensed under both the BSD-style license (found in the
10*01826a49SYabin Cui  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
11*01826a49SYabin Cui  * in the COPYING file in the root directory of this source tree).
12*01826a49SYabin Cui  * You may select, at your option, one of the above-listed licenses.
13*01826a49SYabin Cui ****************************************************************** */
14*01826a49SYabin Cui 
15*01826a49SYabin Cui /* **************************************************************
16*01826a49SYabin Cui *  Includes
17*01826a49SYabin Cui ****************************************************************/
18*01826a49SYabin Cui #include "../common/compiler.h"
19*01826a49SYabin Cui #include "../common/mem.h"        /* U32, U16, etc. */
20*01826a49SYabin Cui #include "../common/debug.h"      /* assert, DEBUGLOG */
21*01826a49SYabin Cui #include "hist.h"       /* HIST_count_wksp */
22*01826a49SYabin Cui #include "../common/bitstream.h"
23*01826a49SYabin Cui #define FSE_STATIC_LINKING_ONLY
24*01826a49SYabin Cui #include "../common/fse.h"
25*01826a49SYabin Cui #include "../common/error_private.h"
26*01826a49SYabin Cui #define ZSTD_DEPS_NEED_MALLOC
27*01826a49SYabin Cui #define ZSTD_DEPS_NEED_MATH64
28*01826a49SYabin Cui #include "../common/zstd_deps.h"  /* ZSTD_memset */
29*01826a49SYabin Cui #include "../common/bits.h" /* ZSTD_highbit32 */
30*01826a49SYabin Cui 
31*01826a49SYabin Cui 
32*01826a49SYabin Cui /* **************************************************************
33*01826a49SYabin Cui *  Error Management
34*01826a49SYabin Cui ****************************************************************/
35*01826a49SYabin Cui #define FSE_isError ERR_isError
36*01826a49SYabin Cui 
37*01826a49SYabin Cui 
38*01826a49SYabin Cui /* **************************************************************
39*01826a49SYabin Cui *  Templates
40*01826a49SYabin Cui ****************************************************************/
41*01826a49SYabin Cui /*
42*01826a49SYabin Cui   designed to be included
43*01826a49SYabin Cui   for type-specific functions (template emulation in C)
44*01826a49SYabin Cui   Objective is to write these functions only once, for improved maintenance
45*01826a49SYabin Cui */
46*01826a49SYabin Cui 
47*01826a49SYabin Cui /* safety checks */
48*01826a49SYabin Cui #ifndef FSE_FUNCTION_EXTENSION
49*01826a49SYabin Cui #  error "FSE_FUNCTION_EXTENSION must be defined"
50*01826a49SYabin Cui #endif
51*01826a49SYabin Cui #ifndef FSE_FUNCTION_TYPE
52*01826a49SYabin Cui #  error "FSE_FUNCTION_TYPE must be defined"
53*01826a49SYabin Cui #endif
54*01826a49SYabin Cui 
55*01826a49SYabin Cui /* Function names */
56*01826a49SYabin Cui #define FSE_CAT(X,Y) X##Y
57*01826a49SYabin Cui #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
58*01826a49SYabin Cui #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
59*01826a49SYabin Cui 
60*01826a49SYabin Cui 
61*01826a49SYabin Cui /* Function templates */
62*01826a49SYabin Cui 
63*01826a49SYabin Cui /* FSE_buildCTable_wksp() :
64*01826a49SYabin Cui  * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
65*01826a49SYabin Cui  * wkspSize should be sized to handle worst case situation, which is `1<<max_tableLog * sizeof(FSE_FUNCTION_TYPE)`
66*01826a49SYabin Cui  * workSpace must also be properly aligned with FSE_FUNCTION_TYPE requirements
67*01826a49SYabin Cui  */
FSE_buildCTable_wksp(FSE_CTable * ct,const short * normalizedCounter,unsigned maxSymbolValue,unsigned tableLog,void * workSpace,size_t wkspSize)68*01826a49SYabin Cui size_t FSE_buildCTable_wksp(FSE_CTable* ct,
69*01826a49SYabin Cui                       const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
70*01826a49SYabin Cui                             void* workSpace, size_t wkspSize)
71*01826a49SYabin Cui {
72*01826a49SYabin Cui     U32 const tableSize = 1 << tableLog;
73*01826a49SYabin Cui     U32 const tableMask = tableSize - 1;
74*01826a49SYabin Cui     void* const ptr = ct;
75*01826a49SYabin Cui     U16* const tableU16 = ( (U16*) ptr) + 2;
76*01826a49SYabin Cui     void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableLog ? tableSize>>1 : 1) ;
77*01826a49SYabin Cui     FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
78*01826a49SYabin Cui     U32 const step = FSE_TABLESTEP(tableSize);
79*01826a49SYabin Cui     U32 const maxSV1 = maxSymbolValue+1;
80*01826a49SYabin Cui 
81*01826a49SYabin Cui     U16* cumul = (U16*)workSpace;   /* size = maxSV1 */
82*01826a49SYabin Cui     FSE_FUNCTION_TYPE* const tableSymbol = (FSE_FUNCTION_TYPE*)(cumul + (maxSV1+1));  /* size = tableSize */
83*01826a49SYabin Cui 
84*01826a49SYabin Cui     U32 highThreshold = tableSize-1;
85*01826a49SYabin Cui 
86*01826a49SYabin Cui     assert(((size_t)workSpace & 1) == 0);  /* Must be 2 bytes-aligned */
87*01826a49SYabin Cui     if (FSE_BUILD_CTABLE_WORKSPACE_SIZE(maxSymbolValue, tableLog) > wkspSize) return ERROR(tableLog_tooLarge);
88*01826a49SYabin Cui     /* CTable header */
89*01826a49SYabin Cui     tableU16[-2] = (U16) tableLog;
90*01826a49SYabin Cui     tableU16[-1] = (U16) maxSymbolValue;
91*01826a49SYabin Cui     assert(tableLog < 16);   /* required for threshold strategy to work */
92*01826a49SYabin Cui 
93*01826a49SYabin Cui     /* For explanations on how to distribute symbol values over the table :
94*01826a49SYabin Cui      * https://fastcompression.blogspot.fr/2014/02/fse-distributing-symbol-values.html */
95*01826a49SYabin Cui 
96*01826a49SYabin Cui      #ifdef __clang_analyzer__
97*01826a49SYabin Cui      ZSTD_memset(tableSymbol, 0, sizeof(*tableSymbol) * tableSize);   /* useless initialization, just to keep scan-build happy */
98*01826a49SYabin Cui      #endif
99*01826a49SYabin Cui 
100*01826a49SYabin Cui     /* symbol start positions */
101*01826a49SYabin Cui     {   U32 u;
102*01826a49SYabin Cui         cumul[0] = 0;
103*01826a49SYabin Cui         for (u=1; u <= maxSV1; u++) {
104*01826a49SYabin Cui             if (normalizedCounter[u-1]==-1) {  /* Low proba symbol */
105*01826a49SYabin Cui                 cumul[u] = cumul[u-1] + 1;
106*01826a49SYabin Cui                 tableSymbol[highThreshold--] = (FSE_FUNCTION_TYPE)(u-1);
107*01826a49SYabin Cui             } else {
108*01826a49SYabin Cui                 assert(normalizedCounter[u-1] >= 0);
109*01826a49SYabin Cui                 cumul[u] = cumul[u-1] + (U16)normalizedCounter[u-1];
110*01826a49SYabin Cui                 assert(cumul[u] >= cumul[u-1]);  /* no overflow */
111*01826a49SYabin Cui         }   }
112*01826a49SYabin Cui         cumul[maxSV1] = (U16)(tableSize+1);
113*01826a49SYabin Cui     }
114*01826a49SYabin Cui 
115*01826a49SYabin Cui     /* Spread symbols */
116*01826a49SYabin Cui     if (highThreshold == tableSize - 1) {
117*01826a49SYabin Cui         /* Case for no low prob count symbols. Lay down 8 bytes at a time
118*01826a49SYabin Cui          * to reduce branch misses since we are operating on a small block
119*01826a49SYabin Cui          */
120*01826a49SYabin Cui         BYTE* const spread = tableSymbol + tableSize; /* size = tableSize + 8 (may write beyond tableSize) */
121*01826a49SYabin Cui         {   U64 const add = 0x0101010101010101ull;
122*01826a49SYabin Cui             size_t pos = 0;
123*01826a49SYabin Cui             U64 sv = 0;
124*01826a49SYabin Cui             U32 s;
125*01826a49SYabin Cui             for (s=0; s<maxSV1; ++s, sv += add) {
126*01826a49SYabin Cui                 int i;
127*01826a49SYabin Cui                 int const n = normalizedCounter[s];
128*01826a49SYabin Cui                 MEM_write64(spread + pos, sv);
129*01826a49SYabin Cui                 for (i = 8; i < n; i += 8) {
130*01826a49SYabin Cui                     MEM_write64(spread + pos + i, sv);
131*01826a49SYabin Cui                 }
132*01826a49SYabin Cui                 assert(n>=0);
133*01826a49SYabin Cui                 pos += (size_t)n;
134*01826a49SYabin Cui             }
135*01826a49SYabin Cui         }
136*01826a49SYabin Cui         /* Spread symbols across the table. Lack of lowprob symbols means that
137*01826a49SYabin Cui          * we don't need variable sized inner loop, so we can unroll the loop and
138*01826a49SYabin Cui          * reduce branch misses.
139*01826a49SYabin Cui          */
140*01826a49SYabin Cui         {   size_t position = 0;
141*01826a49SYabin Cui             size_t s;
142*01826a49SYabin Cui             size_t const unroll = 2; /* Experimentally determined optimal unroll */
143*01826a49SYabin Cui             assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
144*01826a49SYabin Cui             for (s = 0; s < (size_t)tableSize; s += unroll) {
145*01826a49SYabin Cui                 size_t u;
146*01826a49SYabin Cui                 for (u = 0; u < unroll; ++u) {
147*01826a49SYabin Cui                     size_t const uPosition = (position + (u * step)) & tableMask;
148*01826a49SYabin Cui                     tableSymbol[uPosition] = spread[s + u];
149*01826a49SYabin Cui                 }
150*01826a49SYabin Cui                 position = (position + (unroll * step)) & tableMask;
151*01826a49SYabin Cui             }
152*01826a49SYabin Cui             assert(position == 0);   /* Must have initialized all positions */
153*01826a49SYabin Cui         }
154*01826a49SYabin Cui     } else {
155*01826a49SYabin Cui         U32 position = 0;
156*01826a49SYabin Cui         U32 symbol;
157*01826a49SYabin Cui         for (symbol=0; symbol<maxSV1; symbol++) {
158*01826a49SYabin Cui             int nbOccurrences;
159*01826a49SYabin Cui             int const freq = normalizedCounter[symbol];
160*01826a49SYabin Cui             for (nbOccurrences=0; nbOccurrences<freq; nbOccurrences++) {
161*01826a49SYabin Cui                 tableSymbol[position] = (FSE_FUNCTION_TYPE)symbol;
162*01826a49SYabin Cui                 position = (position + step) & tableMask;
163*01826a49SYabin Cui                 while (position > highThreshold)
164*01826a49SYabin Cui                     position = (position + step) & tableMask;   /* Low proba area */
165*01826a49SYabin Cui         }   }
166*01826a49SYabin Cui         assert(position==0);  /* Must have initialized all positions */
167*01826a49SYabin Cui     }
168*01826a49SYabin Cui 
169*01826a49SYabin Cui     /* Build table */
170*01826a49SYabin Cui     {   U32 u; for (u=0; u<tableSize; u++) {
171*01826a49SYabin Cui         FSE_FUNCTION_TYPE s = tableSymbol[u];   /* note : static analyzer may not understand tableSymbol is properly initialized */
172*01826a49SYabin Cui         tableU16[cumul[s]++] = (U16) (tableSize+u);   /* TableU16 : sorted by symbol order; gives next state value */
173*01826a49SYabin Cui     }   }
174*01826a49SYabin Cui 
175*01826a49SYabin Cui     /* Build Symbol Transformation Table */
176*01826a49SYabin Cui     {   unsigned total = 0;
177*01826a49SYabin Cui         unsigned s;
178*01826a49SYabin Cui         for (s=0; s<=maxSymbolValue; s++) {
179*01826a49SYabin Cui             switch (normalizedCounter[s])
180*01826a49SYabin Cui             {
181*01826a49SYabin Cui             case  0:
182*01826a49SYabin Cui                 /* filling nonetheless, for compatibility with FSE_getMaxNbBits() */
183*01826a49SYabin Cui                 symbolTT[s].deltaNbBits = ((tableLog+1) << 16) - (1<<tableLog);
184*01826a49SYabin Cui                 break;
185*01826a49SYabin Cui 
186*01826a49SYabin Cui             case -1:
187*01826a49SYabin Cui             case  1:
188*01826a49SYabin Cui                 symbolTT[s].deltaNbBits = (tableLog << 16) - (1<<tableLog);
189*01826a49SYabin Cui                 assert(total <= INT_MAX);
190*01826a49SYabin Cui                 symbolTT[s].deltaFindState = (int)(total - 1);
191*01826a49SYabin Cui                 total ++;
192*01826a49SYabin Cui                 break;
193*01826a49SYabin Cui             default :
194*01826a49SYabin Cui                 assert(normalizedCounter[s] > 1);
195*01826a49SYabin Cui                 {   U32 const maxBitsOut = tableLog - ZSTD_highbit32 ((U32)normalizedCounter[s]-1);
196*01826a49SYabin Cui                     U32 const minStatePlus = (U32)normalizedCounter[s] << maxBitsOut;
197*01826a49SYabin Cui                     symbolTT[s].deltaNbBits = (maxBitsOut << 16) - minStatePlus;
198*01826a49SYabin Cui                     symbolTT[s].deltaFindState = (int)(total - (unsigned)normalizedCounter[s]);
199*01826a49SYabin Cui                     total +=  (unsigned)normalizedCounter[s];
200*01826a49SYabin Cui     }   }   }   }
201*01826a49SYabin Cui 
202*01826a49SYabin Cui #if 0  /* debug : symbol costs */
203*01826a49SYabin Cui     DEBUGLOG(5, "\n --- table statistics : ");
204*01826a49SYabin Cui     {   U32 symbol;
205*01826a49SYabin Cui         for (symbol=0; symbol<=maxSymbolValue; symbol++) {
206*01826a49SYabin Cui             DEBUGLOG(5, "%3u: w=%3i,   maxBits=%u, fracBits=%.2f",
207*01826a49SYabin Cui                 symbol, normalizedCounter[symbol],
208*01826a49SYabin Cui                 FSE_getMaxNbBits(symbolTT, symbol),
209*01826a49SYabin Cui                 (double)FSE_bitCost(symbolTT, tableLog, symbol, 8) / 256);
210*01826a49SYabin Cui     }   }
211*01826a49SYabin Cui #endif
212*01826a49SYabin Cui 
213*01826a49SYabin Cui     return 0;
214*01826a49SYabin Cui }
215*01826a49SYabin Cui 
216*01826a49SYabin Cui 
217*01826a49SYabin Cui 
218*01826a49SYabin Cui #ifndef FSE_COMMONDEFS_ONLY
219*01826a49SYabin Cui 
220*01826a49SYabin Cui /*-**************************************************************
221*01826a49SYabin Cui *  FSE NCount encoding
222*01826a49SYabin Cui ****************************************************************/
FSE_NCountWriteBound(unsigned maxSymbolValue,unsigned tableLog)223*01826a49SYabin Cui size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
224*01826a49SYabin Cui {
225*01826a49SYabin Cui     size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog
226*01826a49SYabin Cui                                    + 4 /* bitCount initialized at 4 */
227*01826a49SYabin Cui                                    + 2 /* first two symbols may use one additional bit each */) / 8)
228*01826a49SYabin Cui                                    + 1 /* round up to whole nb bytes */
229*01826a49SYabin Cui                                    + 2 /* additional two bytes for bitstream flush */;
230*01826a49SYabin Cui     return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND;  /* maxSymbolValue==0 ? use default */
231*01826a49SYabin Cui }
232*01826a49SYabin Cui 
233*01826a49SYabin Cui static size_t
FSE_writeNCount_generic(void * header,size_t headerBufferSize,const short * normalizedCounter,unsigned maxSymbolValue,unsigned tableLog,unsigned writeIsSafe)234*01826a49SYabin Cui FSE_writeNCount_generic (void* header, size_t headerBufferSize,
235*01826a49SYabin Cui                    const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
236*01826a49SYabin Cui                          unsigned writeIsSafe)
237*01826a49SYabin Cui {
238*01826a49SYabin Cui     BYTE* const ostart = (BYTE*) header;
239*01826a49SYabin Cui     BYTE* out = ostart;
240*01826a49SYabin Cui     BYTE* const oend = ostart + headerBufferSize;
241*01826a49SYabin Cui     int nbBits;
242*01826a49SYabin Cui     const int tableSize = 1 << tableLog;
243*01826a49SYabin Cui     int remaining;
244*01826a49SYabin Cui     int threshold;
245*01826a49SYabin Cui     U32 bitStream = 0;
246*01826a49SYabin Cui     int bitCount = 0;
247*01826a49SYabin Cui     unsigned symbol = 0;
248*01826a49SYabin Cui     unsigned const alphabetSize = maxSymbolValue + 1;
249*01826a49SYabin Cui     int previousIs0 = 0;
250*01826a49SYabin Cui 
251*01826a49SYabin Cui     /* Table Size */
252*01826a49SYabin Cui     bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
253*01826a49SYabin Cui     bitCount  += 4;
254*01826a49SYabin Cui 
255*01826a49SYabin Cui     /* Init */
256*01826a49SYabin Cui     remaining = tableSize+1;   /* +1 for extra accuracy */
257*01826a49SYabin Cui     threshold = tableSize;
258*01826a49SYabin Cui     nbBits = (int)tableLog+1;
259*01826a49SYabin Cui 
260*01826a49SYabin Cui     while ((symbol < alphabetSize) && (remaining>1)) {  /* stops at 1 */
261*01826a49SYabin Cui         if (previousIs0) {
262*01826a49SYabin Cui             unsigned start = symbol;
263*01826a49SYabin Cui             while ((symbol < alphabetSize) && !normalizedCounter[symbol]) symbol++;
264*01826a49SYabin Cui             if (symbol == alphabetSize) break;   /* incorrect distribution */
265*01826a49SYabin Cui             while (symbol >= start+24) {
266*01826a49SYabin Cui                 start+=24;
267*01826a49SYabin Cui                 bitStream += 0xFFFFU << bitCount;
268*01826a49SYabin Cui                 if ((!writeIsSafe) && (out > oend-2))
269*01826a49SYabin Cui                     return ERROR(dstSize_tooSmall);   /* Buffer overflow */
270*01826a49SYabin Cui                 out[0] = (BYTE) bitStream;
271*01826a49SYabin Cui                 out[1] = (BYTE)(bitStream>>8);
272*01826a49SYabin Cui                 out+=2;
273*01826a49SYabin Cui                 bitStream>>=16;
274*01826a49SYabin Cui             }
275*01826a49SYabin Cui             while (symbol >= start+3) {
276*01826a49SYabin Cui                 start+=3;
277*01826a49SYabin Cui                 bitStream += 3U << bitCount;
278*01826a49SYabin Cui                 bitCount += 2;
279*01826a49SYabin Cui             }
280*01826a49SYabin Cui             bitStream += (symbol-start) << bitCount;
281*01826a49SYabin Cui             bitCount += 2;
282*01826a49SYabin Cui             if (bitCount>16) {
283*01826a49SYabin Cui                 if ((!writeIsSafe) && (out > oend - 2))
284*01826a49SYabin Cui                     return ERROR(dstSize_tooSmall);   /* Buffer overflow */
285*01826a49SYabin Cui                 out[0] = (BYTE)bitStream;
286*01826a49SYabin Cui                 out[1] = (BYTE)(bitStream>>8);
287*01826a49SYabin Cui                 out += 2;
288*01826a49SYabin Cui                 bitStream >>= 16;
289*01826a49SYabin Cui                 bitCount -= 16;
290*01826a49SYabin Cui         }   }
291*01826a49SYabin Cui         {   int count = normalizedCounter[symbol++];
292*01826a49SYabin Cui             int const max = (2*threshold-1) - remaining;
293*01826a49SYabin Cui             remaining -= count < 0 ? -count : count;
294*01826a49SYabin Cui             count++;   /* +1 for extra accuracy */
295*01826a49SYabin Cui             if (count>=threshold)
296*01826a49SYabin Cui                 count += max;   /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
297*01826a49SYabin Cui             bitStream += (U32)count << bitCount;
298*01826a49SYabin Cui             bitCount  += nbBits;
299*01826a49SYabin Cui             bitCount  -= (count<max);
300*01826a49SYabin Cui             previousIs0  = (count==1);
301*01826a49SYabin Cui             if (remaining<1) return ERROR(GENERIC);
302*01826a49SYabin Cui             while (remaining<threshold) { nbBits--; threshold>>=1; }
303*01826a49SYabin Cui         }
304*01826a49SYabin Cui         if (bitCount>16) {
305*01826a49SYabin Cui             if ((!writeIsSafe) && (out > oend - 2))
306*01826a49SYabin Cui                 return ERROR(dstSize_tooSmall);   /* Buffer overflow */
307*01826a49SYabin Cui             out[0] = (BYTE)bitStream;
308*01826a49SYabin Cui             out[1] = (BYTE)(bitStream>>8);
309*01826a49SYabin Cui             out += 2;
310*01826a49SYabin Cui             bitStream >>= 16;
311*01826a49SYabin Cui             bitCount -= 16;
312*01826a49SYabin Cui     }   }
313*01826a49SYabin Cui 
314*01826a49SYabin Cui     if (remaining != 1)
315*01826a49SYabin Cui         return ERROR(GENERIC);  /* incorrect normalized distribution */
316*01826a49SYabin Cui     assert(symbol <= alphabetSize);
317*01826a49SYabin Cui 
318*01826a49SYabin Cui     /* flush remaining bitStream */
319*01826a49SYabin Cui     if ((!writeIsSafe) && (out > oend - 2))
320*01826a49SYabin Cui         return ERROR(dstSize_tooSmall);   /* Buffer overflow */
321*01826a49SYabin Cui     out[0] = (BYTE)bitStream;
322*01826a49SYabin Cui     out[1] = (BYTE)(bitStream>>8);
323*01826a49SYabin Cui     out+= (bitCount+7) /8;
324*01826a49SYabin Cui 
325*01826a49SYabin Cui     assert(out >= ostart);
326*01826a49SYabin Cui     return (size_t)(out-ostart);
327*01826a49SYabin Cui }
328*01826a49SYabin Cui 
329*01826a49SYabin Cui 
FSE_writeNCount(void * buffer,size_t bufferSize,const short * normalizedCounter,unsigned maxSymbolValue,unsigned tableLog)330*01826a49SYabin Cui size_t FSE_writeNCount (void* buffer, size_t bufferSize,
331*01826a49SYabin Cui                   const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
332*01826a49SYabin Cui {
333*01826a49SYabin Cui     if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);   /* Unsupported */
334*01826a49SYabin Cui     if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC);   /* Unsupported */
335*01826a49SYabin Cui 
336*01826a49SYabin Cui     if (bufferSize < FSE_NCountWriteBound(maxSymbolValue, tableLog))
337*01826a49SYabin Cui         return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
338*01826a49SYabin Cui 
339*01826a49SYabin Cui     return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1 /* write in buffer is safe */);
340*01826a49SYabin Cui }
341*01826a49SYabin Cui 
342*01826a49SYabin Cui 
343*01826a49SYabin Cui /*-**************************************************************
344*01826a49SYabin Cui *  FSE Compression Code
345*01826a49SYabin Cui ****************************************************************/
346*01826a49SYabin Cui 
347*01826a49SYabin Cui /* provides the minimum logSize to safely represent a distribution */
FSE_minTableLog(size_t srcSize,unsigned maxSymbolValue)348*01826a49SYabin Cui static unsigned FSE_minTableLog(size_t srcSize, unsigned maxSymbolValue)
349*01826a49SYabin Cui {
350*01826a49SYabin Cui     U32 minBitsSrc = ZSTD_highbit32((U32)(srcSize)) + 1;
351*01826a49SYabin Cui     U32 minBitsSymbols = ZSTD_highbit32(maxSymbolValue) + 2;
352*01826a49SYabin Cui     U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
353*01826a49SYabin Cui     assert(srcSize > 1); /* Not supported, RLE should be used instead */
354*01826a49SYabin Cui     return minBits;
355*01826a49SYabin Cui }
356*01826a49SYabin Cui 
FSE_optimalTableLog_internal(unsigned maxTableLog,size_t srcSize,unsigned maxSymbolValue,unsigned minus)357*01826a49SYabin Cui unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
358*01826a49SYabin Cui {
359*01826a49SYabin Cui     U32 maxBitsSrc = ZSTD_highbit32((U32)(srcSize - 1)) - minus;
360*01826a49SYabin Cui     U32 tableLog = maxTableLog;
361*01826a49SYabin Cui     U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
362*01826a49SYabin Cui     assert(srcSize > 1); /* Not supported, RLE should be used instead */
363*01826a49SYabin Cui     if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
364*01826a49SYabin Cui     if (maxBitsSrc < tableLog) tableLog = maxBitsSrc;   /* Accuracy can be reduced */
365*01826a49SYabin Cui     if (minBits > tableLog) tableLog = minBits;   /* Need a minimum to safely represent all symbol values */
366*01826a49SYabin Cui     if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
367*01826a49SYabin Cui     if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
368*01826a49SYabin Cui     return tableLog;
369*01826a49SYabin Cui }
370*01826a49SYabin Cui 
FSE_optimalTableLog(unsigned maxTableLog,size_t srcSize,unsigned maxSymbolValue)371*01826a49SYabin Cui unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
372*01826a49SYabin Cui {
373*01826a49SYabin Cui     return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 2);
374*01826a49SYabin Cui }
375*01826a49SYabin Cui 
376*01826a49SYabin Cui /* Secondary normalization method.
377*01826a49SYabin Cui    To be used when primary method fails. */
378*01826a49SYabin Cui 
FSE_normalizeM2(short * norm,U32 tableLog,const unsigned * count,size_t total,U32 maxSymbolValue,short lowProbCount)379*01826a49SYabin Cui static size_t FSE_normalizeM2(short* norm, U32 tableLog, const unsigned* count, size_t total, U32 maxSymbolValue, short lowProbCount)
380*01826a49SYabin Cui {
381*01826a49SYabin Cui     short const NOT_YET_ASSIGNED = -2;
382*01826a49SYabin Cui     U32 s;
383*01826a49SYabin Cui     U32 distributed = 0;
384*01826a49SYabin Cui     U32 ToDistribute;
385*01826a49SYabin Cui 
386*01826a49SYabin Cui     /* Init */
387*01826a49SYabin Cui     U32 const lowThreshold = (U32)(total >> tableLog);
388*01826a49SYabin Cui     U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
389*01826a49SYabin Cui 
390*01826a49SYabin Cui     for (s=0; s<=maxSymbolValue; s++) {
391*01826a49SYabin Cui         if (count[s] == 0) {
392*01826a49SYabin Cui             norm[s]=0;
393*01826a49SYabin Cui             continue;
394*01826a49SYabin Cui         }
395*01826a49SYabin Cui         if (count[s] <= lowThreshold) {
396*01826a49SYabin Cui             norm[s] = lowProbCount;
397*01826a49SYabin Cui             distributed++;
398*01826a49SYabin Cui             total -= count[s];
399*01826a49SYabin Cui             continue;
400*01826a49SYabin Cui         }
401*01826a49SYabin Cui         if (count[s] <= lowOne) {
402*01826a49SYabin Cui             norm[s] = 1;
403*01826a49SYabin Cui             distributed++;
404*01826a49SYabin Cui             total -= count[s];
405*01826a49SYabin Cui             continue;
406*01826a49SYabin Cui         }
407*01826a49SYabin Cui 
408*01826a49SYabin Cui         norm[s]=NOT_YET_ASSIGNED;
409*01826a49SYabin Cui     }
410*01826a49SYabin Cui     ToDistribute = (1 << tableLog) - distributed;
411*01826a49SYabin Cui 
412*01826a49SYabin Cui     if (ToDistribute == 0)
413*01826a49SYabin Cui         return 0;
414*01826a49SYabin Cui 
415*01826a49SYabin Cui     if ((total / ToDistribute) > lowOne) {
416*01826a49SYabin Cui         /* risk of rounding to zero */
417*01826a49SYabin Cui         lowOne = (U32)((total * 3) / (ToDistribute * 2));
418*01826a49SYabin Cui         for (s=0; s<=maxSymbolValue; s++) {
419*01826a49SYabin Cui             if ((norm[s] == NOT_YET_ASSIGNED) && (count[s] <= lowOne)) {
420*01826a49SYabin Cui                 norm[s] = 1;
421*01826a49SYabin Cui                 distributed++;
422*01826a49SYabin Cui                 total -= count[s];
423*01826a49SYabin Cui                 continue;
424*01826a49SYabin Cui         }   }
425*01826a49SYabin Cui         ToDistribute = (1 << tableLog) - distributed;
426*01826a49SYabin Cui     }
427*01826a49SYabin Cui 
428*01826a49SYabin Cui     if (distributed == maxSymbolValue+1) {
429*01826a49SYabin Cui         /* all values are pretty poor;
430*01826a49SYabin Cui            probably incompressible data (should have already been detected);
431*01826a49SYabin Cui            find max, then give all remaining points to max */
432*01826a49SYabin Cui         U32 maxV = 0, maxC = 0;
433*01826a49SYabin Cui         for (s=0; s<=maxSymbolValue; s++)
434*01826a49SYabin Cui             if (count[s] > maxC) { maxV=s; maxC=count[s]; }
435*01826a49SYabin Cui         norm[maxV] += (short)ToDistribute;
436*01826a49SYabin Cui         return 0;
437*01826a49SYabin Cui     }
438*01826a49SYabin Cui 
439*01826a49SYabin Cui     if (total == 0) {
440*01826a49SYabin Cui         /* all of the symbols were low enough for the lowOne or lowThreshold */
441*01826a49SYabin Cui         for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
442*01826a49SYabin Cui             if (norm[s] > 0) { ToDistribute--; norm[s]++; }
443*01826a49SYabin Cui         return 0;
444*01826a49SYabin Cui     }
445*01826a49SYabin Cui 
446*01826a49SYabin Cui     {   U64 const vStepLog = 62 - tableLog;
447*01826a49SYabin Cui         U64 const mid = (1ULL << (vStepLog-1)) - 1;
448*01826a49SYabin Cui         U64 const rStep = ZSTD_div64((((U64)1<<vStepLog) * ToDistribute) + mid, (U32)total);   /* scale on remaining */
449*01826a49SYabin Cui         U64 tmpTotal = mid;
450*01826a49SYabin Cui         for (s=0; s<=maxSymbolValue; s++) {
451*01826a49SYabin Cui             if (norm[s]==NOT_YET_ASSIGNED) {
452*01826a49SYabin Cui                 U64 const end = tmpTotal + (count[s] * rStep);
453*01826a49SYabin Cui                 U32 const sStart = (U32)(tmpTotal >> vStepLog);
454*01826a49SYabin Cui                 U32 const sEnd = (U32)(end >> vStepLog);
455*01826a49SYabin Cui                 U32 const weight = sEnd - sStart;
456*01826a49SYabin Cui                 if (weight < 1)
457*01826a49SYabin Cui                     return ERROR(GENERIC);
458*01826a49SYabin Cui                 norm[s] = (short)weight;
459*01826a49SYabin Cui                 tmpTotal = end;
460*01826a49SYabin Cui     }   }   }
461*01826a49SYabin Cui 
462*01826a49SYabin Cui     return 0;
463*01826a49SYabin Cui }
464*01826a49SYabin Cui 
FSE_normalizeCount(short * normalizedCounter,unsigned tableLog,const unsigned * count,size_t total,unsigned maxSymbolValue,unsigned useLowProbCount)465*01826a49SYabin Cui size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
466*01826a49SYabin Cui                            const unsigned* count, size_t total,
467*01826a49SYabin Cui                            unsigned maxSymbolValue, unsigned useLowProbCount)
468*01826a49SYabin Cui {
469*01826a49SYabin Cui     /* Sanity checks */
470*01826a49SYabin Cui     if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
471*01826a49SYabin Cui     if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC);   /* Unsupported size */
472*01826a49SYabin Cui     if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);   /* Unsupported size */
473*01826a49SYabin Cui     if (tableLog < FSE_minTableLog(total, maxSymbolValue)) return ERROR(GENERIC);   /* Too small tableLog, compression potentially impossible */
474*01826a49SYabin Cui 
475*01826a49SYabin Cui     {   static U32 const rtbTable[] = {     0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
476*01826a49SYabin Cui         short const lowProbCount = useLowProbCount ? -1 : 1;
477*01826a49SYabin Cui         U64 const scale = 62 - tableLog;
478*01826a49SYabin Cui         U64 const step = ZSTD_div64((U64)1<<62, (U32)total);   /* <== here, one division ! */
479*01826a49SYabin Cui         U64 const vStep = 1ULL<<(scale-20);
480*01826a49SYabin Cui         int stillToDistribute = 1<<tableLog;
481*01826a49SYabin Cui         unsigned s;
482*01826a49SYabin Cui         unsigned largest=0;
483*01826a49SYabin Cui         short largestP=0;
484*01826a49SYabin Cui         U32 lowThreshold = (U32)(total >> tableLog);
485*01826a49SYabin Cui 
486*01826a49SYabin Cui         for (s=0; s<=maxSymbolValue; s++) {
487*01826a49SYabin Cui             if (count[s] == total) return 0;   /* rle special case */
488*01826a49SYabin Cui             if (count[s] == 0) { normalizedCounter[s]=0; continue; }
489*01826a49SYabin Cui             if (count[s] <= lowThreshold) {
490*01826a49SYabin Cui                 normalizedCounter[s] = lowProbCount;
491*01826a49SYabin Cui                 stillToDistribute--;
492*01826a49SYabin Cui             } else {
493*01826a49SYabin Cui                 short proba = (short)((count[s]*step) >> scale);
494*01826a49SYabin Cui                 if (proba<8) {
495*01826a49SYabin Cui                     U64 restToBeat = vStep * rtbTable[proba];
496*01826a49SYabin Cui                     proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
497*01826a49SYabin Cui                 }
498*01826a49SYabin Cui                 if (proba > largestP) { largestP=proba; largest=s; }
499*01826a49SYabin Cui                 normalizedCounter[s] = proba;
500*01826a49SYabin Cui                 stillToDistribute -= proba;
501*01826a49SYabin Cui         }   }
502*01826a49SYabin Cui         if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
503*01826a49SYabin Cui             /* corner case, need another normalization method */
504*01826a49SYabin Cui             size_t const errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue, lowProbCount);
505*01826a49SYabin Cui             if (FSE_isError(errorCode)) return errorCode;
506*01826a49SYabin Cui         }
507*01826a49SYabin Cui         else normalizedCounter[largest] += (short)stillToDistribute;
508*01826a49SYabin Cui     }
509*01826a49SYabin Cui 
510*01826a49SYabin Cui #if 0
511*01826a49SYabin Cui     {   /* Print Table (debug) */
512*01826a49SYabin Cui         U32 s;
513*01826a49SYabin Cui         U32 nTotal = 0;
514*01826a49SYabin Cui         for (s=0; s<=maxSymbolValue; s++)
515*01826a49SYabin Cui             RAWLOG(2, "%3i: %4i \n", s, normalizedCounter[s]);
516*01826a49SYabin Cui         for (s=0; s<=maxSymbolValue; s++)
517*01826a49SYabin Cui             nTotal += abs(normalizedCounter[s]);
518*01826a49SYabin Cui         if (nTotal != (1U<<tableLog))
519*01826a49SYabin Cui             RAWLOG(2, "Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
520*01826a49SYabin Cui         getchar();
521*01826a49SYabin Cui     }
522*01826a49SYabin Cui #endif
523*01826a49SYabin Cui 
524*01826a49SYabin Cui     return tableLog;
525*01826a49SYabin Cui }
526*01826a49SYabin Cui 
527*01826a49SYabin Cui /* fake FSE_CTable, for rle input (always same symbol) */
FSE_buildCTable_rle(FSE_CTable * ct,BYTE symbolValue)528*01826a49SYabin Cui size_t FSE_buildCTable_rle (FSE_CTable* ct, BYTE symbolValue)
529*01826a49SYabin Cui {
530*01826a49SYabin Cui     void* ptr = ct;
531*01826a49SYabin Cui     U16* tableU16 = ( (U16*) ptr) + 2;
532*01826a49SYabin Cui     void* FSCTptr = (U32*)ptr + 2;
533*01826a49SYabin Cui     FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
534*01826a49SYabin Cui 
535*01826a49SYabin Cui     /* header */
536*01826a49SYabin Cui     tableU16[-2] = (U16) 0;
537*01826a49SYabin Cui     tableU16[-1] = (U16) symbolValue;
538*01826a49SYabin Cui 
539*01826a49SYabin Cui     /* Build table */
540*01826a49SYabin Cui     tableU16[0] = 0;
541*01826a49SYabin Cui     tableU16[1] = 0;   /* just in case */
542*01826a49SYabin Cui 
543*01826a49SYabin Cui     /* Build Symbol Transformation Table */
544*01826a49SYabin Cui     symbolTT[symbolValue].deltaNbBits = 0;
545*01826a49SYabin Cui     symbolTT[symbolValue].deltaFindState = 0;
546*01826a49SYabin Cui 
547*01826a49SYabin Cui     return 0;
548*01826a49SYabin Cui }
549*01826a49SYabin Cui 
550*01826a49SYabin Cui 
FSE_compress_usingCTable_generic(void * dst,size_t dstSize,const void * src,size_t srcSize,const FSE_CTable * ct,const unsigned fast)551*01826a49SYabin Cui static size_t FSE_compress_usingCTable_generic (void* dst, size_t dstSize,
552*01826a49SYabin Cui                            const void* src, size_t srcSize,
553*01826a49SYabin Cui                            const FSE_CTable* ct, const unsigned fast)
554*01826a49SYabin Cui {
555*01826a49SYabin Cui     const BYTE* const istart = (const BYTE*) src;
556*01826a49SYabin Cui     const BYTE* const iend = istart + srcSize;
557*01826a49SYabin Cui     const BYTE* ip=iend;
558*01826a49SYabin Cui 
559*01826a49SYabin Cui     BIT_CStream_t bitC;
560*01826a49SYabin Cui     FSE_CState_t CState1, CState2;
561*01826a49SYabin Cui 
562*01826a49SYabin Cui     /* init */
563*01826a49SYabin Cui     if (srcSize <= 2) return 0;
564*01826a49SYabin Cui     { size_t const initError = BIT_initCStream(&bitC, dst, dstSize);
565*01826a49SYabin Cui       if (FSE_isError(initError)) return 0; /* not enough space available to write a bitstream */ }
566*01826a49SYabin Cui 
567*01826a49SYabin Cui #define FSE_FLUSHBITS(s)  (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
568*01826a49SYabin Cui 
569*01826a49SYabin Cui     if (srcSize & 1) {
570*01826a49SYabin Cui         FSE_initCState2(&CState1, ct, *--ip);
571*01826a49SYabin Cui         FSE_initCState2(&CState2, ct, *--ip);
572*01826a49SYabin Cui         FSE_encodeSymbol(&bitC, &CState1, *--ip);
573*01826a49SYabin Cui         FSE_FLUSHBITS(&bitC);
574*01826a49SYabin Cui     } else {
575*01826a49SYabin Cui         FSE_initCState2(&CState2, ct, *--ip);
576*01826a49SYabin Cui         FSE_initCState2(&CState1, ct, *--ip);
577*01826a49SYabin Cui     }
578*01826a49SYabin Cui 
579*01826a49SYabin Cui     /* join to mod 4 */
580*01826a49SYabin Cui     srcSize -= 2;
581*01826a49SYabin Cui     if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) {  /* test bit 2 */
582*01826a49SYabin Cui         FSE_encodeSymbol(&bitC, &CState2, *--ip);
583*01826a49SYabin Cui         FSE_encodeSymbol(&bitC, &CState1, *--ip);
584*01826a49SYabin Cui         FSE_FLUSHBITS(&bitC);
585*01826a49SYabin Cui     }
586*01826a49SYabin Cui 
587*01826a49SYabin Cui     /* 2 or 4 encoding per loop */
588*01826a49SYabin Cui     while ( ip>istart ) {
589*01826a49SYabin Cui 
590*01826a49SYabin Cui         FSE_encodeSymbol(&bitC, &CState2, *--ip);
591*01826a49SYabin Cui 
592*01826a49SYabin Cui         if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 )   /* this test must be static */
593*01826a49SYabin Cui             FSE_FLUSHBITS(&bitC);
594*01826a49SYabin Cui 
595*01826a49SYabin Cui         FSE_encodeSymbol(&bitC, &CState1, *--ip);
596*01826a49SYabin Cui 
597*01826a49SYabin Cui         if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) {  /* this test must be static */
598*01826a49SYabin Cui             FSE_encodeSymbol(&bitC, &CState2, *--ip);
599*01826a49SYabin Cui             FSE_encodeSymbol(&bitC, &CState1, *--ip);
600*01826a49SYabin Cui         }
601*01826a49SYabin Cui 
602*01826a49SYabin Cui         FSE_FLUSHBITS(&bitC);
603*01826a49SYabin Cui     }
604*01826a49SYabin Cui 
605*01826a49SYabin Cui     FSE_flushCState(&bitC, &CState2);
606*01826a49SYabin Cui     FSE_flushCState(&bitC, &CState1);
607*01826a49SYabin Cui     return BIT_closeCStream(&bitC);
608*01826a49SYabin Cui }
609*01826a49SYabin Cui 
FSE_compress_usingCTable(void * dst,size_t dstSize,const void * src,size_t srcSize,const FSE_CTable * ct)610*01826a49SYabin Cui size_t FSE_compress_usingCTable (void* dst, size_t dstSize,
611*01826a49SYabin Cui                            const void* src, size_t srcSize,
612*01826a49SYabin Cui                            const FSE_CTable* ct)
613*01826a49SYabin Cui {
614*01826a49SYabin Cui     unsigned const fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
615*01826a49SYabin Cui 
616*01826a49SYabin Cui     if (fast)
617*01826a49SYabin Cui         return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
618*01826a49SYabin Cui     else
619*01826a49SYabin Cui         return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
620*01826a49SYabin Cui }
621*01826a49SYabin Cui 
622*01826a49SYabin Cui 
FSE_compressBound(size_t size)623*01826a49SYabin Cui size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); }
624*01826a49SYabin Cui 
625*01826a49SYabin Cui #endif   /* FSE_COMMONDEFS_ONLY */
626