1
0

zdict.c 43 KB

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