2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
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.
13 /* **************************************
15 ****************************************/
17 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
21 /*-*************************************
23 ***************************************/
24 #include "platform.h" /* Large Files support */
25 #include "util.h" /* UTIL_getFileSize, UTIL_getTotalFileSize */
26 #include <stdlib.h> /* malloc, free */
27 #include <string.h> /* memset */
28 #include <stdio.h> /* fprintf, fopen, ftello64 */
29 #include <errno.h> /* errno */
31 #include "mem.h" /* read */
32 #include "error_private.h"
36 /*-*************************************
38 ***************************************/
43 #define SAMPLESIZE_MAX (128 KB)
44 #define MEMMULT 11 /* rough estimation : memory cost to analyze 1 byte of sample */
45 #define COVER_MEMMULT 9 /* rough estimation : memory cost to analyze 1 byte of sample */
46 static const size_t g_maxMemory = (sizeof(size_t) == 4) ? (2 GB - 64 MB) : ((size_t)(512 MB) << sizeof(size_t));
48 #define NOISELENGTH 32
51 /*-*************************************
53 ***************************************/
54 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
55 #define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
57 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
58 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
60 #define DISPLAYUPDATE(l, ...) { if (displayLevel>=l) { \
61 if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (displayLevel>=4)) \
62 { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \
63 if (displayLevel>=4) fflush(stderr); } } }
65 /*-*************************************
67 ***************************************/
71 #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
72 #define EXM_THROW(error, ...) \
74 DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
75 DISPLAY("Error %i : ", error); \
76 DISPLAY(__VA_ARGS__); \
82 /* ********************************************************
84 **********************************************************/
85 unsigned DiB_isError(size_t errorCode) { return ERR_isError(errorCode); }
87 const char* DiB_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
90 #define MIN(a,b) ((a) < (b) ? (a) : (b))
93 /* ********************************************************
94 * File related operations
95 **********************************************************/
97 * load samples from files listed in fileNamesTable into buffer.
98 * works even if buffer is too small to load all samples.
99 * Also provides the size of each sample into sampleSizes table
100 * which must be sized correctly, using DiB_fileStats().
101 * @return : nb of samples effectively loaded into `buffer`
102 * *bufferSizePtr is modified, it provides the amount data loaded within buffer.
103 * sampleSizes is filled with the size of each sample.
105 static unsigned DiB_loadFiles(void* buffer, size_t* bufferSizePtr,
106 size_t* sampleSizes, unsigned sstSize,
107 const char** fileNamesTable, unsigned nbFiles, size_t targetChunkSize,
108 unsigned displayLevel)
110 char* const buff = (char*)buffer;
112 unsigned nbLoadedChunks = 0, fileIndex;
114 for (fileIndex=0; fileIndex<nbFiles; fileIndex++) {
115 const char* const fileName = fileNamesTable[fileIndex];
116 unsigned long long const fs64 = UTIL_getFileSize(fileName);
117 unsigned long long remainingToLoad = (fs64 == UTIL_FILESIZE_UNKNOWN) ? 0 : fs64;
118 U32 const nbChunks = targetChunkSize ? (U32)((fs64 + (targetChunkSize-1)) / targetChunkSize) : 1;
119 U64 const chunkSize = targetChunkSize ? MIN(targetChunkSize, fs64) : fs64;
120 size_t const maxChunkSize = (size_t)MIN(chunkSize, SAMPLESIZE_MAX);
122 FILE* const f = fopen(fileName, "rb");
123 if (f==NULL) EXM_THROW(10, "zstd: dictBuilder: %s %s ", fileName, strerror(errno));
124 DISPLAYUPDATE(2, "Loading %s... \r", fileName);
125 for (cnb=0; cnb<nbChunks; cnb++) {
126 size_t const toLoad = (size_t)MIN(maxChunkSize, remainingToLoad);
127 if (toLoad > *bufferSizePtr-pos) break;
128 { size_t const readSize = fread(buff+pos, 1, toLoad, f);
129 if (readSize != toLoad) EXM_THROW(11, "Pb reading %s", fileName);
131 sampleSizes[nbLoadedChunks++] = toLoad;
132 remainingToLoad -= targetChunkSize;
133 if (nbLoadedChunks == sstSize) { /* no more space left in sampleSizes table */
134 fileIndex = nbFiles; /* stop there */
137 if (toLoad < targetChunkSize) {
138 fseek(f, (long)(targetChunkSize - toLoad), SEEK_CUR);
142 DISPLAYLEVEL(2, "\r%79s\r", "");
143 *bufferSizePtr = pos;
144 DISPLAYLEVEL(4, "loaded : %u KB \n", (U32)(pos >> 10))
145 return nbLoadedChunks;
148 #define DiB_rotl32(x,r) ((x << r) | (x >> (32 - r)))
149 static U32 DiB_rand(U32* src)
151 static const U32 prime1 = 2654435761U;
152 static const U32 prime2 = 2246822519U;
156 rand32 = DiB_rotl32(rand32, 13);
162 * shuffle a table of file names in a semi-random way
163 * It improves dictionary quality by reducing "locality" impact, so if sample set is very large,
164 * it will load random elements from it, instead of just the first ones. */
165 static void DiB_shuffle(const char** fileNamesTable, unsigned nbFiles) {
166 U32 seed = 0xFD2FB528;
168 for (i = nbFiles - 1; i > 0; --i) {
169 unsigned const j = DiB_rand(&seed) % (i + 1);
170 const char* const tmp = fileNamesTable[j];
171 fileNamesTable[j] = fileNamesTable[i];
172 fileNamesTable[i] = tmp;
177 /*-********************************************************
178 * Dictionary training functions
179 **********************************************************/
180 static size_t DiB_findMaxMem(unsigned long long requiredMem)
182 size_t const step = 8 MB;
183 void* testmem = NULL;
185 requiredMem = (((requiredMem >> 23) + 1) << 23);
187 if (requiredMem > g_maxMemory) requiredMem = g_maxMemory;
190 testmem = malloc((size_t)requiredMem);
195 return (size_t)requiredMem;
199 static void DiB_fillNoise(void* buffer, size_t length)
201 unsigned const prime1 = 2654435761U;
202 unsigned const prime2 = 2246822519U;
203 unsigned acc = prime1;
206 for (p=0; p<length; p++) {
208 ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
213 static void DiB_saveDict(const char* dictFileName,
214 const void* buff, size_t buffSize)
216 FILE* const f = fopen(dictFileName, "wb");
217 if (f==NULL) EXM_THROW(3, "cannot open %s ", dictFileName);
219 { size_t const n = fwrite(buff, 1, buffSize, f);
220 if (n!=buffSize) EXM_THROW(4, "%s : write error", dictFileName) }
222 { size_t const n = (size_t)fclose(f);
223 if (n!=0) EXM_THROW(5, "%s : flush error", dictFileName) }
229 unsigned oneSampleTooLarge;
233 /*! DiB_fileStats() :
234 * Given a list of files, and a chunkSize (0 == no chunk, whole files)
235 * provides the amount of data to be loaded and the resulting nb of samples.
236 * This is useful primarily for allocation purpose => sample buffer, and sample sizes table.
238 static fileStats DiB_fileStats(const char** fileNamesTable, unsigned nbFiles, size_t chunkSize, unsigned displayLevel)
242 memset(&fs, 0, sizeof(fs));
243 for (n=0; n<nbFiles; n++) {
244 U64 const fileSize = UTIL_getFileSize(fileNamesTable[n]);
245 U64 const srcSize = (fileSize == UTIL_FILESIZE_UNKNOWN) ? 0 : fileSize;
246 U32 const nbSamples = (U32)(chunkSize ? (srcSize + (chunkSize-1)) / chunkSize : 1);
247 U64 const chunkToLoad = chunkSize ? MIN(chunkSize, srcSize) : srcSize;
248 size_t const cappedChunkSize = (size_t)MIN(chunkToLoad, SAMPLESIZE_MAX);
249 fs.totalSizeToLoad += cappedChunkSize * nbSamples;
250 fs.oneSampleTooLarge |= (chunkSize > 2*SAMPLESIZE_MAX);
251 fs.nbSamples += nbSamples;
253 DISPLAYLEVEL(4, "Preparing to load : %u KB \n", (U32)(fs.totalSizeToLoad >> 10));
258 /*! ZDICT_trainFromBuffer_unsafe_legacy() :
259 Strictly Internal use only !!
260 Same as ZDICT_trainFromBuffer_legacy(), but does not control `samplesBuffer`.
261 `samplesBuffer` must be followed by noisy guard band to avoid out-of-buffer reads.
262 @return : size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
265 size_t ZDICT_trainFromBuffer_unsafe_legacy(void* dictBuffer, size_t dictBufferCapacity,
266 const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
267 ZDICT_legacy_params_t parameters);
270 int DiB_trainFromFiles(const char* dictFileName, unsigned maxDictSize,
271 const char** fileNamesTable, unsigned nbFiles, size_t chunkSize,
272 ZDICT_legacy_params_t *params, ZDICT_cover_params_t *coverParams,
275 unsigned const displayLevel = params ? params->zParams.notificationLevel :
276 coverParams ? coverParams->zParams.notificationLevel :
277 0; /* should never happen */
278 void* const dictBuffer = malloc(maxDictSize);
279 fileStats const fs = DiB_fileStats(fileNamesTable, nbFiles, chunkSize, displayLevel);
280 size_t* const sampleSizes = (size_t*)malloc(fs.nbSamples * sizeof(size_t));
281 size_t const memMult = params ? MEMMULT : COVER_MEMMULT;
282 size_t const maxMem = DiB_findMaxMem(fs.totalSizeToLoad * memMult) / memMult;
283 size_t loadedSize = (size_t) MIN ((unsigned long long)maxMem, fs.totalSizeToLoad);
284 void* const srcBuffer = malloc(loadedSize+NOISELENGTH);
288 if ((!sampleSizes) || (!srcBuffer) || (!dictBuffer))
289 EXM_THROW(12, "not enough memory for DiB_trainFiles"); /* should not happen */
290 if (fs.oneSampleTooLarge) {
291 DISPLAYLEVEL(2, "! Warning : some sample(s) are very large \n");
292 DISPLAYLEVEL(2, "! Note that dictionary is only useful for small samples. \n");
293 DISPLAYLEVEL(2, "! As a consequence, only the first %u bytes of each sample are loaded \n", SAMPLESIZE_MAX);
295 if (fs.nbSamples < 5) {
296 DISPLAYLEVEL(2, "! Warning : nb of samples too low for proper processing ! \n");
297 DISPLAYLEVEL(2, "! Please provide _one file per sample_. \n");
298 DISPLAYLEVEL(2, "! Alternatively, split files into fixed-size blocks representative of samples, with -B# \n");
299 EXM_THROW(14, "nb of samples too low"); /* we now clearly forbid this case */
301 if (fs.totalSizeToLoad < (unsigned long long)(8 * maxDictSize)) {
302 DISPLAYLEVEL(2, "! Warning : data size of samples too small for target dictionary size \n");
303 DISPLAYLEVEL(2, "! Samples should be about 100x larger than target dictionary size \n");
307 if (loadedSize < fs.totalSizeToLoad)
308 DISPLAYLEVEL(1, "Not enough memory; training on %u MB only...\n", (unsigned)(loadedSize >> 20));
310 /* Load input buffer */
311 DISPLAYLEVEL(3, "Shuffling input files\n");
312 DiB_shuffle(fileNamesTable, nbFiles);
313 nbFiles = DiB_loadFiles(srcBuffer, &loadedSize, sampleSizes, fs.nbSamples, fileNamesTable, nbFiles, chunkSize, displayLevel);
317 DiB_fillNoise((char*)srcBuffer + loadedSize, NOISELENGTH); /* guard band, for end of buffer condition */
318 dictSize = ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, maxDictSize,
319 srcBuffer, sampleSizes, fs.nbSamples,
321 } else if (optimizeCover) {
322 dictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, maxDictSize,
323 srcBuffer, sampleSizes, fs.nbSamples,
325 if (!ZDICT_isError(dictSize)) {
326 DISPLAYLEVEL(2, "k=%u\nd=%u\nsteps=%u\n", coverParams->k, coverParams->d, coverParams->steps);
329 dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, maxDictSize, srcBuffer,
330 sampleSizes, fs.nbSamples, *coverParams);
332 if (ZDICT_isError(dictSize)) {
333 DISPLAYLEVEL(1, "dictionary training failed : %s \n", ZDICT_getErrorName(dictSize)); /* should not happen */
338 DISPLAYLEVEL(2, "Save dictionary of size %u into file %s \n", (U32)dictSize, dictFileName);
339 DiB_saveDict(dictFileName, dictBuffer, dictSize);