/* ******************************************************************1* FSE : Finite State Entropy codec2* Public Prototypes declaration3* Copyright (c) Meta Platforms, Inc. and affiliates.4*5* You can contact the author at :6* - Source repository : https://github.com/Cyan4973/FiniteStateEntropy7*8* This source code is licensed under both the BSD-style license (found in the9* LICENSE file in the root directory of this source tree) and the GPLv2 (found10* in the COPYING file in the root directory of this source tree).11* You may select, at your option, one of the above-listed licenses.12****************************************************************** */13#ifndef FSE_H14#define FSE_H151617/*-*****************************************18* Dependencies19******************************************/20#include "zstd_deps.h" /* size_t, ptrdiff_t */2122/*-*****************************************23* FSE_PUBLIC_API : control library symbols visibility24******************************************/25#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4)26# define FSE_PUBLIC_API __attribute__ ((visibility ("default")))27#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) /* Visual expected */28# define FSE_PUBLIC_API __declspec(dllexport)29#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1)30# define FSE_PUBLIC_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/31#else32# define FSE_PUBLIC_API33#endif3435/*------ Version ------*/36#define FSE_VERSION_MAJOR 037#define FSE_VERSION_MINOR 938#define FSE_VERSION_RELEASE 03940#define FSE_LIB_VERSION FSE_VERSION_MAJOR.FSE_VERSION_MINOR.FSE_VERSION_RELEASE41#define FSE_QUOTE(str) #str42#define FSE_EXPAND_AND_QUOTE(str) FSE_QUOTE(str)43#define FSE_VERSION_STRING FSE_EXPAND_AND_QUOTE(FSE_LIB_VERSION)4445#define FSE_VERSION_NUMBER (FSE_VERSION_MAJOR *100*100 + FSE_VERSION_MINOR *100 + FSE_VERSION_RELEASE)46FSE_PUBLIC_API unsigned FSE_versionNumber(void); /**< library version number; to be used when checking dll version */474849/*-*****************************************50* Tool functions51******************************************/52FSE_PUBLIC_API size_t FSE_compressBound(size_t size); /* maximum compressed size */5354/* Error Management */55FSE_PUBLIC_API unsigned FSE_isError(size_t code); /* tells if a return value is an error code */56FSE_PUBLIC_API const char* FSE_getErrorName(size_t code); /* provides error code string (useful for debugging) */575859/*-*****************************************60* FSE detailed API61******************************************/62/*!63FSE_compress() does the following:641. count symbol occurrence from source[] into table count[] (see hist.h)652. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)663. save normalized counters to memory buffer using writeNCount()674. build encoding table 'CTable' from normalized counters685. encode the data stream using encoding table 'CTable'6970FSE_decompress() does the following:711. read normalized counters with readNCount()722. build decoding table 'DTable' from normalized counters733. decode the data stream using decoding table 'DTable'7475The following API allows targeting specific sub-functions for advanced tasks.76For example, it's possible to compress several blocks using the same 'CTable',77or to save and provide normalized distribution using external method.78*/7980/* *** COMPRESSION *** */8182/*! FSE_optimalTableLog():83dynamically downsize 'tableLog' when conditions are met.84It saves CPU time, by using smaller tables, while preserving or even improving compression ratio.85@return : recommended tableLog (necessarily <= 'maxTableLog') */86FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue);8788/*! FSE_normalizeCount():89normalize counts so that sum(count[]) == Power_of_2 (2^tableLog)90'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1).91useLowProbCount is a boolean parameter which trades off compressed size for92faster header decoding. When it is set to 1, the compressed data will be slightly93smaller. And when it is set to 0, FSE_readNCount() and FSE_buildDTable() will be94faster. If you are compressing a small amount of data (< 2 KB) then useLowProbCount=095is a good default, since header deserialization makes a big speed difference.96Otherwise, useLowProbCount=1 is a good default, since the speed difference is small.97@return : tableLog,98or an errorCode, which can be tested using FSE_isError() */99FSE_PUBLIC_API size_t FSE_normalizeCount(short* normalizedCounter, unsigned tableLog,100const unsigned* count, size_t srcSize, unsigned maxSymbolValue, unsigned useLowProbCount);101102/*! FSE_NCountWriteBound():103Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'.104Typically useful for allocation purpose. */105FSE_PUBLIC_API size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog);106107/*! FSE_writeNCount():108Compactly save 'normalizedCounter' into 'buffer'.109@return : size of the compressed table,110or an errorCode, which can be tested using FSE_isError(). */111FSE_PUBLIC_API size_t FSE_writeNCount (void* buffer, size_t bufferSize,112const short* normalizedCounter,113unsigned maxSymbolValue, unsigned tableLog);114115/*! Constructor and Destructor of FSE_CTable.116Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue' */117typedef unsigned FSE_CTable; /* don't allocate that. It's only meant to be more restrictive than void* */118119/*! FSE_buildCTable():120Builds `ct`, which must be already allocated, using FSE_createCTable().121@return : 0, or an errorCode, which can be tested using FSE_isError() */122FSE_PUBLIC_API size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);123124/*! FSE_compress_usingCTable():125Compress `src` using `ct` into `dst` which must be already allocated.126@return : size of compressed data (<= `dstCapacity`),127or 0 if compressed data could not fit into `dst`,128or an errorCode, which can be tested using FSE_isError() */129FSE_PUBLIC_API size_t FSE_compress_usingCTable (void* dst, size_t dstCapacity, const void* src, size_t srcSize, const FSE_CTable* ct);130131/*!132Tutorial :133----------134The first step is to count all symbols. FSE_count() does this job very fast.135Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells.136'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0]137maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value)138FSE_count() will return the number of occurrence of the most frequent symbol.139This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility.140If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).141142The next step is to normalize the frequencies.143FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'.144It also guarantees a minimum of 1 to any Symbol with frequency >= 1.145You can use 'tableLog'==0 to mean "use default tableLog value".146If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(),147which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default").148149The result of FSE_normalizeCount() will be saved into a table,150called 'normalizedCounter', which is a table of signed short.151'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells.152The return value is tableLog if everything proceeded as expected.153It is 0 if there is a single symbol within distribution.154If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()).155156'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount().157'buffer' must be already allocated.158For guaranteed success, buffer size must be at least FSE_headerBound().159The result of the function is the number of bytes written into 'buffer'.160If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small).161162'normalizedCounter' can then be used to create the compression table 'CTable'.163The space required by 'CTable' must be already allocated, using FSE_createCTable().164You can then use FSE_buildCTable() to fill 'CTable'.165If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()).166167'CTable' can then be used to compress 'src', with FSE_compress_usingCTable().168Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize'169The function returns the size of compressed data (without header), necessarily <= `dstCapacity`.170If it returns '0', compressed data could not fit into 'dst'.171If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).172*/173174175/* *** DECOMPRESSION *** */176177/*! FSE_readNCount():178Read compactly saved 'normalizedCounter' from 'rBuffer'.179@return : size read from 'rBuffer',180or an errorCode, which can be tested using FSE_isError().181maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */182FSE_PUBLIC_API size_t FSE_readNCount (short* normalizedCounter,183unsigned* maxSymbolValuePtr, unsigned* tableLogPtr,184const void* rBuffer, size_t rBuffSize);185186/*! FSE_readNCount_bmi2():187* Same as FSE_readNCount() but pass bmi2=1 when your CPU supports BMI2 and 0 otherwise.188*/189FSE_PUBLIC_API size_t FSE_readNCount_bmi2(short* normalizedCounter,190unsigned* maxSymbolValuePtr, unsigned* tableLogPtr,191const void* rBuffer, size_t rBuffSize, int bmi2);192193typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */194195/*!196Tutorial :197----------198(Note : these functions only decompress FSE-compressed blocks.199If block is uncompressed, use memcpy() instead200If block is a single repeated byte, use memset() instead )201202The first step is to obtain the normalized frequencies of symbols.203This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount().204'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.205In practice, that means it's necessary to know 'maxSymbolValue' beforehand,206or size the table to handle worst case situations (typically 256).207FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'.208The result of FSE_readNCount() is the number of bytes read from 'rBuffer'.209Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.210If there is an error, the function will return an error code, which can be tested using FSE_isError().211212The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'.213This is performed by the function FSE_buildDTable().214The space required by 'FSE_DTable' must be already allocated using FSE_createDTable().215If there is an error, the function will return an error code, which can be tested using FSE_isError().216217`FSE_DTable` can then be used to decompress `cSrc`, with FSE_decompress_usingDTable().218`cSrcSize` must be strictly correct, otherwise decompression will fail.219FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).220If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)221*/222223#endif /* FSE_H */224225226#if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)227#define FSE_H_FSE_STATIC_LINKING_ONLY228#include "bitstream.h"229230/* *****************************************231* Static allocation232*******************************************/233/* FSE buffer bounds */234#define FSE_NCOUNTBOUND 512235#define FSE_BLOCKBOUND(size) ((size) + ((size)>>7) + 4 /* fse states */ + sizeof(size_t) /* bitContainer */)236#define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */237238/* It is possible to statically allocate FSE CTable/DTable as a table of FSE_CTable/FSE_DTable using below macros */239#define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1<<((maxTableLog)-1)) + (((maxSymbolValue)+1)*2))240#define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<(maxTableLog)))241242/* or use the size to malloc() space directly. Pay attention to alignment restrictions though */243#define FSE_CTABLE_SIZE(maxTableLog, maxSymbolValue) (FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(FSE_CTable))244#define FSE_DTABLE_SIZE(maxTableLog) (FSE_DTABLE_SIZE_U32(maxTableLog) * sizeof(FSE_DTable))245246247/* *****************************************248* FSE advanced API249***************************************** */250251unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);252/**< same as FSE_optimalTableLog(), which used `minus==2` */253254size_t FSE_buildCTable_rle (FSE_CTable* ct, unsigned char symbolValue);255/**< build a fake FSE_CTable, designed to compress always the same symbolValue */256257/* FSE_buildCTable_wksp() :258* Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).259* `wkspSize` must be >= `FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog)` of `unsigned`.260* See FSE_buildCTable_wksp() for breakdown of workspace usage.261*/262#define FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog) (((maxSymbolValue + 2) + (1ull << (tableLog)))/2 + sizeof(U64)/sizeof(U32) /* additional 8 bytes for potential table overwrite */)263#define FSE_BUILD_CTABLE_WORKSPACE_SIZE(maxSymbolValue, tableLog) (sizeof(unsigned) * FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog))264size_t FSE_buildCTable_wksp(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);265266#define FSE_BUILD_DTABLE_WKSP_SIZE(maxTableLog, maxSymbolValue) (sizeof(short) * (maxSymbolValue + 1) + (1ULL << maxTableLog) + 8)267#define FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) ((FSE_BUILD_DTABLE_WKSP_SIZE(maxTableLog, maxSymbolValue) + sizeof(unsigned) - 1) / sizeof(unsigned))268FSE_PUBLIC_API size_t FSE_buildDTable_wksp(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);269/**< Same as FSE_buildDTable(), using an externally allocated `workspace` produced with `FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxSymbolValue)` */270271#define FSE_DECOMPRESS_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) (FSE_DTABLE_SIZE_U32(maxTableLog) + 1 + FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) + (FSE_MAX_SYMBOL_VALUE + 1) / 2 + 1)272#define FSE_DECOMPRESS_WKSP_SIZE(maxTableLog, maxSymbolValue) (FSE_DECOMPRESS_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(unsigned))273size_t FSE_decompress_wksp_bmi2(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize, int bmi2);274/**< same as FSE_decompress(), using an externally allocated `workSpace` produced with `FSE_DECOMPRESS_WKSP_SIZE_U32(maxLog, maxSymbolValue)`.275* Set bmi2 to 1 if your CPU supports BMI2 or 0 if it doesn't */276277typedef enum {278FSE_repeat_none, /**< Cannot use the previous table */279FSE_repeat_check, /**< Can use the previous table but it must be checked */280FSE_repeat_valid /**< Can use the previous table and it is assumed to be valid */281} FSE_repeat;282283/* *****************************************284* FSE symbol compression API285*******************************************/286/*!287This API consists of small unitary functions, which highly benefit from being inlined.288Hence their body are included in next section.289*/290typedef struct {291ptrdiff_t value;292const void* stateTable;293const void* symbolTT;294unsigned stateLog;295} FSE_CState_t;296297static void FSE_initCState(FSE_CState_t* CStatePtr, const FSE_CTable* ct);298299static void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* CStatePtr, unsigned symbol);300301static void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* CStatePtr);302303/**<304These functions are inner components of FSE_compress_usingCTable().305They allow the creation of custom streams, mixing multiple tables and bit sources.306307A key property to keep in mind is that encoding and decoding are done **in reverse direction**.308So the first symbol you will encode is the last you will decode, like a LIFO stack.309310You will need a few variables to track your CStream. They are :311312FSE_CTable ct; // Provided by FSE_buildCTable()313BIT_CStream_t bitStream; // bitStream tracking structure314FSE_CState_t state; // State tracking structure (can have several)315316317The first thing to do is to init bitStream and state.318size_t errorCode = BIT_initCStream(&bitStream, dstBuffer, maxDstSize);319FSE_initCState(&state, ct);320321Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError();322You can then encode your input data, byte after byte.323FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time.324Remember decoding will be done in reverse direction.325FSE_encodeByte(&bitStream, &state, symbol);326327At any time, you can also add any bit sequence.328Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders329BIT_addBits(&bitStream, bitField, nbBits);330331The above methods don't commit data to memory, they just store it into local register, for speed.332Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).333Writing data to memory is a manual operation, performed by the flushBits function.334BIT_flushBits(&bitStream);335336Your last FSE encoding operation shall be to flush your last state value(s).337FSE_flushState(&bitStream, &state);338339Finally, you must close the bitStream.340The function returns the size of CStream in bytes.341If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible)342If there is an error, it returns an errorCode (which can be tested using FSE_isError()).343size_t size = BIT_closeCStream(&bitStream);344*/345346347/* *****************************************348* FSE symbol decompression API349*******************************************/350typedef struct {351size_t state;352const void* table; /* precise table may vary, depending on U16 */353} FSE_DState_t;354355356static void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt);357358static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);359360static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr);361362/**<363Let's now decompose FSE_decompress_usingDTable() into its unitary components.364You will decode FSE-encoded symbols from the bitStream,365and also any other bitFields you put in, **in reverse order**.366367You will need a few variables to track your bitStream. They are :368369BIT_DStream_t DStream; // Stream context370FSE_DState_t DState; // State context. Multiple ones are possible371FSE_DTable* DTablePtr; // Decoding table, provided by FSE_buildDTable()372373The first thing to do is to init the bitStream.374errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize);375376You should then retrieve your initial state(s)377(in reverse flushing order if you have several ones) :378errorCode = FSE_initDState(&DState, &DStream, DTablePtr);379380You can then decode your data, symbol after symbol.381For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'.382Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out).383unsigned char symbol = FSE_decodeSymbol(&DState, &DStream);384385You can retrieve any bitfield you eventually stored into the bitStream (in reverse order)386Note : maximum allowed nbBits is 25, for 32-bits compatibility387size_t bitField = BIT_readBits(&DStream, nbBits);388389All above operations only read from local register (which size depends on size_t).390Refueling the register from memory is manually performed by the reload method.391endSignal = FSE_reloadDStream(&DStream);392393BIT_reloadDStream() result tells if there is still some more data to read from DStream.394BIT_DStream_unfinished : there is still some data left into the DStream.395BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled.396BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed.397BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted.398399When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop,400to properly detect the exact end of stream.401After each decoded symbol, check if DStream is fully consumed using this simple test :402BIT_reloadDStream(&DStream) >= BIT_DStream_completed403404When it's done, verify decompression is fully completed, by checking both DStream and the relevant states.405Checking if DStream has reached its end is performed by :406BIT_endOfDStream(&DStream);407Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible.408FSE_endOfDState(&DState);409*/410411412/* *****************************************413* FSE unsafe API414*******************************************/415static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);416/* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */417418419/* *****************************************420* Implementation of inlined functions421*******************************************/422typedef struct {423int deltaFindState;424U32 deltaNbBits;425} FSE_symbolCompressionTransform; /* total 8 bytes */426427MEM_STATIC void FSE_initCState(FSE_CState_t* statePtr, const FSE_CTable* ct)428{429const void* ptr = ct;430const U16* u16ptr = (const U16*) ptr;431const U32 tableLog = MEM_read16(ptr);432statePtr->value = (ptrdiff_t)1<<tableLog;433statePtr->stateTable = u16ptr+2;434statePtr->symbolTT = ct + 1 + (tableLog ? (1<<(tableLog-1)) : 1);435statePtr->stateLog = tableLog;436}437438439/*! FSE_initCState2() :440* Same as FSE_initCState(), but the first symbol to include (which will be the last to be read)441* uses the smallest state value possible, saving the cost of this symbol */442MEM_STATIC void FSE_initCState2(FSE_CState_t* statePtr, const FSE_CTable* ct, U32 symbol)443{444FSE_initCState(statePtr, ct);445{ const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];446const U16* stateTable = (const U16*)(statePtr->stateTable);447U32 nbBitsOut = (U32)((symbolTT.deltaNbBits + (1<<15)) >> 16);448statePtr->value = (nbBitsOut << 16) - symbolTT.deltaNbBits;449statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];450}451}452453MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, unsigned symbol)454{455FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];456const U16* const stateTable = (const U16*)(statePtr->stateTable);457U32 const nbBitsOut = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16);458BIT_addBits(bitC, (BitContainerType)statePtr->value, nbBitsOut);459statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];460}461462MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr)463{464BIT_addBits(bitC, (BitContainerType)statePtr->value, statePtr->stateLog);465BIT_flushBits(bitC);466}467468469/* FSE_getMaxNbBits() :470* Approximate maximum cost of a symbol, in bits.471* Fractional get rounded up (i.e. a symbol with a normalized frequency of 3 gives the same result as a frequency of 2)472* note 1 : assume symbolValue is valid (<= maxSymbolValue)473* note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */474MEM_STATIC U32 FSE_getMaxNbBits(const void* symbolTTPtr, U32 symbolValue)475{476const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;477return (symbolTT[symbolValue].deltaNbBits + ((1<<16)-1)) >> 16;478}479480/* FSE_bitCost() :481* Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits)482* note 1 : assume symbolValue is valid (<= maxSymbolValue)483* note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */484MEM_STATIC U32 FSE_bitCost(const void* symbolTTPtr, U32 tableLog, U32 symbolValue, U32 accuracyLog)485{486const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;487U32 const minNbBits = symbolTT[symbolValue].deltaNbBits >> 16;488U32 const threshold = (minNbBits+1) << 16;489assert(tableLog < 16);490assert(accuracyLog < 31-tableLog); /* ensure enough room for renormalization double shift */491{ U32 const tableSize = 1 << tableLog;492U32 const deltaFromThreshold = threshold - (symbolTT[symbolValue].deltaNbBits + tableSize);493U32 const normalizedDeltaFromThreshold = (deltaFromThreshold << accuracyLog) >> tableLog; /* linear interpolation (very approximate) */494U32 const bitMultiplier = 1 << accuracyLog;495assert(symbolTT[symbolValue].deltaNbBits + tableSize <= threshold);496assert(normalizedDeltaFromThreshold <= bitMultiplier);497return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold;498}499}500501502/* ====== Decompression ====== */503504typedef struct {505U16 tableLog;506U16 fastMode;507} FSE_DTableHeader; /* sizeof U32 */508509typedef struct510{511unsigned short newState;512unsigned char symbol;513unsigned char nbBits;514} FSE_decode_t; /* size == U32 */515516MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt)517{518const void* ptr = dt;519const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr;520DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);521BIT_reloadDStream(bitD);522DStatePtr->table = dt + 1;523}524525MEM_STATIC BYTE FSE_peekSymbol(const FSE_DState_t* DStatePtr)526{527FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];528return DInfo.symbol;529}530531MEM_STATIC void FSE_updateState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)532{533FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];534U32 const nbBits = DInfo.nbBits;535size_t const lowBits = BIT_readBits(bitD, nbBits);536DStatePtr->state = DInfo.newState + lowBits;537}538539MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)540{541FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];542U32 const nbBits = DInfo.nbBits;543BYTE const symbol = DInfo.symbol;544size_t const lowBits = BIT_readBits(bitD, nbBits);545546DStatePtr->state = DInfo.newState + lowBits;547return symbol;548}549550/*! FSE_decodeSymbolFast() :551unsafe, only works if no symbol has a probability > 50% */552MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)553{554FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];555U32 const nbBits = DInfo.nbBits;556BYTE const symbol = DInfo.symbol;557size_t const lowBits = BIT_readBitsFast(bitD, nbBits);558559DStatePtr->state = DInfo.newState + lowBits;560return symbol;561}562563MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)564{565return DStatePtr->state == 0;566}567568569570#ifndef FSE_COMMONDEFS_ONLY571572/* **************************************************************573* Tuning parameters574****************************************************************/575/*!MEMORY_USAGE :576* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)577* Increasing memory usage improves compression ratio578* Reduced memory usage can improve speed, due to cache effect579* Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */580#ifndef FSE_MAX_MEMORY_USAGE581# define FSE_MAX_MEMORY_USAGE 14582#endif583#ifndef FSE_DEFAULT_MEMORY_USAGE584# define FSE_DEFAULT_MEMORY_USAGE 13585#endif586#if (FSE_DEFAULT_MEMORY_USAGE > FSE_MAX_MEMORY_USAGE)587# error "FSE_DEFAULT_MEMORY_USAGE must be <= FSE_MAX_MEMORY_USAGE"588#endif589590/*!FSE_MAX_SYMBOL_VALUE :591* Maximum symbol value authorized.592* Required for proper stack allocation */593#ifndef FSE_MAX_SYMBOL_VALUE594# define FSE_MAX_SYMBOL_VALUE 255595#endif596597/* **************************************************************598* template functions type & suffix599****************************************************************/600#define FSE_FUNCTION_TYPE BYTE601#define FSE_FUNCTION_EXTENSION602#define FSE_DECODE_TYPE FSE_decode_t603604605#endif /* !FSE_COMMONDEFS_ONLY */606607608/* ***************************************************************609* Constants610*****************************************************************/611#define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2)612#define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)613#define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)614#define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)615#define FSE_MIN_TABLELOG 5616617#define FSE_TABLELOG_ABSOLUTE_MAX 15618#if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX619# error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"620#endif621622#define FSE_TABLESTEP(tableSize) (((tableSize)>>1) + ((tableSize)>>3) + 3)623624#endif /* FSE_STATIC_LINKING_ONLY */625626627