entropy_common.c 13 KB

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