xref: /aosp_15_r20/external/zstd/programs/dibio.c (revision 01826a4963a0d8a59bc3812d29bdf0fb76416722)
1*01826a49SYabin Cui /*
2*01826a49SYabin Cui  * Copyright (c) Meta Platforms, Inc. and affiliates.
3*01826a49SYabin Cui  * All rights reserved.
4*01826a49SYabin Cui  *
5*01826a49SYabin Cui  * This source code is licensed under both the BSD-style license (found in the
6*01826a49SYabin Cui  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7*01826a49SYabin Cui  * in the COPYING file in the root directory of this source tree).
8*01826a49SYabin Cui  * You may select, at your option, one of the above-listed licenses.
9*01826a49SYabin Cui  */
10*01826a49SYabin Cui 
11*01826a49SYabin Cui 
12*01826a49SYabin Cui 
13*01826a49SYabin Cui /* **************************************
14*01826a49SYabin Cui *  Compiler Warnings
15*01826a49SYabin Cui ****************************************/
16*01826a49SYabin Cui #ifdef _MSC_VER
17*01826a49SYabin Cui #  pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
18*01826a49SYabin Cui #endif
19*01826a49SYabin Cui 
20*01826a49SYabin Cui 
21*01826a49SYabin Cui /*-*************************************
22*01826a49SYabin Cui *  Includes
23*01826a49SYabin Cui ***************************************/
24*01826a49SYabin Cui #include "platform.h"       /* Large Files support */
25*01826a49SYabin Cui #include "util.h"           /* UTIL_getFileSize, UTIL_getTotalFileSize */
26*01826a49SYabin Cui #include <stdlib.h>         /* malloc, free */
27*01826a49SYabin Cui #include <string.h>         /* memset */
28*01826a49SYabin Cui #include <stdio.h>          /* fprintf, fopen, ftello64 */
29*01826a49SYabin Cui #include <errno.h>          /* errno */
30*01826a49SYabin Cui 
31*01826a49SYabin Cui #include "timefn.h"         /* UTIL_time_t, UTIL_clockSpanMicro, UTIL_getTime */
32*01826a49SYabin Cui #include "../lib/common/debug.h" /* assert */
33*01826a49SYabin Cui #include "../lib/common/mem.h"  /* read */
34*01826a49SYabin Cui #include "../lib/zstd_errors.h"
35*01826a49SYabin Cui #include "dibio.h"
36*01826a49SYabin Cui 
37*01826a49SYabin Cui 
38*01826a49SYabin Cui /*-*************************************
39*01826a49SYabin Cui *  Constants
40*01826a49SYabin Cui ***************************************/
41*01826a49SYabin Cui #define KB *(1 <<10)
42*01826a49SYabin Cui #define MB *(1 <<20)
43*01826a49SYabin Cui #define GB *(1U<<30)
44*01826a49SYabin Cui 
45*01826a49SYabin Cui #define SAMPLESIZE_MAX (128 KB)
46*01826a49SYabin Cui #define MEMMULT 11    /* rough estimation : memory cost to analyze 1 byte of sample */
47*01826a49SYabin Cui #define COVER_MEMMULT 9    /* rough estimation : memory cost to analyze 1 byte of sample */
48*01826a49SYabin Cui #define FASTCOVER_MEMMULT 1    /* rough estimation : memory cost to analyze 1 byte of sample */
49*01826a49SYabin Cui static const size_t g_maxMemory = (sizeof(size_t) == 4) ? (2 GB - 64 MB) : ((size_t)(512 MB) << sizeof(size_t));
50*01826a49SYabin Cui 
51*01826a49SYabin Cui #define NOISELENGTH 32
52*01826a49SYabin Cui #define MAX_SAMPLES_SIZE (2 GB) /* training dataset limited to 2GB */
53*01826a49SYabin Cui 
54*01826a49SYabin Cui 
55*01826a49SYabin Cui /*-*************************************
56*01826a49SYabin Cui *  Console display
57*01826a49SYabin Cui ***************************************/
58*01826a49SYabin Cui #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
59*01826a49SYabin Cui #define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
60*01826a49SYabin Cui 
61*01826a49SYabin Cui static const U64 g_refreshRate = SEC_TO_MICRO / 6;
62*01826a49SYabin Cui static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
63*01826a49SYabin Cui 
64*01826a49SYabin Cui #define DISPLAYUPDATE(l, ...) { if (displayLevel>=l) { \
65*01826a49SYabin Cui             if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (displayLevel>=4)) \
66*01826a49SYabin Cui             { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \
67*01826a49SYabin Cui             if (displayLevel>=4) fflush(stderr); } } }
68*01826a49SYabin Cui 
69*01826a49SYabin Cui /*-*************************************
70*01826a49SYabin Cui *  Exceptions
71*01826a49SYabin Cui ***************************************/
72*01826a49SYabin Cui #ifndef DEBUG
73*01826a49SYabin Cui #  define DEBUG 0
74*01826a49SYabin Cui #endif
75*01826a49SYabin Cui #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
76*01826a49SYabin Cui #define EXM_THROW(error, ...)                                             \
77*01826a49SYabin Cui {                                                                         \
78*01826a49SYabin Cui     DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
79*01826a49SYabin Cui     DISPLAY("Error %i : ", error);                                        \
80*01826a49SYabin Cui     DISPLAY(__VA_ARGS__);                                                 \
81*01826a49SYabin Cui     DISPLAY("\n");                                                        \
82*01826a49SYabin Cui     exit(error);                                                          \
83*01826a49SYabin Cui }
84*01826a49SYabin Cui 
85*01826a49SYabin Cui 
86*01826a49SYabin Cui /* ********************************************************
87*01826a49SYabin Cui *  Helper functions
88*01826a49SYabin Cui **********************************************************/
89*01826a49SYabin Cui #undef MIN
90*01826a49SYabin Cui #define MIN(a,b)    ((a) < (b) ? (a) : (b))
91*01826a49SYabin Cui 
92*01826a49SYabin Cui /**
93*01826a49SYabin Cui   Returns the size of a file.
94*01826a49SYabin Cui   If error returns -1.
95*01826a49SYabin Cui */
DiB_getFileSize(const char * fileName)96*01826a49SYabin Cui static S64 DiB_getFileSize (const char * fileName)
97*01826a49SYabin Cui {
98*01826a49SYabin Cui     U64 const fileSize = UTIL_getFileSize(fileName);
99*01826a49SYabin Cui     return (fileSize == UTIL_FILESIZE_UNKNOWN) ? -1 : (S64)fileSize;
100*01826a49SYabin Cui }
101*01826a49SYabin Cui 
102*01826a49SYabin Cui /* ********************************************************
103*01826a49SYabin Cui *  File related operations
104*01826a49SYabin Cui **********************************************************/
105*01826a49SYabin Cui /** DiB_loadFiles() :
106*01826a49SYabin Cui  *  load samples from files listed in fileNamesTable into buffer.
107*01826a49SYabin Cui  *  works even if buffer is too small to load all samples.
108*01826a49SYabin Cui  *  Also provides the size of each sample into sampleSizes table
109*01826a49SYabin Cui  *  which must be sized correctly, using DiB_fileStats().
110*01826a49SYabin Cui  * @return : nb of samples effectively loaded into `buffer`
111*01826a49SYabin Cui  * *bufferSizePtr is modified, it provides the amount data loaded within buffer.
112*01826a49SYabin Cui  *  sampleSizes is filled with the size of each sample.
113*01826a49SYabin Cui  */
DiB_loadFiles(void * buffer,size_t * bufferSizePtr,size_t * sampleSizes,int sstSize,const char ** fileNamesTable,int nbFiles,size_t targetChunkSize,int displayLevel)114*01826a49SYabin Cui static int DiB_loadFiles(
115*01826a49SYabin Cui     void* buffer, size_t* bufferSizePtr,
116*01826a49SYabin Cui     size_t* sampleSizes, int sstSize,
117*01826a49SYabin Cui     const char** fileNamesTable, int nbFiles,
118*01826a49SYabin Cui     size_t targetChunkSize, int displayLevel )
119*01826a49SYabin Cui {
120*01826a49SYabin Cui     char* const buff = (char*)buffer;
121*01826a49SYabin Cui     size_t totalDataLoaded = 0;
122*01826a49SYabin Cui     int nbSamplesLoaded = 0;
123*01826a49SYabin Cui     int fileIndex = 0;
124*01826a49SYabin Cui     FILE * f = NULL;
125*01826a49SYabin Cui 
126*01826a49SYabin Cui     assert(targetChunkSize <= SAMPLESIZE_MAX);
127*01826a49SYabin Cui 
128*01826a49SYabin Cui     while ( nbSamplesLoaded < sstSize && fileIndex < nbFiles ) {
129*01826a49SYabin Cui         size_t fileDataLoaded;
130*01826a49SYabin Cui         S64 const fileSize = DiB_getFileSize(fileNamesTable[fileIndex]);
131*01826a49SYabin Cui         if (fileSize <= 0) {
132*01826a49SYabin Cui             /* skip if zero-size or file error */
133*01826a49SYabin Cui             ++fileIndex;
134*01826a49SYabin Cui             continue;
135*01826a49SYabin Cui         }
136*01826a49SYabin Cui 
137*01826a49SYabin Cui         f = fopen( fileNamesTable[fileIndex], "rb");
138*01826a49SYabin Cui         if (f == NULL)
139*01826a49SYabin Cui             EXM_THROW(10, "zstd: dictBuilder: %s %s ", fileNamesTable[fileIndex], strerror(errno));
140*01826a49SYabin Cui         DISPLAYUPDATE(2, "Loading %s...       \r", fileNamesTable[fileIndex]);
141*01826a49SYabin Cui 
142*01826a49SYabin Cui         /* Load the first chunk of data from the file */
143*01826a49SYabin Cui         fileDataLoaded = targetChunkSize > 0 ?
144*01826a49SYabin Cui                             (size_t)MIN(fileSize, (S64)targetChunkSize) :
145*01826a49SYabin Cui                             (size_t)MIN(fileSize, SAMPLESIZE_MAX );
146*01826a49SYabin Cui         if (totalDataLoaded + fileDataLoaded > *bufferSizePtr)
147*01826a49SYabin Cui             break;
148*01826a49SYabin Cui         if (fread( buff+totalDataLoaded, 1, fileDataLoaded, f ) != fileDataLoaded)
149*01826a49SYabin Cui             EXM_THROW(11, "Pb reading %s", fileNamesTable[fileIndex]);
150*01826a49SYabin Cui         sampleSizes[nbSamplesLoaded++] = fileDataLoaded;
151*01826a49SYabin Cui         totalDataLoaded += fileDataLoaded;
152*01826a49SYabin Cui 
153*01826a49SYabin Cui         /* If file-chunking is enabled, load the rest of the file as more samples */
154*01826a49SYabin Cui         if (targetChunkSize > 0) {
155*01826a49SYabin Cui             while( (S64)fileDataLoaded < fileSize && nbSamplesLoaded < sstSize ) {
156*01826a49SYabin Cui                 size_t const chunkSize = MIN((size_t)(fileSize-fileDataLoaded), targetChunkSize);
157*01826a49SYabin Cui                 if (totalDataLoaded + chunkSize > *bufferSizePtr) /* buffer is full */
158*01826a49SYabin Cui                     break;
159*01826a49SYabin Cui 
160*01826a49SYabin Cui                 if (fread( buff+totalDataLoaded, 1, chunkSize, f ) != chunkSize)
161*01826a49SYabin Cui                     EXM_THROW(11, "Pb reading %s", fileNamesTable[fileIndex]);
162*01826a49SYabin Cui                 sampleSizes[nbSamplesLoaded++] = chunkSize;
163*01826a49SYabin Cui                 totalDataLoaded += chunkSize;
164*01826a49SYabin Cui                 fileDataLoaded += chunkSize;
165*01826a49SYabin Cui             }
166*01826a49SYabin Cui         }
167*01826a49SYabin Cui         fileIndex += 1;
168*01826a49SYabin Cui         fclose(f); f = NULL;
169*01826a49SYabin Cui     }
170*01826a49SYabin Cui     if (f != NULL)
171*01826a49SYabin Cui         fclose(f);
172*01826a49SYabin Cui 
173*01826a49SYabin Cui     DISPLAYLEVEL(2, "\r%79s\r", "");
174*01826a49SYabin Cui     DISPLAYLEVEL(4, "Loaded %d KB total training data, %d nb samples \n",
175*01826a49SYabin Cui         (int)(totalDataLoaded / (1 KB)), nbSamplesLoaded );
176*01826a49SYabin Cui     *bufferSizePtr = totalDataLoaded;
177*01826a49SYabin Cui     return nbSamplesLoaded;
178*01826a49SYabin Cui }
179*01826a49SYabin Cui 
180*01826a49SYabin Cui #define DiB_rotl32(x,r) ((x << r) | (x >> (32 - r)))
DiB_rand(U32 * src)181*01826a49SYabin Cui static U32 DiB_rand(U32* src)
182*01826a49SYabin Cui {
183*01826a49SYabin Cui     static const U32 prime1 = 2654435761U;
184*01826a49SYabin Cui     static const U32 prime2 = 2246822519U;
185*01826a49SYabin Cui     U32 rand32 = *src;
186*01826a49SYabin Cui     rand32 *= prime1;
187*01826a49SYabin Cui     rand32 ^= prime2;
188*01826a49SYabin Cui     rand32  = DiB_rotl32(rand32, 13);
189*01826a49SYabin Cui     *src = rand32;
190*01826a49SYabin Cui     return rand32 >> 5;
191*01826a49SYabin Cui }
192*01826a49SYabin Cui 
193*01826a49SYabin Cui /* DiB_shuffle() :
194*01826a49SYabin Cui  * shuffle a table of file names in a semi-random way
195*01826a49SYabin Cui  * It improves dictionary quality by reducing "locality" impact, so if sample set is very large,
196*01826a49SYabin Cui  * it will load random elements from it, instead of just the first ones. */
DiB_shuffle(const char ** fileNamesTable,unsigned nbFiles)197*01826a49SYabin Cui static void DiB_shuffle(const char** fileNamesTable, unsigned nbFiles) {
198*01826a49SYabin Cui     U32 seed = 0xFD2FB528;
199*01826a49SYabin Cui     unsigned i;
200*01826a49SYabin Cui     if (nbFiles == 0)
201*01826a49SYabin Cui         return;
202*01826a49SYabin Cui     for (i = nbFiles - 1; i > 0; --i) {
203*01826a49SYabin Cui         unsigned const j = DiB_rand(&seed) % (i + 1);
204*01826a49SYabin Cui         const char* const tmp = fileNamesTable[j];
205*01826a49SYabin Cui         fileNamesTable[j] = fileNamesTable[i];
206*01826a49SYabin Cui         fileNamesTable[i] = tmp;
207*01826a49SYabin Cui     }
208*01826a49SYabin Cui }
209*01826a49SYabin Cui 
210*01826a49SYabin Cui 
211*01826a49SYabin Cui /*-********************************************************
212*01826a49SYabin Cui *  Dictionary training functions
213*01826a49SYabin Cui **********************************************************/
DiB_findMaxMem(unsigned long long requiredMem)214*01826a49SYabin Cui static size_t DiB_findMaxMem(unsigned long long requiredMem)
215*01826a49SYabin Cui {
216*01826a49SYabin Cui     size_t const step = 8 MB;
217*01826a49SYabin Cui     void* testmem = NULL;
218*01826a49SYabin Cui 
219*01826a49SYabin Cui     requiredMem = (((requiredMem >> 23) + 1) << 23);
220*01826a49SYabin Cui     requiredMem += step;
221*01826a49SYabin Cui     if (requiredMem > g_maxMemory) requiredMem = g_maxMemory;
222*01826a49SYabin Cui 
223*01826a49SYabin Cui     while (!testmem) {
224*01826a49SYabin Cui         testmem = malloc((size_t)requiredMem);
225*01826a49SYabin Cui         requiredMem -= step;
226*01826a49SYabin Cui     }
227*01826a49SYabin Cui 
228*01826a49SYabin Cui     free(testmem);
229*01826a49SYabin Cui     return (size_t)requiredMem;
230*01826a49SYabin Cui }
231*01826a49SYabin Cui 
232*01826a49SYabin Cui 
DiB_fillNoise(void * buffer,size_t length)233*01826a49SYabin Cui static void DiB_fillNoise(void* buffer, size_t length)
234*01826a49SYabin Cui {
235*01826a49SYabin Cui     unsigned const prime1 = 2654435761U;
236*01826a49SYabin Cui     unsigned const prime2 = 2246822519U;
237*01826a49SYabin Cui     unsigned acc = prime1;
238*01826a49SYabin Cui     size_t p=0;
239*01826a49SYabin Cui 
240*01826a49SYabin Cui     for (p=0; p<length; p++) {
241*01826a49SYabin Cui         acc *= prime2;
242*01826a49SYabin Cui         ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
243*01826a49SYabin Cui     }
244*01826a49SYabin Cui }
245*01826a49SYabin Cui 
246*01826a49SYabin Cui 
DiB_saveDict(const char * dictFileName,const void * buff,size_t buffSize)247*01826a49SYabin Cui static void DiB_saveDict(const char* dictFileName,
248*01826a49SYabin Cui                          const void* buff, size_t buffSize)
249*01826a49SYabin Cui {
250*01826a49SYabin Cui     FILE* const f = fopen(dictFileName, "wb");
251*01826a49SYabin Cui     if (f==NULL) EXM_THROW(3, "cannot open %s ", dictFileName);
252*01826a49SYabin Cui 
253*01826a49SYabin Cui     { size_t const n = fwrite(buff, 1, buffSize, f);
254*01826a49SYabin Cui       if (n!=buffSize) EXM_THROW(4, "%s : write error", dictFileName) }
255*01826a49SYabin Cui 
256*01826a49SYabin Cui     { size_t const n = (size_t)fclose(f);
257*01826a49SYabin Cui       if (n!=0) EXM_THROW(5, "%s : flush error", dictFileName) }
258*01826a49SYabin Cui }
259*01826a49SYabin Cui 
260*01826a49SYabin Cui typedef struct {
261*01826a49SYabin Cui     S64 totalSizeToLoad;
262*01826a49SYabin Cui     int nbSamples;
263*01826a49SYabin Cui     int oneSampleTooLarge;
264*01826a49SYabin Cui } fileStats;
265*01826a49SYabin Cui 
266*01826a49SYabin Cui /*! DiB_fileStats() :
267*01826a49SYabin Cui  *  Given a list of files, and a chunkSize (0 == no chunk, whole files)
268*01826a49SYabin Cui  *  provides the amount of data to be loaded and the resulting nb of samples.
269*01826a49SYabin Cui  *  This is useful primarily for allocation purpose => sample buffer, and sample sizes table.
270*01826a49SYabin Cui  */
DiB_fileStats(const char ** fileNamesTable,int nbFiles,size_t chunkSize,int displayLevel)271*01826a49SYabin Cui static fileStats DiB_fileStats(const char** fileNamesTable, int nbFiles, size_t chunkSize, int displayLevel)
272*01826a49SYabin Cui {
273*01826a49SYabin Cui     fileStats fs;
274*01826a49SYabin Cui     int n;
275*01826a49SYabin Cui     memset(&fs, 0, sizeof(fs));
276*01826a49SYabin Cui 
277*01826a49SYabin Cui     /* We assume that if chunking is requested, the chunk size is < SAMPLESIZE_MAX */
278*01826a49SYabin Cui     assert( chunkSize <= SAMPLESIZE_MAX );
279*01826a49SYabin Cui 
280*01826a49SYabin Cui     for (n=0; n<nbFiles; n++) {
281*01826a49SYabin Cui       S64 const fileSize = DiB_getFileSize(fileNamesTable[n]);
282*01826a49SYabin Cui       /* TODO: is there a minimum sample size? What if the file is 1-byte? */
283*01826a49SYabin Cui       if (fileSize == 0) {
284*01826a49SYabin Cui         DISPLAYLEVEL(3, "Sample file '%s' has zero size, skipping...\n", fileNamesTable[n]);
285*01826a49SYabin Cui         continue;
286*01826a49SYabin Cui       }
287*01826a49SYabin Cui 
288*01826a49SYabin Cui       /* the case where we are breaking up files in sample chunks */
289*01826a49SYabin Cui       if (chunkSize > 0) {
290*01826a49SYabin Cui         /* TODO: is there a minimum sample size? Can we have a 1-byte sample? */
291*01826a49SYabin Cui         fs.nbSamples += (int)((fileSize + chunkSize-1) / chunkSize);
292*01826a49SYabin Cui         fs.totalSizeToLoad += fileSize;
293*01826a49SYabin Cui       }
294*01826a49SYabin Cui       else {
295*01826a49SYabin Cui       /* the case where one file is one sample */
296*01826a49SYabin Cui         if (fileSize > SAMPLESIZE_MAX) {
297*01826a49SYabin Cui           /* flag excessively large sample files */
298*01826a49SYabin Cui           fs.oneSampleTooLarge |= (fileSize > 2*SAMPLESIZE_MAX);
299*01826a49SYabin Cui 
300*01826a49SYabin Cui           /* Limit to the first SAMPLESIZE_MAX (128kB) of the file */
301*01826a49SYabin Cui           DISPLAYLEVEL(3, "Sample file '%s' is too large, limiting to %d KB",
302*01826a49SYabin Cui               fileNamesTable[n], SAMPLESIZE_MAX / (1 KB));
303*01826a49SYabin Cui         }
304*01826a49SYabin Cui         fs.nbSamples += 1;
305*01826a49SYabin Cui         fs.totalSizeToLoad += MIN(fileSize, SAMPLESIZE_MAX);
306*01826a49SYabin Cui       }
307*01826a49SYabin Cui     }
308*01826a49SYabin Cui     DISPLAYLEVEL(4, "Found training data %d files, %d KB, %d samples\n", nbFiles, (int)(fs.totalSizeToLoad / (1 KB)), fs.nbSamples);
309*01826a49SYabin Cui     return fs;
310*01826a49SYabin Cui }
311*01826a49SYabin Cui 
DiB_trainFromFiles(const char * dictFileName,size_t maxDictSize,const char ** fileNamesTable,int nbFiles,size_t chunkSize,ZDICT_legacy_params_t * params,ZDICT_cover_params_t * coverParams,ZDICT_fastCover_params_t * fastCoverParams,int optimize,unsigned memLimit)312*01826a49SYabin Cui int DiB_trainFromFiles(const char* dictFileName, size_t maxDictSize,
313*01826a49SYabin Cui                        const char** fileNamesTable, int nbFiles, size_t chunkSize,
314*01826a49SYabin Cui                        ZDICT_legacy_params_t* params, ZDICT_cover_params_t* coverParams,
315*01826a49SYabin Cui                        ZDICT_fastCover_params_t* fastCoverParams, int optimize, unsigned memLimit)
316*01826a49SYabin Cui {
317*01826a49SYabin Cui     fileStats fs;
318*01826a49SYabin Cui     size_t* sampleSizes; /* vector of sample sizes. Each sample can be up to SAMPLESIZE_MAX */
319*01826a49SYabin Cui     int nbSamplesLoaded; /* nb of samples effectively loaded in srcBuffer */
320*01826a49SYabin Cui     size_t loadedSize; /* total data loaded in srcBuffer for all samples */
321*01826a49SYabin Cui     void* srcBuffer /* contiguous buffer with training data/samples */;
322*01826a49SYabin Cui     void* const dictBuffer = malloc(maxDictSize);
323*01826a49SYabin Cui     int result = 0;
324*01826a49SYabin Cui 
325*01826a49SYabin Cui     int const displayLevel = params ? params->zParams.notificationLevel :
326*01826a49SYabin Cui         coverParams ? coverParams->zParams.notificationLevel :
327*01826a49SYabin Cui         fastCoverParams ? fastCoverParams->zParams.notificationLevel : 0;
328*01826a49SYabin Cui 
329*01826a49SYabin Cui     /* Shuffle input files before we start assessing how much sample datA to load.
330*01826a49SYabin Cui        The purpose of the shuffle is to pick random samples when the sample
331*01826a49SYabin Cui        set is larger than what we can load in memory. */
332*01826a49SYabin Cui     DISPLAYLEVEL(3, "Shuffling input files\n");
333*01826a49SYabin Cui     DiB_shuffle(fileNamesTable, nbFiles);
334*01826a49SYabin Cui 
335*01826a49SYabin Cui     /* Figure out how much sample data to load with how many samples */
336*01826a49SYabin Cui     fs = DiB_fileStats(fileNamesTable, nbFiles, chunkSize, displayLevel);
337*01826a49SYabin Cui 
338*01826a49SYabin Cui     {
339*01826a49SYabin Cui         int const memMult = params ? MEMMULT :
340*01826a49SYabin Cui                             coverParams ? COVER_MEMMULT:
341*01826a49SYabin Cui                             FASTCOVER_MEMMULT;
342*01826a49SYabin Cui         size_t const maxMem =  DiB_findMaxMem(fs.totalSizeToLoad * memMult) / memMult;
343*01826a49SYabin Cui         /* Limit the size of the training data to the free memory */
344*01826a49SYabin Cui         /* Limit the size of the training data to 2GB */
345*01826a49SYabin Cui         /* TODO: there is opportunity to stop DiB_fileStats() early when the data limit is reached */
346*01826a49SYabin Cui         loadedSize = (size_t)MIN( MIN((S64)maxMem, fs.totalSizeToLoad), MAX_SAMPLES_SIZE );
347*01826a49SYabin Cui         if (memLimit != 0) {
348*01826a49SYabin Cui             DISPLAYLEVEL(2, "!  Warning : setting manual memory limit for dictionary training data at %u MB \n",
349*01826a49SYabin Cui                 (unsigned)(memLimit / (1 MB)));
350*01826a49SYabin Cui             loadedSize = (size_t)MIN(loadedSize, memLimit);
351*01826a49SYabin Cui         }
352*01826a49SYabin Cui         srcBuffer = malloc(loadedSize+NOISELENGTH);
353*01826a49SYabin Cui         sampleSizes = (size_t*)malloc(fs.nbSamples * sizeof(size_t));
354*01826a49SYabin Cui     }
355*01826a49SYabin Cui 
356*01826a49SYabin Cui     /* Checks */
357*01826a49SYabin Cui     if ((fs.nbSamples && !sampleSizes) || (!srcBuffer) || (!dictBuffer))
358*01826a49SYabin Cui         EXM_THROW(12, "not enough memory for DiB_trainFiles");   /* should not happen */
359*01826a49SYabin Cui     if (fs.oneSampleTooLarge) {
360*01826a49SYabin Cui         DISPLAYLEVEL(2, "!  Warning : some sample(s) are very large \n");
361*01826a49SYabin Cui         DISPLAYLEVEL(2, "!  Note that dictionary is only useful for small samples. \n");
362*01826a49SYabin Cui         DISPLAYLEVEL(2, "!  As a consequence, only the first %u bytes of each sample are loaded \n", SAMPLESIZE_MAX);
363*01826a49SYabin Cui     }
364*01826a49SYabin Cui     if (fs.nbSamples < 5) {
365*01826a49SYabin Cui         DISPLAYLEVEL(2, "!  Warning : nb of samples too low for proper processing ! \n");
366*01826a49SYabin Cui         DISPLAYLEVEL(2, "!  Please provide _one file per sample_. \n");
367*01826a49SYabin Cui         DISPLAYLEVEL(2, "!  Alternatively, split files into fixed-size blocks representative of samples, with -B# \n");
368*01826a49SYabin Cui         EXM_THROW(14, "nb of samples too low");   /* we now clearly forbid this case */
369*01826a49SYabin Cui     }
370*01826a49SYabin Cui     if (fs.totalSizeToLoad < (S64)maxDictSize * 8) {
371*01826a49SYabin Cui         DISPLAYLEVEL(2, "!  Warning : data size of samples too small for target dictionary size \n");
372*01826a49SYabin Cui         DISPLAYLEVEL(2, "!  Samples should be about 100x larger than target dictionary size \n");
373*01826a49SYabin Cui     }
374*01826a49SYabin Cui 
375*01826a49SYabin Cui     /* init */
376*01826a49SYabin Cui     if ((S64)loadedSize < fs.totalSizeToLoad)
377*01826a49SYabin Cui         DISPLAYLEVEL(1, "Training samples set too large (%u MB); training on %u MB only...\n",
378*01826a49SYabin Cui             (unsigned)(fs.totalSizeToLoad / (1 MB)),
379*01826a49SYabin Cui             (unsigned)(loadedSize / (1 MB)));
380*01826a49SYabin Cui 
381*01826a49SYabin Cui     /* Load input buffer */
382*01826a49SYabin Cui     nbSamplesLoaded = DiB_loadFiles(
383*01826a49SYabin Cui         srcBuffer, &loadedSize, sampleSizes, fs.nbSamples, fileNamesTable,
384*01826a49SYabin Cui         nbFiles, chunkSize, displayLevel);
385*01826a49SYabin Cui 
386*01826a49SYabin Cui     {   size_t dictSize = ZSTD_error_GENERIC;
387*01826a49SYabin Cui         if (params) {
388*01826a49SYabin Cui             DiB_fillNoise((char*)srcBuffer + loadedSize, NOISELENGTH);   /* guard band, for end of buffer condition */
389*01826a49SYabin Cui             dictSize = ZDICT_trainFromBuffer_legacy(dictBuffer, maxDictSize,
390*01826a49SYabin Cui                                                     srcBuffer, sampleSizes, nbSamplesLoaded,
391*01826a49SYabin Cui                                                     *params);
392*01826a49SYabin Cui         } else if (coverParams) {
393*01826a49SYabin Cui             if (optimize) {
394*01826a49SYabin Cui               dictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, maxDictSize,
395*01826a49SYabin Cui                                                              srcBuffer, sampleSizes, nbSamplesLoaded,
396*01826a49SYabin Cui                                                              coverParams);
397*01826a49SYabin Cui               if (!ZDICT_isError(dictSize)) {
398*01826a49SYabin Cui                   unsigned splitPercentage = (unsigned)(coverParams->splitPoint * 100);
399*01826a49SYabin Cui                   DISPLAYLEVEL(2, "k=%u\nd=%u\nsteps=%u\nsplit=%u\n", coverParams->k, coverParams->d,
400*01826a49SYabin Cui                               coverParams->steps, splitPercentage);
401*01826a49SYabin Cui               }
402*01826a49SYabin Cui             } else {
403*01826a49SYabin Cui               dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, maxDictSize, srcBuffer,
404*01826a49SYabin Cui                                                      sampleSizes, nbSamplesLoaded, *coverParams);
405*01826a49SYabin Cui             }
406*01826a49SYabin Cui         } else if (fastCoverParams != NULL) {
407*01826a49SYabin Cui             if (optimize) {
408*01826a49SYabin Cui               dictSize = ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, maxDictSize,
409*01826a49SYabin Cui                                                               srcBuffer, sampleSizes, nbSamplesLoaded,
410*01826a49SYabin Cui                                                               fastCoverParams);
411*01826a49SYabin Cui               if (!ZDICT_isError(dictSize)) {
412*01826a49SYabin Cui                 unsigned splitPercentage = (unsigned)(fastCoverParams->splitPoint * 100);
413*01826a49SYabin Cui                 DISPLAYLEVEL(2, "k=%u\nd=%u\nf=%u\nsteps=%u\nsplit=%u\naccel=%u\n", fastCoverParams->k,
414*01826a49SYabin Cui                             fastCoverParams->d, fastCoverParams->f, fastCoverParams->steps, splitPercentage,
415*01826a49SYabin Cui                             fastCoverParams->accel);
416*01826a49SYabin Cui               }
417*01826a49SYabin Cui             } else {
418*01826a49SYabin Cui               dictSize = ZDICT_trainFromBuffer_fastCover(dictBuffer, maxDictSize, srcBuffer,
419*01826a49SYabin Cui                                                         sampleSizes, nbSamplesLoaded, *fastCoverParams);
420*01826a49SYabin Cui             }
421*01826a49SYabin Cui         } else {
422*01826a49SYabin Cui             assert(0 /* Impossible */);
423*01826a49SYabin Cui         }
424*01826a49SYabin Cui         if (ZDICT_isError(dictSize)) {
425*01826a49SYabin Cui             DISPLAYLEVEL(1, "dictionary training failed : %s \n", ZDICT_getErrorName(dictSize));   /* should not happen */
426*01826a49SYabin Cui             result = 1;
427*01826a49SYabin Cui             goto _cleanup;
428*01826a49SYabin Cui         }
429*01826a49SYabin Cui         /* save dict */
430*01826a49SYabin Cui         DISPLAYLEVEL(2, "Save dictionary of size %u into file %s \n", (unsigned)dictSize, dictFileName);
431*01826a49SYabin Cui         DiB_saveDict(dictFileName, dictBuffer, dictSize);
432*01826a49SYabin Cui     }
433*01826a49SYabin Cui 
434*01826a49SYabin Cui     /* clean up */
435*01826a49SYabin Cui _cleanup:
436*01826a49SYabin Cui     free(srcBuffer);
437*01826a49SYabin Cui     free(sampleSizes);
438*01826a49SYabin Cui     free(dictBuffer);
439*01826a49SYabin Cui     return result;
440*01826a49SYabin Cui }
441