blob: fa4241b14a41d7903398426559916e90d8ec02e8 [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
Yann Collet71eafdd2016-02-12 02:31:57 +010012/*-*************************************
13* Includes
14***************************************/
inikep13c84242016-05-05 13:58:56 +020015#include "util.h" /* Compiler options, UTIL_GetFileSize, UTIL_getTotalFileSize */
Yann Collet71eafdd2016-02-12 02:31:57 +010016#include <stdlib.h> /* malloc, free */
17#include <string.h> /* memset */
18#include <stdio.h> /* fprintf, fopen, ftello64 */
inikep37337972016-05-10 14:22:55 +020019#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
Yann Colleta3d03a32016-07-06 16:27:17 +020020#include <errno.h> /* errno */
Yann Collet71eafdd2016-02-12 02:31:57 +010021
22#include "mem.h" /* read */
23#include "error_private.h"
inikep23a08892016-04-22 12:43:18 +020024#include "dibio.h"
Yann Collet71eafdd2016-02-12 02:31:57 +010025
26
27/*-*************************************
28* Constants
29***************************************/
30#define KB *(1 <<10)
31#define MB *(1 <<20)
32#define GB *(1U<<30)
33
Yann Collet1496c3d2016-12-18 11:58:23 +010034#define SAMPLESIZE_MAX (128 KB)
35#define MEMMULT 11 /* rough estimation : memory cost to analyze 1 byte of sample */
Yann Collet71eafdd2016-02-12 02:31:57 +010036static const size_t maxMemory = (sizeof(size_t) == 4) ? (2 GB - 64 MB) : ((size_t)(512 MB) << sizeof(size_t));
37
38#define NOISELENGTH 32
Yann Collet71eafdd2016-02-12 02:31:57 +010039
40
41/*-*************************************
42* Console display
43***************************************/
44#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
45#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
46static unsigned g_displayLevel = 0; /* 0 : no display; 1: errors; 2: default; 4: full information */
Yann Collet71eafdd2016-02-12 02:31:57 +010047
Yann Colletf6ca09b2016-05-09 04:44:45 +020048#define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
Yann Colletbcb5f772016-07-06 15:41:03 +020049 if ((DIB_clockSpan(g_time) > refreshRate) || (g_displayLevel>=4)) \
Yann Colletf6ca09b2016-05-09 04:44:45 +020050 { g_time = clock(); DISPLAY(__VA_ARGS__); \
51 if (g_displayLevel>=4) fflush(stdout); } }
Yann Colletbcb5f772016-07-06 15:41:03 +020052static const clock_t refreshRate = CLOCKS_PER_SEC * 2 / 10;
Yann Colletf6ca09b2016-05-09 04:44:45 +020053static clock_t g_time = 0;
54
Yann Colletbcb5f772016-07-06 15:41:03 +020055static clock_t DIB_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
Yann Colletf6ca09b2016-05-09 04:44:45 +020056
Yann Collet71eafdd2016-02-12 02:31:57 +010057
58/*-*************************************
59* Exceptions
60***************************************/
61#ifndef DEBUG
62# define DEBUG 0
63#endif
64#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
65#define EXM_THROW(error, ...) \
66{ \
67 DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
68 DISPLAYLEVEL(1, "Error %i : ", error); \
69 DISPLAYLEVEL(1, __VA_ARGS__); \
70 DISPLAYLEVEL(1, "\n"); \
71 exit(error); \
72}
73
74
75/* ********************************************************
76* Helper functions
77**********************************************************/
78unsigned DiB_isError(size_t errorCode) { return ERR_isError(errorCode); }
79
80const char* DiB_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
81
Yann Colletbcb5f772016-07-06 15:41:03 +020082#define MIN(a,b) ( (a) < (b) ? (a) : (b) )
83
Yann Collet71eafdd2016-02-12 02:31:57 +010084
85/* ********************************************************
86* File related operations
87**********************************************************/
Yann Collet290aaa72016-05-30 21:18:52 +020088/** DiB_loadFiles() :
89* @return : nb of files effectively loaded into `buffer` */
Yann Colletbcb5f772016-07-06 15:41:03 +020090static unsigned DiB_loadFiles(void* buffer, size_t* bufferSizePtr,
Yann Collet290aaa72016-05-30 21:18:52 +020091 size_t* fileSizes,
92 const char** fileNamesTable, unsigned nbFiles)
Yann Collet71eafdd2016-02-12 02:31:57 +010093{
Yann Collet290aaa72016-05-30 21:18:52 +020094 char* const buff = (char*)buffer;
Yann Collet71eafdd2016-02-12 02:31:57 +010095 size_t pos = 0;
96 unsigned n;
97
98 for (n=0; n<nbFiles; n++) {
Yann Colletbcb5f772016-07-06 15:41:03 +020099 const char* const fileName = fileNamesTable[n];
100 unsigned long long const fs64 = UTIL_getFileSize(fileName);
Yann Collet1496c3d2016-12-18 11:58:23 +0100101 size_t const fileSize = (size_t) MIN(fs64, SAMPLESIZE_MAX);
Yann Colletbcb5f772016-07-06 15:41:03 +0200102 if (fileSize > *bufferSizePtr-pos) break;
103 { FILE* const f = fopen(fileName, "rb");
104 if (f==NULL) EXM_THROW(10, "zstd: dictBuilder: %s %s ", fileName, strerror(errno));
105 DISPLAYUPDATE(2, "Loading %s... \r", fileName);
106 { size_t const readSize = fread(buff+pos, 1, fileSize, f);
107 if (readSize != fileSize) EXM_THROW(11, "Pb reading %s", fileName);
108 pos += readSize; }
109 fileSizes[n] = fileSize;
110 fclose(f);
111 } }
112 *bufferSizePtr = pos;
Yann Collet290aaa72016-05-30 21:18:52 +0200113 return n;
Yann Collet71eafdd2016-02-12 02:31:57 +0100114}
115
116
117/*-********************************************************
118* Dictionary training functions
119**********************************************************/
120static size_t DiB_findMaxMem(unsigned long long requiredMem)
121{
Yann Collet290aaa72016-05-30 21:18:52 +0200122 size_t const step = 8 MB;
Yann Collet71eafdd2016-02-12 02:31:57 +0100123 void* testmem = NULL;
124
125 requiredMem = (((requiredMem >> 23) + 1) << 23);
Yann Colletbcb5f772016-07-06 15:41:03 +0200126 requiredMem += step;
Yann Collet71eafdd2016-02-12 02:31:57 +0100127 if (requiredMem > maxMemory) requiredMem = maxMemory;
128
129 while (!testmem) {
Yann Collet71eafdd2016-02-12 02:31:57 +0100130 testmem = malloc((size_t)requiredMem);
Yann Colletbcb5f772016-07-06 15:41:03 +0200131 requiredMem -= step;
Yann Collet71eafdd2016-02-12 02:31:57 +0100132 }
133
134 free(testmem);
Yann Colletbcb5f772016-07-06 15:41:03 +0200135 return (size_t)requiredMem;
Yann Collet71eafdd2016-02-12 02:31:57 +0100136}
137
138
139static void DiB_fillNoise(void* buffer, size_t length)
140{
Yann Colletbcb5f772016-07-06 15:41:03 +0200141 unsigned const prime1 = 2654435761U;
142 unsigned const prime2 = 2246822519U;
143 unsigned acc = prime1;
Yann Collet71eafdd2016-02-12 02:31:57 +0100144 size_t p=0;;
145
146 for (p=0; p<length; p++) {
Yann Colletbcb5f772016-07-06 15:41:03 +0200147 acc *= prime2;
Yann Collet71eafdd2016-02-12 02:31:57 +0100148 ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
149 }
150}
151
152
153static void DiB_saveDict(const char* dictFileName,
154 const void* buff, size_t buffSize)
155{
Yann Collet290aaa72016-05-30 21:18:52 +0200156 FILE* const f = fopen(dictFileName, "wb");
Yann Collet71eafdd2016-02-12 02:31:57 +0100157 if (f==NULL) EXM_THROW(3, "cannot open %s ", dictFileName);
158
Yann Colletf6ca09b2016-05-09 04:44:45 +0200159 { size_t const n = fwrite(buff, 1, buffSize, f);
160 if (n!=buffSize) EXM_THROW(4, "%s : write error", dictFileName) }
Yann Collet71eafdd2016-02-12 02:31:57 +0100161
Yann Colletf6ca09b2016-05-09 04:44:45 +0200162 { size_t const n = (size_t)fclose(f);
163 if (n!=0) EXM_THROW(5, "%s : flush error", dictFileName) }
Yann Collet71eafdd2016-02-12 02:31:57 +0100164}
165
166
Yann Collet1496c3d2016-12-18 11:58:23 +0100167static int g_tooLargeSamples = 0;
168static U64 DiB_getTotalCappedFileSize(const char** fileNamesTable, unsigned nbFiles)
169{
170 U64 total = 0;
171 unsigned n;
172 for (n=0; n<nbFiles; n++) {
173 U64 const fileSize = UTIL_getFileSize(fileNamesTable[n]);
174 U64 const cappedFileSize = MIN(fileSize, SAMPLESIZE_MAX);
175 total += cappedFileSize;
176 g_tooLargeSamples |= (fileSize > 2*SAMPLESIZE_MAX);
177 }
178 return total;
179}
180
181
Yann Collet6f3acba2016-02-12 20:19:48 +0100182/*! ZDICT_trainFromBuffer_unsafe() :
183 Strictly Internal use only !!
184 Same as ZDICT_trainFromBuffer_advanced(), but does not control `samplesBuffer`.
185 `samplesBuffer` must be followed by noisy guard band to avoid out-of-buffer reads.
186 @return : size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
187 or an error code.
188*/
189size_t ZDICT_trainFromBuffer_unsafe(void* dictBuffer, size_t dictBufferCapacity,
190 const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
191 ZDICT_params_t parameters);
192
193
Yann Collet71eafdd2016-02-12 02:31:57 +0100194int DiB_trainFromFiles(const char* dictFileName, unsigned maxDictSize,
195 const char** fileNamesTable, unsigned nbFiles,
196 ZDICT_params_t params)
197{
Yann Collet290aaa72016-05-30 21:18:52 +0200198 void* const dictBuffer = malloc(maxDictSize);
199 size_t* const fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t));
Yann Collet1496c3d2016-12-18 11:58:23 +0100200 unsigned long long const totalSizeToLoad = DiB_getTotalCappedFileSize(fileNamesTable, nbFiles);
Yann Collet290aaa72016-05-30 21:18:52 +0200201 size_t const maxMem = DiB_findMaxMem(totalSizeToLoad * MEMMULT) / MEMMULT;
Yann Colletd46ecb52016-12-17 16:28:12 +0100202 size_t benchedSize = (size_t) MIN ((unsigned long long)maxMem, totalSizeToLoad);
Yann Collet290aaa72016-05-30 21:18:52 +0200203 void* const srcBuffer = malloc(benchedSize+NOISELENGTH);
Yann Collet71eafdd2016-02-12 02:31:57 +0100204 int result = 0;
205
Yann Collet290aaa72016-05-30 21:18:52 +0200206 /* Checks */
207 if ((!fileSizes) || (!srcBuffer) || (!dictBuffer)) EXM_THROW(12, "not enough memory for DiB_trainFiles"); /* should not happen */
Yann Colletdd25a272016-07-27 12:35:29 +0200208 g_displayLevel = params.notificationLevel;
Yann Collet1496c3d2016-12-18 11:58:23 +0100209 if (g_tooLargeSamples) {
210 DISPLAYLEVEL(2, "! Warning : some samples are very large \n");
211 DISPLAYLEVEL(2, "! Note that dictionary is only useful for small files or beginning of large files. \n");
212 DISPLAYLEVEL(2, "! As a consequence, only the first %u bytes of each file are loaded \n", SAMPLESIZE_MAX);
213 }
214 if ((nbFiles < 5) || (totalSizeToLoad < 9 * (unsigned long long)maxDictSize)) {
Yann Collet49d105c2016-08-18 15:02:11 +0200215 DISPLAYLEVEL(2, "! Warning : nb of samples too low for proper processing ! \n");
216 DISPLAYLEVEL(2, "! Please provide _one file per sample_. \n");
217 DISPLAYLEVEL(2, "! Do not concatenate samples together into a single file, \n");
218 DISPLAYLEVEL(2, "! as dictBuilder will be unable to find the beginning of each sample, \n");
219 DISPLAYLEVEL(2, "! resulting in poor dictionary quality. \n");
Yann Colletdd25a272016-07-27 12:35:29 +0200220 }
Yann Collet290aaa72016-05-30 21:18:52 +0200221
Yann Collet71eafdd2016-02-12 02:31:57 +0100222 /* init */
Yann Collet71eafdd2016-02-12 02:31:57 +0100223 if (benchedSize < totalSizeToLoad)
224 DISPLAYLEVEL(1, "Not enough memory; training on %u MB only...\n", (unsigned)(benchedSize >> 20));
225
Yann Collet71eafdd2016-02-12 02:31:57 +0100226 /* Load input buffer */
Yann Colletbcb5f772016-07-06 15:41:03 +0200227 nbFiles = DiB_loadFiles(srcBuffer, &benchedSize, fileSizes, fileNamesTable, nbFiles);
Yann Collet71eafdd2016-02-12 02:31:57 +0100228 DiB_fillNoise((char*)srcBuffer + benchedSize, NOISELENGTH); /* guard band, for end of buffer condition */
229
Yann Collet290aaa72016-05-30 21:18:52 +0200230 { size_t const dictSize = ZDICT_trainFromBuffer_unsafe(dictBuffer, maxDictSize,
231 srcBuffer, fileSizes, nbFiles,
232 params);
233 if (ZDICT_isError(dictSize)) {
234 DISPLAYLEVEL(1, "dictionary training failed : %s \n", ZDICT_getErrorName(dictSize)); /* should not happen */
235 result = 1;
236 goto _cleanup;
237 }
238 /* save dict */
239 DISPLAYLEVEL(2, "Save dictionary of size %u into file %s \n", (U32)dictSize, dictFileName);
240 DiB_saveDict(dictFileName, dictBuffer, dictSize);
Yann Collet71eafdd2016-02-12 02:31:57 +0100241 }
242
Yann Collet71eafdd2016-02-12 02:31:57 +0100243 /* clean up */
244_cleanup:
245 free(srcBuffer);
246 free(dictBuffer);
247 free(fileSizes);
248 return result;
249}