fse_decompress.c 12 KB

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