zdict.c 46 KB

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