fse_compress.c 24 KB

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