xref: /freebsd/sys/contrib/zstd/lib/dictBuilder/zdict.c (revision 37f1f2684f2670b204080ef2d6c303becd28545f)
10c16b537SWarner Losh /*
2*37f1f268SConrad Meyer  * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
30c16b537SWarner Losh  * All rights reserved.
40c16b537SWarner Losh  *
50c16b537SWarner Losh  * This source code is licensed under both the BSD-style license (found in the
60c16b537SWarner Losh  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
70c16b537SWarner Losh  * in the COPYING file in the root directory of this source tree).
80c16b537SWarner Losh  * You may select, at your option, one of the above-listed licenses.
90c16b537SWarner Losh  */
100c16b537SWarner Losh 
110c16b537SWarner Losh 
120c16b537SWarner Losh /*-**************************************
130c16b537SWarner Losh *  Tuning parameters
140c16b537SWarner Losh ****************************************/
150c16b537SWarner Losh #define MINRATIO 4   /* minimum nb of apparition to be selected in dictionary */
160c16b537SWarner Losh #define ZDICT_MAX_SAMPLES_SIZE (2000U << 20)
170c16b537SWarner Losh #define ZDICT_MIN_SAMPLES_SIZE (ZDICT_CONTENTSIZE_MIN * MINRATIO)
180c16b537SWarner Losh 
190c16b537SWarner Losh 
200c16b537SWarner Losh /*-**************************************
210c16b537SWarner Losh *  Compiler Options
220c16b537SWarner Losh ****************************************/
230c16b537SWarner Losh /* Unix Large Files support (>4GB) */
240c16b537SWarner Losh #define _FILE_OFFSET_BITS 64
250c16b537SWarner Losh #if (defined(__sun__) && (!defined(__LP64__)))   /* Sun Solaris 32-bits requires specific definitions */
260c16b537SWarner Losh #  define _LARGEFILE_SOURCE
270c16b537SWarner Losh #elif ! defined(__LP64__)                        /* No point defining Large file for 64 bit */
280c16b537SWarner Losh #  define _LARGEFILE64_SOURCE
290c16b537SWarner Losh #endif
300c16b537SWarner Losh 
310c16b537SWarner Losh 
320c16b537SWarner Losh /*-*************************************
330c16b537SWarner Losh *  Dependencies
340c16b537SWarner Losh ***************************************/
350c16b537SWarner Losh #include <stdlib.h>        /* malloc, free */
360c16b537SWarner Losh #include <string.h>        /* memset */
370c16b537SWarner Losh #include <stdio.h>         /* fprintf, fopen, ftello64 */
380c16b537SWarner Losh #include <time.h>          /* clock */
390c16b537SWarner Losh 
40*37f1f268SConrad Meyer #include "../common/mem.h"           /* read */
41*37f1f268SConrad Meyer #include "../common/fse.h"           /* FSE_normalizeCount, FSE_writeNCount */
420c16b537SWarner Losh #define HUF_STATIC_LINKING_ONLY
43*37f1f268SConrad Meyer #include "../common/huf.h"           /* HUF_buildCTable, HUF_writeCTable */
44*37f1f268SConrad Meyer #include "../common/zstd_internal.h" /* includes zstd.h */
45*37f1f268SConrad Meyer #include "../common/xxhash.h"        /* XXH64 */
460c16b537SWarner Losh #include "divsufsort.h"
470c16b537SWarner Losh #ifndef ZDICT_STATIC_LINKING_ONLY
480c16b537SWarner Losh #  define ZDICT_STATIC_LINKING_ONLY
490c16b537SWarner Losh #endif
500c16b537SWarner Losh #include "zdict.h"
51*37f1f268SConrad Meyer #include "../compress/zstd_compress_internal.h" /* ZSTD_loadCEntropy() */
520c16b537SWarner Losh 
530c16b537SWarner Losh 
540c16b537SWarner Losh /*-*************************************
550c16b537SWarner Losh *  Constants
560c16b537SWarner Losh ***************************************/
570c16b537SWarner Losh #define KB *(1 <<10)
580c16b537SWarner Losh #define MB *(1 <<20)
590c16b537SWarner Losh #define GB *(1U<<30)
600c16b537SWarner Losh 
610c16b537SWarner Losh #define DICTLISTSIZE_DEFAULT 10000
620c16b537SWarner Losh 
630c16b537SWarner Losh #define NOISELENGTH 32
640c16b537SWarner Losh 
650c16b537SWarner Losh static const int g_compressionLevel_default = 3;
660c16b537SWarner Losh static const U32 g_selectivity_default = 9;
670c16b537SWarner Losh 
680c16b537SWarner Losh 
690c16b537SWarner Losh /*-*************************************
700c16b537SWarner Losh *  Console display
710c16b537SWarner Losh ***************************************/
720c16b537SWarner Losh #define DISPLAY(...)         { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }
730c16b537SWarner Losh #define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); }    /* 0 : no display;   1: errors;   2: default;  3: details;  4: debug */
740c16b537SWarner Losh 
750c16b537SWarner Losh static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
760c16b537SWarner Losh 
770c16b537SWarner Losh static void ZDICT_printHex(const void* ptr, size_t length)
780c16b537SWarner Losh {
790c16b537SWarner Losh     const BYTE* const b = (const BYTE*)ptr;
800c16b537SWarner Losh     size_t u;
810c16b537SWarner Losh     for (u=0; u<length; u++) {
820c16b537SWarner Losh         BYTE c = b[u];
830c16b537SWarner Losh         if (c<32 || c>126) c = '.';   /* non-printable char */
840c16b537SWarner Losh         DISPLAY("%c", c);
850c16b537SWarner Losh     }
860c16b537SWarner Losh }
870c16b537SWarner Losh 
880c16b537SWarner Losh 
890c16b537SWarner Losh /*-********************************************************
900c16b537SWarner Losh *  Helper functions
910c16b537SWarner Losh **********************************************************/
920c16b537SWarner Losh unsigned ZDICT_isError(size_t errorCode) { return ERR_isError(errorCode); }
930c16b537SWarner Losh 
940c16b537SWarner Losh const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
950c16b537SWarner Losh 
960c16b537SWarner Losh unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize)
970c16b537SWarner Losh {
980c16b537SWarner Losh     if (dictSize < 8) return 0;
990c16b537SWarner Losh     if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;
1000c16b537SWarner Losh     return MEM_readLE32((const char*)dictBuffer + 4);
1010c16b537SWarner Losh }
1020c16b537SWarner Losh 
103*37f1f268SConrad Meyer size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize)
104*37f1f268SConrad Meyer {
105*37f1f268SConrad Meyer     size_t headerSize;
106*37f1f268SConrad Meyer     if (dictSize <= 8 || MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return ERROR(dictionary_corrupted);
107*37f1f268SConrad Meyer 
108*37f1f268SConrad Meyer     {   unsigned offcodeMaxValue = MaxOff;
109*37f1f268SConrad Meyer         ZSTD_compressedBlockState_t* bs = (ZSTD_compressedBlockState_t*)malloc(sizeof(ZSTD_compressedBlockState_t));
110*37f1f268SConrad Meyer         U32* wksp = (U32*)malloc(HUF_WORKSPACE_SIZE);
111*37f1f268SConrad Meyer         short* offcodeNCount = (short*)malloc((MaxOff+1)*sizeof(short));
112*37f1f268SConrad Meyer         if (!bs || !wksp || !offcodeNCount) {
113*37f1f268SConrad Meyer             headerSize = ERROR(memory_allocation);
114*37f1f268SConrad Meyer         } else {
115*37f1f268SConrad Meyer             ZSTD_reset_compressedBlockState(bs);
116*37f1f268SConrad Meyer             headerSize = ZSTD_loadCEntropy(bs, wksp, offcodeNCount, &offcodeMaxValue, dictBuffer, dictSize);
117*37f1f268SConrad Meyer         }
118*37f1f268SConrad Meyer 
119*37f1f268SConrad Meyer         free(bs);
120*37f1f268SConrad Meyer         free(wksp);
121*37f1f268SConrad Meyer         free(offcodeNCount);
122*37f1f268SConrad Meyer     }
123*37f1f268SConrad Meyer 
124*37f1f268SConrad Meyer     return headerSize;
125*37f1f268SConrad Meyer }
1260c16b537SWarner Losh 
1270c16b537SWarner Losh /*-********************************************************
1280c16b537SWarner Losh *  Dictionary training functions
1290c16b537SWarner Losh **********************************************************/
130052d3c12SConrad Meyer static unsigned ZDICT_NbCommonBytes (size_t val)
1310c16b537SWarner Losh {
1320c16b537SWarner Losh     if (MEM_isLittleEndian()) {
1330c16b537SWarner Losh         if (MEM_64bits()) {
1340c16b537SWarner Losh #       if defined(_MSC_VER) && defined(_WIN64)
1350c16b537SWarner Losh             unsigned long r = 0;
1360c16b537SWarner Losh             _BitScanForward64( &r, (U64)val );
1370c16b537SWarner Losh             return (unsigned)(r>>3);
1380c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1390c16b537SWarner Losh             return (__builtin_ctzll((U64)val) >> 3);
1400c16b537SWarner Losh #       else
1410c16b537SWarner Losh             static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
1420c16b537SWarner Losh             return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
1430c16b537SWarner Losh #       endif
1440c16b537SWarner Losh         } else { /* 32 bits */
1450c16b537SWarner Losh #       if defined(_MSC_VER)
1460c16b537SWarner Losh             unsigned long r=0;
1470c16b537SWarner Losh             _BitScanForward( &r, (U32)val );
1480c16b537SWarner Losh             return (unsigned)(r>>3);
1490c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1500c16b537SWarner Losh             return (__builtin_ctz((U32)val) >> 3);
1510c16b537SWarner Losh #       else
1520c16b537SWarner Losh             static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
1530c16b537SWarner Losh             return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
1540c16b537SWarner Losh #       endif
1550c16b537SWarner Losh         }
1560c16b537SWarner Losh     } else {  /* Big Endian CPU */
1570c16b537SWarner Losh         if (MEM_64bits()) {
1580c16b537SWarner Losh #       if defined(_MSC_VER) && defined(_WIN64)
1590c16b537SWarner Losh             unsigned long r = 0;
1600c16b537SWarner Losh             _BitScanReverse64( &r, val );
1610c16b537SWarner Losh             return (unsigned)(r>>3);
1620c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1630c16b537SWarner Losh             return (__builtin_clzll(val) >> 3);
1640c16b537SWarner Losh #       else
1650c16b537SWarner Losh             unsigned r;
1660c16b537SWarner Losh             const unsigned n32 = sizeof(size_t)*4;   /* calculate this way due to compiler complaining in 32-bits mode */
1670c16b537SWarner Losh             if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
1680c16b537SWarner Losh             if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
1690c16b537SWarner Losh             r += (!val);
1700c16b537SWarner Losh             return r;
1710c16b537SWarner Losh #       endif
1720c16b537SWarner Losh         } else { /* 32 bits */
1730c16b537SWarner Losh #       if defined(_MSC_VER)
1740c16b537SWarner Losh             unsigned long r = 0;
1750c16b537SWarner Losh             _BitScanReverse( &r, (unsigned long)val );
1760c16b537SWarner Losh             return (unsigned)(r>>3);
1770c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
1780c16b537SWarner Losh             return (__builtin_clz((U32)val) >> 3);
1790c16b537SWarner Losh #       else
1800c16b537SWarner Losh             unsigned r;
1810c16b537SWarner Losh             if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
1820c16b537SWarner Losh             r += (!val);
1830c16b537SWarner Losh             return r;
1840c16b537SWarner Losh #       endif
1850c16b537SWarner Losh     }   }
1860c16b537SWarner Losh }
1870c16b537SWarner Losh 
1880c16b537SWarner Losh 
1890c16b537SWarner Losh /*! ZDICT_count() :
1900c16b537SWarner Losh     Count the nb of common bytes between 2 pointers.
1910c16b537SWarner Losh     Note : this function presumes end of buffer followed by noisy guard band.
1920c16b537SWarner Losh */
1930c16b537SWarner Losh static size_t ZDICT_count(const void* pIn, const void* pMatch)
1940c16b537SWarner Losh {
1950c16b537SWarner Losh     const char* const pStart = (const char*)pIn;
1960c16b537SWarner Losh     for (;;) {
1970c16b537SWarner Losh         size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
1980c16b537SWarner Losh         if (!diff) {
1990c16b537SWarner Losh             pIn = (const char*)pIn+sizeof(size_t);
2000c16b537SWarner Losh             pMatch = (const char*)pMatch+sizeof(size_t);
2010c16b537SWarner Losh             continue;
2020c16b537SWarner Losh         }
2030c16b537SWarner Losh         pIn = (const char*)pIn+ZDICT_NbCommonBytes(diff);
2040c16b537SWarner Losh         return (size_t)((const char*)pIn - pStart);
2050c16b537SWarner Losh     }
2060c16b537SWarner Losh }
2070c16b537SWarner Losh 
2080c16b537SWarner Losh 
2090c16b537SWarner Losh typedef struct {
2100c16b537SWarner Losh     U32 pos;
2110c16b537SWarner Losh     U32 length;
2120c16b537SWarner Losh     U32 savings;
2130c16b537SWarner Losh } dictItem;
2140c16b537SWarner Losh 
2150c16b537SWarner Losh static void ZDICT_initDictItem(dictItem* d)
2160c16b537SWarner Losh {
2170c16b537SWarner Losh     d->pos = 1;
2180c16b537SWarner Losh     d->length = 0;
2190c16b537SWarner Losh     d->savings = (U32)(-1);
2200c16b537SWarner Losh }
2210c16b537SWarner Losh 
2220c16b537SWarner Losh 
2230c16b537SWarner Losh #define LLIMIT 64          /* heuristic determined experimentally */
2240c16b537SWarner Losh #define MINMATCHLENGTH 7   /* heuristic determined experimentally */
2250c16b537SWarner Losh static dictItem ZDICT_analyzePos(
2260c16b537SWarner Losh                        BYTE* doneMarks,
2270c16b537SWarner Losh                        const int* suffix, U32 start,
2280c16b537SWarner Losh                        const void* buffer, U32 minRatio, U32 notificationLevel)
2290c16b537SWarner Losh {
2300c16b537SWarner Losh     U32 lengthList[LLIMIT] = {0};
2310c16b537SWarner Losh     U32 cumulLength[LLIMIT] = {0};
2320c16b537SWarner Losh     U32 savings[LLIMIT] = {0};
2330c16b537SWarner Losh     const BYTE* b = (const BYTE*)buffer;
2340c16b537SWarner Losh     size_t maxLength = LLIMIT;
2350c16b537SWarner Losh     size_t pos = suffix[start];
2360c16b537SWarner Losh     U32 end = start;
2370c16b537SWarner Losh     dictItem solution;
2380c16b537SWarner Losh 
2390c16b537SWarner Losh     /* init */
2400c16b537SWarner Losh     memset(&solution, 0, sizeof(solution));
2410c16b537SWarner Losh     doneMarks[pos] = 1;
2420c16b537SWarner Losh 
2430c16b537SWarner Losh     /* trivial repetition cases */
2440c16b537SWarner Losh     if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))
2450c16b537SWarner Losh        ||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))
2460c16b537SWarner Losh        ||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {
2470c16b537SWarner Losh         /* skip and mark segment */
24819fcbaf1SConrad Meyer         U16 const pattern16 = MEM_read16(b+pos+4);
24919fcbaf1SConrad Meyer         U32 u, patternEnd = 6;
25019fcbaf1SConrad Meyer         while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;
25119fcbaf1SConrad Meyer         if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;
25219fcbaf1SConrad Meyer         for (u=1; u<patternEnd; u++)
2530c16b537SWarner Losh             doneMarks[pos+u] = 1;
2540c16b537SWarner Losh         return solution;
2550c16b537SWarner Losh     }
2560c16b537SWarner Losh 
2570c16b537SWarner Losh     /* look forward */
25819fcbaf1SConrad Meyer     {   size_t length;
2590c16b537SWarner Losh         do {
2600c16b537SWarner Losh             end++;
2610c16b537SWarner Losh             length = ZDICT_count(b + pos, b + suffix[end]);
2620c16b537SWarner Losh         } while (length >= MINMATCHLENGTH);
26319fcbaf1SConrad Meyer     }
2640c16b537SWarner Losh 
2650c16b537SWarner Losh     /* look backward */
26619fcbaf1SConrad Meyer     {   size_t length;
2670c16b537SWarner Losh         do {
2680c16b537SWarner Losh             length = ZDICT_count(b + pos, b + *(suffix+start-1));
2690c16b537SWarner Losh             if (length >=MINMATCHLENGTH) start--;
2700c16b537SWarner Losh         } while(length >= MINMATCHLENGTH);
27119fcbaf1SConrad Meyer     }
2720c16b537SWarner Losh 
2730c16b537SWarner Losh     /* exit if not found a minimum nb of repetitions */
2740c16b537SWarner Losh     if (end-start < minRatio) {
2750c16b537SWarner Losh         U32 idx;
2760c16b537SWarner Losh         for(idx=start; idx<end; idx++)
2770c16b537SWarner Losh             doneMarks[suffix[idx]] = 1;
2780c16b537SWarner Losh         return solution;
2790c16b537SWarner Losh     }
2800c16b537SWarner Losh 
2810c16b537SWarner Losh     {   int i;
282a0483764SConrad Meyer         U32 mml;
2830c16b537SWarner Losh         U32 refinedStart = start;
2840c16b537SWarner Losh         U32 refinedEnd = end;
2850c16b537SWarner Losh 
2860c16b537SWarner Losh         DISPLAYLEVEL(4, "\n");
287a0483764SConrad Meyer         DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u  ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);
2880c16b537SWarner Losh         DISPLAYLEVEL(4, "\n");
2890c16b537SWarner Losh 
290a0483764SConrad Meyer         for (mml = MINMATCHLENGTH ; ; mml++) {
2910c16b537SWarner Losh             BYTE currentChar = 0;
2920c16b537SWarner Losh             U32 currentCount = 0;
2930c16b537SWarner Losh             U32 currentID = refinedStart;
2940c16b537SWarner Losh             U32 id;
2950c16b537SWarner Losh             U32 selectedCount = 0;
2960c16b537SWarner Losh             U32 selectedID = currentID;
2970c16b537SWarner Losh             for (id =refinedStart; id < refinedEnd; id++) {
298a0483764SConrad Meyer                 if (b[suffix[id] + mml] != currentChar) {
2990c16b537SWarner Losh                     if (currentCount > selectedCount) {
3000c16b537SWarner Losh                         selectedCount = currentCount;
3010c16b537SWarner Losh                         selectedID = currentID;
3020c16b537SWarner Losh                     }
3030c16b537SWarner Losh                     currentID = id;
304a0483764SConrad Meyer                     currentChar = b[ suffix[id] + mml];
3050c16b537SWarner Losh                     currentCount = 0;
3060c16b537SWarner Losh                 }
3070c16b537SWarner Losh                 currentCount ++;
3080c16b537SWarner Losh             }
3090c16b537SWarner Losh             if (currentCount > selectedCount) {  /* for last */
3100c16b537SWarner Losh                 selectedCount = currentCount;
3110c16b537SWarner Losh                 selectedID = currentID;
3120c16b537SWarner Losh             }
3130c16b537SWarner Losh 
3140c16b537SWarner Losh             if (selectedCount < minRatio)
3150c16b537SWarner Losh                 break;
3160c16b537SWarner Losh             refinedStart = selectedID;
3170c16b537SWarner Losh             refinedEnd = refinedStart + selectedCount;
3180c16b537SWarner Losh         }
3190c16b537SWarner Losh 
3200f743729SConrad Meyer         /* evaluate gain based on new dict */
3210c16b537SWarner Losh         start = refinedStart;
3220c16b537SWarner Losh         pos = suffix[refinedStart];
3230c16b537SWarner Losh         end = start;
3240c16b537SWarner Losh         memset(lengthList, 0, sizeof(lengthList));
3250c16b537SWarner Losh 
3260c16b537SWarner Losh         /* look forward */
32719fcbaf1SConrad Meyer         {   size_t length;
3280c16b537SWarner Losh             do {
3290c16b537SWarner Losh                 end++;
3300c16b537SWarner Losh                 length = ZDICT_count(b + pos, b + suffix[end]);
3310c16b537SWarner Losh                 if (length >= LLIMIT) length = LLIMIT-1;
3320c16b537SWarner Losh                 lengthList[length]++;
3330c16b537SWarner Losh             } while (length >=MINMATCHLENGTH);
33419fcbaf1SConrad Meyer         }
3350c16b537SWarner Losh 
3360c16b537SWarner Losh         /* look backward */
33719fcbaf1SConrad Meyer         {   size_t length = MINMATCHLENGTH;
3380c16b537SWarner Losh             while ((length >= MINMATCHLENGTH) & (start > 0)) {
3390c16b537SWarner Losh                 length = ZDICT_count(b + pos, b + suffix[start - 1]);
3400c16b537SWarner Losh                 if (length >= LLIMIT) length = LLIMIT - 1;
3410c16b537SWarner Losh                 lengthList[length]++;
3420c16b537SWarner Losh                 if (length >= MINMATCHLENGTH) start--;
3430c16b537SWarner Losh             }
34419fcbaf1SConrad Meyer         }
3450c16b537SWarner Losh 
3460c16b537SWarner Losh         /* largest useful length */
3470c16b537SWarner Losh         memset(cumulLength, 0, sizeof(cumulLength));
3480c16b537SWarner Losh         cumulLength[maxLength-1] = lengthList[maxLength-1];
3490c16b537SWarner Losh         for (i=(int)(maxLength-2); i>=0; i--)
3500c16b537SWarner Losh             cumulLength[i] = cumulLength[i+1] + lengthList[i];
3510c16b537SWarner Losh 
3520c16b537SWarner Losh         for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;
3530c16b537SWarner Losh         maxLength = i;
3540c16b537SWarner Losh 
3550c16b537SWarner Losh         /* reduce maxLength in case of final into repetitive data */
3560c16b537SWarner Losh         {   U32 l = (U32)maxLength;
3570c16b537SWarner Losh             BYTE const c = b[pos + maxLength-1];
3580c16b537SWarner Losh             while (b[pos+l-2]==c) l--;
3590c16b537SWarner Losh             maxLength = l;
3600c16b537SWarner Losh         }
3610c16b537SWarner Losh         if (maxLength < MINMATCHLENGTH) return solution;   /* skip : no long-enough solution */
3620c16b537SWarner Losh 
3630c16b537SWarner Losh         /* calculate savings */
3640c16b537SWarner Losh         savings[5] = 0;
3650c16b537SWarner Losh         for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)
3660c16b537SWarner Losh             savings[i] = savings[i-1] + (lengthList[i] * (i-3));
3670c16b537SWarner Losh 
3680f743729SConrad Meyer         DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f)  \n",
369a0483764SConrad Meyer                      (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / maxLength);
3700c16b537SWarner Losh 
3710c16b537SWarner Losh         solution.pos = (U32)pos;
3720c16b537SWarner Losh         solution.length = (U32)maxLength;
3730c16b537SWarner Losh         solution.savings = savings[maxLength];
3740c16b537SWarner Losh 
3750c16b537SWarner Losh         /* mark positions done */
3760c16b537SWarner Losh         {   U32 id;
3770c16b537SWarner Losh             for (id=start; id<end; id++) {
37819fcbaf1SConrad Meyer                 U32 p, pEnd, length;
3790c16b537SWarner Losh                 U32 const testedPos = suffix[id];
3800c16b537SWarner Losh                 if (testedPos == pos)
3810c16b537SWarner Losh                     length = solution.length;
3820c16b537SWarner Losh                 else {
38319fcbaf1SConrad Meyer                     length = (U32)ZDICT_count(b+pos, b+testedPos);
3840c16b537SWarner Losh                     if (length > solution.length) length = solution.length;
3850c16b537SWarner Losh                 }
3860c16b537SWarner Losh                 pEnd = (U32)(testedPos + length);
3870c16b537SWarner Losh                 for (p=testedPos; p<pEnd; p++)
3880c16b537SWarner Losh                     doneMarks[p] = 1;
3890c16b537SWarner Losh     }   }   }
3900c16b537SWarner Losh 
3910c16b537SWarner Losh     return solution;
3920c16b537SWarner Losh }
3930c16b537SWarner Losh 
3940c16b537SWarner Losh 
3950c16b537SWarner Losh static int isIncluded(const void* in, const void* container, size_t length)
3960c16b537SWarner Losh {
3970c16b537SWarner Losh     const char* const ip = (const char*) in;
3980c16b537SWarner Losh     const char* const into = (const char*) container;
3990c16b537SWarner Losh     size_t u;
4000c16b537SWarner Losh 
4010c16b537SWarner Losh     for (u=0; u<length; u++) {  /* works because end of buffer is a noisy guard band */
4020c16b537SWarner Losh         if (ip[u] != into[u]) break;
4030c16b537SWarner Losh     }
4040c16b537SWarner Losh 
4050c16b537SWarner Losh     return u==length;
4060c16b537SWarner Losh }
4070c16b537SWarner Losh 
4080c16b537SWarner Losh /*! ZDICT_tryMerge() :
4090c16b537SWarner Losh     check if dictItem can be merged, do it if possible
4100c16b537SWarner Losh     @return : id of destination elt, 0 if not merged
4110c16b537SWarner Losh */
4120c16b537SWarner Losh static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const void* buffer)
4130c16b537SWarner Losh {
4140c16b537SWarner Losh     const U32 tableSize = table->pos;
4150c16b537SWarner Losh     const U32 eltEnd = elt.pos + elt.length;
4160c16b537SWarner Losh     const char* const buf = (const char*) buffer;
4170c16b537SWarner Losh 
4180c16b537SWarner Losh     /* tail overlap */
4190c16b537SWarner Losh     U32 u; for (u=1; u<tableSize; u++) {
4200c16b537SWarner Losh         if (u==eltNbToSkip) continue;
4210c16b537SWarner Losh         if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) {  /* overlap, existing > new */
4220c16b537SWarner Losh             /* append */
4230c16b537SWarner Losh             U32 const addedLength = table[u].pos - elt.pos;
4240c16b537SWarner Losh             table[u].length += addedLength;
4250c16b537SWarner Losh             table[u].pos = elt.pos;
4260c16b537SWarner Losh             table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
4270c16b537SWarner Losh             table[u].savings += elt.length / 8;    /* rough approx bonus */
4280c16b537SWarner Losh             elt = table[u];
4290c16b537SWarner Losh             /* sort : improve rank */
4300c16b537SWarner Losh             while ((u>1) && (table[u-1].savings < elt.savings))
4310c16b537SWarner Losh             table[u] = table[u-1], u--;
4320c16b537SWarner Losh             table[u] = elt;
4330c16b537SWarner Losh             return u;
4340c16b537SWarner Losh     }   }
4350c16b537SWarner Losh 
4360c16b537SWarner Losh     /* front overlap */
4370c16b537SWarner Losh     for (u=1; u<tableSize; u++) {
4380c16b537SWarner Losh         if (u==eltNbToSkip) continue;
4390c16b537SWarner Losh 
4400c16b537SWarner Losh         if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) {  /* overlap, existing < new */
4410c16b537SWarner Losh             /* append */
4420c16b537SWarner Losh             int const addedLength = (int)eltEnd - (table[u].pos + table[u].length);
4430c16b537SWarner Losh             table[u].savings += elt.length / 8;    /* rough approx bonus */
4440c16b537SWarner Losh             if (addedLength > 0) {   /* otherwise, elt fully included into existing */
4450c16b537SWarner Losh                 table[u].length += addedLength;
4460c16b537SWarner Losh                 table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
4470c16b537SWarner Losh             }
4480c16b537SWarner Losh             /* sort : improve rank */
4490c16b537SWarner Losh             elt = table[u];
4500c16b537SWarner Losh             while ((u>1) && (table[u-1].savings < elt.savings))
4510c16b537SWarner Losh                 table[u] = table[u-1], u--;
4520c16b537SWarner Losh             table[u] = elt;
4530c16b537SWarner Losh             return u;
4540c16b537SWarner Losh         }
4550c16b537SWarner Losh 
4560c16b537SWarner Losh         if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {
4570c16b537SWarner Losh             if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {
4580c16b537SWarner Losh                 size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );
4590c16b537SWarner Losh                 table[u].pos = elt.pos;
4600c16b537SWarner Losh                 table[u].savings += (U32)(elt.savings * addedLength / elt.length);
4610c16b537SWarner Losh                 table[u].length = MIN(elt.length, table[u].length + 1);
4620c16b537SWarner Losh                 return u;
4630c16b537SWarner Losh             }
4640c16b537SWarner Losh         }
4650c16b537SWarner Losh     }
4660c16b537SWarner Losh 
4670c16b537SWarner Losh     return 0;
4680c16b537SWarner Losh }
4690c16b537SWarner Losh 
4700c16b537SWarner Losh 
4710c16b537SWarner Losh static void ZDICT_removeDictItem(dictItem* table, U32 id)
4720c16b537SWarner Losh {
4730c16b537SWarner Losh     /* convention : table[0].pos stores nb of elts */
4740c16b537SWarner Losh     U32 const max = table[0].pos;
4750c16b537SWarner Losh     U32 u;
4760c16b537SWarner Losh     if (!id) return;   /* protection, should never happen */
4770c16b537SWarner Losh     for (u=id; u<max-1; u++)
4780c16b537SWarner Losh         table[u] = table[u+1];
4790c16b537SWarner Losh     table->pos--;
4800c16b537SWarner Losh }
4810c16b537SWarner Losh 
4820c16b537SWarner Losh 
4830c16b537SWarner Losh static void ZDICT_insertDictItem(dictItem* table, U32 maxSize, dictItem elt, const void* buffer)
4840c16b537SWarner Losh {
4850c16b537SWarner Losh     /* merge if possible */
4860c16b537SWarner Losh     U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);
4870c16b537SWarner Losh     if (mergeId) {
4880c16b537SWarner Losh         U32 newMerge = 1;
4890c16b537SWarner Losh         while (newMerge) {
4900c16b537SWarner Losh             newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);
4910c16b537SWarner Losh             if (newMerge) ZDICT_removeDictItem(table, mergeId);
4920c16b537SWarner Losh             mergeId = newMerge;
4930c16b537SWarner Losh         }
4940c16b537SWarner Losh         return;
4950c16b537SWarner Losh     }
4960c16b537SWarner Losh 
4970c16b537SWarner Losh     /* insert */
4980c16b537SWarner Losh     {   U32 current;
4990c16b537SWarner Losh         U32 nextElt = table->pos;
5000c16b537SWarner Losh         if (nextElt >= maxSize) nextElt = maxSize-1;
5010c16b537SWarner Losh         current = nextElt-1;
5020c16b537SWarner Losh         while (table[current].savings < elt.savings) {
5030c16b537SWarner Losh             table[current+1] = table[current];
5040c16b537SWarner Losh             current--;
5050c16b537SWarner Losh         }
5060c16b537SWarner Losh         table[current+1] = elt;
5070c16b537SWarner Losh         table->pos = nextElt+1;
5080c16b537SWarner Losh     }
5090c16b537SWarner Losh }
5100c16b537SWarner Losh 
5110c16b537SWarner Losh 
5120c16b537SWarner Losh static U32 ZDICT_dictSize(const dictItem* dictList)
5130c16b537SWarner Losh {
5140c16b537SWarner Losh     U32 u, dictSize = 0;
5150c16b537SWarner Losh     for (u=1; u<dictList[0].pos; u++)
5160c16b537SWarner Losh         dictSize += dictList[u].length;
5170c16b537SWarner Losh     return dictSize;
5180c16b537SWarner Losh }
5190c16b537SWarner Losh 
5200c16b537SWarner Losh 
5210c16b537SWarner Losh static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,
5220c16b537SWarner Losh                             const void* const buffer, size_t bufferSize,   /* buffer must end with noisy guard band */
5230c16b537SWarner Losh                             const size_t* fileSizes, unsigned nbFiles,
524a0483764SConrad Meyer                             unsigned minRatio, U32 notificationLevel)
5250c16b537SWarner Losh {
5260c16b537SWarner Losh     int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));
5270c16b537SWarner Losh     int* const suffix = suffix0+1;
5280c16b537SWarner Losh     U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));
5290c16b537SWarner Losh     BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks));   /* +16 for overflow security */
5300c16b537SWarner Losh     U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));
5310c16b537SWarner Losh     size_t result = 0;
5320c16b537SWarner Losh     clock_t displayClock = 0;
5330c16b537SWarner Losh     clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
5340c16b537SWarner Losh 
5350c16b537SWarner Losh #   define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \
5360c16b537SWarner Losh             if (ZDICT_clockSpan(displayClock) > refreshRate)  \
5370c16b537SWarner Losh             { displayClock = clock(); DISPLAY(__VA_ARGS__); \
5380c16b537SWarner Losh             if (notificationLevel>=4) fflush(stderr); } }
5390c16b537SWarner Losh 
5400c16b537SWarner Losh     /* init */
5410c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
5420c16b537SWarner Losh     if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
5430c16b537SWarner Losh         result = ERROR(memory_allocation);
5440c16b537SWarner Losh         goto _cleanup;
5450c16b537SWarner Losh     }
5460c16b537SWarner Losh     if (minRatio < MINRATIO) minRatio = MINRATIO;
5470c16b537SWarner Losh     memset(doneMarks, 0, bufferSize+16);
5480c16b537SWarner Losh 
5490c16b537SWarner Losh     /* limit sample set size (divsufsort limitation)*/
550a0483764SConrad Meyer     if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
5510c16b537SWarner Losh     while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
5520c16b537SWarner Losh 
5530c16b537SWarner Losh     /* sort */
554a0483764SConrad Meyer     DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
5550c16b537SWarner Losh     {   int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
5560c16b537SWarner Losh         if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
5570c16b537SWarner Losh     }
5580c16b537SWarner Losh     suffix[bufferSize] = (int)bufferSize;   /* leads into noise */
5590c16b537SWarner Losh     suffix0[0] = (int)bufferSize;           /* leads into noise */
5600c16b537SWarner Losh     /* build reverse suffix sort */
5610c16b537SWarner Losh     {   size_t pos;
5620c16b537SWarner Losh         for (pos=0; pos < bufferSize; pos++)
5630c16b537SWarner Losh             reverseSuffix[suffix[pos]] = (U32)pos;
5640c16b537SWarner Losh         /* note filePos tracks borders between samples.
5650c16b537SWarner Losh            It's not used at this stage, but planned to become useful in a later update */
5660c16b537SWarner Losh         filePos[0] = 0;
5670c16b537SWarner Losh         for (pos=1; pos<nbFiles; pos++)
5680c16b537SWarner Losh             filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
5690c16b537SWarner Losh     }
5700c16b537SWarner Losh 
5710c16b537SWarner Losh     DISPLAYLEVEL(2, "finding patterns ... \n");
5720c16b537SWarner Losh     DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
5730c16b537SWarner Losh 
5740c16b537SWarner Losh     {   U32 cursor; for (cursor=0; cursor < bufferSize; ) {
5750c16b537SWarner Losh             dictItem solution;
5760c16b537SWarner Losh             if (doneMarks[cursor]) { cursor++; continue; }
5770c16b537SWarner Losh             solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
5780c16b537SWarner Losh             if (solution.length==0) { cursor++; continue; }
5790c16b537SWarner Losh             ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
5800c16b537SWarner Losh             cursor += solution.length;
5810c16b537SWarner Losh             DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / bufferSize * 100);
5820c16b537SWarner Losh     }   }
5830c16b537SWarner Losh 
5840c16b537SWarner Losh _cleanup:
5850c16b537SWarner Losh     free(suffix0);
5860c16b537SWarner Losh     free(reverseSuffix);
5870c16b537SWarner Losh     free(doneMarks);
5880c16b537SWarner Losh     free(filePos);
5890c16b537SWarner Losh     return result;
5900c16b537SWarner Losh }
5910c16b537SWarner Losh 
5920c16b537SWarner Losh 
5930c16b537SWarner Losh static void ZDICT_fillNoise(void* buffer, size_t length)
5940c16b537SWarner Losh {
5950c16b537SWarner Losh     unsigned const prime1 = 2654435761U;
5960c16b537SWarner Losh     unsigned const prime2 = 2246822519U;
5970c16b537SWarner Losh     unsigned acc = prime1;
5989cbefe25SConrad Meyer     size_t p=0;
5990c16b537SWarner Losh     for (p=0; p<length; p++) {
6000c16b537SWarner Losh         acc *= prime2;
6010c16b537SWarner Losh         ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
6020c16b537SWarner Losh     }
6030c16b537SWarner Losh }
6040c16b537SWarner Losh 
6050c16b537SWarner Losh 
6060c16b537SWarner Losh typedef struct
6070c16b537SWarner Losh {
6080f743729SConrad Meyer     ZSTD_CDict* dict;    /* dictionary */
60919fcbaf1SConrad Meyer     ZSTD_CCtx* zc;     /* working context */
6100c16b537SWarner Losh     void* workPlace;   /* must be ZSTD_BLOCKSIZE_MAX allocated */
6110c16b537SWarner Losh } EStats_ress_t;
6120c16b537SWarner Losh 
6130c16b537SWarner Losh #define MAXREPOFFSET 1024
6140c16b537SWarner Losh 
615*37f1f268SConrad Meyer static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params,
616a0483764SConrad Meyer                               unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,
61719fcbaf1SConrad Meyer                               const void* src, size_t srcSize,
61819fcbaf1SConrad Meyer                               U32 notificationLevel)
6190c16b537SWarner Losh {
620*37f1f268SConrad Meyer     size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params->cParams.windowLog);
6210c16b537SWarner Losh     size_t cSize;
6220c16b537SWarner Losh 
6230c16b537SWarner Losh     if (srcSize > blockSizeMax) srcSize = blockSizeMax;   /* protection vs large samples */
6240f743729SConrad Meyer     {   size_t const errorCode = ZSTD_compressBegin_usingCDict(esr.zc, esr.dict);
6250f743729SConrad Meyer         if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
6260f743729SConrad Meyer 
6270c16b537SWarner Losh     }
6280c16b537SWarner Losh     cSize = ZSTD_compressBlock(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
629a0483764SConrad Meyer     if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
6300c16b537SWarner Losh 
6310c16b537SWarner Losh     if (cSize) {  /* if == 0; block is not compressible */
63219fcbaf1SConrad Meyer         const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
6330c16b537SWarner Losh 
6340c16b537SWarner Losh         /* literals stats */
6350c16b537SWarner Losh         {   const BYTE* bytePtr;
6360c16b537SWarner Losh             for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
6370c16b537SWarner Losh                 countLit[*bytePtr]++;
6380c16b537SWarner Losh         }
6390c16b537SWarner Losh 
6400c16b537SWarner Losh         /* seqStats */
6410c16b537SWarner Losh         {   U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
6420c16b537SWarner Losh             ZSTD_seqToCodes(seqStorePtr);
6430c16b537SWarner Losh 
6440c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->ofCode;
6450c16b537SWarner Losh                 U32 u;
6460c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
6470c16b537SWarner Losh             }
6480c16b537SWarner Losh 
6490c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->mlCode;
6500c16b537SWarner Losh                 U32 u;
6510c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
6520c16b537SWarner Losh             }
6530c16b537SWarner Losh 
6540c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->llCode;
6550c16b537SWarner Losh                 U32 u;
6560c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
6570c16b537SWarner Losh             }
6580c16b537SWarner Losh 
6590c16b537SWarner Losh             if (nbSeq >= 2) { /* rep offsets */
6600c16b537SWarner Losh                 const seqDef* const seq = seqStorePtr->sequencesStart;
6610c16b537SWarner Losh                 U32 offset1 = seq[0].offset - 3;
6620c16b537SWarner Losh                 U32 offset2 = seq[1].offset - 3;
6630c16b537SWarner Losh                 if (offset1 >= MAXREPOFFSET) offset1 = 0;
6640c16b537SWarner Losh                 if (offset2 >= MAXREPOFFSET) offset2 = 0;
6650c16b537SWarner Losh                 repOffsets[offset1] += 3;
6660c16b537SWarner Losh                 repOffsets[offset2] += 1;
6670c16b537SWarner Losh     }   }   }
6680c16b537SWarner Losh }
6690c16b537SWarner Losh 
6700c16b537SWarner Losh static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)
6710c16b537SWarner Losh {
6720c16b537SWarner Losh     size_t total=0;
6730c16b537SWarner Losh     unsigned u;
6740c16b537SWarner Losh     for (u=0; u<nbFiles; u++) total += fileSizes[u];
6750c16b537SWarner Losh     return total;
6760c16b537SWarner Losh }
6770c16b537SWarner Losh 
6780c16b537SWarner Losh typedef struct { U32 offset; U32 count; } offsetCount_t;
6790c16b537SWarner Losh 
6800c16b537SWarner Losh static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
6810c16b537SWarner Losh {
6820c16b537SWarner Losh     U32 u;
6830c16b537SWarner Losh     table[ZSTD_REP_NUM].offset = val;
6840c16b537SWarner Losh     table[ZSTD_REP_NUM].count = count;
6850c16b537SWarner Losh     for (u=ZSTD_REP_NUM; u>0; u--) {
6860c16b537SWarner Losh         offsetCount_t tmp;
6870c16b537SWarner Losh         if (table[u-1].count >= table[u].count) break;
6880c16b537SWarner Losh         tmp = table[u-1];
6890c16b537SWarner Losh         table[u-1] = table[u];
6900c16b537SWarner Losh         table[u] = tmp;
6910c16b537SWarner Losh     }
6920c16b537SWarner Losh }
6930c16b537SWarner Losh 
69419fcbaf1SConrad Meyer /* ZDICT_flatLit() :
69519fcbaf1SConrad Meyer  * rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.
69619fcbaf1SConrad Meyer  * necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.
69719fcbaf1SConrad Meyer  */
698a0483764SConrad Meyer static void ZDICT_flatLit(unsigned* countLit)
69919fcbaf1SConrad Meyer {
70019fcbaf1SConrad Meyer     int u;
70119fcbaf1SConrad Meyer     for (u=1; u<256; u++) countLit[u] = 2;
70219fcbaf1SConrad Meyer     countLit[0]   = 4;
70319fcbaf1SConrad Meyer     countLit[253] = 1;
70419fcbaf1SConrad Meyer     countLit[254] = 1;
70519fcbaf1SConrad Meyer }
7060c16b537SWarner Losh 
7070c16b537SWarner Losh #define OFFCODE_MAX 30  /* only applicable to first block */
7080c16b537SWarner Losh static size_t ZDICT_analyzeEntropy(void*  dstBuffer, size_t maxDstSize,
7090c16b537SWarner Losh                                    unsigned compressionLevel,
7100c16b537SWarner Losh                              const void*  srcBuffer, const size_t* fileSizes, unsigned nbFiles,
7110c16b537SWarner Losh                              const void* dictBuffer, size_t  dictBufferSize,
7120c16b537SWarner Losh                                    unsigned notificationLevel)
7130c16b537SWarner Losh {
714a0483764SConrad Meyer     unsigned countLit[256];
7150c16b537SWarner Losh     HUF_CREATE_STATIC_CTABLE(hufTable, 255);
716a0483764SConrad Meyer     unsigned offcodeCount[OFFCODE_MAX+1];
7170c16b537SWarner Losh     short offcodeNCount[OFFCODE_MAX+1];
7180c16b537SWarner Losh     U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
719a0483764SConrad Meyer     unsigned matchLengthCount[MaxML+1];
7200c16b537SWarner Losh     short matchLengthNCount[MaxML+1];
721a0483764SConrad Meyer     unsigned litLengthCount[MaxLL+1];
7220c16b537SWarner Losh     short litLengthNCount[MaxLL+1];
7230c16b537SWarner Losh     U32 repOffset[MAXREPOFFSET];
7240c16b537SWarner Losh     offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
7250f743729SConrad Meyer     EStats_ress_t esr = { NULL, NULL, NULL };
7260c16b537SWarner Losh     ZSTD_parameters params;
7270c16b537SWarner Losh     U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
7280c16b537SWarner Losh     size_t pos = 0, errorCode;
7290c16b537SWarner Losh     size_t eSize = 0;
7300c16b537SWarner Losh     size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
7310c16b537SWarner Losh     size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
7320c16b537SWarner Losh     BYTE* dstPtr = (BYTE*)dstBuffer;
7330c16b537SWarner Losh 
7340c16b537SWarner Losh     /* init */
73519fcbaf1SConrad Meyer     DEBUGLOG(4, "ZDICT_analyzeEntropy");
7360c16b537SWarner Losh     if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; }   /* too large dictionary */
7370c16b537SWarner Losh     for (u=0; u<256; u++) countLit[u] = 1;   /* any character must be described */
7380c16b537SWarner Losh     for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
7390c16b537SWarner Losh     for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
7400c16b537SWarner Losh     for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
7410c16b537SWarner Losh     memset(repOffset, 0, sizeof(repOffset));
7420c16b537SWarner Losh     repOffset[1] = repOffset[4] = repOffset[8] = 1;
7430c16b537SWarner Losh     memset(bestRepOffset, 0, sizeof(bestRepOffset));
7440f743729SConrad Meyer     if (compressionLevel==0) compressionLevel = g_compressionLevel_default;
7450c16b537SWarner Losh     params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
7460f743729SConrad Meyer 
7470f743729SConrad Meyer     esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
7480f743729SConrad Meyer     esr.zc = ZSTD_createCCtx();
7490f743729SConrad Meyer     esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
7500f743729SConrad Meyer     if (!esr.dict || !esr.zc || !esr.workPlace) {
7510f743729SConrad Meyer         eSize = ERROR(memory_allocation);
7520f743729SConrad Meyer         DISPLAYLEVEL(1, "Not enough memory \n");
7530c16b537SWarner Losh         goto _cleanup;
7540f743729SConrad Meyer     }
7550c16b537SWarner Losh 
75619fcbaf1SConrad Meyer     /* collect stats on all samples */
7570c16b537SWarner Losh     for (u=0; u<nbFiles; u++) {
758*37f1f268SConrad Meyer         ZDICT_countEStats(esr, &params,
7590c16b537SWarner Losh                           countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
7600c16b537SWarner Losh                          (const char*)srcBuffer + pos, fileSizes[u],
7610c16b537SWarner Losh                           notificationLevel);
7620c16b537SWarner Losh         pos += fileSizes[u];
7630c16b537SWarner Losh     }
7640c16b537SWarner Losh 
76519fcbaf1SConrad Meyer     /* analyze, build stats, starting with literals */
76619fcbaf1SConrad Meyer     {   size_t maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
76719fcbaf1SConrad Meyer         if (HUF_isError(maxNbBits)) {
7684d3f1eafSConrad Meyer             eSize = maxNbBits;
7690c16b537SWarner Losh             DISPLAYLEVEL(1, " HUF_buildCTable error \n");
7700c16b537SWarner Losh             goto _cleanup;
7710c16b537SWarner Losh         }
77219fcbaf1SConrad Meyer         if (maxNbBits==8) {  /* not compressible : will fail on HUF_writeCTable() */
77319fcbaf1SConrad Meyer             DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
77419fcbaf1SConrad Meyer             ZDICT_flatLit(countLit);  /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
77519fcbaf1SConrad Meyer             maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
77619fcbaf1SConrad Meyer             assert(maxNbBits==9);
77719fcbaf1SConrad Meyer         }
77819fcbaf1SConrad Meyer         huffLog = (U32)maxNbBits;
77919fcbaf1SConrad Meyer     }
7800c16b537SWarner Losh 
7810c16b537SWarner Losh     /* looking for most common first offsets */
7820c16b537SWarner Losh     {   U32 offset;
7830c16b537SWarner Losh         for (offset=1; offset<MAXREPOFFSET; offset++)
7840c16b537SWarner Losh             ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
7850c16b537SWarner Losh     }
7860c16b537SWarner Losh     /* note : the result of this phase should be used to better appreciate the impact on statistics */
7870c16b537SWarner Losh 
7880c16b537SWarner Losh     total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
7890c16b537SWarner Losh     errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax);
7900c16b537SWarner Losh     if (FSE_isError(errorCode)) {
7914d3f1eafSConrad Meyer         eSize = errorCode;
7920c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
7930c16b537SWarner Losh         goto _cleanup;
7940c16b537SWarner Losh     }
7950c16b537SWarner Losh     Offlog = (U32)errorCode;
7960c16b537SWarner Losh 
7970c16b537SWarner Losh     total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
7980c16b537SWarner Losh     errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML);
7990c16b537SWarner Losh     if (FSE_isError(errorCode)) {
8004d3f1eafSConrad Meyer         eSize = errorCode;
8010c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
8020c16b537SWarner Losh         goto _cleanup;
8030c16b537SWarner Losh     }
8040c16b537SWarner Losh     mlLog = (U32)errorCode;
8050c16b537SWarner Losh 
8060c16b537SWarner Losh     total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
8070c16b537SWarner Losh     errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL);
8080c16b537SWarner Losh     if (FSE_isError(errorCode)) {
8094d3f1eafSConrad Meyer         eSize = errorCode;
8100c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
8110c16b537SWarner Losh         goto _cleanup;
8120c16b537SWarner Losh     }
8130c16b537SWarner Losh     llLog = (U32)errorCode;
8140c16b537SWarner Losh 
8150c16b537SWarner Losh     /* write result to buffer */
8160c16b537SWarner Losh     {   size_t const hhSize = HUF_writeCTable(dstPtr, maxDstSize, hufTable, 255, huffLog);
8170c16b537SWarner Losh         if (HUF_isError(hhSize)) {
8184d3f1eafSConrad Meyer             eSize = hhSize;
8190c16b537SWarner Losh             DISPLAYLEVEL(1, "HUF_writeCTable error \n");
8200c16b537SWarner Losh             goto _cleanup;
8210c16b537SWarner Losh         }
8220c16b537SWarner Losh         dstPtr += hhSize;
8230c16b537SWarner Losh         maxDstSize -= hhSize;
8240c16b537SWarner Losh         eSize += hhSize;
8250c16b537SWarner Losh     }
8260c16b537SWarner Losh 
8270c16b537SWarner Losh     {   size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
8280c16b537SWarner Losh         if (FSE_isError(ohSize)) {
8294d3f1eafSConrad Meyer             eSize = ohSize;
8300c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
8310c16b537SWarner Losh             goto _cleanup;
8320c16b537SWarner Losh         }
8330c16b537SWarner Losh         dstPtr += ohSize;
8340c16b537SWarner Losh         maxDstSize -= ohSize;
8350c16b537SWarner Losh         eSize += ohSize;
8360c16b537SWarner Losh     }
8370c16b537SWarner Losh 
8380c16b537SWarner Losh     {   size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
8390c16b537SWarner Losh         if (FSE_isError(mhSize)) {
8404d3f1eafSConrad Meyer             eSize = mhSize;
8410c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
8420c16b537SWarner Losh             goto _cleanup;
8430c16b537SWarner Losh         }
8440c16b537SWarner Losh         dstPtr += mhSize;
8450c16b537SWarner Losh         maxDstSize -= mhSize;
8460c16b537SWarner Losh         eSize += mhSize;
8470c16b537SWarner Losh     }
8480c16b537SWarner Losh 
8490c16b537SWarner Losh     {   size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
8500c16b537SWarner Losh         if (FSE_isError(lhSize)) {
8514d3f1eafSConrad Meyer             eSize = lhSize;
8520c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
8530c16b537SWarner Losh             goto _cleanup;
8540c16b537SWarner Losh         }
8550c16b537SWarner Losh         dstPtr += lhSize;
8560c16b537SWarner Losh         maxDstSize -= lhSize;
8570c16b537SWarner Losh         eSize += lhSize;
8580c16b537SWarner Losh     }
8590c16b537SWarner Losh 
8600c16b537SWarner Losh     if (maxDstSize<12) {
8614d3f1eafSConrad Meyer         eSize = ERROR(dstSize_tooSmall);
8620c16b537SWarner Losh         DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
8630c16b537SWarner Losh         goto _cleanup;
8640c16b537SWarner Losh     }
8650c16b537SWarner Losh # if 0
8660c16b537SWarner Losh     MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
8670c16b537SWarner Losh     MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
8680c16b537SWarner Losh     MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
8690c16b537SWarner Losh #else
8700c16b537SWarner Losh     /* at this stage, we don't use the result of "most common first offset",
8710c16b537SWarner Losh        as the impact of statistics is not properly evaluated */
8720c16b537SWarner Losh     MEM_writeLE32(dstPtr+0, repStartValue[0]);
8730c16b537SWarner Losh     MEM_writeLE32(dstPtr+4, repStartValue[1]);
8740c16b537SWarner Losh     MEM_writeLE32(dstPtr+8, repStartValue[2]);
8750c16b537SWarner Losh #endif
8760c16b537SWarner Losh     eSize += 12;
8770c16b537SWarner Losh 
8780c16b537SWarner Losh _cleanup:
8790f743729SConrad Meyer     ZSTD_freeCDict(esr.dict);
8800c16b537SWarner Losh     ZSTD_freeCCtx(esr.zc);
8810c16b537SWarner Losh     free(esr.workPlace);
8820c16b537SWarner Losh 
8830c16b537SWarner Losh     return eSize;
8840c16b537SWarner Losh }
8850c16b537SWarner Losh 
8860c16b537SWarner Losh 
8870c16b537SWarner Losh 
8880c16b537SWarner Losh size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
8890c16b537SWarner Losh                           const void* customDictContent, size_t dictContentSize,
8900f743729SConrad Meyer                           const void* samplesBuffer, const size_t* samplesSizes,
8910f743729SConrad Meyer                           unsigned nbSamples, ZDICT_params_t params)
8920c16b537SWarner Losh {
8930c16b537SWarner Losh     size_t hSize;
8940c16b537SWarner Losh #define HBUFFSIZE 256   /* should prove large enough for all entropy headers */
8950c16b537SWarner Losh     BYTE header[HBUFFSIZE];
8960f743729SConrad Meyer     int const compressionLevel = (params.compressionLevel == 0) ? g_compressionLevel_default : params.compressionLevel;
8970c16b537SWarner Losh     U32 const notificationLevel = params.notificationLevel;
8980c16b537SWarner Losh 
8990c16b537SWarner Losh     /* check conditions */
90019fcbaf1SConrad Meyer     DEBUGLOG(4, "ZDICT_finalizeDictionary");
9010c16b537SWarner Losh     if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
9020c16b537SWarner Losh     if (dictContentSize < ZDICT_CONTENTSIZE_MIN) return ERROR(srcSize_wrong);
9030c16b537SWarner Losh     if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
9040c16b537SWarner Losh 
9050c16b537SWarner Losh     /* dictionary header */
9060c16b537SWarner Losh     MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
9070c16b537SWarner Losh     {   U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
9080c16b537SWarner Losh         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
9090c16b537SWarner Losh         U32 const dictID = params.dictID ? params.dictID : compliantID;
9100c16b537SWarner Losh         MEM_writeLE32(header+4, dictID);
9110c16b537SWarner Losh     }
9120c16b537SWarner Losh     hSize = 8;
9130c16b537SWarner Losh 
9140c16b537SWarner Losh     /* entropy tables */
9150c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
9160c16b537SWarner Losh     DISPLAYLEVEL(2, "statistics ... \n");
9170c16b537SWarner Losh     {   size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
9180c16b537SWarner Losh                                   compressionLevel,
9190c16b537SWarner Losh                                   samplesBuffer, samplesSizes, nbSamples,
9200c16b537SWarner Losh                                   customDictContent, dictContentSize,
9210c16b537SWarner Losh                                   notificationLevel);
9220c16b537SWarner Losh         if (ZDICT_isError(eSize)) return eSize;
9230c16b537SWarner Losh         hSize += eSize;
9240c16b537SWarner Losh     }
9250c16b537SWarner Losh 
9260c16b537SWarner Losh     /* copy elements in final buffer ; note : src and dst buffer can overlap */
9270c16b537SWarner Losh     if (hSize + dictContentSize > dictBufferCapacity) dictContentSize = dictBufferCapacity - hSize;
9280c16b537SWarner Losh     {   size_t const dictSize = hSize + dictContentSize;
9290c16b537SWarner Losh         char* dictEnd = (char*)dictBuffer + dictSize;
9300c16b537SWarner Losh         memmove(dictEnd - dictContentSize, customDictContent, dictContentSize);
9310c16b537SWarner Losh         memcpy(dictBuffer, header, hSize);
9320c16b537SWarner Losh         return dictSize;
9330c16b537SWarner Losh     }
9340c16b537SWarner Losh }
9350c16b537SWarner Losh 
9360c16b537SWarner Losh 
9370f743729SConrad Meyer static size_t ZDICT_addEntropyTablesFromBuffer_advanced(
9380f743729SConrad Meyer         void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
9390c16b537SWarner Losh         const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9400c16b537SWarner Losh         ZDICT_params_t params)
9410c16b537SWarner Losh {
9420f743729SConrad Meyer     int const compressionLevel = (params.compressionLevel == 0) ? g_compressionLevel_default : params.compressionLevel;
9430c16b537SWarner Losh     U32 const notificationLevel = params.notificationLevel;
9440c16b537SWarner Losh     size_t hSize = 8;
9450c16b537SWarner Losh 
9460c16b537SWarner Losh     /* calculate entropy tables */
9470c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
9480c16b537SWarner Losh     DISPLAYLEVEL(2, "statistics ... \n");
9490c16b537SWarner Losh     {   size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
9500c16b537SWarner Losh                                   compressionLevel,
9510c16b537SWarner Losh                                   samplesBuffer, samplesSizes, nbSamples,
9520c16b537SWarner Losh                                   (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
9530c16b537SWarner Losh                                   notificationLevel);
9540c16b537SWarner Losh         if (ZDICT_isError(eSize)) return eSize;
9550c16b537SWarner Losh         hSize += eSize;
9560c16b537SWarner Losh     }
9570c16b537SWarner Losh 
9580c16b537SWarner Losh     /* add dictionary header (after entropy tables) */
9590c16b537SWarner Losh     MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
9600c16b537SWarner Losh     {   U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
9610c16b537SWarner Losh         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
9620c16b537SWarner Losh         U32 const dictID = params.dictID ? params.dictID : compliantID;
9630c16b537SWarner Losh         MEM_writeLE32((char*)dictBuffer+4, dictID);
9640c16b537SWarner Losh     }
9650c16b537SWarner Losh 
9660c16b537SWarner Losh     if (hSize + dictContentSize < dictBufferCapacity)
9670c16b537SWarner Losh         memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);
9680c16b537SWarner Losh     return MIN(dictBufferCapacity, hSize+dictContentSize);
9690c16b537SWarner Losh }
9700c16b537SWarner Losh 
9710f743729SConrad Meyer /* Hidden declaration for dbio.c */
9720f743729SConrad Meyer size_t ZDICT_trainFromBuffer_unsafe_legacy(
9730f743729SConrad Meyer                             void* dictBuffer, size_t maxDictSize,
9740f743729SConrad Meyer                             const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9750f743729SConrad Meyer                             ZDICT_legacy_params_t params);
9760c16b537SWarner Losh /*! ZDICT_trainFromBuffer_unsafe_legacy() :
9770c16b537SWarner Losh *   Warning : `samplesBuffer` must be followed by noisy guard band.
9780c16b537SWarner Losh *   @return : size of dictionary, or an error code which can be tested with ZDICT_isError()
9790c16b537SWarner Losh */
9800c16b537SWarner Losh size_t ZDICT_trainFromBuffer_unsafe_legacy(
9810c16b537SWarner Losh                             void* dictBuffer, size_t maxDictSize,
9820c16b537SWarner Losh                             const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
9830c16b537SWarner Losh                             ZDICT_legacy_params_t params)
9840c16b537SWarner Losh {
9850c16b537SWarner Losh     U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
9860c16b537SWarner Losh     dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
9870c16b537SWarner Losh     unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
9880c16b537SWarner Losh     unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
9890c16b537SWarner Losh     size_t const targetDictSize = maxDictSize;
9900c16b537SWarner Losh     size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
9910c16b537SWarner Losh     size_t dictSize = 0;
9920c16b537SWarner Losh     U32 const notificationLevel = params.zParams.notificationLevel;
9930c16b537SWarner Losh 
9940c16b537SWarner Losh     /* checks */
9950c16b537SWarner Losh     if (!dictList) return ERROR(memory_allocation);
9960c16b537SWarner Losh     if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); }   /* requested dictionary size is too small */
9970c16b537SWarner Losh     if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* not enough source to create dictionary */
9980c16b537SWarner Losh 
9990c16b537SWarner Losh     /* init */
10000c16b537SWarner Losh     ZDICT_initDictItem(dictList);
10010c16b537SWarner Losh 
10020c16b537SWarner Losh     /* build dictionary */
10030c16b537SWarner Losh     ZDICT_trainBuffer_legacy(dictList, dictListSize,
10040c16b537SWarner Losh                        samplesBuffer, samplesBuffSize,
10050c16b537SWarner Losh                        samplesSizes, nbSamples,
10060c16b537SWarner Losh                        minRep, notificationLevel);
10070c16b537SWarner Losh 
10080c16b537SWarner Losh     /* display best matches */
10090c16b537SWarner Losh     if (params.zParams.notificationLevel>= 3) {
1010a0483764SConrad Meyer         unsigned const nb = MIN(25, dictList[0].pos);
1011a0483764SConrad Meyer         unsigned const dictContentSize = ZDICT_dictSize(dictList);
1012a0483764SConrad Meyer         unsigned u;
1013a0483764SConrad Meyer         DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
10140c16b537SWarner Losh         DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
10150c16b537SWarner Losh         for (u=1; u<nb; u++) {
1016a0483764SConrad Meyer             unsigned const pos = dictList[u].pos;
1017a0483764SConrad Meyer             unsigned const length = dictList[u].length;
10180c16b537SWarner Losh             U32 const printedLength = MIN(40, length);
10190f743729SConrad Meyer             if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
10200f743729SConrad Meyer                 free(dictList);
10210c16b537SWarner Losh                 return ERROR(GENERIC);   /* should never happen */
10220f743729SConrad Meyer             }
10230c16b537SWarner Losh             DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
1024a0483764SConrad Meyer                          u, length, pos, (unsigned)dictList[u].savings);
10250c16b537SWarner Losh             ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
10260c16b537SWarner Losh             DISPLAYLEVEL(3, "| \n");
10270c16b537SWarner Losh     }   }
10280c16b537SWarner Losh 
10290c16b537SWarner Losh 
10300c16b537SWarner Losh     /* create dictionary */
1031a0483764SConrad Meyer     {   unsigned dictContentSize = ZDICT_dictSize(dictList);
10320c16b537SWarner Losh         if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* dictionary content too small */
10330c16b537SWarner Losh         if (dictContentSize < targetDictSize/4) {
1034a0483764SConrad Meyer             DISPLAYLEVEL(2, "!  warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
10350c16b537SWarner Losh             if (samplesBuffSize < 10 * targetDictSize)
1036a0483764SConrad Meyer                 DISPLAYLEVEL(2, "!  consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
10370c16b537SWarner Losh             if (minRep > MINRATIO) {
10380c16b537SWarner Losh                 DISPLAYLEVEL(2, "!  consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
10390c16b537SWarner Losh                 DISPLAYLEVEL(2, "!  note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
10400c16b537SWarner Losh             }
10410c16b537SWarner Losh         }
10420c16b537SWarner Losh 
10430c16b537SWarner Losh         if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
1044a0483764SConrad Meyer             unsigned proposedSelectivity = selectivity-1;
10450c16b537SWarner Losh             while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
1046a0483764SConrad Meyer             DISPLAYLEVEL(2, "!  note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
10470c16b537SWarner Losh             DISPLAYLEVEL(2, "!  consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
10480c16b537SWarner Losh             DISPLAYLEVEL(2, "!  always test dictionary efficiency on real samples \n");
10490c16b537SWarner Losh         }
10500c16b537SWarner Losh 
10510c16b537SWarner Losh         /* limit dictionary size */
10520c16b537SWarner Losh         {   U32 const max = dictList->pos;   /* convention : nb of useful elts within dictList */
10530c16b537SWarner Losh             U32 currentSize = 0;
10540c16b537SWarner Losh             U32 n; for (n=1; n<max; n++) {
10550c16b537SWarner Losh                 currentSize += dictList[n].length;
10560c16b537SWarner Losh                 if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
10570c16b537SWarner Losh             }
10580c16b537SWarner Losh             dictList->pos = n;
10590c16b537SWarner Losh             dictContentSize = currentSize;
10600c16b537SWarner Losh         }
10610c16b537SWarner Losh 
10620c16b537SWarner Losh         /* build dict content */
10630c16b537SWarner Losh         {   U32 u;
10640c16b537SWarner Losh             BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
10650c16b537SWarner Losh             for (u=1; u<dictList->pos; u++) {
10660c16b537SWarner Losh                 U32 l = dictList[u].length;
10670c16b537SWarner Losh                 ptr -= l;
10680c16b537SWarner Losh                 if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); }   /* should not happen */
10690c16b537SWarner Losh                 memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
10700c16b537SWarner Losh         }   }
10710c16b537SWarner Losh 
10720c16b537SWarner Losh         dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
10730c16b537SWarner Losh                                                              samplesBuffer, samplesSizes, nbSamples,
10740c16b537SWarner Losh                                                              params.zParams);
10750c16b537SWarner Losh     }
10760c16b537SWarner Losh 
10770c16b537SWarner Losh     /* clean up */
10780c16b537SWarner Losh     free(dictList);
10790c16b537SWarner Losh     return dictSize;
10800c16b537SWarner Losh }
10810c16b537SWarner Losh 
10820c16b537SWarner Losh 
108319fcbaf1SConrad Meyer /* ZDICT_trainFromBuffer_legacy() :
108419fcbaf1SConrad Meyer  * issue : samplesBuffer need to be followed by a noisy guard band.
10850c16b537SWarner Losh  * work around : duplicate the buffer, and add the noise */
10860c16b537SWarner Losh size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,
10870c16b537SWarner Losh                               const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
10880c16b537SWarner Losh                               ZDICT_legacy_params_t params)
10890c16b537SWarner Losh {
10900c16b537SWarner Losh     size_t result;
10910c16b537SWarner Losh     void* newBuff;
10920c16b537SWarner Losh     size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
10930c16b537SWarner Losh     if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0;   /* not enough content => no dictionary */
10940c16b537SWarner Losh 
10950c16b537SWarner Losh     newBuff = malloc(sBuffSize + NOISELENGTH);
10960c16b537SWarner Losh     if (!newBuff) return ERROR(memory_allocation);
10970c16b537SWarner Losh 
10980c16b537SWarner Losh     memcpy(newBuff, samplesBuffer, sBuffSize);
10990c16b537SWarner Losh     ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH);   /* guard band, for end of buffer condition */
11000c16b537SWarner Losh 
11010c16b537SWarner Losh     result =
11020c16b537SWarner Losh         ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,
11030c16b537SWarner Losh                                             samplesSizes, nbSamples, params);
11040c16b537SWarner Losh     free(newBuff);
11050c16b537SWarner Losh     return result;
11060c16b537SWarner Losh }
11070c16b537SWarner Losh 
11080c16b537SWarner Losh 
11090c16b537SWarner Losh size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
11100c16b537SWarner Losh                              const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
11110c16b537SWarner Losh {
11120f743729SConrad Meyer     ZDICT_fastCover_params_t params;
111319fcbaf1SConrad Meyer     DEBUGLOG(3, "ZDICT_trainFromBuffer");
11140c16b537SWarner Losh     memset(&params, 0, sizeof(params));
11150c16b537SWarner Losh     params.d = 8;
11160c16b537SWarner Losh     params.steps = 4;
111719fcbaf1SConrad Meyer     /* Default to level 6 since no compression level information is available */
11180f743729SConrad Meyer     params.zParams.compressionLevel = 3;
11190f743729SConrad Meyer #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)
11200f743729SConrad Meyer     params.zParams.notificationLevel = DEBUGLEVEL;
112119fcbaf1SConrad Meyer #endif
11220f743729SConrad Meyer     return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,
112319fcbaf1SConrad Meyer                                                samplesBuffer, samplesSizes, nbSamples,
112419fcbaf1SConrad Meyer                                                &params);
11250c16b537SWarner Losh }
11260c16b537SWarner Losh 
11270c16b537SWarner Losh size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
11280c16b537SWarner Losh                                   const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
11290c16b537SWarner Losh {
11300c16b537SWarner Losh     ZDICT_params_t params;
11310c16b537SWarner Losh     memset(&params, 0, sizeof(params));
11320c16b537SWarner Losh     return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,
11330c16b537SWarner Losh                                                      samplesBuffer, samplesSizes, nbSamples,
11340c16b537SWarner Losh                                                      params);
11350c16b537SWarner Losh }
1136