Path: blob/master/Utilities/cmzstd/lib/compress/zstd_compress_sequences.c
3158 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*/910/*-*************************************11* Dependencies12***************************************/13#include "zstd_compress_sequences.h"1415/**16* -log2(x / 256) lookup table for x in [0, 256).17* If x == 0: Return 018* Else: Return floor(-log2(x / 256) * 256)19*/20static unsigned const kInverseProbabilityLog256[256] = {210, 2048, 1792, 1642, 1536, 1453, 1386, 1329, 1280, 1236, 1197, 1162,221130, 1100, 1073, 1047, 1024, 1001, 980, 960, 941, 923, 906, 889,23874, 859, 844, 830, 817, 804, 791, 779, 768, 756, 745, 734,24724, 714, 704, 694, 685, 676, 667, 658, 650, 642, 633, 626,25618, 610, 603, 595, 588, 581, 574, 567, 561, 554, 548, 542,26535, 529, 523, 517, 512, 506, 500, 495, 489, 484, 478, 473,27468, 463, 458, 453, 448, 443, 438, 434, 429, 424, 420, 415,28411, 407, 402, 398, 394, 390, 386, 382, 377, 373, 370, 366,29362, 358, 354, 350, 347, 343, 339, 336, 332, 329, 325, 322,30318, 315, 311, 308, 305, 302, 298, 295, 292, 289, 286, 282,31279, 276, 273, 270, 267, 264, 261, 258, 256, 253, 250, 247,32244, 241, 239, 236, 233, 230, 228, 225, 222, 220, 217, 215,33212, 209, 207, 204, 202, 199, 197, 194, 192, 190, 187, 185,34182, 180, 178, 175, 173, 171, 168, 166, 164, 162, 159, 157,35155, 153, 151, 149, 146, 144, 142, 140, 138, 136, 134, 132,36130, 128, 126, 123, 121, 119, 117, 115, 114, 112, 110, 108,37106, 104, 102, 100, 98, 96, 94, 93, 91, 89, 87, 85,3883, 82, 80, 78, 76, 74, 73, 71, 69, 67, 66, 64,3962, 61, 59, 57, 55, 54, 52, 50, 49, 47, 46, 44,4042, 41, 39, 37, 36, 34, 33, 31, 30, 28, 26, 25,4123, 22, 20, 19, 17, 16, 14, 13, 11, 10, 8, 7,425, 4, 2, 1,43};4445static unsigned ZSTD_getFSEMaxSymbolValue(FSE_CTable const* ctable) {46void const* ptr = ctable;47U16 const* u16ptr = (U16 const*)ptr;48U32 const maxSymbolValue = MEM_read16(u16ptr + 1);49return maxSymbolValue;50}5152/**53* Returns true if we should use ncount=-1 else we should54* use ncount=1 for low probability symbols instead.55*/56static unsigned ZSTD_useLowProbCount(size_t const nbSeq)57{58/* Heuristic: This should cover most blocks <= 16K and59* start to fade out after 16K to about 32K depending on60* compressibility.61*/62return nbSeq >= 2048;63}6465/**66* Returns the cost in bytes of encoding the normalized count header.67* Returns an error if any of the helper functions return an error.68*/69static size_t ZSTD_NCountCost(unsigned const* count, unsigned const max,70size_t const nbSeq, unsigned const FSELog)71{72BYTE wksp[FSE_NCOUNTBOUND];73S16 norm[MaxSeq + 1];74const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);75FORWARD_IF_ERROR(FSE_normalizeCount(norm, tableLog, count, nbSeq, max, ZSTD_useLowProbCount(nbSeq)), "");76return FSE_writeNCount(wksp, sizeof(wksp), norm, max, tableLog);77}7879/**80* Returns the cost in bits of encoding the distribution described by count81* using the entropy bound.82*/83static size_t ZSTD_entropyCost(unsigned const* count, unsigned const max, size_t const total)84{85unsigned cost = 0;86unsigned s;8788assert(total > 0);89for (s = 0; s <= max; ++s) {90unsigned norm = (unsigned)((256 * count[s]) / total);91if (count[s] != 0 && norm == 0)92norm = 1;93assert(count[s] < total);94cost += count[s] * kInverseProbabilityLog256[norm];95}96return cost >> 8;97}9899/**100* Returns the cost in bits of encoding the distribution in count using ctable.101* Returns an error if ctable cannot represent all the symbols in count.102*/103size_t ZSTD_fseBitCost(104FSE_CTable const* ctable,105unsigned const* count,106unsigned const max)107{108unsigned const kAccuracyLog = 8;109size_t cost = 0;110unsigned s;111FSE_CState_t cstate;112FSE_initCState(&cstate, ctable);113if (ZSTD_getFSEMaxSymbolValue(ctable) < max) {114DEBUGLOG(5, "Repeat FSE_CTable has maxSymbolValue %u < %u",115ZSTD_getFSEMaxSymbolValue(ctable), max);116return ERROR(GENERIC);117}118for (s = 0; s <= max; ++s) {119unsigned const tableLog = cstate.stateLog;120unsigned const badCost = (tableLog + 1) << kAccuracyLog;121unsigned const bitCost = FSE_bitCost(cstate.symbolTT, tableLog, s, kAccuracyLog);122if (count[s] == 0)123continue;124if (bitCost >= badCost) {125DEBUGLOG(5, "Repeat FSE_CTable has Prob[%u] == 0", s);126return ERROR(GENERIC);127}128cost += (size_t)count[s] * bitCost;129}130return cost >> kAccuracyLog;131}132133/**134* Returns the cost in bits of encoding the distribution in count using the135* table described by norm. The max symbol support by norm is assumed >= max.136* norm must be valid for every symbol with non-zero probability in count.137*/138size_t ZSTD_crossEntropyCost(short const* norm, unsigned accuracyLog,139unsigned const* count, unsigned const max)140{141unsigned const shift = 8 - accuracyLog;142size_t cost = 0;143unsigned s;144assert(accuracyLog <= 8);145for (s = 0; s <= max; ++s) {146unsigned const normAcc = (norm[s] != -1) ? (unsigned)norm[s] : 1;147unsigned const norm256 = normAcc << shift;148assert(norm256 > 0);149assert(norm256 < 256);150cost += count[s] * kInverseProbabilityLog256[norm256];151}152return cost >> 8;153}154155symbolEncodingType_e156ZSTD_selectEncodingType(157FSE_repeat* repeatMode, unsigned const* count, unsigned const max,158size_t const mostFrequent, size_t nbSeq, unsigned const FSELog,159FSE_CTable const* prevCTable,160short const* defaultNorm, U32 defaultNormLog,161ZSTD_defaultPolicy_e const isDefaultAllowed,162ZSTD_strategy const strategy)163{164ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0);165if (mostFrequent == nbSeq) {166*repeatMode = FSE_repeat_none;167if (isDefaultAllowed && nbSeq <= 2) {168/* Prefer set_basic over set_rle when there are 2 or fewer symbols,169* since RLE uses 1 byte, but set_basic uses 5-6 bits per symbol.170* If basic encoding isn't possible, always choose RLE.171*/172DEBUGLOG(5, "Selected set_basic");173return set_basic;174}175DEBUGLOG(5, "Selected set_rle");176return set_rle;177}178if (strategy < ZSTD_lazy) {179if (isDefaultAllowed) {180size_t const staticFse_nbSeq_max = 1000;181size_t const mult = 10 - strategy;182size_t const baseLog = 3;183size_t const dynamicFse_nbSeq_min = (((size_t)1 << defaultNormLog) * mult) >> baseLog; /* 28-36 for offset, 56-72 for lengths */184assert(defaultNormLog >= 5 && defaultNormLog <= 6); /* xx_DEFAULTNORMLOG */185assert(mult <= 9 && mult >= 7);186if ( (*repeatMode == FSE_repeat_valid)187&& (nbSeq < staticFse_nbSeq_max) ) {188DEBUGLOG(5, "Selected set_repeat");189return set_repeat;190}191if ( (nbSeq < dynamicFse_nbSeq_min)192|| (mostFrequent < (nbSeq >> (defaultNormLog-1))) ) {193DEBUGLOG(5, "Selected set_basic");194/* The format allows default tables to be repeated, but it isn't useful.195* When using simple heuristics to select encoding type, we don't want196* to confuse these tables with dictionaries. When running more careful197* analysis, we don't need to waste time checking both repeating tables198* and default tables.199*/200*repeatMode = FSE_repeat_none;201return set_basic;202}203}204} else {205size_t const basicCost = isDefaultAllowed ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, count, max) : ERROR(GENERIC);206size_t const repeatCost = *repeatMode != FSE_repeat_none ? ZSTD_fseBitCost(prevCTable, count, max) : ERROR(GENERIC);207size_t const NCountCost = ZSTD_NCountCost(count, max, nbSeq, FSELog);208size_t const compressedCost = (NCountCost << 3) + ZSTD_entropyCost(count, max, nbSeq);209210if (isDefaultAllowed) {211assert(!ZSTD_isError(basicCost));212assert(!(*repeatMode == FSE_repeat_valid && ZSTD_isError(repeatCost)));213}214assert(!ZSTD_isError(NCountCost));215assert(compressedCost < ERROR(maxCode));216DEBUGLOG(5, "Estimated bit costs: basic=%u\trepeat=%u\tcompressed=%u",217(unsigned)basicCost, (unsigned)repeatCost, (unsigned)compressedCost);218if (basicCost <= repeatCost && basicCost <= compressedCost) {219DEBUGLOG(5, "Selected set_basic");220assert(isDefaultAllowed);221*repeatMode = FSE_repeat_none;222return set_basic;223}224if (repeatCost <= compressedCost) {225DEBUGLOG(5, "Selected set_repeat");226assert(!ZSTD_isError(repeatCost));227return set_repeat;228}229assert(compressedCost < basicCost && compressedCost < repeatCost);230}231DEBUGLOG(5, "Selected set_compressed");232*repeatMode = FSE_repeat_check;233return set_compressed;234}235236typedef struct {237S16 norm[MaxSeq + 1];238U32 wksp[FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(MaxSeq, MaxFSELog)];239} ZSTD_BuildCTableWksp;240241size_t242ZSTD_buildCTable(void* dst, size_t dstCapacity,243FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,244unsigned* count, U32 max,245const BYTE* codeTable, size_t nbSeq,246const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,247const FSE_CTable* prevCTable, size_t prevCTableSize,248void* entropyWorkspace, size_t entropyWorkspaceSize)249{250BYTE* op = (BYTE*)dst;251const BYTE* const oend = op + dstCapacity;252DEBUGLOG(6, "ZSTD_buildCTable (dstCapacity=%u)", (unsigned)dstCapacity);253254switch (type) {255case set_rle:256FORWARD_IF_ERROR(FSE_buildCTable_rle(nextCTable, (BYTE)max), "");257RETURN_ERROR_IF(dstCapacity==0, dstSize_tooSmall, "not enough space");258*op = codeTable[0];259return 1;260case set_repeat:261ZSTD_memcpy(nextCTable, prevCTable, prevCTableSize);262return 0;263case set_basic:264FORWARD_IF_ERROR(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, entropyWorkspace, entropyWorkspaceSize), ""); /* note : could be pre-calculated */265return 0;266case set_compressed: {267ZSTD_BuildCTableWksp* wksp = (ZSTD_BuildCTableWksp*)entropyWorkspace;268size_t nbSeq_1 = nbSeq;269const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);270if (count[codeTable[nbSeq-1]] > 1) {271count[codeTable[nbSeq-1]]--;272nbSeq_1--;273}274assert(nbSeq_1 > 1);275assert(entropyWorkspaceSize >= sizeof(ZSTD_BuildCTableWksp));276(void)entropyWorkspaceSize;277FORWARD_IF_ERROR(FSE_normalizeCount(wksp->norm, tableLog, count, nbSeq_1, max, ZSTD_useLowProbCount(nbSeq_1)), "FSE_normalizeCount failed");278assert(oend >= op);279{ size_t const NCountSize = FSE_writeNCount(op, (size_t)(oend - op), wksp->norm, max, tableLog); /* overflow protected */280FORWARD_IF_ERROR(NCountSize, "FSE_writeNCount failed");281FORWARD_IF_ERROR(FSE_buildCTable_wksp(nextCTable, wksp->norm, max, tableLog, wksp->wksp, sizeof(wksp->wksp)), "FSE_buildCTable_wksp failed");282return NCountSize;283}284}285default: assert(0); RETURN_ERROR(GENERIC, "impossible to reach");286}287}288289FORCE_INLINE_TEMPLATE size_t290ZSTD_encodeSequences_body(291void* dst, size_t dstCapacity,292FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,293FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,294FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,295seqDef const* sequences, size_t nbSeq, int longOffsets)296{297BIT_CStream_t blockStream;298FSE_CState_t stateMatchLength;299FSE_CState_t stateOffsetBits;300FSE_CState_t stateLitLength;301302RETURN_ERROR_IF(303ERR_isError(BIT_initCStream(&blockStream, dst, dstCapacity)),304dstSize_tooSmall, "not enough space remaining");305DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)",306(int)(blockStream.endPtr - blockStream.startPtr),307(unsigned)dstCapacity);308309/* first symbols */310FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);311FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);312FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);313BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);314if (MEM_32bits()) BIT_flushBits(&blockStream);315BIT_addBits(&blockStream, sequences[nbSeq-1].mlBase, ML_bits[mlCodeTable[nbSeq-1]]);316if (MEM_32bits()) BIT_flushBits(&blockStream);317if (longOffsets) {318U32 const ofBits = ofCodeTable[nbSeq-1];319unsigned const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);320if (extraBits) {321BIT_addBits(&blockStream, sequences[nbSeq-1].offBase, extraBits);322BIT_flushBits(&blockStream);323}324BIT_addBits(&blockStream, sequences[nbSeq-1].offBase >> extraBits,325ofBits - extraBits);326} else {327BIT_addBits(&blockStream, sequences[nbSeq-1].offBase, ofCodeTable[nbSeq-1]);328}329BIT_flushBits(&blockStream);330331{ size_t n;332for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */333BYTE const llCode = llCodeTable[n];334BYTE const ofCode = ofCodeTable[n];335BYTE const mlCode = mlCodeTable[n];336U32 const llBits = LL_bits[llCode];337U32 const ofBits = ofCode;338U32 const mlBits = ML_bits[mlCode];339DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",340(unsigned)sequences[n].litLength,341(unsigned)sequences[n].mlBase + MINMATCH,342(unsigned)sequences[n].offBase);343/* 32b*/ /* 64b*/344/* (7)*/ /* (7)*/345FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */346FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */347if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/348FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */349if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))350BIT_flushBits(&blockStream); /* (7)*/351BIT_addBits(&blockStream, sequences[n].litLength, llBits);352if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);353BIT_addBits(&blockStream, sequences[n].mlBase, mlBits);354if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);355if (longOffsets) {356unsigned const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);357if (extraBits) {358BIT_addBits(&blockStream, sequences[n].offBase, extraBits);359BIT_flushBits(&blockStream); /* (7)*/360}361BIT_addBits(&blockStream, sequences[n].offBase >> extraBits,362ofBits - extraBits); /* 31 */363} else {364BIT_addBits(&blockStream, sequences[n].offBase, ofBits); /* 31 */365}366BIT_flushBits(&blockStream); /* (7)*/367DEBUGLOG(7, "remaining space : %i", (int)(blockStream.endPtr - blockStream.ptr));368} }369370DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);371FSE_flushCState(&blockStream, &stateMatchLength);372DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);373FSE_flushCState(&blockStream, &stateOffsetBits);374DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);375FSE_flushCState(&blockStream, &stateLitLength);376377{ size_t const streamSize = BIT_closeCStream(&blockStream);378RETURN_ERROR_IF(streamSize==0, dstSize_tooSmall, "not enough space");379return streamSize;380}381}382383static size_t384ZSTD_encodeSequences_default(385void* dst, size_t dstCapacity,386FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,387FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,388FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,389seqDef const* sequences, size_t nbSeq, int longOffsets)390{391return ZSTD_encodeSequences_body(dst, dstCapacity,392CTable_MatchLength, mlCodeTable,393CTable_OffsetBits, ofCodeTable,394CTable_LitLength, llCodeTable,395sequences, nbSeq, longOffsets);396}397398399#if DYNAMIC_BMI2400401static BMI2_TARGET_ATTRIBUTE size_t402ZSTD_encodeSequences_bmi2(403void* dst, size_t dstCapacity,404FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,405FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,406FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,407seqDef const* sequences, size_t nbSeq, int longOffsets)408{409return ZSTD_encodeSequences_body(dst, dstCapacity,410CTable_MatchLength, mlCodeTable,411CTable_OffsetBits, ofCodeTable,412CTable_LitLength, llCodeTable,413sequences, nbSeq, longOffsets);414}415416#endif417418size_t ZSTD_encodeSequences(419void* dst, size_t dstCapacity,420FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,421FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,422FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,423seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2)424{425DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity);426#if DYNAMIC_BMI2427if (bmi2) {428return ZSTD_encodeSequences_bmi2(dst, dstCapacity,429CTable_MatchLength, mlCodeTable,430CTable_OffsetBits, ofCodeTable,431CTable_LitLength, llCodeTable,432sequences, nbSeq, longOffsets);433}434#endif435(void)bmi2;436return ZSTD_encodeSequences_default(dst, dstCapacity,437CTable_MatchLength, mlCodeTable,438CTable_OffsetBits, ofCodeTable,439CTable_LitLength, llCodeTable,440sequences, nbSeq, longOffsets);441}442443444