fse_compress.c 26 KB

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