huf_compress.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. /*
  2. * Huffman encoder, part of New Generation Entropy library
  3. * Copyright (C) 2013-2016, Yann Collet.
  4. *
  5. * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are
  9. * met:
  10. *
  11. * * Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. * * Redistributions in binary form must reproduce the above
  14. * copyright notice, this list of conditions and the following disclaimer
  15. * in the documentation and/or other materials provided with the
  16. * distribution.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *
  30. * This program is free software; you can redistribute it and/or modify it under
  31. * the terms of the GNU General Public License version 2 as published by the
  32. * Free Software Foundation. This program is dual-licensed; you may select
  33. * either version 2 of the GNU General Public License ("GPL") or BSD license
  34. * ("BSD").
  35. *
  36. * You can contact the author at :
  37. * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  38. */
  39. /* **************************************************************
  40. * Includes
  41. ****************************************************************/
  42. #include "bitstream.h"
  43. #include "fse.h" /* header compression */
  44. #include "huf.h"
  45. #include <linux/kernel.h>
  46. #include <linux/string.h> /* memcpy, memset */
  47. /* **************************************************************
  48. * Error Management
  49. ****************************************************************/
  50. #define HUF_STATIC_ASSERT(c) \
  51. { \
  52. enum { HUF_static_assert = 1 / (int)(!!(c)) }; \
  53. } /* use only *after* variable declarations */
  54. #define CHECK_V_F(e, f) \
  55. size_t const e = f; \
  56. if (ERR_isError(e)) \
  57. return f
  58. #define CHECK_F(f) \
  59. { \
  60. CHECK_V_F(_var_err__, f); \
  61. }
  62. /* **************************************************************
  63. * Utils
  64. ****************************************************************/
  65. unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
  66. {
  67. return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 1);
  68. }
  69. /* *******************************************************
  70. * HUF : Huffman block compression
  71. *********************************************************/
  72. /* HUF_compressWeights() :
  73. * Same as FSE_compress(), but dedicated to huff0's weights compression.
  74. * The use case needs much less stack memory.
  75. * Note : all elements within weightTable are supposed to be <= HUF_TABLELOG_MAX.
  76. */
  77. #define MAX_FSE_TABLELOG_FOR_HUFF_HEADER 6
  78. size_t HUF_compressWeights_wksp(void *dst, size_t dstSize, const void *weightTable, size_t wtSize, void *workspace, size_t workspaceSize)
  79. {
  80. BYTE *const ostart = (BYTE *)dst;
  81. BYTE *op = ostart;
  82. BYTE *const oend = ostart + dstSize;
  83. U32 maxSymbolValue = HUF_TABLELOG_MAX;
  84. U32 tableLog = MAX_FSE_TABLELOG_FOR_HUFF_HEADER;
  85. FSE_CTable *CTable;
  86. U32 *count;
  87. S16 *norm;
  88. size_t spaceUsed32 = 0;
  89. HUF_STATIC_ASSERT(sizeof(FSE_CTable) == sizeof(U32));
  90. CTable = (FSE_CTable *)((U32 *)workspace + spaceUsed32);
  91. spaceUsed32 += FSE_CTABLE_SIZE_U32(MAX_FSE_TABLELOG_FOR_HUFF_HEADER, HUF_TABLELOG_MAX);
  92. count = (U32 *)workspace + spaceUsed32;
  93. spaceUsed32 += HUF_TABLELOG_MAX + 1;
  94. norm = (S16 *)((U32 *)workspace + spaceUsed32);
  95. spaceUsed32 += ALIGN(sizeof(S16) * (HUF_TABLELOG_MAX + 1), sizeof(U32)) >> 2;
  96. if ((spaceUsed32 << 2) > workspaceSize)
  97. return ERROR(tableLog_tooLarge);
  98. workspace = (U32 *)workspace + spaceUsed32;
  99. workspaceSize -= (spaceUsed32 << 2);
  100. /* init conditions */
  101. if (wtSize <= 1)
  102. return 0; /* Not compressible */
  103. /* Scan input and build symbol stats */
  104. {
  105. CHECK_V_F(maxCount, FSE_count_simple(count, &maxSymbolValue, weightTable, wtSize));
  106. if (maxCount == wtSize)
  107. return 1; /* only a single symbol in src : rle */
  108. if (maxCount == 1)
  109. return 0; /* each symbol present maximum once => not compressible */
  110. }
  111. tableLog = FSE_optimalTableLog(tableLog, wtSize, maxSymbolValue);
  112. CHECK_F(FSE_normalizeCount(norm, tableLog, count, wtSize, maxSymbolValue));
  113. /* Write table description header */
  114. {
  115. CHECK_V_F(hSize, FSE_writeNCount(op, oend - op, norm, maxSymbolValue, tableLog));
  116. op += hSize;
  117. }
  118. /* Compress */
  119. CHECK_F(FSE_buildCTable_wksp(CTable, norm, maxSymbolValue, tableLog, workspace, workspaceSize));
  120. {
  121. CHECK_V_F(cSize, FSE_compress_usingCTable(op, oend - op, weightTable, wtSize, CTable));
  122. if (cSize == 0)
  123. return 0; /* not enough space for compressed data */
  124. op += cSize;
  125. }
  126. return op - ostart;
  127. }
  128. struct HUF_CElt_s {
  129. U16 val;
  130. BYTE nbBits;
  131. }; /* typedef'd to HUF_CElt within "huf.h" */
  132. /*! HUF_writeCTable_wksp() :
  133. `CTable` : Huffman tree to save, using huf representation.
  134. @return : size of saved CTable */
  135. size_t HUF_writeCTable_wksp(void *dst, size_t maxDstSize, const HUF_CElt *CTable, U32 maxSymbolValue, U32 huffLog, void *workspace, size_t workspaceSize)
  136. {
  137. BYTE *op = (BYTE *)dst;
  138. U32 n;
  139. BYTE *bitsToWeight;
  140. BYTE *huffWeight;
  141. size_t spaceUsed32 = 0;
  142. bitsToWeight = (BYTE *)((U32 *)workspace + spaceUsed32);
  143. spaceUsed32 += ALIGN(HUF_TABLELOG_MAX + 1, sizeof(U32)) >> 2;
  144. huffWeight = (BYTE *)((U32 *)workspace + spaceUsed32);
  145. spaceUsed32 += ALIGN(HUF_SYMBOLVALUE_MAX, sizeof(U32)) >> 2;
  146. if ((spaceUsed32 << 2) > workspaceSize)
  147. return ERROR(tableLog_tooLarge);
  148. workspace = (U32 *)workspace + spaceUsed32;
  149. workspaceSize -= (spaceUsed32 << 2);
  150. /* check conditions */
  151. if (maxSymbolValue > HUF_SYMBOLVALUE_MAX)
  152. return ERROR(maxSymbolValue_tooLarge);
  153. /* convert to weight */
  154. bitsToWeight[0] = 0;
  155. for (n = 1; n < huffLog + 1; n++)
  156. bitsToWeight[n] = (BYTE)(huffLog + 1 - n);
  157. for (n = 0; n < maxSymbolValue; n++)
  158. huffWeight[n] = bitsToWeight[CTable[n].nbBits];
  159. /* attempt weights compression by FSE */
  160. {
  161. CHECK_V_F(hSize, HUF_compressWeights_wksp(op + 1, maxDstSize - 1, huffWeight, maxSymbolValue, workspace, workspaceSize));
  162. if ((hSize > 1) & (hSize < maxSymbolValue / 2)) { /* FSE compressed */
  163. op[0] = (BYTE)hSize;
  164. return hSize + 1;
  165. }
  166. }
  167. /* write raw values as 4-bits (max : 15) */
  168. if (maxSymbolValue > (256 - 128))
  169. return ERROR(GENERIC); /* should not happen : likely means source cannot be compressed */
  170. if (((maxSymbolValue + 1) / 2) + 1 > maxDstSize)
  171. return ERROR(dstSize_tooSmall); /* not enough space within dst buffer */
  172. op[0] = (BYTE)(128 /*special case*/ + (maxSymbolValue - 1));
  173. huffWeight[maxSymbolValue] = 0; /* to be sure it doesn't cause msan issue in final combination */
  174. for (n = 0; n < maxSymbolValue; n += 2)
  175. op[(n / 2) + 1] = (BYTE)((huffWeight[n] << 4) + huffWeight[n + 1]);
  176. return ((maxSymbolValue + 1) / 2) + 1;
  177. }
  178. size_t HUF_readCTable_wksp(HUF_CElt *CTable, U32 maxSymbolValue, const void *src, size_t srcSize, void *workspace, size_t workspaceSize)
  179. {
  180. U32 *rankVal;
  181. BYTE *huffWeight;
  182. U32 tableLog = 0;
  183. U32 nbSymbols = 0;
  184. size_t readSize;
  185. size_t spaceUsed32 = 0;
  186. rankVal = (U32 *)workspace + spaceUsed32;
  187. spaceUsed32 += HUF_TABLELOG_ABSOLUTEMAX + 1;
  188. huffWeight = (BYTE *)((U32 *)workspace + spaceUsed32);
  189. spaceUsed32 += ALIGN(HUF_SYMBOLVALUE_MAX + 1, sizeof(U32)) >> 2;
  190. if ((spaceUsed32 << 2) > workspaceSize)
  191. return ERROR(tableLog_tooLarge);
  192. workspace = (U32 *)workspace + spaceUsed32;
  193. workspaceSize -= (spaceUsed32 << 2);
  194. /* get symbol weights */
  195. readSize = HUF_readStats_wksp(huffWeight, HUF_SYMBOLVALUE_MAX + 1, rankVal, &nbSymbols, &tableLog, src, srcSize, workspace, workspaceSize);
  196. if (ERR_isError(readSize))
  197. return readSize;
  198. /* check result */
  199. if (tableLog > HUF_TABLELOG_MAX)
  200. return ERROR(tableLog_tooLarge);
  201. if (nbSymbols > maxSymbolValue + 1)
  202. return ERROR(maxSymbolValue_tooSmall);
  203. /* Prepare base value per rank */
  204. {
  205. U32 n, nextRankStart = 0;
  206. for (n = 1; n <= tableLog; n++) {
  207. U32 curr = nextRankStart;
  208. nextRankStart += (rankVal[n] << (n - 1));
  209. rankVal[n] = curr;
  210. }
  211. }
  212. /* fill nbBits */
  213. {
  214. U32 n;
  215. for (n = 0; n < nbSymbols; n++) {
  216. const U32 w = huffWeight[n];
  217. CTable[n].nbBits = (BYTE)(tableLog + 1 - w);
  218. }
  219. }
  220. /* fill val */
  221. {
  222. U16 nbPerRank[HUF_TABLELOG_MAX + 2] = {0}; /* support w=0=>n=tableLog+1 */
  223. U16 valPerRank[HUF_TABLELOG_MAX + 2] = {0};
  224. {
  225. U32 n;
  226. for (n = 0; n < nbSymbols; n++)
  227. nbPerRank[CTable[n].nbBits]++;
  228. }
  229. /* determine stating value per rank */
  230. valPerRank[tableLog + 1] = 0; /* for w==0 */
  231. {
  232. U16 min = 0;
  233. U32 n;
  234. for (n = tableLog; n > 0; n--) { /* start at n=tablelog <-> w=1 */
  235. valPerRank[n] = min; /* get starting value within each rank */
  236. min += nbPerRank[n];
  237. min >>= 1;
  238. }
  239. }
  240. /* assign value within rank, symbol order */
  241. {
  242. U32 n;
  243. for (n = 0; n <= maxSymbolValue; n++)
  244. CTable[n].val = valPerRank[CTable[n].nbBits]++;
  245. }
  246. }
  247. return readSize;
  248. }
  249. typedef struct nodeElt_s {
  250. U32 count;
  251. U16 parent;
  252. BYTE byte;
  253. BYTE nbBits;
  254. } nodeElt;
  255. static U32 HUF_setMaxHeight(nodeElt *huffNode, U32 lastNonNull, U32 maxNbBits)
  256. {
  257. const U32 largestBits = huffNode[lastNonNull].nbBits;
  258. if (largestBits <= maxNbBits)
  259. return largestBits; /* early exit : no elt > maxNbBits */
  260. /* there are several too large elements (at least >= 2) */
  261. {
  262. int totalCost = 0;
  263. const U32 baseCost = 1 << (largestBits - maxNbBits);
  264. U32 n = lastNonNull;
  265. while (huffNode[n].nbBits > maxNbBits) {
  266. totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits));
  267. huffNode[n].nbBits = (BYTE)maxNbBits;
  268. n--;
  269. } /* n stops at huffNode[n].nbBits <= maxNbBits */
  270. while (huffNode[n].nbBits == maxNbBits)
  271. n--; /* n end at index of smallest symbol using < maxNbBits */
  272. /* renorm totalCost */
  273. totalCost >>= (largestBits - maxNbBits); /* note : totalCost is necessarily a multiple of baseCost */
  274. /* repay normalized cost */
  275. {
  276. U32 const noSymbol = 0xF0F0F0F0;
  277. U32 rankLast[HUF_TABLELOG_MAX + 2];
  278. int pos;
  279. /* Get pos of last (smallest) symbol per rank */
  280. memset(rankLast, 0xF0, sizeof(rankLast));
  281. {
  282. U32 currNbBits = maxNbBits;
  283. for (pos = n; pos >= 0; pos--) {
  284. if (huffNode[pos].nbBits >= currNbBits)
  285. continue;
  286. currNbBits = huffNode[pos].nbBits; /* < maxNbBits */
  287. rankLast[maxNbBits - currNbBits] = pos;
  288. }
  289. }
  290. while (totalCost > 0) {
  291. U32 nBitsToDecrease = BIT_highbit32(totalCost) + 1;
  292. for (; nBitsToDecrease > 1; nBitsToDecrease--) {
  293. U32 highPos = rankLast[nBitsToDecrease];
  294. U32 lowPos = rankLast[nBitsToDecrease - 1];
  295. if (highPos == noSymbol)
  296. continue;
  297. if (lowPos == noSymbol)
  298. break;
  299. {
  300. U32 const highTotal = huffNode[highPos].count;
  301. U32 const lowTotal = 2 * huffNode[lowPos].count;
  302. if (highTotal <= lowTotal)
  303. break;
  304. }
  305. }
  306. /* only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) */
  307. /* HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary */
  308. while ((nBitsToDecrease <= HUF_TABLELOG_MAX) && (rankLast[nBitsToDecrease] == noSymbol))
  309. nBitsToDecrease++;
  310. totalCost -= 1 << (nBitsToDecrease - 1);
  311. if (rankLast[nBitsToDecrease - 1] == noSymbol)
  312. rankLast[nBitsToDecrease - 1] = rankLast[nBitsToDecrease]; /* this rank is no longer empty */
  313. huffNode[rankLast[nBitsToDecrease]].nbBits++;
  314. if (rankLast[nBitsToDecrease] == 0) /* special case, reached largest symbol */
  315. rankLast[nBitsToDecrease] = noSymbol;
  316. else {
  317. rankLast[nBitsToDecrease]--;
  318. if (huffNode[rankLast[nBitsToDecrease]].nbBits != maxNbBits - nBitsToDecrease)
  319. rankLast[nBitsToDecrease] = noSymbol; /* this rank is now empty */
  320. }
  321. } /* while (totalCost > 0) */
  322. while (totalCost < 0) { /* Sometimes, cost correction overshoot */
  323. if (rankLast[1] == noSymbol) { /* special case : no rank 1 symbol (using maxNbBits-1); let's create one from largest rank 0
  324. (using maxNbBits) */
  325. while (huffNode[n].nbBits == maxNbBits)
  326. n--;
  327. huffNode[n + 1].nbBits--;
  328. rankLast[1] = n + 1;
  329. totalCost++;
  330. continue;
  331. }
  332. huffNode[rankLast[1] + 1].nbBits--;
  333. rankLast[1]++;
  334. totalCost++;
  335. }
  336. }
  337. } /* there are several too large elements (at least >= 2) */
  338. return maxNbBits;
  339. }
  340. typedef struct {
  341. U32 base;
  342. U32 curr;
  343. } rankPos;
  344. static void HUF_sort(nodeElt *huffNode, const U32 *count, U32 maxSymbolValue)
  345. {
  346. rankPos rank[32];
  347. U32 n;
  348. memset(rank, 0, sizeof(rank));
  349. for (n = 0; n <= maxSymbolValue; n++) {
  350. U32 r = BIT_highbit32(count[n] + 1);
  351. rank[r].base++;
  352. }
  353. for (n = 30; n > 0; n--)
  354. rank[n - 1].base += rank[n].base;
  355. for (n = 0; n < 32; n++)
  356. rank[n].curr = rank[n].base;
  357. for (n = 0; n <= maxSymbolValue; n++) {
  358. U32 const c = count[n];
  359. U32 const r = BIT_highbit32(c + 1) + 1;
  360. U32 pos = rank[r].curr++;
  361. while ((pos > rank[r].base) && (c > huffNode[pos - 1].count))
  362. huffNode[pos] = huffNode[pos - 1], pos--;
  363. huffNode[pos].count = c;
  364. huffNode[pos].byte = (BYTE)n;
  365. }
  366. }
  367. /** HUF_buildCTable_wksp() :
  368. * Same as HUF_buildCTable(), but using externally allocated scratch buffer.
  369. * `workSpace` must be aligned on 4-bytes boundaries, and be at least as large as a table of 1024 unsigned.
  370. */
  371. #define STARTNODE (HUF_SYMBOLVALUE_MAX + 1)
  372. typedef nodeElt huffNodeTable[2 * HUF_SYMBOLVALUE_MAX + 1 + 1];
  373. size_t HUF_buildCTable_wksp(HUF_CElt *tree, const U32 *count, U32 maxSymbolValue, U32 maxNbBits, void *workSpace, size_t wkspSize)
  374. {
  375. nodeElt *const huffNode0 = (nodeElt *)workSpace;
  376. nodeElt *const huffNode = huffNode0 + 1;
  377. U32 n, nonNullRank;
  378. int lowS, lowN;
  379. U16 nodeNb = STARTNODE;
  380. U32 nodeRoot;
  381. /* safety checks */
  382. if (wkspSize < sizeof(huffNodeTable))
  383. return ERROR(GENERIC); /* workSpace is not large enough */
  384. if (maxNbBits == 0)
  385. maxNbBits = HUF_TABLELOG_DEFAULT;
  386. if (maxSymbolValue > HUF_SYMBOLVALUE_MAX)
  387. return ERROR(GENERIC);
  388. memset(huffNode0, 0, sizeof(huffNodeTable));
  389. /* sort, decreasing order */
  390. HUF_sort(huffNode, count, maxSymbolValue);
  391. /* init for parents */
  392. nonNullRank = maxSymbolValue;
  393. while (huffNode[nonNullRank].count == 0)
  394. nonNullRank--;
  395. lowS = nonNullRank;
  396. nodeRoot = nodeNb + lowS - 1;
  397. lowN = nodeNb;
  398. huffNode[nodeNb].count = huffNode[lowS].count + huffNode[lowS - 1].count;
  399. huffNode[lowS].parent = huffNode[lowS - 1].parent = nodeNb;
  400. nodeNb++;
  401. lowS -= 2;
  402. for (n = nodeNb; n <= nodeRoot; n++)
  403. huffNode[n].count = (U32)(1U << 30);
  404. huffNode0[0].count = (U32)(1U << 31); /* fake entry, strong barrier */
  405. /* create parents */
  406. while (nodeNb <= nodeRoot) {
  407. U32 n1 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
  408. U32 n2 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
  409. huffNode[nodeNb].count = huffNode[n1].count + huffNode[n2].count;
  410. huffNode[n1].parent = huffNode[n2].parent = nodeNb;
  411. nodeNb++;
  412. }
  413. /* distribute weights (unlimited tree height) */
  414. huffNode[nodeRoot].nbBits = 0;
  415. for (n = nodeRoot - 1; n >= STARTNODE; n--)
  416. huffNode[n].nbBits = huffNode[huffNode[n].parent].nbBits + 1;
  417. for (n = 0; n <= nonNullRank; n++)
  418. huffNode[n].nbBits = huffNode[huffNode[n].parent].nbBits + 1;
  419. /* enforce maxTableLog */
  420. maxNbBits = HUF_setMaxHeight(huffNode, nonNullRank, maxNbBits);
  421. /* fill result into tree (val, nbBits) */
  422. {
  423. U16 nbPerRank[HUF_TABLELOG_MAX + 1] = {0};
  424. U16 valPerRank[HUF_TABLELOG_MAX + 1] = {0};
  425. if (maxNbBits > HUF_TABLELOG_MAX)
  426. return ERROR(GENERIC); /* check fit into table */
  427. for (n = 0; n <= nonNullRank; n++)
  428. nbPerRank[huffNode[n].nbBits]++;
  429. /* determine stating value per rank */
  430. {
  431. U16 min = 0;
  432. for (n = maxNbBits; n > 0; n--) {
  433. valPerRank[n] = min; /* get starting value within each rank */
  434. min += nbPerRank[n];
  435. min >>= 1;
  436. }
  437. }
  438. for (n = 0; n <= maxSymbolValue; n++)
  439. tree[huffNode[n].byte].nbBits = huffNode[n].nbBits; /* push nbBits per symbol, symbol order */
  440. for (n = 0; n <= maxSymbolValue; n++)
  441. tree[n].val = valPerRank[tree[n].nbBits]++; /* assign value within rank, symbol order */
  442. }
  443. return maxNbBits;
  444. }
  445. static size_t HUF_estimateCompressedSize(HUF_CElt *CTable, const unsigned *count, unsigned maxSymbolValue)
  446. {
  447. size_t nbBits = 0;
  448. int s;
  449. for (s = 0; s <= (int)maxSymbolValue; ++s) {
  450. nbBits += CTable[s].nbBits * count[s];
  451. }
  452. return nbBits >> 3;
  453. }
  454. static int HUF_validateCTable(const HUF_CElt *CTable, const unsigned *count, unsigned maxSymbolValue)
  455. {
  456. int bad = 0;
  457. int s;
  458. for (s = 0; s <= (int)maxSymbolValue; ++s) {
  459. bad |= (count[s] != 0) & (CTable[s].nbBits == 0);
  460. }
  461. return !bad;
  462. }
  463. static void HUF_encodeSymbol(BIT_CStream_t *bitCPtr, U32 symbol, const HUF_CElt *CTable)
  464. {
  465. BIT_addBitsFast(bitCPtr, CTable[symbol].val, CTable[symbol].nbBits);
  466. }
  467. size_t HUF_compressBound(size_t size) { return HUF_COMPRESSBOUND(size); }
  468. #define HUF_FLUSHBITS(s) BIT_flushBits(s)
  469. #define HUF_FLUSHBITS_1(stream) \
  470. if (sizeof((stream)->bitContainer) * 8 < HUF_TABLELOG_MAX * 2 + 7) \
  471. HUF_FLUSHBITS(stream)
  472. #define HUF_FLUSHBITS_2(stream) \
  473. if (sizeof((stream)->bitContainer) * 8 < HUF_TABLELOG_MAX * 4 + 7) \
  474. HUF_FLUSHBITS(stream)
  475. size_t HUF_compress1X_usingCTable(void *dst, size_t dstSize, const void *src, size_t srcSize, const HUF_CElt *CTable)
  476. {
  477. const BYTE *ip = (const BYTE *)src;
  478. BYTE *const ostart = (BYTE *)dst;
  479. BYTE *const oend = ostart + dstSize;
  480. BYTE *op = ostart;
  481. size_t n;
  482. BIT_CStream_t bitC;
  483. /* init */
  484. if (dstSize < 8)
  485. return 0; /* not enough space to compress */
  486. {
  487. size_t const initErr = BIT_initCStream(&bitC, op, oend - op);
  488. if (HUF_isError(initErr))
  489. return 0;
  490. }
  491. n = srcSize & ~3; /* join to mod 4 */
  492. switch (srcSize & 3) {
  493. case 3: HUF_encodeSymbol(&bitC, ip[n + 2], CTable); HUF_FLUSHBITS_2(&bitC);
  494. case 2: HUF_encodeSymbol(&bitC, ip[n + 1], CTable); HUF_FLUSHBITS_1(&bitC);
  495. case 1: HUF_encodeSymbol(&bitC, ip[n + 0], CTable); HUF_FLUSHBITS(&bitC);
  496. case 0:
  497. default:;
  498. }
  499. for (; n > 0; n -= 4) { /* note : n&3==0 at this stage */
  500. HUF_encodeSymbol(&bitC, ip[n - 1], CTable);
  501. HUF_FLUSHBITS_1(&bitC);
  502. HUF_encodeSymbol(&bitC, ip[n - 2], CTable);
  503. HUF_FLUSHBITS_2(&bitC);
  504. HUF_encodeSymbol(&bitC, ip[n - 3], CTable);
  505. HUF_FLUSHBITS_1(&bitC);
  506. HUF_encodeSymbol(&bitC, ip[n - 4], CTable);
  507. HUF_FLUSHBITS(&bitC);
  508. }
  509. return BIT_closeCStream(&bitC);
  510. }
  511. size_t HUF_compress4X_usingCTable(void *dst, size_t dstSize, const void *src, size_t srcSize, const HUF_CElt *CTable)
  512. {
  513. size_t const segmentSize = (srcSize + 3) / 4; /* first 3 segments */
  514. const BYTE *ip = (const BYTE *)src;
  515. const BYTE *const iend = ip + srcSize;
  516. BYTE *const ostart = (BYTE *)dst;
  517. BYTE *const oend = ostart + dstSize;
  518. BYTE *op = ostart;
  519. if (dstSize < 6 + 1 + 1 + 1 + 8)
  520. return 0; /* minimum space to compress successfully */
  521. if (srcSize < 12)
  522. return 0; /* no saving possible : too small input */
  523. op += 6; /* jumpTable */
  524. {
  525. CHECK_V_F(cSize, HUF_compress1X_usingCTable(op, oend - op, ip, segmentSize, CTable));
  526. if (cSize == 0)
  527. return 0;
  528. ZSTD_writeLE16(ostart, (U16)cSize);
  529. op += cSize;
  530. }
  531. ip += segmentSize;
  532. {
  533. CHECK_V_F(cSize, HUF_compress1X_usingCTable(op, oend - op, ip, segmentSize, CTable));
  534. if (cSize == 0)
  535. return 0;
  536. ZSTD_writeLE16(ostart + 2, (U16)cSize);
  537. op += cSize;
  538. }
  539. ip += segmentSize;
  540. {
  541. CHECK_V_F(cSize, HUF_compress1X_usingCTable(op, oend - op, ip, segmentSize, CTable));
  542. if (cSize == 0)
  543. return 0;
  544. ZSTD_writeLE16(ostart + 4, (U16)cSize);
  545. op += cSize;
  546. }
  547. ip += segmentSize;
  548. {
  549. CHECK_V_F(cSize, HUF_compress1X_usingCTable(op, oend - op, ip, iend - ip, CTable));
  550. if (cSize == 0)
  551. return 0;
  552. op += cSize;
  553. }
  554. return op - ostart;
  555. }
  556. static size_t HUF_compressCTable_internal(BYTE *const ostart, BYTE *op, BYTE *const oend, const void *src, size_t srcSize, unsigned singleStream,
  557. const HUF_CElt *CTable)
  558. {
  559. size_t const cSize =
  560. singleStream ? HUF_compress1X_usingCTable(op, oend - op, src, srcSize, CTable) : HUF_compress4X_usingCTable(op, oend - op, src, srcSize, CTable);
  561. if (HUF_isError(cSize)) {
  562. return cSize;
  563. }
  564. if (cSize == 0) {
  565. return 0;
  566. } /* uncompressible */
  567. op += cSize;
  568. /* check compressibility */
  569. if ((size_t)(op - ostart) >= srcSize - 1) {
  570. return 0;
  571. }
  572. return op - ostart;
  573. }
  574. /* `workSpace` must a table of at least 1024 unsigned */
  575. static size_t HUF_compress_internal(void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned huffLog,
  576. unsigned singleStream, void *workSpace, size_t wkspSize, HUF_CElt *oldHufTable, HUF_repeat *repeat, int preferRepeat)
  577. {
  578. BYTE *const ostart = (BYTE *)dst;
  579. BYTE *const oend = ostart + dstSize;
  580. BYTE *op = ostart;
  581. U32 *count;
  582. size_t const countSize = sizeof(U32) * (HUF_SYMBOLVALUE_MAX + 1);
  583. HUF_CElt *CTable;
  584. size_t const CTableSize = sizeof(HUF_CElt) * (HUF_SYMBOLVALUE_MAX + 1);
  585. /* checks & inits */
  586. if (wkspSize < sizeof(huffNodeTable) + countSize + CTableSize)
  587. return ERROR(GENERIC);
  588. if (!srcSize)
  589. return 0; /* Uncompressed (note : 1 means rle, so first byte must be correct) */
  590. if (!dstSize)
  591. return 0; /* cannot fit within dst budget */
  592. if (srcSize > HUF_BLOCKSIZE_MAX)
  593. return ERROR(srcSize_wrong); /* curr block size limit */
  594. if (huffLog > HUF_TABLELOG_MAX)
  595. return ERROR(tableLog_tooLarge);
  596. if (!maxSymbolValue)
  597. maxSymbolValue = HUF_SYMBOLVALUE_MAX;
  598. if (!huffLog)
  599. huffLog = HUF_TABLELOG_DEFAULT;
  600. count = (U32 *)workSpace;
  601. workSpace = (BYTE *)workSpace + countSize;
  602. wkspSize -= countSize;
  603. CTable = (HUF_CElt *)workSpace;
  604. workSpace = (BYTE *)workSpace + CTableSize;
  605. wkspSize -= CTableSize;
  606. /* Heuristic : If we don't need to check the validity of the old table use the old table for small inputs */
  607. if (preferRepeat && repeat && *repeat == HUF_repeat_valid) {
  608. return HUF_compressCTable_internal(ostart, op, oend, src, srcSize, singleStream, oldHufTable);
  609. }
  610. /* Scan input and build symbol stats */
  611. {
  612. CHECK_V_F(largest, FSE_count_wksp(count, &maxSymbolValue, (const BYTE *)src, srcSize, (U32 *)workSpace));
  613. if (largest == srcSize) {
  614. *ostart = ((const BYTE *)src)[0];
  615. return 1;
  616. } /* single symbol, rle */
  617. if (largest <= (srcSize >> 7) + 1)
  618. return 0; /* Fast heuristic : not compressible enough */
  619. }
  620. /* Check validity of previous table */
  621. if (repeat && *repeat == HUF_repeat_check && !HUF_validateCTable(oldHufTable, count, maxSymbolValue)) {
  622. *repeat = HUF_repeat_none;
  623. }
  624. /* Heuristic : use existing table for small inputs */
  625. if (preferRepeat && repeat && *repeat != HUF_repeat_none) {
  626. return HUF_compressCTable_internal(ostart, op, oend, src, srcSize, singleStream, oldHufTable);
  627. }
  628. /* Build Huffman Tree */
  629. huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue);
  630. {
  631. CHECK_V_F(maxBits, HUF_buildCTable_wksp(CTable, count, maxSymbolValue, huffLog, workSpace, wkspSize));
  632. huffLog = (U32)maxBits;
  633. /* Zero the unused symbols so we can check it for validity */
  634. memset(CTable + maxSymbolValue + 1, 0, CTableSize - (maxSymbolValue + 1) * sizeof(HUF_CElt));
  635. }
  636. /* Write table description header */
  637. {
  638. CHECK_V_F(hSize, HUF_writeCTable_wksp(op, dstSize, CTable, maxSymbolValue, huffLog, workSpace, wkspSize));
  639. /* Check if using the previous table will be beneficial */
  640. if (repeat && *repeat != HUF_repeat_none) {
  641. size_t const oldSize = HUF_estimateCompressedSize(oldHufTable, count, maxSymbolValue);
  642. size_t const newSize = HUF_estimateCompressedSize(CTable, count, maxSymbolValue);
  643. if (oldSize <= hSize + newSize || hSize + 12 >= srcSize) {
  644. return HUF_compressCTable_internal(ostart, op, oend, src, srcSize, singleStream, oldHufTable);
  645. }
  646. }
  647. /* Use the new table */
  648. if (hSize + 12ul >= srcSize) {
  649. return 0;
  650. }
  651. op += hSize;
  652. if (repeat) {
  653. *repeat = HUF_repeat_none;
  654. }
  655. if (oldHufTable) {
  656. memcpy(oldHufTable, CTable, CTableSize);
  657. } /* Save the new table */
  658. }
  659. return HUF_compressCTable_internal(ostart, op, oend, src, srcSize, singleStream, CTable);
  660. }
  661. size_t HUF_compress1X_wksp(void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned huffLog, void *workSpace,
  662. size_t wkspSize)
  663. {
  664. return HUF_compress_internal(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, 1 /* single stream */, workSpace, wkspSize, NULL, NULL, 0);
  665. }
  666. size_t HUF_compress1X_repeat(void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned huffLog, void *workSpace,
  667. size_t wkspSize, HUF_CElt *hufTable, HUF_repeat *repeat, int preferRepeat)
  668. {
  669. return HUF_compress_internal(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, 1 /* single stream */, workSpace, wkspSize, hufTable, repeat,
  670. preferRepeat);
  671. }
  672. size_t HUF_compress4X_wksp(void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned huffLog, void *workSpace,
  673. size_t wkspSize)
  674. {
  675. return HUF_compress_internal(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, 0 /* 4 streams */, workSpace, wkspSize, NULL, NULL, 0);
  676. }
  677. size_t HUF_compress4X_repeat(void *dst, size_t dstSize, const void *src, size_t srcSize, unsigned maxSymbolValue, unsigned huffLog, void *workSpace,
  678. size_t wkspSize, HUF_CElt *hufTable, HUF_repeat *repeat, int preferRepeat)
  679. {
  680. return HUF_compress_internal(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, 0 /* 4 streams */, workSpace, wkspSize, hufTable, repeat,
  681. preferRepeat);
  682. }