10c16b537SWarner Losh /* ******************************************************************
237f1f268SConrad Meyer * FSE : Finite State Entropy encoder
3*5ff13fbcSAllan Jude * Copyright (c) Yann Collet, Facebook, Inc.
437f1f268SConrad Meyer *
537f1f268SConrad Meyer * You can contact the author at :
637f1f268SConrad Meyer * - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
737f1f268SConrad Meyer * - Public forum : https://groups.google.com/forum/#!forum/lz4c
837f1f268SConrad Meyer *
937f1f268SConrad Meyer * This source code is licensed under both the BSD-style license (found in the
1037f1f268SConrad Meyer * LICENSE file in the root directory of this source tree) and the GPLv2 (found
1137f1f268SConrad Meyer * in the COPYING file in the root directory of this source tree).
1237f1f268SConrad Meyer * You may select, at your option, one of the above-listed licenses.
130c16b537SWarner Losh ****************************************************************** */
140c16b537SWarner Losh
150c16b537SWarner Losh /* **************************************************************
160c16b537SWarner Losh * Includes
170c16b537SWarner Losh ****************************************************************/
1837f1f268SConrad Meyer #include "../common/compiler.h"
1937f1f268SConrad Meyer #include "../common/mem.h" /* U32, U16, etc. */
2037f1f268SConrad Meyer #include "../common/debug.h" /* assert, DEBUGLOG */
210f743729SConrad Meyer #include "hist.h" /* HIST_count_wksp */
2237f1f268SConrad Meyer #include "../common/bitstream.h"
230c16b537SWarner Losh #define FSE_STATIC_LINKING_ONLY
2437f1f268SConrad Meyer #include "../common/fse.h"
2537f1f268SConrad Meyer #include "../common/error_private.h"
26f7cd7fe5SConrad Meyer #define ZSTD_DEPS_NEED_MALLOC
27f7cd7fe5SConrad Meyer #define ZSTD_DEPS_NEED_MATH64
28f7cd7fe5SConrad Meyer #include "../common/zstd_deps.h" /* ZSTD_malloc, ZSTD_free, ZSTD_memcpy, ZSTD_memset */
290c16b537SWarner Losh
300c16b537SWarner Losh
310c16b537SWarner Losh /* **************************************************************
320c16b537SWarner Losh * Error Management
330c16b537SWarner Losh ****************************************************************/
340c16b537SWarner Losh #define FSE_isError ERR_isError
350c16b537SWarner Losh
360c16b537SWarner Losh
370c16b537SWarner Losh /* **************************************************************
380c16b537SWarner Losh * Templates
390c16b537SWarner Losh ****************************************************************/
400c16b537SWarner Losh /*
410c16b537SWarner Losh designed to be included
420c16b537SWarner Losh for type-specific functions (template emulation in C)
430c16b537SWarner Losh Objective is to write these functions only once, for improved maintenance
440c16b537SWarner Losh */
450c16b537SWarner Losh
460c16b537SWarner Losh /* safety checks */
470c16b537SWarner Losh #ifndef FSE_FUNCTION_EXTENSION
480c16b537SWarner Losh # error "FSE_FUNCTION_EXTENSION must be defined"
490c16b537SWarner Losh #endif
500c16b537SWarner Losh #ifndef FSE_FUNCTION_TYPE
510c16b537SWarner Losh # error "FSE_FUNCTION_TYPE must be defined"
520c16b537SWarner Losh #endif
530c16b537SWarner Losh
540c16b537SWarner Losh /* Function names */
550c16b537SWarner Losh #define FSE_CAT(X,Y) X##Y
560c16b537SWarner Losh #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
570c16b537SWarner Losh #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
580c16b537SWarner Losh
590c16b537SWarner Losh
600c16b537SWarner Losh /* Function templates */
610c16b537SWarner Losh
620c16b537SWarner Losh /* FSE_buildCTable_wksp() :
630c16b537SWarner Losh * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
640c16b537SWarner Losh * wkspSize should be sized to handle worst case situation, which is `1<<max_tableLog * sizeof(FSE_FUNCTION_TYPE)`
650c16b537SWarner Losh * workSpace must also be properly aligned with FSE_FUNCTION_TYPE requirements
660c16b537SWarner Losh */
FSE_buildCTable_wksp(FSE_CTable * ct,const short * normalizedCounter,unsigned maxSymbolValue,unsigned tableLog,void * workSpace,size_t wkspSize)670f743729SConrad Meyer size_t FSE_buildCTable_wksp(FSE_CTable* ct,
680f743729SConrad Meyer const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
690f743729SConrad Meyer void* workSpace, size_t wkspSize)
700c16b537SWarner Losh {
710c16b537SWarner Losh U32 const tableSize = 1 << tableLog;
720c16b537SWarner Losh U32 const tableMask = tableSize - 1;
730c16b537SWarner Losh void* const ptr = ct;
740c16b537SWarner Losh U16* const tableU16 = ( (U16*) ptr) + 2;
750c16b537SWarner Losh void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableLog ? tableSize>>1 : 1) ;
760c16b537SWarner Losh FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
770c16b537SWarner Losh U32 const step = FSE_TABLESTEP(tableSize);
78*5ff13fbcSAllan Jude U32 const maxSV1 = maxSymbolValue+1;
790c16b537SWarner Losh
80*5ff13fbcSAllan Jude U16* cumul = (U16*)workSpace; /* size = maxSV1 */
81*5ff13fbcSAllan Jude FSE_FUNCTION_TYPE* const tableSymbol = (FSE_FUNCTION_TYPE*)(cumul + (maxSV1+1)); /* size = tableSize */
82f7cd7fe5SConrad Meyer
830c16b537SWarner Losh U32 highThreshold = tableSize-1;
840c16b537SWarner Losh
85*5ff13fbcSAllan Jude assert(((size_t)workSpace & 1) == 0); /* Must be 2 bytes-aligned */
86f7cd7fe5SConrad Meyer if (FSE_BUILD_CTABLE_WORKSPACE_SIZE(maxSymbolValue, tableLog) > wkspSize) return ERROR(tableLog_tooLarge);
870c16b537SWarner Losh /* CTable header */
880c16b537SWarner Losh tableU16[-2] = (U16) tableLog;
890c16b537SWarner Losh tableU16[-1] = (U16) maxSymbolValue;
900f743729SConrad Meyer assert(tableLog < 16); /* required for threshold strategy to work */
910c16b537SWarner Losh
920c16b537SWarner Losh /* For explanations on how to distribute symbol values over the table :
930c16b537SWarner Losh * http://fastcompression.blogspot.fr/2014/02/fse-distributing-symbol-values.html */
940c16b537SWarner Losh
950f743729SConrad Meyer #ifdef __clang_analyzer__
96f7cd7fe5SConrad Meyer ZSTD_memset(tableSymbol, 0, sizeof(*tableSymbol) * tableSize); /* useless initialization, just to keep scan-build happy */
970f743729SConrad Meyer #endif
980f743729SConrad Meyer
990c16b537SWarner Losh /* symbol start positions */
1000c16b537SWarner Losh { U32 u;
1010c16b537SWarner Losh cumul[0] = 0;
102*5ff13fbcSAllan Jude for (u=1; u <= maxSV1; u++) {
1030c16b537SWarner Losh if (normalizedCounter[u-1]==-1) { /* Low proba symbol */
1040c16b537SWarner Losh cumul[u] = cumul[u-1] + 1;
1050c16b537SWarner Losh tableSymbol[highThreshold--] = (FSE_FUNCTION_TYPE)(u-1);
1060c16b537SWarner Losh } else {
107*5ff13fbcSAllan Jude assert(normalizedCounter[u-1] >= 0);
108*5ff13fbcSAllan Jude cumul[u] = cumul[u-1] + (U16)normalizedCounter[u-1];
109*5ff13fbcSAllan Jude assert(cumul[u] >= cumul[u-1]); /* no overflow */
1100c16b537SWarner Losh } }
111*5ff13fbcSAllan Jude cumul[maxSV1] = (U16)(tableSize+1);
1120c16b537SWarner Losh }
1130c16b537SWarner Losh
1140c16b537SWarner Losh /* Spread symbols */
115*5ff13fbcSAllan Jude if (highThreshold == tableSize - 1) {
116*5ff13fbcSAllan Jude /* Case for no low prob count symbols. Lay down 8 bytes at a time
117*5ff13fbcSAllan Jude * to reduce branch misses since we are operating on a small block
118*5ff13fbcSAllan Jude */
119*5ff13fbcSAllan Jude BYTE* const spread = tableSymbol + tableSize; /* size = tableSize + 8 (may write beyond tableSize) */
120*5ff13fbcSAllan Jude { U64 const add = 0x0101010101010101ull;
121*5ff13fbcSAllan Jude size_t pos = 0;
122*5ff13fbcSAllan Jude U64 sv = 0;
123*5ff13fbcSAllan Jude U32 s;
124*5ff13fbcSAllan Jude for (s=0; s<maxSV1; ++s, sv += add) {
125*5ff13fbcSAllan Jude int i;
126*5ff13fbcSAllan Jude int const n = normalizedCounter[s];
127*5ff13fbcSAllan Jude MEM_write64(spread + pos, sv);
128*5ff13fbcSAllan Jude for (i = 8; i < n; i += 8) {
129*5ff13fbcSAllan Jude MEM_write64(spread + pos + i, sv);
130*5ff13fbcSAllan Jude }
131*5ff13fbcSAllan Jude assert(n>=0);
132*5ff13fbcSAllan Jude pos += (size_t)n;
133*5ff13fbcSAllan Jude }
134*5ff13fbcSAllan Jude }
135*5ff13fbcSAllan Jude /* Spread symbols across the table. Lack of lowprob symbols means that
136*5ff13fbcSAllan Jude * we don't need variable sized inner loop, so we can unroll the loop and
137*5ff13fbcSAllan Jude * reduce branch misses.
138*5ff13fbcSAllan Jude */
139*5ff13fbcSAllan Jude { size_t position = 0;
140*5ff13fbcSAllan Jude size_t s;
141*5ff13fbcSAllan Jude size_t const unroll = 2; /* Experimentally determined optimal unroll */
142*5ff13fbcSAllan Jude assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
143*5ff13fbcSAllan Jude for (s = 0; s < (size_t)tableSize; s += unroll) {
144*5ff13fbcSAllan Jude size_t u;
145*5ff13fbcSAllan Jude for (u = 0; u < unroll; ++u) {
146*5ff13fbcSAllan Jude size_t const uPosition = (position + (u * step)) & tableMask;
147*5ff13fbcSAllan Jude tableSymbol[uPosition] = spread[s + u];
148*5ff13fbcSAllan Jude }
149*5ff13fbcSAllan Jude position = (position + (unroll * step)) & tableMask;
150*5ff13fbcSAllan Jude }
151*5ff13fbcSAllan Jude assert(position == 0); /* Must have initialized all positions */
152*5ff13fbcSAllan Jude }
153*5ff13fbcSAllan Jude } else {
154*5ff13fbcSAllan Jude U32 position = 0;
1550c16b537SWarner Losh U32 symbol;
156*5ff13fbcSAllan Jude for (symbol=0; symbol<maxSV1; symbol++) {
1572b9c00cbSConrad Meyer int nbOccurrences;
1580f743729SConrad Meyer int const freq = normalizedCounter[symbol];
1592b9c00cbSConrad Meyer for (nbOccurrences=0; nbOccurrences<freq; nbOccurrences++) {
1600c16b537SWarner Losh tableSymbol[position] = (FSE_FUNCTION_TYPE)symbol;
1610c16b537SWarner Losh position = (position + step) & tableMask;
1620f743729SConrad Meyer while (position > highThreshold)
1630f743729SConrad Meyer position = (position + step) & tableMask; /* Low proba area */
1640c16b537SWarner Losh } }
1650f743729SConrad Meyer assert(position==0); /* Must have initialized all positions */
1660c16b537SWarner Losh }
1670c16b537SWarner Losh
1680c16b537SWarner Losh /* Build table */
1690c16b537SWarner Losh { U32 u; for (u=0; u<tableSize; u++) {
1700c16b537SWarner Losh FSE_FUNCTION_TYPE s = tableSymbol[u]; /* note : static analyzer may not understand tableSymbol is properly initialized */
1710c16b537SWarner Losh tableU16[cumul[s]++] = (U16) (tableSize+u); /* TableU16 : sorted by symbol order; gives next state value */
1720c16b537SWarner Losh } }
1730c16b537SWarner Losh
1740c16b537SWarner Losh /* Build Symbol Transformation Table */
1750c16b537SWarner Losh { unsigned total = 0;
1760c16b537SWarner Losh unsigned s;
1770c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++) {
1780c16b537SWarner Losh switch (normalizedCounter[s])
1790c16b537SWarner Losh {
1800f743729SConrad Meyer case 0:
1810f743729SConrad Meyer /* filling nonetheless, for compatibility with FSE_getMaxNbBits() */
1820f743729SConrad Meyer symbolTT[s].deltaNbBits = ((tableLog+1) << 16) - (1<<tableLog);
1830f743729SConrad Meyer break;
1840c16b537SWarner Losh
1850c16b537SWarner Losh case -1:
1860c16b537SWarner Losh case 1:
1870c16b537SWarner Losh symbolTT[s].deltaNbBits = (tableLog << 16) - (1<<tableLog);
188*5ff13fbcSAllan Jude assert(total <= INT_MAX);
189*5ff13fbcSAllan Jude symbolTT[s].deltaFindState = (int)(total - 1);
1900c16b537SWarner Losh total ++;
1910c16b537SWarner Losh break;
1920c16b537SWarner Losh default :
193*5ff13fbcSAllan Jude assert(normalizedCounter[s] > 1);
194*5ff13fbcSAllan Jude { U32 const maxBitsOut = tableLog - BIT_highbit32 ((U32)normalizedCounter[s]-1);
195*5ff13fbcSAllan Jude U32 const minStatePlus = (U32)normalizedCounter[s] << maxBitsOut;
1960c16b537SWarner Losh symbolTT[s].deltaNbBits = (maxBitsOut << 16) - minStatePlus;
197*5ff13fbcSAllan Jude symbolTT[s].deltaFindState = (int)(total - (unsigned)normalizedCounter[s]);
198*5ff13fbcSAllan Jude total += (unsigned)normalizedCounter[s];
1990c16b537SWarner Losh } } } }
2000c16b537SWarner Losh
2010f743729SConrad Meyer #if 0 /* debug : symbol costs */
2020f743729SConrad Meyer DEBUGLOG(5, "\n --- table statistics : ");
2030f743729SConrad Meyer { U32 symbol;
2040f743729SConrad Meyer for (symbol=0; symbol<=maxSymbolValue; symbol++) {
2050f743729SConrad Meyer DEBUGLOG(5, "%3u: w=%3i, maxBits=%u, fracBits=%.2f",
2060f743729SConrad Meyer symbol, normalizedCounter[symbol],
2070f743729SConrad Meyer FSE_getMaxNbBits(symbolTT, symbol),
2080f743729SConrad Meyer (double)FSE_bitCost(symbolTT, tableLog, symbol, 8) / 256);
209*5ff13fbcSAllan Jude } }
2100f743729SConrad Meyer #endif
2110f743729SConrad Meyer
2120c16b537SWarner Losh return 0;
2130c16b537SWarner Losh }
2140c16b537SWarner Losh
2150c16b537SWarner Losh
2160c16b537SWarner Losh
2170c16b537SWarner Losh #ifndef FSE_COMMONDEFS_ONLY
2180c16b537SWarner Losh
2190c16b537SWarner Losh /*-**************************************************************
2200f743729SConrad Meyer * FSE NCount encoding
2210c16b537SWarner Losh ****************************************************************/
FSE_NCountWriteBound(unsigned maxSymbolValue,unsigned tableLog)2220c16b537SWarner Losh size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
2230c16b537SWarner Losh {
224*5ff13fbcSAllan Jude size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog
225*5ff13fbcSAllan Jude + 4 /* bitCount initialized at 4 */
226*5ff13fbcSAllan Jude + 2 /* first two symbols may use one additional bit each */) / 8)
227*5ff13fbcSAllan Jude + 1 /* round up to whole nb bytes */
228*5ff13fbcSAllan Jude + 2 /* additional two bytes for bitstream flush */;
2290c16b537SWarner Losh return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND; /* maxSymbolValue==0 ? use default */
2300c16b537SWarner Losh }
2310c16b537SWarner Losh
2320f743729SConrad Meyer static size_t
FSE_writeNCount_generic(void * header,size_t headerBufferSize,const short * normalizedCounter,unsigned maxSymbolValue,unsigned tableLog,unsigned writeIsSafe)2330f743729SConrad Meyer FSE_writeNCount_generic (void* header, size_t headerBufferSize,
2340c16b537SWarner Losh const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
2350c16b537SWarner Losh unsigned writeIsSafe)
2360c16b537SWarner Losh {
2370c16b537SWarner Losh BYTE* const ostart = (BYTE*) header;
2380c16b537SWarner Losh BYTE* out = ostart;
2390c16b537SWarner Losh BYTE* const oend = ostart + headerBufferSize;
2400c16b537SWarner Losh int nbBits;
2410c16b537SWarner Losh const int tableSize = 1 << tableLog;
2420c16b537SWarner Losh int remaining;
2430c16b537SWarner Losh int threshold;
2440f743729SConrad Meyer U32 bitStream = 0;
2450f743729SConrad Meyer int bitCount = 0;
2460f743729SConrad Meyer unsigned symbol = 0;
2470f743729SConrad Meyer unsigned const alphabetSize = maxSymbolValue + 1;
2480f743729SConrad Meyer int previousIs0 = 0;
2490c16b537SWarner Losh
2500c16b537SWarner Losh /* Table Size */
2510c16b537SWarner Losh bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
2520c16b537SWarner Losh bitCount += 4;
2530c16b537SWarner Losh
2540c16b537SWarner Losh /* Init */
2550c16b537SWarner Losh remaining = tableSize+1; /* +1 for extra accuracy */
2560c16b537SWarner Losh threshold = tableSize;
2570c16b537SWarner Losh nbBits = tableLog+1;
2580c16b537SWarner Losh
2590f743729SConrad Meyer while ((symbol < alphabetSize) && (remaining>1)) { /* stops at 1 */
2600f743729SConrad Meyer if (previousIs0) {
2610f743729SConrad Meyer unsigned start = symbol;
2620f743729SConrad Meyer while ((symbol < alphabetSize) && !normalizedCounter[symbol]) symbol++;
2630f743729SConrad Meyer if (symbol == alphabetSize) break; /* incorrect distribution */
2640f743729SConrad Meyer while (symbol >= start+24) {
2650c16b537SWarner Losh start+=24;
2660c16b537SWarner Losh bitStream += 0xFFFFU << bitCount;
2670f743729SConrad Meyer if ((!writeIsSafe) && (out > oend-2))
2680f743729SConrad Meyer return ERROR(dstSize_tooSmall); /* Buffer overflow */
2690c16b537SWarner Losh out[0] = (BYTE) bitStream;
2700c16b537SWarner Losh out[1] = (BYTE)(bitStream>>8);
2710c16b537SWarner Losh out+=2;
2720c16b537SWarner Losh bitStream>>=16;
2730c16b537SWarner Losh }
2740f743729SConrad Meyer while (symbol >= start+3) {
2750c16b537SWarner Losh start+=3;
2760c16b537SWarner Losh bitStream += 3 << bitCount;
2770c16b537SWarner Losh bitCount += 2;
2780c16b537SWarner Losh }
2790f743729SConrad Meyer bitStream += (symbol-start) << bitCount;
2800c16b537SWarner Losh bitCount += 2;
2810c16b537SWarner Losh if (bitCount>16) {
2820f743729SConrad Meyer if ((!writeIsSafe) && (out > oend - 2))
2830f743729SConrad Meyer return ERROR(dstSize_tooSmall); /* Buffer overflow */
2840c16b537SWarner Losh out[0] = (BYTE)bitStream;
2850c16b537SWarner Losh out[1] = (BYTE)(bitStream>>8);
2860c16b537SWarner Losh out += 2;
2870c16b537SWarner Losh bitStream >>= 16;
2880c16b537SWarner Losh bitCount -= 16;
2890c16b537SWarner Losh } }
2900f743729SConrad Meyer { int count = normalizedCounter[symbol++];
2910c16b537SWarner Losh int const max = (2*threshold-1) - remaining;
2920c16b537SWarner Losh remaining -= count < 0 ? -count : count;
2930c16b537SWarner Losh count++; /* +1 for extra accuracy */
2940f743729SConrad Meyer if (count>=threshold)
2950f743729SConrad Meyer count += max; /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
2960c16b537SWarner Losh bitStream += count << bitCount;
2970c16b537SWarner Losh bitCount += nbBits;
2980c16b537SWarner Losh bitCount -= (count<max);
2990f743729SConrad Meyer previousIs0 = (count==1);
3000c16b537SWarner Losh if (remaining<1) return ERROR(GENERIC);
30119fcbaf1SConrad Meyer while (remaining<threshold) { nbBits--; threshold>>=1; }
3020c16b537SWarner Losh }
3030c16b537SWarner Losh if (bitCount>16) {
3040f743729SConrad Meyer if ((!writeIsSafe) && (out > oend - 2))
3050f743729SConrad Meyer return ERROR(dstSize_tooSmall); /* Buffer overflow */
3060c16b537SWarner Losh out[0] = (BYTE)bitStream;
3070c16b537SWarner Losh out[1] = (BYTE)(bitStream>>8);
3080c16b537SWarner Losh out += 2;
3090c16b537SWarner Losh bitStream >>= 16;
3100c16b537SWarner Losh bitCount -= 16;
3110c16b537SWarner Losh } }
3120c16b537SWarner Losh
3130f743729SConrad Meyer if (remaining != 1)
3140f743729SConrad Meyer return ERROR(GENERIC); /* incorrect normalized distribution */
3150f743729SConrad Meyer assert(symbol <= alphabetSize);
3160f743729SConrad Meyer
3170c16b537SWarner Losh /* flush remaining bitStream */
3180f743729SConrad Meyer if ((!writeIsSafe) && (out > oend - 2))
3190f743729SConrad Meyer return ERROR(dstSize_tooSmall); /* Buffer overflow */
3200c16b537SWarner Losh out[0] = (BYTE)bitStream;
3210c16b537SWarner Losh out[1] = (BYTE)(bitStream>>8);
3220c16b537SWarner Losh out+= (bitCount+7) /8;
3230c16b537SWarner Losh
3240c16b537SWarner Losh return (out-ostart);
3250c16b537SWarner Losh }
3260c16b537SWarner Losh
3270c16b537SWarner Losh
FSE_writeNCount(void * buffer,size_t bufferSize,const short * normalizedCounter,unsigned maxSymbolValue,unsigned tableLog)3280f743729SConrad Meyer size_t FSE_writeNCount (void* buffer, size_t bufferSize,
3290f743729SConrad Meyer const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
3300c16b537SWarner Losh {
3310c16b537SWarner Losh if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported */
3320c16b537SWarner Losh if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported */
3330c16b537SWarner Losh
3340c16b537SWarner Losh if (bufferSize < FSE_NCountWriteBound(maxSymbolValue, tableLog))
3350c16b537SWarner Losh return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
3360c16b537SWarner Losh
3370f743729SConrad Meyer return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1 /* write in buffer is safe */);
3380c16b537SWarner Losh }
3390c16b537SWarner Losh
3400c16b537SWarner Losh
3410c16b537SWarner Losh /*-**************************************************************
3420c16b537SWarner Losh * FSE Compression Code
3430c16b537SWarner Losh ****************************************************************/
3440c16b537SWarner Losh
FSE_createCTable(unsigned maxSymbolValue,unsigned tableLog)3450c16b537SWarner Losh FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog)
3460c16b537SWarner Losh {
3470c16b537SWarner Losh size_t size;
3480c16b537SWarner Losh if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX;
3490c16b537SWarner Losh size = FSE_CTABLE_SIZE_U32 (tableLog, maxSymbolValue) * sizeof(U32);
350f7cd7fe5SConrad Meyer return (FSE_CTable*)ZSTD_malloc(size);
3510c16b537SWarner Losh }
3520c16b537SWarner Losh
FSE_freeCTable(FSE_CTable * ct)353f7cd7fe5SConrad Meyer void FSE_freeCTable (FSE_CTable* ct) { ZSTD_free(ct); }
3540c16b537SWarner Losh
3550c16b537SWarner Losh /* provides the minimum logSize to safely represent a distribution */
FSE_minTableLog(size_t srcSize,unsigned maxSymbolValue)3560c16b537SWarner Losh static unsigned FSE_minTableLog(size_t srcSize, unsigned maxSymbolValue)
3570c16b537SWarner Losh {
3580f743729SConrad Meyer U32 minBitsSrc = BIT_highbit32((U32)(srcSize)) + 1;
3590c16b537SWarner Losh U32 minBitsSymbols = BIT_highbit32(maxSymbolValue) + 2;
3600c16b537SWarner Losh U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
3610c16b537SWarner Losh assert(srcSize > 1); /* Not supported, RLE should be used instead */
3620c16b537SWarner Losh return minBits;
3630c16b537SWarner Losh }
3640c16b537SWarner Losh
FSE_optimalTableLog_internal(unsigned maxTableLog,size_t srcSize,unsigned maxSymbolValue,unsigned minus)3650c16b537SWarner Losh unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
3660c16b537SWarner Losh {
3670c16b537SWarner Losh U32 maxBitsSrc = BIT_highbit32((U32)(srcSize - 1)) - minus;
3680c16b537SWarner Losh U32 tableLog = maxTableLog;
3690c16b537SWarner Losh U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
3700c16b537SWarner Losh assert(srcSize > 1); /* Not supported, RLE should be used instead */
3710c16b537SWarner Losh if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
3720c16b537SWarner Losh if (maxBitsSrc < tableLog) tableLog = maxBitsSrc; /* Accuracy can be reduced */
3730c16b537SWarner Losh if (minBits > tableLog) tableLog = minBits; /* Need a minimum to safely represent all symbol values */
3740c16b537SWarner Losh if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
3750c16b537SWarner Losh if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
3760c16b537SWarner Losh return tableLog;
3770c16b537SWarner Losh }
3780c16b537SWarner Losh
FSE_optimalTableLog(unsigned maxTableLog,size_t srcSize,unsigned maxSymbolValue)3790c16b537SWarner Losh unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
3800c16b537SWarner Losh {
3810c16b537SWarner Losh return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 2);
3820c16b537SWarner Losh }
3830c16b537SWarner Losh
3840c16b537SWarner Losh /* Secondary normalization method.
3850c16b537SWarner Losh To be used when primary method fails. */
3860c16b537SWarner Losh
FSE_normalizeM2(short * norm,U32 tableLog,const unsigned * count,size_t total,U32 maxSymbolValue,short lowProbCount)387f7cd7fe5SConrad Meyer static size_t FSE_normalizeM2(short* norm, U32 tableLog, const unsigned* count, size_t total, U32 maxSymbolValue, short lowProbCount)
3880c16b537SWarner Losh {
3890c16b537SWarner Losh short const NOT_YET_ASSIGNED = -2;
3900c16b537SWarner Losh U32 s;
3910c16b537SWarner Losh U32 distributed = 0;
3920c16b537SWarner Losh U32 ToDistribute;
3930c16b537SWarner Losh
3940c16b537SWarner Losh /* Init */
3950c16b537SWarner Losh U32 const lowThreshold = (U32)(total >> tableLog);
3960c16b537SWarner Losh U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
3970c16b537SWarner Losh
3980c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++) {
3990c16b537SWarner Losh if (count[s] == 0) {
4000c16b537SWarner Losh norm[s]=0;
4010c16b537SWarner Losh continue;
4020c16b537SWarner Losh }
4030c16b537SWarner Losh if (count[s] <= lowThreshold) {
404f7cd7fe5SConrad Meyer norm[s] = lowProbCount;
4050c16b537SWarner Losh distributed++;
4060c16b537SWarner Losh total -= count[s];
4070c16b537SWarner Losh continue;
4080c16b537SWarner Losh }
4090c16b537SWarner Losh if (count[s] <= lowOne) {
4100c16b537SWarner Losh norm[s] = 1;
4110c16b537SWarner Losh distributed++;
4120c16b537SWarner Losh total -= count[s];
4130c16b537SWarner Losh continue;
4140c16b537SWarner Losh }
4150c16b537SWarner Losh
4160c16b537SWarner Losh norm[s]=NOT_YET_ASSIGNED;
4170c16b537SWarner Losh }
4180c16b537SWarner Losh ToDistribute = (1 << tableLog) - distributed;
4190c16b537SWarner Losh
4200f743729SConrad Meyer if (ToDistribute == 0)
4210f743729SConrad Meyer return 0;
4220f743729SConrad Meyer
4230c16b537SWarner Losh if ((total / ToDistribute) > lowOne) {
4240c16b537SWarner Losh /* risk of rounding to zero */
4250c16b537SWarner Losh lowOne = (U32)((total * 3) / (ToDistribute * 2));
4260c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++) {
4270c16b537SWarner Losh if ((norm[s] == NOT_YET_ASSIGNED) && (count[s] <= lowOne)) {
4280c16b537SWarner Losh norm[s] = 1;
4290c16b537SWarner Losh distributed++;
4300c16b537SWarner Losh total -= count[s];
4310c16b537SWarner Losh continue;
4320c16b537SWarner Losh } }
4330c16b537SWarner Losh ToDistribute = (1 << tableLog) - distributed;
4340c16b537SWarner Losh }
4350c16b537SWarner Losh
4360c16b537SWarner Losh if (distributed == maxSymbolValue+1) {
4370c16b537SWarner Losh /* all values are pretty poor;
4380c16b537SWarner Losh probably incompressible data (should have already been detected);
4390c16b537SWarner Losh find max, then give all remaining points to max */
4400c16b537SWarner Losh U32 maxV = 0, maxC = 0;
4410c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++)
44219fcbaf1SConrad Meyer if (count[s] > maxC) { maxV=s; maxC=count[s]; }
4430c16b537SWarner Losh norm[maxV] += (short)ToDistribute;
4440c16b537SWarner Losh return 0;
4450c16b537SWarner Losh }
4460c16b537SWarner Losh
4470c16b537SWarner Losh if (total == 0) {
4480c16b537SWarner Losh /* all of the symbols were low enough for the lowOne or lowThreshold */
4490c16b537SWarner Losh for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
45019fcbaf1SConrad Meyer if (norm[s] > 0) { ToDistribute--; norm[s]++; }
4510c16b537SWarner Losh return 0;
4520c16b537SWarner Losh }
4530c16b537SWarner Losh
4540c16b537SWarner Losh { U64 const vStepLog = 62 - tableLog;
4550c16b537SWarner Losh U64 const mid = (1ULL << (vStepLog-1)) - 1;
456f7cd7fe5SConrad Meyer U64 const rStep = ZSTD_div64((((U64)1<<vStepLog) * ToDistribute) + mid, (U32)total); /* scale on remaining */
4570c16b537SWarner Losh U64 tmpTotal = mid;
4580c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++) {
4590c16b537SWarner Losh if (norm[s]==NOT_YET_ASSIGNED) {
4600c16b537SWarner Losh U64 const end = tmpTotal + (count[s] * rStep);
4610c16b537SWarner Losh U32 const sStart = (U32)(tmpTotal >> vStepLog);
4620c16b537SWarner Losh U32 const sEnd = (U32)(end >> vStepLog);
4630c16b537SWarner Losh U32 const weight = sEnd - sStart;
4640c16b537SWarner Losh if (weight < 1)
4650c16b537SWarner Losh return ERROR(GENERIC);
4660c16b537SWarner Losh norm[s] = (short)weight;
4670c16b537SWarner Losh tmpTotal = end;
4680c16b537SWarner Losh } } }
4690c16b537SWarner Losh
4700c16b537SWarner Losh return 0;
4710c16b537SWarner Losh }
4720c16b537SWarner Losh
FSE_normalizeCount(short * normalizedCounter,unsigned tableLog,const unsigned * count,size_t total,unsigned maxSymbolValue,unsigned useLowProbCount)4730c16b537SWarner Losh size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
4740c16b537SWarner Losh const unsigned* count, size_t total,
475f7cd7fe5SConrad Meyer unsigned maxSymbolValue, unsigned useLowProbCount)
4760c16b537SWarner Losh {
4770c16b537SWarner Losh /* Sanity checks */
4780c16b537SWarner Losh if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
4790c16b537SWarner Losh if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported size */
4800c16b537SWarner Losh if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported size */
4810c16b537SWarner Losh if (tableLog < FSE_minTableLog(total, maxSymbolValue)) return ERROR(GENERIC); /* Too small tableLog, compression potentially impossible */
4820c16b537SWarner Losh
4830c16b537SWarner Losh { static U32 const rtbTable[] = { 0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
484f7cd7fe5SConrad Meyer short const lowProbCount = useLowProbCount ? -1 : 1;
4850c16b537SWarner Losh U64 const scale = 62 - tableLog;
486f7cd7fe5SConrad Meyer U64 const step = ZSTD_div64((U64)1<<62, (U32)total); /* <== here, one division ! */
4870c16b537SWarner Losh U64 const vStep = 1ULL<<(scale-20);
4880c16b537SWarner Losh int stillToDistribute = 1<<tableLog;
4890c16b537SWarner Losh unsigned s;
4900c16b537SWarner Losh unsigned largest=0;
4910c16b537SWarner Losh short largestP=0;
4920c16b537SWarner Losh U32 lowThreshold = (U32)(total >> tableLog);
4930c16b537SWarner Losh
4940c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++) {
4950c16b537SWarner Losh if (count[s] == total) return 0; /* rle special case */
4960c16b537SWarner Losh if (count[s] == 0) { normalizedCounter[s]=0; continue; }
4970c16b537SWarner Losh if (count[s] <= lowThreshold) {
498f7cd7fe5SConrad Meyer normalizedCounter[s] = lowProbCount;
4990c16b537SWarner Losh stillToDistribute--;
5000c16b537SWarner Losh } else {
5010c16b537SWarner Losh short proba = (short)((count[s]*step) >> scale);
5020c16b537SWarner Losh if (proba<8) {
5030c16b537SWarner Losh U64 restToBeat = vStep * rtbTable[proba];
5040c16b537SWarner Losh proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
5050c16b537SWarner Losh }
50619fcbaf1SConrad Meyer if (proba > largestP) { largestP=proba; largest=s; }
5070c16b537SWarner Losh normalizedCounter[s] = proba;
5080c16b537SWarner Losh stillToDistribute -= proba;
5090c16b537SWarner Losh } }
5100c16b537SWarner Losh if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
5110c16b537SWarner Losh /* corner case, need another normalization method */
512f7cd7fe5SConrad Meyer size_t const errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue, lowProbCount);
5130c16b537SWarner Losh if (FSE_isError(errorCode)) return errorCode;
5140c16b537SWarner Losh }
5150c16b537SWarner Losh else normalizedCounter[largest] += (short)stillToDistribute;
5160c16b537SWarner Losh }
5170c16b537SWarner Losh
5180c16b537SWarner Losh #if 0
5190c16b537SWarner Losh { /* Print Table (debug) */
5200c16b537SWarner Losh U32 s;
5210c16b537SWarner Losh U32 nTotal = 0;
5220c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++)
5230f743729SConrad Meyer RAWLOG(2, "%3i: %4i \n", s, normalizedCounter[s]);
5240c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++)
5250c16b537SWarner Losh nTotal += abs(normalizedCounter[s]);
5260c16b537SWarner Losh if (nTotal != (1U<<tableLog))
5270f743729SConrad Meyer RAWLOG(2, "Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
5280c16b537SWarner Losh getchar();
5290c16b537SWarner Losh }
5300c16b537SWarner Losh #endif
5310c16b537SWarner Losh
5320c16b537SWarner Losh return tableLog;
5330c16b537SWarner Losh }
5340c16b537SWarner Losh
5350c16b537SWarner Losh
5360c16b537SWarner Losh /* fake FSE_CTable, for raw (uncompressed) input */
FSE_buildCTable_raw(FSE_CTable * ct,unsigned nbBits)5370c16b537SWarner Losh size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits)
5380c16b537SWarner Losh {
5390c16b537SWarner Losh const unsigned tableSize = 1 << nbBits;
5400c16b537SWarner Losh const unsigned tableMask = tableSize - 1;
5410c16b537SWarner Losh const unsigned maxSymbolValue = tableMask;
5420c16b537SWarner Losh void* const ptr = ct;
5430c16b537SWarner Losh U16* const tableU16 = ( (U16*) ptr) + 2;
5440c16b537SWarner Losh void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableSize>>1); /* assumption : tableLog >= 1 */
5450c16b537SWarner Losh FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
5460c16b537SWarner Losh unsigned s;
5470c16b537SWarner Losh
5480c16b537SWarner Losh /* Sanity checks */
5490c16b537SWarner Losh if (nbBits < 1) return ERROR(GENERIC); /* min size */
5500c16b537SWarner Losh
5510c16b537SWarner Losh /* header */
5520c16b537SWarner Losh tableU16[-2] = (U16) nbBits;
5530c16b537SWarner Losh tableU16[-1] = (U16) maxSymbolValue;
5540c16b537SWarner Losh
5550c16b537SWarner Losh /* Build table */
5560c16b537SWarner Losh for (s=0; s<tableSize; s++)
5570c16b537SWarner Losh tableU16[s] = (U16)(tableSize + s);
5580c16b537SWarner Losh
5590c16b537SWarner Losh /* Build Symbol Transformation Table */
5600c16b537SWarner Losh { const U32 deltaNbBits = (nbBits << 16) - (1 << nbBits);
5610c16b537SWarner Losh for (s=0; s<=maxSymbolValue; s++) {
5620c16b537SWarner Losh symbolTT[s].deltaNbBits = deltaNbBits;
5630c16b537SWarner Losh symbolTT[s].deltaFindState = s-1;
5640c16b537SWarner Losh } }
5650c16b537SWarner Losh
5660c16b537SWarner Losh return 0;
5670c16b537SWarner Losh }
5680c16b537SWarner Losh
5690c16b537SWarner Losh /* fake FSE_CTable, for rle input (always same symbol) */
FSE_buildCTable_rle(FSE_CTable * ct,BYTE symbolValue)5700c16b537SWarner Losh size_t FSE_buildCTable_rle (FSE_CTable* ct, BYTE symbolValue)
5710c16b537SWarner Losh {
5720c16b537SWarner Losh void* ptr = ct;
5730c16b537SWarner Losh U16* tableU16 = ( (U16*) ptr) + 2;
5740c16b537SWarner Losh void* FSCTptr = (U32*)ptr + 2;
5750c16b537SWarner Losh FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
5760c16b537SWarner Losh
5770c16b537SWarner Losh /* header */
5780c16b537SWarner Losh tableU16[-2] = (U16) 0;
5790c16b537SWarner Losh tableU16[-1] = (U16) symbolValue;
5800c16b537SWarner Losh
5810c16b537SWarner Losh /* Build table */
5820c16b537SWarner Losh tableU16[0] = 0;
5830c16b537SWarner Losh tableU16[1] = 0; /* just in case */
5840c16b537SWarner Losh
5850c16b537SWarner Losh /* Build Symbol Transformation Table */
5860c16b537SWarner Losh symbolTT[symbolValue].deltaNbBits = 0;
5870c16b537SWarner Losh symbolTT[symbolValue].deltaFindState = 0;
5880c16b537SWarner Losh
5890c16b537SWarner Losh return 0;
5900c16b537SWarner Losh }
5910c16b537SWarner Losh
5920c16b537SWarner Losh
FSE_compress_usingCTable_generic(void * dst,size_t dstSize,const void * src,size_t srcSize,const FSE_CTable * ct,const unsigned fast)5930c16b537SWarner Losh static size_t FSE_compress_usingCTable_generic (void* dst, size_t dstSize,
5940c16b537SWarner Losh const void* src, size_t srcSize,
5950c16b537SWarner Losh const FSE_CTable* ct, const unsigned fast)
5960c16b537SWarner Losh {
5970c16b537SWarner Losh const BYTE* const istart = (const BYTE*) src;
5980c16b537SWarner Losh const BYTE* const iend = istart + srcSize;
5990c16b537SWarner Losh const BYTE* ip=iend;
6000c16b537SWarner Losh
6010c16b537SWarner Losh BIT_CStream_t bitC;
6020c16b537SWarner Losh FSE_CState_t CState1, CState2;
6030c16b537SWarner Losh
6040c16b537SWarner Losh /* init */
6050c16b537SWarner Losh if (srcSize <= 2) return 0;
6060c16b537SWarner Losh { size_t const initError = BIT_initCStream(&bitC, dst, dstSize);
6070c16b537SWarner Losh if (FSE_isError(initError)) return 0; /* not enough space available to write a bitstream */ }
6080c16b537SWarner Losh
6090c16b537SWarner Losh #define FSE_FLUSHBITS(s) (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
6100c16b537SWarner Losh
6110c16b537SWarner Losh if (srcSize & 1) {
6120c16b537SWarner Losh FSE_initCState2(&CState1, ct, *--ip);
6130c16b537SWarner Losh FSE_initCState2(&CState2, ct, *--ip);
6140c16b537SWarner Losh FSE_encodeSymbol(&bitC, &CState1, *--ip);
6150c16b537SWarner Losh FSE_FLUSHBITS(&bitC);
6160c16b537SWarner Losh } else {
6170c16b537SWarner Losh FSE_initCState2(&CState2, ct, *--ip);
6180c16b537SWarner Losh FSE_initCState2(&CState1, ct, *--ip);
6190c16b537SWarner Losh }
6200c16b537SWarner Losh
6210c16b537SWarner Losh /* join to mod 4 */
6220c16b537SWarner Losh srcSize -= 2;
6230c16b537SWarner Losh if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) { /* test bit 2 */
6240c16b537SWarner Losh FSE_encodeSymbol(&bitC, &CState2, *--ip);
6250c16b537SWarner Losh FSE_encodeSymbol(&bitC, &CState1, *--ip);
6260c16b537SWarner Losh FSE_FLUSHBITS(&bitC);
6270c16b537SWarner Losh }
6280c16b537SWarner Losh
6290c16b537SWarner Losh /* 2 or 4 encoding per loop */
6300c16b537SWarner Losh while ( ip>istart ) {
6310c16b537SWarner Losh
6320c16b537SWarner Losh FSE_encodeSymbol(&bitC, &CState2, *--ip);
6330c16b537SWarner Losh
6340c16b537SWarner Losh if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 ) /* this test must be static */
6350c16b537SWarner Losh FSE_FLUSHBITS(&bitC);
6360c16b537SWarner Losh
6370c16b537SWarner Losh FSE_encodeSymbol(&bitC, &CState1, *--ip);
6380c16b537SWarner Losh
6390c16b537SWarner Losh if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) { /* this test must be static */
6400c16b537SWarner Losh FSE_encodeSymbol(&bitC, &CState2, *--ip);
6410c16b537SWarner Losh FSE_encodeSymbol(&bitC, &CState1, *--ip);
6420c16b537SWarner Losh }
6430c16b537SWarner Losh
6440c16b537SWarner Losh FSE_FLUSHBITS(&bitC);
6450c16b537SWarner Losh }
6460c16b537SWarner Losh
6470c16b537SWarner Losh FSE_flushCState(&bitC, &CState2);
6480c16b537SWarner Losh FSE_flushCState(&bitC, &CState1);
6490c16b537SWarner Losh return BIT_closeCStream(&bitC);
6500c16b537SWarner Losh }
6510c16b537SWarner Losh
FSE_compress_usingCTable(void * dst,size_t dstSize,const void * src,size_t srcSize,const FSE_CTable * ct)6520c16b537SWarner Losh size_t FSE_compress_usingCTable (void* dst, size_t dstSize,
6530c16b537SWarner Losh const void* src, size_t srcSize,
6540c16b537SWarner Losh const FSE_CTable* ct)
6550c16b537SWarner Losh {
6560c16b537SWarner Losh unsigned const fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
6570c16b537SWarner Losh
6580c16b537SWarner Losh if (fast)
6590c16b537SWarner Losh return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
6600c16b537SWarner Losh else
6610c16b537SWarner Losh return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
6620c16b537SWarner Losh }
6630c16b537SWarner Losh
6640c16b537SWarner Losh
FSE_compressBound(size_t size)6650c16b537SWarner Losh size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); }
6660c16b537SWarner Losh
667f7cd7fe5SConrad Meyer #ifndef ZSTD_NO_UNUSED_FUNCTIONS
6680c16b537SWarner Losh /* FSE_compress_wksp() :
6690c16b537SWarner Losh * Same as FSE_compress2(), but using an externally allocated scratch buffer (`workSpace`).
6700c16b537SWarner Losh * `wkspSize` size must be `(1<<tableLog)`.
6710c16b537SWarner Losh */
FSE_compress_wksp(void * dst,size_t dstSize,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned tableLog,void * workSpace,size_t wkspSize)6720c16b537SWarner Losh size_t FSE_compress_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize)
6730c16b537SWarner Losh {
6740c16b537SWarner Losh BYTE* const ostart = (BYTE*) dst;
6750c16b537SWarner Losh BYTE* op = ostart;
6760c16b537SWarner Losh BYTE* const oend = ostart + dstSize;
6770c16b537SWarner Losh
678a0483764SConrad Meyer unsigned count[FSE_MAX_SYMBOL_VALUE+1];
6790c16b537SWarner Losh S16 norm[FSE_MAX_SYMBOL_VALUE+1];
6800c16b537SWarner Losh FSE_CTable* CTable = (FSE_CTable*)workSpace;
6810c16b537SWarner Losh size_t const CTableSize = FSE_CTABLE_SIZE_U32(tableLog, maxSymbolValue);
6820c16b537SWarner Losh void* scratchBuffer = (void*)(CTable + CTableSize);
6830c16b537SWarner Losh size_t const scratchBufferSize = wkspSize - (CTableSize * sizeof(FSE_CTable));
6840c16b537SWarner Losh
6850c16b537SWarner Losh /* init conditions */
686f7cd7fe5SConrad Meyer if (wkspSize < FSE_COMPRESS_WKSP_SIZE_U32(tableLog, maxSymbolValue)) return ERROR(tableLog_tooLarge);
6870c16b537SWarner Losh if (srcSize <= 1) return 0; /* Not compressible */
6880c16b537SWarner Losh if (!maxSymbolValue) maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
6890c16b537SWarner Losh if (!tableLog) tableLog = FSE_DEFAULT_TABLELOG;
6900c16b537SWarner Losh
6910c16b537SWarner Losh /* Scan input and build symbol stats */
692a0483764SConrad Meyer { CHECK_V_F(maxCount, HIST_count_wksp(count, &maxSymbolValue, src, srcSize, scratchBuffer, scratchBufferSize) );
6930c16b537SWarner Losh if (maxCount == srcSize) return 1; /* only a single symbol in src : rle */
6940c16b537SWarner Losh if (maxCount == 1) return 0; /* each symbol present maximum once => not compressible */
6950c16b537SWarner Losh if (maxCount < (srcSize >> 7)) return 0; /* Heuristic : not compressible enough */
6960c16b537SWarner Losh }
6970c16b537SWarner Losh
6980c16b537SWarner Losh tableLog = FSE_optimalTableLog(tableLog, srcSize, maxSymbolValue);
699f7cd7fe5SConrad Meyer CHECK_F( FSE_normalizeCount(norm, tableLog, count, srcSize, maxSymbolValue, /* useLowProbCount */ srcSize >= 2048) );
7000c16b537SWarner Losh
7010c16b537SWarner Losh /* Write table description header */
7020c16b537SWarner Losh { CHECK_V_F(nc_err, FSE_writeNCount(op, oend-op, norm, maxSymbolValue, tableLog) );
7030c16b537SWarner Losh op += nc_err;
7040c16b537SWarner Losh }
7050c16b537SWarner Losh
7060c16b537SWarner Losh /* Compress */
7070c16b537SWarner Losh CHECK_F( FSE_buildCTable_wksp(CTable, norm, maxSymbolValue, tableLog, scratchBuffer, scratchBufferSize) );
7080c16b537SWarner Losh { CHECK_V_F(cSize, FSE_compress_usingCTable(op, oend - op, src, srcSize, CTable) );
7090c16b537SWarner Losh if (cSize == 0) return 0; /* not enough space for compressed data */
7100c16b537SWarner Losh op += cSize;
7110c16b537SWarner Losh }
7120c16b537SWarner Losh
7130c16b537SWarner Losh /* check compressibility */
7140c16b537SWarner Losh if ( (size_t)(op-ostart) >= srcSize-1 ) return 0;
7150c16b537SWarner Losh
7160c16b537SWarner Losh return op-ostart;
7170c16b537SWarner Losh }
7180c16b537SWarner Losh
7190c16b537SWarner Losh typedef struct {
7200c16b537SWarner Losh FSE_CTable CTable_max[FSE_CTABLE_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)];
721f7cd7fe5SConrad Meyer union {
722f7cd7fe5SConrad Meyer U32 hist_wksp[HIST_WKSP_SIZE_U32];
7230c16b537SWarner Losh BYTE scratchBuffer[1 << FSE_MAX_TABLELOG];
724f7cd7fe5SConrad Meyer } workspace;
7250c16b537SWarner Losh } fseWkspMax_t;
7260c16b537SWarner Losh
FSE_compress2(void * dst,size_t dstCapacity,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned tableLog)7270c16b537SWarner Losh size_t FSE_compress2 (void* dst, size_t dstCapacity, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog)
7280c16b537SWarner Losh {
7290c16b537SWarner Losh fseWkspMax_t scratchBuffer;
730f7cd7fe5SConrad Meyer DEBUG_STATIC_ASSERT(sizeof(scratchBuffer) >= FSE_COMPRESS_WKSP_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)); /* compilation failures here means scratchBuffer is not large enough */
7310c16b537SWarner Losh if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
7320c16b537SWarner Losh return FSE_compress_wksp(dst, dstCapacity, src, srcSize, maxSymbolValue, tableLog, &scratchBuffer, sizeof(scratchBuffer));
7330c16b537SWarner Losh }
7340c16b537SWarner Losh
FSE_compress(void * dst,size_t dstCapacity,const void * src,size_t srcSize)7350c16b537SWarner Losh size_t FSE_compress (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
7360c16b537SWarner Losh {
7370c16b537SWarner Losh return FSE_compress2(dst, dstCapacity, src, srcSize, FSE_MAX_SYMBOL_VALUE, FSE_DEFAULT_TABLELOG);
7380c16b537SWarner Losh }
739f7cd7fe5SConrad Meyer #endif
7400c16b537SWarner Losh
7410c16b537SWarner Losh #endif /* FSE_COMMONDEFS_ONLY */
742