xref: /freebsd/sys/contrib/zstd/lib/dictBuilder/zdict.c (revision 5ff13fbc199bdf5f0572845351c68ee5ca828e71)
10c16b537SWarner Losh /*
2*5ff13fbcSAllan Jude  * Copyright (c) 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 */
26*5ff13fbcSAllan Jude #  ifndef _LARGEFILE_SOURCE
270c16b537SWarner Losh #  define _LARGEFILE_SOURCE
28*5ff13fbcSAllan Jude #  endif
290c16b537SWarner Losh #elif ! defined(__LP64__)                        /* No point defining Large file for 64 bit */
30*5ff13fbcSAllan Jude #  ifndef _LARGEFILE64_SOURCE
310c16b537SWarner Losh #  define _LARGEFILE64_SOURCE
320c16b537SWarner Losh #  endif
33*5ff13fbcSAllan Jude #endif
340c16b537SWarner Losh 
350c16b537SWarner Losh 
360c16b537SWarner Losh /*-*************************************
370c16b537SWarner Losh *  Dependencies
380c16b537SWarner Losh ***************************************/
390c16b537SWarner Losh #include <stdlib.h>        /* malloc, free */
400c16b537SWarner Losh #include <string.h>        /* memset */
410c16b537SWarner Losh #include <stdio.h>         /* fprintf, fopen, ftello64 */
420c16b537SWarner Losh #include <time.h>          /* clock */
430c16b537SWarner Losh 
440c16b537SWarner Losh #ifndef ZDICT_STATIC_LINKING_ONLY
450c16b537SWarner Losh #  define ZDICT_STATIC_LINKING_ONLY
460c16b537SWarner Losh #endif
47*5ff13fbcSAllan Jude #define HUF_STATIC_LINKING_ONLY
48*5ff13fbcSAllan Jude 
49*5ff13fbcSAllan Jude #include "../common/mem.h"           /* read */
50*5ff13fbcSAllan Jude #include "../common/fse.h"           /* FSE_normalizeCount, FSE_writeNCount */
51*5ff13fbcSAllan Jude #include "../common/huf.h"           /* HUF_buildCTable, HUF_writeCTable */
52*5ff13fbcSAllan Jude #include "../common/zstd_internal.h" /* includes zstd.h */
53*5ff13fbcSAllan Jude #include "../common/xxhash.h"        /* XXH64 */
5437f1f268SConrad Meyer #include "../compress/zstd_compress_internal.h" /* ZSTD_loadCEntropy() */
55*5ff13fbcSAllan Jude #include "../zdict.h"
56*5ff13fbcSAllan Jude #include "divsufsort.h"
570c16b537SWarner Losh 
580c16b537SWarner Losh 
590c16b537SWarner Losh /*-*************************************
600c16b537SWarner Losh *  Constants
610c16b537SWarner Losh ***************************************/
620c16b537SWarner Losh #define KB *(1 <<10)
630c16b537SWarner Losh #define MB *(1 <<20)
640c16b537SWarner Losh #define GB *(1U<<30)
650c16b537SWarner Losh 
660c16b537SWarner Losh #define DICTLISTSIZE_DEFAULT 10000
670c16b537SWarner Losh 
680c16b537SWarner Losh #define NOISELENGTH 32
690c16b537SWarner Losh 
700c16b537SWarner Losh static const U32 g_selectivity_default = 9;
710c16b537SWarner Losh 
720c16b537SWarner Losh 
730c16b537SWarner Losh /*-*************************************
740c16b537SWarner Losh *  Console display
750c16b537SWarner Losh ***************************************/
76f7cd7fe5SConrad Meyer #undef  DISPLAY
770c16b537SWarner Losh #define DISPLAY(...)         { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }
78f7cd7fe5SConrad Meyer #undef  DISPLAYLEVEL
790c16b537SWarner Losh #define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); }    /* 0 : no display;   1: errors;   2: default;  3: details;  4: debug */
800c16b537SWarner Losh 
ZDICT_clockSpan(clock_t nPrevious)810c16b537SWarner Losh static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
820c16b537SWarner Losh 
ZDICT_printHex(const void * ptr,size_t length)830c16b537SWarner Losh static void ZDICT_printHex(const void* ptr, size_t length)
840c16b537SWarner Losh {
850c16b537SWarner Losh     const BYTE* const b = (const BYTE*)ptr;
860c16b537SWarner Losh     size_t u;
870c16b537SWarner Losh     for (u=0; u<length; u++) {
880c16b537SWarner Losh         BYTE c = b[u];
890c16b537SWarner Losh         if (c<32 || c>126) c = '.';   /* non-printable char */
900c16b537SWarner Losh         DISPLAY("%c", c);
910c16b537SWarner Losh     }
920c16b537SWarner Losh }
930c16b537SWarner Losh 
940c16b537SWarner Losh 
950c16b537SWarner Losh /*-********************************************************
960c16b537SWarner Losh *  Helper functions
970c16b537SWarner Losh **********************************************************/
ZDICT_isError(size_t errorCode)980c16b537SWarner Losh unsigned ZDICT_isError(size_t errorCode) { return ERR_isError(errorCode); }
990c16b537SWarner Losh 
ZDICT_getErrorName(size_t errorCode)1000c16b537SWarner Losh const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
1010c16b537SWarner Losh 
ZDICT_getDictID(const void * dictBuffer,size_t dictSize)1020c16b537SWarner Losh unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize)
1030c16b537SWarner Losh {
1040c16b537SWarner Losh     if (dictSize < 8) return 0;
1050c16b537SWarner Losh     if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;
1060c16b537SWarner Losh     return MEM_readLE32((const char*)dictBuffer + 4);
1070c16b537SWarner Losh }
1080c16b537SWarner Losh 
ZDICT_getDictHeaderSize(const void * dictBuffer,size_t dictSize)10937f1f268SConrad Meyer size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize)
11037f1f268SConrad Meyer {
11137f1f268SConrad Meyer     size_t headerSize;
11237f1f268SConrad Meyer     if (dictSize <= 8 || MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return ERROR(dictionary_corrupted);
11337f1f268SConrad Meyer 
114f7cd7fe5SConrad Meyer     {   ZSTD_compressedBlockState_t* bs = (ZSTD_compressedBlockState_t*)malloc(sizeof(ZSTD_compressedBlockState_t));
11537f1f268SConrad Meyer         U32* wksp = (U32*)malloc(HUF_WORKSPACE_SIZE);
116f7cd7fe5SConrad Meyer         if (!bs || !wksp) {
11737f1f268SConrad Meyer             headerSize = ERROR(memory_allocation);
11837f1f268SConrad Meyer         } else {
11937f1f268SConrad Meyer             ZSTD_reset_compressedBlockState(bs);
120f7cd7fe5SConrad Meyer             headerSize = ZSTD_loadCEntropy(bs, wksp, dictBuffer, dictSize);
12137f1f268SConrad Meyer         }
12237f1f268SConrad Meyer 
12337f1f268SConrad Meyer         free(bs);
12437f1f268SConrad Meyer         free(wksp);
12537f1f268SConrad Meyer     }
12637f1f268SConrad Meyer 
12737f1f268SConrad Meyer     return headerSize;
12837f1f268SConrad Meyer }
1290c16b537SWarner Losh 
1300c16b537SWarner Losh /*-********************************************************
1310c16b537SWarner Losh *  Dictionary training functions
1320c16b537SWarner Losh **********************************************************/
ZDICT_NbCommonBytes(size_t val)133052d3c12SConrad Meyer static unsigned ZDICT_NbCommonBytes (size_t val)
1340c16b537SWarner Losh {
1350c16b537SWarner Losh     if (MEM_isLittleEndian()) {
1360c16b537SWarner Losh         if (MEM_64bits()) {
1370c16b537SWarner Losh #       if defined(_MSC_VER) && defined(_WIN64)
138*5ff13fbcSAllan Jude             if (val != 0) {
139*5ff13fbcSAllan Jude                 unsigned long r;
1400c16b537SWarner Losh                 _BitScanForward64(&r, (U64)val);
1410c16b537SWarner Losh                 return (unsigned)(r >> 3);
142*5ff13fbcSAllan Jude             } else {
143*5ff13fbcSAllan Jude                 /* Should not reach this code path */
144*5ff13fbcSAllan Jude                 __assume(0);
145*5ff13fbcSAllan Jude             }
1460c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
147*5ff13fbcSAllan Jude             return (unsigned)(__builtin_ctzll((U64)val) >> 3);
1480c16b537SWarner Losh #       else
1490c16b537SWarner 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 };
1500c16b537SWarner Losh             return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
1510c16b537SWarner Losh #       endif
1520c16b537SWarner Losh         } else { /* 32 bits */
1530c16b537SWarner Losh #       if defined(_MSC_VER)
154*5ff13fbcSAllan Jude             if (val != 0) {
155*5ff13fbcSAllan Jude                 unsigned long r;
1560c16b537SWarner Losh                 _BitScanForward(&r, (U32)val);
1570c16b537SWarner Losh                 return (unsigned)(r >> 3);
158*5ff13fbcSAllan Jude             } else {
159*5ff13fbcSAllan Jude                 /* Should not reach this code path */
160*5ff13fbcSAllan Jude                 __assume(0);
161*5ff13fbcSAllan Jude             }
1620c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
163*5ff13fbcSAllan Jude             return (unsigned)(__builtin_ctz((U32)val) >> 3);
1640c16b537SWarner Losh #       else
1650c16b537SWarner 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 };
1660c16b537SWarner Losh             return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
1670c16b537SWarner Losh #       endif
1680c16b537SWarner Losh         }
1690c16b537SWarner Losh     } else {  /* Big Endian CPU */
1700c16b537SWarner Losh         if (MEM_64bits()) {
1710c16b537SWarner Losh #       if defined(_MSC_VER) && defined(_WIN64)
172*5ff13fbcSAllan Jude             if (val != 0) {
173*5ff13fbcSAllan Jude                 unsigned long r;
1740c16b537SWarner Losh                 _BitScanReverse64(&r, val);
1750c16b537SWarner Losh                 return (unsigned)(r >> 3);
176*5ff13fbcSAllan Jude             } else {
177*5ff13fbcSAllan Jude                 /* Should not reach this code path */
178*5ff13fbcSAllan Jude                 __assume(0);
179*5ff13fbcSAllan Jude             }
1800c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
181*5ff13fbcSAllan Jude             return (unsigned)(__builtin_clzll(val) >> 3);
1820c16b537SWarner Losh #       else
1830c16b537SWarner Losh             unsigned r;
1840c16b537SWarner Losh             const unsigned n32 = sizeof(size_t)*4;   /* calculate this way due to compiler complaining in 32-bits mode */
1850c16b537SWarner Losh             if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
1860c16b537SWarner Losh             if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
1870c16b537SWarner Losh             r += (!val);
1880c16b537SWarner Losh             return r;
1890c16b537SWarner Losh #       endif
1900c16b537SWarner Losh         } else { /* 32 bits */
1910c16b537SWarner Losh #       if defined(_MSC_VER)
192*5ff13fbcSAllan Jude             if (val != 0) {
193*5ff13fbcSAllan Jude                 unsigned long r;
1940c16b537SWarner Losh                 _BitScanReverse(&r, (unsigned long)val);
1950c16b537SWarner Losh                 return (unsigned)(r >> 3);
196*5ff13fbcSAllan Jude             } else {
197*5ff13fbcSAllan Jude                 /* Should not reach this code path */
198*5ff13fbcSAllan Jude                 __assume(0);
199*5ff13fbcSAllan Jude             }
2000c16b537SWarner Losh #       elif defined(__GNUC__) && (__GNUC__ >= 3)
201*5ff13fbcSAllan Jude             return (unsigned)(__builtin_clz((U32)val) >> 3);
2020c16b537SWarner Losh #       else
2030c16b537SWarner Losh             unsigned r;
2040c16b537SWarner Losh             if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
2050c16b537SWarner Losh             r += (!val);
2060c16b537SWarner Losh             return r;
2070c16b537SWarner Losh #       endif
2080c16b537SWarner Losh     }   }
2090c16b537SWarner Losh }
2100c16b537SWarner Losh 
2110c16b537SWarner Losh 
2120c16b537SWarner Losh /*! ZDICT_count() :
2130c16b537SWarner Losh     Count the nb of common bytes between 2 pointers.
2140c16b537SWarner Losh     Note : this function presumes end of buffer followed by noisy guard band.
2150c16b537SWarner Losh */
ZDICT_count(const void * pIn,const void * pMatch)2160c16b537SWarner Losh static size_t ZDICT_count(const void* pIn, const void* pMatch)
2170c16b537SWarner Losh {
2180c16b537SWarner Losh     const char* const pStart = (const char*)pIn;
2190c16b537SWarner Losh     for (;;) {
2200c16b537SWarner Losh         size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
2210c16b537SWarner Losh         if (!diff) {
2220c16b537SWarner Losh             pIn = (const char*)pIn+sizeof(size_t);
2230c16b537SWarner Losh             pMatch = (const char*)pMatch+sizeof(size_t);
2240c16b537SWarner Losh             continue;
2250c16b537SWarner Losh         }
2260c16b537SWarner Losh         pIn = (const char*)pIn+ZDICT_NbCommonBytes(diff);
2270c16b537SWarner Losh         return (size_t)((const char*)pIn - pStart);
2280c16b537SWarner Losh     }
2290c16b537SWarner Losh }
2300c16b537SWarner Losh 
2310c16b537SWarner Losh 
2320c16b537SWarner Losh typedef struct {
2330c16b537SWarner Losh     U32 pos;
2340c16b537SWarner Losh     U32 length;
2350c16b537SWarner Losh     U32 savings;
2360c16b537SWarner Losh } dictItem;
2370c16b537SWarner Losh 
ZDICT_initDictItem(dictItem * d)2380c16b537SWarner Losh static void ZDICT_initDictItem(dictItem* d)
2390c16b537SWarner Losh {
2400c16b537SWarner Losh     d->pos = 1;
2410c16b537SWarner Losh     d->length = 0;
2420c16b537SWarner Losh     d->savings = (U32)(-1);
2430c16b537SWarner Losh }
2440c16b537SWarner Losh 
2450c16b537SWarner Losh 
2460c16b537SWarner Losh #define LLIMIT 64          /* heuristic determined experimentally */
2470c16b537SWarner Losh #define MINMATCHLENGTH 7   /* heuristic determined experimentally */
ZDICT_analyzePos(BYTE * doneMarks,const int * suffix,U32 start,const void * buffer,U32 minRatio,U32 notificationLevel)2480c16b537SWarner Losh static dictItem ZDICT_analyzePos(
2490c16b537SWarner Losh                        BYTE* doneMarks,
2500c16b537SWarner Losh                        const int* suffix, U32 start,
2510c16b537SWarner Losh                        const void* buffer, U32 minRatio, U32 notificationLevel)
2520c16b537SWarner Losh {
2530c16b537SWarner Losh     U32 lengthList[LLIMIT] = {0};
2540c16b537SWarner Losh     U32 cumulLength[LLIMIT] = {0};
2550c16b537SWarner Losh     U32 savings[LLIMIT] = {0};
2560c16b537SWarner Losh     const BYTE* b = (const BYTE*)buffer;
2570c16b537SWarner Losh     size_t maxLength = LLIMIT;
258*5ff13fbcSAllan Jude     size_t pos = (size_t)suffix[start];
2590c16b537SWarner Losh     U32 end = start;
2600c16b537SWarner Losh     dictItem solution;
2610c16b537SWarner Losh 
2620c16b537SWarner Losh     /* init */
2630c16b537SWarner Losh     memset(&solution, 0, sizeof(solution));
2640c16b537SWarner Losh     doneMarks[pos] = 1;
2650c16b537SWarner Losh 
2660c16b537SWarner Losh     /* trivial repetition cases */
2670c16b537SWarner Losh     if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))
2680c16b537SWarner Losh        ||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))
2690c16b537SWarner Losh        ||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {
2700c16b537SWarner Losh         /* skip and mark segment */
27119fcbaf1SConrad Meyer         U16 const pattern16 = MEM_read16(b+pos+4);
27219fcbaf1SConrad Meyer         U32 u, patternEnd = 6;
27319fcbaf1SConrad Meyer         while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;
27419fcbaf1SConrad Meyer         if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;
27519fcbaf1SConrad Meyer         for (u=1; u<patternEnd; u++)
2760c16b537SWarner Losh             doneMarks[pos+u] = 1;
2770c16b537SWarner Losh         return solution;
2780c16b537SWarner Losh     }
2790c16b537SWarner Losh 
2800c16b537SWarner Losh     /* look forward */
28119fcbaf1SConrad Meyer     {   size_t length;
2820c16b537SWarner Losh         do {
2830c16b537SWarner Losh             end++;
2840c16b537SWarner Losh             length = ZDICT_count(b + pos, b + suffix[end]);
2850c16b537SWarner Losh         } while (length >= MINMATCHLENGTH);
28619fcbaf1SConrad Meyer     }
2870c16b537SWarner Losh 
2880c16b537SWarner Losh     /* look backward */
28919fcbaf1SConrad Meyer     {   size_t length;
2900c16b537SWarner Losh         do {
2910c16b537SWarner Losh             length = ZDICT_count(b + pos, b + *(suffix+start-1));
2920c16b537SWarner Losh             if (length >=MINMATCHLENGTH) start--;
2930c16b537SWarner Losh         } while(length >= MINMATCHLENGTH);
29419fcbaf1SConrad Meyer     }
2950c16b537SWarner Losh 
2960c16b537SWarner Losh     /* exit if not found a minimum nb of repetitions */
2970c16b537SWarner Losh     if (end-start < minRatio) {
2980c16b537SWarner Losh         U32 idx;
2990c16b537SWarner Losh         for(idx=start; idx<end; idx++)
3000c16b537SWarner Losh             doneMarks[suffix[idx]] = 1;
3010c16b537SWarner Losh         return solution;
3020c16b537SWarner Losh     }
3030c16b537SWarner Losh 
3040c16b537SWarner Losh     {   int i;
305a0483764SConrad Meyer         U32 mml;
3060c16b537SWarner Losh         U32 refinedStart = start;
3070c16b537SWarner Losh         U32 refinedEnd = end;
3080c16b537SWarner Losh 
3090c16b537SWarner Losh         DISPLAYLEVEL(4, "\n");
310a0483764SConrad Meyer         DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u  ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);
3110c16b537SWarner Losh         DISPLAYLEVEL(4, "\n");
3120c16b537SWarner Losh 
313a0483764SConrad Meyer         for (mml = MINMATCHLENGTH ; ; mml++) {
3140c16b537SWarner Losh             BYTE currentChar = 0;
3150c16b537SWarner Losh             U32 currentCount = 0;
3160c16b537SWarner Losh             U32 currentID = refinedStart;
3170c16b537SWarner Losh             U32 id;
3180c16b537SWarner Losh             U32 selectedCount = 0;
3190c16b537SWarner Losh             U32 selectedID = currentID;
3200c16b537SWarner Losh             for (id =refinedStart; id < refinedEnd; id++) {
321a0483764SConrad Meyer                 if (b[suffix[id] + mml] != currentChar) {
3220c16b537SWarner Losh                     if (currentCount > selectedCount) {
3230c16b537SWarner Losh                         selectedCount = currentCount;
3240c16b537SWarner Losh                         selectedID = currentID;
3250c16b537SWarner Losh                     }
3260c16b537SWarner Losh                     currentID = id;
327a0483764SConrad Meyer                     currentChar = b[ suffix[id] + mml];
3280c16b537SWarner Losh                     currentCount = 0;
3290c16b537SWarner Losh                 }
3300c16b537SWarner Losh                 currentCount ++;
3310c16b537SWarner Losh             }
3320c16b537SWarner Losh             if (currentCount > selectedCount) {  /* for last */
3330c16b537SWarner Losh                 selectedCount = currentCount;
3340c16b537SWarner Losh                 selectedID = currentID;
3350c16b537SWarner Losh             }
3360c16b537SWarner Losh 
3370c16b537SWarner Losh             if (selectedCount < minRatio)
3380c16b537SWarner Losh                 break;
3390c16b537SWarner Losh             refinedStart = selectedID;
3400c16b537SWarner Losh             refinedEnd = refinedStart + selectedCount;
3410c16b537SWarner Losh         }
3420c16b537SWarner Losh 
3430f743729SConrad Meyer         /* evaluate gain based on new dict */
3440c16b537SWarner Losh         start = refinedStart;
3450c16b537SWarner Losh         pos = suffix[refinedStart];
3460c16b537SWarner Losh         end = start;
3470c16b537SWarner Losh         memset(lengthList, 0, sizeof(lengthList));
3480c16b537SWarner Losh 
3490c16b537SWarner Losh         /* look forward */
35019fcbaf1SConrad Meyer         {   size_t length;
3510c16b537SWarner Losh             do {
3520c16b537SWarner Losh                 end++;
3530c16b537SWarner Losh                 length = ZDICT_count(b + pos, b + suffix[end]);
3540c16b537SWarner Losh                 if (length >= LLIMIT) length = LLIMIT-1;
3550c16b537SWarner Losh                 lengthList[length]++;
3560c16b537SWarner Losh             } while (length >=MINMATCHLENGTH);
35719fcbaf1SConrad Meyer         }
3580c16b537SWarner Losh 
3590c16b537SWarner Losh         /* look backward */
36019fcbaf1SConrad Meyer         {   size_t length = MINMATCHLENGTH;
3610c16b537SWarner Losh             while ((length >= MINMATCHLENGTH) & (start > 0)) {
3620c16b537SWarner Losh                 length = ZDICT_count(b + pos, b + suffix[start - 1]);
3630c16b537SWarner Losh                 if (length >= LLIMIT) length = LLIMIT - 1;
3640c16b537SWarner Losh                 lengthList[length]++;
3650c16b537SWarner Losh                 if (length >= MINMATCHLENGTH) start--;
3660c16b537SWarner Losh             }
36719fcbaf1SConrad Meyer         }
3680c16b537SWarner Losh 
3690c16b537SWarner Losh         /* largest useful length */
3700c16b537SWarner Losh         memset(cumulLength, 0, sizeof(cumulLength));
3710c16b537SWarner Losh         cumulLength[maxLength-1] = lengthList[maxLength-1];
3720c16b537SWarner Losh         for (i=(int)(maxLength-2); i>=0; i--)
3730c16b537SWarner Losh             cumulLength[i] = cumulLength[i+1] + lengthList[i];
3740c16b537SWarner Losh 
3750c16b537SWarner Losh         for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;
3760c16b537SWarner Losh         maxLength = i;
3770c16b537SWarner Losh 
3780c16b537SWarner Losh         /* reduce maxLength in case of final into repetitive data */
3790c16b537SWarner Losh         {   U32 l = (U32)maxLength;
3800c16b537SWarner Losh             BYTE const c = b[pos + maxLength-1];
3810c16b537SWarner Losh             while (b[pos+l-2]==c) l--;
3820c16b537SWarner Losh             maxLength = l;
3830c16b537SWarner Losh         }
3840c16b537SWarner Losh         if (maxLength < MINMATCHLENGTH) return solution;   /* skip : no long-enough solution */
3850c16b537SWarner Losh 
3860c16b537SWarner Losh         /* calculate savings */
3870c16b537SWarner Losh         savings[5] = 0;
3880c16b537SWarner Losh         for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)
3890c16b537SWarner Losh             savings[i] = savings[i-1] + (lengthList[i] * (i-3));
3900c16b537SWarner Losh 
3910f743729SConrad Meyer         DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f)  \n",
392*5ff13fbcSAllan Jude                      (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / (double)maxLength);
3930c16b537SWarner Losh 
3940c16b537SWarner Losh         solution.pos = (U32)pos;
3950c16b537SWarner Losh         solution.length = (U32)maxLength;
3960c16b537SWarner Losh         solution.savings = savings[maxLength];
3970c16b537SWarner Losh 
3980c16b537SWarner Losh         /* mark positions done */
3990c16b537SWarner Losh         {   U32 id;
4000c16b537SWarner Losh             for (id=start; id<end; id++) {
40119fcbaf1SConrad Meyer                 U32 p, pEnd, length;
402*5ff13fbcSAllan Jude                 U32 const testedPos = (U32)suffix[id];
4030c16b537SWarner Losh                 if (testedPos == pos)
4040c16b537SWarner Losh                     length = solution.length;
4050c16b537SWarner Losh                 else {
40619fcbaf1SConrad Meyer                     length = (U32)ZDICT_count(b+pos, b+testedPos);
4070c16b537SWarner Losh                     if (length > solution.length) length = solution.length;
4080c16b537SWarner Losh                 }
4090c16b537SWarner Losh                 pEnd = (U32)(testedPos + length);
4100c16b537SWarner Losh                 for (p=testedPos; p<pEnd; p++)
4110c16b537SWarner Losh                     doneMarks[p] = 1;
4120c16b537SWarner Losh     }   }   }
4130c16b537SWarner Losh 
4140c16b537SWarner Losh     return solution;
4150c16b537SWarner Losh }
4160c16b537SWarner Losh 
4170c16b537SWarner Losh 
isIncluded(const void * in,const void * container,size_t length)4180c16b537SWarner Losh static int isIncluded(const void* in, const void* container, size_t length)
4190c16b537SWarner Losh {
4200c16b537SWarner Losh     const char* const ip = (const char*) in;
4210c16b537SWarner Losh     const char* const into = (const char*) container;
4220c16b537SWarner Losh     size_t u;
4230c16b537SWarner Losh 
4240c16b537SWarner Losh     for (u=0; u<length; u++) {  /* works because end of buffer is a noisy guard band */
4250c16b537SWarner Losh         if (ip[u] != into[u]) break;
4260c16b537SWarner Losh     }
4270c16b537SWarner Losh 
4280c16b537SWarner Losh     return u==length;
4290c16b537SWarner Losh }
4300c16b537SWarner Losh 
4310c16b537SWarner Losh /*! ZDICT_tryMerge() :
4320c16b537SWarner Losh     check if dictItem can be merged, do it if possible
4330c16b537SWarner Losh     @return : id of destination elt, 0 if not merged
4340c16b537SWarner Losh */
ZDICT_tryMerge(dictItem * table,dictItem elt,U32 eltNbToSkip,const void * buffer)4350c16b537SWarner Losh static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const void* buffer)
4360c16b537SWarner Losh {
4370c16b537SWarner Losh     const U32 tableSize = table->pos;
4380c16b537SWarner Losh     const U32 eltEnd = elt.pos + elt.length;
4390c16b537SWarner Losh     const char* const buf = (const char*) buffer;
4400c16b537SWarner Losh 
4410c16b537SWarner Losh     /* tail overlap */
4420c16b537SWarner Losh     U32 u; for (u=1; u<tableSize; u++) {
4430c16b537SWarner Losh         if (u==eltNbToSkip) continue;
4440c16b537SWarner Losh         if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) {  /* overlap, existing > new */
4450c16b537SWarner Losh             /* append */
4460c16b537SWarner Losh             U32 const addedLength = table[u].pos - elt.pos;
4470c16b537SWarner Losh             table[u].length += addedLength;
4480c16b537SWarner Losh             table[u].pos = elt.pos;
4490c16b537SWarner Losh             table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
4500c16b537SWarner Losh             table[u].savings += elt.length / 8;    /* rough approx bonus */
4510c16b537SWarner Losh             elt = table[u];
4520c16b537SWarner Losh             /* sort : improve rank */
4530c16b537SWarner Losh             while ((u>1) && (table[u-1].savings < elt.savings))
4540c16b537SWarner Losh             table[u] = table[u-1], u--;
4550c16b537SWarner Losh             table[u] = elt;
4560c16b537SWarner Losh             return u;
4570c16b537SWarner Losh     }   }
4580c16b537SWarner Losh 
4590c16b537SWarner Losh     /* front overlap */
4600c16b537SWarner Losh     for (u=1; u<tableSize; u++) {
4610c16b537SWarner Losh         if (u==eltNbToSkip) continue;
4620c16b537SWarner Losh 
4630c16b537SWarner Losh         if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) {  /* overlap, existing < new */
4640c16b537SWarner Losh             /* append */
465*5ff13fbcSAllan Jude             int const addedLength = (int)eltEnd - (int)(table[u].pos + table[u].length);
4660c16b537SWarner Losh             table[u].savings += elt.length / 8;    /* rough approx bonus */
4670c16b537SWarner Losh             if (addedLength > 0) {   /* otherwise, elt fully included into existing */
4680c16b537SWarner Losh                 table[u].length += addedLength;
4690c16b537SWarner Losh                 table[u].savings += elt.savings * addedLength / elt.length;   /* rough approx */
4700c16b537SWarner Losh             }
4710c16b537SWarner Losh             /* sort : improve rank */
4720c16b537SWarner Losh             elt = table[u];
4730c16b537SWarner Losh             while ((u>1) && (table[u-1].savings < elt.savings))
4740c16b537SWarner Losh                 table[u] = table[u-1], u--;
4750c16b537SWarner Losh             table[u] = elt;
4760c16b537SWarner Losh             return u;
4770c16b537SWarner Losh         }
4780c16b537SWarner Losh 
4790c16b537SWarner Losh         if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {
4800c16b537SWarner Losh             if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {
4810c16b537SWarner Losh                 size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );
4820c16b537SWarner Losh                 table[u].pos = elt.pos;
4830c16b537SWarner Losh                 table[u].savings += (U32)(elt.savings * addedLength / elt.length);
4840c16b537SWarner Losh                 table[u].length = MIN(elt.length, table[u].length + 1);
4850c16b537SWarner Losh                 return u;
4860c16b537SWarner Losh             }
4870c16b537SWarner Losh         }
4880c16b537SWarner Losh     }
4890c16b537SWarner Losh 
4900c16b537SWarner Losh     return 0;
4910c16b537SWarner Losh }
4920c16b537SWarner Losh 
4930c16b537SWarner Losh 
ZDICT_removeDictItem(dictItem * table,U32 id)4940c16b537SWarner Losh static void ZDICT_removeDictItem(dictItem* table, U32 id)
4950c16b537SWarner Losh {
4960c16b537SWarner Losh     /* convention : table[0].pos stores nb of elts */
4970c16b537SWarner Losh     U32 const max = table[0].pos;
4980c16b537SWarner Losh     U32 u;
4990c16b537SWarner Losh     if (!id) return;   /* protection, should never happen */
5000c16b537SWarner Losh     for (u=id; u<max-1; u++)
5010c16b537SWarner Losh         table[u] = table[u+1];
5020c16b537SWarner Losh     table->pos--;
5030c16b537SWarner Losh }
5040c16b537SWarner Losh 
5050c16b537SWarner Losh 
ZDICT_insertDictItem(dictItem * table,U32 maxSize,dictItem elt,const void * buffer)5060c16b537SWarner Losh static void ZDICT_insertDictItem(dictItem* table, U32 maxSize, dictItem elt, const void* buffer)
5070c16b537SWarner Losh {
5080c16b537SWarner Losh     /* merge if possible */
5090c16b537SWarner Losh     U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);
5100c16b537SWarner Losh     if (mergeId) {
5110c16b537SWarner Losh         U32 newMerge = 1;
5120c16b537SWarner Losh         while (newMerge) {
5130c16b537SWarner Losh             newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);
5140c16b537SWarner Losh             if (newMerge) ZDICT_removeDictItem(table, mergeId);
5150c16b537SWarner Losh             mergeId = newMerge;
5160c16b537SWarner Losh         }
5170c16b537SWarner Losh         return;
5180c16b537SWarner Losh     }
5190c16b537SWarner Losh 
5200c16b537SWarner Losh     /* insert */
5210c16b537SWarner Losh     {   U32 current;
5220c16b537SWarner Losh         U32 nextElt = table->pos;
5230c16b537SWarner Losh         if (nextElt >= maxSize) nextElt = maxSize-1;
5240c16b537SWarner Losh         current = nextElt-1;
5250c16b537SWarner Losh         while (table[current].savings < elt.savings) {
5260c16b537SWarner Losh             table[current+1] = table[current];
5270c16b537SWarner Losh             current--;
5280c16b537SWarner Losh         }
5290c16b537SWarner Losh         table[current+1] = elt;
5300c16b537SWarner Losh         table->pos = nextElt+1;
5310c16b537SWarner Losh     }
5320c16b537SWarner Losh }
5330c16b537SWarner Losh 
5340c16b537SWarner Losh 
ZDICT_dictSize(const dictItem * dictList)5350c16b537SWarner Losh static U32 ZDICT_dictSize(const dictItem* dictList)
5360c16b537SWarner Losh {
5370c16b537SWarner Losh     U32 u, dictSize = 0;
5380c16b537SWarner Losh     for (u=1; u<dictList[0].pos; u++)
5390c16b537SWarner Losh         dictSize += dictList[u].length;
5400c16b537SWarner Losh     return dictSize;
5410c16b537SWarner Losh }
5420c16b537SWarner Losh 
5430c16b537SWarner Losh 
ZDICT_trainBuffer_legacy(dictItem * dictList,U32 dictListSize,const void * const buffer,size_t bufferSize,const size_t * fileSizes,unsigned nbFiles,unsigned minRatio,U32 notificationLevel)5440c16b537SWarner Losh static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,
5450c16b537SWarner Losh                             const void* const buffer, size_t bufferSize,   /* buffer must end with noisy guard band */
5460c16b537SWarner Losh                             const size_t* fileSizes, unsigned nbFiles,
547a0483764SConrad Meyer                             unsigned minRatio, U32 notificationLevel)
5480c16b537SWarner Losh {
5490c16b537SWarner Losh     int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));
5500c16b537SWarner Losh     int* const suffix = suffix0+1;
5510c16b537SWarner Losh     U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));
5520c16b537SWarner Losh     BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks));   /* +16 for overflow security */
5530c16b537SWarner Losh     U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));
5540c16b537SWarner Losh     size_t result = 0;
5550c16b537SWarner Losh     clock_t displayClock = 0;
5560c16b537SWarner Losh     clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
5570c16b537SWarner Losh 
558f7cd7fe5SConrad Meyer #   undef  DISPLAYUPDATE
5590c16b537SWarner Losh #   define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \
5600c16b537SWarner Losh             if (ZDICT_clockSpan(displayClock) > refreshRate)  \
5610c16b537SWarner Losh             { displayClock = clock(); DISPLAY(__VA_ARGS__); \
5620c16b537SWarner Losh             if (notificationLevel>=4) fflush(stderr); } }
5630c16b537SWarner Losh 
5640c16b537SWarner Losh     /* init */
5650c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
5660c16b537SWarner Losh     if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
5670c16b537SWarner Losh         result = ERROR(memory_allocation);
5680c16b537SWarner Losh         goto _cleanup;
5690c16b537SWarner Losh     }
5700c16b537SWarner Losh     if (minRatio < MINRATIO) minRatio = MINRATIO;
5710c16b537SWarner Losh     memset(doneMarks, 0, bufferSize+16);
5720c16b537SWarner Losh 
5730c16b537SWarner Losh     /* limit sample set size (divsufsort limitation)*/
574a0483764SConrad Meyer     if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
5750c16b537SWarner Losh     while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
5760c16b537SWarner Losh 
5770c16b537SWarner Losh     /* sort */
578a0483764SConrad Meyer     DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
5790c16b537SWarner Losh     {   int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
5800c16b537SWarner Losh         if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
5810c16b537SWarner Losh     }
5820c16b537SWarner Losh     suffix[bufferSize] = (int)bufferSize;   /* leads into noise */
5830c16b537SWarner Losh     suffix0[0] = (int)bufferSize;           /* leads into noise */
5840c16b537SWarner Losh     /* build reverse suffix sort */
5850c16b537SWarner Losh     {   size_t pos;
5860c16b537SWarner Losh         for (pos=0; pos < bufferSize; pos++)
5870c16b537SWarner Losh             reverseSuffix[suffix[pos]] = (U32)pos;
5880c16b537SWarner Losh         /* note filePos tracks borders between samples.
5890c16b537SWarner Losh            It's not used at this stage, but planned to become useful in a later update */
5900c16b537SWarner Losh         filePos[0] = 0;
5910c16b537SWarner Losh         for (pos=1; pos<nbFiles; pos++)
5920c16b537SWarner Losh             filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
5930c16b537SWarner Losh     }
5940c16b537SWarner Losh 
5950c16b537SWarner Losh     DISPLAYLEVEL(2, "finding patterns ... \n");
5960c16b537SWarner Losh     DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
5970c16b537SWarner Losh 
5980c16b537SWarner Losh     {   U32 cursor; for (cursor=0; cursor < bufferSize; ) {
5990c16b537SWarner Losh             dictItem solution;
6000c16b537SWarner Losh             if (doneMarks[cursor]) { cursor++; continue; }
6010c16b537SWarner Losh             solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
6020c16b537SWarner Losh             if (solution.length==0) { cursor++; continue; }
6030c16b537SWarner Losh             ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
6040c16b537SWarner Losh             cursor += solution.length;
6050c16b537SWarner Losh             DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / bufferSize * 100);
6060c16b537SWarner Losh     }   }
6070c16b537SWarner Losh 
6080c16b537SWarner Losh _cleanup:
6090c16b537SWarner Losh     free(suffix0);
6100c16b537SWarner Losh     free(reverseSuffix);
6110c16b537SWarner Losh     free(doneMarks);
6120c16b537SWarner Losh     free(filePos);
6130c16b537SWarner Losh     return result;
6140c16b537SWarner Losh }
6150c16b537SWarner Losh 
6160c16b537SWarner Losh 
ZDICT_fillNoise(void * buffer,size_t length)6170c16b537SWarner Losh static void ZDICT_fillNoise(void* buffer, size_t length)
6180c16b537SWarner Losh {
6190c16b537SWarner Losh     unsigned const prime1 = 2654435761U;
6200c16b537SWarner Losh     unsigned const prime2 = 2246822519U;
6210c16b537SWarner Losh     unsigned acc = prime1;
6229cbefe25SConrad Meyer     size_t p=0;
6230c16b537SWarner Losh     for (p=0; p<length; p++) {
6240c16b537SWarner Losh         acc *= prime2;
6250c16b537SWarner Losh         ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
6260c16b537SWarner Losh     }
6270c16b537SWarner Losh }
6280c16b537SWarner Losh 
6290c16b537SWarner Losh 
6300c16b537SWarner Losh typedef struct
6310c16b537SWarner Losh {
6320f743729SConrad Meyer     ZSTD_CDict* dict;    /* dictionary */
63319fcbaf1SConrad Meyer     ZSTD_CCtx* zc;     /* working context */
6340c16b537SWarner Losh     void* workPlace;   /* must be ZSTD_BLOCKSIZE_MAX allocated */
6350c16b537SWarner Losh } EStats_ress_t;
6360c16b537SWarner Losh 
6370c16b537SWarner Losh #define MAXREPOFFSET 1024
6380c16b537SWarner Losh 
ZDICT_countEStats(EStats_ress_t esr,const ZSTD_parameters * params,unsigned * countLit,unsigned * offsetcodeCount,unsigned * matchlengthCount,unsigned * litlengthCount,U32 * repOffsets,const void * src,size_t srcSize,U32 notificationLevel)63937f1f268SConrad Meyer static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params,
640a0483764SConrad Meyer                               unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,
64119fcbaf1SConrad Meyer                               const void* src, size_t srcSize,
64219fcbaf1SConrad Meyer                               U32 notificationLevel)
6430c16b537SWarner Losh {
64437f1f268SConrad Meyer     size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params->cParams.windowLog);
6450c16b537SWarner Losh     size_t cSize;
6460c16b537SWarner Losh 
6470c16b537SWarner Losh     if (srcSize > blockSizeMax) srcSize = blockSizeMax;   /* protection vs large samples */
6480f743729SConrad Meyer     {   size_t const errorCode = ZSTD_compressBegin_usingCDict(esr.zc, esr.dict);
6490f743729SConrad Meyer         if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
6500f743729SConrad Meyer 
6510c16b537SWarner Losh     }
6520c16b537SWarner Losh     cSize = ZSTD_compressBlock(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
653a0483764SConrad Meyer     if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
6540c16b537SWarner Losh 
6550c16b537SWarner Losh     if (cSize) {  /* if == 0; block is not compressible */
65619fcbaf1SConrad Meyer         const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
6570c16b537SWarner Losh 
6580c16b537SWarner Losh         /* literals stats */
6590c16b537SWarner Losh         {   const BYTE* bytePtr;
6600c16b537SWarner Losh             for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
6610c16b537SWarner Losh                 countLit[*bytePtr]++;
6620c16b537SWarner Losh         }
6630c16b537SWarner Losh 
6640c16b537SWarner Losh         /* seqStats */
6650c16b537SWarner Losh         {   U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
6660c16b537SWarner Losh             ZSTD_seqToCodes(seqStorePtr);
6670c16b537SWarner Losh 
6680c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->ofCode;
6690c16b537SWarner Losh                 U32 u;
6700c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
6710c16b537SWarner Losh             }
6720c16b537SWarner Losh 
6730c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->mlCode;
6740c16b537SWarner Losh                 U32 u;
6750c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
6760c16b537SWarner Losh             }
6770c16b537SWarner Losh 
6780c16b537SWarner Losh             {   const BYTE* codePtr = seqStorePtr->llCode;
6790c16b537SWarner Losh                 U32 u;
6800c16b537SWarner Losh                 for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
6810c16b537SWarner Losh             }
6820c16b537SWarner Losh 
6830c16b537SWarner Losh             if (nbSeq >= 2) { /* rep offsets */
6840c16b537SWarner Losh                 const seqDef* const seq = seqStorePtr->sequencesStart;
685*5ff13fbcSAllan Jude                 U32 offset1 = seq[0].offBase - ZSTD_REP_NUM;
686*5ff13fbcSAllan Jude                 U32 offset2 = seq[1].offBase - ZSTD_REP_NUM;
6870c16b537SWarner Losh                 if (offset1 >= MAXREPOFFSET) offset1 = 0;
6880c16b537SWarner Losh                 if (offset2 >= MAXREPOFFSET) offset2 = 0;
6890c16b537SWarner Losh                 repOffsets[offset1] += 3;
6900c16b537SWarner Losh                 repOffsets[offset2] += 1;
6910c16b537SWarner Losh     }   }   }
6920c16b537SWarner Losh }
6930c16b537SWarner Losh 
ZDICT_totalSampleSize(const size_t * fileSizes,unsigned nbFiles)6940c16b537SWarner Losh static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)
6950c16b537SWarner Losh {
6960c16b537SWarner Losh     size_t total=0;
6970c16b537SWarner Losh     unsigned u;
6980c16b537SWarner Losh     for (u=0; u<nbFiles; u++) total += fileSizes[u];
6990c16b537SWarner Losh     return total;
7000c16b537SWarner Losh }
7010c16b537SWarner Losh 
7020c16b537SWarner Losh typedef struct { U32 offset; U32 count; } offsetCount_t;
7030c16b537SWarner Losh 
ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1],U32 val,U32 count)7040c16b537SWarner Losh static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
7050c16b537SWarner Losh {
7060c16b537SWarner Losh     U32 u;
7070c16b537SWarner Losh     table[ZSTD_REP_NUM].offset = val;
7080c16b537SWarner Losh     table[ZSTD_REP_NUM].count = count;
7090c16b537SWarner Losh     for (u=ZSTD_REP_NUM; u>0; u--) {
7100c16b537SWarner Losh         offsetCount_t tmp;
7110c16b537SWarner Losh         if (table[u-1].count >= table[u].count) break;
7120c16b537SWarner Losh         tmp = table[u-1];
7130c16b537SWarner Losh         table[u-1] = table[u];
7140c16b537SWarner Losh         table[u] = tmp;
7150c16b537SWarner Losh     }
7160c16b537SWarner Losh }
7170c16b537SWarner Losh 
71819fcbaf1SConrad Meyer /* ZDICT_flatLit() :
71919fcbaf1SConrad Meyer  * rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.
72019fcbaf1SConrad Meyer  * necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.
72119fcbaf1SConrad Meyer  */
ZDICT_flatLit(unsigned * countLit)722a0483764SConrad Meyer static void ZDICT_flatLit(unsigned* countLit)
72319fcbaf1SConrad Meyer {
72419fcbaf1SConrad Meyer     int u;
72519fcbaf1SConrad Meyer     for (u=1; u<256; u++) countLit[u] = 2;
72619fcbaf1SConrad Meyer     countLit[0]   = 4;
72719fcbaf1SConrad Meyer     countLit[253] = 1;
72819fcbaf1SConrad Meyer     countLit[254] = 1;
72919fcbaf1SConrad Meyer }
7300c16b537SWarner Losh 
7310c16b537SWarner Losh #define OFFCODE_MAX 30  /* only applicable to first block */
ZDICT_analyzeEntropy(void * dstBuffer,size_t maxDstSize,int compressionLevel,const void * srcBuffer,const size_t * fileSizes,unsigned nbFiles,const void * dictBuffer,size_t dictBufferSize,unsigned notificationLevel)7320c16b537SWarner Losh static size_t ZDICT_analyzeEntropy(void*  dstBuffer, size_t maxDstSize,
733f7cd7fe5SConrad Meyer                                    int compressionLevel,
7340c16b537SWarner Losh                              const void*  srcBuffer, const size_t* fileSizes, unsigned nbFiles,
7350c16b537SWarner Losh                              const void* dictBuffer, size_t  dictBufferSize,
7360c16b537SWarner Losh                                    unsigned notificationLevel)
7370c16b537SWarner Losh {
738a0483764SConrad Meyer     unsigned countLit[256];
7390c16b537SWarner Losh     HUF_CREATE_STATIC_CTABLE(hufTable, 255);
740a0483764SConrad Meyer     unsigned offcodeCount[OFFCODE_MAX+1];
7410c16b537SWarner Losh     short offcodeNCount[OFFCODE_MAX+1];
7420c16b537SWarner Losh     U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
743a0483764SConrad Meyer     unsigned matchLengthCount[MaxML+1];
7440c16b537SWarner Losh     short matchLengthNCount[MaxML+1];
745a0483764SConrad Meyer     unsigned litLengthCount[MaxLL+1];
7460c16b537SWarner Losh     short litLengthNCount[MaxLL+1];
7470c16b537SWarner Losh     U32 repOffset[MAXREPOFFSET];
7480c16b537SWarner Losh     offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
7490f743729SConrad Meyer     EStats_ress_t esr = { NULL, NULL, NULL };
7500c16b537SWarner Losh     ZSTD_parameters params;
7510c16b537SWarner Losh     U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
7520c16b537SWarner Losh     size_t pos = 0, errorCode;
7530c16b537SWarner Losh     size_t eSize = 0;
7540c16b537SWarner Losh     size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
7550c16b537SWarner Losh     size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
7560c16b537SWarner Losh     BYTE* dstPtr = (BYTE*)dstBuffer;
7570c16b537SWarner Losh 
7580c16b537SWarner Losh     /* init */
75919fcbaf1SConrad Meyer     DEBUGLOG(4, "ZDICT_analyzeEntropy");
7600c16b537SWarner Losh     if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; }   /* too large dictionary */
7610c16b537SWarner Losh     for (u=0; u<256; u++) countLit[u] = 1;   /* any character must be described */
7620c16b537SWarner Losh     for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
7630c16b537SWarner Losh     for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
7640c16b537SWarner Losh     for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
7650c16b537SWarner Losh     memset(repOffset, 0, sizeof(repOffset));
7660c16b537SWarner Losh     repOffset[1] = repOffset[4] = repOffset[8] = 1;
7670c16b537SWarner Losh     memset(bestRepOffset, 0, sizeof(bestRepOffset));
768f7cd7fe5SConrad Meyer     if (compressionLevel==0) compressionLevel = ZSTD_CLEVEL_DEFAULT;
7690c16b537SWarner Losh     params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
7700f743729SConrad Meyer 
7710f743729SConrad Meyer     esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
7720f743729SConrad Meyer     esr.zc = ZSTD_createCCtx();
7730f743729SConrad Meyer     esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
7740f743729SConrad Meyer     if (!esr.dict || !esr.zc || !esr.workPlace) {
7750f743729SConrad Meyer         eSize = ERROR(memory_allocation);
7760f743729SConrad Meyer         DISPLAYLEVEL(1, "Not enough memory \n");
7770c16b537SWarner Losh         goto _cleanup;
7780f743729SConrad Meyer     }
7790c16b537SWarner Losh 
78019fcbaf1SConrad Meyer     /* collect stats on all samples */
7810c16b537SWarner Losh     for (u=0; u<nbFiles; u++) {
78237f1f268SConrad Meyer         ZDICT_countEStats(esr, &params,
7830c16b537SWarner Losh                           countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
7840c16b537SWarner Losh                          (const char*)srcBuffer + pos, fileSizes[u],
7850c16b537SWarner Losh                           notificationLevel);
7860c16b537SWarner Losh         pos += fileSizes[u];
7870c16b537SWarner Losh     }
7880c16b537SWarner Losh 
789*5ff13fbcSAllan Jude     if (notificationLevel >= 4) {
790*5ff13fbcSAllan Jude         /* writeStats */
791*5ff13fbcSAllan Jude         DISPLAYLEVEL(4, "Offset Code Frequencies : \n");
792*5ff13fbcSAllan Jude         for (u=0; u<=offcodeMax; u++) {
793*5ff13fbcSAllan Jude             DISPLAYLEVEL(4, "%2u :%7u \n", u, offcodeCount[u]);
794*5ff13fbcSAllan Jude     }   }
795*5ff13fbcSAllan Jude 
79619fcbaf1SConrad Meyer     /* analyze, build stats, starting with literals */
79719fcbaf1SConrad Meyer     {   size_t maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
79819fcbaf1SConrad Meyer         if (HUF_isError(maxNbBits)) {
7994d3f1eafSConrad Meyer             eSize = maxNbBits;
8000c16b537SWarner Losh             DISPLAYLEVEL(1, " HUF_buildCTable error \n");
8010c16b537SWarner Losh             goto _cleanup;
8020c16b537SWarner Losh         }
80319fcbaf1SConrad Meyer         if (maxNbBits==8) {  /* not compressible : will fail on HUF_writeCTable() */
80419fcbaf1SConrad Meyer             DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
80519fcbaf1SConrad Meyer             ZDICT_flatLit(countLit);  /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
80619fcbaf1SConrad Meyer             maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
80719fcbaf1SConrad Meyer             assert(maxNbBits==9);
80819fcbaf1SConrad Meyer         }
80919fcbaf1SConrad Meyer         huffLog = (U32)maxNbBits;
81019fcbaf1SConrad Meyer     }
8110c16b537SWarner Losh 
8120c16b537SWarner Losh     /* looking for most common first offsets */
8130c16b537SWarner Losh     {   U32 offset;
8140c16b537SWarner Losh         for (offset=1; offset<MAXREPOFFSET; offset++)
8150c16b537SWarner Losh             ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
8160c16b537SWarner Losh     }
8170c16b537SWarner Losh     /* note : the result of this phase should be used to better appreciate the impact on statistics */
8180c16b537SWarner Losh 
8190c16b537SWarner Losh     total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
820f7cd7fe5SConrad Meyer     errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax, /* useLowProbCount */ 1);
8210c16b537SWarner Losh     if (FSE_isError(errorCode)) {
8224d3f1eafSConrad Meyer         eSize = errorCode;
8230c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
8240c16b537SWarner Losh         goto _cleanup;
8250c16b537SWarner Losh     }
8260c16b537SWarner Losh     Offlog = (U32)errorCode;
8270c16b537SWarner Losh 
8280c16b537SWarner Losh     total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
829f7cd7fe5SConrad Meyer     errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML, /* useLowProbCount */ 1);
8300c16b537SWarner Losh     if (FSE_isError(errorCode)) {
8314d3f1eafSConrad Meyer         eSize = errorCode;
8320c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
8330c16b537SWarner Losh         goto _cleanup;
8340c16b537SWarner Losh     }
8350c16b537SWarner Losh     mlLog = (U32)errorCode;
8360c16b537SWarner Losh 
8370c16b537SWarner Losh     total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
838f7cd7fe5SConrad Meyer     errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL, /* useLowProbCount */ 1);
8390c16b537SWarner Losh     if (FSE_isError(errorCode)) {
8404d3f1eafSConrad Meyer         eSize = errorCode;
8410c16b537SWarner Losh         DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
8420c16b537SWarner Losh         goto _cleanup;
8430c16b537SWarner Losh     }
8440c16b537SWarner Losh     llLog = (U32)errorCode;
8450c16b537SWarner Losh 
8460c16b537SWarner Losh     /* write result to buffer */
8470c16b537SWarner Losh     {   size_t const hhSize = HUF_writeCTable(dstPtr, maxDstSize, hufTable, 255, huffLog);
8480c16b537SWarner Losh         if (HUF_isError(hhSize)) {
8494d3f1eafSConrad Meyer             eSize = hhSize;
8500c16b537SWarner Losh             DISPLAYLEVEL(1, "HUF_writeCTable error \n");
8510c16b537SWarner Losh             goto _cleanup;
8520c16b537SWarner Losh         }
8530c16b537SWarner Losh         dstPtr += hhSize;
8540c16b537SWarner Losh         maxDstSize -= hhSize;
8550c16b537SWarner Losh         eSize += hhSize;
8560c16b537SWarner Losh     }
8570c16b537SWarner Losh 
8580c16b537SWarner Losh     {   size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
8590c16b537SWarner Losh         if (FSE_isError(ohSize)) {
8604d3f1eafSConrad Meyer             eSize = ohSize;
8610c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
8620c16b537SWarner Losh             goto _cleanup;
8630c16b537SWarner Losh         }
8640c16b537SWarner Losh         dstPtr += ohSize;
8650c16b537SWarner Losh         maxDstSize -= ohSize;
8660c16b537SWarner Losh         eSize += ohSize;
8670c16b537SWarner Losh     }
8680c16b537SWarner Losh 
8690c16b537SWarner Losh     {   size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
8700c16b537SWarner Losh         if (FSE_isError(mhSize)) {
8714d3f1eafSConrad Meyer             eSize = mhSize;
8720c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
8730c16b537SWarner Losh             goto _cleanup;
8740c16b537SWarner Losh         }
8750c16b537SWarner Losh         dstPtr += mhSize;
8760c16b537SWarner Losh         maxDstSize -= mhSize;
8770c16b537SWarner Losh         eSize += mhSize;
8780c16b537SWarner Losh     }
8790c16b537SWarner Losh 
8800c16b537SWarner Losh     {   size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
8810c16b537SWarner Losh         if (FSE_isError(lhSize)) {
8824d3f1eafSConrad Meyer             eSize = lhSize;
8830c16b537SWarner Losh             DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
8840c16b537SWarner Losh             goto _cleanup;
8850c16b537SWarner Losh         }
8860c16b537SWarner Losh         dstPtr += lhSize;
8870c16b537SWarner Losh         maxDstSize -= lhSize;
8880c16b537SWarner Losh         eSize += lhSize;
8890c16b537SWarner Losh     }
8900c16b537SWarner Losh 
8910c16b537SWarner Losh     if (maxDstSize<12) {
8924d3f1eafSConrad Meyer         eSize = ERROR(dstSize_tooSmall);
8930c16b537SWarner Losh         DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
8940c16b537SWarner Losh         goto _cleanup;
8950c16b537SWarner Losh     }
8960c16b537SWarner Losh # if 0
8970c16b537SWarner Losh     MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
8980c16b537SWarner Losh     MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
8990c16b537SWarner Losh     MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
9000c16b537SWarner Losh #else
9010c16b537SWarner Losh     /* at this stage, we don't use the result of "most common first offset",
902*5ff13fbcSAllan Jude      * as the impact of statistics is not properly evaluated */
9030c16b537SWarner Losh     MEM_writeLE32(dstPtr+0, repStartValue[0]);
9040c16b537SWarner Losh     MEM_writeLE32(dstPtr+4, repStartValue[1]);
9050c16b537SWarner Losh     MEM_writeLE32(dstPtr+8, repStartValue[2]);
9060c16b537SWarner Losh #endif
9070c16b537SWarner Losh     eSize += 12;
9080c16b537SWarner Losh 
9090c16b537SWarner Losh _cleanup:
9100f743729SConrad Meyer     ZSTD_freeCDict(esr.dict);
9110c16b537SWarner Losh     ZSTD_freeCCtx(esr.zc);
9120c16b537SWarner Losh     free(esr.workPlace);
9130c16b537SWarner Losh 
9140c16b537SWarner Losh     return eSize;
9150c16b537SWarner Losh }
9160c16b537SWarner Losh 
9170c16b537SWarner Losh 
918*5ff13fbcSAllan Jude /**
919*5ff13fbcSAllan Jude  * @returns the maximum repcode value
920*5ff13fbcSAllan Jude  */
ZDICT_maxRep(U32 const reps[ZSTD_REP_NUM])921*5ff13fbcSAllan Jude static U32 ZDICT_maxRep(U32 const reps[ZSTD_REP_NUM])
922*5ff13fbcSAllan Jude {
923*5ff13fbcSAllan Jude     U32 maxRep = reps[0];
924*5ff13fbcSAllan Jude     int r;
925*5ff13fbcSAllan Jude     for (r = 1; r < ZSTD_REP_NUM; ++r)
926*5ff13fbcSAllan Jude         maxRep = MAX(maxRep, reps[r]);
927*5ff13fbcSAllan Jude     return maxRep;
928*5ff13fbcSAllan Jude }
9290c16b537SWarner Losh 
ZDICT_finalizeDictionary(void * dictBuffer,size_t dictBufferCapacity,const void * customDictContent,size_t dictContentSize,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples,ZDICT_params_t params)9300c16b537SWarner Losh size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
9310c16b537SWarner Losh                           const void* customDictContent, size_t dictContentSize,
9320f743729SConrad Meyer                           const void* samplesBuffer, const size_t* samplesSizes,
9330f743729SConrad Meyer                           unsigned nbSamples, ZDICT_params_t params)
9340c16b537SWarner Losh {
9350c16b537SWarner Losh     size_t hSize;
9360c16b537SWarner Losh #define HBUFFSIZE 256   /* should prove large enough for all entropy headers */
9370c16b537SWarner Losh     BYTE header[HBUFFSIZE];
938f7cd7fe5SConrad Meyer     int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
9390c16b537SWarner Losh     U32 const notificationLevel = params.notificationLevel;
940*5ff13fbcSAllan Jude     /* The final dictionary content must be at least as large as the largest repcode */
941*5ff13fbcSAllan Jude     size_t const minContentSize = (size_t)ZDICT_maxRep(repStartValue);
942*5ff13fbcSAllan Jude     size_t paddingSize;
9430c16b537SWarner Losh 
9440c16b537SWarner Losh     /* check conditions */
94519fcbaf1SConrad Meyer     DEBUGLOG(4, "ZDICT_finalizeDictionary");
9460c16b537SWarner Losh     if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
9470c16b537SWarner Losh     if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
9480c16b537SWarner Losh 
9490c16b537SWarner Losh     /* dictionary header */
9500c16b537SWarner Losh     MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
9510c16b537SWarner Losh     {   U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
9520c16b537SWarner Losh         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
9530c16b537SWarner Losh         U32 const dictID = params.dictID ? params.dictID : compliantID;
9540c16b537SWarner Losh         MEM_writeLE32(header+4, dictID);
9550c16b537SWarner Losh     }
9560c16b537SWarner Losh     hSize = 8;
9570c16b537SWarner Losh 
9580c16b537SWarner Losh     /* entropy tables */
9590c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
9600c16b537SWarner Losh     DISPLAYLEVEL(2, "statistics ... \n");
9610c16b537SWarner Losh     {   size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
9620c16b537SWarner Losh                                   compressionLevel,
9630c16b537SWarner Losh                                   samplesBuffer, samplesSizes, nbSamples,
9640c16b537SWarner Losh                                   customDictContent, dictContentSize,
9650c16b537SWarner Losh                                   notificationLevel);
9660c16b537SWarner Losh         if (ZDICT_isError(eSize)) return eSize;
9670c16b537SWarner Losh         hSize += eSize;
9680c16b537SWarner Losh     }
9690c16b537SWarner Losh 
970*5ff13fbcSAllan Jude     /* Shrink the content size if it doesn't fit in the buffer */
971*5ff13fbcSAllan Jude     if (hSize + dictContentSize > dictBufferCapacity) {
972*5ff13fbcSAllan Jude         dictContentSize = dictBufferCapacity - hSize;
973*5ff13fbcSAllan Jude     }
974*5ff13fbcSAllan Jude 
975*5ff13fbcSAllan Jude     /* Pad the dictionary content with zeros if it is too small */
976*5ff13fbcSAllan Jude     if (dictContentSize < minContentSize) {
977*5ff13fbcSAllan Jude         RETURN_ERROR_IF(hSize + minContentSize > dictBufferCapacity, dstSize_tooSmall,
978*5ff13fbcSAllan Jude                         "dictBufferCapacity too small to fit max repcode");
979*5ff13fbcSAllan Jude         paddingSize = minContentSize - dictContentSize;
980*5ff13fbcSAllan Jude     } else {
981*5ff13fbcSAllan Jude         paddingSize = 0;
982*5ff13fbcSAllan Jude     }
983*5ff13fbcSAllan Jude 
984*5ff13fbcSAllan Jude     {
985*5ff13fbcSAllan Jude         size_t const dictSize = hSize + paddingSize + dictContentSize;
986*5ff13fbcSAllan Jude 
987*5ff13fbcSAllan Jude         /* The dictionary consists of the header, optional padding, and the content.
988*5ff13fbcSAllan Jude          * The padding comes before the content because the "best" position in the
989*5ff13fbcSAllan Jude          * dictionary is the last byte.
990*5ff13fbcSAllan Jude          */
991*5ff13fbcSAllan Jude         BYTE* const outDictHeader = (BYTE*)dictBuffer;
992*5ff13fbcSAllan Jude         BYTE* const outDictPadding = outDictHeader + hSize;
993*5ff13fbcSAllan Jude         BYTE* const outDictContent = outDictPadding + paddingSize;
994*5ff13fbcSAllan Jude 
995*5ff13fbcSAllan Jude         assert(dictSize <= dictBufferCapacity);
996*5ff13fbcSAllan Jude         assert(outDictContent + dictContentSize == (BYTE*)dictBuffer + dictSize);
997*5ff13fbcSAllan Jude 
998*5ff13fbcSAllan Jude         /* First copy the customDictContent into its final location.
999*5ff13fbcSAllan Jude          * `customDictContent` and `dictBuffer` may overlap, so we must
1000*5ff13fbcSAllan Jude          * do this before any other writes into the output buffer.
1001*5ff13fbcSAllan Jude          * Then copy the header & padding into the output buffer.
1002*5ff13fbcSAllan Jude          */
1003*5ff13fbcSAllan Jude         memmove(outDictContent, customDictContent, dictContentSize);
1004*5ff13fbcSAllan Jude         memcpy(outDictHeader, header, hSize);
1005*5ff13fbcSAllan Jude         memset(outDictPadding, 0, paddingSize);
1006*5ff13fbcSAllan Jude 
10070c16b537SWarner Losh         return dictSize;
10080c16b537SWarner Losh     }
10090c16b537SWarner Losh }
10100c16b537SWarner Losh 
10110c16b537SWarner Losh 
ZDICT_addEntropyTablesFromBuffer_advanced(void * dictBuffer,size_t dictContentSize,size_t dictBufferCapacity,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples,ZDICT_params_t params)10120f743729SConrad Meyer static size_t ZDICT_addEntropyTablesFromBuffer_advanced(
10130f743729SConrad Meyer         void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
10140c16b537SWarner Losh         const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
10150c16b537SWarner Losh         ZDICT_params_t params)
10160c16b537SWarner Losh {
1017f7cd7fe5SConrad Meyer     int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;
10180c16b537SWarner Losh     U32 const notificationLevel = params.notificationLevel;
10190c16b537SWarner Losh     size_t hSize = 8;
10200c16b537SWarner Losh 
10210c16b537SWarner Losh     /* calculate entropy tables */
10220c16b537SWarner Losh     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */
10230c16b537SWarner Losh     DISPLAYLEVEL(2, "statistics ... \n");
10240c16b537SWarner Losh     {   size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
10250c16b537SWarner Losh                                   compressionLevel,
10260c16b537SWarner Losh                                   samplesBuffer, samplesSizes, nbSamples,
10270c16b537SWarner Losh                                   (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
10280c16b537SWarner Losh                                   notificationLevel);
10290c16b537SWarner Losh         if (ZDICT_isError(eSize)) return eSize;
10300c16b537SWarner Losh         hSize += eSize;
10310c16b537SWarner Losh     }
10320c16b537SWarner Losh 
10330c16b537SWarner Losh     /* add dictionary header (after entropy tables) */
10340c16b537SWarner Losh     MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
10350c16b537SWarner Losh     {   U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
10360c16b537SWarner Losh         U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
10370c16b537SWarner Losh         U32 const dictID = params.dictID ? params.dictID : compliantID;
10380c16b537SWarner Losh         MEM_writeLE32((char*)dictBuffer+4, dictID);
10390c16b537SWarner Losh     }
10400c16b537SWarner Losh 
10410c16b537SWarner Losh     if (hSize + dictContentSize < dictBufferCapacity)
10420c16b537SWarner Losh         memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);
10430c16b537SWarner Losh     return MIN(dictBufferCapacity, hSize+dictContentSize);
10440c16b537SWarner Losh }
10450c16b537SWarner Losh 
1046*5ff13fbcSAllan Jude /*! ZDICT_trainFromBuffer_unsafe_legacy() :
1047*5ff13fbcSAllan Jude *   Warning : `samplesBuffer` must be followed by noisy guard band !!!
1048*5ff13fbcSAllan Jude *   @return : size of dictionary, or an error code which can be tested with ZDICT_isError()
1049*5ff13fbcSAllan Jude */
105098689d0fSConrad Meyer /* Begin FreeBSD - This symbol is needed by dll-linked CLI zstd(1). */
105198689d0fSConrad Meyer ZSTDLIB_API
105298689d0fSConrad Meyer /* End FreeBSD */
ZDICT_trainFromBuffer_unsafe_legacy(void * dictBuffer,size_t maxDictSize,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples,ZDICT_legacy_params_t params)1053*5ff13fbcSAllan Jude static size_t ZDICT_trainFromBuffer_unsafe_legacy(
10540c16b537SWarner Losh                             void* dictBuffer, size_t maxDictSize,
10550c16b537SWarner Losh                             const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
10560c16b537SWarner Losh                             ZDICT_legacy_params_t params)
10570c16b537SWarner Losh {
10580c16b537SWarner Losh     U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
10590c16b537SWarner Losh     dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
10600c16b537SWarner Losh     unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
10610c16b537SWarner Losh     unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
10620c16b537SWarner Losh     size_t const targetDictSize = maxDictSize;
10630c16b537SWarner Losh     size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
10640c16b537SWarner Losh     size_t dictSize = 0;
10650c16b537SWarner Losh     U32 const notificationLevel = params.zParams.notificationLevel;
10660c16b537SWarner Losh 
10670c16b537SWarner Losh     /* checks */
10680c16b537SWarner Losh     if (!dictList) return ERROR(memory_allocation);
10690c16b537SWarner Losh     if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); }   /* requested dictionary size is too small */
10700c16b537SWarner Losh     if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* not enough source to create dictionary */
10710c16b537SWarner Losh 
10720c16b537SWarner Losh     /* init */
10730c16b537SWarner Losh     ZDICT_initDictItem(dictList);
10740c16b537SWarner Losh 
10750c16b537SWarner Losh     /* build dictionary */
10760c16b537SWarner Losh     ZDICT_trainBuffer_legacy(dictList, dictListSize,
10770c16b537SWarner Losh                        samplesBuffer, samplesBuffSize,
10780c16b537SWarner Losh                        samplesSizes, nbSamples,
10790c16b537SWarner Losh                        minRep, notificationLevel);
10800c16b537SWarner Losh 
10810c16b537SWarner Losh     /* display best matches */
10820c16b537SWarner Losh     if (params.zParams.notificationLevel>= 3) {
1083a0483764SConrad Meyer         unsigned const nb = MIN(25, dictList[0].pos);
1084a0483764SConrad Meyer         unsigned const dictContentSize = ZDICT_dictSize(dictList);
1085a0483764SConrad Meyer         unsigned u;
1086a0483764SConrad Meyer         DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
10870c16b537SWarner Losh         DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
10880c16b537SWarner Losh         for (u=1; u<nb; u++) {
1089a0483764SConrad Meyer             unsigned const pos = dictList[u].pos;
1090a0483764SConrad Meyer             unsigned const length = dictList[u].length;
10910c16b537SWarner Losh             U32 const printedLength = MIN(40, length);
10920f743729SConrad Meyer             if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
10930f743729SConrad Meyer                 free(dictList);
10940c16b537SWarner Losh                 return ERROR(GENERIC);   /* should never happen */
10950f743729SConrad Meyer             }
10960c16b537SWarner Losh             DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
1097a0483764SConrad Meyer                          u, length, pos, (unsigned)dictList[u].savings);
10980c16b537SWarner Losh             ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
10990c16b537SWarner Losh             DISPLAYLEVEL(3, "| \n");
11000c16b537SWarner Losh     }   }
11010c16b537SWarner Losh 
11020c16b537SWarner Losh 
11030c16b537SWarner Losh     /* create dictionary */
1104a0483764SConrad Meyer     {   unsigned dictContentSize = ZDICT_dictSize(dictList);
11050c16b537SWarner Losh         if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); }   /* dictionary content too small */
11060c16b537SWarner Losh         if (dictContentSize < targetDictSize/4) {
1107a0483764SConrad Meyer             DISPLAYLEVEL(2, "!  warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
11080c16b537SWarner Losh             if (samplesBuffSize < 10 * targetDictSize)
1109a0483764SConrad Meyer                 DISPLAYLEVEL(2, "!  consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
11100c16b537SWarner Losh             if (minRep > MINRATIO) {
11110c16b537SWarner Losh                 DISPLAYLEVEL(2, "!  consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
11120c16b537SWarner Losh                 DISPLAYLEVEL(2, "!  note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
11130c16b537SWarner Losh             }
11140c16b537SWarner Losh         }
11150c16b537SWarner Losh 
11160c16b537SWarner Losh         if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
1117a0483764SConrad Meyer             unsigned proposedSelectivity = selectivity-1;
11180c16b537SWarner Losh             while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
1119a0483764SConrad Meyer             DISPLAYLEVEL(2, "!  note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
11200c16b537SWarner Losh             DISPLAYLEVEL(2, "!  consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
11210c16b537SWarner Losh             DISPLAYLEVEL(2, "!  always test dictionary efficiency on real samples \n");
11220c16b537SWarner Losh         }
11230c16b537SWarner Losh 
11240c16b537SWarner Losh         /* limit dictionary size */
11250c16b537SWarner Losh         {   U32 const max = dictList->pos;   /* convention : nb of useful elts within dictList */
11260c16b537SWarner Losh             U32 currentSize = 0;
11270c16b537SWarner Losh             U32 n; for (n=1; n<max; n++) {
11280c16b537SWarner Losh                 currentSize += dictList[n].length;
11290c16b537SWarner Losh                 if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
11300c16b537SWarner Losh             }
11310c16b537SWarner Losh             dictList->pos = n;
11320c16b537SWarner Losh             dictContentSize = currentSize;
11330c16b537SWarner Losh         }
11340c16b537SWarner Losh 
11350c16b537SWarner Losh         /* build dict content */
11360c16b537SWarner Losh         {   U32 u;
11370c16b537SWarner Losh             BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
11380c16b537SWarner Losh             for (u=1; u<dictList->pos; u++) {
11390c16b537SWarner Losh                 U32 l = dictList[u].length;
11400c16b537SWarner Losh                 ptr -= l;
11410c16b537SWarner Losh                 if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); }   /* should not happen */
11420c16b537SWarner Losh                 memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
11430c16b537SWarner Losh         }   }
11440c16b537SWarner Losh 
11450c16b537SWarner Losh         dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
11460c16b537SWarner Losh                                                              samplesBuffer, samplesSizes, nbSamples,
11470c16b537SWarner Losh                                                              params.zParams);
11480c16b537SWarner Losh     }
11490c16b537SWarner Losh 
11500c16b537SWarner Losh     /* clean up */
11510c16b537SWarner Losh     free(dictList);
11520c16b537SWarner Losh     return dictSize;
11530c16b537SWarner Losh }
11540c16b537SWarner Losh 
11550c16b537SWarner Losh 
115619fcbaf1SConrad Meyer /* ZDICT_trainFromBuffer_legacy() :
115719fcbaf1SConrad Meyer  * issue : samplesBuffer need to be followed by a noisy guard band.
11580c16b537SWarner Losh  * work around : duplicate the buffer, and add the noise */
ZDICT_trainFromBuffer_legacy(void * dictBuffer,size_t dictBufferCapacity,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples,ZDICT_legacy_params_t params)11590c16b537SWarner Losh size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,
11600c16b537SWarner Losh                               const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
11610c16b537SWarner Losh                               ZDICT_legacy_params_t params)
11620c16b537SWarner Losh {
11630c16b537SWarner Losh     size_t result;
11640c16b537SWarner Losh     void* newBuff;
11650c16b537SWarner Losh     size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
11660c16b537SWarner Losh     if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0;   /* not enough content => no dictionary */
11670c16b537SWarner Losh 
11680c16b537SWarner Losh     newBuff = malloc(sBuffSize + NOISELENGTH);
11690c16b537SWarner Losh     if (!newBuff) return ERROR(memory_allocation);
11700c16b537SWarner Losh 
11710c16b537SWarner Losh     memcpy(newBuff, samplesBuffer, sBuffSize);
11720c16b537SWarner Losh     ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH);   /* guard band, for end of buffer condition */
11730c16b537SWarner Losh 
11740c16b537SWarner Losh     result =
11750c16b537SWarner Losh         ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,
11760c16b537SWarner Losh                                             samplesSizes, nbSamples, params);
11770c16b537SWarner Losh     free(newBuff);
11780c16b537SWarner Losh     return result;
11790c16b537SWarner Losh }
11800c16b537SWarner Losh 
11810c16b537SWarner Losh 
ZDICT_trainFromBuffer(void * dictBuffer,size_t dictBufferCapacity,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples)11820c16b537SWarner Losh size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
11830c16b537SWarner Losh                              const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
11840c16b537SWarner Losh {
11850f743729SConrad Meyer     ZDICT_fastCover_params_t params;
118619fcbaf1SConrad Meyer     DEBUGLOG(3, "ZDICT_trainFromBuffer");
11870c16b537SWarner Losh     memset(&params, 0, sizeof(params));
11880c16b537SWarner Losh     params.d = 8;
11890c16b537SWarner Losh     params.steps = 4;
1190f7cd7fe5SConrad Meyer     /* Use default level since no compression level information is available */
1191f7cd7fe5SConrad Meyer     params.zParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;
11920f743729SConrad Meyer #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)
11930f743729SConrad Meyer     params.zParams.notificationLevel = DEBUGLEVEL;
119419fcbaf1SConrad Meyer #endif
11950f743729SConrad Meyer     return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,
119619fcbaf1SConrad Meyer                                                samplesBuffer, samplesSizes, nbSamples,
119719fcbaf1SConrad Meyer                                                &params);
11980c16b537SWarner Losh }
11990c16b537SWarner Losh 
ZDICT_addEntropyTablesFromBuffer(void * dictBuffer,size_t dictContentSize,size_t dictBufferCapacity,const void * samplesBuffer,const size_t * samplesSizes,unsigned nbSamples)12000c16b537SWarner Losh size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
12010c16b537SWarner Losh                                   const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
12020c16b537SWarner Losh {
12030c16b537SWarner Losh     ZDICT_params_t params;
12040c16b537SWarner Losh     memset(&params, 0, sizeof(params));
12050c16b537SWarner Losh     return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,
12060c16b537SWarner Losh                                                      samplesBuffer, samplesSizes, nbSamples,
12070c16b537SWarner Losh                                                      params);
12080c16b537SWarner Losh }
1209