blob: 646fe2c60d35ddd8b82a6e90a220c25982bfb1dc [file] [log] [blame]
Yann Collet71eafdd2016-02-12 02:31:57 +01001/*
2 dibio - I/O API for dictionary builder
3 Copyright (C) Yann Collet 2016
4
5 GPL v2 License
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License along
18 with this program; if not, write to the Free Software Foundation, Inc.,
19 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 You can contact the author at :
22 - zstd homepage : http://www.zstd.net/
23*/
24
25/*-**************************************
26* Compiler Options
27****************************************/
28/* Disable some Visual warning messages */
29#ifdef _MSC_VER
30# define _CRT_SECURE_NO_WARNINGS /* fopen */
31# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
32#endif
33
34/* Unix Large Files support (>4GB) */
35#define _FILE_OFFSET_BITS 64
36#if (defined(__sun__) && (!defined(__LP64__))) /* Sun Solaris 32-bits requires specific definitions */
37# define _LARGEFILE_SOURCE
38#elif ! defined(__LP64__) /* No point defining Large file for 64 bit */
39# define _LARGEFILE64_SOURCE
40#endif
41
42
43/*-*************************************
44* Includes
45***************************************/
46#include <stdlib.h> /* malloc, free */
47#include <string.h> /* memset */
48#include <stdio.h> /* fprintf, fopen, ftello64 */
49#include <sys/types.h> /* stat64 */
50#include <sys/stat.h> /* stat64 */
51#include <time.h> /* clock */
52
53#include "mem.h" /* read */
54#include "error_private.h"
Yann Colletf4c9d752016-02-12 18:45:02 +010055#include "zdict_static.h"
56
Yann Collet71eafdd2016-02-12 02:31:57 +010057
58/*-*************************************
59* Compiler specifics
60***************************************/
61#if !defined(S_ISREG)
62# define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)
63#endif
64
65
66/*-*************************************
67* Constants
68***************************************/
69#define KB *(1 <<10)
70#define MB *(1 <<20)
71#define GB *(1U<<30)
72
73#define DICTLISTSIZE 10000
74#define MEMMULT 11
75static const size_t maxMemory = (sizeof(size_t) == 4) ? (2 GB - 64 MB) : ((size_t)(512 MB) << sizeof(size_t));
76
77#define NOISELENGTH 32
78#define PRIME1 2654435761U
79#define PRIME2 2246822519U
80
81
82/*-*************************************
83* Console display
84***************************************/
85#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
86#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
87static unsigned g_displayLevel = 0; /* 0 : no display; 1: errors; 2: default; 4: full information */
Yann Collet71eafdd2016-02-12 02:31:57 +010088
Yann Collet71eafdd2016-02-12 02:31:57 +010089
90/*-*************************************
91* Exceptions
92***************************************/
93#ifndef DEBUG
94# define DEBUG 0
95#endif
96#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
97#define EXM_THROW(error, ...) \
98{ \
99 DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
100 DISPLAYLEVEL(1, "Error %i : ", error); \
101 DISPLAYLEVEL(1, __VA_ARGS__); \
102 DISPLAYLEVEL(1, "\n"); \
103 exit(error); \
104}
105
106
107/* ********************************************************
108* Helper functions
109**********************************************************/
110unsigned DiB_isError(size_t errorCode) { return ERR_isError(errorCode); }
111
112const char* DiB_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
113
114
115/* ********************************************************
116* File related operations
117**********************************************************/
118static unsigned long long DiB_getFileSize(const char* infilename)
119{
120 int r;
121#if defined(_MSC_VER)
122 struct _stat64 statbuf;
123 r = _stat64(infilename, &statbuf);
124#else
125 struct stat statbuf;
126 r = stat(infilename, &statbuf);
127#endif
128 if (r || !S_ISREG(statbuf.st_mode)) return 0; /* No good... */
129 return (unsigned long long)statbuf.st_size;
130}
131
132
133static unsigned long long DiB_getTotalFileSize(const char** fileNamesTable, unsigned nbFiles)
134{
135 unsigned long long total = 0;
136 unsigned n;
137 for (n=0; n<nbFiles; n++)
138 total += DiB_getFileSize(fileNamesTable[n]);
139 return total;
140}
141
142
143static void DiB_loadFiles(void* buffer, size_t bufferSize,
144 size_t* fileSizes,
145 const char** fileNamesTable, unsigned nbFiles)
146{
147 char* buff = (char*)buffer;
148 size_t pos = 0;
149 unsigned n;
150
151 for (n=0; n<nbFiles; n++) {
152 size_t readSize;
153 unsigned long long fileSize = DiB_getFileSize(fileNamesTable[n]);
154 FILE* f = fopen(fileNamesTable[n], "rb");
155 if (f==NULL) EXM_THROW(10, "impossible to open file %s", fileNamesTable[n]);
156 DISPLAYLEVEL(2, "Loading %s... \r", fileNamesTable[n]);
157 if (fileSize > bufferSize-pos) fileSize = 0; /* stop there, not enough memory to load all files */
158 readSize = fread(buff+pos, 1, (size_t)fileSize, f);
159 if (readSize != (size_t)fileSize) EXM_THROW(11, "could not read %s", fileNamesTable[n]);
160 pos += readSize;
161 fileSizes[n] = (size_t)fileSize;
162 fclose(f);
163 }
164}
165
166
167/*-********************************************************
168* Dictionary training functions
169**********************************************************/
170static size_t DiB_findMaxMem(unsigned long long requiredMem)
171{
172 size_t step = 8 MB;
173 void* testmem = NULL;
174
175 requiredMem = (((requiredMem >> 23) + 1) << 23);
176 requiredMem += 2 * step;
177 if (requiredMem > maxMemory) requiredMem = maxMemory;
178
179 while (!testmem) {
180 requiredMem -= step;
181 testmem = malloc((size_t)requiredMem);
182 }
183
184 free(testmem);
185 return (size_t)(requiredMem - step);
186}
187
188
189static void DiB_fillNoise(void* buffer, size_t length)
190{
191 unsigned acc = PRIME1;
192 size_t p=0;;
193
194 for (p=0; p<length; p++) {
195 acc *= PRIME2;
196 ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
197 }
198}
199
200
201static void DiB_saveDict(const char* dictFileName,
202 const void* buff, size_t buffSize)
203{
204 FILE* f;
205 size_t n;
206
207 f = fopen(dictFileName, "wb");
208 if (f==NULL) EXM_THROW(3, "cannot open %s ", dictFileName);
209
210 n = fwrite(buff, 1, buffSize, f);
211 if (n!=buffSize) EXM_THROW(4, "%s : write error", dictFileName)
212
213 n = (size_t)fclose(f);
214 if (n!=0) EXM_THROW(5, "%s : flush error", dictFileName)
215}
216
217
Yann Collet6f3acba2016-02-12 20:19:48 +0100218/*! ZDICT_trainFromBuffer_unsafe() :
219 Strictly Internal use only !!
220 Same as ZDICT_trainFromBuffer_advanced(), but does not control `samplesBuffer`.
221 `samplesBuffer` must be followed by noisy guard band to avoid out-of-buffer reads.
222 @return : size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
223 or an error code.
224*/
225size_t ZDICT_trainFromBuffer_unsafe(void* dictBuffer, size_t dictBufferCapacity,
226 const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
227 ZDICT_params_t parameters);
228
229
Yann Collet71eafdd2016-02-12 02:31:57 +0100230int DiB_trainFromFiles(const char* dictFileName, unsigned maxDictSize,
231 const char** fileNamesTable, unsigned nbFiles,
232 ZDICT_params_t params)
233{
234 void* srcBuffer;
235 size_t benchedSize;
236 size_t* fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t));
237 unsigned long long totalSizeToLoad = DiB_getTotalFileSize(fileNamesTable, nbFiles);
238 void* dictBuffer = malloc(maxDictSize);
239 size_t dictSize;
240 int result = 0;
241
242 /* init */
Yann Collet6f3acba2016-02-12 20:19:48 +0100243 g_displayLevel = params.notificationLevel;
Yann Collet71eafdd2016-02-12 02:31:57 +0100244 benchedSize = DiB_findMaxMem(totalSizeToLoad * MEMMULT) / MEMMULT;
245 if ((unsigned long long)benchedSize > totalSizeToLoad) benchedSize = (size_t)totalSizeToLoad;
246 if (benchedSize < totalSizeToLoad)
247 DISPLAYLEVEL(1, "Not enough memory; training on %u MB only...\n", (unsigned)(benchedSize >> 20));
248
249 /* Memory allocation & restrictions */
250 srcBuffer = malloc(benchedSize+NOISELENGTH); /* + noise */
251 if ((!fileSizes) || (!srcBuffer) || (!dictBuffer)) EXM_THROW(12, "not enough memory for DiB_trainFiles"); /* should not happen */
252
253 /* Load input buffer */
254 DiB_loadFiles(srcBuffer, benchedSize, fileSizes, fileNamesTable, nbFiles);
255 DiB_fillNoise((char*)srcBuffer + benchedSize, NOISELENGTH); /* guard band, for end of buffer condition */
256
257 /* call buffer version */
258 dictSize = ZDICT_trainFromBuffer_unsafe(dictBuffer, maxDictSize,
259 srcBuffer, fileSizes, nbFiles,
260 params);
261 if (ZDICT_isError(dictSize)) {
262 DISPLAYLEVEL(1, "dictionary training failed : %s", ZDICT_getErrorName(dictSize)); /* should not happen */
263 result = 1;
264 goto _cleanup;
265 }
266
267 /* save dict */
268 DISPLAYLEVEL(2, "Save dictionary of size %u into file %s \n", (U32)dictSize, dictFileName);
269 DiB_saveDict(dictFileName, dictBuffer, dictSize);
270
271 /* clean up */
272_cleanup:
273 free(srcBuffer);
274 free(dictBuffer);
275 free(fileSizes);
276 return result;
277}