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 26KB

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