entropy_common.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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) {
  62. /* This function only works when hbSize >= 4 */
  63. char buffer[4];
  64. memset(buffer, 0, sizeof(buffer));
  65. memcpy(buffer, headerBuffer, hbSize);
  66. { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
  67. buffer, sizeof(buffer));
  68. if (FSE_isError(countSize)) return countSize;
  69. if (countSize > hbSize) return ERROR(corruption_detected);
  70. return countSize;
  71. } }
  72. assert(hbSize >= 4);
  73. /* init */
  74. memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */
  75. bitStream = MEM_readLE32(ip);
  76. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  77. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  78. bitStream >>= 4;
  79. bitCount = 4;
  80. *tableLogPtr = nbBits;
  81. remaining = (1<<nbBits)+1;
  82. threshold = 1<<nbBits;
  83. nbBits++;
  84. while ((remaining>1) & (charnum<=*maxSVPtr)) {
  85. if (previous0) {
  86. unsigned n0 = charnum;
  87. while ((bitStream & 0xFFFF) == 0xFFFF) {
  88. n0 += 24;
  89. if (ip < iend-5) {
  90. ip += 2;
  91. bitStream = MEM_readLE32(ip) >> bitCount;
  92. } else {
  93. bitStream >>= 16;
  94. bitCount += 16;
  95. } }
  96. while ((bitStream & 3) == 3) {
  97. n0 += 3;
  98. bitStream >>= 2;
  99. bitCount += 2;
  100. }
  101. n0 += bitStream & 3;
  102. bitCount += 2;
  103. if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
  104. while (charnum < n0) normalizedCounter[charnum++] = 0;
  105. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  106. assert((bitCount >> 3) <= 3); /* For first condition to work */
  107. ip += bitCount>>3;
  108. bitCount &= 7;
  109. bitStream = MEM_readLE32(ip) >> bitCount;
  110. } else {
  111. bitStream >>= 2;
  112. } }
  113. { int const max = (2*threshold-1) - remaining;
  114. int count;
  115. if ((bitStream & (threshold-1)) < (U32)max) {
  116. count = bitStream & (threshold-1);
  117. bitCount += nbBits-1;
  118. } else {
  119. count = bitStream & (2*threshold-1);
  120. if (count >= threshold) count -= max;
  121. bitCount += nbBits;
  122. }
  123. count--; /* extra accuracy */
  124. remaining -= count < 0 ? -count : count; /* -1 means +1 */
  125. normalizedCounter[charnum++] = (short)count;
  126. previous0 = !count;
  127. while (remaining < threshold) {
  128. nbBits--;
  129. threshold >>= 1;
  130. }
  131. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  132. ip += bitCount>>3;
  133. bitCount &= 7;
  134. } else {
  135. bitCount -= (int)(8 * (iend - 4 - ip));
  136. ip = iend - 4;
  137. }
  138. bitStream = MEM_readLE32(ip) >> (bitCount & 31);
  139. } } /* while ((remaining>1) & (charnum<=*maxSVPtr)) */
  140. if (remaining != 1) return ERROR(corruption_detected);
  141. if (bitCount > 32) return ERROR(corruption_detected);
  142. *maxSVPtr = charnum-1;
  143. ip += (bitCount+7)>>3;
  144. return ip-istart;
  145. }
  146. /*! HUF_readStats() :
  147. Read compact Huffman tree, saved by HUF_writeCTable().
  148. `huffWeight` is destination buffer.
  149. `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
  150. @return : size read from `src` , or an error Code .
  151. Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
  152. */
  153. size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  154. U32* nbSymbolsPtr, U32* tableLogPtr,
  155. const void* src, size_t srcSize)
  156. {
  157. U32 weightTotal;
  158. const BYTE* ip = (const BYTE*) src;
  159. size_t iSize;
  160. size_t oSize;
  161. if (!srcSize) return ERROR(srcSize_wrong);
  162. iSize = ip[0];
  163. /* memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
  164. if (iSize >= 128) { /* special header */
  165. oSize = iSize - 127;
  166. iSize = ((oSize+1)/2);
  167. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  168. if (oSize >= hwSize) return ERROR(corruption_detected);
  169. ip += 1;
  170. { U32 n;
  171. for (n=0; n<oSize; n+=2) {
  172. huffWeight[n] = ip[n/2] >> 4;
  173. huffWeight[n+1] = ip[n/2] & 15;
  174. } } }
  175. else { /* header compressed with FSE (normal case) */
  176. FSE_DTable fseWorkspace[FSE_DTABLE_SIZE_U32(6)]; /* 6 is max possible tableLog for HUF header (maybe even 5, to be tested) */
  177. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  178. oSize = FSE_decompress_wksp(huffWeight, hwSize-1, ip+1, iSize, fseWorkspace, 6); /* max (hwSize-1) values decoded, as last one is implied */
  179. if (FSE_isError(oSize)) return oSize;
  180. }
  181. /* collect weight stats */
  182. memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
  183. weightTotal = 0;
  184. { U32 n; for (n=0; n<oSize; n++) {
  185. if (huffWeight[n] >= HUF_TABLELOG_MAX) return ERROR(corruption_detected);
  186. rankStats[huffWeight[n]]++;
  187. weightTotal += (1 << huffWeight[n]) >> 1;
  188. } }
  189. if (weightTotal == 0) return ERROR(corruption_detected);
  190. /* get last non-null symbol weight (implied, total must be 2^n) */
  191. { U32 const tableLog = BIT_highbit32(weightTotal) + 1;
  192. if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
  193. *tableLogPtr = tableLog;
  194. /* determine last weight */
  195. { U32 const total = 1 << tableLog;
  196. U32 const rest = total - weightTotal;
  197. U32 const verif = 1 << BIT_highbit32(rest);
  198. U32 const lastWeight = BIT_highbit32(rest) + 1;
  199. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  200. huffWeight[oSize] = (BYTE)lastWeight;
  201. rankStats[lastWeight]++;
  202. } }
  203. /* check tree construction validity */
  204. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  205. /* results */
  206. *nbSymbolsPtr = (U32)(oSize+1);
  207. return iSize+1;
  208. }