2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree. An additional grant
7 * of patent rights can be found in the PATENTS file in the same directory.
12 /* **************************************
14 ****************************************/
16 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
20 /*-*************************************
22 ***************************************/
23 #include "platform.h" /* Large Files support */
24 #include "util.h" /* UTIL_getFileSize, UTIL_getTotalFileSize */
25 #include <stdlib.h> /* malloc, free */
26 #include <string.h> /* memset */
27 #include <stdio.h> /* fprintf, fopen, ftello64 */
28 #include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
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 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 (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
56 static int g_displayLevel = 0; /* 0 : no display; 1: errors; 2: default; 4: full information */
58 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
59 if ((DIB_clockSpan(g_time) > refreshRate) || (g_displayLevel>=4)) \
60 { g_time = clock(); DISPLAY(__VA_ARGS__); \
61 if (g_displayLevel>=4) fflush(stderr); } }
62 static const clock_t refreshRate = CLOCKS_PER_SEC * 2 / 10;
63 static clock_t g_time = 0;
65 static clock_t DIB_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
68 /*-*************************************
70 ***************************************/
74 #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
75 #define EXM_THROW(error, ...) \
77 DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
78 DISPLAYLEVEL(1, "Error %i : ", error); \
79 DISPLAYLEVEL(1, __VA_ARGS__); \
80 DISPLAYLEVEL(1, "\n"); \
85 /* ********************************************************
87 **********************************************************/
88 unsigned DiB_isError(size_t errorCode) { return ERR_isError(errorCode); }
90 const char* DiB_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
93 #define MIN(a,b) ((a) < (b) ? (a) : (b))
96 /* ********************************************************
97 * File related operations
98 **********************************************************/
100 * @return : nb of files effectively loaded into `buffer` */
101 static unsigned DiB_loadFiles(void* buffer, size_t* bufferSizePtr,
103 const char** fileNamesTable, unsigned nbFiles)
105 char* const buff = (char*)buffer;
109 for (n=0; n<nbFiles; n++) {
110 const char* const fileName = fileNamesTable[n];
111 unsigned long long const fs64 = UTIL_getFileSize(fileName);
112 size_t const fileSize = (size_t) MIN(fs64, SAMPLESIZE_MAX);
113 if (fileSize > *bufferSizePtr-pos) break;
114 { FILE* const f = fopen(fileName, "rb");
115 if (f==NULL) EXM_THROW(10, "zstd: dictBuilder: %s %s ", fileName, strerror(errno));
116 DISPLAYUPDATE(2, "Loading %s... \r", fileName);
117 { size_t const readSize = fread(buff+pos, 1, fileSize, f);
118 if (readSize != fileSize) EXM_THROW(11, "Pb reading %s", fileName);
120 fileSizes[n] = fileSize;
123 DISPLAYLEVEL(2, "\r%79s\r", "");
124 *bufferSizePtr = pos;
128 #define DiB_rotl32(x,r) ((x << r) | (x >> (32 - r)))
129 static U32 DiB_rand(U32* src)
131 static const U32 prime1 = 2654435761U;
132 static const U32 prime2 = 2246822519U;
136 rand32 = DiB_rotl32(rand32, 13);
141 static void DiB_shuffle(const char** fileNamesTable, unsigned nbFiles) {
142 /* Initialize the pseudorandom number generator */
143 U32 seed = 0xFD2FB528;
145 for (i = nbFiles - 1; i > 0; --i) {
146 unsigned const j = DiB_rand(&seed) % (i + 1);
147 const char* tmp = fileNamesTable[j];
148 fileNamesTable[j] = fileNamesTable[i];
149 fileNamesTable[i] = tmp;
154 /*-********************************************************
155 * Dictionary training functions
156 **********************************************************/
157 static size_t DiB_findMaxMem(unsigned long long requiredMem)
159 size_t const step = 8 MB;
160 void* testmem = NULL;
162 requiredMem = (((requiredMem >> 23) + 1) << 23);
164 if (requiredMem > maxMemory) requiredMem = maxMemory;
167 testmem = malloc((size_t)requiredMem);
172 return (size_t)requiredMem;
176 static void DiB_fillNoise(void* buffer, size_t length)
178 unsigned const prime1 = 2654435761U;
179 unsigned const prime2 = 2246822519U;
180 unsigned acc = prime1;
183 for (p=0; p<length; p++) {
185 ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
190 static void DiB_saveDict(const char* dictFileName,
191 const void* buff, size_t buffSize)
193 FILE* const f = fopen(dictFileName, "wb");
194 if (f==NULL) EXM_THROW(3, "cannot open %s ", dictFileName);
196 { size_t const n = fwrite(buff, 1, buffSize, f);
197 if (n!=buffSize) EXM_THROW(4, "%s : write error", dictFileName) }
199 { size_t const n = (size_t)fclose(f);
200 if (n!=0) EXM_THROW(5, "%s : flush error", dictFileName) }
204 static int g_tooLargeSamples = 0;
205 static U64 DiB_getTotalCappedFileSize(const char** fileNamesTable, unsigned nbFiles)
209 for (n=0; n<nbFiles; n++) {
210 U64 const fileSize = UTIL_getFileSize(fileNamesTable[n]);
211 U64 const cappedFileSize = MIN(fileSize, SAMPLESIZE_MAX);
212 total += cappedFileSize;
213 g_tooLargeSamples |= (fileSize > 2*SAMPLESIZE_MAX);
219 /*! ZDICT_trainFromBuffer_unsafe() :
220 Strictly Internal use only !!
221 Same as ZDICT_trainFromBuffer_advanced(), but does not control `samplesBuffer`.
222 `samplesBuffer` must be followed by noisy guard band to avoid out-of-buffer reads.
223 @return : size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
226 size_t ZDICT_trainFromBuffer_unsafe(void* dictBuffer, size_t dictBufferCapacity,
227 const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
228 ZDICT_params_t parameters);
231 int DiB_trainFromFiles(const char* dictFileName, unsigned maxDictSize,
232 const char** fileNamesTable, unsigned nbFiles,
233 ZDICT_params_t *params, COVER_params_t *coverParams,
236 void* const dictBuffer = malloc(maxDictSize);
237 size_t* const fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t));
238 unsigned long long const totalSizeToLoad = DiB_getTotalCappedFileSize(fileNamesTable, nbFiles);
239 size_t const memMult = params ? MEMMULT : COVER_MEMMULT;
240 size_t const maxMem = DiB_findMaxMem(totalSizeToLoad * memMult) / memMult;
241 size_t benchedSize = (size_t) MIN ((unsigned long long)maxMem, totalSizeToLoad);
242 void* const srcBuffer = malloc(benchedSize+NOISELENGTH);
246 if (params) g_displayLevel = params->notificationLevel;
247 else if (coverParams) g_displayLevel = coverParams->notificationLevel;
248 else EXM_THROW(13, "Neither dictionary algorith selected"); /* should not happen */
249 if ((!fileSizes) || (!srcBuffer) || (!dictBuffer)) EXM_THROW(12, "not enough memory for DiB_trainFiles"); /* should not happen */
250 if (g_tooLargeSamples) {
251 DISPLAYLEVEL(2, "! Warning : some samples are very large \n");
252 DISPLAYLEVEL(2, "! Note that dictionary is only useful for small files or beginning of large files. \n");
253 DISPLAYLEVEL(2, "! As a consequence, only the first %u bytes of each file are loaded \n", SAMPLESIZE_MAX);
255 if ((nbFiles < 5) || (totalSizeToLoad < 9 * (unsigned long long)maxDictSize)) {
256 DISPLAYLEVEL(2, "! Warning : nb of samples too low for proper processing ! \n");
257 DISPLAYLEVEL(2, "! Please provide _one file per sample_. \n");
258 DISPLAYLEVEL(2, "! Do not concatenate samples together into a single file, \n");
259 DISPLAYLEVEL(2, "! as dictBuilder will be unable to find the beginning of each sample, \n");
260 DISPLAYLEVEL(2, "! resulting in poor dictionary quality. \n");
264 if (benchedSize < totalSizeToLoad)
265 DISPLAYLEVEL(1, "Not enough memory; training on %u MB only...\n", (unsigned)(benchedSize >> 20));
267 /* Load input buffer */
268 DISPLAYLEVEL(3, "Shuffling input files\n");
269 DiB_shuffle(fileNamesTable, nbFiles);
270 nbFiles = DiB_loadFiles(srcBuffer, &benchedSize, fileSizes, fileNamesTable, nbFiles);
275 DiB_fillNoise((char*)srcBuffer + benchedSize, NOISELENGTH); /* guard band, for end of buffer condition */
276 dictSize = ZDICT_trainFromBuffer_unsafe(dictBuffer, maxDictSize,
277 srcBuffer, fileSizes, nbFiles,
279 } else if (optimizeCover) {
280 dictSize = COVER_optimizeTrainFromBuffer(
281 dictBuffer, maxDictSize, srcBuffer, fileSizes, nbFiles,
283 if (!ZDICT_isError(dictSize)) {
284 DISPLAYLEVEL(2, "k=%u\nd=%u\nsteps=%u\n", coverParams->k, coverParams->d, coverParams->steps);
287 dictSize = COVER_trainFromBuffer(dictBuffer, maxDictSize,
288 srcBuffer, fileSizes, nbFiles,
291 if (ZDICT_isError(dictSize)) {
292 DISPLAYLEVEL(1, "dictionary training failed : %s \n", ZDICT_getErrorName(dictSize)); /* should not happen */
297 DISPLAYLEVEL(2, "Save dictionary of size %u into file %s \n", (U32)dictSize, dictFileName);
298 DiB_saveDict(dictFileName, dictBuffer, dictSize);