fse_compress.c 28 KB

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