fse_compress.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. * Compiler specifics
  31. ****************************************************************/
  32. #ifdef _MSC_VER /* Visual Studio */
  33. # define FORCE_INLINE static __forceinline
  34. # include <intrin.h> /* For Visual 2005 */
  35. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  36. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  37. #else
  38. # ifdef __GNUC__
  39. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
  40. # define FORCE_INLINE static inline __attribute__((always_inline))
  41. # else
  42. # define FORCE_INLINE static inline
  43. # endif
  44. #endif
  45. /* **************************************************************
  46. * Includes
  47. ****************************************************************/
  48. #include <stdlib.h> /* malloc, free, qsort */
  49. #include <string.h> /* memcpy, memset */
  50. #include <stdio.h> /* printf (debug) */
  51. #include "bitstream.h"
  52. #include "fse_static.h"
  53. /* **************************************************************
  54. * Error Management
  55. ****************************************************************/
  56. #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  57. /* **************************************************************
  58. * Complex types
  59. ****************************************************************/
  60. typedef U32 CTable_max_t[FSE_CTABLE_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)];
  61. /* **************************************************************
  62. * Templates
  63. ****************************************************************/
  64. /*
  65. designed to be included
  66. for type-specific functions (template emulation in C)
  67. Objective is to write these functions only once, for improved maintenance
  68. */
  69. /* safety checks */
  70. #ifndef FSE_FUNCTION_EXTENSION
  71. # error "FSE_FUNCTION_EXTENSION must be defined"
  72. #endif
  73. #ifndef FSE_FUNCTION_TYPE
  74. # error "FSE_FUNCTION_TYPE must be defined"
  75. #endif
  76. /* Function names */
  77. #define FSE_CAT(X,Y) X##Y
  78. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  79. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  80. /* Function templates */
  81. size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  82. {
  83. U32 const tableSize = 1 << tableLog;
  84. U32 const tableMask = tableSize - 1;
  85. void* const ptr = ct;
  86. U16* const tableU16 = ( (U16*) ptr) + 2;
  87. void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableLog ? tableSize>>1 : 1) ;
  88. FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
  89. U32 const step = FSE_TABLESTEP(tableSize);
  90. U32 cumul[FSE_MAX_SYMBOL_VALUE+2];
  91. FSE_FUNCTION_TYPE tableSymbol[FSE_MAX_TABLESIZE]; /* memset() is not necessary, even if static analyzer complain about it */
  92. U32 highThreshold = tableSize-1;
  93. /* CTable header */
  94. tableU16[-2] = (U16) tableLog;
  95. tableU16[-1] = (U16) maxSymbolValue;
  96. /* For explanations on how to distribute symbol values over the table :
  97. * http://fastcompression.blogspot.fr/2014/02/fse-distributing-symbol-values.html */
  98. /* symbol start positions */
  99. { U32 u;
  100. cumul[0] = 0;
  101. for (u=1; u<=maxSymbolValue+1; u++) {
  102. if (normalizedCounter[u-1]==-1) { /* Low proba symbol */
  103. cumul[u] = cumul[u-1] + 1;
  104. tableSymbol[highThreshold--] = (FSE_FUNCTION_TYPE)(u-1);
  105. } else {
  106. cumul[u] = cumul[u-1] + normalizedCounter[u-1];
  107. } }
  108. cumul[maxSymbolValue+1] = tableSize+1;
  109. }
  110. /* Spread symbols */
  111. { U32 position = 0;
  112. U32 symbol;
  113. for (symbol=0; symbol<=maxSymbolValue; symbol++) {
  114. int nbOccurences;
  115. for (nbOccurences=0; nbOccurences<normalizedCounter[symbol]; nbOccurences++) {
  116. tableSymbol[position] = (FSE_FUNCTION_TYPE)symbol;
  117. position = (position + step) & tableMask;
  118. while (position > highThreshold) position = (position + step) & tableMask; /* Low proba area */
  119. } }
  120. if (position!=0) return ERROR(GENERIC); /* Must have gone through all positions */
  121. }
  122. /* Build table */
  123. { U32 u; for (u=0; u<tableSize; u++) {
  124. FSE_FUNCTION_TYPE s = tableSymbol[u]; /* note : static analyzer may not understand tableSymbol is properly initialized */
  125. tableU16[cumul[s]++] = (U16) (tableSize+u); /* TableU16 : sorted by symbol order; gives next state value */
  126. }}
  127. /* Build Symbol Transformation Table */
  128. { unsigned total = 0;
  129. unsigned s;
  130. for (s=0; s<=maxSymbolValue; s++) {
  131. switch (normalizedCounter[s])
  132. {
  133. case 0: break;
  134. case -1:
  135. case 1:
  136. symbolTT[s].deltaNbBits = (tableLog << 16) - (1<<tableLog);
  137. symbolTT[s].deltaFindState = total - 1;
  138. total ++;
  139. break;
  140. default :
  141. {
  142. U32 const maxBitsOut = tableLog - BIT_highbit32 (normalizedCounter[s]-1);
  143. U32 const minStatePlus = normalizedCounter[s] << maxBitsOut;
  144. symbolTT[s].deltaNbBits = (maxBitsOut << 16) - minStatePlus;
  145. symbolTT[s].deltaFindState = total - normalizedCounter[s];
  146. total += normalizedCounter[s];
  147. } } } }
  148. return 0;
  149. }
  150. #ifndef FSE_COMMONDEFS_ONLY
  151. /*-**************************************************************
  152. * FSE NCount encoding-decoding
  153. ****************************************************************/
  154. size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
  155. {
  156. size_t maxHeaderSize = (((maxSymbolValue+1) * tableLog) >> 3) + 3;
  157. return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND; /* maxSymbolValue==0 ? use default */
  158. }
  159. static short FSE_abs(short a) { return a<0 ? -a : a; }
  160. static size_t FSE_writeNCount_generic (void* header, size_t headerBufferSize,
  161. const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
  162. unsigned writeIsSafe)
  163. {
  164. BYTE* const ostart = (BYTE*) header;
  165. BYTE* out = ostart;
  166. BYTE* const oend = ostart + headerBufferSize;
  167. int nbBits;
  168. const int tableSize = 1 << tableLog;
  169. int remaining;
  170. int threshold;
  171. U32 bitStream;
  172. int bitCount;
  173. unsigned charnum = 0;
  174. int previous0 = 0;
  175. bitStream = 0;
  176. bitCount = 0;
  177. /* Table Size */
  178. bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
  179. bitCount += 4;
  180. /* Init */
  181. remaining = tableSize+1; /* +1 for extra accuracy */
  182. threshold = tableSize;
  183. nbBits = tableLog+1;
  184. while (remaining>1) { /* stops at 1 */
  185. if (previous0) {
  186. unsigned start = charnum;
  187. while (!normalizedCounter[charnum]) charnum++;
  188. while (charnum >= start+24) {
  189. start+=24;
  190. bitStream += 0xFFFFU << bitCount;
  191. if ((!writeIsSafe) && (out > oend-2)) return ERROR(dstSize_tooSmall); /* Buffer overflow */
  192. out[0] = (BYTE) bitStream;
  193. out[1] = (BYTE)(bitStream>>8);
  194. out+=2;
  195. bitStream>>=16;
  196. }
  197. while (charnum >= start+3) {
  198. start+=3;
  199. bitStream += 3 << bitCount;
  200. bitCount += 2;
  201. }
  202. bitStream += (charnum-start) << bitCount;
  203. bitCount += 2;
  204. if (bitCount>16) {
  205. if ((!writeIsSafe) && (out > oend - 2)) return ERROR(dstSize_tooSmall); /* Buffer overflow */
  206. out[0] = (BYTE)bitStream;
  207. out[1] = (BYTE)(bitStream>>8);
  208. out += 2;
  209. bitStream >>= 16;
  210. bitCount -= 16;
  211. } }
  212. { short count = normalizedCounter[charnum++];
  213. const short max = (short)((2*threshold-1)-remaining);
  214. remaining -= FSE_abs(count);
  215. if (remaining<1) return ERROR(GENERIC);
  216. count++; /* +1 for extra accuracy */
  217. if (count>=threshold) count += max; /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
  218. bitStream += count << bitCount;
  219. bitCount += nbBits;
  220. bitCount -= (count<max);
  221. previous0 = (count==1);
  222. while (remaining<threshold) nbBits--, threshold>>=1;
  223. }
  224. if (bitCount>16) {
  225. if ((!writeIsSafe) && (out > oend - 2)) return ERROR(dstSize_tooSmall); /* Buffer overflow */
  226. out[0] = (BYTE)bitStream;
  227. out[1] = (BYTE)(bitStream>>8);
  228. out += 2;
  229. bitStream >>= 16;
  230. bitCount -= 16;
  231. } }
  232. /* flush remaining bitStream */
  233. if ((!writeIsSafe) && (out > oend - 2)) return ERROR(dstSize_tooSmall); /* Buffer overflow */
  234. out[0] = (BYTE)bitStream;
  235. out[1] = (BYTE)(bitStream>>8);
  236. out+= (bitCount+7) /8;
  237. if (charnum > maxSymbolValue + 1) return ERROR(GENERIC);
  238. return (out-ostart);
  239. }
  240. size_t FSE_writeNCount (void* buffer, size_t bufferSize, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  241. {
  242. if (tableLog > FSE_MAX_TABLELOG) return ERROR(GENERIC); /* Unsupported */
  243. if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported */
  244. if (bufferSize < FSE_NCountWriteBound(maxSymbolValue, tableLog))
  245. return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
  246. return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1);
  247. }
  248. /*-**************************************************************
  249. * Counting histogram
  250. ****************************************************************/
  251. /*! FSE_count_simple
  252. This function just counts byte values within `src`,
  253. and store the histogram into table `count`.
  254. This function is unsafe : it doesn't check that all values within `src` can fit into `count`.
  255. For this reason, prefer using a table `count` with 256 elements.
  256. @return : count of most numerous element
  257. */
  258. static size_t FSE_count_simple(unsigned* count, unsigned* maxSymbolValuePtr,
  259. const void* src, size_t srcSize)
  260. {
  261. const BYTE* ip = (const BYTE*)src;
  262. const BYTE* const end = ip + srcSize;
  263. unsigned maxSymbolValue = *maxSymbolValuePtr;
  264. unsigned max=0;
  265. memset(count, 0, (maxSymbolValue+1)*sizeof(*count));
  266. if (srcSize==0) { *maxSymbolValuePtr = 0; return 0; }
  267. while (ip<end) count[*ip++]++;
  268. while (!count[maxSymbolValue]) maxSymbolValue--;
  269. *maxSymbolValuePtr = maxSymbolValue;
  270. { U32 s; for (s=0; s<=maxSymbolValue; s++) if (count[s] > max) max = count[s]; }
  271. return (size_t)max;
  272. }
  273. static size_t FSE_count_parallel(unsigned* count, unsigned* maxSymbolValuePtr,
  274. const void* source, size_t sourceSize,
  275. unsigned checkMax)
  276. {
  277. const BYTE* ip = (const BYTE*)source;
  278. const BYTE* const iend = ip+sourceSize;
  279. unsigned maxSymbolValue = *maxSymbolValuePtr;
  280. unsigned max=0;
  281. U32 Counting1[256] = { 0 };
  282. U32 Counting2[256] = { 0 };
  283. U32 Counting3[256] = { 0 };
  284. U32 Counting4[256] = { 0 };
  285. /* safety checks */
  286. if (!sourceSize) {
  287. memset(count, 0, maxSymbolValue + 1);
  288. *maxSymbolValuePtr = 0;
  289. return 0;
  290. }
  291. if (!maxSymbolValue) maxSymbolValue = 255; /* 0 == default */
  292. /* by stripes of 16 bytes */
  293. { U32 cached = MEM_read32(ip); ip += 4;
  294. while (ip < iend-15) {
  295. U32 c = cached; cached = MEM_read32(ip); ip += 4;
  296. Counting1[(BYTE) c ]++;
  297. Counting2[(BYTE)(c>>8) ]++;
  298. Counting3[(BYTE)(c>>16)]++;
  299. Counting4[ c>>24 ]++;
  300. c = cached; cached = MEM_read32(ip); ip += 4;
  301. Counting1[(BYTE) c ]++;
  302. Counting2[(BYTE)(c>>8) ]++;
  303. Counting3[(BYTE)(c>>16)]++;
  304. Counting4[ c>>24 ]++;
  305. c = cached; cached = MEM_read32(ip); ip += 4;
  306. Counting1[(BYTE) c ]++;
  307. Counting2[(BYTE)(c>>8) ]++;
  308. Counting3[(BYTE)(c>>16)]++;
  309. Counting4[ c>>24 ]++;
  310. c = cached; cached = MEM_read32(ip); ip += 4;
  311. Counting1[(BYTE) c ]++;
  312. Counting2[(BYTE)(c>>8) ]++;
  313. Counting3[(BYTE)(c>>16)]++;
  314. Counting4[ c>>24 ]++;
  315. }
  316. ip-=4;
  317. }
  318. /* finish last symbols */
  319. while (ip<iend) Counting1[*ip++]++;
  320. if (checkMax) { /* verify stats will fit into destination table */
  321. U32 s; for (s=255; s>maxSymbolValue; s--) {
  322. Counting1[s] += Counting2[s] + Counting3[s] + Counting4[s];
  323. if (Counting1[s]) return ERROR(maxSymbolValue_tooSmall);
  324. } }
  325. { U32 s; for (s=0; s<=maxSymbolValue; s++) {
  326. count[s] = Counting1[s] + Counting2[s] + Counting3[s] + Counting4[s];
  327. if (count[s] > max) max = count[s];
  328. }}
  329. while (!count[maxSymbolValue]) maxSymbolValue--;
  330. *maxSymbolValuePtr = maxSymbolValue;
  331. return (size_t)max;
  332. }
  333. /* fast variant (unsafe : won't check if src contains values beyond count[] limit) */
  334. size_t FSE_countFast(unsigned* count, unsigned* maxSymbolValuePtr,
  335. const void* source, size_t sourceSize)
  336. {
  337. if (sourceSize < 1500) return FSE_count_simple(count, maxSymbolValuePtr, source, sourceSize);
  338. return FSE_count_parallel(count, maxSymbolValuePtr, source, sourceSize, 0);
  339. }
  340. size_t FSE_count(unsigned* count, unsigned* maxSymbolValuePtr,
  341. const void* source, size_t sourceSize)
  342. {
  343. if (*maxSymbolValuePtr <255)
  344. return FSE_count_parallel(count, maxSymbolValuePtr, source, sourceSize, 1);
  345. *maxSymbolValuePtr = 255;
  346. return FSE_countFast(count, maxSymbolValuePtr, source, sourceSize);
  347. }
  348. /*-**************************************************************
  349. * FSE Compression Code
  350. ****************************************************************/
  351. /*! FSE_sizeof_CTable() :
  352. FSE_CTable is a variable size structure which contains :
  353. `U16 tableLog;`
  354. `U16 maxSymbolValue;`
  355. `U16 nextStateNumber[1 << tableLog];` // This size is variable
  356. `FSE_symbolCompressionTransform symbolTT[maxSymbolValue+1];` // This size is variable
  357. Allocation is manual (C standard does not support variable-size structures).
  358. */
  359. size_t FSE_sizeof_CTable (unsigned maxSymbolValue, unsigned tableLog)
  360. {
  361. size_t size;
  362. FSE_STATIC_ASSERT((size_t)FSE_CTABLE_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)*4 >= sizeof(CTable_max_t)); /* A compilation error here means FSE_CTABLE_SIZE_U32 is not large enough */
  363. if (tableLog > FSE_MAX_TABLELOG) return ERROR(GENERIC);
  364. size = FSE_CTABLE_SIZE_U32 (tableLog, maxSymbolValue) * sizeof(U32);
  365. return size;
  366. }
  367. FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog)
  368. {
  369. size_t size;
  370. if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX;
  371. size = FSE_CTABLE_SIZE_U32 (tableLog, maxSymbolValue) * sizeof(U32);
  372. return (FSE_CTable*)malloc(size);
  373. }
  374. void FSE_freeCTable (FSE_CTable* ct) { free(ct); }
  375. /* provides the minimum logSize to safely represent a distribution */
  376. static unsigned FSE_minTableLog(size_t srcSize, unsigned maxSymbolValue)
  377. {
  378. U32 minBitsSrc = BIT_highbit32((U32)(srcSize - 1)) + 1;
  379. U32 minBitsSymbols = BIT_highbit32(maxSymbolValue) + 2;
  380. U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
  381. return minBits;
  382. }
  383. unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
  384. {
  385. U32 maxBitsSrc = BIT_highbit32((U32)(srcSize - 1)) - 2;
  386. U32 tableLog = maxTableLog;
  387. U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
  388. if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
  389. if (maxBitsSrc < tableLog) tableLog = maxBitsSrc; /* Accuracy can be reduced */
  390. if (minBits > tableLog) tableLog = minBits; /* Need a minimum to safely represent all symbol values */
  391. if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
  392. if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
  393. return tableLog;
  394. }
  395. /* Secondary normalization method.
  396. To be used when primary method fails. */
  397. static size_t FSE_normalizeM2(short* norm, U32 tableLog, const unsigned* count, size_t total, U32 maxSymbolValue)
  398. {
  399. U32 s;
  400. U32 distributed = 0;
  401. U32 ToDistribute;
  402. /* Init */
  403. U32 lowThreshold = (U32)(total >> tableLog);
  404. U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
  405. for (s=0; s<=maxSymbolValue; s++) {
  406. if (count[s] == 0) {
  407. norm[s]=0;
  408. continue;
  409. }
  410. if (count[s] <= lowThreshold) {
  411. norm[s] = -1;
  412. distributed++;
  413. total -= count[s];
  414. continue;
  415. }
  416. if (count[s] <= lowOne) {
  417. norm[s] = 1;
  418. distributed++;
  419. total -= count[s];
  420. continue;
  421. }
  422. norm[s]=-2;
  423. }
  424. ToDistribute = (1 << tableLog) - distributed;
  425. if ((total / ToDistribute) > lowOne) {
  426. /* risk of rounding to zero */
  427. lowOne = (U32)((total * 3) / (ToDistribute * 2));
  428. for (s=0; s<=maxSymbolValue; s++) {
  429. if ((norm[s] == -2) && (count[s] <= lowOne)) {
  430. norm[s] = 1;
  431. distributed++;
  432. total -= count[s];
  433. continue;
  434. } }
  435. ToDistribute = (1 << tableLog) - distributed;
  436. }
  437. if (distributed == maxSymbolValue+1) {
  438. /* all values are pretty poor;
  439. probably incompressible data (should have already been detected);
  440. find max, then give all remaining points to max */
  441. U32 maxV = 0, maxC = 0;
  442. for (s=0; s<=maxSymbolValue; s++)
  443. if (count[s] > maxC) maxV=s, maxC=count[s];
  444. norm[maxV] += (short)ToDistribute;
  445. return 0;
  446. }
  447. {
  448. U64 const vStepLog = 62 - tableLog;
  449. U64 const mid = (1ULL << (vStepLog-1)) - 1;
  450. U64 const rStep = ((((U64)1<<vStepLog) * ToDistribute) + mid) / total; /* scale on remaining */
  451. U64 tmpTotal = mid;
  452. for (s=0; s<=maxSymbolValue; s++) {
  453. if (norm[s]==-2) {
  454. U64 end = tmpTotal + (count[s] * rStep);
  455. U32 sStart = (U32)(tmpTotal >> vStepLog);
  456. U32 sEnd = (U32)(end >> vStepLog);
  457. U32 weight = sEnd - sStart;
  458. if (weight < 1)
  459. return ERROR(GENERIC);
  460. norm[s] = (short)weight;
  461. tmpTotal = end;
  462. } } }
  463. return 0;
  464. }
  465. size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
  466. const unsigned* count, size_t total,
  467. unsigned maxSymbolValue)
  468. {
  469. /* Sanity checks */
  470. if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
  471. if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported size */
  472. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported size */
  473. if (tableLog < FSE_minTableLog(total, maxSymbolValue)) return ERROR(GENERIC); /* Too small tableLog, compression potentially impossible */
  474. { U32 const rtbTable[] = { 0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
  475. U64 const scale = 62 - tableLog;
  476. U64 const step = ((U64)1<<62) / total; /* <== here, one division ! */
  477. U64 const vStep = 1ULL<<(scale-20);
  478. int stillToDistribute = 1<<tableLog;
  479. unsigned s;
  480. unsigned largest=0;
  481. short largestP=0;
  482. U32 lowThreshold = (U32)(total >> tableLog);
  483. for (s=0; s<=maxSymbolValue; s++) {
  484. if (count[s] == total) return 0; /* rle special case */
  485. if (count[s] == 0) { normalizedCounter[s]=0; continue; }
  486. if (count[s] <= lowThreshold) {
  487. normalizedCounter[s] = -1;
  488. stillToDistribute--;
  489. } else {
  490. short proba = (short)((count[s]*step) >> scale);
  491. if (proba<8) {
  492. U64 restToBeat = vStep * rtbTable[proba];
  493. proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
  494. }
  495. if (proba > largestP) largestP=proba, largest=s;
  496. normalizedCounter[s] = proba;
  497. stillToDistribute -= proba;
  498. } }
  499. if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
  500. /* corner case, need another normalization method */
  501. size_t errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue);
  502. if (FSE_isError(errorCode)) return errorCode;
  503. }
  504. else normalizedCounter[largest] += (short)stillToDistribute;
  505. }
  506. #if 0
  507. { /* Print Table (debug) */
  508. U32 s;
  509. U32 nTotal = 0;
  510. for (s=0; s<=maxSymbolValue; s++)
  511. printf("%3i: %4i \n", s, normalizedCounter[s]);
  512. for (s=0; s<=maxSymbolValue; s++)
  513. nTotal += abs(normalizedCounter[s]);
  514. if (nTotal != (1U<<tableLog))
  515. printf("Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
  516. getchar();
  517. }
  518. #endif
  519. return tableLog;
  520. }
  521. /* fake FSE_CTable, for raw (uncompressed) input */
  522. size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits)
  523. {
  524. const unsigned tableSize = 1 << nbBits;
  525. const unsigned tableMask = tableSize - 1;
  526. const unsigned maxSymbolValue = tableMask;
  527. void* const ptr = ct;
  528. U16* const tableU16 = ( (U16*) ptr) + 2;
  529. void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableSize>>1); /* assumption : tableLog >= 1 */
  530. FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
  531. unsigned s;
  532. /* Sanity checks */
  533. if (nbBits < 1) return ERROR(GENERIC); /* min size */
  534. /* header */
  535. tableU16[-2] = (U16) nbBits;
  536. tableU16[-1] = (U16) maxSymbolValue;
  537. /* Build table */
  538. for (s=0; s<tableSize; s++)
  539. tableU16[s] = (U16)(tableSize + s);
  540. /* Build Symbol Transformation Table */
  541. { const U32 deltaNbBits = (nbBits << 16) - (1 << nbBits);
  542. for (s=0; s<=maxSymbolValue; s++) {
  543. symbolTT[s].deltaNbBits = deltaNbBits;
  544. symbolTT[s].deltaFindState = s-1;
  545. } }
  546. return 0;
  547. }
  548. /* fake FSE_CTable, for rle (100% always same symbol) input */
  549. size_t FSE_buildCTable_rle (FSE_CTable* ct, BYTE symbolValue)
  550. {
  551. void* ptr = ct;
  552. U16* tableU16 = ( (U16*) ptr) + 2;
  553. void* FSCTptr = (U32*)ptr + 2;
  554. FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
  555. /* header */
  556. tableU16[-2] = (U16) 0;
  557. tableU16[-1] = (U16) symbolValue;
  558. /* Build table */
  559. tableU16[0] = 0;
  560. tableU16[1] = 0; /* just in case */
  561. /* Build Symbol Transformation Table */
  562. symbolTT[symbolValue].deltaNbBits = 0;
  563. symbolTT[symbolValue].deltaFindState = 0;
  564. return 0;
  565. }
  566. static size_t FSE_compress_usingCTable_generic (void* dst, size_t dstSize,
  567. const void* src, size_t srcSize,
  568. const FSE_CTable* ct, const unsigned fast)
  569. {
  570. const BYTE* const istart = (const BYTE*) src;
  571. const BYTE* const iend = istart + srcSize;
  572. const BYTE* ip=iend;
  573. BIT_CStream_t bitC;
  574. FSE_CState_t CState1, CState2;
  575. /* init */
  576. if (srcSize <= 2) return 0;
  577. { size_t const errorCode = BIT_initCStream(&bitC, dst, dstSize);
  578. if (FSE_isError(errorCode)) return 0; }
  579. #define FSE_FLUSHBITS(s) (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
  580. if (srcSize & 1) {
  581. FSE_initCState2(&CState1, ct, *--ip);
  582. FSE_initCState2(&CState2, ct, *--ip);
  583. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  584. FSE_FLUSHBITS(&bitC);
  585. } else {
  586. FSE_initCState2(&CState2, ct, *--ip);
  587. FSE_initCState2(&CState1, ct, *--ip);
  588. }
  589. /* join to mod 4 */
  590. srcSize -= 2;
  591. if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) { /* test bit 2 */
  592. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  593. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  594. FSE_FLUSHBITS(&bitC);
  595. }
  596. /* 2 or 4 encoding per loop */
  597. for ( ; ip>istart ; ) {
  598. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  599. if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 ) /* this test must be static */
  600. FSE_FLUSHBITS(&bitC);
  601. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  602. if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) { /* this test must be static */
  603. FSE_encodeSymbol(&bitC, &CState2, *--ip);
  604. FSE_encodeSymbol(&bitC, &CState1, *--ip);
  605. }
  606. FSE_FLUSHBITS(&bitC);
  607. }
  608. FSE_flushCState(&bitC, &CState2);
  609. FSE_flushCState(&bitC, &CState1);
  610. return BIT_closeCStream(&bitC);
  611. }
  612. size_t FSE_compress_usingCTable (void* dst, size_t dstSize,
  613. const void* src, size_t srcSize,
  614. const FSE_CTable* ct)
  615. {
  616. const unsigned fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
  617. if (fast)
  618. return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
  619. else
  620. return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
  621. }
  622. size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); }
  623. size_t FSE_compress2 (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog)
  624. {
  625. const BYTE* const istart = (const BYTE*) src;
  626. const BYTE* ip = istart;
  627. BYTE* const ostart = (BYTE*) dst;
  628. BYTE* op = ostart;
  629. BYTE* const oend = ostart + dstSize;
  630. U32 count[FSE_MAX_SYMBOL_VALUE+1];
  631. S16 norm[FSE_MAX_SYMBOL_VALUE+1];
  632. CTable_max_t ct;
  633. size_t errorCode;
  634. /* init conditions */
  635. if (srcSize <= 1) return 0; /* Uncompressible */
  636. if (!maxSymbolValue) maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  637. if (!tableLog) tableLog = FSE_DEFAULT_TABLELOG;
  638. /* Scan input and build symbol stats */
  639. errorCode = FSE_count (count, &maxSymbolValue, ip, srcSize);
  640. if (FSE_isError(errorCode)) return errorCode;
  641. if (errorCode == srcSize) return 1;
  642. if (errorCode == 1) return 0; /* each symbol only present once */
  643. if (errorCode < (srcSize >> 7)) return 0; /* Heuristic : not compressible enough */
  644. tableLog = FSE_optimalTableLog(tableLog, srcSize, maxSymbolValue);
  645. errorCode = FSE_normalizeCount (norm, tableLog, count, srcSize, maxSymbolValue);
  646. if (FSE_isError(errorCode)) return errorCode;
  647. /* Write table description header */
  648. errorCode = FSE_writeNCount (op, oend-op, norm, maxSymbolValue, tableLog);
  649. if (FSE_isError(errorCode)) return errorCode;
  650. op += errorCode;
  651. /* Compress */
  652. errorCode = FSE_buildCTable (ct, norm, maxSymbolValue, tableLog);
  653. if (FSE_isError(errorCode)) return errorCode;
  654. errorCode = FSE_compress_usingCTable(op, oend - op, ip, srcSize, ct);
  655. if (errorCode == 0) return 0; /* not enough space for compressed data */
  656. op += errorCode;
  657. /* check compressibility */
  658. if ( (size_t)(op-ostart) >= srcSize-1 )
  659. return 0;
  660. return op-ostart;
  661. }
  662. size_t FSE_compress (void* dst, size_t dstSize, const void* src, size_t srcSize)
  663. {
  664. return FSE_compress2(dst, dstSize, src, (U32)srcSize, FSE_MAX_SYMBOL_VALUE, FSE_DEFAULT_TABLELOG);
  665. }
  666. #endif /* FSE_COMMONDEFS_ONLY */