fse_decompress.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /* ******************************************************************
  2. * FSE : Finite State Entropy decoder
  3. * Copyright (c) Meta Platforms, Inc. and affiliates.
  4. *
  5. * You can contact the author at :
  6. * - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  7. * - Public forum : https://groups.google.com/forum/#!forum/lz4c
  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. /* **************************************************************
  15. * Includes
  16. ****************************************************************/
  17. #include "debug.h" /* assert */
  18. #include "bitstream.h"
  19. #include "compiler.h"
  20. #define FSE_STATIC_LINKING_ONLY
  21. #include "fse.h"
  22. #include "error_private.h"
  23. #include "zstd_deps.h" /* ZSTD_memcpy */
  24. #include "bits.h" /* ZSTD_highbit32 */
  25. /* **************************************************************
  26. * Error Management
  27. ****************************************************************/
  28. #define FSE_isError ERR_isError
  29. #define FSE_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) /* use only *after* variable declarations */
  30. /* **************************************************************
  31. * Templates
  32. ****************************************************************/
  33. /*
  34. designed to be included
  35. for type-specific functions (template emulation in C)
  36. Objective is to write these functions only once, for improved maintenance
  37. */
  38. /* safety checks */
  39. #ifndef FSE_FUNCTION_EXTENSION
  40. # error "FSE_FUNCTION_EXTENSION must be defined"
  41. #endif
  42. #ifndef FSE_FUNCTION_TYPE
  43. # error "FSE_FUNCTION_TYPE must be defined"
  44. #endif
  45. /* Function names */
  46. #define FSE_CAT(X,Y) X##Y
  47. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  48. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  49. static size_t FSE_buildDTable_internal(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize)
  50. {
  51. void* const tdPtr = dt+1; /* because *dt is unsigned, 32-bits aligned on 32-bits */
  52. FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (tdPtr);
  53. U16* symbolNext = (U16*)workSpace;
  54. BYTE* spread = (BYTE*)(symbolNext + maxSymbolValue + 1);
  55. U32 const maxSV1 = maxSymbolValue + 1;
  56. U32 const tableSize = 1 << tableLog;
  57. U32 highThreshold = tableSize-1;
  58. /* Sanity Checks */
  59. if (FSE_BUILD_DTABLE_WKSP_SIZE(tableLog, maxSymbolValue) > wkspSize) return ERROR(maxSymbolValue_tooLarge);
  60. if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
  61. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  62. /* Init, lay down lowprob symbols */
  63. { FSE_DTableHeader DTableH;
  64. DTableH.tableLog = (U16)tableLog;
  65. DTableH.fastMode = 1;
  66. { S16 const largeLimit= (S16)(1 << (tableLog-1));
  67. U32 s;
  68. for (s=0; s<maxSV1; s++) {
  69. if (normalizedCounter[s]==-1) {
  70. tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
  71. symbolNext[s] = 1;
  72. } else {
  73. if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
  74. symbolNext[s] = (U16)normalizedCounter[s];
  75. } } }
  76. ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));
  77. }
  78. /* Spread symbols */
  79. if (highThreshold == tableSize - 1) {
  80. size_t const tableMask = tableSize-1;
  81. size_t const step = FSE_TABLESTEP(tableSize);
  82. /* First lay down the symbols in order.
  83. * We use a uint64_t to lay down 8 bytes at a time. This reduces branch
  84. * misses since small blocks generally have small table logs, so nearly
  85. * all symbols have counts <= 8. We ensure we have 8 bytes at the end of
  86. * our buffer to handle the over-write.
  87. */
  88. { U64 const add = 0x0101010101010101ull;
  89. size_t pos = 0;
  90. U64 sv = 0;
  91. U32 s;
  92. for (s=0; s<maxSV1; ++s, sv += add) {
  93. int i;
  94. int const n = normalizedCounter[s];
  95. MEM_write64(spread + pos, sv);
  96. for (i = 8; i < n; i += 8) {
  97. MEM_write64(spread + pos + i, sv);
  98. }
  99. pos += (size_t)n;
  100. } }
  101. /* Now we spread those positions across the table.
  102. * The benefit of doing it in two stages is that we avoid the
  103. * variable size inner loop, which caused lots of branch misses.
  104. * Now we can run through all the positions without any branch misses.
  105. * We unroll the loop twice, since that is what empirically worked best.
  106. */
  107. {
  108. size_t position = 0;
  109. size_t s;
  110. size_t const unroll = 2;
  111. assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
  112. for (s = 0; s < (size_t)tableSize; s += unroll) {
  113. size_t u;
  114. for (u = 0; u < unroll; ++u) {
  115. size_t const uPosition = (position + (u * step)) & tableMask;
  116. tableDecode[uPosition].symbol = spread[s + u];
  117. }
  118. position = (position + (unroll * step)) & tableMask;
  119. }
  120. assert(position == 0);
  121. }
  122. } else {
  123. U32 const tableMask = tableSize-1;
  124. U32 const step = FSE_TABLESTEP(tableSize);
  125. U32 s, position = 0;
  126. for (s=0; s<maxSV1; s++) {
  127. int i;
  128. for (i=0; i<normalizedCounter[s]; i++) {
  129. tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
  130. position = (position + step) & tableMask;
  131. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  132. } }
  133. if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  134. }
  135. /* Build Decoding table */
  136. { U32 u;
  137. for (u=0; u<tableSize; u++) {
  138. FSE_FUNCTION_TYPE const symbol = (FSE_FUNCTION_TYPE)(tableDecode[u].symbol);
  139. U32 const nextState = symbolNext[symbol]++;
  140. tableDecode[u].nbBits = (BYTE) (tableLog - ZSTD_highbit32(nextState) );
  141. tableDecode[u].newState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
  142. } }
  143. return 0;
  144. }
  145. size_t FSE_buildDTable_wksp(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize)
  146. {
  147. return FSE_buildDTable_internal(dt, normalizedCounter, maxSymbolValue, tableLog, workSpace, wkspSize);
  148. }
  149. #ifndef FSE_COMMONDEFS_ONLY
  150. /*-*******************************************************
  151. * Decompression (Byte symbols)
  152. *********************************************************/
  153. FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic(
  154. void* dst, size_t maxDstSize,
  155. const void* cSrc, size_t cSrcSize,
  156. const FSE_DTable* dt, const unsigned fast)
  157. {
  158. BYTE* const ostart = (BYTE*) dst;
  159. BYTE* op = ostart;
  160. BYTE* const omax = op + maxDstSize;
  161. BYTE* const olimit = omax-3;
  162. BIT_DStream_t bitD;
  163. FSE_DState_t state1;
  164. FSE_DState_t state2;
  165. /* Init */
  166. CHECK_F(BIT_initDStream(&bitD, cSrc, cSrcSize));
  167. FSE_initDState(&state1, &bitD, dt);
  168. FSE_initDState(&state2, &bitD, dt);
  169. #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
  170. /* 4 symbols per loop */
  171. for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) & (op<olimit) ; op+=4) {
  172. op[0] = FSE_GETSYMBOL(&state1);
  173. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  174. BIT_reloadDStream(&bitD);
  175. op[1] = FSE_GETSYMBOL(&state2);
  176. if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  177. { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }
  178. op[2] = FSE_GETSYMBOL(&state1);
  179. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  180. BIT_reloadDStream(&bitD);
  181. op[3] = FSE_GETSYMBOL(&state2);
  182. }
  183. /* tail */
  184. /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
  185. while (1) {
  186. if (op>(omax-2)) return ERROR(dstSize_tooSmall);
  187. *op++ = FSE_GETSYMBOL(&state1);
  188. if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
  189. *op++ = FSE_GETSYMBOL(&state2);
  190. break;
  191. }
  192. if (op>(omax-2)) return ERROR(dstSize_tooSmall);
  193. *op++ = FSE_GETSYMBOL(&state2);
  194. if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
  195. *op++ = FSE_GETSYMBOL(&state1);
  196. break;
  197. } }
  198. assert(op >= ostart);
  199. return (size_t)(op-ostart);
  200. }
  201. typedef struct {
  202. short ncount[FSE_MAX_SYMBOL_VALUE + 1];
  203. } FSE_DecompressWksp;
  204. FORCE_INLINE_TEMPLATE size_t FSE_decompress_wksp_body(
  205. void* dst, size_t dstCapacity,
  206. const void* cSrc, size_t cSrcSize,
  207. unsigned maxLog, void* workSpace, size_t wkspSize,
  208. int bmi2)
  209. {
  210. const BYTE* const istart = (const BYTE*)cSrc;
  211. const BYTE* ip = istart;
  212. unsigned tableLog;
  213. unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  214. FSE_DecompressWksp* const wksp = (FSE_DecompressWksp*)workSpace;
  215. size_t const dtablePos = sizeof(FSE_DecompressWksp) / sizeof(FSE_DTable);
  216. FSE_DTable* const dtable = (FSE_DTable*)workSpace + dtablePos;
  217. FSE_STATIC_ASSERT((FSE_MAX_SYMBOL_VALUE + 1) % 2 == 0);
  218. if (wkspSize < sizeof(*wksp)) return ERROR(GENERIC);
  219. /* correct offset to dtable depends on this property */
  220. FSE_STATIC_ASSERT(sizeof(FSE_DecompressWksp) % sizeof(FSE_DTable) == 0);
  221. /* normal FSE decoding mode */
  222. { size_t const NCountLength =
  223. FSE_readNCount_bmi2(wksp->ncount, &maxSymbolValue, &tableLog, istart, cSrcSize, bmi2);
  224. if (FSE_isError(NCountLength)) return NCountLength;
  225. if (tableLog > maxLog) return ERROR(tableLog_tooLarge);
  226. assert(NCountLength <= cSrcSize);
  227. ip += NCountLength;
  228. cSrcSize -= NCountLength;
  229. }
  230. if (FSE_DECOMPRESS_WKSP_SIZE(tableLog, maxSymbolValue) > wkspSize) return ERROR(tableLog_tooLarge);
  231. assert(sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog) <= wkspSize);
  232. workSpace = (BYTE*)workSpace + sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog);
  233. wkspSize -= sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog);
  234. CHECK_F( FSE_buildDTable_internal(dtable, wksp->ncount, maxSymbolValue, tableLog, workSpace, wkspSize) );
  235. {
  236. const void* ptr = dtable;
  237. const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)ptr;
  238. const U32 fastMode = DTableH->fastMode;
  239. /* select fast mode (static) */
  240. if (fastMode) return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, dtable, 1);
  241. return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, dtable, 0);
  242. }
  243. }
  244. /* Avoids the FORCE_INLINE of the _body() function. */
  245. static size_t FSE_decompress_wksp_body_default(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize)
  246. {
  247. return FSE_decompress_wksp_body(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize, 0);
  248. }
  249. #if DYNAMIC_BMI2
  250. BMI2_TARGET_ATTRIBUTE static size_t FSE_decompress_wksp_body_bmi2(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize)
  251. {
  252. return FSE_decompress_wksp_body(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize, 1);
  253. }
  254. #endif
  255. 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)
  256. {
  257. #if DYNAMIC_BMI2
  258. if (bmi2) {
  259. return FSE_decompress_wksp_body_bmi2(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize);
  260. }
  261. #endif
  262. (void)bmi2;
  263. return FSE_decompress_wksp_body_default(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize);
  264. }
  265. #endif /* FSE_COMMONDEFS_ONLY */