huf.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /* ******************************************************************
  2. * huff0 huffman codec,
  3. * part of Finite State Entropy library
  4. * Copyright (c) Meta Platforms, Inc. and affiliates.
  5. *
  6. * You can contact the author at :
  7. * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  8. *
  9. * This source code is licensed under both the BSD-style license (found in the
  10. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  11. * in the COPYING file in the root directory of this source tree).
  12. * You may select, at your option, one of the above-listed licenses.
  13. ****************************************************************** */
  14. #if defined (__cplusplus)
  15. extern "C" {
  16. #endif
  17. #ifndef HUF_H_298734234
  18. #define HUF_H_298734234
  19. /* *** Dependencies *** */
  20. #include "zstd_deps.h" /* size_t */
  21. #include "mem.h" /* U32 */
  22. #define FSE_STATIC_LINKING_ONLY
  23. #include "fse.h"
  24. /* *** Tool functions *** */
  25. #define HUF_BLOCKSIZE_MAX (128 * 1024) /**< maximum input size for a single block compressed with HUF_compress */
  26. size_t HUF_compressBound(size_t size); /**< maximum compressed size (worst case) */
  27. /* Error Management */
  28. unsigned HUF_isError(size_t code); /**< tells if a return value is an error code */
  29. const char* HUF_getErrorName(size_t code); /**< provides error code string (useful for debugging) */
  30. #define HUF_WORKSPACE_SIZE ((8 << 10) + 512 /* sorting scratch space */)
  31. #define HUF_WORKSPACE_SIZE_U64 (HUF_WORKSPACE_SIZE / sizeof(U64))
  32. /* *** Constants *** */
  33. #define HUF_TABLELOG_MAX 12 /* max runtime value of tableLog (due to static allocation); can be modified up to HUF_TABLELOG_ABSOLUTEMAX */
  34. #define HUF_TABLELOG_DEFAULT 11 /* default tableLog value when none specified */
  35. #define HUF_SYMBOLVALUE_MAX 255
  36. #define HUF_TABLELOG_ABSOLUTEMAX 12 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
  37. #if (HUF_TABLELOG_MAX > HUF_TABLELOG_ABSOLUTEMAX)
  38. # error "HUF_TABLELOG_MAX is too large !"
  39. #endif
  40. /* ****************************************
  41. * Static allocation
  42. ******************************************/
  43. /* HUF buffer bounds */
  44. #define HUF_CTABLEBOUND 129
  45. #define HUF_BLOCKBOUND(size) (size + (size>>8) + 8) /* only true when incompressible is pre-filtered with fast heuristic */
  46. #define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size)) /* Macro version, useful for static allocation */
  47. /* static allocation of HUF's Compression Table */
  48. /* this is a private definition, just exposed for allocation and strict aliasing purpose. never EVER access its members directly */
  49. typedef size_t HUF_CElt; /* consider it an incomplete type */
  50. #define HUF_CTABLE_SIZE_ST(maxSymbolValue) ((maxSymbolValue)+2) /* Use tables of size_t, for proper alignment */
  51. #define HUF_CTABLE_SIZE(maxSymbolValue) (HUF_CTABLE_SIZE_ST(maxSymbolValue) * sizeof(size_t))
  52. #define HUF_CREATE_STATIC_CTABLE(name, maxSymbolValue) \
  53. HUF_CElt name[HUF_CTABLE_SIZE_ST(maxSymbolValue)] /* no final ; */
  54. /* static allocation of HUF's DTable */
  55. typedef U32 HUF_DTable;
  56. #define HUF_DTABLE_SIZE(maxTableLog) (1 + (1<<(maxTableLog)))
  57. #define HUF_CREATE_STATIC_DTABLEX1(DTable, maxTableLog) \
  58. HUF_DTable DTable[HUF_DTABLE_SIZE((maxTableLog)-1)] = { ((U32)((maxTableLog)-1) * 0x01000001) }
  59. #define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
  60. HUF_DTable DTable[HUF_DTABLE_SIZE(maxTableLog)] = { ((U32)(maxTableLog) * 0x01000001) }
  61. /* ****************************************
  62. * Advanced decompression functions
  63. ******************************************/
  64. /**
  65. * Huffman flags bitset.
  66. * For all flags, 0 is the default value.
  67. */
  68. typedef enum {
  69. /**
  70. * If compiled with DYNAMIC_BMI2: Set flag only if the CPU supports BMI2 at runtime.
  71. * Otherwise: Ignored.
  72. */
  73. HUF_flags_bmi2 = (1 << 0),
  74. /**
  75. * If set: Test possible table depths to find the one that produces the smallest header + encoded size.
  76. * If unset: Use heuristic to find the table depth.
  77. */
  78. HUF_flags_optimalDepth = (1 << 1),
  79. /**
  80. * If set: If the previous table can encode the input, always reuse the previous table.
  81. * If unset: If the previous table can encode the input, reuse the previous table if it results in a smaller output.
  82. */
  83. HUF_flags_preferRepeat = (1 << 2),
  84. /**
  85. * If set: Sample the input and check if the sample is uncompressible, if it is then don't attempt to compress.
  86. * If unset: Always histogram the entire input.
  87. */
  88. HUF_flags_suspectUncompressible = (1 << 3),
  89. /**
  90. * If set: Don't use assembly implementations
  91. * If unset: Allow using assembly implementations
  92. */
  93. HUF_flags_disableAsm = (1 << 4),
  94. /**
  95. * If set: Don't use the fast decoding loop, always use the fallback decoding loop.
  96. * If unset: Use the fast decoding loop when possible.
  97. */
  98. HUF_flags_disableFast = (1 << 5)
  99. } HUF_flags_e;
  100. /* ****************************************
  101. * HUF detailed API
  102. * ****************************************/
  103. #define HUF_OPTIMAL_DEPTH_THRESHOLD ZSTD_btultra
  104. /*! HUF_compress() does the following:
  105. * 1. count symbol occurrence from source[] into table count[] using FSE_count() (exposed within "fse.h")
  106. * 2. (optional) refine tableLog using HUF_optimalTableLog()
  107. * 3. build Huffman table from count using HUF_buildCTable()
  108. * 4. save Huffman table to memory buffer using HUF_writeCTable()
  109. * 5. encode the data stream using HUF_compress4X_usingCTable()
  110. *
  111. * The following API allows targeting specific sub-functions for advanced tasks.
  112. * For example, it's possible to compress several blocks using the same 'CTable',
  113. * or to save and regenerate 'CTable' using external methods.
  114. */
  115. unsigned HUF_minTableLog(unsigned symbolCardinality);
  116. unsigned HUF_cardinality(const unsigned* count, unsigned maxSymbolValue);
  117. unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, void* workSpace,
  118. size_t wkspSize, HUF_CElt* table, const unsigned* count, int flags); /* table is used as scratch space for building and testing tables, not a return value */
  119. size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize, const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog, void* workspace, size_t workspaceSize);
  120. size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags);
  121. size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue);
  122. int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue);
  123. typedef enum {
  124. HUF_repeat_none, /**< Cannot use the previous table */
  125. HUF_repeat_check, /**< Can use the previous table but it must be checked. Note : The previous table must have been constructed by HUF_compress{1, 4}X_repeat */
  126. HUF_repeat_valid /**< Can use the previous table and it is assumed to be valid */
  127. } HUF_repeat;
  128. /** HUF_compress4X_repeat() :
  129. * Same as HUF_compress4X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.
  130. * If it uses hufTable it does not modify hufTable or repeat.
  131. * If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used.
  132. * If preferRepeat then the old table will always be used if valid.
  133. * If suspectUncompressible then some sampling checks will be run to potentially skip huffman coding */
  134. size_t HUF_compress4X_repeat(void* dst, size_t dstSize,
  135. const void* src, size_t srcSize,
  136. unsigned maxSymbolValue, unsigned tableLog,
  137. void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */
  138. HUF_CElt* hufTable, HUF_repeat* repeat, int flags);
  139. /** HUF_buildCTable_wksp() :
  140. * Same as HUF_buildCTable(), but using externally allocated scratch buffer.
  141. * `workSpace` must be aligned on 4-bytes boundaries, and its size must be >= HUF_CTABLE_WORKSPACE_SIZE.
  142. */
  143. #define HUF_CTABLE_WORKSPACE_SIZE_U32 ((4 * (HUF_SYMBOLVALUE_MAX + 1)) + 192)
  144. #define HUF_CTABLE_WORKSPACE_SIZE (HUF_CTABLE_WORKSPACE_SIZE_U32 * sizeof(unsigned))
  145. size_t HUF_buildCTable_wksp (HUF_CElt* tree,
  146. const unsigned* count, U32 maxSymbolValue, U32 maxNbBits,
  147. void* workSpace, size_t wkspSize);
  148. /*! HUF_readStats() :
  149. * Read compact Huffman tree, saved by HUF_writeCTable().
  150. * `huffWeight` is destination buffer.
  151. * @return : size read from `src` , or an error Code .
  152. * Note : Needed by HUF_readCTable() and HUF_readDTableXn() . */
  153. size_t HUF_readStats(BYTE* huffWeight, size_t hwSize,
  154. U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr,
  155. const void* src, size_t srcSize);
  156. /*! HUF_readStats_wksp() :
  157. * Same as HUF_readStats() but takes an external workspace which must be
  158. * 4-byte aligned and its size must be >= HUF_READ_STATS_WORKSPACE_SIZE.
  159. * If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0.
  160. */
  161. #define HUF_READ_STATS_WORKSPACE_SIZE_U32 FSE_DECOMPRESS_WKSP_SIZE_U32(6, HUF_TABLELOG_MAX-1)
  162. #define HUF_READ_STATS_WORKSPACE_SIZE (HUF_READ_STATS_WORKSPACE_SIZE_U32 * sizeof(unsigned))
  163. size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize,
  164. U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr,
  165. const void* src, size_t srcSize,
  166. void* workspace, size_t wkspSize,
  167. int flags);
  168. /** HUF_readCTable() :
  169. * Loading a CTable saved with HUF_writeCTable() */
  170. size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned *hasZeroWeights);
  171. /** HUF_getNbBitsFromCTable() :
  172. * Read nbBits from CTable symbolTable, for symbol `symbolValue` presumed <= HUF_SYMBOLVALUE_MAX
  173. * Note 1 : is not inlined, as HUF_CElt definition is private */
  174. U32 HUF_getNbBitsFromCTable(const HUF_CElt* symbolTable, U32 symbolValue);
  175. /*
  176. * HUF_decompress() does the following:
  177. * 1. select the decompression algorithm (X1, X2) based on pre-computed heuristics
  178. * 2. build Huffman table from save, using HUF_readDTableX?()
  179. * 3. decode 1 or 4 segments in parallel using HUF_decompress?X?_usingDTable()
  180. */
  181. /** HUF_selectDecoder() :
  182. * Tells which decoder is likely to decode faster,
  183. * based on a set of pre-computed metrics.
  184. * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 .
  185. * Assumption : 0 < dstSize <= 128 KB */
  186. U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize);
  187. /**
  188. * The minimum workspace size for the `workSpace` used in
  189. * HUF_readDTableX1_wksp() and HUF_readDTableX2_wksp().
  190. *
  191. * The space used depends on HUF_TABLELOG_MAX, ranging from ~1500 bytes when
  192. * HUF_TABLE_LOG_MAX=12 to ~1850 bytes when HUF_TABLE_LOG_MAX=15.
  193. * Buffer overflow errors may potentially occur if code modifications result in
  194. * a required workspace size greater than that specified in the following
  195. * macro.
  196. */
  197. #define HUF_DECOMPRESS_WORKSPACE_SIZE ((2 << 10) + (1 << 9))
  198. #define HUF_DECOMPRESS_WORKSPACE_SIZE_U32 (HUF_DECOMPRESS_WORKSPACE_SIZE / sizeof(U32))
  199. /* ====================== */
  200. /* single stream variants */
  201. /* ====================== */
  202. size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags);
  203. /** HUF_compress1X_repeat() :
  204. * Same as HUF_compress1X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.
  205. * If it uses hufTable it does not modify hufTable or repeat.
  206. * If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used.
  207. * If preferRepeat then the old table will always be used if valid.
  208. * If suspectUncompressible then some sampling checks will be run to potentially skip huffman coding */
  209. size_t HUF_compress1X_repeat(void* dst, size_t dstSize,
  210. const void* src, size_t srcSize,
  211. unsigned maxSymbolValue, unsigned tableLog,
  212. void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */
  213. HUF_CElt* hufTable, HUF_repeat* repeat, int flags);
  214. size_t HUF_decompress1X_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags);
  215. #ifndef HUF_FORCE_DECOMPRESS_X1
  216. size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags); /**< double-symbols decoder */
  217. #endif
  218. /* BMI2 variants.
  219. * If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0.
  220. */
  221. size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags);
  222. #ifndef HUF_FORCE_DECOMPRESS_X2
  223. size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags);
  224. #endif
  225. size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags);
  226. size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags);
  227. #ifndef HUF_FORCE_DECOMPRESS_X2
  228. size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags);
  229. #endif
  230. #ifndef HUF_FORCE_DECOMPRESS_X1
  231. size_t HUF_readDTableX2_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags);
  232. #endif
  233. #endif /* HUF_H_298734234 */
  234. #if defined (__cplusplus)
  235. }
  236. #endif