fse_compress.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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 "../common/compiler.h"
  18. #include "../common/mem.h" /* U32, U16, etc. */
  19. #include "../common/debug.h" /* assert, DEBUGLOG */
  20. #include "hist.h" /* HIST_count_wksp */
  21. #include "../common/bitstream.h"
  22. #define FSE_STATIC_LINKING_ONLY
  23. #include "../common/fse.h"
  24. #include "../common/error_private.h"
  25. #define ZSTD_DEPS_NEED_MALLOC
  26. #define ZSTD_DEPS_NEED_MATH64
  27. #include "../common/zstd_deps.h" /* ZSTD_memset */
  28. #include "../common/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 = (int)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 += 3U << 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 += (U32)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. assert(out >= ostart);
  293. return (size_t)(out-ostart);
  294. }
  295. size_t FSE_writeNCount (void* buffer, size_t bufferSize,
  296. const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  297. {
  298. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported */
  299. if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported */
  300. if (bufferSize < FSE_NCountWriteBound(maxSymbolValue, tableLog))
  301. return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
  302. return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1 /* write in buffer is safe */);
  303. }
  304. /*-**************************************************************
  305. * FSE Compression Code
  306. ****************************************************************/
  307. /* provides the minimum logSize to safely represent a distribution */
  308. static unsigned FSE_minTableLog(size_t srcSize, unsigned maxSymbolValue)
  309. {
  310. U32 minBitsSrc = ZSTD_highbit32((U32)(srcSize)) + 1;
  311. U32 minBitsSymbols = ZSTD_highbit32(maxSymbolValue) + 2;
  312. U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
  313. assert(srcSize > 1); /* Not supported, RLE should be used instead */
  314. return minBits;
  315. }
  316. unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
  317. {
  318. U32 maxBitsSrc = ZSTD_highbit32((U32)(srcSize - 1)) - minus;
  319. U32 tableLog = maxTableLog;
  320. U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
  321. assert(srcSize > 1); /* Not supported, RLE should be used instead */
  322. if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
  323. if (maxBitsSrc < tableLog) tableLog = maxBitsSrc; /* Accuracy can be reduced */
  324. if (minBits > tableLog) tableLog = minBits; /* Need a minimum to safely represent all symbol values */
  325. if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
  326. if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
  327. return tableLog;
  328. }
  329. unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
  330. {
  331. return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 2);
  332. }
  333. /* Secondary normalization method.
  334. To be used when primary method fails. */
  335. static size_t FSE_normalizeM2(short* norm, U32 tableLog, const unsigned* count, size_t total, U32 maxSymbolValue, short lowProbCount)
  336. {
  337. short const NOT_YET_ASSIGNED = -2;
  338. U32 s;
  339. U32 distributed = 0;
  340. U32 ToDistribute;
  341. /* Init */
  342. U32 const lowThreshold = (U32)(total >> tableLog);
  343. U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
  344. for (s=0; s<=maxSymbolValue; s++) {
  345. if (count[s] == 0) {
  346. norm[s]=0;
  347. continue;
  348. }
  349. if (count[s] <= lowThreshold) {
  350. norm[s] = lowProbCount;
  351. distributed++;
  352. total -= count[s];
  353. continue;
  354. }
  355. if (count[s] <= lowOne) {
  356. norm[s] = 1;
  357. distributed++;
  358. total -= count[s];
  359. continue;
  360. }
  361. norm[s]=NOT_YET_ASSIGNED;
  362. }
  363. ToDistribute = (1 << tableLog) - distributed;
  364. if (ToDistribute == 0)
  365. return 0;
  366. if ((total / ToDistribute) > lowOne) {
  367. /* risk of rounding to zero */
  368. lowOne = (U32)((total * 3) / (ToDistribute * 2));
  369. for (s=0; s<=maxSymbolValue; s++) {
  370. if ((norm[s] == NOT_YET_ASSIGNED) && (count[s] <= lowOne)) {
  371. norm[s] = 1;
  372. distributed++;
  373. total -= count[s];
  374. continue;
  375. } }
  376. ToDistribute = (1 << tableLog) - distributed;
  377. }
  378. if (distributed == maxSymbolValue+1) {
  379. /* all values are pretty poor;
  380. probably incompressible data (should have already been detected);
  381. find max, then give all remaining points to max */
  382. U32 maxV = 0, maxC = 0;
  383. for (s=0; s<=maxSymbolValue; s++)
  384. if (count[s] > maxC) { maxV=s; maxC=count[s]; }
  385. norm[maxV] += (short)ToDistribute;
  386. return 0;
  387. }
  388. if (total == 0) {
  389. /* all of the symbols were low enough for the lowOne or lowThreshold */
  390. for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
  391. if (norm[s] > 0) { ToDistribute--; norm[s]++; }
  392. return 0;
  393. }
  394. { U64 const vStepLog = 62 - tableLog;
  395. U64 const mid = (1ULL << (vStepLog-1)) - 1;
  396. U64 const rStep = ZSTD_div64((((U64)1<<vStepLog) * ToDistribute) + mid, (U32)total); /* scale on remaining */
  397. U64 tmpTotal = mid;
  398. for (s=0; s<=maxSymbolValue; s++) {
  399. if (norm[s]==NOT_YET_ASSIGNED) {
  400. U64 const end = tmpTotal + (count[s] * rStep);
  401. U32 const sStart = (U32)(tmpTotal >> vStepLog);
  402. U32 const sEnd = (U32)(end >> vStepLog);
  403. U32 const weight = sEnd - sStart;
  404. if (weight < 1)
  405. return ERROR(GENERIC);
  406. norm[s] = (short)weight;
  407. tmpTotal = end;
  408. } } }
  409. return 0;
  410. }
  411. size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
  412. const unsigned* count, size_t total,
  413. unsigned maxSymbolValue, unsigned useLowProbCount)
  414. {
  415. /* Sanity checks */
  416. if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
  417. if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported size */
  418. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported size */
  419. if (tableLog < FSE_minTableLog(total, maxSymbolValue)) return ERROR(GENERIC); /* Too small tableLog, compression potentially impossible */
  420. { static U32 const rtbTable[] = { 0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
  421. short const lowProbCount = useLowProbCount ? -1 : 1;
  422. U64 const scale = 62 - tableLog;
  423. U64 const step = ZSTD_div64((U64)1<<62, (U32)total); /* <== here, one division ! */
  424. U64 const vStep = 1ULL<<(scale-20);
  425. int stillToDistribute = 1<<tableLog;
  426. unsigned s;
  427. unsigned largest=0;
  428. short largestP=0;
  429. U32 lowThreshold = (U32)(total >> tableLog);
  430. for (s=0; s<=maxSymbolValue; s++) {
  431. if (count[s] == total) return 0; /* rle special case */
  432. if (count[s] == 0) { normalizedCounter[s]=0; continue; }
  433. if (count[s] <= lowThreshold) {
  434. normalizedCounter[s] = lowProbCount;
  435. stillToDistribute--;
  436. } else {
  437. short proba = (short)((count[s]*step) >> scale);
  438. if (proba<8) {
  439. U64 restToBeat = vStep * rtbTable[proba];
  440. proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
  441. }
  442. if (proba > largestP) { largestP=proba; largest=s; }
  443. normalizedCounter[s] = proba;
  444. stillToDistribute -= proba;
  445. } }
  446. if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
  447. /* corner case, need another normalization method */
  448. size_t const errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue, lowProbCount);
  449. if (FSE_isError(errorCode)) return errorCode;
  450. }
  451. else normalizedCounter[largest] += (short)stillToDistribute;
  452. }
  453. #if 0
  454. { /* Print Table (debug) */
  455. U32 s;
  456. U32 nTotal = 0;
  457. for (s=0; s<=maxSymbolValue; s++)
  458. RAWLOG(2, "%3i: %4i \n", s, normalizedCounter[s]);
  459. for (s=0; s<=maxSymbolValue; s++)
  460. nTotal += abs(normalizedCounter[s]);
  461. if (nTotal != (1U<<tableLog))
  462. RAWLOG(2, "Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
  463. getchar();
  464. }
  465. #endif
  466. return tableLog;
  467. }
  468. /* fake FSE_CTable, for rle input (always same symbol) */
  469. size_t FSE_buildCTable_rle (FSE_CTable* ct, BYTE symbolValue)
  470. {
  471. void* ptr = ct;
  472. U16* tableU16 = ( (U16*) ptr) + 2;
  473. void* FSCTptr = (U32*)ptr + 2;
  474. FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
  475. /* header */
  476. tableU16[-2] = (U16) 0;
  477. tableU16[-1] = (U16) symbolValue;
  478. /* Build table */
  479. tableU16[0] = 0;
  480. tableU16[1] = 0; /* just in case */
  481. /* Build Symbol Transformation Table */
  482. symbolTT[symbolValue].deltaNbBits = 0;
  483. symbolTT[symbolValue].deltaFindState = 0;
  484. return 0;
  485. }
  486. static size_t FSE_compress_usingCTable_generic (void* dst, size_t dstSize,
  487. const void* src, size_t srcSize,
  488. const FSE_CTable* ct, const unsigned fast)
  489. {
  490. const BYTE* const istart = (const BYTE*) src;
  491. const BYTE* const iend = istart + srcSize;
  492. const BYTE* ip=iend;
  493. BIT_CStream_t bitC;
  494. FSE_CState_t CState1, CState2;
  495. /* init */
  496. if (srcSize <= 2) return 0;
  497. { size_t const initError = BIT_initCStream(&bitC, dst, dstSize);
  498. if (FSE_isError(initError)) return 0; /* not enough space available to write a bitstream */ }
  499. #define FSE_FLUSHBITS(s) (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
  500. if (srcSize & 1) {
  501. FSE_initCState2(&CState1, ct, *--ip);
  502. FSE_initCState2(&CState2, ct, *--ip);
  503. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  504. FSE_FLUSHBITS(&bitC);
  505. } else {
  506. FSE_initCState2(&CState2, ct, *--ip);
  507. FSE_initCState2(&CState1, ct, *--ip);
  508. }
  509. /* join to mod 4 */
  510. srcSize -= 2;
  511. if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) { /* test bit 2 */
  512. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  513. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  514. FSE_FLUSHBITS(&bitC);
  515. }
  516. /* 2 or 4 encoding per loop */
  517. while ( ip>istart ) {
  518. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  519. if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 ) /* this test must be static */
  520. FSE_FLUSHBITS(&bitC);
  521. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  522. if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) { /* this test must be static */
  523. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  524. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  525. }
  526. FSE_FLUSHBITS(&bitC);
  527. }
  528. FSE_flushCState(&bitC, &CState2);
  529. FSE_flushCState(&bitC, &CState1);
  530. return BIT_closeCStream(&bitC);
  531. }
  532. size_t FSE_compress_usingCTable (void* dst, size_t dstSize,
  533. const void* src, size_t srcSize,
  534. const FSE_CTable* ct)
  535. {
  536. unsigned const fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
  537. if (fast)
  538. return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
  539. else
  540. return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
  541. }
  542. size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); }
  543. #endif /* FSE_COMMONDEFS_ONLY */