entropy_common.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /* ******************************************************************
  2. * Common functions of New Generation Entropy library
  3. * Copyright (c) Yann Collet, Facebook, Inc.
  4. *
  5. * You can contact the author at :
  6. * - FSE+HUF 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. * Dependencies
  16. ***************************************/
  17. #include "mem.h"
  18. #include "error_private.h" /* ERR_*, ERROR */
  19. #define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */
  20. #include "fse.h"
  21. #define HUF_STATIC_LINKING_ONLY /* HUF_TABLELOG_ABSOLUTEMAX */
  22. #include "huf.h"
  23. /*=== Version ===*/
  24. unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }
  25. /*=== Error Management ===*/
  26. unsigned FSE_isError(size_t code) { return ERR_isError(code); }
  27. const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }
  28. unsigned HUF_isError(size_t code) { return ERR_isError(code); }
  29. const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }
  30. /*-**************************************************************
  31. * FSE NCount encoding-decoding
  32. ****************************************************************/
  33. static U32 FSE_ctz(U32 val)
  34. {
  35. assert(val != 0);
  36. {
  37. # if (__GNUC__ >= 3) /* GCC Intrinsic */
  38. return __builtin_ctz(val);
  39. # else /* Software version */
  40. U32 count = 0;
  41. while ((val & 1) == 0) {
  42. val >>= 1;
  43. ++count;
  44. }
  45. return count;
  46. # endif
  47. }
  48. }
  49. FORCE_INLINE_TEMPLATE
  50. size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  51. const void* headerBuffer, size_t hbSize)
  52. {
  53. const BYTE* const istart = (const BYTE*) headerBuffer;
  54. const BYTE* const iend = istart + hbSize;
  55. const BYTE* ip = istart;
  56. int nbBits;
  57. int remaining;
  58. int threshold;
  59. U32 bitStream;
  60. int bitCount;
  61. unsigned charnum = 0;
  62. unsigned const maxSV1 = *maxSVPtr + 1;
  63. int previous0 = 0;
  64. if (hbSize < 8) {
  65. /* This function only works when hbSize >= 8 */
  66. char buffer[8] = {0};
  67. ZSTD_memcpy(buffer, headerBuffer, hbSize);
  68. { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
  69. buffer, sizeof(buffer));
  70. if (FSE_isError(countSize)) return countSize;
  71. if (countSize > hbSize) return ERROR(corruption_detected);
  72. return countSize;
  73. } }
  74. assert(hbSize >= 8);
  75. /* init */
  76. ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */
  77. bitStream = MEM_readLE32(ip);
  78. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  79. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  80. bitStream >>= 4;
  81. bitCount = 4;
  82. *tableLogPtr = nbBits;
  83. remaining = (1<<nbBits)+1;
  84. threshold = 1<<nbBits;
  85. nbBits++;
  86. for (;;) {
  87. if (previous0) {
  88. /* Count the number of repeats. Each time the
  89. * 2-bit repeat code is 0b11 there is another
  90. * repeat.
  91. * Avoid UB by setting the high bit to 1.
  92. */
  93. int repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
  94. while (repeats >= 12) {
  95. charnum += 3 * 12;
  96. if (LIKELY(ip <= iend-7)) {
  97. ip += 3;
  98. } else {
  99. bitCount -= (int)(8 * (iend - 7 - ip));
  100. bitCount &= 31;
  101. ip = iend - 4;
  102. }
  103. bitStream = MEM_readLE32(ip) >> bitCount;
  104. repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
  105. }
  106. charnum += 3 * repeats;
  107. bitStream >>= 2 * repeats;
  108. bitCount += 2 * repeats;
  109. /* Add the final repeat which isn't 0b11. */
  110. assert((bitStream & 3) < 3);
  111. charnum += bitStream & 3;
  112. bitCount += 2;
  113. /* This is an error, but break and return an error
  114. * at the end, because returning out of a loop makes
  115. * it harder for the compiler to optimize.
  116. */
  117. if (charnum >= maxSV1) break;
  118. /* We don't need to set the normalized count to 0
  119. * because we already memset the whole buffer to 0.
  120. */
  121. if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  122. assert((bitCount >> 3) <= 3); /* For first condition to work */
  123. ip += bitCount>>3;
  124. bitCount &= 7;
  125. } else {
  126. bitCount -= (int)(8 * (iend - 4 - ip));
  127. bitCount &= 31;
  128. ip = iend - 4;
  129. }
  130. bitStream = MEM_readLE32(ip) >> bitCount;
  131. }
  132. {
  133. int const max = (2*threshold-1) - remaining;
  134. int count;
  135. if ((bitStream & (threshold-1)) < (U32)max) {
  136. count = bitStream & (threshold-1);
  137. bitCount += nbBits-1;
  138. } else {
  139. count = bitStream & (2*threshold-1);
  140. if (count >= threshold) count -= max;
  141. bitCount += nbBits;
  142. }
  143. count--; /* extra accuracy */
  144. /* When it matters (small blocks), this is a
  145. * predictable branch, because we don't use -1.
  146. */
  147. if (count >= 0) {
  148. remaining -= count;
  149. } else {
  150. assert(count == -1);
  151. remaining += count;
  152. }
  153. normalizedCounter[charnum++] = (short)count;
  154. previous0 = !count;
  155. assert(threshold > 1);
  156. if (remaining < threshold) {
  157. /* This branch can be folded into the
  158. * threshold update condition because we
  159. * know that threshold > 1.
  160. */
  161. if (remaining <= 1) break;
  162. nbBits = BIT_highbit32(remaining) + 1;
  163. threshold = 1 << (nbBits - 1);
  164. }
  165. if (charnum >= maxSV1) break;
  166. if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  167. ip += bitCount>>3;
  168. bitCount &= 7;
  169. } else {
  170. bitCount -= (int)(8 * (iend - 4 - ip));
  171. bitCount &= 31;
  172. ip = iend - 4;
  173. }
  174. bitStream = MEM_readLE32(ip) >> bitCount;
  175. } }
  176. if (remaining != 1) return ERROR(corruption_detected);
  177. /* Only possible when there are too many zeros. */
  178. if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);
  179. if (bitCount > 32) return ERROR(corruption_detected);
  180. *maxSVPtr = charnum-1;
  181. ip += (bitCount+7)>>3;
  182. return ip-istart;
  183. }
  184. /* Avoids the FORCE_INLINE of the _body() function. */
  185. static size_t FSE_readNCount_body_default(
  186. short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  187. const void* headerBuffer, size_t hbSize)
  188. {
  189. return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
  190. }
  191. #if DYNAMIC_BMI2
  192. BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2(
  193. short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  194. const void* headerBuffer, size_t hbSize)
  195. {
  196. return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
  197. }
  198. #endif
  199. size_t FSE_readNCount_bmi2(
  200. short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  201. const void* headerBuffer, size_t hbSize, int bmi2)
  202. {
  203. #if DYNAMIC_BMI2
  204. if (bmi2) {
  205. return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
  206. }
  207. #endif
  208. (void)bmi2;
  209. return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
  210. }
  211. size_t FSE_readNCount(
  212. short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  213. const void* headerBuffer, size_t hbSize)
  214. {
  215. return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);
  216. }
  217. /*! HUF_readStats() :
  218. Read compact Huffman tree, saved by HUF_writeCTable().
  219. `huffWeight` is destination buffer.
  220. `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
  221. @return : size read from `src` , or an error Code .
  222. Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
  223. */
  224. size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  225. U32* nbSymbolsPtr, U32* tableLogPtr,
  226. const void* src, size_t srcSize)
  227. {
  228. U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
  229. return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* bmi2 */ 0);
  230. }
  231. FORCE_INLINE_TEMPLATE size_t
  232. HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  233. U32* nbSymbolsPtr, U32* tableLogPtr,
  234. const void* src, size_t srcSize,
  235. void* workSpace, size_t wkspSize,
  236. int bmi2)
  237. {
  238. U32 weightTotal;
  239. const BYTE* ip = (const BYTE*) src;
  240. size_t iSize;
  241. size_t oSize;
  242. if (!srcSize) return ERROR(srcSize_wrong);
  243. iSize = ip[0];
  244. /* ZSTD_memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
  245. if (iSize >= 128) { /* special header */
  246. oSize = iSize - 127;
  247. iSize = ((oSize+1)/2);
  248. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  249. if (oSize >= hwSize) return ERROR(corruption_detected);
  250. ip += 1;
  251. { U32 n;
  252. for (n=0; n<oSize; n+=2) {
  253. huffWeight[n] = ip[n/2] >> 4;
  254. huffWeight[n+1] = ip[n/2] & 15;
  255. } } }
  256. else { /* header compressed with FSE (normal case) */
  257. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  258. /* max (hwSize-1) values decoded, as last one is implied */
  259. oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);
  260. if (FSE_isError(oSize)) return oSize;
  261. }
  262. /* collect weight stats */
  263. ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
  264. weightTotal = 0;
  265. { U32 n; for (n=0; n<oSize; n++) {
  266. if (huffWeight[n] > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
  267. rankStats[huffWeight[n]]++;
  268. weightTotal += (1 << huffWeight[n]) >> 1;
  269. } }
  270. if (weightTotal == 0) return ERROR(corruption_detected);
  271. /* get last non-null symbol weight (implied, total must be 2^n) */
  272. { U32 const tableLog = BIT_highbit32(weightTotal) + 1;
  273. if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
  274. *tableLogPtr = tableLog;
  275. /* determine last weight */
  276. { U32 const total = 1 << tableLog;
  277. U32 const rest = total - weightTotal;
  278. U32 const verif = 1 << BIT_highbit32(rest);
  279. U32 const lastWeight = BIT_highbit32(rest) + 1;
  280. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  281. huffWeight[oSize] = (BYTE)lastWeight;
  282. rankStats[lastWeight]++;
  283. } }
  284. /* check tree construction validity */
  285. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  286. /* results */
  287. *nbSymbolsPtr = (U32)(oSize+1);
  288. return iSize+1;
  289. }
  290. /* Avoids the FORCE_INLINE of the _body() function. */
  291. static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  292. U32* nbSymbolsPtr, U32* tableLogPtr,
  293. const void* src, size_t srcSize,
  294. void* workSpace, size_t wkspSize)
  295. {
  296. return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);
  297. }
  298. #if DYNAMIC_BMI2
  299. static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  300. U32* nbSymbolsPtr, U32* tableLogPtr,
  301. const void* src, size_t srcSize,
  302. void* workSpace, size_t wkspSize)
  303. {
  304. return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);
  305. }
  306. #endif
  307. size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  308. U32* nbSymbolsPtr, U32* tableLogPtr,
  309. const void* src, size_t srcSize,
  310. void* workSpace, size_t wkspSize,
  311. int bmi2)
  312. {
  313. #if DYNAMIC_BMI2
  314. if (bmi2) {
  315. return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
  316. }
  317. #endif
  318. (void)bmi2;
  319. return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
  320. }