entropy_common.c 13 KB

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