fse_decompress.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /* ******************************************************************
  2. FSE : Finite State Entropy decoder
  3. Copyright (C) 2013-2015, Yann Collet.
  4. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are
  7. met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above
  11. copyright notice, this list of conditions and the following disclaimer
  12. in the documentation and/or other materials provided with the
  13. distribution.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  16. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  17. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  18. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  19. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  20. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. You can contact the author at :
  26. - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  27. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  28. ****************************************************************** */
  29. /* **************************************************************
  30. * Compiler specifics
  31. ****************************************************************/
  32. #ifdef _MSC_VER /* Visual Studio */
  33. # define FORCE_INLINE static __forceinline
  34. # include <intrin.h> /* For Visual 2005 */
  35. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  36. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  37. #else
  38. # ifdef __GNUC__
  39. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  40. # define FORCE_INLINE static inline __attribute__((always_inline))
  41. # else
  42. # define FORCE_INLINE static inline
  43. # endif
  44. #endif
  45. /* **************************************************************
  46. * Includes
  47. ****************************************************************/
  48. #include <stdlib.h> /* malloc, free, qsort */
  49. #include <string.h> /* memcpy, memset */
  50. #include <stdio.h> /* printf (debug) */
  51. #include "bitstream.h"
  52. #include "fse_static.h"
  53. /* **************************************************************
  54. * Error Management
  55. ****************************************************************/
  56. #define FSE_isError ERR_isError
  57. #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  58. /* **************************************************************
  59. * Complex types
  60. ****************************************************************/
  61. typedef U32 DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];
  62. /* **************************************************************
  63. * Templates
  64. ****************************************************************/
  65. /*
  66. designed to be included
  67. for type-specific functions (template emulation in C)
  68. Objective is to write these functions only once, for improved maintenance
  69. */
  70. /* safety checks */
  71. #ifndef FSE_FUNCTION_EXTENSION
  72. # error "FSE_FUNCTION_EXTENSION must be defined"
  73. #endif
  74. #ifndef FSE_FUNCTION_TYPE
  75. # error "FSE_FUNCTION_TYPE must be defined"
  76. #endif
  77. /* Function names */
  78. #define FSE_CAT(X,Y) X##Y
  79. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  80. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  81. /* Function templates */
  82. FSE_DTable* FSE_createDTable (unsigned tableLog)
  83. {
  84. if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX;
  85. return (FSE_DTable*)malloc( FSE_DTABLE_SIZE_U32(tableLog) * sizeof (U32) );
  86. }
  87. void FSE_freeDTable (FSE_DTable* dt)
  88. {
  89. free(dt);
  90. }
  91. size_t FSE_buildDTable(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  92. {
  93. void* const tdPtr = dt+1; /* because *dt is unsigned, 32-bits aligned on 32-bits */
  94. FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (tdPtr);
  95. U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];
  96. U32 const maxSV1 = maxSymbolValue + 1;
  97. U32 const tableSize = 1 << tableLog;
  98. U32 highThreshold = tableSize-1;
  99. /* Sanity Checks */
  100. if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
  101. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  102. /* Init, lay down lowprob symbols */
  103. { FSE_DTableHeader DTableH;
  104. DTableH.tableLog = (U16)tableLog;
  105. DTableH.fastMode = 1;
  106. { S16 const largeLimit= (S16)(1 << (tableLog-1));
  107. U32 s;
  108. for (s=0; s<maxSV1; s++) {
  109. if (normalizedCounter[s]==-1) {
  110. tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
  111. symbolNext[s] = 1;
  112. } else {
  113. if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
  114. symbolNext[s] = normalizedCounter[s];
  115. } } }
  116. memcpy(dt, &DTableH, sizeof(DTableH));
  117. }
  118. /* Spread symbols */
  119. { U32 const tableMask = tableSize-1;
  120. U32 const step = FSE_TABLESTEP(tableSize);
  121. U32 s, position = 0;
  122. for (s=0; s<maxSV1; s++) {
  123. int i;
  124. for (i=0; i<normalizedCounter[s]; i++) {
  125. tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
  126. position = (position + step) & tableMask;
  127. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  128. } }
  129. if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  130. }
  131. /* Build Decoding table */
  132. { U32 u;
  133. for (u=0; u<tableSize; u++) {
  134. FSE_FUNCTION_TYPE const symbol = (FSE_FUNCTION_TYPE)(tableDecode[u].symbol);
  135. U16 nextState = symbolNext[symbol]++;
  136. tableDecode[u].nbBits = (BYTE) (tableLog - BIT_highbit32 ((U32)nextState) );
  137. tableDecode[u].newState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
  138. } }
  139. return 0;
  140. }
  141. #ifndef FSE_COMMONDEFS_ONLY
  142. /*-*******************************************************
  143. * Decompression (Byte symbols)
  144. *********************************************************/
  145. size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
  146. {
  147. void* ptr = dt;
  148. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  149. void* dPtr = dt + 1;
  150. FSE_decode_t* const cell = (FSE_decode_t*)dPtr;
  151. DTableH->tableLog = 0;
  152. DTableH->fastMode = 0;
  153. cell->newState = 0;
  154. cell->symbol = symbolValue;
  155. cell->nbBits = 0;
  156. return 0;
  157. }
  158. size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
  159. {
  160. void* ptr = dt;
  161. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  162. void* dPtr = dt + 1;
  163. FSE_decode_t* const dinfo = (FSE_decode_t*)dPtr;
  164. const unsigned tableSize = 1 << nbBits;
  165. const unsigned tableMask = tableSize - 1;
  166. const unsigned maxSV1 = tableMask+1;
  167. unsigned s;
  168. /* Sanity checks */
  169. if (nbBits < 1) return ERROR(GENERIC); /* min size */
  170. /* Build Decoding Table */
  171. DTableH->tableLog = (U16)nbBits;
  172. DTableH->fastMode = 1;
  173. for (s=0; s<maxSV1; s++) {
  174. dinfo[s].newState = 0;
  175. dinfo[s].symbol = (BYTE)s;
  176. dinfo[s].nbBits = (BYTE)nbBits;
  177. }
  178. return 0;
  179. }
  180. FORCE_INLINE size_t FSE_decompress_usingDTable_generic(
  181. void* dst, size_t maxDstSize,
  182. const void* cSrc, size_t cSrcSize,
  183. const FSE_DTable* dt, const unsigned fast)
  184. {
  185. BYTE* const ostart = (BYTE*) dst;
  186. BYTE* op = ostart;
  187. BYTE* const omax = op + maxDstSize;
  188. BYTE* const olimit = omax-3;
  189. BIT_DStream_t bitD;
  190. FSE_DState_t state1;
  191. FSE_DState_t state2;
  192. /* Init */
  193. { size_t const errorCode = BIT_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */
  194. if (FSE_isError(errorCode)) return errorCode; }
  195. FSE_initDState(&state1, &bitD, dt);
  196. FSE_initDState(&state2, &bitD, dt);
  197. #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
  198. /* 4 symbols per loop */
  199. for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) && (op<olimit) ; op+=4) {
  200. op[0] = FSE_GETSYMBOL(&state1);
  201. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  202. BIT_reloadDStream(&bitD);
  203. op[1] = FSE_GETSYMBOL(&state2);
  204. if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  205. { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }
  206. op[2] = FSE_GETSYMBOL(&state1);
  207. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  208. BIT_reloadDStream(&bitD);
  209. op[3] = FSE_GETSYMBOL(&state2);
  210. }
  211. /* tail */
  212. /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
  213. while (1) {
  214. if (op>(omax-2)) return ERROR(dstSize_tooSmall);
  215. *op++ = FSE_GETSYMBOL(&state1);
  216. if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
  217. *op++ = FSE_GETSYMBOL(&state2);
  218. break;
  219. }
  220. if (op>(omax-2)) return ERROR(dstSize_tooSmall);
  221. *op++ = FSE_GETSYMBOL(&state2);
  222. if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
  223. *op++ = FSE_GETSYMBOL(&state1);
  224. break;
  225. } }
  226. return op-ostart;
  227. }
  228. size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
  229. const void* cSrc, size_t cSrcSize,
  230. const FSE_DTable* dt)
  231. {
  232. const void* ptr = dt;
  233. const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)ptr;
  234. const U32 fastMode = DTableH->fastMode;
  235. /* select fast mode (static) */
  236. if (fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
  237. return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
  238. }
  239. size_t FSE_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  240. {
  241. const BYTE* const istart = (const BYTE*)cSrc;
  242. const BYTE* ip = istart;
  243. short counting[FSE_MAX_SYMBOL_VALUE+1];
  244. DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
  245. unsigned tableLog;
  246. unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  247. if (cSrcSize<2) return ERROR(srcSize_wrong); /* too small input size */
  248. /* normal FSE decoding mode */
  249. { size_t const NCountLength = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
  250. if (FSE_isError(NCountLength)) return NCountLength;
  251. if (NCountLength >= cSrcSize) return ERROR(srcSize_wrong); /* too small input size */
  252. ip += NCountLength;
  253. cSrcSize -= NCountLength;
  254. }
  255. { size_t const errorCode = FSE_buildDTable (dt, counting, maxSymbolValue, tableLog);
  256. if (FSE_isError(errorCode)) return errorCode; }
  257. return FSE_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt); /* always return, even if it is an error code */
  258. }
  259. #endif /* FSE_COMMONDEFS_ONLY */