entropy_common.c 14 KB

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