18#include "../common/compiler.h"
19#include "../common/mem.h"
20#include "../common/debug.h"
22#include "../common/bitstream.h"
23#define FSE_STATIC_LINKING_ONLY
24#include "../common/fse.h"
25#include "../common/error_private.h"
26#define ZSTD_DEPS_NEED_MALLOC
27#define ZSTD_DEPS_NEED_MATH64
28#include "../common/zstd_deps.h"
29#include "../common/bits.h"
35#define FSE_isError ERR_isError
48#ifndef FSE_FUNCTION_EXTENSION
49# error "FSE_FUNCTION_EXTENSION must be defined"
51#ifndef FSE_FUNCTION_TYPE
52# error "FSE_FUNCTION_TYPE must be defined"
56#define FSE_CAT(X,Y) X##Y
57#define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
58#define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
69 const short* normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog,
70 void* workSpace,
size_t wkspSize)
72 U32 const tableSize = 1 << tableLog;
73 U32 const tableMask = tableSize - 1;
75 U16*
const tableU16 = ( (
U16*) ptr) + 2;
76 void*
const FSCT = ((
U32*)ptr) + 1 + (tableLog ? tableSize>>1 : 1) ;
77 FSE_symbolCompressionTransform*
const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
78 U32 const step = FSE_TABLESTEP(tableSize);
79 U32 const maxSV1 = maxSymbolValue+1;
81 U16* cumul = (
U16*)workSpace;
82 FSE_FUNCTION_TYPE*
const tableSymbol = (FSE_FUNCTION_TYPE*)(cumul + (maxSV1+1));
84 U32 highThreshold = tableSize-1;
86 assert(((
size_t)workSpace & 1) == 0);
87 if (FSE_BUILD_CTABLE_WORKSPACE_SIZE(maxSymbolValue, tableLog) > wkspSize)
return ERROR(tableLog_tooLarge);
89 tableU16[-2] = (
U16) tableLog;
90 tableU16[-1] = (
U16) maxSymbolValue;
96 #ifdef __clang_analyzer__
97 ZSTD_memset(tableSymbol, 0,
sizeof(*tableSymbol) * tableSize);
103 for (u=1; u <= maxSV1; u++) {
104 if (normalizedCounter[u-1]==-1) {
105 cumul[u] = cumul[u-1] + 1;
106 tableSymbol[highThreshold--] = (FSE_FUNCTION_TYPE)(u-1);
108 assert(normalizedCounter[u-1] >= 0);
109 cumul[u] = cumul[u-1] + (
U16)normalizedCounter[u-1];
110 assert(cumul[u] >= cumul[u-1]);
112 cumul[maxSV1] = (
U16)(tableSize+1);
116 if (highThreshold == tableSize - 1) {
120 BYTE*
const spread = tableSymbol + tableSize;
121 {
U64 const add = 0x0101010101010101ull;
125 for (s=0; s<maxSV1; ++s, sv += add) {
127 int const n = normalizedCounter[s];
129 for (i = 8; i < n; i += 8) {
140 {
size_t position = 0;
142 size_t const unroll = 2;
143 assert(tableSize % unroll == 0);
144 for (s = 0; s < (size_t)tableSize; s += unroll) {
146 for (u = 0; u < unroll; ++u) {
147 size_t const uPosition = (position + (u * step)) & tableMask;
148 tableSymbol[uPosition] = spread[s + u];
150 position = (position + (unroll * step)) & tableMask;
157 for (symbol=0; symbol<maxSV1; symbol++) {
159 int const freq = normalizedCounter[symbol];
160 for (nbOccurrences=0; nbOccurrences<freq; nbOccurrences++) {
161 tableSymbol[position] = (FSE_FUNCTION_TYPE)symbol;
162 position = (position + step) & tableMask;
163 while (position > highThreshold)
164 position = (position + step) & tableMask;
170 {
U32 u;
for (u=0; u<tableSize; u++) {
171 FSE_FUNCTION_TYPE s = tableSymbol[u];
172 tableU16[cumul[s]++] = (
U16) (tableSize+u);
176 {
unsigned total = 0;
178 for (s=0; s<=maxSymbolValue; s++) {
179 switch (normalizedCounter[s])
183 symbolTT[s].deltaNbBits = ((tableLog+1) << 16) - (1<<tableLog);
188 symbolTT[s].deltaNbBits = (tableLog << 16) - (1<<tableLog);
190 symbolTT[s].deltaFindState = (int)(total - 1);
194 assert(normalizedCounter[s] > 1);
196 U32 const minStatePlus = (
U32)normalizedCounter[s] << maxBitsOut;
197 symbolTT[s].deltaNbBits = (maxBitsOut << 16) - minStatePlus;
198 symbolTT[s].deltaFindState = (int)(total - (
unsigned)normalizedCounter[s]);
199 total += (unsigned)normalizedCounter[s];
203 DEBUGLOG(5,
"\n --- table statistics : ");
205 for (symbol=0; symbol<=maxSymbolValue; symbol++) {
206 DEBUGLOG(5,
"%3u: w=%3i, maxBits=%u, fracBits=%.2f",
207 symbol, normalizedCounter[symbol],
208 FSE_getMaxNbBits(symbolTT, symbol),
209 (
double)FSE_bitCost(symbolTT, tableLog, symbol, 8) / 256);
218#ifndef FSE_COMMONDEFS_ONLY
225 size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog
230 return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND;
234FSE_writeNCount_generic (
void* header,
size_t headerBufferSize,
235 const short* normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog,
236 unsigned writeIsSafe)
238 BYTE*
const ostart = (
BYTE*) header;
240 BYTE*
const oend = ostart + headerBufferSize;
242 const int tableSize = 1 << tableLog;
248 unsigned const alphabetSize = maxSymbolValue + 1;
252 bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
256 remaining = tableSize+1;
257 threshold = tableSize;
258 nbBits = (int)tableLog+1;
260 while ((symbol < alphabetSize) && (remaining>1)) {
262 unsigned start = symbol;
263 while ((symbol < alphabetSize) && !normalizedCounter[symbol]) symbol++;
264 if (symbol == alphabetSize)
break;
265 while (symbol >= start+24) {
267 bitStream += 0xFFFFU << bitCount;
268 if ((!writeIsSafe) && (out > oend-2))
269 return ERROR(dstSize_tooSmall);
270 out[0] = (
BYTE) bitStream;
271 out[1] = (
BYTE)(bitStream>>8);
275 while (symbol >= start+3) {
277 bitStream += 3U << bitCount;
280 bitStream += (symbol-start) << bitCount;
283 if ((!writeIsSafe) && (out > oend - 2))
284 return ERROR(dstSize_tooSmall);
285 out[0] = (
BYTE)bitStream;
286 out[1] = (
BYTE)(bitStream>>8);
291 {
int count = normalizedCounter[symbol++];
292 int const max = (2*threshold-1) - remaining;
295 if (count>=threshold)
297 bitStream += (
U32)count << bitCount;
300 previousIs0 = (
count==1);
301 if (remaining<1)
return ERROR(GENERIC);
302 while (remaining<threshold) { nbBits--; threshold>>=1; }
305 if ((!writeIsSafe) && (out > oend - 2))
306 return ERROR(dstSize_tooSmall);
307 out[0] = (
BYTE)bitStream;
308 out[1] = (
BYTE)(bitStream>>8);
315 return ERROR(GENERIC);
316 assert(symbol <= alphabetSize);
319 if ((!writeIsSafe) && (out > oend - 2))
320 return ERROR(dstSize_tooSmall);
321 out[0] = (
BYTE)bitStream;
322 out[1] = (
BYTE)(bitStream>>8);
323 out+= (bitCount+7) /8;
326 return (
size_t)(out-ostart);
331 const short* normalizedCounter,
unsigned maxSymbolValue,
unsigned tableLog)
333 if (tableLog > FSE_MAX_TABLELOG)
return ERROR(tableLog_tooLarge);
334 if (tableLog < FSE_MIN_TABLELOG)
return ERROR(GENERIC);
337 return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
339 return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1 );
348static unsigned FSE_minTableLog(
size_t srcSize,
unsigned maxSymbolValue)
352 U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
360 U32 tableLog = maxTableLog;
361 U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
363 if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
364 if (maxBitsSrc < tableLog) tableLog = maxBitsSrc;
365 if (minBits > tableLog) tableLog = minBits;
366 if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
367 if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
379static size_t FSE_normalizeM2(
short* norm,
U32 tableLog,
const unsigned* count,
size_t total,
U32 maxSymbolValue,
short lowProbCount)
381 short const NOT_YET_ASSIGNED = -2;
387 U32 const lowThreshold = (
U32)(total >> tableLog);
388 U32 lowOne = (
U32)((total * 3) >> (tableLog + 1));
390 for (s=0; s<=maxSymbolValue; s++) {
395 if (count[s] <= lowThreshold) {
396 norm[s] = lowProbCount;
401 if (count[s] <= lowOne) {
408 norm[s]=NOT_YET_ASSIGNED;
410 ToDistribute = (1 << tableLog) - distributed;
412 if (ToDistribute == 0)
415 if ((total / ToDistribute) > lowOne) {
417 lowOne = (
U32)((total * 3) / (ToDistribute * 2));
418 for (s=0; s<=maxSymbolValue; s++) {
419 if ((norm[s] == NOT_YET_ASSIGNED) && (
count[s] <= lowOne)) {
425 ToDistribute = (1 << tableLog) - distributed;
428 if (distributed == maxSymbolValue+1) {
432 U32 maxV = 0, maxC = 0;
433 for (s=0; s<=maxSymbolValue; s++)
434 if (count[s] > maxC) { maxV=s; maxC=
count[s]; }
435 norm[maxV] += (short)ToDistribute;
441 for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
442 if (norm[s] > 0) { ToDistribute--; norm[s]++; }
446 {
U64 const vStepLog = 62 - tableLog;
447 U64 const mid = (1ULL << (vStepLog-1)) - 1;
448 U64 const rStep = ZSTD_div64((((
U64)1<<vStepLog) * ToDistribute) + mid, (
U32)total);
450 for (s=0; s<=maxSymbolValue; s++) {
451 if (norm[s]==NOT_YET_ASSIGNED) {
452 U64 const end = tmpTotal + (
count[s] * rStep);
453 U32 const sStart = (
U32)(tmpTotal >> vStepLog);
454 U32 const sEnd = (
U32)(end >> vStepLog);
457 return ERROR(GENERIC);
458 norm[s] = (short)weight;
466 const unsigned* count,
size_t total,
467 unsigned maxSymbolValue,
unsigned useLowProbCount)
470 if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
471 if (tableLog < FSE_MIN_TABLELOG)
return ERROR(GENERIC);
472 if (tableLog > FSE_MAX_TABLELOG)
return ERROR(tableLog_tooLarge);
473 if (tableLog < FSE_minTableLog(total, maxSymbolValue))
return ERROR(GENERIC);
475 {
static U32 const rtbTable[] = { 0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
476 short const lowProbCount = useLowProbCount ? -1 : 1;
477 U64 const scale = 62 - tableLog;
478 U64 const step = ZSTD_div64((
U64)1<<62, (
U32)total);
479 U64 const vStep = 1ULL<<(scale-20);
480 int stillToDistribute = 1<<tableLog;
484 U32 lowThreshold = (
U32)(total >> tableLog);
486 for (s=0; s<=maxSymbolValue; s++) {
487 if (count[s] == total)
return 0;
488 if (count[s] == 0) { normalizedCounter[s]=0;
continue; }
489 if (count[s] <= lowThreshold) {
490 normalizedCounter[s] = lowProbCount;
493 short proba = (short)((count[s]*step) >> scale);
495 U64 restToBeat = vStep * rtbTable[proba];
496 proba += (count[s]*step) - ((
U64)proba<<scale) > restToBeat;
498 if (proba > largestP) { largestP=proba; largest=s; }
499 normalizedCounter[s] = proba;
500 stillToDistribute -= proba;
502 if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
504 size_t const errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue, lowProbCount);
507 else normalizedCounter[largest] += (short)stillToDistribute;
514 for (s=0; s<=maxSymbolValue; s++)
515 RAWLOG(2,
"%3i: %4i \n", s, normalizedCounter[s]);
516 for (s=0; s<=maxSymbolValue; s++)
517 nTotal += abs(normalizedCounter[s]);
518 if (nTotal != (1U<<tableLog))
519 RAWLOG(2,
"Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
531 U16* tableU16 = ( (
U16*) ptr) + 2;
532 void* FSCTptr = (
U32*)ptr + 2;
533 FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
536 tableU16[-2] = (
U16) 0;
537 tableU16[-1] = (
U16) symbolValue;
544 symbolTT[symbolValue].deltaNbBits = 0;
545 symbolTT[symbolValue].deltaFindState = 0;
551static size_t FSE_compress_usingCTable_generic (
void* dst,
size_t dstSize,
552 const void* src,
size_t srcSize,
555 const BYTE*
const istart = (
const BYTE*) src;
556 const BYTE*
const iend = istart + srcSize;
560 FSE_CState_t CState1, CState2;
563 if (srcSize <= 2)
return 0;
567#define FSE_FLUSHBITS(s) (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
570 FSE_initCState2(&CState1, ct, *--ip);
571 FSE_initCState2(&CState2, ct, *--ip);
572 FSE_encodeSymbol(&bitC, &CState1, *--ip);
575 FSE_initCState2(&CState2, ct, *--ip);
576 FSE_initCState2(&CState1, ct, *--ip);
581 if ((
sizeof(bitC.
bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) {
582 FSE_encodeSymbol(&bitC, &CState2, *--ip);
583 FSE_encodeSymbol(&bitC, &CState1, *--ip);
588 while ( ip>istart ) {
590 FSE_encodeSymbol(&bitC, &CState2, *--ip);
592 if (
sizeof(bitC.
bitContainer)*8 < FSE_MAX_TABLELOG*2+7 )
595 FSE_encodeSymbol(&bitC, &CState1, *--ip);
597 if (
sizeof(bitC.
bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) {
598 FSE_encodeSymbol(&bitC, &CState2, *--ip);
599 FSE_encodeSymbol(&bitC, &CState1, *--ip);
605 FSE_flushCState(&bitC, &CState2);
606 FSE_flushCState(&bitC, &CState1);
611 const void* src,
size_t srcSize,
614 unsigned const fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
617 return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
619 return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
MEM_STATIC unsigned ZSTD_highbit32(U32 val)
MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t *bitC)
MEM_STATIC size_t BIT_initCStream(BIT_CStream_t *bitC, void *dstBuffer, size_t dstCapacity)
#define assert(condition)
size_t FSE_compressBound(size_t size)
size_t FSE_buildCTable_wksp(FSE_CTable *ct, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void *workSpace, size_t wkspSize)
size_t FSE_compress_usingCTable(void *dst, size_t dstSize, const void *src, size_t srcSize, const FSE_CTable *ct)
size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
size_t FSE_normalizeCount(short *normalizedCounter, unsigned tableLog, const unsigned *count, size_t total, unsigned maxSymbolValue, unsigned useLowProbCount)
size_t FSE_buildCTable_rle(FSE_CTable *ct, BYTE symbolValue)
unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
size_t FSE_writeNCount(void *buffer, size_t bufferSize, const short *normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
MEM_STATIC void MEM_write64(void *memPtr, U64 value)
constexpr dcon::demographics_key total(0)
MOD_PROV_LIST constexpr uint32_t count
#define ZSTD_memset(p, v, l)