zdict.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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(...) do { fprintf(stderr, __VA_ARGS__); fflush( stderr ); } while (0)
  63. #undef DISPLAYLEVEL
  64. #define DISPLAYLEVEL(l, ...) do { if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); } } while (0) /* 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, ...) \
  410. do { \
  411. if (notificationLevel>=l) { \
  412. if (ZDICT_clockSpan(displayClock) > refreshRate) { \
  413. displayClock = clock(); \
  414. DISPLAY(__VA_ARGS__); \
  415. } \
  416. if (notificationLevel>=4) fflush(stderr); \
  417. } \
  418. } while (0)
  419. /* init */
  420. DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
  421. if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
  422. result = ERROR(memory_allocation);
  423. goto _cleanup;
  424. }
  425. if (minRatio < MINRATIO) minRatio = MINRATIO;
  426. memset(doneMarks, 0, bufferSize+16);
  427. /* limit sample set size (divsufsort limitation)*/
  428. if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
  429. while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
  430. /* sort */
  431. DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
  432. { int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
  433. if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
  434. }
  435. suffix[bufferSize] = (int)bufferSize; /* leads into noise */
  436. suffix0[0] = (int)bufferSize; /* leads into noise */
  437. /* build reverse suffix sort */
  438. { size_t pos;
  439. for (pos=0; pos < bufferSize; pos++)
  440. reverseSuffix[suffix[pos]] = (U32)pos;
  441. /* note filePos tracks borders between samples.
  442. It's not used at this stage, but planned to become useful in a later update */
  443. filePos[0] = 0;
  444. for (pos=1; pos<nbFiles; pos++)
  445. filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
  446. }
  447. DISPLAYLEVEL(2, "finding patterns ... \n");
  448. DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
  449. { U32 cursor; for (cursor=0; cursor < bufferSize; ) {
  450. dictItem solution;
  451. if (doneMarks[cursor]) { cursor++; continue; }
  452. solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
  453. if (solution.length==0) { cursor++; continue; }
  454. ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
  455. cursor += solution.length;
  456. DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / (double)bufferSize * 100.0);
  457. } }
  458. _cleanup:
  459. free(suffix0);
  460. free(reverseSuffix);
  461. free(doneMarks);
  462. free(filePos);
  463. return result;
  464. }
  465. static void ZDICT_fillNoise(void* buffer, size_t length)
  466. {
  467. unsigned const prime1 = 2654435761U;
  468. unsigned const prime2 = 2246822519U;
  469. unsigned acc = prime1;
  470. size_t p=0;
  471. for (p=0; p<length; p++) {
  472. acc *= prime2;
  473. ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
  474. }
  475. }
  476. typedef struct
  477. {
  478. ZSTD_CDict* dict; /* dictionary */
  479. ZSTD_CCtx* zc; /* working context */
  480. void* workPlace; /* must be ZSTD_BLOCKSIZE_MAX allocated */
  481. } EStats_ress_t;
  482. #define MAXREPOFFSET 1024
  483. static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params,
  484. unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,
  485. const void* src, size_t srcSize,
  486. U32 notificationLevel)
  487. {
  488. size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params->cParams.windowLog);
  489. size_t cSize;
  490. if (srcSize > blockSizeMax) srcSize = blockSizeMax; /* protection vs large samples */
  491. { size_t const errorCode = ZSTD_compressBegin_usingCDict_deprecated(esr.zc, esr.dict);
  492. if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
  493. }
  494. cSize = ZSTD_compressBlock_deprecated(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
  495. if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
  496. if (cSize) { /* if == 0; block is not compressible */
  497. const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
  498. /* literals stats */
  499. { const BYTE* bytePtr;
  500. for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
  501. countLit[*bytePtr]++;
  502. }
  503. /* seqStats */
  504. { U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
  505. ZSTD_seqToCodes(seqStorePtr);
  506. { const BYTE* codePtr = seqStorePtr->ofCode;
  507. U32 u;
  508. for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
  509. }
  510. { const BYTE* codePtr = seqStorePtr->mlCode;
  511. U32 u;
  512. for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
  513. }
  514. { const BYTE* codePtr = seqStorePtr->llCode;
  515. U32 u;
  516. for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
  517. }
  518. if (nbSeq >= 2) { /* rep offsets */
  519. const seqDef* const seq = seqStorePtr->sequencesStart;
  520. U32 offset1 = seq[0].offBase - ZSTD_REP_NUM;
  521. U32 offset2 = seq[1].offBase - ZSTD_REP_NUM;
  522. if (offset1 >= MAXREPOFFSET) offset1 = 0;
  523. if (offset2 >= MAXREPOFFSET) offset2 = 0;
  524. repOffsets[offset1] += 3;
  525. repOffsets[offset2] += 1;
  526. } } }
  527. }
  528. static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)
  529. {
  530. size_t total=0;
  531. unsigned u;
  532. for (u=0; u<nbFiles; u++) total += fileSizes[u];
  533. return total;
  534. }
  535. typedef struct { U32 offset; U32 count; } offsetCount_t;
  536. static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
  537. {
  538. U32 u;
  539. table[ZSTD_REP_NUM].offset = val;
  540. table[ZSTD_REP_NUM].count = count;
  541. for (u=ZSTD_REP_NUM; u>0; u--) {
  542. offsetCount_t tmp;
  543. if (table[u-1].count >= table[u].count) break;
  544. tmp = table[u-1];
  545. table[u-1] = table[u];
  546. table[u] = tmp;
  547. }
  548. }
  549. /* ZDICT_flatLit() :
  550. * rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.
  551. * necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.
  552. */
  553. static void ZDICT_flatLit(unsigned* countLit)
  554. {
  555. int u;
  556. for (u=1; u<256; u++) countLit[u] = 2;
  557. countLit[0] = 4;
  558. countLit[253] = 1;
  559. countLit[254] = 1;
  560. }
  561. #define OFFCODE_MAX 30 /* only applicable to first block */
  562. static size_t ZDICT_analyzeEntropy(void* dstBuffer, size_t maxDstSize,
  563. int compressionLevel,
  564. const void* srcBuffer, const size_t* fileSizes, unsigned nbFiles,
  565. const void* dictBuffer, size_t dictBufferSize,
  566. unsigned notificationLevel)
  567. {
  568. unsigned countLit[256];
  569. HUF_CREATE_STATIC_CTABLE(hufTable, 255);
  570. unsigned offcodeCount[OFFCODE_MAX+1];
  571. short offcodeNCount[OFFCODE_MAX+1];
  572. U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
  573. unsigned matchLengthCount[MaxML+1];
  574. short matchLengthNCount[MaxML+1];
  575. unsigned litLengthCount[MaxLL+1];
  576. short litLengthNCount[MaxLL+1];
  577. U32 repOffset[MAXREPOFFSET];
  578. offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
  579. EStats_ress_t esr = { NULL, NULL, NULL };
  580. ZSTD_parameters params;
  581. U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
  582. size_t pos = 0, errorCode;
  583. size_t eSize = 0;
  584. size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
  585. size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
  586. BYTE* dstPtr = (BYTE*)dstBuffer;
  587. U32 wksp[HUF_CTABLE_WORKSPACE_SIZE_U32];
  588. /* init */
  589. DEBUGLOG(4, "ZDICT_analyzeEntropy");
  590. if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; } /* too large dictionary */
  591. for (u=0; u<256; u++) countLit[u] = 1; /* any character must be described */
  592. for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
  593. for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
  594. for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
  595. memset(repOffset, 0, sizeof(repOffset));
  596. repOffset[1] = repOffset[4] = repOffset[8] = 1;
  597. memset(bestRepOffset, 0, sizeof(bestRepOffset));
  598. if (compressionLevel==0) compressionLevel = ZSTD_CLEVEL_DEFAULT;
  599. params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
  600. esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
  601. esr.zc = ZSTD_createCCtx();
  602. esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
  603. if (!esr.dict || !esr.zc || !esr.workPlace) {
  604. eSize = ERROR(memory_allocation);
  605. DISPLAYLEVEL(1, "Not enough memory \n");
  606. goto _cleanup;
  607. }
  608. /* collect stats on all samples */
  609. for (u=0; u<nbFiles; u++) {
  610. ZDICT_countEStats(esr, &params,
  611. countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
  612. (const char*)srcBuffer + pos, fileSizes[u],
  613. notificationLevel);
  614. pos += fileSizes[u];
  615. }
  616. if (notificationLevel >= 4) {
  617. /* writeStats */
  618. DISPLAYLEVEL(4, "Offset Code Frequencies : \n");
  619. for (u=0; u<=offcodeMax; u++) {
  620. DISPLAYLEVEL(4, "%2u :%7u \n", u, offcodeCount[u]);
  621. } }
  622. /* analyze, build stats, starting with literals */
  623. { size_t maxNbBits = HUF_buildCTable_wksp(hufTable, countLit, 255, huffLog, wksp, sizeof(wksp));
  624. if (HUF_isError(maxNbBits)) {
  625. eSize = maxNbBits;
  626. DISPLAYLEVEL(1, " HUF_buildCTable error \n");
  627. goto _cleanup;
  628. }
  629. if (maxNbBits==8) { /* not compressible : will fail on HUF_writeCTable() */
  630. DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
  631. ZDICT_flatLit(countLit); /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
  632. maxNbBits = HUF_buildCTable_wksp(hufTable, countLit, 255, huffLog, wksp, sizeof(wksp));
  633. assert(maxNbBits==9);
  634. }
  635. huffLog = (U32)maxNbBits;
  636. }
  637. /* looking for most common first offsets */
  638. { U32 offset;
  639. for (offset=1; offset<MAXREPOFFSET; offset++)
  640. ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
  641. }
  642. /* note : the result of this phase should be used to better appreciate the impact on statistics */
  643. total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
  644. errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax, /* useLowProbCount */ 1);
  645. if (FSE_isError(errorCode)) {
  646. eSize = errorCode;
  647. DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
  648. goto _cleanup;
  649. }
  650. Offlog = (U32)errorCode;
  651. total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
  652. errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML, /* useLowProbCount */ 1);
  653. if (FSE_isError(errorCode)) {
  654. eSize = errorCode;
  655. DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
  656. goto _cleanup;
  657. }
  658. mlLog = (U32)errorCode;
  659. total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
  660. errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL, /* useLowProbCount */ 1);
  661. if (FSE_isError(errorCode)) {
  662. eSize = errorCode;
  663. DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
  664. goto _cleanup;
  665. }
  666. llLog = (U32)errorCode;
  667. /* write result to buffer */
  668. { size_t const hhSize = HUF_writeCTable_wksp(dstPtr, maxDstSize, hufTable, 255, huffLog, wksp, sizeof(wksp));
  669. if (HUF_isError(hhSize)) {
  670. eSize = hhSize;
  671. DISPLAYLEVEL(1, "HUF_writeCTable error \n");
  672. goto _cleanup;
  673. }
  674. dstPtr += hhSize;
  675. maxDstSize -= hhSize;
  676. eSize += hhSize;
  677. }
  678. { size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
  679. if (FSE_isError(ohSize)) {
  680. eSize = ohSize;
  681. DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
  682. goto _cleanup;
  683. }
  684. dstPtr += ohSize;
  685. maxDstSize -= ohSize;
  686. eSize += ohSize;
  687. }
  688. { size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
  689. if (FSE_isError(mhSize)) {
  690. eSize = mhSize;
  691. DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
  692. goto _cleanup;
  693. }
  694. dstPtr += mhSize;
  695. maxDstSize -= mhSize;
  696. eSize += mhSize;
  697. }
  698. { size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
  699. if (FSE_isError(lhSize)) {
  700. eSize = lhSize;
  701. DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
  702. goto _cleanup;
  703. }
  704. dstPtr += lhSize;
  705. maxDstSize -= lhSize;
  706. eSize += lhSize;
  707. }
  708. if (maxDstSize<12) {
  709. eSize = ERROR(dstSize_tooSmall);
  710. DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
  711. goto _cleanup;
  712. }
  713. # if 0
  714. MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
  715. MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
  716. MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
  717. #else
  718. /* at this stage, we don't use the result of "most common first offset",
  719. * as the impact of statistics is not properly evaluated */
  720. MEM_writeLE32(dstPtr+0, repStartValue[0]);
  721. MEM_writeLE32(dstPtr+4, repStartValue[1]);
  722. MEM_writeLE32(dstPtr+8, repStartValue[2]);
  723. #endif
  724. eSize += 12;
  725. _cleanup:
  726. ZSTD_freeCDict(esr.dict);
  727. ZSTD_freeCCtx(esr.zc);
  728. free(esr.workPlace);
  729. return eSize;
  730. }
  731. /**
  732. * @returns the maximum repcode value
  733. */
  734. static U32 ZDICT_maxRep(U32 const reps[ZSTD_REP_NUM])
  735. {
  736. U32 maxRep = reps[0];
  737. int r;
  738. for (r = 1; r < ZSTD_REP_NUM; ++r)
  739. maxRep = MAX(maxRep, reps[r]);
  740. return maxRep;
  741. }
  742. size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
  743. const void* customDictContent, size_t dictContentSize,
  744. const void* samplesBuffer, const size_t* samplesSizes,
  745. unsigned nbSamples, ZDICT_params_t params)
  746. {
  747. size_t hSize;
  748. #define HBUFFSIZE 256 /* should prove large enough for all entropy headers */
  749. BYTE header[HBUFFSIZE];
  750. int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
  751. U32 const notificationLevel = params.notificationLevel;
  752. /* The final dictionary content must be at least as large as the largest repcode */
  753. size_t const minContentSize = (size_t)ZDICT_maxRep(repStartValue);
  754. size_t paddingSize;
  755. /* check conditions */
  756. DEBUGLOG(4, "ZDICT_finalizeDictionary");
  757. if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
  758. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
  759. /* dictionary header */
  760. MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
  761. { U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
  762. U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
  763. U32 const dictID = params.dictID ? params.dictID : compliantID;
  764. MEM_writeLE32(header+4, dictID);
  765. }
  766. hSize = 8;
  767. /* entropy tables */
  768. DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
  769. DISPLAYLEVEL(2, "statistics ... \n");
  770. { size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
  771. compressionLevel,
  772. samplesBuffer, samplesSizes, nbSamples,
  773. customDictContent, dictContentSize,
  774. notificationLevel);
  775. if (ZDICT_isError(eSize)) return eSize;
  776. hSize += eSize;
  777. }
  778. /* Shrink the content size if it doesn't fit in the buffer */
  779. if (hSize + dictContentSize > dictBufferCapacity) {
  780. dictContentSize = dictBufferCapacity - hSize;
  781. }
  782. /* Pad the dictionary content with zeros if it is too small */
  783. if (dictContentSize < minContentSize) {
  784. RETURN_ERROR_IF(hSize + minContentSize > dictBufferCapacity, dstSize_tooSmall,
  785. "dictBufferCapacity too small to fit max repcode");
  786. paddingSize = minContentSize - dictContentSize;
  787. } else {
  788. paddingSize = 0;
  789. }
  790. {
  791. size_t const dictSize = hSize + paddingSize + dictContentSize;
  792. /* The dictionary consists of the header, optional padding, and the content.
  793. * The padding comes before the content because the "best" position in the
  794. * dictionary is the last byte.
  795. */
  796. BYTE* const outDictHeader = (BYTE*)dictBuffer;
  797. BYTE* const outDictPadding = outDictHeader + hSize;
  798. BYTE* const outDictContent = outDictPadding + paddingSize;
  799. assert(dictSize <= dictBufferCapacity);
  800. assert(outDictContent + dictContentSize == (BYTE*)dictBuffer + dictSize);
  801. /* First copy the customDictContent into its final location.
  802. * `customDictContent` and `dictBuffer` may overlap, so we must
  803. * do this before any other writes into the output buffer.
  804. * Then copy the header & padding into the output buffer.
  805. */
  806. memmove(outDictContent, customDictContent, dictContentSize);
  807. memcpy(outDictHeader, header, hSize);
  808. memset(outDictPadding, 0, paddingSize);
  809. return dictSize;
  810. }
  811. }
  812. static size_t ZDICT_addEntropyTablesFromBuffer_advanced(
  813. void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
  814. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
  815. ZDICT_params_t params)
  816. {
  817. int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
  818. U32 const notificationLevel = params.notificationLevel;
  819. size_t hSize = 8;
  820. /* calculate entropy tables */
  821. DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
  822. DISPLAYLEVEL(2, "statistics ... \n");
  823. { size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
  824. compressionLevel,
  825. samplesBuffer, samplesSizes, nbSamples,
  826. (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
  827. notificationLevel);
  828. if (ZDICT_isError(eSize)) return eSize;
  829. hSize += eSize;
  830. }
  831. /* add dictionary header (after entropy tables) */
  832. MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
  833. { U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
  834. U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
  835. U32 const dictID = params.dictID ? params.dictID : compliantID;
  836. MEM_writeLE32((char*)dictBuffer+4, dictID);
  837. }
  838. if (hSize + dictContentSize < dictBufferCapacity)
  839. memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);
  840. return MIN(dictBufferCapacity, hSize+dictContentSize);
  841. }
  842. /*! ZDICT_trainFromBuffer_unsafe_legacy() :
  843. * Warning : `samplesBuffer` must be followed by noisy guard band !!!
  844. * @return : size of dictionary, or an error code which can be tested with ZDICT_isError()
  845. */
  846. static size_t ZDICT_trainFromBuffer_unsafe_legacy(
  847. void* dictBuffer, size_t maxDictSize,
  848. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
  849. ZDICT_legacy_params_t params)
  850. {
  851. U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
  852. dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
  853. unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
  854. unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
  855. size_t const targetDictSize = maxDictSize;
  856. size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
  857. size_t dictSize = 0;
  858. U32 const notificationLevel = params.zParams.notificationLevel;
  859. /* checks */
  860. if (!dictList) return ERROR(memory_allocation);
  861. if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); } /* requested dictionary size is too small */
  862. if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); } /* not enough source to create dictionary */
  863. /* init */
  864. ZDICT_initDictItem(dictList);
  865. /* build dictionary */
  866. ZDICT_trainBuffer_legacy(dictList, dictListSize,
  867. samplesBuffer, samplesBuffSize,
  868. samplesSizes, nbSamples,
  869. minRep, notificationLevel);
  870. /* display best matches */
  871. if (params.zParams.notificationLevel>= 3) {
  872. unsigned const nb = MIN(25, dictList[0].pos);
  873. unsigned const dictContentSize = ZDICT_dictSize(dictList);
  874. unsigned u;
  875. DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
  876. DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
  877. for (u=1; u<nb; u++) {
  878. unsigned const pos = dictList[u].pos;
  879. unsigned const length = dictList[u].length;
  880. U32 const printedLength = MIN(40, length);
  881. if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
  882. free(dictList);
  883. return ERROR(GENERIC); /* should never happen */
  884. }
  885. DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
  886. u, length, pos, (unsigned)dictList[u].savings);
  887. ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
  888. DISPLAYLEVEL(3, "| \n");
  889. } }
  890. /* create dictionary */
  891. { unsigned dictContentSize = ZDICT_dictSize(dictList);
  892. if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); } /* dictionary content too small */
  893. if (dictContentSize < targetDictSize/4) {
  894. DISPLAYLEVEL(2, "! warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
  895. if (samplesBuffSize < 10 * targetDictSize)
  896. DISPLAYLEVEL(2, "! consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
  897. if (minRep > MINRATIO) {
  898. DISPLAYLEVEL(2, "! consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
  899. DISPLAYLEVEL(2, "! note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
  900. }
  901. }
  902. if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
  903. unsigned proposedSelectivity = selectivity-1;
  904. while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
  905. DISPLAYLEVEL(2, "! note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
  906. DISPLAYLEVEL(2, "! consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
  907. DISPLAYLEVEL(2, "! always test dictionary efficiency on real samples \n");
  908. }
  909. /* limit dictionary size */
  910. { U32 const max = dictList->pos; /* convention : nb of useful elts within dictList */
  911. U32 currentSize = 0;
  912. U32 n; for (n=1; n<max; n++) {
  913. currentSize += dictList[n].length;
  914. if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
  915. }
  916. dictList->pos = n;
  917. dictContentSize = currentSize;
  918. }
  919. /* build dict content */
  920. { U32 u;
  921. BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
  922. for (u=1; u<dictList->pos; u++) {
  923. U32 l = dictList[u].length;
  924. ptr -= l;
  925. if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); } /* should not happen */
  926. memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
  927. } }
  928. dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
  929. samplesBuffer, samplesSizes, nbSamples,
  930. params.zParams);
  931. }
  932. /* clean up */
  933. free(dictList);
  934. return dictSize;
  935. }
  936. /* ZDICT_trainFromBuffer_legacy() :
  937. * issue : samplesBuffer need to be followed by a noisy guard band.
  938. * work around : duplicate the buffer, and add the noise */
  939. size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,
  940. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
  941. ZDICT_legacy_params_t params)
  942. {
  943. size_t result;
  944. void* newBuff;
  945. size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
  946. if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0; /* not enough content => no dictionary */
  947. newBuff = malloc(sBuffSize + NOISELENGTH);
  948. if (!newBuff) return ERROR(memory_allocation);
  949. memcpy(newBuff, samplesBuffer, sBuffSize);
  950. ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH); /* guard band, for end of buffer condition */
  951. result =
  952. ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,
  953. samplesSizes, nbSamples, params);
  954. free(newBuff);
  955. return result;
  956. }
  957. size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
  958. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
  959. {
  960. ZDICT_fastCover_params_t params;
  961. DEBUGLOG(3, "ZDICT_trainFromBuffer");
  962. memset(&params, 0, sizeof(params));
  963. params.d = 8;
  964. params.steps = 4;
  965. /* Use default level since no compression level information is available */
  966. params.zParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;
  967. #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)
  968. params.zParams.notificationLevel = DEBUGLEVEL;
  969. #endif
  970. return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,
  971. samplesBuffer, samplesSizes, nbSamples,
  972. &params);
  973. }
  974. size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
  975. const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
  976. {
  977. ZDICT_params_t params;
  978. memset(&params, 0, sizeof(params));
  979. return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,
  980. samplesBuffer, samplesSizes, nbSamples,
  981. params);
  982. }