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