fse_compress.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. /* ******************************************************************
  2. FSE : Finite State Entropy encoder
  3. Copyright (C) 2013-2015, Yann Collet.
  4. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are
  7. met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above
  11. copyright notice, this list of conditions and the following disclaimer
  12. in the documentation and/or other materials provided with the
  13. distribution.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  16. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  17. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  18. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  19. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  20. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. You can contact the author at :
  26. - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  27. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  28. ****************************************************************** */
  29. /* **************************************************************
  30. * Includes
  31. ****************************************************************/
  32. #include <stdlib.h> /* malloc, free, qsort */
  33. #include <string.h> /* memcpy, memset */
  34. #include <stdio.h> /* printf (debug) */
  35. #include "bitstream.h"
  36. #include "compiler.h"
  37. #define FSE_STATIC_LINKING_ONLY
  38. #include "fse.h"
  39. #include "error_private.h"
  40. /* **************************************************************
  41. * Error Management
  42. ****************************************************************/
  43. #define FSE_isError ERR_isError
  44. #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  45. /* **************************************************************
  46. * Templates
  47. ****************************************************************/
  48. /*
  49. designed to be included
  50. for type-specific functions (template emulation in C)
  51. Objective is to write these functions only once, for improved maintenance
  52. */
  53. /* safety checks */
  54. #ifndef FSE_FUNCTION_EXTENSION
  55. # error "FSE_FUNCTION_EXTENSION must be defined"
  56. #endif
  57. #ifndef FSE_FUNCTION_TYPE
  58. # error "FSE_FUNCTION_TYPE must be defined"
  59. #endif
  60. /* Function names */
  61. #define FSE_CAT(X,Y) X##Y
  62. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  63. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  64. /* Function templates */
  65. /* FSE_buildCTable_wksp() :
  66. * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
  67. * wkspSize should be sized to handle worst case situation, which is `1<<max_tableLog * sizeof(FSE_FUNCTION_TYPE)`
  68. * workSpace must also be properly aligned with FSE_FUNCTION_TYPE requirements
  69. */
  70. size_t FSE_buildCTable_wksp(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize)
  71. {
  72. U32 const tableSize = 1 << tableLog;
  73. U32 const tableMask = tableSize - 1;
  74. void* const ptr = ct;
  75. U16* const tableU16 = ( (U16*) ptr) + 2;
  76. void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableLog ? tableSize>>1 : 1) ;
  77. FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
  78. U32 const step = FSE_TABLESTEP(tableSize);
  79. U32 cumul[FSE_MAX_SYMBOL_VALUE+2];
  80. FSE_FUNCTION_TYPE* const tableSymbol = (FSE_FUNCTION_TYPE*)workSpace;
  81. U32 highThreshold = tableSize-1;
  82. /* CTable header */
  83. if (((size_t)1 << tableLog) * sizeof(FSE_FUNCTION_TYPE) > wkspSize) return ERROR(tableLog_tooLarge);
  84. tableU16[-2] = (U16) tableLog;
  85. tableU16[-1] = (U16) maxSymbolValue;
  86. /* For explanations on how to distribute symbol values over the table :
  87. * http://fastcompression.blogspot.fr/2014/02/fse-distributing-symbol-values.html */
  88. /* symbol start positions */
  89. { U32 u;
  90. cumul[0] = 0;
  91. for (u=1; u<=maxSymbolValue+1; u++) {
  92. if (normalizedCounter[u-1]==-1) { /* Low proba symbol */
  93. cumul[u] = cumul[u-1] + 1;
  94. tableSymbol[highThreshold--] = (FSE_FUNCTION_TYPE)(u-1);
  95. } else {
  96. cumul[u] = cumul[u-1] + normalizedCounter[u-1];
  97. } }
  98. cumul[maxSymbolValue+1] = tableSize+1;
  99. }
  100. /* Spread symbols */
  101. { U32 position = 0;
  102. U32 symbol;
  103. for (symbol=0; symbol<=maxSymbolValue; symbol++) {
  104. int nbOccurences;
  105. for (nbOccurences=0; nbOccurences<normalizedCounter[symbol]; nbOccurences++) {
  106. tableSymbol[position] = (FSE_FUNCTION_TYPE)symbol;
  107. position = (position + step) & tableMask;
  108. while (position > highThreshold) position = (position + step) & tableMask; /* Low proba area */
  109. } }
  110. if (position!=0) return ERROR(GENERIC); /* Must have gone through all positions */
  111. }
  112. /* Build table */
  113. { U32 u; for (u=0; u<tableSize; u++) {
  114. FSE_FUNCTION_TYPE s = tableSymbol[u]; /* note : static analyzer may not understand tableSymbol is properly initialized */
  115. tableU16[cumul[s]++] = (U16) (tableSize+u); /* TableU16 : sorted by symbol order; gives next state value */
  116. } }
  117. /* Build Symbol Transformation Table */
  118. { unsigned total = 0;
  119. unsigned s;
  120. for (s=0; s<=maxSymbolValue; s++) {
  121. switch (normalizedCounter[s])
  122. {
  123. case 0: break;
  124. case -1:
  125. case 1:
  126. symbolTT[s].deltaNbBits = (tableLog << 16) - (1<<tableLog);
  127. symbolTT[s].deltaFindState = total - 1;
  128. total ++;
  129. break;
  130. default :
  131. {
  132. U32 const maxBitsOut = tableLog - BIT_highbit32 (normalizedCounter[s]-1);
  133. U32 const minStatePlus = normalizedCounter[s] << maxBitsOut;
  134. symbolTT[s].deltaNbBits = (maxBitsOut << 16) - minStatePlus;
  135. symbolTT[s].deltaFindState = total - normalizedCounter[s];
  136. total += normalizedCounter[s];
  137. } } } }
  138. return 0;
  139. }
  140. size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  141. {
  142. FSE_FUNCTION_TYPE tableSymbol[FSE_MAX_TABLESIZE]; /* memset() is not necessary, even if static analyzer complain about it */
  143. return FSE_buildCTable_wksp(ct, normalizedCounter, maxSymbolValue, tableLog, tableSymbol, sizeof(tableSymbol));
  144. }
  145. #ifndef FSE_COMMONDEFS_ONLY
  146. /*-**************************************************************
  147. * FSE NCount encoding-decoding
  148. ****************************************************************/
  149. size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
  150. {
  151. size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog) >> 3) + 3;
  152. return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND; /* maxSymbolValue==0 ? use default */
  153. }
  154. static size_t FSE_writeNCount_generic (void* header, size_t headerBufferSize,
  155. const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
  156. unsigned writeIsSafe)
  157. {
  158. BYTE* const ostart = (BYTE*) header;
  159. BYTE* out = ostart;
  160. BYTE* const oend = ostart + headerBufferSize;
  161. int nbBits;
  162. const int tableSize = 1 << tableLog;
  163. int remaining;
  164. int threshold;
  165. U32 bitStream;
  166. int bitCount;
  167. unsigned charnum = 0;
  168. int previous0 = 0;
  169. bitStream = 0;
  170. bitCount = 0;
  171. /* Table Size */
  172. bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
  173. bitCount += 4;
  174. /* Init */
  175. remaining = tableSize+1; /* +1 for extra accuracy */
  176. threshold = tableSize;
  177. nbBits = tableLog+1;
  178. while (remaining>1) { /* stops at 1 */
  179. if (previous0) {
  180. unsigned start = charnum;
  181. while (!normalizedCounter[charnum]) charnum++;
  182. while (charnum >= start+24) {
  183. start+=24;
  184. bitStream += 0xFFFFU << bitCount;
  185. if ((!writeIsSafe) && (out > oend-2)) return ERROR(dstSize_tooSmall); /* Buffer overflow */
  186. out[0] = (BYTE) bitStream;
  187. out[1] = (BYTE)(bitStream>>8);
  188. out+=2;
  189. bitStream>>=16;
  190. }
  191. while (charnum >= start+3) {
  192. start+=3;
  193. bitStream += 3 << bitCount;
  194. bitCount += 2;
  195. }
  196. bitStream += (charnum-start) << bitCount;
  197. bitCount += 2;
  198. if (bitCount>16) {
  199. if ((!writeIsSafe) && (out > oend - 2)) return ERROR(dstSize_tooSmall); /* Buffer overflow */
  200. out[0] = (BYTE)bitStream;
  201. out[1] = (BYTE)(bitStream>>8);
  202. out += 2;
  203. bitStream >>= 16;
  204. bitCount -= 16;
  205. } }
  206. { int count = normalizedCounter[charnum++];
  207. int const max = (2*threshold-1)-remaining;
  208. remaining -= count < 0 ? -count : count;
  209. count++; /* +1 for extra accuracy */
  210. if (count>=threshold) count += max; /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
  211. bitStream += count << bitCount;
  212. bitCount += nbBits;
  213. bitCount -= (count<max);
  214. previous0 = (count==1);
  215. if (remaining<1) return ERROR(GENERIC);
  216. while (remaining<threshold) nbBits--, threshold>>=1;
  217. }
  218. if (bitCount>16) {
  219. if ((!writeIsSafe) && (out > oend - 2)) return ERROR(dstSize_tooSmall); /* Buffer overflow */
  220. out[0] = (BYTE)bitStream;
  221. out[1] = (BYTE)(bitStream>>8);
  222. out += 2;
  223. bitStream >>= 16;
  224. bitCount -= 16;
  225. } }
  226. /* flush remaining bitStream */
  227. if ((!writeIsSafe) && (out > oend - 2)) return ERROR(dstSize_tooSmall); /* Buffer overflow */
  228. out[0] = (BYTE)bitStream;
  229. out[1] = (BYTE)(bitStream>>8);
  230. out+= (bitCount+7) /8;
  231. if (charnum > maxSymbolValue + 1) return ERROR(GENERIC);
  232. return (out-ostart);
  233. }
  234. size_t FSE_writeNCount (void* buffer, size_t bufferSize, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  235. {
  236. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported */
  237. if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported */
  238. if (bufferSize < FSE_NCountWriteBound(maxSymbolValue, tableLog))
  239. return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
  240. return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1);
  241. }
  242. /*-**************************************************************
  243. * Counting histogram
  244. ****************************************************************/
  245. /*! FSE_count_simple
  246. This function counts byte values within `src`, and store the histogram into table `count`.
  247. It doesn't use any additional memory.
  248. But this function is unsafe : it doesn't check that all values within `src` can fit into `count`.
  249. For this reason, prefer using a table `count` with 256 elements.
  250. @return : count of most numerous element
  251. */
  252. size_t FSE_count_simple(unsigned* count, unsigned* maxSymbolValuePtr,
  253. const void* src, size_t srcSize)
  254. {
  255. const BYTE* ip = (const BYTE*)src;
  256. const BYTE* const end = ip + srcSize;
  257. unsigned maxSymbolValue = *maxSymbolValuePtr;
  258. unsigned max=0;
  259. memset(count, 0, (maxSymbolValue+1)*sizeof(*count));
  260. if (srcSize==0) { *maxSymbolValuePtr = 0; return 0; }
  261. while (ip<end) count[*ip++]++;
  262. while (!count[maxSymbolValue]) maxSymbolValue--;
  263. *maxSymbolValuePtr = maxSymbolValue;
  264. { U32 s; for (s=0; s<=maxSymbolValue; s++) if (count[s] > max) max = count[s]; }
  265. return (size_t)max;
  266. }
  267. /* FSE_count_parallel_wksp() :
  268. * Same as FSE_count_parallel(), but using an externally provided scratch buffer.
  269. * `workSpace` size must be a minimum of `1024 * sizeof(unsigned)`` */
  270. static size_t FSE_count_parallel_wksp(
  271. unsigned* count, unsigned* maxSymbolValuePtr,
  272. const void* source, size_t sourceSize,
  273. unsigned checkMax, unsigned* const workSpace)
  274. {
  275. const BYTE* ip = (const BYTE*)source;
  276. const BYTE* const iend = ip+sourceSize;
  277. unsigned maxSymbolValue = *maxSymbolValuePtr;
  278. unsigned max=0;
  279. U32* const Counting1 = workSpace;
  280. U32* const Counting2 = Counting1 + 256;
  281. U32* const Counting3 = Counting2 + 256;
  282. U32* const Counting4 = Counting3 + 256;
  283. memset(Counting1, 0, 4*256*sizeof(unsigned));
  284. /* safety checks */
  285. if (!sourceSize) {
  286. memset(count, 0, maxSymbolValue + 1);
  287. *maxSymbolValuePtr = 0;
  288. return 0;
  289. }
  290. if (!maxSymbolValue) maxSymbolValue = 255; /* 0 == default */
  291. /* by stripes of 16 bytes */
  292. { U32 cached = MEM_read32(ip); ip += 4;
  293. while (ip < iend-15) {
  294. U32 c = cached; cached = MEM_read32(ip); ip += 4;
  295. Counting1[(BYTE) c ]++;
  296. Counting2[(BYTE)(c>>8) ]++;
  297. Counting3[(BYTE)(c>>16)]++;
  298. Counting4[ c>>24 ]++;
  299. c = cached; cached = MEM_read32(ip); ip += 4;
  300. Counting1[(BYTE) c ]++;
  301. Counting2[(BYTE)(c>>8) ]++;
  302. Counting3[(BYTE)(c>>16)]++;
  303. Counting4[ c>>24 ]++;
  304. c = cached; cached = MEM_read32(ip); ip += 4;
  305. Counting1[(BYTE) c ]++;
  306. Counting2[(BYTE)(c>>8) ]++;
  307. Counting3[(BYTE)(c>>16)]++;
  308. Counting4[ c>>24 ]++;
  309. c = cached; cached = MEM_read32(ip); ip += 4;
  310. Counting1[(BYTE) c ]++;
  311. Counting2[(BYTE)(c>>8) ]++;
  312. Counting3[(BYTE)(c>>16)]++;
  313. Counting4[ c>>24 ]++;
  314. }
  315. ip-=4;
  316. }
  317. /* finish last symbols */
  318. while (ip<iend) Counting1[*ip++]++;
  319. if (checkMax) { /* verify stats will fit into destination table */
  320. U32 s; for (s=255; s>maxSymbolValue; s--) {
  321. Counting1[s] += Counting2[s] + Counting3[s] + Counting4[s];
  322. if (Counting1[s]) return ERROR(maxSymbolValue_tooSmall);
  323. } }
  324. { U32 s; for (s=0; s<=maxSymbolValue; s++) {
  325. count[s] = Counting1[s] + Counting2[s] + Counting3[s] + Counting4[s];
  326. if (count[s] > max) max = count[s];
  327. } }
  328. while (!count[maxSymbolValue]) maxSymbolValue--;
  329. *maxSymbolValuePtr = maxSymbolValue;
  330. return (size_t)max;
  331. }
  332. /* FSE_countFast_wksp() :
  333. * Same as FSE_countFast(), but using an externally provided scratch buffer.
  334. * `workSpace` size must be table of >= `1024` unsigned */
  335. size_t FSE_countFast_wksp(unsigned* count, unsigned* maxSymbolValuePtr,
  336. const void* source, size_t sourceSize, unsigned* workSpace)
  337. {
  338. if (sourceSize < 1500) return FSE_count_simple(count, maxSymbolValuePtr, source, sourceSize);
  339. return FSE_count_parallel_wksp(count, maxSymbolValuePtr, source, sourceSize, 0, workSpace);
  340. }
  341. /* fast variant (unsafe : won't check if src contains values beyond count[] limit) */
  342. size_t FSE_countFast(unsigned* count, unsigned* maxSymbolValuePtr,
  343. const void* source, size_t sourceSize)
  344. {
  345. unsigned tmpCounters[1024];
  346. return FSE_countFast_wksp(count, maxSymbolValuePtr, source, sourceSize, tmpCounters);
  347. }
  348. /* FSE_count_wksp() :
  349. * Same as FSE_count(), but using an externally provided scratch buffer.
  350. * `workSpace` size must be table of >= `1024` unsigned */
  351. size_t FSE_count_wksp(unsigned* count, unsigned* maxSymbolValuePtr,
  352. const void* source, size_t sourceSize, unsigned* workSpace)
  353. {
  354. if (*maxSymbolValuePtr < 255)
  355. return FSE_count_parallel_wksp(count, maxSymbolValuePtr, source, sourceSize, 1, workSpace);
  356. *maxSymbolValuePtr = 255;
  357. return FSE_countFast_wksp(count, maxSymbolValuePtr, source, sourceSize, workSpace);
  358. }
  359. size_t FSE_count(unsigned* count, unsigned* maxSymbolValuePtr,
  360. const void* src, size_t srcSize)
  361. {
  362. unsigned tmpCounters[1024];
  363. return FSE_count_wksp(count, maxSymbolValuePtr, src, srcSize, tmpCounters);
  364. }
  365. /*-**************************************************************
  366. * FSE Compression Code
  367. ****************************************************************/
  368. /*! FSE_sizeof_CTable() :
  369. FSE_CTable is a variable size structure which contains :
  370. `U16 tableLog;`
  371. `U16 maxSymbolValue;`
  372. `U16 nextStateNumber[1 << tableLog];` // This size is variable
  373. `FSE_symbolCompressionTransform symbolTT[maxSymbolValue+1];` // This size is variable
  374. Allocation is manual (C standard does not support variable-size structures).
  375. */
  376. size_t FSE_sizeof_CTable (unsigned maxSymbolValue, unsigned tableLog)
  377. {
  378. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  379. return FSE_CTABLE_SIZE_U32 (tableLog, maxSymbolValue) * sizeof(U32);
  380. }
  381. FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog)
  382. {
  383. size_t size;
  384. if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX;
  385. size = FSE_CTABLE_SIZE_U32 (tableLog, maxSymbolValue) * sizeof(U32);
  386. return (FSE_CTable*)malloc(size);
  387. }
  388. void FSE_freeCTable (FSE_CTable* ct) { free(ct); }
  389. /* provides the minimum logSize to safely represent a distribution */
  390. static unsigned FSE_minTableLog(size_t srcSize, unsigned maxSymbolValue)
  391. {
  392. U32 minBitsSrc = BIT_highbit32((U32)(srcSize - 1)) + 1;
  393. U32 minBitsSymbols = BIT_highbit32(maxSymbolValue) + 2;
  394. U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
  395. assert(srcSize > 1); /* Not supported, RLE should be used instead */
  396. return minBits;
  397. }
  398. unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
  399. {
  400. U32 maxBitsSrc = BIT_highbit32((U32)(srcSize - 1)) - minus;
  401. U32 tableLog = maxTableLog;
  402. U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
  403. assert(srcSize > 1); /* Not supported, RLE should be used instead */
  404. if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
  405. if (maxBitsSrc < tableLog) tableLog = maxBitsSrc; /* Accuracy can be reduced */
  406. if (minBits > tableLog) tableLog = minBits; /* Need a minimum to safely represent all symbol values */
  407. if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
  408. if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
  409. return tableLog;
  410. }
  411. unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
  412. {
  413. return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 2);
  414. }
  415. /* Secondary normalization method.
  416. To be used when primary method fails. */
  417. static size_t FSE_normalizeM2(short* norm, U32 tableLog, const unsigned* count, size_t total, U32 maxSymbolValue)
  418. {
  419. short const NOT_YET_ASSIGNED = -2;
  420. U32 s;
  421. U32 distributed = 0;
  422. U32 ToDistribute;
  423. /* Init */
  424. U32 const lowThreshold = (U32)(total >> tableLog);
  425. U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
  426. for (s=0; s<=maxSymbolValue; s++) {
  427. if (count[s] == 0) {
  428. norm[s]=0;
  429. continue;
  430. }
  431. if (count[s] <= lowThreshold) {
  432. norm[s] = -1;
  433. distributed++;
  434. total -= count[s];
  435. continue;
  436. }
  437. if (count[s] <= lowOne) {
  438. norm[s] = 1;
  439. distributed++;
  440. total -= count[s];
  441. continue;
  442. }
  443. norm[s]=NOT_YET_ASSIGNED;
  444. }
  445. ToDistribute = (1 << tableLog) - distributed;
  446. if ((total / ToDistribute) > lowOne) {
  447. /* risk of rounding to zero */
  448. lowOne = (U32)((total * 3) / (ToDistribute * 2));
  449. for (s=0; s<=maxSymbolValue; s++) {
  450. if ((norm[s] == NOT_YET_ASSIGNED) && (count[s] <= lowOne)) {
  451. norm[s] = 1;
  452. distributed++;
  453. total -= count[s];
  454. continue;
  455. } }
  456. ToDistribute = (1 << tableLog) - distributed;
  457. }
  458. if (distributed == maxSymbolValue+1) {
  459. /* all values are pretty poor;
  460. probably incompressible data (should have already been detected);
  461. find max, then give all remaining points to max */
  462. U32 maxV = 0, maxC = 0;
  463. for (s=0; s<=maxSymbolValue; s++)
  464. if (count[s] > maxC) maxV=s, maxC=count[s];
  465. norm[maxV] += (short)ToDistribute;
  466. return 0;
  467. }
  468. if (total == 0) {
  469. /* all of the symbols were low enough for the lowOne or lowThreshold */
  470. for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
  471. if (norm[s] > 0) ToDistribute--, norm[s]++;
  472. return 0;
  473. }
  474. { U64 const vStepLog = 62 - tableLog;
  475. U64 const mid = (1ULL << (vStepLog-1)) - 1;
  476. U64 const rStep = ((((U64)1<<vStepLog) * ToDistribute) + mid) / total; /* scale on remaining */
  477. U64 tmpTotal = mid;
  478. for (s=0; s<=maxSymbolValue; s++) {
  479. if (norm[s]==NOT_YET_ASSIGNED) {
  480. U64 const end = tmpTotal + (count[s] * rStep);
  481. U32 const sStart = (U32)(tmpTotal >> vStepLog);
  482. U32 const sEnd = (U32)(end >> vStepLog);
  483. U32 const weight = sEnd - sStart;
  484. if (weight < 1)
  485. return ERROR(GENERIC);
  486. norm[s] = (short)weight;
  487. tmpTotal = end;
  488. } } }
  489. return 0;
  490. }
  491. size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
  492. const unsigned* count, size_t total,
  493. unsigned maxSymbolValue)
  494. {
  495. /* Sanity checks */
  496. if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
  497. if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported size */
  498. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported size */
  499. if (tableLog < FSE_minTableLog(total, maxSymbolValue)) return ERROR(GENERIC); /* Too small tableLog, compression potentially impossible */
  500. { static U32 const rtbTable[] = { 0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
  501. U64 const scale = 62 - tableLog;
  502. U64 const step = ((U64)1<<62) / total; /* <== here, one division ! */
  503. U64 const vStep = 1ULL<<(scale-20);
  504. int stillToDistribute = 1<<tableLog;
  505. unsigned s;
  506. unsigned largest=0;
  507. short largestP=0;
  508. U32 lowThreshold = (U32)(total >> tableLog);
  509. for (s=0; s<=maxSymbolValue; s++) {
  510. if (count[s] == total) return 0; /* rle special case */
  511. if (count[s] == 0) { normalizedCounter[s]=0; continue; }
  512. if (count[s] <= lowThreshold) {
  513. normalizedCounter[s] = -1;
  514. stillToDistribute--;
  515. } else {
  516. short proba = (short)((count[s]*step) >> scale);
  517. if (proba<8) {
  518. U64 restToBeat = vStep * rtbTable[proba];
  519. proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
  520. }
  521. if (proba > largestP) largestP=proba, largest=s;
  522. normalizedCounter[s] = proba;
  523. stillToDistribute -= proba;
  524. } }
  525. if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
  526. /* corner case, need another normalization method */
  527. size_t const errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue);
  528. if (FSE_isError(errorCode)) return errorCode;
  529. }
  530. else normalizedCounter[largest] += (short)stillToDistribute;
  531. }
  532. #if 0
  533. { /* Print Table (debug) */
  534. U32 s;
  535. U32 nTotal = 0;
  536. for (s=0; s<=maxSymbolValue; s++)
  537. printf("%3i: %4i \n", s, normalizedCounter[s]);
  538. for (s=0; s<=maxSymbolValue; s++)
  539. nTotal += abs(normalizedCounter[s]);
  540. if (nTotal != (1U<<tableLog))
  541. printf("Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
  542. getchar();
  543. }
  544. #endif
  545. return tableLog;
  546. }
  547. /* fake FSE_CTable, for raw (uncompressed) input */
  548. size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits)
  549. {
  550. const unsigned tableSize = 1 << nbBits;
  551. const unsigned tableMask = tableSize - 1;
  552. const unsigned maxSymbolValue = tableMask;
  553. void* const ptr = ct;
  554. U16* const tableU16 = ( (U16*) ptr) + 2;
  555. void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableSize>>1); /* assumption : tableLog >= 1 */
  556. FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
  557. unsigned s;
  558. /* Sanity checks */
  559. if (nbBits < 1) return ERROR(GENERIC); /* min size */
  560. /* header */
  561. tableU16[-2] = (U16) nbBits;
  562. tableU16[-1] = (U16) maxSymbolValue;
  563. /* Build table */
  564. for (s=0; s<tableSize; s++)
  565. tableU16[s] = (U16)(tableSize + s);
  566. /* Build Symbol Transformation Table */
  567. { const U32 deltaNbBits = (nbBits << 16) - (1 << nbBits);
  568. for (s=0; s<=maxSymbolValue; s++) {
  569. symbolTT[s].deltaNbBits = deltaNbBits;
  570. symbolTT[s].deltaFindState = s-1;
  571. } }
  572. return 0;
  573. }
  574. /* fake FSE_CTable, for rle input (always same symbol) */
  575. size_t FSE_buildCTable_rle (FSE_CTable* ct, BYTE symbolValue)
  576. {
  577. void* ptr = ct;
  578. U16* tableU16 = ( (U16*) ptr) + 2;
  579. void* FSCTptr = (U32*)ptr + 2;
  580. FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
  581. /* header */
  582. tableU16[-2] = (U16) 0;
  583. tableU16[-1] = (U16) symbolValue;
  584. /* Build table */
  585. tableU16[0] = 0;
  586. tableU16[1] = 0; /* just in case */
  587. /* Build Symbol Transformation Table */
  588. symbolTT[symbolValue].deltaNbBits = 0;
  589. symbolTT[symbolValue].deltaFindState = 0;
  590. return 0;
  591. }
  592. static size_t FSE_compress_usingCTable_generic (void* dst, size_t dstSize,
  593. const void* src, size_t srcSize,
  594. const FSE_CTable* ct, const unsigned fast)
  595. {
  596. const BYTE* const istart = (const BYTE*) src;
  597. const BYTE* const iend = istart + srcSize;
  598. const BYTE* ip=iend;
  599. BIT_CStream_t bitC;
  600. FSE_CState_t CState1, CState2;
  601. /* init */
  602. if (srcSize <= 2) return 0;
  603. { size_t const initError = BIT_initCStream(&bitC, dst, dstSize);
  604. if (FSE_isError(initError)) return 0; /* not enough space available to write a bitstream */ }
  605. #define FSE_FLUSHBITS(s) (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
  606. if (srcSize & 1) {
  607. FSE_initCState2(&CState1, ct, *--ip);
  608. FSE_initCState2(&CState2, ct, *--ip);
  609. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  610. FSE_FLUSHBITS(&bitC);
  611. } else {
  612. FSE_initCState2(&CState2, ct, *--ip);
  613. FSE_initCState2(&CState1, ct, *--ip);
  614. }
  615. /* join to mod 4 */
  616. srcSize -= 2;
  617. if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) { /* test bit 2 */
  618. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  619. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  620. FSE_FLUSHBITS(&bitC);
  621. }
  622. /* 2 or 4 encoding per loop */
  623. while ( ip>istart ) {
  624. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  625. if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 ) /* this test must be static */
  626. FSE_FLUSHBITS(&bitC);
  627. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  628. if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) { /* this test must be static */
  629. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  630. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  631. }
  632. FSE_FLUSHBITS(&bitC);
  633. }
  634. FSE_flushCState(&bitC, &CState2);
  635. FSE_flushCState(&bitC, &CState1);
  636. return BIT_closeCStream(&bitC);
  637. }
  638. size_t FSE_compress_usingCTable (void* dst, size_t dstSize,
  639. const void* src, size_t srcSize,
  640. const FSE_CTable* ct)
  641. {
  642. unsigned const fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
  643. if (fast)
  644. return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
  645. else
  646. return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
  647. }
  648. size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); }
  649. #define CHECK_V_F(e, f) size_t const e = f; if (ERR_isError(e)) return e
  650. #define CHECK_F(f) { CHECK_V_F(_var_err__, f); }
  651. /* FSE_compress_wksp() :
  652. * Same as FSE_compress2(), but using an externally allocated scratch buffer (`workSpace`).
  653. * `wkspSize` size must be `(1<<tableLog)`.
  654. */
  655. 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)
  656. {
  657. BYTE* const ostart = (BYTE*) dst;
  658. BYTE* op = ostart;
  659. BYTE* const oend = ostart + dstSize;
  660. U32 count[FSE_MAX_SYMBOL_VALUE+1];
  661. S16 norm[FSE_MAX_SYMBOL_VALUE+1];
  662. FSE_CTable* CTable = (FSE_CTable*)workSpace;
  663. size_t const CTableSize = FSE_CTABLE_SIZE_U32(tableLog, maxSymbolValue);
  664. void* scratchBuffer = (void*)(CTable + CTableSize);
  665. size_t const scratchBufferSize = wkspSize - (CTableSize * sizeof(FSE_CTable));
  666. /* init conditions */
  667. if (wkspSize < FSE_WKSP_SIZE_U32(tableLog, maxSymbolValue)) return ERROR(tableLog_tooLarge);
  668. if (srcSize <= 1) return 0; /* Not compressible */
  669. if (!maxSymbolValue) maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  670. if (!tableLog) tableLog = FSE_DEFAULT_TABLELOG;
  671. /* Scan input and build symbol stats */
  672. { CHECK_V_F(maxCount, FSE_count_wksp(count, &maxSymbolValue, src, srcSize, (unsigned*)scratchBuffer) );
  673. if (maxCount == srcSize) return 1; /* only a single symbol in src : rle */
  674. if (maxCount == 1) return 0; /* each symbol present maximum once => not compressible */
  675. if (maxCount < (srcSize >> 7)) return 0; /* Heuristic : not compressible enough */
  676. }
  677. tableLog = FSE_optimalTableLog(tableLog, srcSize, maxSymbolValue);
  678. CHECK_F( FSE_normalizeCount(norm, tableLog, count, srcSize, maxSymbolValue) );
  679. /* Write table description header */
  680. { CHECK_V_F(nc_err, FSE_writeNCount(op, oend-op, norm, maxSymbolValue, tableLog) );
  681. op += nc_err;
  682. }
  683. /* Compress */
  684. CHECK_F( FSE_buildCTable_wksp(CTable, norm, maxSymbolValue, tableLog, scratchBuffer, scratchBufferSize) );
  685. { CHECK_V_F(cSize, FSE_compress_usingCTable(op, oend - op, src, srcSize, CTable) );
  686. if (cSize == 0) return 0; /* not enough space for compressed data */
  687. op += cSize;
  688. }
  689. /* check compressibility */
  690. if ( (size_t)(op-ostart) >= srcSize-1 ) return 0;
  691. return op-ostart;
  692. }
  693. typedef struct {
  694. FSE_CTable CTable_max[FSE_CTABLE_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)];
  695. BYTE scratchBuffer[1 << FSE_MAX_TABLELOG];
  696. } fseWkspMax_t;
  697. size_t FSE_compress2 (void* dst, size_t dstCapacity, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog)
  698. {
  699. fseWkspMax_t scratchBuffer;
  700. FSE_STATIC_ASSERT(sizeof(scratchBuffer) >= FSE_WKSP_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)); /* compilation failures here means scratchBuffer is not large enough */
  701. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  702. return FSE_compress_wksp(dst, dstCapacity, src, srcSize, maxSymbolValue, tableLog, &scratchBuffer, sizeof(scratchBuffer));
  703. }
  704. size_t FSE_compress (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  705. {
  706. return FSE_compress2(dst, dstCapacity, src, srcSize, FSE_MAX_SYMBOL_VALUE, FSE_DEFAULT_TABLELOG);
  707. }
  708. #endif /* FSE_COMMONDEFS_ONLY */