Back to home page

OSCL-LXR

 
 

    


0001 /* ******************************************************************
0002  * FSE : Finite State Entropy codec
0003  * Public Prototypes declaration
0004  * Copyright (c) Yann Collet, Facebook, Inc.
0005  *
0006  * You can contact the author at :
0007  * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
0008  *
0009  * This source code is licensed under both the BSD-style license (found in the
0010  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
0011  * in the COPYING file in the root directory of this source tree).
0012  * You may select, at your option, one of the above-listed licenses.
0013 ****************************************************************** */
0014 
0015 
0016 #ifndef FSE_H
0017 #define FSE_H
0018 
0019 
0020 /*-*****************************************
0021 *  Dependencies
0022 ******************************************/
0023 #include "zstd_deps.h"    /* size_t, ptrdiff_t */
0024 
0025 
0026 /*-*****************************************
0027 *  FSE_PUBLIC_API : control library symbols visibility
0028 ******************************************/
0029 #if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4)
0030 #  define FSE_PUBLIC_API __attribute__ ((visibility ("default")))
0031 #elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1)   /* Visual expected */
0032 #  define FSE_PUBLIC_API __declspec(dllexport)
0033 #elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1)
0034 #  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.*/
0035 #else
0036 #  define FSE_PUBLIC_API
0037 #endif
0038 
0039 /*------   Version   ------*/
0040 #define FSE_VERSION_MAJOR    0
0041 #define FSE_VERSION_MINOR    9
0042 #define FSE_VERSION_RELEASE  0
0043 
0044 #define FSE_LIB_VERSION FSE_VERSION_MAJOR.FSE_VERSION_MINOR.FSE_VERSION_RELEASE
0045 #define FSE_QUOTE(str) #str
0046 #define FSE_EXPAND_AND_QUOTE(str) FSE_QUOTE(str)
0047 #define FSE_VERSION_STRING FSE_EXPAND_AND_QUOTE(FSE_LIB_VERSION)
0048 
0049 #define FSE_VERSION_NUMBER  (FSE_VERSION_MAJOR *100*100 + FSE_VERSION_MINOR *100 + FSE_VERSION_RELEASE)
0050 FSE_PUBLIC_API unsigned FSE_versionNumber(void);   /*< library version number; to be used when checking dll version */
0051 
0052 
0053 /*-****************************************
0054 *  FSE simple functions
0055 ******************************************/
0056 /*! FSE_compress() :
0057     Compress content of buffer 'src', of size 'srcSize', into destination buffer 'dst'.
0058     'dst' buffer must be already allocated. Compression runs faster is dstCapacity >= FSE_compressBound(srcSize).
0059     @return : size of compressed data (<= dstCapacity).
0060     Special values : if return == 0, srcData is not compressible => Nothing is stored within dst !!!
0061                      if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression instead.
0062                      if FSE_isError(return), compression failed (more details using FSE_getErrorName())
0063 */
0064 FSE_PUBLIC_API size_t FSE_compress(void* dst, size_t dstCapacity,
0065                              const void* src, size_t srcSize);
0066 
0067 /*! FSE_decompress():
0068     Decompress FSE data from buffer 'cSrc', of size 'cSrcSize',
0069     into already allocated destination buffer 'dst', of size 'dstCapacity'.
0070     @return : size of regenerated data (<= maxDstSize),
0071               or an error code, which can be tested using FSE_isError() .
0072 
0073     ** Important ** : FSE_decompress() does not decompress non-compressible nor RLE data !!!
0074     Why ? : making this distinction requires a header.
0075     Header management is intentionally delegated to the user layer, which can better manage special cases.
0076 */
0077 FSE_PUBLIC_API size_t FSE_decompress(void* dst,  size_t dstCapacity,
0078                                const void* cSrc, size_t cSrcSize);
0079 
0080 
0081 /*-*****************************************
0082 *  Tool functions
0083 ******************************************/
0084 FSE_PUBLIC_API size_t FSE_compressBound(size_t size);       /* maximum compressed size */
0085 
0086 /* Error Management */
0087 FSE_PUBLIC_API unsigned    FSE_isError(size_t code);        /* tells if a return value is an error code */
0088 FSE_PUBLIC_API const char* FSE_getErrorName(size_t code);   /* provides error code string (useful for debugging) */
0089 
0090 
0091 /*-*****************************************
0092 *  FSE advanced functions
0093 ******************************************/
0094 /*! FSE_compress2() :
0095     Same as FSE_compress(), but allows the selection of 'maxSymbolValue' and 'tableLog'
0096     Both parameters can be defined as '0' to mean : use default value
0097     @return : size of compressed data
0098     Special values : if return == 0, srcData is not compressible => Nothing is stored within cSrc !!!
0099                      if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression.
0100                      if FSE_isError(return), it's an error code.
0101 */
0102 FSE_PUBLIC_API size_t FSE_compress2 (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog);
0103 
0104 
0105 /*-*****************************************
0106 *  FSE detailed API
0107 ******************************************/
0108 /*!
0109 FSE_compress() does the following:
0110 1. count symbol occurrence from source[] into table count[] (see hist.h)
0111 2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)
0112 3. save normalized counters to memory buffer using writeNCount()
0113 4. build encoding table 'CTable' from normalized counters
0114 5. encode the data stream using encoding table 'CTable'
0115 
0116 FSE_decompress() does the following:
0117 1. read normalized counters with readNCount()
0118 2. build decoding table 'DTable' from normalized counters
0119 3. decode the data stream using decoding table 'DTable'
0120 
0121 The following API allows targeting specific sub-functions for advanced tasks.
0122 For example, it's possible to compress several blocks using the same 'CTable',
0123 or to save and provide normalized distribution using external method.
0124 */
0125 
0126 /* *** COMPRESSION *** */
0127 
0128 /*! FSE_optimalTableLog():
0129     dynamically downsize 'tableLog' when conditions are met.
0130     It saves CPU time, by using smaller tables, while preserving or even improving compression ratio.
0131     @return : recommended tableLog (necessarily <= 'maxTableLog') */
0132 FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue);
0133 
0134 /*! FSE_normalizeCount():
0135     normalize counts so that sum(count[]) == Power_of_2 (2^tableLog)
0136     'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1).
0137     useLowProbCount is a boolean parameter which trades off compressed size for
0138     faster header decoding. When it is set to 1, the compressed data will be slightly
0139     smaller. And when it is set to 0, FSE_readNCount() and FSE_buildDTable() will be
0140     faster. If you are compressing a small amount of data (< 2 KB) then useLowProbCount=0
0141     is a good default, since header deserialization makes a big speed difference.
0142     Otherwise, useLowProbCount=1 is a good default, since the speed difference is small.
0143     @return : tableLog,
0144               or an errorCode, which can be tested using FSE_isError() */
0145 FSE_PUBLIC_API size_t FSE_normalizeCount(short* normalizedCounter, unsigned tableLog,
0146                     const unsigned* count, size_t srcSize, unsigned maxSymbolValue, unsigned useLowProbCount);
0147 
0148 /*! FSE_NCountWriteBound():
0149     Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'.
0150     Typically useful for allocation purpose. */
0151 FSE_PUBLIC_API size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog);
0152 
0153 /*! FSE_writeNCount():
0154     Compactly save 'normalizedCounter' into 'buffer'.
0155     @return : size of the compressed table,
0156               or an errorCode, which can be tested using FSE_isError(). */
0157 FSE_PUBLIC_API size_t FSE_writeNCount (void* buffer, size_t bufferSize,
0158                                  const short* normalizedCounter,
0159                                  unsigned maxSymbolValue, unsigned tableLog);
0160 
0161 /*! Constructor and Destructor of FSE_CTable.
0162     Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue' */
0163 typedef unsigned FSE_CTable;   /* don't allocate that. It's only meant to be more restrictive than void* */
0164 FSE_PUBLIC_API FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog);
0165 FSE_PUBLIC_API void        FSE_freeCTable (FSE_CTable* ct);
0166 
0167 /*! FSE_buildCTable():
0168     Builds `ct`, which must be already allocated, using FSE_createCTable().
0169     @return : 0, or an errorCode, which can be tested using FSE_isError() */
0170 FSE_PUBLIC_API size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
0171 
0172 /*! FSE_compress_usingCTable():
0173     Compress `src` using `ct` into `dst` which must be already allocated.
0174     @return : size of compressed data (<= `dstCapacity`),
0175               or 0 if compressed data could not fit into `dst`,
0176               or an errorCode, which can be tested using FSE_isError() */
0177 FSE_PUBLIC_API size_t FSE_compress_usingCTable (void* dst, size_t dstCapacity, const void* src, size_t srcSize, const FSE_CTable* ct);
0178 
0179 /*!
0180 Tutorial :
0181 ----------
0182 The first step is to count all symbols. FSE_count() does this job very fast.
0183 Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells.
0184 'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0]
0185 maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value)
0186 FSE_count() will return the number of occurrence of the most frequent symbol.
0187 This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility.
0188 If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
0189 
0190 The next step is to normalize the frequencies.
0191 FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'.
0192 It also guarantees a minimum of 1 to any Symbol with frequency >= 1.
0193 You can use 'tableLog'==0 to mean "use default tableLog value".
0194 If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(),
0195 which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default").
0196 
0197 The result of FSE_normalizeCount() will be saved into a table,
0198 called 'normalizedCounter', which is a table of signed short.
0199 'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells.
0200 The return value is tableLog if everything proceeded as expected.
0201 It is 0 if there is a single symbol within distribution.
0202 If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()).
0203 
0204 'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount().
0205 'buffer' must be already allocated.
0206 For guaranteed success, buffer size must be at least FSE_headerBound().
0207 The result of the function is the number of bytes written into 'buffer'.
0208 If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small).
0209 
0210 'normalizedCounter' can then be used to create the compression table 'CTable'.
0211 The space required by 'CTable' must be already allocated, using FSE_createCTable().
0212 You can then use FSE_buildCTable() to fill 'CTable'.
0213 If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()).
0214 
0215 'CTable' can then be used to compress 'src', with FSE_compress_usingCTable().
0216 Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize'
0217 The function returns the size of compressed data (without header), necessarily <= `dstCapacity`.
0218 If it returns '0', compressed data could not fit into 'dst'.
0219 If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
0220 */
0221 
0222 
0223 /* *** DECOMPRESSION *** */
0224 
0225 /*! FSE_readNCount():
0226     Read compactly saved 'normalizedCounter' from 'rBuffer'.
0227     @return : size read from 'rBuffer',
0228               or an errorCode, which can be tested using FSE_isError().
0229               maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
0230 FSE_PUBLIC_API size_t FSE_readNCount (short* normalizedCounter,
0231                            unsigned* maxSymbolValuePtr, unsigned* tableLogPtr,
0232                            const void* rBuffer, size_t rBuffSize);
0233 
0234 /*! FSE_readNCount_bmi2():
0235  * Same as FSE_readNCount() but pass bmi2=1 when your CPU supports BMI2 and 0 otherwise.
0236  */
0237 FSE_PUBLIC_API size_t FSE_readNCount_bmi2(short* normalizedCounter,
0238                            unsigned* maxSymbolValuePtr, unsigned* tableLogPtr,
0239                            const void* rBuffer, size_t rBuffSize, int bmi2);
0240 
0241 /*! Constructor and Destructor of FSE_DTable.
0242     Note that its size depends on 'tableLog' */
0243 typedef unsigned FSE_DTable;   /* don't allocate that. It's just a way to be more restrictive than void* */
0244 FSE_PUBLIC_API FSE_DTable* FSE_createDTable(unsigned tableLog);
0245 FSE_PUBLIC_API void        FSE_freeDTable(FSE_DTable* dt);
0246 
0247 /*! FSE_buildDTable():
0248     Builds 'dt', which must be already allocated, using FSE_createDTable().
0249     return : 0, or an errorCode, which can be tested using FSE_isError() */
0250 FSE_PUBLIC_API size_t FSE_buildDTable (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
0251 
0252 /*! FSE_decompress_usingDTable():
0253     Decompress compressed source `cSrc` of size `cSrcSize` using `dt`
0254     into `dst` which must be already allocated.
0255     @return : size of regenerated data (necessarily <= `dstCapacity`),
0256               or an errorCode, which can be tested using FSE_isError() */
0257 FSE_PUBLIC_API size_t FSE_decompress_usingDTable(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, const FSE_DTable* dt);
0258 
0259 /*!
0260 Tutorial :
0261 ----------
0262 (Note : these functions only decompress FSE-compressed blocks.
0263  If block is uncompressed, use memcpy() instead
0264  If block is a single repeated byte, use memset() instead )
0265 
0266 The first step is to obtain the normalized frequencies of symbols.
0267 This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount().
0268 'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.
0269 In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
0270 or size the table to handle worst case situations (typically 256).
0271 FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
0272 The result of FSE_readNCount() is the number of bytes read from 'rBuffer'.
0273 Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
0274 If there is an error, the function will return an error code, which can be tested using FSE_isError().
0275 
0276 The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'.
0277 This is performed by the function FSE_buildDTable().
0278 The space required by 'FSE_DTable' must be already allocated using FSE_createDTable().
0279 If there is an error, the function will return an error code, which can be tested using FSE_isError().
0280 
0281 `FSE_DTable` can then be used to decompress `cSrc`, with FSE_decompress_usingDTable().
0282 `cSrcSize` must be strictly correct, otherwise decompression will fail.
0283 FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).
0284 If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)
0285 */
0286 
0287 #endif  /* FSE_H */
0288 
0289 #if !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
0290 #define FSE_H_FSE_STATIC_LINKING_ONLY
0291 
0292 /* *** Dependency *** */
0293 #include "bitstream.h"
0294 
0295 
0296 /* *****************************************
0297 *  Static allocation
0298 *******************************************/
0299 /* FSE buffer bounds */
0300 #define FSE_NCOUNTBOUND 512
0301 #define FSE_BLOCKBOUND(size) ((size) + ((size)>>7) + 4 /* fse states */ + sizeof(size_t) /* bitContainer */)
0302 #define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size))   /* Macro version, useful for static allocation */
0303 
0304 /* It is possible to statically allocate FSE CTable/DTable as a table of FSE_CTable/FSE_DTable using below macros */
0305 #define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue)   (1 + (1<<((maxTableLog)-1)) + (((maxSymbolValue)+1)*2))
0306 #define FSE_DTABLE_SIZE_U32(maxTableLog)                   (1 + (1<<(maxTableLog)))
0307 
0308 /* or use the size to malloc() space directly. Pay attention to alignment restrictions though */
0309 #define FSE_CTABLE_SIZE(maxTableLog, maxSymbolValue)   (FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(FSE_CTable))
0310 #define FSE_DTABLE_SIZE(maxTableLog)                   (FSE_DTABLE_SIZE_U32(maxTableLog) * sizeof(FSE_DTable))
0311 
0312 
0313 /* *****************************************
0314  *  FSE advanced API
0315  ***************************************** */
0316 
0317 unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
0318 /*< same as FSE_optimalTableLog(), which used `minus==2` */
0319 
0320 /* FSE_compress_wksp() :
0321  * Same as FSE_compress2(), but using an externally allocated scratch buffer (`workSpace`).
0322  * FSE_COMPRESS_WKSP_SIZE_U32() provides the minimum size required for `workSpace` as a table of FSE_CTable.
0323  */
0324 #define FSE_COMPRESS_WKSP_SIZE_U32(maxTableLog, maxSymbolValue)   ( FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) + ((maxTableLog > 12) ? (1 << (maxTableLog - 2)) : 1024) )
0325 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);
0326 
0327 size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits);
0328 /*< build a fake FSE_CTable, designed for a flat distribution, where each symbol uses nbBits */
0329 
0330 size_t FSE_buildCTable_rle (FSE_CTable* ct, unsigned char symbolValue);
0331 /*< build a fake FSE_CTable, designed to compress always the same symbolValue */
0332 
0333 /* FSE_buildCTable_wksp() :
0334  * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
0335  * `wkspSize` must be >= `FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog)` of `unsigned`.
0336  */
0337 #define FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog) (maxSymbolValue + 2 + (1ull << (tableLog - 2)))
0338 #define FSE_BUILD_CTABLE_WORKSPACE_SIZE(maxSymbolValue, tableLog) (sizeof(unsigned) * FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(maxSymbolValue, tableLog))
0339 size_t FSE_buildCTable_wksp(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);
0340 
0341 #define FSE_BUILD_DTABLE_WKSP_SIZE(maxTableLog, maxSymbolValue) (sizeof(short) * (maxSymbolValue + 1) + (1ULL << maxTableLog) + 8)
0342 #define FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) ((FSE_BUILD_DTABLE_WKSP_SIZE(maxTableLog, maxSymbolValue) + sizeof(unsigned) - 1) / sizeof(unsigned))
0343 FSE_PUBLIC_API size_t FSE_buildDTable_wksp(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);
0344 /*< Same as FSE_buildDTable(), using an externally allocated `workspace` produced with `FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxSymbolValue)` */
0345 
0346 size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits);
0347 /*< build a fake FSE_DTable, designed to read a flat distribution where each symbol uses nbBits */
0348 
0349 size_t FSE_buildDTable_rle (FSE_DTable* dt, unsigned char symbolValue);
0350 /*< build a fake FSE_DTable, designed to always generate the same symbolValue */
0351 
0352 #define FSE_DECOMPRESS_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) (FSE_DTABLE_SIZE_U32(maxTableLog) + FSE_BUILD_DTABLE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) + (FSE_MAX_SYMBOL_VALUE + 1) / 2 + 1)
0353 #define FSE_DECOMPRESS_WKSP_SIZE(maxTableLog, maxSymbolValue) (FSE_DECOMPRESS_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(unsigned))
0354 size_t FSE_decompress_wksp(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize);
0355 /*< same as FSE_decompress(), using an externally allocated `workSpace` produced with `FSE_DECOMPRESS_WKSP_SIZE_U32(maxLog, maxSymbolValue)` */
0356 
0357 size_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);
0358 /*< Same as FSE_decompress_wksp() but with dynamic BMI2 support. Pass 1 if your CPU supports BMI2 or 0 if it doesn't. */
0359 
0360 typedef enum {
0361    FSE_repeat_none,  /*< Cannot use the previous table */
0362    FSE_repeat_check, /*< Can use the previous table but it must be checked */
0363    FSE_repeat_valid  /*< Can use the previous table and it is assumed to be valid */
0364  } FSE_repeat;
0365 
0366 /* *****************************************
0367 *  FSE symbol compression API
0368 *******************************************/
0369 /*!
0370    This API consists of small unitary functions, which highly benefit from being inlined.
0371    Hence their body are included in next section.
0372 */
0373 typedef struct {
0374     ptrdiff_t   value;
0375     const void* stateTable;
0376     const void* symbolTT;
0377     unsigned    stateLog;
0378 } FSE_CState_t;
0379 
0380 static void FSE_initCState(FSE_CState_t* CStatePtr, const FSE_CTable* ct);
0381 
0382 static void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* CStatePtr, unsigned symbol);
0383 
0384 static void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* CStatePtr);
0385 
0386 /*<
0387 These functions are inner components of FSE_compress_usingCTable().
0388 They allow the creation of custom streams, mixing multiple tables and bit sources.
0389 
0390 A key property to keep in mind is that encoding and decoding are done **in reverse direction**.
0391 So the first symbol you will encode is the last you will decode, like a LIFO stack.
0392 
0393 You will need a few variables to track your CStream. They are :
0394 
0395 FSE_CTable    ct;         // Provided by FSE_buildCTable()
0396 BIT_CStream_t bitStream;  // bitStream tracking structure
0397 FSE_CState_t  state;      // State tracking structure (can have several)
0398 
0399 
0400 The first thing to do is to init bitStream and state.
0401     size_t errorCode = BIT_initCStream(&bitStream, dstBuffer, maxDstSize);
0402     FSE_initCState(&state, ct);
0403 
0404 Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError();
0405 You can then encode your input data, byte after byte.
0406 FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time.
0407 Remember decoding will be done in reverse direction.
0408     FSE_encodeByte(&bitStream, &state, symbol);
0409 
0410 At any time, you can also add any bit sequence.
0411 Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders
0412     BIT_addBits(&bitStream, bitField, nbBits);
0413 
0414 The above methods don't commit data to memory, they just store it into local register, for speed.
0415 Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
0416 Writing data to memory is a manual operation, performed by the flushBits function.
0417     BIT_flushBits(&bitStream);
0418 
0419 Your last FSE encoding operation shall be to flush your last state value(s).
0420     FSE_flushState(&bitStream, &state);
0421 
0422 Finally, you must close the bitStream.
0423 The function returns the size of CStream in bytes.
0424 If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible)
0425 If there is an error, it returns an errorCode (which can be tested using FSE_isError()).
0426     size_t size = BIT_closeCStream(&bitStream);
0427 */
0428 
0429 
0430 /* *****************************************
0431 *  FSE symbol decompression API
0432 *******************************************/
0433 typedef struct {
0434     size_t      state;
0435     const void* table;   /* precise table may vary, depending on U16 */
0436 } FSE_DState_t;
0437 
0438 
0439 static void     FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt);
0440 
0441 static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
0442 
0443 static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr);
0444 
0445 /*<
0446 Let's now decompose FSE_decompress_usingDTable() into its unitary components.
0447 You will decode FSE-encoded symbols from the bitStream,
0448 and also any other bitFields you put in, **in reverse order**.
0449 
0450 You will need a few variables to track your bitStream. They are :
0451 
0452 BIT_DStream_t DStream;    // Stream context
0453 FSE_DState_t  DState;     // State context. Multiple ones are possible
0454 FSE_DTable*   DTablePtr;  // Decoding table, provided by FSE_buildDTable()
0455 
0456 The first thing to do is to init the bitStream.
0457     errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize);
0458 
0459 You should then retrieve your initial state(s)
0460 (in reverse flushing order if you have several ones) :
0461     errorCode = FSE_initDState(&DState, &DStream, DTablePtr);
0462 
0463 You can then decode your data, symbol after symbol.
0464 For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'.
0465 Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out).
0466     unsigned char symbol = FSE_decodeSymbol(&DState, &DStream);
0467 
0468 You can retrieve any bitfield you eventually stored into the bitStream (in reverse order)
0469 Note : maximum allowed nbBits is 25, for 32-bits compatibility
0470     size_t bitField = BIT_readBits(&DStream, nbBits);
0471 
0472 All above operations only read from local register (which size depends on size_t).
0473 Refueling the register from memory is manually performed by the reload method.
0474     endSignal = FSE_reloadDStream(&DStream);
0475 
0476 BIT_reloadDStream() result tells if there is still some more data to read from DStream.
0477 BIT_DStream_unfinished : there is still some data left into the DStream.
0478 BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled.
0479 BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed.
0480 BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted.
0481 
0482 When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop,
0483 to properly detect the exact end of stream.
0484 After each decoded symbol, check if DStream is fully consumed using this simple test :
0485     BIT_reloadDStream(&DStream) >= BIT_DStream_completed
0486 
0487 When it's done, verify decompression is fully completed, by checking both DStream and the relevant states.
0488 Checking if DStream has reached its end is performed by :
0489     BIT_endOfDStream(&DStream);
0490 Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible.
0491     FSE_endOfDState(&DState);
0492 */
0493 
0494 
0495 /* *****************************************
0496 *  FSE unsafe API
0497 *******************************************/
0498 static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
0499 /* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
0500 
0501 
0502 /* *****************************************
0503 *  Implementation of inlined functions
0504 *******************************************/
0505 typedef struct {
0506     int deltaFindState;
0507     U32 deltaNbBits;
0508 } FSE_symbolCompressionTransform; /* total 8 bytes */
0509 
0510 MEM_STATIC void FSE_initCState(FSE_CState_t* statePtr, const FSE_CTable* ct)
0511 {
0512     const void* ptr = ct;
0513     const U16* u16ptr = (const U16*) ptr;
0514     const U32 tableLog = MEM_read16(ptr);
0515     statePtr->value = (ptrdiff_t)1<<tableLog;
0516     statePtr->stateTable = u16ptr+2;
0517     statePtr->symbolTT = ct + 1 + (tableLog ? (1<<(tableLog-1)) : 1);
0518     statePtr->stateLog = tableLog;
0519 }
0520 
0521 
0522 /*! FSE_initCState2() :
0523 *   Same as FSE_initCState(), but the first symbol to include (which will be the last to be read)
0524 *   uses the smallest state value possible, saving the cost of this symbol */
0525 MEM_STATIC void FSE_initCState2(FSE_CState_t* statePtr, const FSE_CTable* ct, U32 symbol)
0526 {
0527     FSE_initCState(statePtr, ct);
0528     {   const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
0529         const U16* stateTable = (const U16*)(statePtr->stateTable);
0530         U32 nbBitsOut  = (U32)((symbolTT.deltaNbBits + (1<<15)) >> 16);
0531         statePtr->value = (nbBitsOut << 16) - symbolTT.deltaNbBits;
0532         statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
0533     }
0534 }
0535 
0536 MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, unsigned symbol)
0537 {
0538     FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
0539     const U16* const stateTable = (const U16*)(statePtr->stateTable);
0540     U32 const nbBitsOut  = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16);
0541     BIT_addBits(bitC, statePtr->value, nbBitsOut);
0542     statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
0543 }
0544 
0545 MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr)
0546 {
0547     BIT_addBits(bitC, statePtr->value, statePtr->stateLog);
0548     BIT_flushBits(bitC);
0549 }
0550 
0551 
0552 /* FSE_getMaxNbBits() :
0553  * Approximate maximum cost of a symbol, in bits.
0554  * Fractional get rounded up (i.e : a symbol with a normalized frequency of 3 gives the same result as a frequency of 2)
0555  * note 1 : assume symbolValue is valid (<= maxSymbolValue)
0556  * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */
0557 MEM_STATIC U32 FSE_getMaxNbBits(const void* symbolTTPtr, U32 symbolValue)
0558 {
0559     const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;
0560     return (symbolTT[symbolValue].deltaNbBits + ((1<<16)-1)) >> 16;
0561 }
0562 
0563 /* FSE_bitCost() :
0564  * Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits)
0565  * note 1 : assume symbolValue is valid (<= maxSymbolValue)
0566  * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */
0567 MEM_STATIC U32 FSE_bitCost(const void* symbolTTPtr, U32 tableLog, U32 symbolValue, U32 accuracyLog)
0568 {
0569     const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;
0570     U32 const minNbBits = symbolTT[symbolValue].deltaNbBits >> 16;
0571     U32 const threshold = (minNbBits+1) << 16;
0572     assert(tableLog < 16);
0573     assert(accuracyLog < 31-tableLog);  /* ensure enough room for renormalization double shift */
0574     {   U32 const tableSize = 1 << tableLog;
0575         U32 const deltaFromThreshold = threshold - (symbolTT[symbolValue].deltaNbBits + tableSize);
0576         U32 const normalizedDeltaFromThreshold = (deltaFromThreshold << accuracyLog) >> tableLog;   /* linear interpolation (very approximate) */
0577         U32 const bitMultiplier = 1 << accuracyLog;
0578         assert(symbolTT[symbolValue].deltaNbBits + tableSize <= threshold);
0579         assert(normalizedDeltaFromThreshold <= bitMultiplier);
0580         return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold;
0581     }
0582 }
0583 
0584 
0585 /* ======    Decompression    ====== */
0586 
0587 typedef struct {
0588     U16 tableLog;
0589     U16 fastMode;
0590 } FSE_DTableHeader;   /* sizeof U32 */
0591 
0592 typedef struct
0593 {
0594     unsigned short newState;
0595     unsigned char  symbol;
0596     unsigned char  nbBits;
0597 } FSE_decode_t;   /* size == U32 */
0598 
0599 MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt)
0600 {
0601     const void* ptr = dt;
0602     const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr;
0603     DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
0604     BIT_reloadDStream(bitD);
0605     DStatePtr->table = dt + 1;
0606 }
0607 
0608 MEM_STATIC BYTE FSE_peekSymbol(const FSE_DState_t* DStatePtr)
0609 {
0610     FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
0611     return DInfo.symbol;
0612 }
0613 
0614 MEM_STATIC void FSE_updateState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
0615 {
0616     FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
0617     U32 const nbBits = DInfo.nbBits;
0618     size_t const lowBits = BIT_readBits(bitD, nbBits);
0619     DStatePtr->state = DInfo.newState + lowBits;
0620 }
0621 
0622 MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
0623 {
0624     FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
0625     U32 const nbBits = DInfo.nbBits;
0626     BYTE const symbol = DInfo.symbol;
0627     size_t const lowBits = BIT_readBits(bitD, nbBits);
0628 
0629     DStatePtr->state = DInfo.newState + lowBits;
0630     return symbol;
0631 }
0632 
0633 /*! FSE_decodeSymbolFast() :
0634     unsafe, only works if no symbol has a probability > 50% */
0635 MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
0636 {
0637     FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
0638     U32 const nbBits = DInfo.nbBits;
0639     BYTE const symbol = DInfo.symbol;
0640     size_t const lowBits = BIT_readBitsFast(bitD, nbBits);
0641 
0642     DStatePtr->state = DInfo.newState + lowBits;
0643     return symbol;
0644 }
0645 
0646 MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
0647 {
0648     return DStatePtr->state == 0;
0649 }
0650 
0651 
0652 
0653 #ifndef FSE_COMMONDEFS_ONLY
0654 
0655 /* **************************************************************
0656 *  Tuning parameters
0657 ****************************************************************/
0658 /*!MEMORY_USAGE :
0659 *  Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
0660 *  Increasing memory usage improves compression ratio
0661 *  Reduced memory usage can improve speed, due to cache effect
0662 *  Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
0663 #ifndef FSE_MAX_MEMORY_USAGE
0664 #  define FSE_MAX_MEMORY_USAGE 14
0665 #endif
0666 #ifndef FSE_DEFAULT_MEMORY_USAGE
0667 #  define FSE_DEFAULT_MEMORY_USAGE 13
0668 #endif
0669 #if (FSE_DEFAULT_MEMORY_USAGE > FSE_MAX_MEMORY_USAGE)
0670 #  error "FSE_DEFAULT_MEMORY_USAGE must be <= FSE_MAX_MEMORY_USAGE"
0671 #endif
0672 
0673 /*!FSE_MAX_SYMBOL_VALUE :
0674 *  Maximum symbol value authorized.
0675 *  Required for proper stack allocation */
0676 #ifndef FSE_MAX_SYMBOL_VALUE
0677 #  define FSE_MAX_SYMBOL_VALUE 255
0678 #endif
0679 
0680 /* **************************************************************
0681 *  template functions type & suffix
0682 ****************************************************************/
0683 #define FSE_FUNCTION_TYPE BYTE
0684 #define FSE_FUNCTION_EXTENSION
0685 #define FSE_DECODE_TYPE FSE_decode_t
0686 
0687 
0688 #endif   /* !FSE_COMMONDEFS_ONLY */
0689 
0690 
0691 /* ***************************************************************
0692 *  Constants
0693 *****************************************************************/
0694 #define FSE_MAX_TABLELOG  (FSE_MAX_MEMORY_USAGE-2)
0695 #define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
0696 #define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
0697 #define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
0698 #define FSE_MIN_TABLELOG 5
0699 
0700 #define FSE_TABLELOG_ABSOLUTE_MAX 15
0701 #if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
0702 #  error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
0703 #endif
0704 
0705 #define FSE_TABLESTEP(tableSize) (((tableSize)>>1) + ((tableSize)>>3) + 3)
0706 
0707 
0708 #endif /* FSE_STATIC_LINKING_ONLY */
0709 
0710