blob: 31cde5c95db11f11ac491e3bb8d4c816c311b6ab [file] [log] [blame]
Yann Collet4ded9e52016-08-30 10:04:33 -07001/**
2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3 * All rights reserved.
4 *
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.
8 */
Yann Collet71eafdd2016-02-12 02:31:57 +01009
Yann Collet71eafdd2016-02-12 02:31:57 +010010
Yann Collet71eafdd2016-02-12 02:31:57 +010011
Przemyslaw Skibinski2f6ccee2016-12-21 13:23:34 +010012/* **************************************
13* Compiler Warnings
14****************************************/
15#ifdef _MSC_VER
Przemyslaw Skibinski2f6ccee2016-12-21 13:23:34 +010016# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
17#endif
18
19
Yann Collet71eafdd2016-02-12 02:31:57 +010020/*-*************************************
21* Includes
22***************************************/
Przemyslaw Skibinski7a8a03c2016-12-21 15:08:44 +010023#include "platform.h" /* Large Files support */
Przemyslaw Skibinski2f6ccee2016-12-21 13:23:34 +010024#include "util.h" /* UTIL_getFileSize, UTIL_getTotalFileSize */
Yann Collet71eafdd2016-02-12 02:31:57 +010025#include <stdlib.h> /* malloc, free */
26#include <string.h> /* memset */
27#include <stdio.h> /* fprintf, fopen, ftello64 */
inikep37337972016-05-10 14:22:55 +020028#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
Yann Colleta3d03a32016-07-06 16:27:17 +020029#include <errno.h> /* errno */
Yann Collet71eafdd2016-02-12 02:31:57 +010030
Przemyslaw Skibinski2f6ccee2016-12-21 13:23:34 +010031#include "mem.h" /* read */
Yann Collet71eafdd2016-02-12 02:31:57 +010032#include "error_private.h"
inikep23a08892016-04-22 12:43:18 +020033#include "dibio.h"
Yann Collet71eafdd2016-02-12 02:31:57 +010034
35
36/*-*************************************
37* Constants
38***************************************/
39#define KB *(1 <<10)
40#define MB *(1 <<20)
41#define GB *(1U<<30)
42
Yann Collet1496c3d2016-12-18 11:58:23 +010043#define SAMPLESIZE_MAX (128 KB)
44#define MEMMULT 11 /* rough estimation : memory cost to analyze 1 byte of sample */
Nick Terrelldf8415c2016-12-31 21:08:24 -080045#define COVER_MEMMULT 9 /* rough estimation : memory cost to analyze 1 byte of sample */
Yann Collet71eafdd2016-02-12 02:31:57 +010046static const size_t maxMemory = (sizeof(size_t) == 4) ? (2 GB - 64 MB) : ((size_t)(512 MB) << sizeof(size_t));
47
48#define NOISELENGTH 32
Yann Collet71eafdd2016-02-12 02:31:57 +010049
50
51/*-*************************************
52* Console display
53***************************************/
54#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
55#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
Sean Purcell042ba122017-03-23 11:13:52 -070056static int g_displayLevel = 0; /* 0 : no display; 1: errors; 2: default; 4: full information */
Yann Collet71eafdd2016-02-12 02:31:57 +010057
Yann Colletf6ca09b2016-05-09 04:44:45 +020058#define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
Yann Colletbcb5f772016-07-06 15:41:03 +020059 if ((DIB_clockSpan(g_time) > refreshRate) || (g_displayLevel>=4)) \
Yann Colletf6ca09b2016-05-09 04:44:45 +020060 { g_time = clock(); DISPLAY(__VA_ARGS__); \
Sean Purcell042ba122017-03-23 11:13:52 -070061 if (g_displayLevel>=4) fflush(stderr); } }
Yann Colletbcb5f772016-07-06 15:41:03 +020062static const clock_t refreshRate = CLOCKS_PER_SEC * 2 / 10;
Yann Colletf6ca09b2016-05-09 04:44:45 +020063static clock_t g_time = 0;
64
Yann Colletbcb5f772016-07-06 15:41:03 +020065static clock_t DIB_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
Yann Colletf6ca09b2016-05-09 04:44:45 +020066
Yann Collet71eafdd2016-02-12 02:31:57 +010067
68/*-*************************************
69* Exceptions
70***************************************/
71#ifndef DEBUG
72# define DEBUG 0
73#endif
74#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
75#define EXM_THROW(error, ...) \
76{ \
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"); \
81 exit(error); \
82}
83
84
85/* ********************************************************
86* Helper functions
87**********************************************************/
88unsigned DiB_isError(size_t errorCode) { return ERR_isError(errorCode); }
89
90const char* DiB_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
91
Sean Purcell42bac7f2017-04-13 15:35:05 -070092#undef MIN
93#define MIN(a,b) ((a) < (b) ? (a) : (b))
Yann Colletbcb5f772016-07-06 15:41:03 +020094
Yann Collet71eafdd2016-02-12 02:31:57 +010095
96/* ********************************************************
97* File related operations
98**********************************************************/
Yann Collet290aaa72016-05-30 21:18:52 +020099/** DiB_loadFiles() :
100* @return : nb of files effectively loaded into `buffer` */
Yann Colletbcb5f772016-07-06 15:41:03 +0200101static unsigned DiB_loadFiles(void* buffer, size_t* bufferSizePtr,
Yann Collet290aaa72016-05-30 21:18:52 +0200102 size_t* fileSizes,
103 const char** fileNamesTable, unsigned nbFiles)
Yann Collet71eafdd2016-02-12 02:31:57 +0100104{
Yann Collet290aaa72016-05-30 21:18:52 +0200105 char* const buff = (char*)buffer;
Yann Collet71eafdd2016-02-12 02:31:57 +0100106 size_t pos = 0;
107 unsigned n;
108
109 for (n=0; n<nbFiles; n++) {
Yann Colletbcb5f772016-07-06 15:41:03 +0200110 const char* const fileName = fileNamesTable[n];
111 unsigned long long const fs64 = UTIL_getFileSize(fileName);
Yann Collet1496c3d2016-12-18 11:58:23 +0100112 size_t const fileSize = (size_t) MIN(fs64, SAMPLESIZE_MAX);
Yann Colletbcb5f772016-07-06 15:41:03 +0200113 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);
119 pos += readSize; }
120 fileSizes[n] = fileSize;
121 fclose(f);
122 } }
Nick Terrelldf8415c2016-12-31 21:08:24 -0800123 DISPLAYLEVEL(2, "\r%79s\r", "");
Yann Colletbcb5f772016-07-06 15:41:03 +0200124 *bufferSizePtr = pos;
Yann Collet290aaa72016-05-30 21:18:52 +0200125 return n;
Yann Collet71eafdd2016-02-12 02:31:57 +0100126}
127
Nick Terrelldf8415c2016-12-31 21:08:24 -0800128#define DiB_rotl32(x,r) ((x << r) | (x >> (32 - r)))
129static U32 DiB_rand(U32* src)
130{
131 static const U32 prime1 = 2654435761U;
132 static const U32 prime2 = 2246822519U;
133 U32 rand32 = *src;
134 rand32 *= prime1;
135 rand32 ^= prime2;
136 rand32 = DiB_rotl32(rand32, 13);
137 *src = rand32;
138 return rand32 >> 5;
139}
140
141static void DiB_shuffle(const char** fileNamesTable, unsigned nbFiles) {
142 /* Initialize the pseudorandom number generator */
143 U32 seed = 0xFD2FB528;
144 unsigned i;
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;
150 }
151}
152
Yann Collet71eafdd2016-02-12 02:31:57 +0100153
154/*-********************************************************
155* Dictionary training functions
156**********************************************************/
157static size_t DiB_findMaxMem(unsigned long long requiredMem)
158{
Yann Collet290aaa72016-05-30 21:18:52 +0200159 size_t const step = 8 MB;
Yann Collet71eafdd2016-02-12 02:31:57 +0100160 void* testmem = NULL;
161
162 requiredMem = (((requiredMem >> 23) + 1) << 23);
Yann Colletbcb5f772016-07-06 15:41:03 +0200163 requiredMem += step;
Yann Collet71eafdd2016-02-12 02:31:57 +0100164 if (requiredMem > maxMemory) requiredMem = maxMemory;
165
166 while (!testmem) {
Yann Collet71eafdd2016-02-12 02:31:57 +0100167 testmem = malloc((size_t)requiredMem);
Yann Colletbcb5f772016-07-06 15:41:03 +0200168 requiredMem -= step;
Yann Collet71eafdd2016-02-12 02:31:57 +0100169 }
170
171 free(testmem);
Yann Colletbcb5f772016-07-06 15:41:03 +0200172 return (size_t)requiredMem;
Yann Collet71eafdd2016-02-12 02:31:57 +0100173}
174
175
176static void DiB_fillNoise(void* buffer, size_t length)
177{
Yann Colletbcb5f772016-07-06 15:41:03 +0200178 unsigned const prime1 = 2654435761U;
179 unsigned const prime2 = 2246822519U;
180 unsigned acc = prime1;
Yann Collet71eafdd2016-02-12 02:31:57 +0100181 size_t p=0;;
182
183 for (p=0; p<length; p++) {
Yann Colletbcb5f772016-07-06 15:41:03 +0200184 acc *= prime2;
Yann Collet71eafdd2016-02-12 02:31:57 +0100185 ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
186 }
187}
188
189
190static void DiB_saveDict(const char* dictFileName,
191 const void* buff, size_t buffSize)
192{
Yann Collet290aaa72016-05-30 21:18:52 +0200193 FILE* const f = fopen(dictFileName, "wb");
Yann Collet71eafdd2016-02-12 02:31:57 +0100194 if (f==NULL) EXM_THROW(3, "cannot open %s ", dictFileName);
195
Yann Colletf6ca09b2016-05-09 04:44:45 +0200196 { size_t const n = fwrite(buff, 1, buffSize, f);
197 if (n!=buffSize) EXM_THROW(4, "%s : write error", dictFileName) }
Yann Collet71eafdd2016-02-12 02:31:57 +0100198
Yann Colletf6ca09b2016-05-09 04:44:45 +0200199 { size_t const n = (size_t)fclose(f);
200 if (n!=0) EXM_THROW(5, "%s : flush error", dictFileName) }
Yann Collet71eafdd2016-02-12 02:31:57 +0100201}
202
203
Yann Collet1496c3d2016-12-18 11:58:23 +0100204static int g_tooLargeSamples = 0;
205static U64 DiB_getTotalCappedFileSize(const char** fileNamesTable, unsigned nbFiles)
206{
207 U64 total = 0;
208 unsigned n;
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);
214 }
215 return total;
216}
217
218
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700219/*! ZDICT_trainFromBuffer_unsafe_legacy() :
Yann Collet6f3acba2016-02-12 20:19:48 +0100220 Strictly Internal use only !!
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700221 Same as ZDICT_trainFromBuffer_legacy(), but does not control `samplesBuffer`.
Yann Collet6f3acba2016-02-12 20:19:48 +0100222 `samplesBuffer` must be followed by noisy guard band to avoid out-of-buffer reads.
223 @return : size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
224 or an error code.
225*/
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700226size_t ZDICT_trainFromBuffer_unsafe_legacy(void* dictBuffer, size_t dictBufferCapacity,
227 const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
228 ZDICT_legacy_params_t parameters);
Yann Collet6f3acba2016-02-12 20:19:48 +0100229
230
Yann Collet71eafdd2016-02-12 02:31:57 +0100231int DiB_trainFromFiles(const char* dictFileName, unsigned maxDictSize,
232 const char** fileNamesTable, unsigned nbFiles,
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700233 ZDICT_legacy_params_t *params, ZDICT_cover_params_t *coverParams,
Nick Terrelldf8415c2016-12-31 21:08:24 -0800234 int optimizeCover)
Yann Collet71eafdd2016-02-12 02:31:57 +0100235{
Yann Collet290aaa72016-05-30 21:18:52 +0200236 void* const dictBuffer = malloc(maxDictSize);
237 size_t* const fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t));
Yann Collet1496c3d2016-12-18 11:58:23 +0100238 unsigned long long const totalSizeToLoad = DiB_getTotalCappedFileSize(fileNamesTable, nbFiles);
Nick Terrellc220d4c2017-01-09 16:49:04 -0800239 size_t const memMult = params ? MEMMULT : COVER_MEMMULT;
240 size_t const maxMem = DiB_findMaxMem(totalSizeToLoad * memMult) / memMult;
Yann Colletd46ecb52016-12-17 16:28:12 +0100241 size_t benchedSize = (size_t) MIN ((unsigned long long)maxMem, totalSizeToLoad);
Yann Collet290aaa72016-05-30 21:18:52 +0200242 void* const srcBuffer = malloc(benchedSize+NOISELENGTH);
Yann Collet71eafdd2016-02-12 02:31:57 +0100243 int result = 0;
244
Yann Collet290aaa72016-05-30 21:18:52 +0200245 /* Checks */
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700246 if (params) g_displayLevel = params->zParams.notificationLevel;
247 else if (coverParams) g_displayLevel = coverParams->zParams.notificationLevel;
Nick Terrelldf8415c2016-12-31 21:08:24 -0800248 else EXM_THROW(13, "Neither dictionary algorith selected"); /* should not happen */
Yann Collet290aaa72016-05-30 21:18:52 +0200249 if ((!fileSizes) || (!srcBuffer) || (!dictBuffer)) EXM_THROW(12, "not enough memory for DiB_trainFiles"); /* should not happen */
Yann Collet1496c3d2016-12-18 11:58:23 +0100250 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);
254 }
255 if ((nbFiles < 5) || (totalSizeToLoad < 9 * (unsigned long long)maxDictSize)) {
Yann Collet49d105c2016-08-18 15:02:11 +0200256 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");
Yann Colletdd25a272016-07-27 12:35:29 +0200261 }
Yann Collet290aaa72016-05-30 21:18:52 +0200262
Yann Collet71eafdd2016-02-12 02:31:57 +0100263 /* init */
Yann Collet71eafdd2016-02-12 02:31:57 +0100264 if (benchedSize < totalSizeToLoad)
265 DISPLAYLEVEL(1, "Not enough memory; training on %u MB only...\n", (unsigned)(benchedSize >> 20));
266
Yann Collet71eafdd2016-02-12 02:31:57 +0100267 /* Load input buffer */
Nick Terrelldf8415c2016-12-31 21:08:24 -0800268 DISPLAYLEVEL(3, "Shuffling input files\n");
269 DiB_shuffle(fileNamesTable, nbFiles);
Yann Colletbcb5f772016-07-06 15:41:03 +0200270 nbFiles = DiB_loadFiles(srcBuffer, &benchedSize, fileSizes, fileNamesTable, nbFiles);
Yann Collet71eafdd2016-02-12 02:31:57 +0100271
Nick Terrelldf8415c2016-12-31 21:08:24 -0800272 {
273 size_t dictSize;
274 if (params) {
275 DiB_fillNoise((char*)srcBuffer + benchedSize, NOISELENGTH); /* guard band, for end of buffer condition */
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700276 dictSize = ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, maxDictSize,
277 srcBuffer, fileSizes, nbFiles,
278 *params);
Nick Terrelldf8415c2016-12-31 21:08:24 -0800279 } else if (optimizeCover) {
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700280 dictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, maxDictSize,
281 srcBuffer, fileSizes, nbFiles,
282 coverParams);
Nick Terrelldf8415c2016-12-31 21:08:24 -0800283 if (!ZDICT_isError(dictSize)) {
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700284 DISPLAYLEVEL(2, "k=%u\nd=%u\nsteps=%u\n", coverParams->k, coverParams->d, coverParams->steps);
Nick Terrelldf8415c2016-12-31 21:08:24 -0800285 }
286 } else {
Nick Terrell5b7fd7c2017-06-26 21:07:14 -0700287 dictSize =
288 ZDICT_trainFromBuffer_cover(dictBuffer, maxDictSize, srcBuffer,
289 fileSizes, nbFiles, *coverParams);
Nick Terrelldf8415c2016-12-31 21:08:24 -0800290 }
Yann Collet290aaa72016-05-30 21:18:52 +0200291 if (ZDICT_isError(dictSize)) {
292 DISPLAYLEVEL(1, "dictionary training failed : %s \n", ZDICT_getErrorName(dictSize)); /* should not happen */
293 result = 1;
294 goto _cleanup;
295 }
296 /* save dict */
297 DISPLAYLEVEL(2, "Save dictionary of size %u into file %s \n", (U32)dictSize, dictFileName);
298 DiB_saveDict(dictFileName, dictBuffer, dictSize);
Yann Collet71eafdd2016-02-12 02:31:57 +0100299 }
300
Yann Collet71eafdd2016-02-12 02:31:57 +0100301 /* clean up */
302_cleanup:
303 free(srcBuffer);
304 free(dictBuffer);
305 free(fileSizes);
306 return result;
307}