You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fse_compress.c 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /* ******************************************************************
  2. * FSE : Finite State Entropy encoder
  3. * Copyright (c) Meta Platforms, Inc. and affiliates.
  4. *
  5. * You can contact the author at :
  6. * - FSE 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. * Includes
  16. ****************************************************************/
  17. #include "compiler.h"
  18. #include "mem.h" /* U32, U16, etc. */
  19. #include "debug.h" /* assert, DEBUGLOG */
  20. #include "hist.h" /* HIST_count_wksp */
  21. #include "bitstream.h"
  22. #define FSE_STATIC_LINKING_ONLY
  23. #include "fse.h"
  24. #include "error_private.h"
  25. #define ZSTD_DEPS_NEED_MALLOC
  26. #define ZSTD_DEPS_NEED_MATH64
  27. #include "zstd_deps.h" /* ZSTD_malloc, ZSTD_free, ZSTD_memcpy, ZSTD_memset */
  28. #include "bits.h" /* ZSTD_highbit32 */
  29. /* **************************************************************
  30. * Error Management
  31. ****************************************************************/
  32. #define FSE_isError ERR_isError
  33. /* **************************************************************
  34. * Templates
  35. ****************************************************************/
  36. /*
  37. designed to be included
  38. for type-specific functions (template emulation in C)
  39. Objective is to write these functions only once, for improved maintenance
  40. */
  41. /* safety checks */
  42. #ifndef FSE_FUNCTION_EXTENSION
  43. # error "FSE_FUNCTION_EXTENSION must be defined"
  44. #endif
  45. #ifndef FSE_FUNCTION_TYPE
  46. # error "FSE_FUNCTION_TYPE must be defined"
  47. #endif
  48. /* Function names */
  49. #define FSE_CAT(X,Y) X##Y
  50. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  51. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  52. /* Function templates */
  53. /* FSE_buildCTable_wksp() :
  54. * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
  55. * wkspSize should be sized to handle worst case situation, which is `1<<max_tableLog * sizeof(FSE_FUNCTION_TYPE)`
  56. * workSpace must also be properly aligned with FSE_FUNCTION_TYPE requirements
  57. */
  58. size_t FSE_buildCTable_wksp(FSE_CTable* ct,
  59. const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
  60. void* workSpace, size_t wkspSize)
  61. {
  62. U32 const tableSize = 1 << tableLog;
  63. U32 const tableMask = tableSize - 1;
  64. void* const ptr = ct;
  65. U16* const tableU16 = ( (U16*) ptr) + 2;
  66. void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableLog ? tableSize>>1 : 1) ;
  67. FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
  68. U32 const step = FSE_TABLESTEP(tableSize);
  69. U32 const maxSV1 = maxSymbolValue+1;
  70. U16* cumul = (U16*)workSpace; /* size = maxSV1 */
  71. FSE_FUNCTION_TYPE* const tableSymbol = (FSE_FUNCTION_TYPE*)(cumul + (maxSV1+1)); /* size = tableSize */
  72. U32 highThreshold = tableSize-1;
  73. assert(((size_t)workSpace & 1) == 0); /* Must be 2 bytes-aligned */
  74. if (FSE_BUILD_CTABLE_WORKSPACE_SIZE(maxSymbolValue, tableLog) > wkspSize) return ERROR(tableLog_tooLarge);
  75. /* CTable header */
  76. tableU16[-2] = (U16) tableLog;
  77. tableU16[-1] = (U16) maxSymbolValue;
  78. assert(tableLog < 16); /* required for threshold strategy to work */
  79. /* For explanations on how to distribute symbol values over the table :
  80. * https://fastcompression.blogspot.fr/2014/02/fse-distributing-symbol-values.html */
  81. #ifdef __clang_analyzer__
  82. ZSTD_memset(tableSymbol, 0, sizeof(*tableSymbol) * tableSize); /* useless initialization, just to keep scan-build happy */
  83. #endif
  84. /* symbol start positions */
  85. { U32 u;
  86. cumul[0] = 0;
  87. for (u=1; u <= maxSV1; u++) {
  88. if (normalizedCounter[u-1]==-1) { /* Low proba symbol */
  89. cumul[u] = cumul[u-1] + 1;
  90. tableSymbol[highThreshold--] = (FSE_FUNCTION_TYPE)(u-1);
  91. } else {
  92. assert(normalizedCounter[u-1] >= 0);
  93. cumul[u] = cumul[u-1] + (U16)normalizedCounter[u-1];
  94. assert(cumul[u] >= cumul[u-1]); /* no overflow */
  95. } }
  96. cumul[maxSV1] = (U16)(tableSize+1);
  97. }
  98. /* Spread symbols */
  99. if (highThreshold == tableSize - 1) {
  100. /* Case for no low prob count symbols. Lay down 8 bytes at a time
  101. * to reduce branch misses since we are operating on a small block
  102. */
  103. BYTE* const spread = tableSymbol + tableSize; /* size = tableSize + 8 (may write beyond tableSize) */
  104. { U64 const add = 0x0101010101010101ull;
  105. size_t pos = 0;
  106. U64 sv = 0;
  107. U32 s;
  108. for (s=0; s<maxSV1; ++s, sv += add) {
  109. int i;
  110. int const n = normalizedCounter[s];
  111. MEM_write64(spread + pos, sv);
  112. for (i = 8; i < n; i += 8) {
  113. MEM_write64(spread + pos + i, sv);
  114. }
  115. assert(n>=0);
  116. pos += (size_t)n;
  117. }
  118. }
  119. /* Spread symbols across the table. Lack of lowprob symbols means that
  120. * we don't need variable sized inner loop, so we can unroll the loop and
  121. * reduce branch misses.
  122. */
  123. { size_t position = 0;
  124. size_t s;
  125. size_t const unroll = 2; /* Experimentally determined optimal unroll */
  126. assert(tableSize % unroll == 0); /* FSE_MIN_TABLELOG is 5 */
  127. for (s = 0; s < (size_t)tableSize; s += unroll) {
  128. size_t u;
  129. for (u = 0; u < unroll; ++u) {
  130. size_t const uPosition = (position + (u * step)) & tableMask;
  131. tableSymbol[uPosition] = spread[s + u];
  132. }
  133. position = (position + (unroll * step)) & tableMask;
  134. }
  135. assert(position == 0); /* Must have initialized all positions */
  136. }
  137. } else {
  138. U32 position = 0;
  139. U32 symbol;
  140. for (symbol=0; symbol<maxSV1; symbol++) {
  141. int nbOccurrences;
  142. int const freq = normalizedCounter[symbol];
  143. for (nbOccurrences=0; nbOccurrences<freq; nbOccurrences++) {
  144. tableSymbol[position] = (FSE_FUNCTION_TYPE)symbol;
  145. position = (position + step) & tableMask;
  146. while (position > highThreshold)
  147. position = (position + step) & tableMask; /* Low proba area */
  148. } }
  149. assert(position==0); /* Must have initialized all positions */
  150. }
  151. /* Build table */
  152. { U32 u; for (u=0; u<tableSize; u++) {
  153. FSE_FUNCTION_TYPE s = tableSymbol[u]; /* note : static analyzer may not understand tableSymbol is properly initialized */
  154. tableU16[cumul[s]++] = (U16) (tableSize+u); /* TableU16 : sorted by symbol order; gives next state value */
  155. } }
  156. /* Build Symbol Transformation Table */
  157. { unsigned total = 0;
  158. unsigned s;
  159. for (s=0; s<=maxSymbolValue; s++) {
  160. switch (normalizedCounter[s])
  161. {
  162. case 0:
  163. /* filling nonetheless, for compatibility with FSE_getMaxNbBits() */
  164. symbolTT[s].deltaNbBits = ((tableLog+1) << 16) - (1<<tableLog);
  165. break;
  166. case -1:
  167. case 1:
  168. symbolTT[s].deltaNbBits = (tableLog << 16) - (1<<tableLog);
  169. assert(total <= INT_MAX);
  170. symbolTT[s].deltaFindState = (int)(total - 1);
  171. total ++;
  172. break;
  173. default :
  174. assert(normalizedCounter[s] > 1);
  175. { U32 const maxBitsOut = tableLog - ZSTD_highbit32 ((U32)normalizedCounter[s]-1);
  176. U32 const minStatePlus = (U32)normalizedCounter[s] << maxBitsOut;
  177. symbolTT[s].deltaNbBits = (maxBitsOut << 16) - minStatePlus;
  178. symbolTT[s].deltaFindState = (int)(total - (unsigned)normalizedCounter[s]);
  179. total += (unsigned)normalizedCounter[s];
  180. } } } }
  181. #if 0 /* debug : symbol costs */
  182. DEBUGLOG(5, "\n --- table statistics : ");
  183. { U32 symbol;
  184. for (symbol=0; symbol<=maxSymbolValue; symbol++) {
  185. DEBUGLOG(5, "%3u: w=%3i, maxBits=%u, fracBits=%.2f",
  186. symbol, normalizedCounter[symbol],
  187. FSE_getMaxNbBits(symbolTT, symbol),
  188. (double)FSE_bitCost(symbolTT, tableLog, symbol, 8) / 256);
  189. } }
  190. #endif
  191. return 0;
  192. }
  193. #ifndef FSE_COMMONDEFS_ONLY
  194. /*-**************************************************************
  195. * FSE NCount encoding
  196. ****************************************************************/
  197. size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
  198. {
  199. size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog
  200. + 4 /* bitCount initialized at 4 */
  201. + 2 /* first two symbols may use one additional bit each */) / 8)
  202. + 1 /* round up to whole nb bytes */
  203. + 2 /* additional two bytes for bitstream flush */;
  204. return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND; /* maxSymbolValue==0 ? use default */
  205. }
  206. static size_t
  207. FSE_writeNCount_generic (void* header, size_t headerBufferSize,
  208. const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
  209. unsigned writeIsSafe)
  210. {
  211. BYTE* const ostart = (BYTE*) header;
  212. BYTE* out = ostart;
  213. BYTE* const oend = ostart + headerBufferSize;
  214. int nbBits;
  215. const int tableSize = 1 << tableLog;
  216. int remaining;
  217. int threshold;
  218. U32 bitStream = 0;
  219. int bitCount = 0;
  220. unsigned symbol = 0;
  221. unsigned const alphabetSize = maxSymbolValue + 1;
  222. int previousIs0 = 0;
  223. /* Table Size */
  224. bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
  225. bitCount += 4;
  226. /* Init */
  227. remaining = tableSize+1; /* +1 for extra accuracy */
  228. threshold = tableSize;
  229. nbBits = tableLog+1;
  230. while ((symbol < alphabetSize) && (remaining>1)) { /* stops at 1 */
  231. if (previousIs0) {
  232. unsigned start = symbol;
  233. while ((symbol < alphabetSize) && !normalizedCounter[symbol]) symbol++;
  234. if (symbol == alphabetSize) break; /* incorrect distribution */
  235. while (symbol >= start+24) {
  236. start+=24;
  237. bitStream += 0xFFFFU << bitCount;
  238. if ((!writeIsSafe) && (out > oend-2))
  239. return ERROR(dstSize_tooSmall); /* Buffer overflow */
  240. out[0] = (BYTE) bitStream;
  241. out[1] = (BYTE)(bitStream>>8);
  242. out+=2;
  243. bitStream>>=16;
  244. }
  245. while (symbol >= start+3) {
  246. start+=3;
  247. bitStream += 3 << bitCount;
  248. bitCount += 2;
  249. }
  250. bitStream += (symbol-start) << bitCount;
  251. bitCount += 2;
  252. if (bitCount>16) {
  253. if ((!writeIsSafe) && (out > oend - 2))
  254. return ERROR(dstSize_tooSmall); /* Buffer overflow */
  255. out[0] = (BYTE)bitStream;
  256. out[1] = (BYTE)(bitStream>>8);
  257. out += 2;
  258. bitStream >>= 16;
  259. bitCount -= 16;
  260. } }
  261. { int count = normalizedCounter[symbol++];
  262. int const max = (2*threshold-1) - remaining;
  263. remaining -= count < 0 ? -count : count;
  264. count++; /* +1 for extra accuracy */
  265. if (count>=threshold)
  266. count += max; /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
  267. bitStream += count << bitCount;
  268. bitCount += nbBits;
  269. bitCount -= (count<max);
  270. previousIs0 = (count==1);
  271. if (remaining<1) return ERROR(GENERIC);
  272. while (remaining<threshold) { nbBits--; threshold>>=1; }
  273. }
  274. if (bitCount>16) {
  275. if ((!writeIsSafe) && (out > oend - 2))
  276. return ERROR(dstSize_tooSmall); /* Buffer overflow */
  277. out[0] = (BYTE)bitStream;
  278. out[1] = (BYTE)(bitStream>>8);
  279. out += 2;
  280. bitStream >>= 16;
  281. bitCount -= 16;
  282. } }
  283. if (remaining != 1)
  284. return ERROR(GENERIC); /* incorrect normalized distribution */
  285. assert(symbol <= alphabetSize);
  286. /* flush remaining bitStream */
  287. if ((!writeIsSafe) && (out > oend - 2))
  288. return ERROR(dstSize_tooSmall); /* Buffer overflow */
  289. out[0] = (BYTE)bitStream;
  290. out[1] = (BYTE)(bitStream>>8);
  291. out+= (bitCount+7) /8;
  292. return (out-ostart);
  293. }
  294. size_t FSE_writeNCount (void* buffer, size_t bufferSize,
  295. const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  296. {
  297. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported */
  298. if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported */
  299. if (bufferSize < FSE_NCountWriteBound(maxSymbolValue, tableLog))
  300. return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
  301. return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1 /* write in buffer is safe */);
  302. }
  303. /*-**************************************************************
  304. * FSE Compression Code
  305. ****************************************************************/
  306. /* provides the minimum logSize to safely represent a distribution */
  307. static unsigned FSE_minTableLog(size_t srcSize, unsigned maxSymbolValue)
  308. {
  309. U32 minBitsSrc = ZSTD_highbit32((U32)(srcSize)) + 1;
  310. U32 minBitsSymbols = ZSTD_highbit32(maxSymbolValue) + 2;
  311. U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
  312. assert(srcSize > 1); /* Not supported, RLE should be used instead */
  313. return minBits;
  314. }
  315. unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
  316. {
  317. U32 maxBitsSrc = ZSTD_highbit32((U32)(srcSize - 1)) - minus;
  318. U32 tableLog = maxTableLog;
  319. U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
  320. assert(srcSize > 1); /* Not supported, RLE should be used instead */
  321. if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
  322. if (maxBitsSrc < tableLog) tableLog = maxBitsSrc; /* Accuracy can be reduced */
  323. if (minBits > tableLog) tableLog = minBits; /* Need a minimum to safely represent all symbol values */
  324. if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
  325. if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
  326. return tableLog;
  327. }
  328. unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
  329. {
  330. return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 2);
  331. }
  332. /* Secondary normalization method.
  333. To be used when primary method fails. */
  334. static size_t FSE_normalizeM2(short* norm, U32 tableLog, const unsigned* count, size_t total, U32 maxSymbolValue, short lowProbCount)
  335. {
  336. short const NOT_YET_ASSIGNED = -2;
  337. U32 s;
  338. U32 distributed = 0;
  339. U32 ToDistribute;
  340. /* Init */
  341. U32 const lowThreshold = (U32)(total >> tableLog);
  342. U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
  343. for (s=0; s<=maxSymbolValue; s++) {
  344. if (count[s] == 0) {
  345. norm[s]=0;
  346. continue;
  347. }
  348. if (count[s] <= lowThreshold) {
  349. norm[s] = lowProbCount;
  350. distributed++;
  351. total -= count[s];
  352. continue;
  353. }
  354. if (count[s] <= lowOne) {
  355. norm[s] = 1;
  356. distributed++;
  357. total -= count[s];
  358. continue;
  359. }
  360. norm[s]=NOT_YET_ASSIGNED;
  361. }
  362. ToDistribute = (1 << tableLog) - distributed;
  363. if (ToDistribute == 0)
  364. return 0;
  365. if ((total / ToDistribute) > lowOne) {
  366. /* risk of rounding to zero */
  367. lowOne = (U32)((total * 3) / (ToDistribute * 2));
  368. for (s=0; s<=maxSymbolValue; s++) {
  369. if ((norm[s] == NOT_YET_ASSIGNED) && (count[s] <= lowOne)) {
  370. norm[s] = 1;
  371. distributed++;
  372. total -= count[s];
  373. continue;
  374. } }
  375. ToDistribute = (1 << tableLog) - distributed;
  376. }
  377. if (distributed == maxSymbolValue+1) {
  378. /* all values are pretty poor;
  379. probably incompressible data (should have already been detected);
  380. find max, then give all remaining points to max */
  381. U32 maxV = 0, maxC = 0;
  382. for (s=0; s<=maxSymbolValue; s++)
  383. if (count[s] > maxC) { maxV=s; maxC=count[s]; }
  384. norm[maxV] += (short)ToDistribute;
  385. return 0;
  386. }
  387. if (total == 0) {
  388. /* all of the symbols were low enough for the lowOne or lowThreshold */
  389. for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
  390. if (norm[s] > 0) { ToDistribute--; norm[s]++; }
  391. return 0;
  392. }
  393. { U64 const vStepLog = 62 - tableLog;
  394. U64 const mid = (1ULL << (vStepLog-1)) - 1;
  395. U64 const rStep = ZSTD_div64((((U64)1<<vStepLog) * ToDistribute) + mid, (U32)total); /* scale on remaining */
  396. U64 tmpTotal = mid;
  397. for (s=0; s<=maxSymbolValue; s++) {
  398. if (norm[s]==NOT_YET_ASSIGNED) {
  399. U64 const end = tmpTotal + (count[s] * rStep);
  400. U32 const sStart = (U32)(tmpTotal >> vStepLog);
  401. U32 const sEnd = (U32)(end >> vStepLog);
  402. U32 const weight = sEnd - sStart;
  403. if (weight < 1)
  404. return ERROR(GENERIC);
  405. norm[s] = (short)weight;
  406. tmpTotal = end;
  407. } } }
  408. return 0;
  409. }
  410. size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
  411. const unsigned* count, size_t total,
  412. unsigned maxSymbolValue, unsigned useLowProbCount)
  413. {
  414. /* Sanity checks */
  415. if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
  416. if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported size */
  417. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported size */
  418. if (tableLog < FSE_minTableLog(total, maxSymbolValue)) return ERROR(GENERIC); /* Too small tableLog, compression potentially impossible */
  419. { static U32 const rtbTable[] = { 0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
  420. short const lowProbCount = useLowProbCount ? -1 : 1;
  421. U64 const scale = 62 - tableLog;
  422. U64 const step = ZSTD_div64((U64)1<<62, (U32)total); /* <== here, one division ! */
  423. U64 const vStep = 1ULL<<(scale-20);
  424. int stillToDistribute = 1<<tableLog;
  425. unsigned s;
  426. unsigned largest=0;
  427. short largestP=0;
  428. U32 lowThreshold = (U32)(total >> tableLog);
  429. for (s=0; s<=maxSymbolValue; s++) {
  430. if (count[s] == total) return 0; /* rle special case */
  431. if (count[s] == 0) { normalizedCounter[s]=0; continue; }
  432. if (count[s] <= lowThreshold) {
  433. normalizedCounter[s] = lowProbCount;
  434. stillToDistribute--;
  435. } else {
  436. short proba = (short)((count[s]*step) >> scale);
  437. if (proba<8) {
  438. U64 restToBeat = vStep * rtbTable[proba];
  439. proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
  440. }
  441. if (proba > largestP) { largestP=proba; largest=s; }
  442. normalizedCounter[s] = proba;
  443. stillToDistribute -= proba;
  444. } }
  445. if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
  446. /* corner case, need another normalization method */
  447. size_t const errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue, lowProbCount);
  448. if (FSE_isError(errorCode)) return errorCode;
  449. }
  450. else normalizedCounter[largest] += (short)stillToDistribute;
  451. }
  452. #if 0
  453. { /* Print Table (debug) */
  454. U32 s;
  455. U32 nTotal = 0;
  456. for (s=0; s<=maxSymbolValue; s++)
  457. RAWLOG(2, "%3i: %4i \n", s, normalizedCounter[s]);
  458. for (s=0; s<=maxSymbolValue; s++)
  459. nTotal += abs(normalizedCounter[s]);
  460. if (nTotal != (1U<<tableLog))
  461. RAWLOG(2, "Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
  462. getchar();
  463. }
  464. #endif
  465. return tableLog;
  466. }
  467. /* fake FSE_CTable, for rle input (always same symbol) */
  468. size_t FSE_buildCTable_rle (FSE_CTable* ct, BYTE symbolValue)
  469. {
  470. void* ptr = ct;
  471. U16* tableU16 = ( (U16*) ptr) + 2;
  472. void* FSCTptr = (U32*)ptr + 2;
  473. FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
  474. /* header */
  475. tableU16[-2] = (U16) 0;
  476. tableU16[-1] = (U16) symbolValue;
  477. /* Build table */
  478. tableU16[0] = 0;
  479. tableU16[1] = 0; /* just in case */
  480. /* Build Symbol Transformation Table */
  481. symbolTT[symbolValue].deltaNbBits = 0;
  482. symbolTT[symbolValue].deltaFindState = 0;
  483. return 0;
  484. }
  485. static size_t FSE_compress_usingCTable_generic (void* dst, size_t dstSize,
  486. const void* src, size_t srcSize,
  487. const FSE_CTable* ct, const unsigned fast)
  488. {
  489. const BYTE* const istart = (const BYTE*) src;
  490. const BYTE* const iend = istart + srcSize;
  491. const BYTE* ip=iend;
  492. BIT_CStream_t bitC;
  493. FSE_CState_t CState1, CState2;
  494. /* init */
  495. if (srcSize <= 2) return 0;
  496. { size_t const initError = BIT_initCStream(&bitC, dst, dstSize);
  497. if (FSE_isError(initError)) return 0; /* not enough space available to write a bitstream */ }
  498. #define FSE_FLUSHBITS(s) (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
  499. if (srcSize & 1) {
  500. FSE_initCState2(&CState1, ct, *--ip);
  501. FSE_initCState2(&CState2, ct, *--ip);
  502. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  503. FSE_FLUSHBITS(&bitC);
  504. } else {
  505. FSE_initCState2(&CState2, ct, *--ip);
  506. FSE_initCState2(&CState1, ct, *--ip);
  507. }
  508. /* join to mod 4 */
  509. srcSize -= 2;
  510. if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) { /* test bit 2 */
  511. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  512. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  513. FSE_FLUSHBITS(&bitC);
  514. }
  515. /* 2 or 4 encoding per loop */
  516. while ( ip>istart ) {
  517. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  518. if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 ) /* this test must be static */
  519. FSE_FLUSHBITS(&bitC);
  520. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  521. if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) { /* this test must be static */
  522. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  523. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  524. }
  525. FSE_FLUSHBITS(&bitC);
  526. }
  527. FSE_flushCState(&bitC, &CState2);
  528. FSE_flushCState(&bitC, &CState1);
  529. return BIT_closeCStream(&bitC);
  530. }
  531. size_t FSE_compress_usingCTable (void* dst, size_t dstSize,
  532. const void* src, size_t srcSize,
  533. const FSE_CTable* ct)
  534. {
  535. unsigned const fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
  536. if (fast)
  537. return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
  538. else
  539. return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
  540. }
  541. size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); }
  542. #endif /* FSE_COMMONDEFS_ONLY */