entropy_common.c 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /*
  2. Common functions of New Generation Entropy library
  3. Copyright (C) 2016, 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+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
  27. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  28. *************************************************************************** */
  29. /* *************************************
  30. * Dependencies
  31. ***************************************/
  32. #include "mem.h"
  33. #include "error_private.h" /* ERR_*, ERROR */
  34. #define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */
  35. #include "fse.h"
  36. #define HUF_STATIC_LINKING_ONLY /* HUF_TABLELOG_ABSOLUTEMAX */
  37. #include "huf.h"
  38. /*=== Version ===*/
  39. unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }
  40. /*=== Error Management ===*/
  41. unsigned FSE_isError(size_t code) { return ERR_isError(code); }
  42. const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }
  43. unsigned HUF_isError(size_t code) { return ERR_isError(code); }
  44. const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }
  45. /*-**************************************************************
  46. * FSE NCount encoding-decoding
  47. ****************************************************************/
  48. size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  49. const void* headerBuffer, size_t hbSize)
  50. {
  51. const BYTE* const istart = (const BYTE*) headerBuffer;
  52. const BYTE* const iend = istart + hbSize;
  53. const BYTE* ip = istart;
  54. int nbBits;
  55. int remaining;
  56. int threshold;
  57. U32 bitStream;
  58. int bitCount;
  59. unsigned charnum = 0;
  60. int previous0 = 0;
  61. if (hbSize < 4) return ERROR(srcSize_wrong);
  62. bitStream = MEM_readLE32(ip);
  63. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  64. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  65. bitStream >>= 4;
  66. bitCount = 4;
  67. *tableLogPtr = nbBits;
  68. remaining = (1<<nbBits)+1;
  69. threshold = 1<<nbBits;
  70. nbBits++;
  71. while ((remaining>1) & (charnum<=*maxSVPtr)) {
  72. if (previous0) {
  73. unsigned n0 = charnum;
  74. while ((bitStream & 0xFFFF) == 0xFFFF) {
  75. n0 += 24;
  76. if (ip < iend-5) {
  77. ip += 2;
  78. bitStream = MEM_readLE32(ip) >> bitCount;
  79. } else {
  80. bitStream >>= 16;
  81. bitCount += 16;
  82. } }
  83. while ((bitStream & 3) == 3) {
  84. n0 += 3;
  85. bitStream >>= 2;
  86. bitCount += 2;
  87. }
  88. n0 += bitStream & 3;
  89. bitCount += 2;
  90. if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
  91. while (charnum < n0) normalizedCounter[charnum++] = 0;
  92. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  93. ip += bitCount>>3;
  94. bitCount &= 7;
  95. bitStream = MEM_readLE32(ip) >> bitCount;
  96. } else {
  97. bitStream >>= 2;
  98. } }
  99. { int const max = (2*threshold-1) - remaining;
  100. int count;
  101. if ((bitStream & (threshold-1)) < (U32)max) {
  102. count = bitStream & (threshold-1);
  103. bitCount += nbBits-1;
  104. } else {
  105. count = bitStream & (2*threshold-1);
  106. if (count >= threshold) count -= max;
  107. bitCount += nbBits;
  108. }
  109. count--; /* extra accuracy */
  110. remaining -= count < 0 ? -count : count; /* -1 means +1 */
  111. normalizedCounter[charnum++] = (short)count;
  112. previous0 = !count;
  113. while (remaining < threshold) {
  114. nbBits--;
  115. threshold >>= 1;
  116. }
  117. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  118. ip += bitCount>>3;
  119. bitCount &= 7;
  120. } else {
  121. bitCount -= (int)(8 * (iend - 4 - ip));
  122. ip = iend - 4;
  123. }
  124. bitStream = MEM_readLE32(ip) >> (bitCount & 31);
  125. } } /* while ((remaining>1) & (charnum<=*maxSVPtr)) */
  126. if (remaining != 1) return ERROR(corruption_detected);
  127. if (bitCount > 32) return ERROR(corruption_detected);
  128. *maxSVPtr = charnum-1;
  129. ip += (bitCount+7)>>3;
  130. return ip-istart;
  131. }
  132. /*! HUF_readStats() :
  133. Read compact Huffman tree, saved by HUF_writeCTable().
  134. `huffWeight` is destination buffer.
  135. `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
  136. @return : size read from `src` , or an error Code .
  137. Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
  138. */
  139. size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  140. U32* nbSymbolsPtr, U32* tableLogPtr,
  141. const void* src, size_t srcSize)
  142. {
  143. U32 weightTotal;
  144. const BYTE* ip = (const BYTE*) src;
  145. size_t iSize;
  146. size_t oSize;
  147. if (!srcSize) return ERROR(srcSize_wrong);
  148. iSize = ip[0];
  149. /* memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
  150. if (iSize >= 128) { /* special header */
  151. oSize = iSize - 127;
  152. iSize = ((oSize+1)/2);
  153. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  154. if (oSize >= hwSize) return ERROR(corruption_detected);
  155. ip += 1;
  156. { U32 n;
  157. for (n=0; n<oSize; n+=2) {
  158. huffWeight[n] = ip[n/2] >> 4;
  159. huffWeight[n+1] = ip[n/2] & 15;
  160. } } }
  161. else { /* header compressed with FSE (normal case) */
  162. FSE_DTable fseWorkspace[FSE_DTABLE_SIZE_U32(6)]; /* 6 is max possible tableLog for HUF header (maybe even 5, to be tested) */
  163. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  164. oSize = FSE_decompress_wksp(huffWeight, hwSize-1, ip+1, iSize, fseWorkspace, 6); /* max (hwSize-1) values decoded, as last one is implied */
  165. if (FSE_isError(oSize)) return oSize;
  166. }
  167. /* collect weight stats */
  168. memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
  169. weightTotal = 0;
  170. { U32 n; for (n=0; n<oSize; n++) {
  171. if (huffWeight[n] >= HUF_TABLELOG_MAX) return ERROR(corruption_detected);
  172. rankStats[huffWeight[n]]++;
  173. weightTotal += (1 << huffWeight[n]) >> 1;
  174. } }
  175. if (weightTotal == 0) return ERROR(corruption_detected);
  176. /* get last non-null symbol weight (implied, total must be 2^n) */
  177. { U32 const tableLog = BIT_highbit32(weightTotal) + 1;
  178. if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
  179. *tableLogPtr = tableLog;
  180. /* determine last weight */
  181. { U32 const total = 1 << tableLog;
  182. U32 const rest = total - weightTotal;
  183. U32 const verif = 1 << BIT_highbit32(rest);
  184. U32 const lastWeight = BIT_highbit32(rest) + 1;
  185. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  186. huffWeight[oSize] = (BYTE)lastWeight;
  187. rankStats[lastWeight]++;
  188. } }
  189. /* check tree construction validity */
  190. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  191. /* results */
  192. *nbSymbolsPtr = (U32)(oSize+1);
  193. return iSize+1;
  194. }