Path: blob/master/Utilities/cmzstd/lib/dictBuilder/zdict.c
3156 views
/*1* Copyright (c) Meta Platforms, Inc. and affiliates.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/91011/*-**************************************12* Tuning parameters13****************************************/14#define MINRATIO 4 /* minimum nb of apparition to be selected in dictionary */15#define ZDICT_MAX_SAMPLES_SIZE (2000U << 20)16#define ZDICT_MIN_SAMPLES_SIZE (ZDICT_CONTENTSIZE_MIN * MINRATIO)171819/*-**************************************20* Compiler Options21****************************************/22/* Unix Large Files support (>4GB) */23#define _FILE_OFFSET_BITS 6424#if (defined(__sun__) && (!defined(__LP64__))) /* Sun Solaris 32-bits requires specific definitions */25# ifndef _LARGEFILE_SOURCE26# define _LARGEFILE_SOURCE27# endif28#elif ! defined(__LP64__) /* No point defining Large file for 64 bit */29# ifndef _LARGEFILE64_SOURCE30# define _LARGEFILE64_SOURCE31# endif32#endif333435/*-*************************************36* Dependencies37***************************************/38#include <stdlib.h> /* malloc, free */39#include <string.h> /* memset */40#include <stdio.h> /* fprintf, fopen, ftello64 */41#include <time.h> /* clock */4243#ifndef ZDICT_STATIC_LINKING_ONLY44# define ZDICT_STATIC_LINKING_ONLY45#endif4647#include "../common/mem.h" /* read */48#include "../common/fse.h" /* FSE_normalizeCount, FSE_writeNCount */49#include "../common/huf.h" /* HUF_buildCTable, HUF_writeCTable */50#include "../common/zstd_internal.h" /* includes zstd.h */51#include "../common/xxhash.h" /* XXH64 */52#include "../compress/zstd_compress_internal.h" /* ZSTD_loadCEntropy() */53#include "../zdict.h"54#include "divsufsort.h"55#include "../common/bits.h" /* ZSTD_NbCommonBytes */565758/*-*************************************59* Constants60***************************************/61#define KB *(1 <<10)62#define MB *(1 <<20)63#define GB *(1U<<30)6465#define DICTLISTSIZE_DEFAULT 100006667#define NOISELENGTH 326869static const U32 g_selectivity_default = 9;707172/*-*************************************73* Console display74***************************************/75#undef DISPLAY76#define DISPLAY(...) { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }77#undef DISPLAYLEVEL78#define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */7980static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }8182static void ZDICT_printHex(const void* ptr, size_t length)83{84const BYTE* const b = (const BYTE*)ptr;85size_t u;86for (u=0; u<length; u++) {87BYTE c = b[u];88if (c<32 || c>126) c = '.'; /* non-printable char */89DISPLAY("%c", c);90}91}929394/*-********************************************************95* Helper functions96**********************************************************/97unsigned ZDICT_isError(size_t errorCode) { return ERR_isError(errorCode); }9899const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }100101unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize)102{103if (dictSize < 8) return 0;104if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;105return MEM_readLE32((const char*)dictBuffer + 4);106}107108size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize)109{110size_t headerSize;111if (dictSize <= 8 || MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return ERROR(dictionary_corrupted);112113{ ZSTD_compressedBlockState_t* bs = (ZSTD_compressedBlockState_t*)malloc(sizeof(ZSTD_compressedBlockState_t));114U32* wksp = (U32*)malloc(HUF_WORKSPACE_SIZE);115if (!bs || !wksp) {116headerSize = ERROR(memory_allocation);117} else {118ZSTD_reset_compressedBlockState(bs);119headerSize = ZSTD_loadCEntropy(bs, wksp, dictBuffer, dictSize);120}121122free(bs);123free(wksp);124}125126return headerSize;127}128129/*-********************************************************130* Dictionary training functions131**********************************************************/132/*! ZDICT_count() :133Count the nb of common bytes between 2 pointers.134Note : this function presumes end of buffer followed by noisy guard band.135*/136static size_t ZDICT_count(const void* pIn, const void* pMatch)137{138const char* const pStart = (const char*)pIn;139for (;;) {140size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);141if (!diff) {142pIn = (const char*)pIn+sizeof(size_t);143pMatch = (const char*)pMatch+sizeof(size_t);144continue;145}146pIn = (const char*)pIn+ZSTD_NbCommonBytes(diff);147return (size_t)((const char*)pIn - pStart);148}149}150151152typedef struct {153U32 pos;154U32 length;155U32 savings;156} dictItem;157158static void ZDICT_initDictItem(dictItem* d)159{160d->pos = 1;161d->length = 0;162d->savings = (U32)(-1);163}164165166#define LLIMIT 64 /* heuristic determined experimentally */167#define MINMATCHLENGTH 7 /* heuristic determined experimentally */168static dictItem ZDICT_analyzePos(169BYTE* doneMarks,170const int* suffix, U32 start,171const void* buffer, U32 minRatio, U32 notificationLevel)172{173U32 lengthList[LLIMIT] = {0};174U32 cumulLength[LLIMIT] = {0};175U32 savings[LLIMIT] = {0};176const BYTE* b = (const BYTE*)buffer;177size_t maxLength = LLIMIT;178size_t pos = (size_t)suffix[start];179U32 end = start;180dictItem solution;181182/* init */183memset(&solution, 0, sizeof(solution));184doneMarks[pos] = 1;185186/* trivial repetition cases */187if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))188||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))189||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {190/* skip and mark segment */191U16 const pattern16 = MEM_read16(b+pos+4);192U32 u, patternEnd = 6;193while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;194if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;195for (u=1; u<patternEnd; u++)196doneMarks[pos+u] = 1;197return solution;198}199200/* look forward */201{ size_t length;202do {203end++;204length = ZDICT_count(b + pos, b + suffix[end]);205} while (length >= MINMATCHLENGTH);206}207208/* look backward */209{ size_t length;210do {211length = ZDICT_count(b + pos, b + *(suffix+start-1));212if (length >=MINMATCHLENGTH) start--;213} while(length >= MINMATCHLENGTH);214}215216/* exit if not found a minimum nb of repetitions */217if (end-start < minRatio) {218U32 idx;219for(idx=start; idx<end; idx++)220doneMarks[suffix[idx]] = 1;221return solution;222}223224{ int i;225U32 mml;226U32 refinedStart = start;227U32 refinedEnd = end;228229DISPLAYLEVEL(4, "\n");230DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);231DISPLAYLEVEL(4, "\n");232233for (mml = MINMATCHLENGTH ; ; mml++) {234BYTE currentChar = 0;235U32 currentCount = 0;236U32 currentID = refinedStart;237U32 id;238U32 selectedCount = 0;239U32 selectedID = currentID;240for (id =refinedStart; id < refinedEnd; id++) {241if (b[suffix[id] + mml] != currentChar) {242if (currentCount > selectedCount) {243selectedCount = currentCount;244selectedID = currentID;245}246currentID = id;247currentChar = b[ suffix[id] + mml];248currentCount = 0;249}250currentCount ++;251}252if (currentCount > selectedCount) { /* for last */253selectedCount = currentCount;254selectedID = currentID;255}256257if (selectedCount < minRatio)258break;259refinedStart = selectedID;260refinedEnd = refinedStart + selectedCount;261}262263/* evaluate gain based on new dict */264start = refinedStart;265pos = suffix[refinedStart];266end = start;267memset(lengthList, 0, sizeof(lengthList));268269/* look forward */270{ size_t length;271do {272end++;273length = ZDICT_count(b + pos, b + suffix[end]);274if (length >= LLIMIT) length = LLIMIT-1;275lengthList[length]++;276} while (length >=MINMATCHLENGTH);277}278279/* look backward */280{ size_t length = MINMATCHLENGTH;281while ((length >= MINMATCHLENGTH) & (start > 0)) {282length = ZDICT_count(b + pos, b + suffix[start - 1]);283if (length >= LLIMIT) length = LLIMIT - 1;284lengthList[length]++;285if (length >= MINMATCHLENGTH) start--;286}287}288289/* largest useful length */290memset(cumulLength, 0, sizeof(cumulLength));291cumulLength[maxLength-1] = lengthList[maxLength-1];292for (i=(int)(maxLength-2); i>=0; i--)293cumulLength[i] = cumulLength[i+1] + lengthList[i];294295for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;296maxLength = i;297298/* reduce maxLength in case of final into repetitive data */299{ U32 l = (U32)maxLength;300BYTE const c = b[pos + maxLength-1];301while (b[pos+l-2]==c) l--;302maxLength = l;303}304if (maxLength < MINMATCHLENGTH) return solution; /* skip : no long-enough solution */305306/* calculate savings */307savings[5] = 0;308for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)309savings[i] = savings[i-1] + (lengthList[i] * (i-3));310311DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f) \n",312(unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / (double)maxLength);313314solution.pos = (U32)pos;315solution.length = (U32)maxLength;316solution.savings = savings[maxLength];317318/* mark positions done */319{ U32 id;320for (id=start; id<end; id++) {321U32 p, pEnd, length;322U32 const testedPos = (U32)suffix[id];323if (testedPos == pos)324length = solution.length;325else {326length = (U32)ZDICT_count(b+pos, b+testedPos);327if (length > solution.length) length = solution.length;328}329pEnd = (U32)(testedPos + length);330for (p=testedPos; p<pEnd; p++)331doneMarks[p] = 1;332} } }333334return solution;335}336337338static int isIncluded(const void* in, const void* container, size_t length)339{340const char* const ip = (const char*) in;341const char* const into = (const char*) container;342size_t u;343344for (u=0; u<length; u++) { /* works because end of buffer is a noisy guard band */345if (ip[u] != into[u]) break;346}347348return u==length;349}350351/*! ZDICT_tryMerge() :352check if dictItem can be merged, do it if possible353@return : id of destination elt, 0 if not merged354*/355static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const void* buffer)356{357const U32 tableSize = table->pos;358const U32 eltEnd = elt.pos + elt.length;359const char* const buf = (const char*) buffer;360361/* tail overlap */362U32 u; for (u=1; u<tableSize; u++) {363if (u==eltNbToSkip) continue;364if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) { /* overlap, existing > new */365/* append */366U32 const addedLength = table[u].pos - elt.pos;367table[u].length += addedLength;368table[u].pos = elt.pos;369table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */370table[u].savings += elt.length / 8; /* rough approx bonus */371elt = table[u];372/* sort : improve rank */373while ((u>1) && (table[u-1].savings < elt.savings))374table[u] = table[u-1], u--;375table[u] = elt;376return u;377} }378379/* front overlap */380for (u=1; u<tableSize; u++) {381if (u==eltNbToSkip) continue;382383if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) { /* overlap, existing < new */384/* append */385int const addedLength = (int)eltEnd - (int)(table[u].pos + table[u].length);386table[u].savings += elt.length / 8; /* rough approx bonus */387if (addedLength > 0) { /* otherwise, elt fully included into existing */388table[u].length += addedLength;389table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */390}391/* sort : improve rank */392elt = table[u];393while ((u>1) && (table[u-1].savings < elt.savings))394table[u] = table[u-1], u--;395table[u] = elt;396return u;397}398399if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {400if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {401size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );402table[u].pos = elt.pos;403table[u].savings += (U32)(elt.savings * addedLength / elt.length);404table[u].length = MIN(elt.length, table[u].length + 1);405return u;406}407}408}409410return 0;411}412413414static void ZDICT_removeDictItem(dictItem* table, U32 id)415{416/* convention : table[0].pos stores nb of elts */417U32 const max = table[0].pos;418U32 u;419if (!id) return; /* protection, should never happen */420for (u=id; u<max-1; u++)421table[u] = table[u+1];422table->pos--;423}424425426static void ZDICT_insertDictItem(dictItem* table, U32 maxSize, dictItem elt, const void* buffer)427{428/* merge if possible */429U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);430if (mergeId) {431U32 newMerge = 1;432while (newMerge) {433newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);434if (newMerge) ZDICT_removeDictItem(table, mergeId);435mergeId = newMerge;436}437return;438}439440/* insert */441{ U32 current;442U32 nextElt = table->pos;443if (nextElt >= maxSize) nextElt = maxSize-1;444current = nextElt-1;445while (table[current].savings < elt.savings) {446table[current+1] = table[current];447current--;448}449table[current+1] = elt;450table->pos = nextElt+1;451}452}453454455static U32 ZDICT_dictSize(const dictItem* dictList)456{457U32 u, dictSize = 0;458for (u=1; u<dictList[0].pos; u++)459dictSize += dictList[u].length;460return dictSize;461}462463464static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,465const void* const buffer, size_t bufferSize, /* buffer must end with noisy guard band */466const size_t* fileSizes, unsigned nbFiles,467unsigned minRatio, U32 notificationLevel)468{469int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));470int* const suffix = suffix0+1;471U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));472BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks)); /* +16 for overflow security */473U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));474size_t result = 0;475clock_t displayClock = 0;476clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;477478# undef DISPLAYUPDATE479# define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \480if (ZDICT_clockSpan(displayClock) > refreshRate) \481{ displayClock = clock(); DISPLAY(__VA_ARGS__); \482if (notificationLevel>=4) fflush(stderr); } }483484/* init */485DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */486if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {487result = ERROR(memory_allocation);488goto _cleanup;489}490if (minRatio < MINRATIO) minRatio = MINRATIO;491memset(doneMarks, 0, bufferSize+16);492493/* limit sample set size (divsufsort limitation)*/494if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));495while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];496497/* sort */498DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));499{ int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);500if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }501}502suffix[bufferSize] = (int)bufferSize; /* leads into noise */503suffix0[0] = (int)bufferSize; /* leads into noise */504/* build reverse suffix sort */505{ size_t pos;506for (pos=0; pos < bufferSize; pos++)507reverseSuffix[suffix[pos]] = (U32)pos;508/* note filePos tracks borders between samples.509It's not used at this stage, but planned to become useful in a later update */510filePos[0] = 0;511for (pos=1; pos<nbFiles; pos++)512filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);513}514515DISPLAYLEVEL(2, "finding patterns ... \n");516DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);517518{ U32 cursor; for (cursor=0; cursor < bufferSize; ) {519dictItem solution;520if (doneMarks[cursor]) { cursor++; continue; }521solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);522if (solution.length==0) { cursor++; continue; }523ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);524cursor += solution.length;525DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / (double)bufferSize * 100.0);526} }527528_cleanup:529free(suffix0);530free(reverseSuffix);531free(doneMarks);532free(filePos);533return result;534}535536537static void ZDICT_fillNoise(void* buffer, size_t length)538{539unsigned const prime1 = 2654435761U;540unsigned const prime2 = 2246822519U;541unsigned acc = prime1;542size_t p=0;543for (p=0; p<length; p++) {544acc *= prime2;545((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);546}547}548549550typedef struct551{552ZSTD_CDict* dict; /* dictionary */553ZSTD_CCtx* zc; /* working context */554void* workPlace; /* must be ZSTD_BLOCKSIZE_MAX allocated */555} EStats_ress_t;556557#define MAXREPOFFSET 1024558559static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params,560unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,561const void* src, size_t srcSize,562U32 notificationLevel)563{564size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params->cParams.windowLog);565size_t cSize;566567if (srcSize > blockSizeMax) srcSize = blockSizeMax; /* protection vs large samples */568{ size_t const errorCode = ZSTD_compressBegin_usingCDict_deprecated(esr.zc, esr.dict);569if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }570571}572cSize = ZSTD_compressBlock_deprecated(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);573if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }574575if (cSize) { /* if == 0; block is not compressible */576const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);577578/* literals stats */579{ const BYTE* bytePtr;580for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)581countLit[*bytePtr]++;582}583584/* seqStats */585{ U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);586ZSTD_seqToCodes(seqStorePtr);587588{ const BYTE* codePtr = seqStorePtr->ofCode;589U32 u;590for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;591}592593{ const BYTE* codePtr = seqStorePtr->mlCode;594U32 u;595for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;596}597598{ const BYTE* codePtr = seqStorePtr->llCode;599U32 u;600for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;601}602603if (nbSeq >= 2) { /* rep offsets */604const seqDef* const seq = seqStorePtr->sequencesStart;605U32 offset1 = seq[0].offBase - ZSTD_REP_NUM;606U32 offset2 = seq[1].offBase - ZSTD_REP_NUM;607if (offset1 >= MAXREPOFFSET) offset1 = 0;608if (offset2 >= MAXREPOFFSET) offset2 = 0;609repOffsets[offset1] += 3;610repOffsets[offset2] += 1;611} } }612}613614static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)615{616size_t total=0;617unsigned u;618for (u=0; u<nbFiles; u++) total += fileSizes[u];619return total;620}621622typedef struct { U32 offset; U32 count; } offsetCount_t;623624static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)625{626U32 u;627table[ZSTD_REP_NUM].offset = val;628table[ZSTD_REP_NUM].count = count;629for (u=ZSTD_REP_NUM; u>0; u--) {630offsetCount_t tmp;631if (table[u-1].count >= table[u].count) break;632tmp = table[u-1];633table[u-1] = table[u];634table[u] = tmp;635}636}637638/* ZDICT_flatLit() :639* rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.640* necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.641*/642static void ZDICT_flatLit(unsigned* countLit)643{644int u;645for (u=1; u<256; u++) countLit[u] = 2;646countLit[0] = 4;647countLit[253] = 1;648countLit[254] = 1;649}650651#define OFFCODE_MAX 30 /* only applicable to first block */652static size_t ZDICT_analyzeEntropy(void* dstBuffer, size_t maxDstSize,653int compressionLevel,654const void* srcBuffer, const size_t* fileSizes, unsigned nbFiles,655const void* dictBuffer, size_t dictBufferSize,656unsigned notificationLevel)657{658unsigned countLit[256];659HUF_CREATE_STATIC_CTABLE(hufTable, 255);660unsigned offcodeCount[OFFCODE_MAX+1];661short offcodeNCount[OFFCODE_MAX+1];662U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));663unsigned matchLengthCount[MaxML+1];664short matchLengthNCount[MaxML+1];665unsigned litLengthCount[MaxLL+1];666short litLengthNCount[MaxLL+1];667U32 repOffset[MAXREPOFFSET];668offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];669EStats_ress_t esr = { NULL, NULL, NULL };670ZSTD_parameters params;671U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;672size_t pos = 0, errorCode;673size_t eSize = 0;674size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);675size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);676BYTE* dstPtr = (BYTE*)dstBuffer;677U32 wksp[HUF_CTABLE_WORKSPACE_SIZE_U32];678679/* init */680DEBUGLOG(4, "ZDICT_analyzeEntropy");681if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; } /* too large dictionary */682for (u=0; u<256; u++) countLit[u] = 1; /* any character must be described */683for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;684for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;685for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;686memset(repOffset, 0, sizeof(repOffset));687repOffset[1] = repOffset[4] = repOffset[8] = 1;688memset(bestRepOffset, 0, sizeof(bestRepOffset));689if (compressionLevel==0) compressionLevel = ZSTD_CLEVEL_DEFAULT;690params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);691692esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);693esr.zc = ZSTD_createCCtx();694esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);695if (!esr.dict || !esr.zc || !esr.workPlace) {696eSize = ERROR(memory_allocation);697DISPLAYLEVEL(1, "Not enough memory \n");698goto _cleanup;699}700701/* collect stats on all samples */702for (u=0; u<nbFiles; u++) {703ZDICT_countEStats(esr, ¶ms,704countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,705(const char*)srcBuffer + pos, fileSizes[u],706notificationLevel);707pos += fileSizes[u];708}709710if (notificationLevel >= 4) {711/* writeStats */712DISPLAYLEVEL(4, "Offset Code Frequencies : \n");713for (u=0; u<=offcodeMax; u++) {714DISPLAYLEVEL(4, "%2u :%7u \n", u, offcodeCount[u]);715} }716717/* analyze, build stats, starting with literals */718{ size_t maxNbBits = HUF_buildCTable_wksp(hufTable, countLit, 255, huffLog, wksp, sizeof(wksp));719if (HUF_isError(maxNbBits)) {720eSize = maxNbBits;721DISPLAYLEVEL(1, " HUF_buildCTable error \n");722goto _cleanup;723}724if (maxNbBits==8) { /* not compressible : will fail on HUF_writeCTable() */725DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");726ZDICT_flatLit(countLit); /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */727maxNbBits = HUF_buildCTable_wksp(hufTable, countLit, 255, huffLog, wksp, sizeof(wksp));728assert(maxNbBits==9);729}730huffLog = (U32)maxNbBits;731}732733/* looking for most common first offsets */734{ U32 offset;735for (offset=1; offset<MAXREPOFFSET; offset++)736ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);737}738/* note : the result of this phase should be used to better appreciate the impact on statistics */739740total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];741errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax, /* useLowProbCount */ 1);742if (FSE_isError(errorCode)) {743eSize = errorCode;744DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");745goto _cleanup;746}747Offlog = (U32)errorCode;748749total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];750errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML, /* useLowProbCount */ 1);751if (FSE_isError(errorCode)) {752eSize = errorCode;753DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");754goto _cleanup;755}756mlLog = (U32)errorCode;757758total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];759errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL, /* useLowProbCount */ 1);760if (FSE_isError(errorCode)) {761eSize = errorCode;762DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");763goto _cleanup;764}765llLog = (U32)errorCode;766767/* write result to buffer */768{ size_t const hhSize = HUF_writeCTable_wksp(dstPtr, maxDstSize, hufTable, 255, huffLog, wksp, sizeof(wksp));769if (HUF_isError(hhSize)) {770eSize = hhSize;771DISPLAYLEVEL(1, "HUF_writeCTable error \n");772goto _cleanup;773}774dstPtr += hhSize;775maxDstSize -= hhSize;776eSize += hhSize;777}778779{ size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);780if (FSE_isError(ohSize)) {781eSize = ohSize;782DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");783goto _cleanup;784}785dstPtr += ohSize;786maxDstSize -= ohSize;787eSize += ohSize;788}789790{ size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);791if (FSE_isError(mhSize)) {792eSize = mhSize;793DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");794goto _cleanup;795}796dstPtr += mhSize;797maxDstSize -= mhSize;798eSize += mhSize;799}800801{ size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);802if (FSE_isError(lhSize)) {803eSize = lhSize;804DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");805goto _cleanup;806}807dstPtr += lhSize;808maxDstSize -= lhSize;809eSize += lhSize;810}811812if (maxDstSize<12) {813eSize = ERROR(dstSize_tooSmall);814DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");815goto _cleanup;816}817# if 0818MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);819MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);820MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);821#else822/* at this stage, we don't use the result of "most common first offset",823* as the impact of statistics is not properly evaluated */824MEM_writeLE32(dstPtr+0, repStartValue[0]);825MEM_writeLE32(dstPtr+4, repStartValue[1]);826MEM_writeLE32(dstPtr+8, repStartValue[2]);827#endif828eSize += 12;829830_cleanup:831ZSTD_freeCDict(esr.dict);832ZSTD_freeCCtx(esr.zc);833free(esr.workPlace);834835return eSize;836}837838839/**840* @returns the maximum repcode value841*/842static U32 ZDICT_maxRep(U32 const reps[ZSTD_REP_NUM])843{844U32 maxRep = reps[0];845int r;846for (r = 1; r < ZSTD_REP_NUM; ++r)847maxRep = MAX(maxRep, reps[r]);848return maxRep;849}850851size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,852const void* customDictContent, size_t dictContentSize,853const void* samplesBuffer, const size_t* samplesSizes,854unsigned nbSamples, ZDICT_params_t params)855{856size_t hSize;857#define HBUFFSIZE 256 /* should prove large enough for all entropy headers */858BYTE header[HBUFFSIZE];859int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;860U32 const notificationLevel = params.notificationLevel;861/* The final dictionary content must be at least as large as the largest repcode */862size_t const minContentSize = (size_t)ZDICT_maxRep(repStartValue);863size_t paddingSize;864865/* check conditions */866DEBUGLOG(4, "ZDICT_finalizeDictionary");867if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);868if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);869870/* dictionary header */871MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);872{ U64 const randomID = XXH64(customDictContent, dictContentSize, 0);873U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;874U32 const dictID = params.dictID ? params.dictID : compliantID;875MEM_writeLE32(header+4, dictID);876}877hSize = 8;878879/* entropy tables */880DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */881DISPLAYLEVEL(2, "statistics ... \n");882{ size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,883compressionLevel,884samplesBuffer, samplesSizes, nbSamples,885customDictContent, dictContentSize,886notificationLevel);887if (ZDICT_isError(eSize)) return eSize;888hSize += eSize;889}890891/* Shrink the content size if it doesn't fit in the buffer */892if (hSize + dictContentSize > dictBufferCapacity) {893dictContentSize = dictBufferCapacity - hSize;894}895896/* Pad the dictionary content with zeros if it is too small */897if (dictContentSize < minContentSize) {898RETURN_ERROR_IF(hSize + minContentSize > dictBufferCapacity, dstSize_tooSmall,899"dictBufferCapacity too small to fit max repcode");900paddingSize = minContentSize - dictContentSize;901} else {902paddingSize = 0;903}904905{906size_t const dictSize = hSize + paddingSize + dictContentSize;907908/* The dictionary consists of the header, optional padding, and the content.909* The padding comes before the content because the "best" position in the910* dictionary is the last byte.911*/912BYTE* const outDictHeader = (BYTE*)dictBuffer;913BYTE* const outDictPadding = outDictHeader + hSize;914BYTE* const outDictContent = outDictPadding + paddingSize;915916assert(dictSize <= dictBufferCapacity);917assert(outDictContent + dictContentSize == (BYTE*)dictBuffer + dictSize);918919/* First copy the customDictContent into its final location.920* `customDictContent` and `dictBuffer` may overlap, so we must921* do this before any other writes into the output buffer.922* Then copy the header & padding into the output buffer.923*/924memmove(outDictContent, customDictContent, dictContentSize);925memcpy(outDictHeader, header, hSize);926memset(outDictPadding, 0, paddingSize);927928return dictSize;929}930}931932933static size_t ZDICT_addEntropyTablesFromBuffer_advanced(934void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,935const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,936ZDICT_params_t params)937{938int const compressionLevel = (params.compressionLevel == 0) ? ZSTD_CLEVEL_DEFAULT : params.compressionLevel;939U32 const notificationLevel = params.notificationLevel;940size_t hSize = 8;941942/* calculate entropy tables */943DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */944DISPLAYLEVEL(2, "statistics ... \n");945{ size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,946compressionLevel,947samplesBuffer, samplesSizes, nbSamples,948(char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,949notificationLevel);950if (ZDICT_isError(eSize)) return eSize;951hSize += eSize;952}953954/* add dictionary header (after entropy tables) */955MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);956{ U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);957U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;958U32 const dictID = params.dictID ? params.dictID : compliantID;959MEM_writeLE32((char*)dictBuffer+4, dictID);960}961962if (hSize + dictContentSize < dictBufferCapacity)963memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);964return MIN(dictBufferCapacity, hSize+dictContentSize);965}966967/*! ZDICT_trainFromBuffer_unsafe_legacy() :968* Warning : `samplesBuffer` must be followed by noisy guard band !!!969* @return : size of dictionary, or an error code which can be tested with ZDICT_isError()970*/971static size_t ZDICT_trainFromBuffer_unsafe_legacy(972void* dictBuffer, size_t maxDictSize,973const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,974ZDICT_legacy_params_t params)975{976U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));977dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));978unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;979unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;980size_t const targetDictSize = maxDictSize;981size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);982size_t dictSize = 0;983U32 const notificationLevel = params.zParams.notificationLevel;984985/* checks */986if (!dictList) return ERROR(memory_allocation);987if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); } /* requested dictionary size is too small */988if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); } /* not enough source to create dictionary */989990/* init */991ZDICT_initDictItem(dictList);992993/* build dictionary */994ZDICT_trainBuffer_legacy(dictList, dictListSize,995samplesBuffer, samplesBuffSize,996samplesSizes, nbSamples,997minRep, notificationLevel);998999/* display best matches */1000if (params.zParams.notificationLevel>= 3) {1001unsigned const nb = MIN(25, dictList[0].pos);1002unsigned const dictContentSize = ZDICT_dictSize(dictList);1003unsigned u;1004DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);1005DISPLAYLEVEL(3, "list %u best segments \n", nb-1);1006for (u=1; u<nb; u++) {1007unsigned const pos = dictList[u].pos;1008unsigned const length = dictList[u].length;1009U32 const printedLength = MIN(40, length);1010if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {1011free(dictList);1012return ERROR(GENERIC); /* should never happen */1013}1014DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",1015u, length, pos, (unsigned)dictList[u].savings);1016ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);1017DISPLAYLEVEL(3, "| \n");1018} }101910201021/* create dictionary */1022{ unsigned dictContentSize = ZDICT_dictSize(dictList);1023if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); } /* dictionary content too small */1024if (dictContentSize < targetDictSize/4) {1025DISPLAYLEVEL(2, "! warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);1026if (samplesBuffSize < 10 * targetDictSize)1027DISPLAYLEVEL(2, "! consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));1028if (minRep > MINRATIO) {1029DISPLAYLEVEL(2, "! consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);1030DISPLAYLEVEL(2, "! note : larger dictionaries are not necessarily better, test its efficiency on samples \n");1031}1032}10331034if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {1035unsigned proposedSelectivity = selectivity-1;1036while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }1037DISPLAYLEVEL(2, "! note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);1038DISPLAYLEVEL(2, "! consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);1039DISPLAYLEVEL(2, "! always test dictionary efficiency on real samples \n");1040}10411042/* limit dictionary size */1043{ U32 const max = dictList->pos; /* convention : nb of useful elts within dictList */1044U32 currentSize = 0;1045U32 n; for (n=1; n<max; n++) {1046currentSize += dictList[n].length;1047if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }1048}1049dictList->pos = n;1050dictContentSize = currentSize;1051}10521053/* build dict content */1054{ U32 u;1055BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;1056for (u=1; u<dictList->pos; u++) {1057U32 l = dictList[u].length;1058ptr -= l;1059if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); } /* should not happen */1060memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);1061} }10621063dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,1064samplesBuffer, samplesSizes, nbSamples,1065params.zParams);1066}10671068/* clean up */1069free(dictList);1070return dictSize;1071}107210731074/* ZDICT_trainFromBuffer_legacy() :1075* issue : samplesBuffer need to be followed by a noisy guard band.1076* work around : duplicate the buffer, and add the noise */1077size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,1078const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,1079ZDICT_legacy_params_t params)1080{1081size_t result;1082void* newBuff;1083size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);1084if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0; /* not enough content => no dictionary */10851086newBuff = malloc(sBuffSize + NOISELENGTH);1087if (!newBuff) return ERROR(memory_allocation);10881089memcpy(newBuff, samplesBuffer, sBuffSize);1090ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH); /* guard band, for end of buffer condition */10911092result =1093ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,1094samplesSizes, nbSamples, params);1095free(newBuff);1096return result;1097}109810991100size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,1101const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)1102{1103ZDICT_fastCover_params_t params;1104DEBUGLOG(3, "ZDICT_trainFromBuffer");1105memset(¶ms, 0, sizeof(params));1106params.d = 8;1107params.steps = 4;1108/* Use default level since no compression level information is available */1109params.zParams.compressionLevel = ZSTD_CLEVEL_DEFAULT;1110#if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)1111params.zParams.notificationLevel = DEBUGLEVEL;1112#endif1113return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,1114samplesBuffer, samplesSizes, nbSamples,1115¶ms);1116}11171118size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,1119const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)1120{1121ZDICT_params_t params;1122memset(¶ms, 0, sizeof(params));1123return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,1124samplesBuffer, samplesSizes, nbSamples,1125params);1126}112711281129