zdict.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /*-**************************************
  11. * Tuning parameters
  12. ****************************************/
  13. #define MINRATIO 4 /* minimum nb of apparition to be selected in dictionary */
  14. #define ZDICT_MAX_SAMPLES_SIZE (2000U << 20)
  15. #define ZDICT_MIN_SAMPLES_SIZE (ZDICT_CONTENTSIZE_MIN * MINRATIO)
  16. /*-**************************************
  17. * Compiler Options
  18. ****************************************/
  19. /* Unix Large Files support (>4GB) */
  20. #define _FILE_OFFSET_BITS 64
  21. #if (defined(__sun__) && (!defined(__LP64__))) /* Sun Solaris 32-bits requires specific definitions */
  22. # ifndef _LARGEFILE_SOURCE
  23. # define _LARGEFILE_SOURCE
  24. # endif
  25. #elif ! defined(__LP64__) /* No point defining Large file for 64 bit */
  26. # ifndef _LARGEFILE64_SOURCE
  27. # define _LARGEFILE64_SOURCE
  28. # endif
  29. #endif
  30. /*-*************************************
  31. * Dependencies
  32. ***************************************/
  33. #include <stdlib.h> /* malloc, free */
  34. #include <string.h> /* memset */
  35. #include <stdio.h> /* fprintf, fopen, ftello64 */
  36. #include <time.h> /* clock */
  37. #ifndef ZDICT_STATIC_LINKING_ONLY
  38. # define ZDICT_STATIC_LINKING_ONLY
  39. #endif
  40. #include "../common/mem.h" /* read */
  41. #include "../common/fse.h" /* FSE_normalizeCount, FSE_writeNCount */
  42. #include "../common/huf.h" /* HUF_buildCTable, HUF_writeCTable */
  43. #include "../common/zstd_internal.h" /* includes zstd.h */
  44. #include <contrib/libs/xxhash/xxhash.h> /* XXH64 */
  45. #include "../compress/zstd_compress_internal.h" /* ZSTD_loadCEntropy() */
  46. #include "../zdict.h"
  47. #include "divsufsort.h"
  48. #include "../common/bits.h" /* ZSTD_NbCommonBytes */
  49. /*-*************************************
  50. * Constants
  51. ***************************************/
  52. #define KB *(1 <<10)
  53. #define MB *(1 <<20)
  54. #define GB *(1U<<30)
  55. #define DICTLISTSIZE_DEFAULT 10000
  56. #define NOISELENGTH 32
  57. static const U32 g_selectivity_default = 9;
  58. /*-*************************************
  59. * Console display
  60. ***************************************/
  61. #undef DISPLAY
  62. #define DISPLAY(...) { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }
  63. #undef DISPLAYLEVEL
  64. #define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */
  65. static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
  66. static void ZDICT_printHex(const void* ptr, size_t length)
  67. {
  68. const BYTE* const b = (const BYTE*)ptr;
  69. size_t u;
  70. for (u=0; u<length; u++) {
  71. BYTE c = b[u];
  72. if (c<32 || c>126) c = '.'; /* non-printable char */
  73. DISPLAY("%c", c);
  74. }
  75. }
  76. /*-********************************************************
  77. * Helper functions
  78. **********************************************************/
  79. unsigned ZDICT_isError(size_t errorCode) { return ERR_isError(errorCode); }
  80. const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
  81. unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize)
  82. {
  83. if (dictSize < 8) return 0;
  84. if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;
  85. return MEM_readLE32((const char*)dictBuffer + 4);
  86. }
  87. size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize)
  88. {
  89. size_t headerSize;
  90. if (dictSize <= 8 || MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return ERROR(dictionary_corrupted);
  91. { ZSTD_compressedBlockState_t* bs = (ZSTD_compressedBlockState_t*)malloc(sizeof(ZSTD_compressedBlockState_t));
  92. U32* wksp = (U32*)malloc(HUF_WORKSPACE_SIZE);
  93. if (!bs || !wksp) {
  94. headerSize = ERROR(memory_allocation);
  95. } else {
  96. ZSTD_reset_compressedBlockState(bs);
  97. headerSize = ZSTD_loadCEntropy(bs, wksp, dictBuffer, dictSize);
  98. }
  99. free(bs);
  100. free(wksp);
  101. }
  102. return headerSize;
  103. }
  104. /*-********************************************************
  105. * Dictionary training functions
  106. **********************************************************/
  107. /*! ZDICT_count() :
  108. Count the nb of common bytes between 2 pointers.
  109. Note : this function presumes end of buffer followed by noisy guard band.
  110. */
  111. static size_t ZDICT_count(const void* pIn, const void* pMatch)
  112. {
  113. const char* const pStart = (const char*)pIn;
  114. for (;;) {
  115. size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
  116. if (!diff) {
  117. pIn = (const char*)pIn+sizeof(size_t);
  118. pMatch = (const char*)pMatch+sizeof(size_t);
  119. continue;
  120. }
  121. pIn = (const char*)pIn+ZSTD_NbCommonBytes(diff);
  122. return (size_t)((const char*)pIn - pStart);
  123. }
  124. }
  125. typedef struct {
  126. U32 pos;
  127. U32 length;
  128. U32 savings;
  129. } dictItem;
  130. static void ZDICT_initDictItem(dictItem* d)
  131. {
  132. d->pos = 1;
  133. d->length = 0;
  134. d->savings = (U32)(-1);
  135. }
  136. #define LLIMIT 64 /* heuristic determined experimentally */
  137. #define MINMATCHLENGTH 7 /* heuristic determined experimentally */
  138. static dictItem ZDICT_analyzePos(
  139. BYTE* doneMarks,
  140. const int* suffix, U32 start,
  141. const void* buffer, U32 minRatio, U32 notificationLevel)
  142. {
  143. U32 lengthList[LLIMIT] = {0};
  144. U32 cumulLength[LLIMIT] = {0};
  145. U32 savings[LLIMIT] = {0};
  146. const BYTE* b = (const BYTE*)buffer;
  147. size_t maxLength = LLIMIT;
  148. size_t pos = (size_t)suffix[start];
  149. U32 end = start;
  150. dictItem solution;
  151. /* init */
  152. memset(&solution, 0, sizeof(solution));
  153. doneMarks[pos] = 1;
  154. /* trivial repetition cases */
  155. if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))
  156. ||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))
  157. ||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {
  158. /* skip and mark segment */
  159. U16 const pattern16 = MEM_read16(b+pos+4);
  160. U32 u, patternEnd = 6;
  161. while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;
  162. if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;
  163. for (u=1; u<patternEnd; u++)
  164. doneMarks[pos+u] = 1;
  165. return solution;
  166. }
  167. /* look forward */
  168. { size_t length;
  169. do {
  170. end++;
  171. length = ZDICT_count(b + pos, b + suffix[end]);
  172. } while (length >= MINMATCHLENGTH);
  173. }
  174. /* look backward */
  175. { size_t length;
  176. do {
  177. length = ZDICT_count(b + pos, b + *(suffix+start-1));
  178. if (length >=MINMATCHLENGTH) start--;
  179. } while(length >= MINMATCHLENGTH);
  180. }
  181. /* exit if not found a minimum nb of repetitions */
  182. if (end-start < minRatio) {
  183. U32 idx;
  184. for(idx=start; idx<end; idx++)
  185. doneMarks[suffix[idx]] = 1;
  186. return solution;
  187. }
  188. { int i;
  189. U32 mml;
  190. U32 refinedStart = start;
  191. U32 refinedEnd = end;
  192. DISPLAYLEVEL(4, "\n");
  193. DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);
  194. DISPLAYLEVEL(4, "\n");
  195. for (mml = MINMATCHLENGTH ; ; mml++) {
  196. BYTE currentChar = 0;
  197. U32 currentCount = 0;
  198. U32 currentID = refinedStart;
  199. U32 id;
  200. U32 selectedCount = 0;
  201. U32 selectedID = currentID;
  202. for (id =refinedStart; id < refinedEnd; id++) {
  203. if (b[suffix[id] + mml] != currentChar) {
  204. if (currentCount > selectedCount) {
  205. selectedCount = currentCount;
  206. selectedID = currentID;
  207. }
  208. currentID = id;
  209. currentChar = b[ suffix[id] + mml];
  210. currentCount = 0;
  211. }
  212. currentCount ++;
  213. }
  214. if (currentCount > selectedCount) { /* for last */
  215. selectedCount = currentCount;
  216. selectedID = currentID;
  217. }
  218. if (selectedCount < minRatio)
  219. break;
  220. refinedStart = selectedID;
  221. refinedEnd = refinedStart + selectedCount;
  222. }
  223. /* evaluate gain based on new dict */
  224. start = refinedStart;
  225. pos = suffix[refinedStart];
  226. end = start;
  227. memset(lengthList, 0, sizeof(lengthList));
  228. /* look forward */
  229. { size_t length;
  230. do {
  231. end++;
  232. length = ZDICT_count(b + pos, b + suffix[end]);
  233. if (length >= LLIMIT) length = LLIMIT-1;
  234. lengthList[length]++;
  235. } while (length >=MINMATCHLENGTH);
  236. }
  237. /* look backward */
  238. { size_t length = MINMATCHLENGTH;
  239. while ((length >= MINMATCHLENGTH) & (start > 0)) {
  240. length = ZDICT_count(b + pos, b + suffix[start - 1]);
  241. if (length >= LLIMIT) length = LLIMIT - 1;
  242. lengthList[length]++;
  243. if (length >= MINMATCHLENGTH) start--;
  244. }
  245. }
  246. /* largest useful length */
  247. memset(cumulLength, 0, sizeof(cumulLength));
  248. cumulLength[maxLength-1] = lengthList[maxLength-1];
  249. for (i=(int)(maxLength-2); i>=0; i--)
  250. cumulLength[i] = cumulLength[i+1] + lengthList[i];
  251. for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;
  252. maxLength = i;
  253. /* reduce maxLength in case of final into repetitive data */
  254. { U32 l = (U32)maxLength;
  255. BYTE const c = b[pos + maxLength-1];
  256. while (b[pos+l-2]==c) l--;
  257. maxLength = l;
  258. }
  259. if (maxLength < MINMATCHLENGTH) return solution; /* skip : no long-enough solution */
  260. /* calculate savings */
  261. savings[5] = 0;
  262. for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)
  263. savings[i] = savings[i-1] + (lengthList[i] * (i-3));
  264. DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f) \n",
  265. (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / (double)maxLength);
  266. solution.pos = (U32)pos;
  267. solution.length = (U32)maxLength;
  268. solution.savings = savings[maxLength];
  269. /* mark positions done */
  270. { U32 id;
  271. for (id=start; id<end; id++) {
  272. U32 p, pEnd, length;
  273. U32 const testedPos = (U32)suffix[id];
  274. if (testedPos == pos)
  275. length = solution.length;
  276. else {
  277. length = (U32)ZDICT_count(b+pos, b+testedPos);
  278. if (length > solution.length) length = solution.length;
  279. }
  280. pEnd = (U32)(testedPos + length);
  281. for (p=testedPos; p<pEnd; p++)
  282. doneMarks[p] = 1;
  283. } } }
  284. return solution;
  285. }
  286. static int isIncluded(const void* in, const void* container, size_t length)
  287. {
  288. const char* const ip = (const char*) in;
  289. const char* const into = (const char*) container;
  290. size_t u;
  291. for (u=0; u<length; u++) { /* works because end of buffer is a noisy guard band */
  292. if (ip[u] != into[u]) break;
  293. }
  294. return u==length;
  295. }
  296. /*! ZDICT_tryMerge() :
  297. check if dictItem can be merged, do it if possible
  298. @return : id of destination elt, 0 if not merged
  299. */
  300. static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const void* buffer)
  301. {
  302. const U32 tableSize = table->pos;
  303. const U32 eltEnd = elt.pos + elt.length;
  304. const char* const buf = (const char*) buffer;
  305. /* tail overlap */
  306. U32 u; for (u=1; u<tableSize; u++) {
  307. if (u==eltNbToSkip) continue;
  308. if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) { /* overlap, existing > new */
  309. /* append */
  310. U32 const addedLength = table[u].pos - elt.pos;
  311. table[u].length += addedLength;
  312. table[u].pos = elt.pos;
  313. table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */
  314. table[u].savings += elt.length / 8; /* rough approx bonus */
  315. elt = table[u];
  316. /* sort : improve rank */
  317. while ((u>1) && (table[u-1].savings < elt.savings))
  318. table[u] = table[u-1], u--;
  319. table[u] = elt;
  320. return u;
  321. } }
  322. /* front overlap */
  323. for (u=1; u<tableSize; u++) {
  324. if (u==eltNbToSkip) continue;
  325. if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) { /* overlap, existing < new */
  326. /* append */
  327. int const addedLength = (int)eltEnd - (int)(table[u].pos + table[u].length);
  328. table[u].savings += elt.length / 8; /* rough approx bonus */
  329. if (addedLength > 0) { /* otherwise, elt fully included into existing */
  330. table[u].length += addedLength;
  331. table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */
  332. }
  333. /* sort : improve rank */
  334. elt = table[u];
  335. while ((u>1) && (table[u-1].savings < elt.savings))
  336. table[u] = table[u-1], u--;
  337. table[u] = elt;
  338. return u;
  339. }
  340. if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {
  341. if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {
  342. size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );
  343. table[u].pos = elt.pos;
  344. table[u].savings += (U32)(elt.savings * addedLength / elt.length);
  345. table[u].length = MIN(elt.length, table[u].length + 1);
  346. return u;
  347. }
  348. }
  349. }
  350. return 0;
  351. }
  352. static void ZDICT_removeDictItem(dictItem* table, U32 id)
  353. {
  354. /* convention : table[0].pos stores nb of elts */
  355. U32 const max = table[0].pos;
  356. U32 u;
  357. if (!id) return; /* protection, should never happen */
  358. for (u=id; u<max-1; u++)
  359. table[u] = table[u+1];
  360. table->pos--;
  361. }
  362. static void ZDICT_insertDictItem(dictItem* table, U32 maxSize, dictItem elt, const void* buffer)
  363. {
  364. /* merge if possible */
  365. U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);
  366. if (mergeId) {
  367. U32 newMerge = 1;
  368. while (newMerge) {
  369. newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);
  370. if (newMerge) ZDICT_removeDictItem(table, mergeId);
  371. mergeId = newMerge;
  372. }
  373. return;
  374. }
  375. /* insert */
  376. { U32 current;
  377. U32 nextElt = table->pos;
  378. if (nextElt >= maxSize) nextElt = maxSize-1;
  379. current = nextElt-1;
  380. while (table[current].savings < elt.savings) {
  381. table[current+1] = table[current];
  382. current--;
  383. }
  384. table[current+1] = elt;
  385. table->pos = nextElt+1;
  386. }
  387. }
  388. static U32 ZDICT_dictSize(const dictItem* dictList)
  389. {
  390. U32 u, dictSize = 0;
  391. for (u=1; u<dictList[0].pos; u++)
  392. dictSize += dictList[u].length;
  393. return dictSize;
  394. }
  395. static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,
  396. const void* const buffer, size_t bufferSize, /* buffer must end with noisy guard band */
  397. const size_t* fileSizes, unsigned nbFiles,
  398. unsigned minRatio, U32 notificationLevel)
  399. {
  400. int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));
  401. int* const suffix = suffix0+1;
  402. U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));
  403. BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks)); /* +16 for overflow security */
  404. U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));
  405. size_t result = 0;
  406. clock_t displayClock = 0;
  407. clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
  408. # undef DISPLAYUPDATE
  409. # define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \
  410. if (ZDICT_clockSpan(displayClock) > refreshRate) \
  411. { displayClock = clock(); DISPLAY(__VA_ARGS__); \
  412. if (notificationLevel>=4) fflush(stderr); } }
  413. /* init */
  414. DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
  415. if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
  416. result = ERROR(memory_allocation);
  417. goto _cleanup;
  418. }
  419. if (minRatio < MINRATIO) minRatio = MINRATIO;
  420. memset(doneMarks, 0, bufferSize+16);
  421. /* limit sample set size (divsufsort limitation)*/
  422. if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
  423. while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
  424. /* sort */
  425. DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
  426. { int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
  427. if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
  428. }
  429. suffix[bufferSize] = (int)bufferSize; /* leads into noise */
  430. suffix0[0] = (int)bufferSize; /* leads into noise */
  431. /* build reverse suffix sort */
  432. { size_t pos;
  433. for (pos=0; pos < bufferSize; pos++)
  434. reverseSuffix[suffix[pos]] = (U32)pos;
  435. /* note filePos tracks borders between samples.
  436. It's not used at this stage, but planned to become useful in a later update */
  437. filePos[0] = 0;
  438. for (pos=1; pos<nbFiles; pos++)
  439. filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
  440. }
  441. DISPLAYLEVEL(2, "finding patterns ... \n");
  442. DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
  443. { U32 cursor; for (cursor=0; cursor < bufferSize; ) {
  444. dictItem solution;
  445. if (doneMarks[cursor]) { cursor++; continue; }
  446. solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
  447. if (solution.length==0) { cursor++; continue; }
  448. ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
  449. cursor += solution.length;
  450. DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / (double)bufferSize * 100.0);
  451. } }
  452. _cleanup:
  453. free(suffix0);
  454. free(reverseSuffix);
  455. free(doneMarks);
  456. free(filePos);
  457. return result;
  458. }
  459. static void ZDICT_fillNoise(void* buffer, size_t length)
  460. {
  461. unsigned const prime1 = 2654435761U;
  462. unsigned const prime2 = 2246822519U;
  463. unsigned acc = prime1;
  464. size_t p=0;
  465. for (p=0; p<length; p++) {
  466. acc *= prime2;
  467. ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
  468. }
  469. }
  470. typedef struct
  471. {
  472. ZSTD_CDict* dict; /* dictionary */
  473. ZSTD_CCtx* zc; /* working context */
  474. void* workPlace; /* must be ZSTD_BLOCKSIZE_MAX allocated */
  475. } EStats_ress_t;
  476. #define MAXREPOFFSET 1024
  477. static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params,
  478. unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,
  479. const void* src, size_t srcSize,
  480. U32 notificationLevel)
  481. {
  482. size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params->cParams.windowLog);
  483. size_t cSize;
  484. if (srcSize > blockSizeMax) srcSize = blockSizeMax; /* protection vs large samples */
  485. { size_t const errorCode = ZSTD_compressBegin_usingCDict_deprecated(esr.zc, esr.dict);
  486. if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
  487. }
  488. cSize = ZSTD_compressBlock_deprecated(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
  489. if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
  490. if (cSize) { /* if == 0; block is not compressible */
  491. const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
  492. /* literals stats */
  493. { const BYTE* bytePtr;
  494. for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
  495. countLit[*bytePtr]++;
  496. }
  497. /* seqStats */
  498. { U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  499. ZSTD_seqToCodes(seqStorePtr);
  500. { const BYTE* codePtr = seqStorePtr->ofCode;
  501. U32 u;
  502. for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
  503. }
  504. { const BYTE* codePtr = seqStorePtr->mlCode;
  505. U32 u;
  506. for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
  507. }
  508. { const BYTE* codePtr = seqStorePtr->llCode;
  509. U32 u;
  510. for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
  511. }
  512. if (nbSeq >= 2) { /* rep offsets */
  513. const seqDef* const seq = seqStorePtr->sequencesStart;
  514. U32 offset1 = seq[0].offBase - ZSTD_REP_NUM;
  515. U32 offset2 = seq[1].offBase - ZSTD_REP_NUM;
  516. if (offset1 >= MAXREPOFFSET) offset1 = 0;
  517. if (offset2 >= MAXREPOFFSET) offset2 = 0;
  518. repOffsets[offset1] += 3;
  519. repOffsets[offset2] += 1;
  520. } } }
  521. }
  522. static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)
  523. {
  524. size_t total=0;
  525. unsigned u;
  526. for (u=0; u<nbFiles; u++) total += fileSizes[u];
  527. return total;
  528. }
  529. typedef struct { U32 offset; U32 count; } offsetCount_t;
  530. static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
  531. {
  532. U32 u;
  533. table[ZSTD_REP_NUM].offset = val;
  534. table[ZSTD_REP_NUM].count = count;
  535. for (u=ZSTD_REP_NUM; u>0; u--) {
  536. offsetCount_t tmp;
  537. if (table[u-1].count >= table[u].count) break;
  538. tmp = table[u-1];
  539. table[u-1] = table[u];
  540. table[u] = tmp;
  541. }
  542. }
  543. /* ZDICT_flatLit() :
  544. * rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.
  545. * necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.
  546. */
  547. static void ZDICT_flatLit(unsigned* countLit)
  548. {
  549. int u;
  550. for (u=1; u<256; u++) countLit[u] = 2;
  551. countLit[0] = 4;
  552. countLit[253] = 1;
  553. countLit[254] = 1;
  554. }
  555. #define OFFCODE_MAX 30 /* only applicable to first block */
  556. static size_t ZDICT_analyzeEntropy(void* dstBuffer, size_t maxDstSize,
  557. int compressionLevel,
  558. const void* srcBuffer, const size_t* fileSizes, unsigned nbFiles,
  559. const void* dictBuffer, size_t dictBufferSize,
  560. unsigned notificationLevel)
  561. {
  562. unsigned countLit[256];
  563. HUF_CREATE_STATIC_CTABLE(hufTable, 255);
  564. unsigned offcodeCount[OFFCODE_MAX+1];
  565. short offcodeNCount[OFFCODE_MAX+1];
  566. U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
  567. unsigned matchLengthCount[MaxML+1];
  568. short matchLengthNCount[MaxML+1];
  569. unsigned litLengthCount[MaxLL+1];
  570. short litLengthNCount[MaxLL+1];
  571. U32 repOffset[MAXREPOFFSET];
  572. offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
  573. EStats_ress_t esr = { NULL, NULL, NULL };
  574. ZSTD_parameters params;
  575. U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
  576. size_t pos = 0, errorCode;
  577. size_t eSize = 0;
  578. size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
  579. size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
  580. BYTE* dstPtr = (BYTE*)dstBuffer;
  581. U32 wksp[HUF_CTABLE_WORKSPACE_SIZE_U32];
  582. /* init */
  583. DEBUGLOG(4, "ZDICT_analyzeEntropy");
  584. if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; } /* too large dictionary */
  585. for (u=0; u<256; u++) countLit[u] = 1; /* any character must be described */
  586. for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
  587. for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
  588. for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
  589. memset(repOffset, 0, sizeof(repOffset));
  590. repOffset[1] = repOffset[4] = repOffset[8] = 1;
  591. memset(bestRepOffset, 0, sizeof(bestRepOffset));
  592. if (compressionLevel==0) compressionLevel = ZSTD_CLEVEL_DEFAULT;
  593. params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
  594. esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
  595. esr.zc = ZSTD_createCCtx();
  596. esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
  597. if (!esr.dict || !esr.zc || !esr.workPlace) {
  598. eSize = ERROR(memory_allocation);
  599. DISPLAYLEVEL(1, "Not enough memory \n");
  600. goto _cleanup;
  601. }
  602. /* collect stats on all samples */
  603. for (u=0; u<nbFiles; u++) {
  604. ZDICT_countEStats(esr, &params,
  605. countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
  606. (const char*)srcBuffer + pos, fileSizes[u],
  607. notificationLevel);
  608. pos += fileSizes[u];
  609. }
  610. if (notificationLevel >= 4) {
  611. /* writeStats */
  612. DISPLAYLEVEL(4, "Offset Code Frequencies : \n");
  613. for (u=0; u<=offcodeMax; u++) {
  614. DISPLAYLEVEL(4, "%2u :%7u \n", u, offcodeCount[u]);
  615. } }
  616. /* analyze, build stats, starting with literals */
  617. { size_t maxNbBits = HUF_buildCTable_wksp(hufTable, countLit, 255, huffLog, wksp, sizeof(wksp));
  618. if (HUF_isError(maxNbBits)) {
  619. eSize = maxNbBits;
  620. DISPLAYLEVEL(1, " HUF_buildCTable error \n");
  621. goto _cleanup;
  622. }
  623. if (maxNbBits==8) { /* not compressible : will fail on HUF_writeCTable() */
  624. DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
  625. ZDICT_flatLit(countLit); /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
  626. maxNbBits = HUF_buildCTable_wksp(hufTable, countLit, 255, huffLog, wksp, sizeof(wksp));
  627. assert(maxNbBits==9);
  628. }
  629. huffLog = (U32)maxNbBits;
  630. }
  631. /* looking for most common first offsets */
  632. { U32 offset;
  633. for (offset=1; offset<MAXREPOFFSET; offset++)
  634. ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
  635. }
  636. /* note : the result of this phase should be used to better appreciate the impact on statistics */
  637. total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
  638. errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax, /* useLowProbCount */ 1);
  639. if (FSE_isError(errorCode)) {
  640. eSize = errorCode;
  641. DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
  642. goto _cleanup;
  643. }
  644. Offlog = (U32)errorCode;
  645. total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
  646. errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML, /* useLowProbCount */ 1);
  647. if (FSE_isError(errorCode)) {
  648. eSize = errorCode;
  649. DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
  650. goto _cleanup;
  651. }
  652. mlLog = (U32)errorCode;
  653. total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
  654. errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL, /* useLowProbCount */ 1);
  655. if (FSE_isError(errorCode)) {
  656. eSize = errorCode;
  657. DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
  658. goto _cleanup;
  659. }
  660. llLog = (U32)errorCode;
  661. /* write result to buffer */
  662. { size_t const hhSize = HUF_writeCTable_wksp(dstPtr, maxDstSize, hufTable, 255, huffLog, wksp, sizeof(wksp));
  663. if (HUF_isError(hhSize)) {
  664. eSize = hhSize;
  665. DISPLAYLEVEL(1, "HUF_writeCTable error \n");
  666. goto _cleanup;
  667. }
  668. dstPtr += hhSize;
  669. maxDstSize -= hhSize;
  670. eSize += hhSize;
  671. }
  672. { size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
  673. if (FSE_isError(ohSize)) {
  674. eSize = ohSize;
  675. DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
  676. goto _cleanup;
  677. }
  678. dstPtr += ohSize;
  679. maxDstSize -= ohSize;
  680. eSize += ohSize;
  681. }
  682. { size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
  683. if (FSE_isError(mhSize)) {
  684. eSize = mhSize;
  685. DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
  686. goto _cleanup;
  687. }
  688. dstPtr += mhSize;
  689. maxDstSize -= mhSize;
  690. eSize += mhSize;
  691. }
  692. { size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
  693. if (FSE_isError(lhSize)) {
  694. eSize = lhSize;
  695. DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
  696. goto _cleanup;
  697. }
  698. dstPtr += lhSize;
  699. maxDstSize -= lhSize;
  700. eSize += lhSize;
  701. }
  702. if (maxDstSize<12) {
  703. eSize = ERROR(dstSize_tooSmall);
  704. DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
  705. goto _cleanup;
  706. }
  707. # if 0
  708. MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
  709. MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
  710. MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
  711. #else
  712. /* at this stage, we don't use the result of "most common first offset",
  713. * as the impact of statistics is not properly evaluated */
  714. MEM_writeLE32(dstPtr+0, repStartValue[0]);
  715. MEM_writeLE32(dstPtr+4, repStartValue[1]);
  716. MEM_writeLE32(dstPtr+8, repStartValue[2]);
  717. #endif
  718. eSize += 12;
  719. _cleanup:
  720. ZSTD_freeCDict(esr.dict);
  721. ZSTD_freeCCtx(esr.zc);
  722. free(esr.workPlace);
  723. return eSize;
  724. }
  725. /**
  726. * @returns the maximum repcode value
  727. */
  728. static U32 ZDICT_maxRep(U32 const reps[ZSTD_REP_NUM])
  729. {
  730. U32 maxRep = reps[0];
  731. int r;
  732. for (r = 1; r < ZSTD_REP_NUM; ++r)
  733. maxRep = MAX(maxRep, reps[r]);
  734. return maxRep;
  735. }
  736. size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
  737. const void* customDictContent, size_t dictContentSize,
  738. const void* samplesBuffer, const size_t* samplesSizes,
  739. unsigned nbSamples, ZDICT_params_t params)
  740. {
  741. size_t hSize;
  742. #define HBUFFSIZE 256 /* should prove large enough for all entropy headers */
  743. BYTE header[HBUFFSIZE];
  744. int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
  745. U32 const notificationLevel = params.notificationLevel;
  746. /* The final dictionary content must be at least as large as the largest repcode */
  747. size_t const minContentSize = (size_t)ZDICT_maxRep(repStartValue);
  748. size_t paddingSize;
  749. /* check conditions */
  750. DEBUGLOG(4, "ZDICT_finalizeDictionary");
  751. if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
  752. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
  753. /* dictionary header */
  754. MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
  755. { U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
  756. U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
  757. U32 const dictID = params.dictID ? params.dictID : compliantID;
  758. MEM_writeLE32(header+4, dictID);
  759. }
  760. hSize = 8;
  761. /* entropy tables */
  762. DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
  763. DISPLAYLEVEL(2, "statistics ... \n");
  764. { size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
  765. compressionLevel,
  766. samplesBuffer, samplesSizes, nbSamples,
  767. customDictContent, dictContentSize,
  768. notificationLevel);
  769. if (ZDICT_isError(eSize)) return eSize;
  770. hSize += eSize;
  771. }
  772. /* Shrink the content size if it doesn't fit in the buffer */
  773. if (hSize + dictContentSize > dictBufferCapacity) {
  774. dictContentSize = dictBufferCapacity - hSize;
  775. }
  776. /* Pad the dictionary content with zeros if it is too small */
  777. if (dictContentSize < minContentSize) {
  778. RETURN_ERROR_IF(hSize + minContentSize > dictBufferCapacity, dstSize_tooSmall,
  779. "dictBufferCapacity too small to fit max repcode");
  780. paddingSize = minContentSize - dictContentSize;
  781. } else {
  782. paddingSize = 0;
  783. }
  784. {
  785. size_t const dictSize = hSize + paddingSize + dictContentSize;
  786. /* The dictionary consists of the header, optional padding, and the content.
  787. * The padding comes before the content because the "best" position in the
  788. * dictionary is the last byte.
  789. */
  790. BYTE* const outDictHeader = (BYTE*)dictBuffer;
  791. BYTE* const outDictPadding = outDictHeader + hSize;
  792. BYTE* const outDictContent = outDictPadding + paddingSize;
  793. assert(dictSize <= dictBufferCapacity);
  794. assert(outDictContent + dictContentSize == (BYTE*)dictBuffer + dictSize);
  795. /* First copy the customDictContent into its final location.
  796. * `customDictContent` and `dictBuffer` may overlap, so we must
  797. * do this before any other writes into the output buffer.
  798. * Then copy the header & padding into the output buffer.
  799. */
  800. memmove(outDictContent, customDictContent, dictContentSize);
  801. memcpy(outDictHeader, header, hSize);
  802. memset(outDictPadding, 0, paddingSize);
  803. return dictSize;
  804. }
  805. }
  806. static size_t ZDICT_addEntropyTablesFromBuffer_advanced(
  807. void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
  808. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
  809. ZDICT_params_t params)
  810. {
  811. int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
  812. U32 const notificationLevel = params.notificationLevel;
  813. size_t hSize = 8;
  814. /* calculate entropy tables */
  815. DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
  816. DISPLAYLEVEL(2, "statistics ... \n");
  817. { size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
  818. compressionLevel,
  819. samplesBuffer, samplesSizes, nbSamples,
  820. (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
  821. notificationLevel);
  822. if (ZDICT_isError(eSize)) return eSize;
  823. hSize += eSize;
  824. }
  825. /* add dictionary header (after entropy tables) */
  826. MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
  827. { U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
  828. U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
  829. U32 const dictID = params.dictID ? params.dictID : compliantID;
  830. MEM_writeLE32((char*)dictBuffer+4, dictID);
  831. }
  832. if (hSize + dictContentSize < dictBufferCapacity)
  833. memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);
  834. return MIN(dictBufferCapacity, hSize+dictContentSize);
  835. }
  836. /*! ZDICT_trainFromBuffer_unsafe_legacy() :
  837. * Warning : `samplesBuffer` must be followed by noisy guard band !!!
  838. * @return : size of dictionary, or an error code which can be tested with ZDICT_isError()
  839. */
  840. static size_t ZDICT_trainFromBuffer_unsafe_legacy(
  841. void* dictBuffer, size_t maxDictSize,
  842. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
  843. ZDICT_legacy_params_t params)
  844. {
  845. U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
  846. dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
  847. unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
  848. unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
  849. size_t const targetDictSize = maxDictSize;
  850. size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
  851. size_t dictSize = 0;
  852. U32 const notificationLevel = params.zParams.notificationLevel;
  853. /* checks */
  854. if (!dictList) return ERROR(memory_allocation);
  855. if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); } /* requested dictionary size is too small */
  856. if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); } /* not enough source to create dictionary */
  857. /* init */
  858. ZDICT_initDictItem(dictList);
  859. /* build dictionary */
  860. ZDICT_trainBuffer_legacy(dictList, dictListSize,
  861. samplesBuffer, samplesBuffSize,
  862. samplesSizes, nbSamples,
  863. minRep, notificationLevel);
  864. /* display best matches */
  865. if (params.zParams.notificationLevel>= 3) {
  866. unsigned const nb = MIN(25, dictList[0].pos);
  867. unsigned const dictContentSize = ZDICT_dictSize(dictList);
  868. unsigned u;
  869. DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
  870. DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
  871. for (u=1; u<nb; u++) {
  872. unsigned const pos = dictList[u].pos;
  873. unsigned const length = dictList[u].length;
  874. U32 const printedLength = MIN(40, length);
  875. if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
  876. free(dictList);
  877. return ERROR(GENERIC); /* should never happen */
  878. }
  879. DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
  880. u, length, pos, (unsigned)dictList[u].savings);
  881. ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
  882. DISPLAYLEVEL(3, "| \n");
  883. } }
  884. /* create dictionary */
  885. { unsigned dictContentSize = ZDICT_dictSize(dictList);
  886. if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); } /* dictionary content too small */
  887. if (dictContentSize < targetDictSize/4) {
  888. DISPLAYLEVEL(2, "! warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
  889. if (samplesBuffSize < 10 * targetDictSize)
  890. DISPLAYLEVEL(2, "! consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
  891. if (minRep > MINRATIO) {
  892. DISPLAYLEVEL(2, "! consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
  893. DISPLAYLEVEL(2, "! note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
  894. }
  895. }
  896. if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
  897. unsigned proposedSelectivity = selectivity-1;
  898. while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
  899. DISPLAYLEVEL(2, "! note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
  900. DISPLAYLEVEL(2, "! consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
  901. DISPLAYLEVEL(2, "! always test dictionary efficiency on real samples \n");
  902. }
  903. /* limit dictionary size */
  904. { U32 const max = dictList->pos; /* convention : nb of useful elts within dictList */
  905. U32 currentSize = 0;
  906. U32 n; for (n=1; n<max; n++) {
  907. currentSize += dictList[n].length;
  908. if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
  909. }
  910. dictList->pos = n;
  911. dictContentSize = currentSize;
  912. }
  913. /* build dict content */
  914. { U32 u;
  915. BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
  916. for (u=1; u<dictList->pos; u++) {
  917. U32 l = dictList[u].length;
  918. ptr -= l;
  919. if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); } /* should not happen */
  920. memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
  921. } }
  922. dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
  923. samplesBuffer, samplesSizes, nbSamples,
  924. params.zParams);
  925. }
  926. /* clean up */
  927. free(dictList);
  928. return dictSize;
  929. }
  930. /* ZDICT_trainFromBuffer_legacy() :
  931. * issue : samplesBuffer need to be followed by a noisy guard band.
  932. * work around : duplicate the buffer, and add the noise */
  933. size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,
  934. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
  935. ZDICT_legacy_params_t params)
  936. {
  937. size_t result;
  938. void* newBuff;
  939. size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
  940. if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0; /* not enough content => no dictionary */
  941. newBuff = malloc(sBuffSize + NOISELENGTH);
  942. if (!newBuff) return ERROR(memory_allocation);
  943. memcpy(newBuff, samplesBuffer, sBuffSize);
  944. ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH); /* guard band, for end of buffer condition */
  945. result =
  946. ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,
  947. samplesSizes, nbSamples, params);
  948. free(newBuff);
  949. return result;
  950. }
  951. size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
  952. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
  953. {
  954. ZDICT_fastCover_params_t params;
  955. DEBUGLOG(3, "ZDICT_trainFromBuffer");
  956. memset(&params, 0, sizeof(params));
  957. params.d = 8;
  958. params.steps = 4;
  959. /* Use default level since no compression level information is available */
  960. params.zParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;
  961. #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)
  962. params.zParams.notificationLevel = DEBUGLEVEL;
  963. #endif
  964. return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,
  965. samplesBuffer, samplesSizes, nbSamples,
  966. &params);
  967. }
  968. size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
  969. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
  970. {
  971. ZDICT_params_t params;
  972. memset(&params, 0, sizeof(params));
  973. return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,
  974. samplesBuffer, samplesSizes, nbSamples,
  975. params);
  976. }