cover.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. /*
  2. * Copyright (c) 2016-2020, 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. * Constructs a dictionary using a heuristic based on the following paper:
  12. *
  13. * Liao, Petri, Moffat, Wirth
  14. * Effective Construction of Relative Lempel-Ziv Dictionaries
  15. * Published in WWW 2016.
  16. *
  17. * Adapted from code originally written by @ot (Giuseppe Ottaviano).
  18. ******************************************************************************/
  19. /*-*************************************
  20. * Dependencies
  21. ***************************************/
  22. #include <stdio.h> /* fprintf */
  23. #include <stdlib.h> /* malloc, free, qsort */
  24. #include <string.h> /* memset */
  25. #include <time.h> /* clock */
  26. #include "../common/mem.h" /* read */
  27. #include "../common/pool.h"
  28. #include "../common/threading.h"
  29. #include "cover.h"
  30. #include "../common/zstd_internal.h" /* includes zstd.h */
  31. #ifndef ZDICT_STATIC_LINKING_ONLY
  32. #define ZDICT_STATIC_LINKING_ONLY
  33. #endif
  34. #include "zdict.h"
  35. /*-*************************************
  36. * Constants
  37. ***************************************/
  38. #define COVER_MAX_SAMPLES_SIZE (sizeof(size_t) == 8 ? ((unsigned)-1) : ((unsigned)1 GB))
  39. #define DEFAULT_SPLITPOINT 1.0
  40. /*-*************************************
  41. * Console display
  42. ***************************************/
  43. static int g_displayLevel = 2;
  44. #define DISPLAY(...) \
  45. { \
  46. fprintf(stderr, __VA_ARGS__); \
  47. fflush(stderr); \
  48. }
  49. #define LOCALDISPLAYLEVEL(displayLevel, l, ...) \
  50. if (displayLevel >= l) { \
  51. DISPLAY(__VA_ARGS__); \
  52. } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */
  53. #define DISPLAYLEVEL(l, ...) LOCALDISPLAYLEVEL(g_displayLevel, l, __VA_ARGS__)
  54. #define LOCALDISPLAYUPDATE(displayLevel, l, ...) \
  55. if (displayLevel >= l) { \
  56. if ((clock() - g_time > refreshRate) || (displayLevel >= 4)) { \
  57. g_time = clock(); \
  58. DISPLAY(__VA_ARGS__); \
  59. } \
  60. }
  61. #define DISPLAYUPDATE(l, ...) LOCALDISPLAYUPDATE(g_displayLevel, l, __VA_ARGS__)
  62. static const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100;
  63. static clock_t g_time = 0;
  64. /*-*************************************
  65. * Hash table
  66. ***************************************
  67. * A small specialized hash map for storing activeDmers.
  68. * The map does not resize, so if it becomes full it will loop forever.
  69. * Thus, the map must be large enough to store every value.
  70. * The map implements linear probing and keeps its load less than 0.5.
  71. */
  72. #define MAP_EMPTY_VALUE ((U32)-1)
  73. typedef struct COVER_map_pair_t_s {
  74. U32 key;
  75. U32 value;
  76. } COVER_map_pair_t;
  77. typedef struct COVER_map_s {
  78. COVER_map_pair_t *data;
  79. U32 sizeLog;
  80. U32 size;
  81. U32 sizeMask;
  82. } COVER_map_t;
  83. /**
  84. * Clear the map.
  85. */
  86. static void COVER_map_clear(COVER_map_t *map) {
  87. memset(map->data, MAP_EMPTY_VALUE, map->size * sizeof(COVER_map_pair_t));
  88. }
  89. /**
  90. * Initializes a map of the given size.
  91. * Returns 1 on success and 0 on failure.
  92. * The map must be destroyed with COVER_map_destroy().
  93. * The map is only guaranteed to be large enough to hold size elements.
  94. */
  95. static int COVER_map_init(COVER_map_t *map, U32 size) {
  96. map->sizeLog = ZSTD_highbit32(size) + 2;
  97. map->size = (U32)1 << map->sizeLog;
  98. map->sizeMask = map->size - 1;
  99. map->data = (COVER_map_pair_t *)malloc(map->size * sizeof(COVER_map_pair_t));
  100. if (!map->data) {
  101. map->sizeLog = 0;
  102. map->size = 0;
  103. return 0;
  104. }
  105. COVER_map_clear(map);
  106. return 1;
  107. }
  108. /**
  109. * Internal hash function
  110. */
  111. static const U32 prime4bytes = 2654435761U;
  112. static U32 COVER_map_hash(COVER_map_t *map, U32 key) {
  113. return (key * prime4bytes) >> (32 - map->sizeLog);
  114. }
  115. /**
  116. * Helper function that returns the index that a key should be placed into.
  117. */
  118. static U32 COVER_map_index(COVER_map_t *map, U32 key) {
  119. const U32 hash = COVER_map_hash(map, key);
  120. U32 i;
  121. for (i = hash;; i = (i + 1) & map->sizeMask) {
  122. COVER_map_pair_t *pos = &map->data[i];
  123. if (pos->value == MAP_EMPTY_VALUE) {
  124. return i;
  125. }
  126. if (pos->key == key) {
  127. return i;
  128. }
  129. }
  130. }
  131. /**
  132. * Returns the pointer to the value for key.
  133. * If key is not in the map, it is inserted and the value is set to 0.
  134. * The map must not be full.
  135. */
  136. static U32 *COVER_map_at(COVER_map_t *map, U32 key) {
  137. COVER_map_pair_t *pos = &map->data[COVER_map_index(map, key)];
  138. if (pos->value == MAP_EMPTY_VALUE) {
  139. pos->key = key;
  140. pos->value = 0;
  141. }
  142. return &pos->value;
  143. }
  144. /**
  145. * Deletes key from the map if present.
  146. */
  147. static void COVER_map_remove(COVER_map_t *map, U32 key) {
  148. U32 i = COVER_map_index(map, key);
  149. COVER_map_pair_t *del = &map->data[i];
  150. U32 shift = 1;
  151. if (del->value == MAP_EMPTY_VALUE) {
  152. return;
  153. }
  154. for (i = (i + 1) & map->sizeMask;; i = (i + 1) & map->sizeMask) {
  155. COVER_map_pair_t *const pos = &map->data[i];
  156. /* If the position is empty we are done */
  157. if (pos->value == MAP_EMPTY_VALUE) {
  158. del->value = MAP_EMPTY_VALUE;
  159. return;
  160. }
  161. /* If pos can be moved to del do so */
  162. if (((i - COVER_map_hash(map, pos->key)) & map->sizeMask) >= shift) {
  163. del->key = pos->key;
  164. del->value = pos->value;
  165. del = pos;
  166. shift = 1;
  167. } else {
  168. ++shift;
  169. }
  170. }
  171. }
  172. /**
  173. * Destroys a map that is inited with COVER_map_init().
  174. */
  175. static void COVER_map_destroy(COVER_map_t *map) {
  176. if (map->data) {
  177. free(map->data);
  178. }
  179. map->data = NULL;
  180. map->size = 0;
  181. }
  182. /*-*************************************
  183. * Context
  184. ***************************************/
  185. typedef struct {
  186. const BYTE *samples;
  187. size_t *offsets;
  188. const size_t *samplesSizes;
  189. size_t nbSamples;
  190. size_t nbTrainSamples;
  191. size_t nbTestSamples;
  192. U32 *suffix;
  193. size_t suffixSize;
  194. U32 *freqs;
  195. U32 *dmerAt;
  196. unsigned d;
  197. } COVER_ctx_t;
  198. /* We need a global context for qsort... */
  199. static COVER_ctx_t *g_ctx = NULL;
  200. /*-*************************************
  201. * Helper functions
  202. ***************************************/
  203. /**
  204. * Returns the sum of the sample sizes.
  205. */
  206. size_t COVER_sum(const size_t *samplesSizes, unsigned nbSamples) {
  207. size_t sum = 0;
  208. unsigned i;
  209. for (i = 0; i < nbSamples; ++i) {
  210. sum += samplesSizes[i];
  211. }
  212. return sum;
  213. }
  214. /**
  215. * Returns -1 if the dmer at lp is less than the dmer at rp.
  216. * Return 0 if the dmers at lp and rp are equal.
  217. * Returns 1 if the dmer at lp is greater than the dmer at rp.
  218. */
  219. static int COVER_cmp(COVER_ctx_t *ctx, const void *lp, const void *rp) {
  220. U32 const lhs = *(U32 const *)lp;
  221. U32 const rhs = *(U32 const *)rp;
  222. return memcmp(ctx->samples + lhs, ctx->samples + rhs, ctx->d);
  223. }
  224. /**
  225. * Faster version for d <= 8.
  226. */
  227. static int COVER_cmp8(COVER_ctx_t *ctx, const void *lp, const void *rp) {
  228. U64 const mask = (ctx->d == 8) ? (U64)-1 : (((U64)1 << (8 * ctx->d)) - 1);
  229. U64 const lhs = MEM_readLE64(ctx->samples + *(U32 const *)lp) & mask;
  230. U64 const rhs = MEM_readLE64(ctx->samples + *(U32 const *)rp) & mask;
  231. if (lhs < rhs) {
  232. return -1;
  233. }
  234. return (lhs > rhs);
  235. }
  236. /**
  237. * Same as COVER_cmp() except ties are broken by pointer value
  238. * NOTE: g_ctx must be set to call this function. A global is required because
  239. * qsort doesn't take an opaque pointer.
  240. */
  241. static int COVER_strict_cmp(const void *lp, const void *rp) {
  242. int result = COVER_cmp(g_ctx, lp, rp);
  243. if (result == 0) {
  244. result = lp < rp ? -1 : 1;
  245. }
  246. return result;
  247. }
  248. /**
  249. * Faster version for d <= 8.
  250. */
  251. static int COVER_strict_cmp8(const void *lp, const void *rp) {
  252. int result = COVER_cmp8(g_ctx, lp, rp);
  253. if (result == 0) {
  254. result = lp < rp ? -1 : 1;
  255. }
  256. return result;
  257. }
  258. /**
  259. * Returns the first pointer in [first, last) whose element does not compare
  260. * less than value. If no such element exists it returns last.
  261. */
  262. static const size_t *COVER_lower_bound(const size_t *first, const size_t *last,
  263. size_t value) {
  264. size_t count = last - first;
  265. while (count != 0) {
  266. size_t step = count / 2;
  267. const size_t *ptr = first;
  268. ptr += step;
  269. if (*ptr < value) {
  270. first = ++ptr;
  271. count -= step + 1;
  272. } else {
  273. count = step;
  274. }
  275. }
  276. return first;
  277. }
  278. /**
  279. * Generic groupBy function.
  280. * Groups an array sorted by cmp into groups with equivalent values.
  281. * Calls grp for each group.
  282. */
  283. static void
  284. COVER_groupBy(const void *data, size_t count, size_t size, COVER_ctx_t *ctx,
  285. int (*cmp)(COVER_ctx_t *, const void *, const void *),
  286. void (*grp)(COVER_ctx_t *, const void *, const void *)) {
  287. const BYTE *ptr = (const BYTE *)data;
  288. size_t num = 0;
  289. while (num < count) {
  290. const BYTE *grpEnd = ptr + size;
  291. ++num;
  292. while (num < count && cmp(ctx, ptr, grpEnd) == 0) {
  293. grpEnd += size;
  294. ++num;
  295. }
  296. grp(ctx, ptr, grpEnd);
  297. ptr = grpEnd;
  298. }
  299. }
  300. /*-*************************************
  301. * Cover functions
  302. ***************************************/
  303. /**
  304. * Called on each group of positions with the same dmer.
  305. * Counts the frequency of each dmer and saves it in the suffix array.
  306. * Fills `ctx->dmerAt`.
  307. */
  308. static void COVER_group(COVER_ctx_t *ctx, const void *group,
  309. const void *groupEnd) {
  310. /* The group consists of all the positions with the same first d bytes. */
  311. const U32 *grpPtr = (const U32 *)group;
  312. const U32 *grpEnd = (const U32 *)groupEnd;
  313. /* The dmerId is how we will reference this dmer.
  314. * This allows us to map the whole dmer space to a much smaller space, the
  315. * size of the suffix array.
  316. */
  317. const U32 dmerId = (U32)(grpPtr - ctx->suffix);
  318. /* Count the number of samples this dmer shows up in */
  319. U32 freq = 0;
  320. /* Details */
  321. const size_t *curOffsetPtr = ctx->offsets;
  322. const size_t *offsetsEnd = ctx->offsets + ctx->nbSamples;
  323. /* Once *grpPtr >= curSampleEnd this occurrence of the dmer is in a
  324. * different sample than the last.
  325. */
  326. size_t curSampleEnd = ctx->offsets[0];
  327. for (; grpPtr != grpEnd; ++grpPtr) {
  328. /* Save the dmerId for this position so we can get back to it. */
  329. ctx->dmerAt[*grpPtr] = dmerId;
  330. /* Dictionaries only help for the first reference to the dmer.
  331. * After that zstd can reference the match from the previous reference.
  332. * So only count each dmer once for each sample it is in.
  333. */
  334. if (*grpPtr < curSampleEnd) {
  335. continue;
  336. }
  337. freq += 1;
  338. /* Binary search to find the end of the sample *grpPtr is in.
  339. * In the common case that grpPtr + 1 == grpEnd we can skip the binary
  340. * search because the loop is over.
  341. */
  342. if (grpPtr + 1 != grpEnd) {
  343. const size_t *sampleEndPtr =
  344. COVER_lower_bound(curOffsetPtr, offsetsEnd, *grpPtr);
  345. curSampleEnd = *sampleEndPtr;
  346. curOffsetPtr = sampleEndPtr + 1;
  347. }
  348. }
  349. /* At this point we are never going to look at this segment of the suffix
  350. * array again. We take advantage of this fact to save memory.
  351. * We store the frequency of the dmer in the first position of the group,
  352. * which is dmerId.
  353. */
  354. ctx->suffix[dmerId] = freq;
  355. }
  356. /**
  357. * Selects the best segment in an epoch.
  358. * Segments of are scored according to the function:
  359. *
  360. * Let F(d) be the frequency of dmer d.
  361. * Let S_i be the dmer at position i of segment S which has length k.
  362. *
  363. * Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})
  364. *
  365. * Once the dmer d is in the dictionary we set F(d) = 0.
  366. */
  367. static COVER_segment_t COVER_selectSegment(const COVER_ctx_t *ctx, U32 *freqs,
  368. COVER_map_t *activeDmers, U32 begin,
  369. U32 end,
  370. ZDICT_cover_params_t parameters) {
  371. /* Constants */
  372. const U32 k = parameters.k;
  373. const U32 d = parameters.d;
  374. const U32 dmersInK = k - d + 1;
  375. /* Try each segment (activeSegment) and save the best (bestSegment) */
  376. COVER_segment_t bestSegment = {0, 0, 0};
  377. COVER_segment_t activeSegment;
  378. /* Reset the activeDmers in the segment */
  379. COVER_map_clear(activeDmers);
  380. /* The activeSegment starts at the beginning of the epoch. */
  381. activeSegment.begin = begin;
  382. activeSegment.end = begin;
  383. activeSegment.score = 0;
  384. /* Slide the activeSegment through the whole epoch.
  385. * Save the best segment in bestSegment.
  386. */
  387. while (activeSegment.end < end) {
  388. /* The dmerId for the dmer at the next position */
  389. U32 newDmer = ctx->dmerAt[activeSegment.end];
  390. /* The entry in activeDmers for this dmerId */
  391. U32 *newDmerOcc = COVER_map_at(activeDmers, newDmer);
  392. /* If the dmer isn't already present in the segment add its score. */
  393. if (*newDmerOcc == 0) {
  394. /* The paper suggest using the L-0.5 norm, but experiments show that it
  395. * doesn't help.
  396. */
  397. activeSegment.score += freqs[newDmer];
  398. }
  399. /* Add the dmer to the segment */
  400. activeSegment.end += 1;
  401. *newDmerOcc += 1;
  402. /* If the window is now too large, drop the first position */
  403. if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
  404. U32 delDmer = ctx->dmerAt[activeSegment.begin];
  405. U32 *delDmerOcc = COVER_map_at(activeDmers, delDmer);
  406. activeSegment.begin += 1;
  407. *delDmerOcc -= 1;
  408. /* If this is the last occurrence of the dmer, subtract its score */
  409. if (*delDmerOcc == 0) {
  410. COVER_map_remove(activeDmers, delDmer);
  411. activeSegment.score -= freqs[delDmer];
  412. }
  413. }
  414. /* If this segment is the best so far save it */
  415. if (activeSegment.score > bestSegment.score) {
  416. bestSegment = activeSegment;
  417. }
  418. }
  419. {
  420. /* Trim off the zero frequency head and tail from the segment. */
  421. U32 newBegin = bestSegment.end;
  422. U32 newEnd = bestSegment.begin;
  423. U32 pos;
  424. for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
  425. U32 freq = freqs[ctx->dmerAt[pos]];
  426. if (freq != 0) {
  427. newBegin = MIN(newBegin, pos);
  428. newEnd = pos + 1;
  429. }
  430. }
  431. bestSegment.begin = newBegin;
  432. bestSegment.end = newEnd;
  433. }
  434. {
  435. /* Zero out the frequency of each dmer covered by the chosen segment. */
  436. U32 pos;
  437. for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
  438. freqs[ctx->dmerAt[pos]] = 0;
  439. }
  440. }
  441. return bestSegment;
  442. }
  443. /**
  444. * Check the validity of the parameters.
  445. * Returns non-zero if the parameters are valid and 0 otherwise.
  446. */
  447. static int COVER_checkParameters(ZDICT_cover_params_t parameters,
  448. size_t maxDictSize) {
  449. /* k and d are required parameters */
  450. if (parameters.d == 0 || parameters.k == 0) {
  451. return 0;
  452. }
  453. /* k <= maxDictSize */
  454. if (parameters.k > maxDictSize) {
  455. return 0;
  456. }
  457. /* d <= k */
  458. if (parameters.d > parameters.k) {
  459. return 0;
  460. }
  461. /* 0 < splitPoint <= 1 */
  462. if (parameters.splitPoint <= 0 || parameters.splitPoint > 1){
  463. return 0;
  464. }
  465. return 1;
  466. }
  467. /**
  468. * Clean up a context initialized with `COVER_ctx_init()`.
  469. */
  470. static void COVER_ctx_destroy(COVER_ctx_t *ctx) {
  471. if (!ctx) {
  472. return;
  473. }
  474. if (ctx->suffix) {
  475. free(ctx->suffix);
  476. ctx->suffix = NULL;
  477. }
  478. if (ctx->freqs) {
  479. free(ctx->freqs);
  480. ctx->freqs = NULL;
  481. }
  482. if (ctx->dmerAt) {
  483. free(ctx->dmerAt);
  484. ctx->dmerAt = NULL;
  485. }
  486. if (ctx->offsets) {
  487. free(ctx->offsets);
  488. ctx->offsets = NULL;
  489. }
  490. }
  491. /**
  492. * Prepare a context for dictionary building.
  493. * The context is only dependent on the parameter `d` and can used multiple
  494. * times.
  495. * Returns 0 on success or error code on error.
  496. * The context must be destroyed with `COVER_ctx_destroy()`.
  497. */
  498. static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer,
  499. const size_t *samplesSizes, unsigned nbSamples,
  500. unsigned d, double splitPoint) {
  501. const BYTE *const samples = (const BYTE *)samplesBuffer;
  502. const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
  503. /* Split samples into testing and training sets */
  504. const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
  505. const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
  506. const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
  507. const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
  508. /* Checks */
  509. if (totalSamplesSize < MAX(d, sizeof(U64)) ||
  510. totalSamplesSize >= (size_t)COVER_MAX_SAMPLES_SIZE) {
  511. DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
  512. (unsigned)(totalSamplesSize>>20), (COVER_MAX_SAMPLES_SIZE >> 20));
  513. return ERROR(srcSize_wrong);
  514. }
  515. /* Check if there are at least 5 training samples */
  516. if (nbTrainSamples < 5) {
  517. DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid.", nbTrainSamples);
  518. return ERROR(srcSize_wrong);
  519. }
  520. /* Check if there's testing sample */
  521. if (nbTestSamples < 1) {
  522. DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.", nbTestSamples);
  523. return ERROR(srcSize_wrong);
  524. }
  525. /* Zero the context */
  526. memset(ctx, 0, sizeof(*ctx));
  527. DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
  528. (unsigned)trainingSamplesSize);
  529. DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
  530. (unsigned)testSamplesSize);
  531. ctx->samples = samples;
  532. ctx->samplesSizes = samplesSizes;
  533. ctx->nbSamples = nbSamples;
  534. ctx->nbTrainSamples = nbTrainSamples;
  535. ctx->nbTestSamples = nbTestSamples;
  536. /* Partial suffix array */
  537. ctx->suffixSize = trainingSamplesSize - MAX(d, sizeof(U64)) + 1;
  538. ctx->suffix = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
  539. /* Maps index to the dmerID */
  540. ctx->dmerAt = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
  541. /* The offsets of each file */
  542. ctx->offsets = (size_t *)malloc((nbSamples + 1) * sizeof(size_t));
  543. if (!ctx->suffix || !ctx->dmerAt || !ctx->offsets) {
  544. DISPLAYLEVEL(1, "Failed to allocate scratch buffers\n");
  545. COVER_ctx_destroy(ctx);
  546. return ERROR(memory_allocation);
  547. }
  548. ctx->freqs = NULL;
  549. ctx->d = d;
  550. /* Fill offsets from the samplesSizes */
  551. {
  552. U32 i;
  553. ctx->offsets[0] = 0;
  554. for (i = 1; i <= nbSamples; ++i) {
  555. ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
  556. }
  557. }
  558. DISPLAYLEVEL(2, "Constructing partial suffix array\n");
  559. {
  560. /* suffix is a partial suffix array.
  561. * It only sorts suffixes by their first parameters.d bytes.
  562. * The sort is stable, so each dmer group is sorted by position in input.
  563. */
  564. U32 i;
  565. for (i = 0; i < ctx->suffixSize; ++i) {
  566. ctx->suffix[i] = i;
  567. }
  568. /* qsort doesn't take an opaque pointer, so pass as a global.
  569. * On OpenBSD qsort() is not guaranteed to be stable, their mergesort() is.
  570. */
  571. g_ctx = ctx;
  572. #if defined(__OpenBSD__)
  573. mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32),
  574. (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
  575. #else
  576. qsort(ctx->suffix, ctx->suffixSize, sizeof(U32),
  577. (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
  578. #endif
  579. }
  580. DISPLAYLEVEL(2, "Computing frequencies\n");
  581. /* For each dmer group (group of positions with the same first d bytes):
  582. * 1. For each position we set dmerAt[position] = dmerID. The dmerID is
  583. * (groupBeginPtr - suffix). This allows us to go from position to
  584. * dmerID so we can look up values in freq.
  585. * 2. We calculate how many samples the dmer occurs in and save it in
  586. * freqs[dmerId].
  587. */
  588. COVER_groupBy(ctx->suffix, ctx->suffixSize, sizeof(U32), ctx,
  589. (ctx->d <= 8 ? &COVER_cmp8 : &COVER_cmp), &COVER_group);
  590. ctx->freqs = ctx->suffix;
  591. ctx->suffix = NULL;
  592. return 0;
  593. }
  594. void COVER_warnOnSmallCorpus(size_t maxDictSize, size_t nbDmers, int displayLevel)
  595. {
  596. const double ratio = (double)nbDmers / maxDictSize;
  597. if (ratio >= 10) {
  598. return;
  599. }
  600. LOCALDISPLAYLEVEL(displayLevel, 1,
  601. "WARNING: The maximum dictionary size %u is too large "
  602. "compared to the source size %u! "
  603. "size(source)/size(dictionary) = %f, but it should be >= "
  604. "10! This may lead to a subpar dictionary! We recommend "
  605. "training on sources at least 10x, and preferably 100x "
  606. "the size of the dictionary! \n", (U32)maxDictSize,
  607. (U32)nbDmers, ratio);
  608. }
  609. COVER_epoch_info_t COVER_computeEpochs(U32 maxDictSize,
  610. U32 nbDmers, U32 k, U32 passes)
  611. {
  612. const U32 minEpochSize = k * 10;
  613. COVER_epoch_info_t epochs;
  614. epochs.num = MAX(1, maxDictSize / k / passes);
  615. epochs.size = nbDmers / epochs.num;
  616. if (epochs.size >= minEpochSize) {
  617. assert(epochs.size * epochs.num <= nbDmers);
  618. return epochs;
  619. }
  620. epochs.size = MIN(minEpochSize, nbDmers);
  621. epochs.num = nbDmers / epochs.size;
  622. assert(epochs.size * epochs.num <= nbDmers);
  623. return epochs;
  624. }
  625. /**
  626. * Given the prepared context build the dictionary.
  627. */
  628. static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs,
  629. COVER_map_t *activeDmers, void *dictBuffer,
  630. size_t dictBufferCapacity,
  631. ZDICT_cover_params_t parameters) {
  632. BYTE *const dict = (BYTE *)dictBuffer;
  633. size_t tail = dictBufferCapacity;
  634. /* Divide the data into epochs. We will select one segment from each epoch. */
  635. const COVER_epoch_info_t epochs = COVER_computeEpochs(
  636. (U32)dictBufferCapacity, (U32)ctx->suffixSize, parameters.k, 4);
  637. const size_t maxZeroScoreRun = MAX(10, MIN(100, epochs.num >> 3));
  638. size_t zeroScoreRun = 0;
  639. size_t epoch;
  640. DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
  641. (U32)epochs.num, (U32)epochs.size);
  642. /* Loop through the epochs until there are no more segments or the dictionary
  643. * is full.
  644. */
  645. for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs.num) {
  646. const U32 epochBegin = (U32)(epoch * epochs.size);
  647. const U32 epochEnd = epochBegin + epochs.size;
  648. size_t segmentSize;
  649. /* Select a segment */
  650. COVER_segment_t segment = COVER_selectSegment(
  651. ctx, freqs, activeDmers, epochBegin, epochEnd, parameters);
  652. /* If the segment covers no dmers, then we are out of content.
  653. * There may be new content in other epochs, for continue for some time.
  654. */
  655. if (segment.score == 0) {
  656. if (++zeroScoreRun >= maxZeroScoreRun) {
  657. break;
  658. }
  659. continue;
  660. }
  661. zeroScoreRun = 0;
  662. /* Trim the segment if necessary and if it is too small then we are done */
  663. segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
  664. if (segmentSize < parameters.d) {
  665. break;
  666. }
  667. /* We fill the dictionary from the back to allow the best segments to be
  668. * referenced with the smallest offsets.
  669. */
  670. tail -= segmentSize;
  671. memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);
  672. DISPLAYUPDATE(
  673. 2, "\r%u%% ",
  674. (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity));
  675. }
  676. DISPLAYLEVEL(2, "\r%79s\r", "");
  677. return tail;
  678. }
  679. ZDICTLIB_API size_t ZDICT_trainFromBuffer_cover(
  680. void *dictBuffer, size_t dictBufferCapacity,
  681. const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
  682. ZDICT_cover_params_t parameters)
  683. {
  684. BYTE* const dict = (BYTE*)dictBuffer;
  685. COVER_ctx_t ctx;
  686. COVER_map_t activeDmers;
  687. parameters.splitPoint = 1.0;
  688. /* Initialize global data */
  689. g_displayLevel = parameters.zParams.notificationLevel;
  690. /* Checks */
  691. if (!COVER_checkParameters(parameters, dictBufferCapacity)) {
  692. DISPLAYLEVEL(1, "Cover parameters incorrect\n");
  693. return ERROR(parameter_outOfBound);
  694. }
  695. if (nbSamples == 0) {
  696. DISPLAYLEVEL(1, "Cover must have at least one input file\n");
  697. return ERROR(srcSize_wrong);
  698. }
  699. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  700. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  701. ZDICT_DICTSIZE_MIN);
  702. return ERROR(dstSize_tooSmall);
  703. }
  704. /* Initialize context and activeDmers */
  705. {
  706. size_t const initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
  707. parameters.d, parameters.splitPoint);
  708. if (ZSTD_isError(initVal)) {
  709. return initVal;
  710. }
  711. }
  712. COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, g_displayLevel);
  713. if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
  714. DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
  715. COVER_ctx_destroy(&ctx);
  716. return ERROR(memory_allocation);
  717. }
  718. DISPLAYLEVEL(2, "Building dictionary\n");
  719. {
  720. const size_t tail =
  721. COVER_buildDictionary(&ctx, ctx.freqs, &activeDmers, dictBuffer,
  722. dictBufferCapacity, parameters);
  723. const size_t dictionarySize = ZDICT_finalizeDictionary(
  724. dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
  725. samplesBuffer, samplesSizes, nbSamples, parameters.zParams);
  726. if (!ZSTD_isError(dictionarySize)) {
  727. DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
  728. (unsigned)dictionarySize);
  729. }
  730. COVER_ctx_destroy(&ctx);
  731. COVER_map_destroy(&activeDmers);
  732. return dictionarySize;
  733. }
  734. }
  735. size_t COVER_checkTotalCompressedSize(const ZDICT_cover_params_t parameters,
  736. const size_t *samplesSizes, const BYTE *samples,
  737. size_t *offsets,
  738. size_t nbTrainSamples, size_t nbSamples,
  739. BYTE *const dict, size_t dictBufferCapacity) {
  740. size_t totalCompressedSize = ERROR(GENERIC);
  741. /* Pointers */
  742. ZSTD_CCtx *cctx;
  743. ZSTD_CDict *cdict;
  744. void *dst;
  745. /* Local variables */
  746. size_t dstCapacity;
  747. size_t i;
  748. /* Allocate dst with enough space to compress the maximum sized sample */
  749. {
  750. size_t maxSampleSize = 0;
  751. i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
  752. for (; i < nbSamples; ++i) {
  753. maxSampleSize = MAX(samplesSizes[i], maxSampleSize);
  754. }
  755. dstCapacity = ZSTD_compressBound(maxSampleSize);
  756. dst = malloc(dstCapacity);
  757. }
  758. /* Create the cctx and cdict */
  759. cctx = ZSTD_createCCtx();
  760. cdict = ZSTD_createCDict(dict, dictBufferCapacity,
  761. parameters.zParams.compressionLevel);
  762. if (!dst || !cctx || !cdict) {
  763. goto _compressCleanup;
  764. }
  765. /* Compress each sample and sum their sizes (or error) */
  766. totalCompressedSize = dictBufferCapacity;
  767. i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
  768. for (; i < nbSamples; ++i) {
  769. const size_t size = ZSTD_compress_usingCDict(
  770. cctx, dst, dstCapacity, samples + offsets[i],
  771. samplesSizes[i], cdict);
  772. if (ZSTD_isError(size)) {
  773. totalCompressedSize = size;
  774. goto _compressCleanup;
  775. }
  776. totalCompressedSize += size;
  777. }
  778. _compressCleanup:
  779. ZSTD_freeCCtx(cctx);
  780. ZSTD_freeCDict(cdict);
  781. if (dst) {
  782. free(dst);
  783. }
  784. return totalCompressedSize;
  785. }
  786. /**
  787. * Initialize the `COVER_best_t`.
  788. */
  789. void COVER_best_init(COVER_best_t *best) {
  790. if (best==NULL) return; /* compatible with init on NULL */
  791. (void)ZSTD_pthread_mutex_init(&best->mutex, NULL);
  792. (void)ZSTD_pthread_cond_init(&best->cond, NULL);
  793. best->liveJobs = 0;
  794. best->dict = NULL;
  795. best->dictSize = 0;
  796. best->compressedSize = (size_t)-1;
  797. memset(&best->parameters, 0, sizeof(best->parameters));
  798. }
  799. /**
  800. * Wait until liveJobs == 0.
  801. */
  802. void COVER_best_wait(COVER_best_t *best) {
  803. if (!best) {
  804. return;
  805. }
  806. ZSTD_pthread_mutex_lock(&best->mutex);
  807. while (best->liveJobs != 0) {
  808. ZSTD_pthread_cond_wait(&best->cond, &best->mutex);
  809. }
  810. ZSTD_pthread_mutex_unlock(&best->mutex);
  811. }
  812. /**
  813. * Call COVER_best_wait() and then destroy the COVER_best_t.
  814. */
  815. void COVER_best_destroy(COVER_best_t *best) {
  816. if (!best) {
  817. return;
  818. }
  819. COVER_best_wait(best);
  820. if (best->dict) {
  821. free(best->dict);
  822. }
  823. ZSTD_pthread_mutex_destroy(&best->mutex);
  824. ZSTD_pthread_cond_destroy(&best->cond);
  825. }
  826. /**
  827. * Called when a thread is about to be launched.
  828. * Increments liveJobs.
  829. */
  830. void COVER_best_start(COVER_best_t *best) {
  831. if (!best) {
  832. return;
  833. }
  834. ZSTD_pthread_mutex_lock(&best->mutex);
  835. ++best->liveJobs;
  836. ZSTD_pthread_mutex_unlock(&best->mutex);
  837. }
  838. /**
  839. * Called when a thread finishes executing, both on error or success.
  840. * Decrements liveJobs and signals any waiting threads if liveJobs == 0.
  841. * If this dictionary is the best so far save it and its parameters.
  842. */
  843. void COVER_best_finish(COVER_best_t *best, ZDICT_cover_params_t parameters,
  844. COVER_dictSelection_t selection) {
  845. void* dict = selection.dictContent;
  846. size_t compressedSize = selection.totalCompressedSize;
  847. size_t dictSize = selection.dictSize;
  848. if (!best) {
  849. return;
  850. }
  851. {
  852. size_t liveJobs;
  853. ZSTD_pthread_mutex_lock(&best->mutex);
  854. --best->liveJobs;
  855. liveJobs = best->liveJobs;
  856. /* If the new dictionary is better */
  857. if (compressedSize < best->compressedSize) {
  858. /* Allocate space if necessary */
  859. if (!best->dict || best->dictSize < dictSize) {
  860. if (best->dict) {
  861. free(best->dict);
  862. }
  863. best->dict = malloc(dictSize);
  864. if (!best->dict) {
  865. best->compressedSize = ERROR(GENERIC);
  866. best->dictSize = 0;
  867. ZSTD_pthread_cond_signal(&best->cond);
  868. ZSTD_pthread_mutex_unlock(&best->mutex);
  869. return;
  870. }
  871. }
  872. /* Save the dictionary, parameters, and size */
  873. if (dict) {
  874. memcpy(best->dict, dict, dictSize);
  875. best->dictSize = dictSize;
  876. best->parameters = parameters;
  877. best->compressedSize = compressedSize;
  878. }
  879. }
  880. if (liveJobs == 0) {
  881. ZSTD_pthread_cond_broadcast(&best->cond);
  882. }
  883. ZSTD_pthread_mutex_unlock(&best->mutex);
  884. }
  885. }
  886. COVER_dictSelection_t COVER_dictSelectionError(size_t error) {
  887. COVER_dictSelection_t selection = { NULL, 0, error };
  888. return selection;
  889. }
  890. unsigned COVER_dictSelectionIsError(COVER_dictSelection_t selection) {
  891. return (ZSTD_isError(selection.totalCompressedSize) || !selection.dictContent);
  892. }
  893. void COVER_dictSelectionFree(COVER_dictSelection_t selection){
  894. free(selection.dictContent);
  895. }
  896. COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent,
  897. size_t dictContentSize, const BYTE* samplesBuffer, const size_t* samplesSizes, unsigned nbFinalizeSamples,
  898. size_t nbCheckSamples, size_t nbSamples, ZDICT_cover_params_t params, size_t* offsets, size_t totalCompressedSize) {
  899. size_t largestDict = 0;
  900. size_t largestCompressed = 0;
  901. BYTE* customDictContentEnd = customDictContent + dictContentSize;
  902. BYTE * largestDictbuffer = (BYTE *)malloc(dictContentSize);
  903. BYTE * candidateDictBuffer = (BYTE *)malloc(dictContentSize);
  904. double regressionTolerance = ((double)params.shrinkDictMaxRegression / 100.0) + 1.00;
  905. if (!largestDictbuffer || !candidateDictBuffer) {
  906. free(largestDictbuffer);
  907. free(candidateDictBuffer);
  908. return COVER_dictSelectionError(dictContentSize);
  909. }
  910. /* Initial dictionary size and compressed size */
  911. memcpy(largestDictbuffer, customDictContent, dictContentSize);
  912. dictContentSize = ZDICT_finalizeDictionary(
  913. largestDictbuffer, dictContentSize, customDictContent, dictContentSize,
  914. samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
  915. if (ZDICT_isError(dictContentSize)) {
  916. free(largestDictbuffer);
  917. free(candidateDictBuffer);
  918. return COVER_dictSelectionError(dictContentSize);
  919. }
  920. totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
  921. samplesBuffer, offsets,
  922. nbCheckSamples, nbSamples,
  923. largestDictbuffer, dictContentSize);
  924. if (ZSTD_isError(totalCompressedSize)) {
  925. free(largestDictbuffer);
  926. free(candidateDictBuffer);
  927. return COVER_dictSelectionError(totalCompressedSize);
  928. }
  929. if (params.shrinkDict == 0) {
  930. COVER_dictSelection_t selection = { largestDictbuffer, dictContentSize, totalCompressedSize };
  931. free(candidateDictBuffer);
  932. return selection;
  933. }
  934. largestDict = dictContentSize;
  935. largestCompressed = totalCompressedSize;
  936. dictContentSize = ZDICT_DICTSIZE_MIN;
  937. /* Largest dict is initially at least ZDICT_DICTSIZE_MIN */
  938. while (dictContentSize < largestDict) {
  939. memcpy(candidateDictBuffer, largestDictbuffer, largestDict);
  940. dictContentSize = ZDICT_finalizeDictionary(
  941. candidateDictBuffer, dictContentSize, customDictContentEnd - dictContentSize, dictContentSize,
  942. samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams);
  943. if (ZDICT_isError(dictContentSize)) {
  944. free(largestDictbuffer);
  945. free(candidateDictBuffer);
  946. return COVER_dictSelectionError(dictContentSize);
  947. }
  948. totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes,
  949. samplesBuffer, offsets,
  950. nbCheckSamples, nbSamples,
  951. candidateDictBuffer, dictContentSize);
  952. if (ZSTD_isError(totalCompressedSize)) {
  953. free(largestDictbuffer);
  954. free(candidateDictBuffer);
  955. return COVER_dictSelectionError(totalCompressedSize);
  956. }
  957. if (totalCompressedSize <= largestCompressed * regressionTolerance) {
  958. COVER_dictSelection_t selection = { candidateDictBuffer, dictContentSize, totalCompressedSize };
  959. free(largestDictbuffer);
  960. return selection;
  961. }
  962. dictContentSize *= 2;
  963. }
  964. dictContentSize = largestDict;
  965. totalCompressedSize = largestCompressed;
  966. {
  967. COVER_dictSelection_t selection = { largestDictbuffer, dictContentSize, totalCompressedSize };
  968. free(candidateDictBuffer);
  969. return selection;
  970. }
  971. }
  972. /**
  973. * Parameters for COVER_tryParameters().
  974. */
  975. typedef struct COVER_tryParameters_data_s {
  976. const COVER_ctx_t *ctx;
  977. COVER_best_t *best;
  978. size_t dictBufferCapacity;
  979. ZDICT_cover_params_t parameters;
  980. } COVER_tryParameters_data_t;
  981. /**
  982. * Tries a set of parameters and updates the COVER_best_t with the results.
  983. * This function is thread safe if zstd is compiled with multithreaded support.
  984. * It takes its parameters as an *OWNING* opaque pointer to support threading.
  985. */
  986. static void COVER_tryParameters(void *opaque) {
  987. /* Save parameters as local variables */
  988. COVER_tryParameters_data_t *const data = (COVER_tryParameters_data_t *)opaque;
  989. const COVER_ctx_t *const ctx = data->ctx;
  990. const ZDICT_cover_params_t parameters = data->parameters;
  991. size_t dictBufferCapacity = data->dictBufferCapacity;
  992. size_t totalCompressedSize = ERROR(GENERIC);
  993. /* Allocate space for hash table, dict, and freqs */
  994. COVER_map_t activeDmers;
  995. BYTE *const dict = (BYTE * const)malloc(dictBufferCapacity);
  996. COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC));
  997. U32 *freqs = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
  998. if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
  999. DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
  1000. goto _cleanup;
  1001. }
  1002. if (!dict || !freqs) {
  1003. DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
  1004. goto _cleanup;
  1005. }
  1006. /* Copy the frequencies because we need to modify them */
  1007. memcpy(freqs, ctx->freqs, ctx->suffixSize * sizeof(U32));
  1008. /* Build the dictionary */
  1009. {
  1010. const size_t tail = COVER_buildDictionary(ctx, freqs, &activeDmers, dict,
  1011. dictBufferCapacity, parameters);
  1012. selection = COVER_selectDict(dict + tail, dictBufferCapacity - tail,
  1013. ctx->samples, ctx->samplesSizes, (unsigned)ctx->nbTrainSamples, ctx->nbTrainSamples, ctx->nbSamples, parameters, ctx->offsets,
  1014. totalCompressedSize);
  1015. if (COVER_dictSelectionIsError(selection)) {
  1016. DISPLAYLEVEL(1, "Failed to select dictionary\n");
  1017. goto _cleanup;
  1018. }
  1019. }
  1020. _cleanup:
  1021. free(dict);
  1022. COVER_best_finish(data->best, parameters, selection);
  1023. free(data);
  1024. COVER_map_destroy(&activeDmers);
  1025. COVER_dictSelectionFree(selection);
  1026. if (freqs) {
  1027. free(freqs);
  1028. }
  1029. }
  1030. ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_cover(
  1031. void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer,
  1032. const size_t *samplesSizes, unsigned nbSamples,
  1033. ZDICT_cover_params_t *parameters) {
  1034. /* constants */
  1035. const unsigned nbThreads = parameters->nbThreads;
  1036. const double splitPoint =
  1037. parameters->splitPoint <= 0.0 ? DEFAULT_SPLITPOINT : parameters->splitPoint;
  1038. const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
  1039. const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
  1040. const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
  1041. const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
  1042. const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
  1043. const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
  1044. const unsigned kIterations =
  1045. (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
  1046. const unsigned shrinkDict = 0;
  1047. /* Local variables */
  1048. const int displayLevel = parameters->zParams.notificationLevel;
  1049. unsigned iteration = 1;
  1050. unsigned d;
  1051. unsigned k;
  1052. COVER_best_t best;
  1053. POOL_ctx *pool = NULL;
  1054. int warned = 0;
  1055. /* Checks */
  1056. if (splitPoint <= 0 || splitPoint > 1) {
  1057. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
  1058. return ERROR(parameter_outOfBound);
  1059. }
  1060. if (kMinK < kMaxD || kMaxK < kMinK) {
  1061. LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
  1062. return ERROR(parameter_outOfBound);
  1063. }
  1064. if (nbSamples == 0) {
  1065. DISPLAYLEVEL(1, "Cover must have at least one input file\n");
  1066. return ERROR(srcSize_wrong);
  1067. }
  1068. if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
  1069. DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
  1070. ZDICT_DICTSIZE_MIN);
  1071. return ERROR(dstSize_tooSmall);
  1072. }
  1073. if (nbThreads > 1) {
  1074. pool = POOL_create(nbThreads, 1);
  1075. if (!pool) {
  1076. return ERROR(memory_allocation);
  1077. }
  1078. }
  1079. /* Initialization */
  1080. COVER_best_init(&best);
  1081. /* Turn down global display level to clean up display at level 2 and below */
  1082. g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
  1083. /* Loop through d first because each new value needs a new context */
  1084. LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
  1085. kIterations);
  1086. for (d = kMinD; d <= kMaxD; d += 2) {
  1087. /* Initialize the context for this value of d */
  1088. COVER_ctx_t ctx;
  1089. LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
  1090. {
  1091. const size_t initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint);
  1092. if (ZSTD_isError(initVal)) {
  1093. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
  1094. COVER_best_destroy(&best);
  1095. POOL_free(pool);
  1096. return initVal;
  1097. }
  1098. }
  1099. if (!warned) {
  1100. COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, displayLevel);
  1101. warned = 1;
  1102. }
  1103. /* Loop through k reusing the same context */
  1104. for (k = kMinK; k <= kMaxK; k += kStepSize) {
  1105. /* Prepare the arguments */
  1106. COVER_tryParameters_data_t *data = (COVER_tryParameters_data_t *)malloc(
  1107. sizeof(COVER_tryParameters_data_t));
  1108. LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
  1109. if (!data) {
  1110. LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
  1111. COVER_best_destroy(&best);
  1112. COVER_ctx_destroy(&ctx);
  1113. POOL_free(pool);
  1114. return ERROR(memory_allocation);
  1115. }
  1116. data->ctx = &ctx;
  1117. data->best = &best;
  1118. data->dictBufferCapacity = dictBufferCapacity;
  1119. data->parameters = *parameters;
  1120. data->parameters.k = k;
  1121. data->parameters.d = d;
  1122. data->parameters.splitPoint = splitPoint;
  1123. data->parameters.steps = kSteps;
  1124. data->parameters.shrinkDict = shrinkDict;
  1125. data->parameters.zParams.notificationLevel = g_displayLevel;
  1126. /* Check the parameters */
  1127. if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) {
  1128. DISPLAYLEVEL(1, "Cover parameters incorrect\n");
  1129. free(data);
  1130. continue;
  1131. }
  1132. /* Call the function and pass ownership of data to it */
  1133. COVER_best_start(&best);
  1134. if (pool) {
  1135. POOL_add(pool, &COVER_tryParameters, data);
  1136. } else {
  1137. COVER_tryParameters(data);
  1138. }
  1139. /* Print status */
  1140. LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
  1141. (unsigned)((iteration * 100) / kIterations));
  1142. ++iteration;
  1143. }
  1144. COVER_best_wait(&best);
  1145. COVER_ctx_destroy(&ctx);
  1146. }
  1147. LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
  1148. /* Fill the output buffer and parameters with output of the best parameters */
  1149. {
  1150. const size_t dictSize = best.dictSize;
  1151. if (ZSTD_isError(best.compressedSize)) {
  1152. const size_t compressedSize = best.compressedSize;
  1153. COVER_best_destroy(&best);
  1154. POOL_free(pool);
  1155. return compressedSize;
  1156. }
  1157. *parameters = best.parameters;
  1158. memcpy(dictBuffer, best.dict, dictSize);
  1159. COVER_best_destroy(&best);
  1160. POOL_free(pool);
  1161. return dictSize;
  1162. }
  1163. }