10c16b537SWarner Losh /* 2*37f1f268SConrad Meyer * Copyright (c) 2016-2020, Przemyslaw Skibinski, 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 11052d3c12SConrad Meyer #include "zstd_compress_internal.h" 120f743729SConrad Meyer #include "hist.h" 130c16b537SWarner Losh #include "zstd_opt.h" 140c16b537SWarner Losh 150c16b537SWarner Losh 160f743729SConrad Meyer #define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */ 17052d3c12SConrad Meyer #define ZSTD_FREQ_DIV 4 /* log factor when using previous stats to init next stats */ 180c16b537SWarner Losh #define ZSTD_MAX_PRICE (1<<30) 190c16b537SWarner Losh 20a0483764SConrad Meyer #define ZSTD_PREDEF_THRESHOLD 1024 /* if srcSize < ZSTD_PREDEF_THRESHOLD, symbols' cost is assumed static, directly determined by pre-defined distributions */ 21a0483764SConrad Meyer 22052d3c12SConrad Meyer 230c16b537SWarner Losh /*-************************************* 240c16b537SWarner Losh * Price functions for optimal parser 250c16b537SWarner Losh ***************************************/ 260f743729SConrad Meyer 270f743729SConrad Meyer #if 0 /* approximation at bit level */ 280f743729SConrad Meyer # define BITCOST_ACCURACY 0 290f743729SConrad Meyer # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY) 300f743729SConrad Meyer # define WEIGHT(stat) ((void)opt, ZSTD_bitWeight(stat)) 310f743729SConrad Meyer #elif 0 /* fractional bit accuracy */ 320f743729SConrad Meyer # define BITCOST_ACCURACY 8 330f743729SConrad Meyer # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY) 340f743729SConrad Meyer # define WEIGHT(stat,opt) ((void)opt, ZSTD_fracWeight(stat)) 350f743729SConrad Meyer #else /* opt==approx, ultra==accurate */ 360f743729SConrad Meyer # define BITCOST_ACCURACY 8 370f743729SConrad Meyer # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY) 380f743729SConrad Meyer # define WEIGHT(stat,opt) (opt ? ZSTD_fracWeight(stat) : ZSTD_bitWeight(stat)) 390f743729SConrad Meyer #endif 400f743729SConrad Meyer 410f743729SConrad Meyer MEM_STATIC U32 ZSTD_bitWeight(U32 stat) 420c16b537SWarner Losh { 430f743729SConrad Meyer return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER); 440c16b537SWarner Losh } 450c16b537SWarner Losh 460f743729SConrad Meyer MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat) 470f743729SConrad Meyer { 480f743729SConrad Meyer U32 const stat = rawStat + 1; 490f743729SConrad Meyer U32 const hb = ZSTD_highbit32(stat); 500f743729SConrad Meyer U32 const BWeight = hb * BITCOST_MULTIPLIER; 510f743729SConrad Meyer U32 const FWeight = (stat << BITCOST_ACCURACY) >> hb; 520f743729SConrad Meyer U32 const weight = BWeight + FWeight; 530f743729SConrad Meyer assert(hb + BITCOST_ACCURACY < 31); 540f743729SConrad Meyer return weight; 550f743729SConrad Meyer } 560f743729SConrad Meyer 57a0483764SConrad Meyer #if (DEBUGLEVEL>=2) 58a0483764SConrad Meyer /* debugging function, 59a0483764SConrad Meyer * @return price in bytes as fractional value 60a0483764SConrad Meyer * for debug messages only */ 610f743729SConrad Meyer MEM_STATIC double ZSTD_fCost(U32 price) 620f743729SConrad Meyer { 630f743729SConrad Meyer return (double)price / (BITCOST_MULTIPLIER*8); 640f743729SConrad Meyer } 65a0483764SConrad Meyer #endif 660f743729SConrad Meyer 672b9c00cbSConrad Meyer static int ZSTD_compressedLiterals(optState_t const* const optPtr) 682b9c00cbSConrad Meyer { 692b9c00cbSConrad Meyer return optPtr->literalCompressionMode != ZSTD_lcm_uncompressed; 702b9c00cbSConrad Meyer } 712b9c00cbSConrad Meyer 720f743729SConrad Meyer static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel) 730f743729SConrad Meyer { 742b9c00cbSConrad Meyer if (ZSTD_compressedLiterals(optPtr)) 750f743729SConrad Meyer optPtr->litSumBasePrice = WEIGHT(optPtr->litSum, optLevel); 760f743729SConrad Meyer optPtr->litLengthSumBasePrice = WEIGHT(optPtr->litLengthSum, optLevel); 770f743729SConrad Meyer optPtr->matchLengthSumBasePrice = WEIGHT(optPtr->matchLengthSum, optLevel); 780f743729SConrad Meyer optPtr->offCodeSumBasePrice = WEIGHT(optPtr->offCodeSum, optLevel); 790f743729SConrad Meyer } 800f743729SConrad Meyer 810f743729SConrad Meyer 82a0483764SConrad Meyer /* ZSTD_downscaleStat() : 83a0483764SConrad Meyer * reduce all elements in table by a factor 2^(ZSTD_FREQ_DIV+malus) 84a0483764SConrad Meyer * return the resulting sum of elements */ 85a0483764SConrad Meyer static U32 ZSTD_downscaleStat(unsigned* table, U32 lastEltIndex, int malus) 860f743729SConrad Meyer { 870f743729SConrad Meyer U32 s, sum=0; 88a0483764SConrad Meyer DEBUGLOG(5, "ZSTD_downscaleStat (nbElts=%u)", (unsigned)lastEltIndex+1); 890f743729SConrad Meyer assert(ZSTD_FREQ_DIV+malus > 0 && ZSTD_FREQ_DIV+malus < 31); 90a0483764SConrad Meyer for (s=0; s<lastEltIndex+1; s++) { 910f743729SConrad Meyer table[s] = 1 + (table[s] >> (ZSTD_FREQ_DIV+malus)); 920f743729SConrad Meyer sum += table[s]; 930f743729SConrad Meyer } 940f743729SConrad Meyer return sum; 950f743729SConrad Meyer } 960c16b537SWarner Losh 97a0483764SConrad Meyer /* ZSTD_rescaleFreqs() : 98a0483764SConrad Meyer * if first block (detected by optPtr->litLengthSum == 0) : init statistics 99a0483764SConrad Meyer * take hints from dictionary if there is one 100a0483764SConrad Meyer * or init from zero, using src for literals stats, or flat 1 for match symbols 101a0483764SConrad Meyer * otherwise downscale existing stats, to be used as seed for next block. 102a0483764SConrad Meyer */ 103a0483764SConrad Meyer static void 104a0483764SConrad Meyer ZSTD_rescaleFreqs(optState_t* const optPtr, 1050f743729SConrad Meyer const BYTE* const src, size_t const srcSize, 106a0483764SConrad Meyer int const optLevel) 1070c16b537SWarner Losh { 1082b9c00cbSConrad Meyer int const compressedLiterals = ZSTD_compressedLiterals(optPtr); 109a0483764SConrad Meyer DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize); 1100f743729SConrad Meyer optPtr->priceType = zop_dynamic; 1110c16b537SWarner Losh 1120f743729SConrad Meyer if (optPtr->litLengthSum == 0) { /* first block : init */ 113a0483764SConrad Meyer if (srcSize <= ZSTD_PREDEF_THRESHOLD) { /* heuristic */ 114a0483764SConrad Meyer DEBUGLOG(5, "(srcSize <= ZSTD_PREDEF_THRESHOLD) => zop_predef"); 1150f743729SConrad Meyer optPtr->priceType = zop_predef; 116a0483764SConrad Meyer } 1170f743729SConrad Meyer 1180f743729SConrad Meyer assert(optPtr->symbolCosts != NULL); 119a0483764SConrad Meyer if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) { 120a0483764SConrad Meyer /* huffman table presumed generated by dictionary */ 1210f743729SConrad Meyer optPtr->priceType = zop_dynamic; 1220c16b537SWarner Losh 1232b9c00cbSConrad Meyer if (compressedLiterals) { 1242b9c00cbSConrad Meyer unsigned lit; 1250c16b537SWarner Losh assert(optPtr->litFreq != NULL); 1260c16b537SWarner Losh optPtr->litSum = 0; 1270f743729SConrad Meyer for (lit=0; lit<=MaxLit; lit++) { 1280f743729SConrad Meyer U32 const scaleLog = 11; /* scale to 2K */ 1290f743729SConrad Meyer U32 const bitCost = HUF_getNbBits(optPtr->symbolCosts->huf.CTable, lit); 1300f743729SConrad Meyer assert(bitCost <= scaleLog); 1310f743729SConrad Meyer optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/; 1320f743729SConrad Meyer optPtr->litSum += optPtr->litFreq[lit]; 1330f743729SConrad Meyer } } 134052d3c12SConrad Meyer 1350f743729SConrad Meyer { unsigned ll; 1360f743729SConrad Meyer FSE_CState_t llstate; 1370f743729SConrad Meyer FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable); 138052d3c12SConrad Meyer optPtr->litLengthSum = 0; 1390f743729SConrad Meyer for (ll=0; ll<=MaxLL; ll++) { 1400f743729SConrad Meyer U32 const scaleLog = 10; /* scale to 1K */ 1410f743729SConrad Meyer U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll); 1420f743729SConrad Meyer assert(bitCost < scaleLog); 1430f743729SConrad Meyer optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/; 1440f743729SConrad Meyer optPtr->litLengthSum += optPtr->litLengthFreq[ll]; 1450f743729SConrad Meyer } } 1460f743729SConrad Meyer 1470f743729SConrad Meyer { unsigned ml; 1480f743729SConrad Meyer FSE_CState_t mlstate; 1490f743729SConrad Meyer FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable); 150052d3c12SConrad Meyer optPtr->matchLengthSum = 0; 1510f743729SConrad Meyer for (ml=0; ml<=MaxML; ml++) { 1520f743729SConrad Meyer U32 const scaleLog = 10; 1530f743729SConrad Meyer U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml); 1540f743729SConrad Meyer assert(bitCost < scaleLog); 1550f743729SConrad Meyer optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/; 1560f743729SConrad Meyer optPtr->matchLengthSum += optPtr->matchLengthFreq[ml]; 1570f743729SConrad Meyer } } 1580f743729SConrad Meyer 1590f743729SConrad Meyer { unsigned of; 1600f743729SConrad Meyer FSE_CState_t ofstate; 1610f743729SConrad Meyer FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable); 162052d3c12SConrad Meyer optPtr->offCodeSum = 0; 1630f743729SConrad Meyer for (of=0; of<=MaxOff; of++) { 1640f743729SConrad Meyer U32 const scaleLog = 10; 1650f743729SConrad Meyer U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of); 1660f743729SConrad Meyer assert(bitCost < scaleLog); 1670f743729SConrad Meyer optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/; 1680f743729SConrad Meyer optPtr->offCodeSum += optPtr->offCodeFreq[of]; 1690f743729SConrad Meyer } } 1700f743729SConrad Meyer 1710f743729SConrad Meyer } else { /* not a dictionary */ 1720f743729SConrad Meyer 1730f743729SConrad Meyer assert(optPtr->litFreq != NULL); 1742b9c00cbSConrad Meyer if (compressedLiterals) { 1752b9c00cbSConrad Meyer unsigned lit = MaxLit; 1760f743729SConrad Meyer HIST_count_simple(optPtr->litFreq, &lit, src, srcSize); /* use raw first block to init statistics */ 1770f743729SConrad Meyer optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1); 1782b9c00cbSConrad Meyer } 1790f743729SConrad Meyer 1800f743729SConrad Meyer { unsigned ll; 1810f743729SConrad Meyer for (ll=0; ll<=MaxLL; ll++) 1820f743729SConrad Meyer optPtr->litLengthFreq[ll] = 1; 1830f743729SConrad Meyer } 1840f743729SConrad Meyer optPtr->litLengthSum = MaxLL+1; 1850f743729SConrad Meyer 1860f743729SConrad Meyer { unsigned ml; 1870f743729SConrad Meyer for (ml=0; ml<=MaxML; ml++) 1880f743729SConrad Meyer optPtr->matchLengthFreq[ml] = 1; 1890f743729SConrad Meyer } 1900f743729SConrad Meyer optPtr->matchLengthSum = MaxML+1; 1910f743729SConrad Meyer 1920f743729SConrad Meyer { unsigned of; 1930f743729SConrad Meyer for (of=0; of<=MaxOff; of++) 1940f743729SConrad Meyer optPtr->offCodeFreq[of] = 1; 1950f743729SConrad Meyer } 1960f743729SConrad Meyer optPtr->offCodeSum = MaxOff+1; 1970f743729SConrad Meyer 1980c16b537SWarner Losh } 1990c16b537SWarner Losh 2000f743729SConrad Meyer } else { /* new block : re-use previous statistics, scaled down */ 2010f743729SConrad Meyer 2022b9c00cbSConrad Meyer if (compressedLiterals) 2030f743729SConrad Meyer optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1); 2040f743729SConrad Meyer optPtr->litLengthSum = ZSTD_downscaleStat(optPtr->litLengthFreq, MaxLL, 0); 2050f743729SConrad Meyer optPtr->matchLengthSum = ZSTD_downscaleStat(optPtr->matchLengthFreq, MaxML, 0); 2060f743729SConrad Meyer optPtr->offCodeSum = ZSTD_downscaleStat(optPtr->offCodeFreq, MaxOff, 0); 2070c16b537SWarner Losh } 2080c16b537SWarner Losh 2090f743729SConrad Meyer ZSTD_setBasePrices(optPtr, optLevel); 2100f743729SConrad Meyer } 2110c16b537SWarner Losh 212052d3c12SConrad Meyer /* ZSTD_rawLiteralsCost() : 2130f743729SConrad Meyer * price of literals (only) in specified segment (which length can be 0). 2140f743729SConrad Meyer * does not include price of literalLength symbol */ 215052d3c12SConrad Meyer static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength, 2160f743729SConrad Meyer const optState_t* const optPtr, 2170f743729SConrad Meyer int optLevel) 2180c16b537SWarner Losh { 219052d3c12SConrad Meyer if (litLength == 0) return 0; 2202b9c00cbSConrad Meyer 2212b9c00cbSConrad Meyer if (!ZSTD_compressedLiterals(optPtr)) 2222b9c00cbSConrad Meyer return (litLength << 3) * BITCOST_MULTIPLIER; /* Uncompressed - 8 bytes per literal. */ 2232b9c00cbSConrad Meyer 2240f743729SConrad Meyer if (optPtr->priceType == zop_predef) 2250f743729SConrad Meyer return (litLength*6) * BITCOST_MULTIPLIER; /* 6 bit per literal - no statistic used */ 2260c16b537SWarner Losh 2270f743729SConrad Meyer /* dynamic statistics */ 2280f743729SConrad Meyer { U32 price = litLength * optPtr->litSumBasePrice; 2290f743729SConrad Meyer U32 u; 2300f743729SConrad Meyer for (u=0; u < litLength; u++) { 2310f743729SConrad Meyer assert(WEIGHT(optPtr->litFreq[literals[u]], optLevel) <= optPtr->litSumBasePrice); /* literal cost should never be negative */ 2320f743729SConrad Meyer price -= WEIGHT(optPtr->litFreq[literals[u]], optLevel); 233052d3c12SConrad Meyer } 2340c16b537SWarner Losh return price; 2350c16b537SWarner Losh } 236052d3c12SConrad Meyer } 2370c16b537SWarner Losh 238052d3c12SConrad Meyer /* ZSTD_litLengthPrice() : 2390f743729SConrad Meyer * cost of literalLength symbol */ 2400f743729SConrad Meyer static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel) 2410c16b537SWarner Losh { 2420f743729SConrad Meyer if (optPtr->priceType == zop_predef) return WEIGHT(litLength, optLevel); 2430f743729SConrad Meyer 2440f743729SConrad Meyer /* dynamic statistics */ 2450f743729SConrad Meyer { U32 const llCode = ZSTD_LLcode(litLength); 246a0483764SConrad Meyer return (LL_bits[llCode] * BITCOST_MULTIPLIER) 247a0483764SConrad Meyer + optPtr->litLengthSumBasePrice 248a0483764SConrad Meyer - WEIGHT(optPtr->litLengthFreq[llCode], optLevel); 2490f743729SConrad Meyer } 250052d3c12SConrad Meyer } 2510c16b537SWarner Losh 252052d3c12SConrad Meyer /* ZSTD_getMatchPrice() : 253052d3c12SConrad Meyer * Provides the cost of the match part (offset + matchLength) of a sequence 254052d3c12SConrad Meyer * Must be combined with ZSTD_fullLiteralsCost() to get the full cost of a sequence. 255052d3c12SConrad Meyer * optLevel: when <2, favors small offset for decompression speed (improved cache efficiency) */ 2560f743729SConrad Meyer FORCE_INLINE_TEMPLATE U32 2570f743729SConrad Meyer ZSTD_getMatchPrice(U32 const offset, 2580f743729SConrad Meyer U32 const matchLength, 259052d3c12SConrad Meyer const optState_t* const optPtr, 260052d3c12SConrad Meyer int const optLevel) 261052d3c12SConrad Meyer { 262052d3c12SConrad Meyer U32 price; 263052d3c12SConrad Meyer U32 const offCode = ZSTD_highbit32(offset+1); 264052d3c12SConrad Meyer U32 const mlBase = matchLength - MINMATCH; 265052d3c12SConrad Meyer assert(matchLength >= MINMATCH); 266052d3c12SConrad Meyer 2670f743729SConrad Meyer if (optPtr->priceType == zop_predef) /* fixed scheme, do not use statistics */ 2680f743729SConrad Meyer return WEIGHT(mlBase, optLevel) + ((16 + offCode) * BITCOST_MULTIPLIER); 2690c16b537SWarner Losh 2700f743729SConrad Meyer /* dynamic statistics */ 2710f743729SConrad Meyer price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel)); 2720f743729SConrad Meyer if ((optLevel<2) /*static*/ && offCode >= 20) 2730f743729SConrad Meyer price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */ 2740c16b537SWarner Losh 2750c16b537SWarner Losh /* match Length */ 276052d3c12SConrad Meyer { U32 const mlCode = ZSTD_MLcode(mlBase); 2770f743729SConrad Meyer price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel)); 2780c16b537SWarner Losh } 2790c16b537SWarner Losh 2800f743729SConrad Meyer price += BITCOST_MULTIPLIER / 5; /* heuristic : make matches a bit more costly to favor less sequences -> faster decompression speed */ 2810f743729SConrad Meyer 282052d3c12SConrad Meyer DEBUGLOG(8, "ZSTD_getMatchPrice(ml:%u) = %u", matchLength, price); 283052d3c12SConrad Meyer return price; 2840c16b537SWarner Losh } 2850c16b537SWarner Losh 2860f743729SConrad Meyer /* ZSTD_updateStats() : 2870f743729SConrad Meyer * assumption : literals + litLengtn <= iend */ 288052d3c12SConrad Meyer static void ZSTD_updateStats(optState_t* const optPtr, 289052d3c12SConrad Meyer U32 litLength, const BYTE* literals, 290052d3c12SConrad Meyer U32 offsetCode, U32 matchLength) 2910c16b537SWarner Losh { 2920c16b537SWarner Losh /* literals */ 2932b9c00cbSConrad Meyer if (ZSTD_compressedLiterals(optPtr)) { 2942b9c00cbSConrad Meyer U32 u; 2950c16b537SWarner Losh for (u=0; u < litLength; u++) 2960c16b537SWarner Losh optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD; 297052d3c12SConrad Meyer optPtr->litSum += litLength*ZSTD_LITFREQ_ADD; 298052d3c12SConrad Meyer } 2990c16b537SWarner Losh 3000c16b537SWarner Losh /* literal Length */ 301052d3c12SConrad Meyer { U32 const llCode = ZSTD_LLcode(litLength); 3020c16b537SWarner Losh optPtr->litLengthFreq[llCode]++; 3030c16b537SWarner Losh optPtr->litLengthSum++; 3040c16b537SWarner Losh } 3050c16b537SWarner Losh 306052d3c12SConrad Meyer /* match offset code (0-2=>repCode; 3+=>offset+2) */ 307052d3c12SConrad Meyer { U32 const offCode = ZSTD_highbit32(offsetCode+1); 308052d3c12SConrad Meyer assert(offCode <= MaxOff); 3090c16b537SWarner Losh optPtr->offCodeFreq[offCode]++; 310052d3c12SConrad Meyer optPtr->offCodeSum++; 3110c16b537SWarner Losh } 3120c16b537SWarner Losh 3130c16b537SWarner Losh /* match Length */ 314052d3c12SConrad Meyer { U32 const mlBase = matchLength - MINMATCH; 315052d3c12SConrad Meyer U32 const mlCode = ZSTD_MLcode(mlBase); 3160c16b537SWarner Losh optPtr->matchLengthFreq[mlCode]++; 3170c16b537SWarner Losh optPtr->matchLengthSum++; 3180c16b537SWarner Losh } 3190c16b537SWarner Losh } 3200c16b537SWarner Losh 3210c16b537SWarner Losh 322052d3c12SConrad Meyer /* ZSTD_readMINMATCH() : 323052d3c12SConrad Meyer * function safe only for comparisons 324052d3c12SConrad Meyer * assumption : memPtr must be at least 4 bytes before end of buffer */ 325052d3c12SConrad Meyer MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length) 3260c16b537SWarner Losh { 3270c16b537SWarner Losh switch (length) 3280c16b537SWarner Losh { 3290c16b537SWarner Losh default : 3300c16b537SWarner Losh case 4 : return MEM_read32(memPtr); 3310c16b537SWarner Losh case 3 : if (MEM_isLittleEndian()) 3320c16b537SWarner Losh return MEM_read32(memPtr)<<8; 3330c16b537SWarner Losh else 3340c16b537SWarner Losh return MEM_read32(memPtr)>>8; 3350c16b537SWarner Losh } 3360c16b537SWarner Losh } 3370c16b537SWarner Losh 3380c16b537SWarner Losh 3390c16b537SWarner Losh /* Update hashTable3 up to ip (excluded) 3400c16b537SWarner Losh Assumption : always within prefix (i.e. not within extDict) */ 3414d3f1eafSConrad Meyer static U32 ZSTD_insertAndFindFirstIndexHash3 (ZSTD_matchState_t* ms, 3424d3f1eafSConrad Meyer U32* nextToUpdate3, 3434d3f1eafSConrad Meyer const BYTE* const ip) 3440c16b537SWarner Losh { 34519fcbaf1SConrad Meyer U32* const hashTable3 = ms->hashTable3; 34619fcbaf1SConrad Meyer U32 const hashLog3 = ms->hashLog3; 34719fcbaf1SConrad Meyer const BYTE* const base = ms->window.base; 3484d3f1eafSConrad Meyer U32 idx = *nextToUpdate3; 3494d3f1eafSConrad Meyer U32 const target = (U32)(ip - base); 350052d3c12SConrad Meyer size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3); 35119fcbaf1SConrad Meyer assert(hashLog3 > 0); 3520c16b537SWarner Losh 3530c16b537SWarner Losh while(idx < target) { 3540c16b537SWarner Losh hashTable3[ZSTD_hash3Ptr(base+idx, hashLog3)] = idx; 3550c16b537SWarner Losh idx++; 3560c16b537SWarner Losh } 3570c16b537SWarner Losh 3584d3f1eafSConrad Meyer *nextToUpdate3 = target; 3590c16b537SWarner Losh return hashTable3[hash3]; 3600c16b537SWarner Losh } 3610c16b537SWarner Losh 3620c16b537SWarner Losh 3630c16b537SWarner Losh /*-************************************* 3640c16b537SWarner Losh * Binary Tree search 3650c16b537SWarner Losh ***************************************/ 36619fcbaf1SConrad Meyer /** ZSTD_insertBt1() : add one or multiple positions to tree. 36719fcbaf1SConrad Meyer * ip : assumed <= iend-8 . 36819fcbaf1SConrad Meyer * @return : nb of positions added */ 36919fcbaf1SConrad Meyer static U32 ZSTD_insertBt1( 3700f743729SConrad Meyer ZSTD_matchState_t* ms, 37119fcbaf1SConrad Meyer const BYTE* const ip, const BYTE* const iend, 3720f743729SConrad Meyer U32 const mls, const int extDict) 37319fcbaf1SConrad Meyer { 3740f743729SConrad Meyer const ZSTD_compressionParameters* const cParams = &ms->cParams; 37519fcbaf1SConrad Meyer U32* const hashTable = ms->hashTable; 37619fcbaf1SConrad Meyer U32 const hashLog = cParams->hashLog; 37719fcbaf1SConrad Meyer size_t const h = ZSTD_hashPtr(ip, hashLog, mls); 37819fcbaf1SConrad Meyer U32* const bt = ms->chainTable; 37919fcbaf1SConrad Meyer U32 const btLog = cParams->chainLog - 1; 38019fcbaf1SConrad Meyer U32 const btMask = (1 << btLog) - 1; 38119fcbaf1SConrad Meyer U32 matchIndex = hashTable[h]; 38219fcbaf1SConrad Meyer size_t commonLengthSmaller=0, commonLengthLarger=0; 38319fcbaf1SConrad Meyer const BYTE* const base = ms->window.base; 38419fcbaf1SConrad Meyer const BYTE* const dictBase = ms->window.dictBase; 38519fcbaf1SConrad Meyer const U32 dictLimit = ms->window.dictLimit; 38619fcbaf1SConrad Meyer const BYTE* const dictEnd = dictBase + dictLimit; 38719fcbaf1SConrad Meyer const BYTE* const prefixStart = base + dictLimit; 38819fcbaf1SConrad Meyer const BYTE* match; 38919fcbaf1SConrad Meyer const U32 current = (U32)(ip-base); 39019fcbaf1SConrad Meyer const U32 btLow = btMask >= current ? 0 : current - btMask; 39119fcbaf1SConrad Meyer U32* smallerPtr = bt + 2*(current&btMask); 39219fcbaf1SConrad Meyer U32* largerPtr = smallerPtr + 1; 39319fcbaf1SConrad Meyer U32 dummy32; /* to be nullified at the end */ 39419fcbaf1SConrad Meyer U32 const windowLow = ms->window.lowLimit; 39519fcbaf1SConrad Meyer U32 matchEndIdx = current+8+1; 39619fcbaf1SConrad Meyer size_t bestLength = 8; 39719fcbaf1SConrad Meyer U32 nbCompares = 1U << cParams->searchLog; 39819fcbaf1SConrad Meyer #ifdef ZSTD_C_PREDICT 39919fcbaf1SConrad Meyer U32 predictedSmall = *(bt + 2*((current-1)&btMask) + 0); 40019fcbaf1SConrad Meyer U32 predictedLarge = *(bt + 2*((current-1)&btMask) + 1); 40119fcbaf1SConrad Meyer predictedSmall += (predictedSmall>0); 40219fcbaf1SConrad Meyer predictedLarge += (predictedLarge>0); 40319fcbaf1SConrad Meyer #endif /* ZSTD_C_PREDICT */ 40419fcbaf1SConrad Meyer 40519fcbaf1SConrad Meyer DEBUGLOG(8, "ZSTD_insertBt1 (%u)", current); 40619fcbaf1SConrad Meyer 40719fcbaf1SConrad Meyer assert(ip <= iend-8); /* required for h calculation */ 40819fcbaf1SConrad Meyer hashTable[h] = current; /* Update Hash Table */ 40919fcbaf1SConrad Meyer 410a0483764SConrad Meyer assert(windowLow > 0); 411a0483764SConrad Meyer while (nbCompares-- && (matchIndex >= windowLow)) { 41219fcbaf1SConrad Meyer U32* const nextPtr = bt + 2*(matchIndex & btMask); 41319fcbaf1SConrad Meyer size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */ 41419fcbaf1SConrad Meyer assert(matchIndex < current); 41519fcbaf1SConrad Meyer 41619fcbaf1SConrad Meyer #ifdef ZSTD_C_PREDICT /* note : can create issues when hlog small <= 11 */ 41719fcbaf1SConrad Meyer const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */ 41819fcbaf1SConrad Meyer if (matchIndex == predictedSmall) { 41919fcbaf1SConrad Meyer /* no need to check length, result known */ 42019fcbaf1SConrad Meyer *smallerPtr = matchIndex; 42119fcbaf1SConrad Meyer if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */ 42219fcbaf1SConrad Meyer smallerPtr = nextPtr+1; /* new "smaller" => larger of match */ 42319fcbaf1SConrad Meyer matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */ 42419fcbaf1SConrad Meyer predictedSmall = predictPtr[1] + (predictPtr[1]>0); 42519fcbaf1SConrad Meyer continue; 42619fcbaf1SConrad Meyer } 42719fcbaf1SConrad Meyer if (matchIndex == predictedLarge) { 42819fcbaf1SConrad Meyer *largerPtr = matchIndex; 42919fcbaf1SConrad Meyer if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */ 43019fcbaf1SConrad Meyer largerPtr = nextPtr; 43119fcbaf1SConrad Meyer matchIndex = nextPtr[0]; 43219fcbaf1SConrad Meyer predictedLarge = predictPtr[0] + (predictPtr[0]>0); 43319fcbaf1SConrad Meyer continue; 43419fcbaf1SConrad Meyer } 43519fcbaf1SConrad Meyer #endif 43619fcbaf1SConrad Meyer 4370f743729SConrad Meyer if (!extDict || (matchIndex+matchLength >= dictLimit)) { 4380f743729SConrad Meyer assert(matchIndex+matchLength >= dictLimit); /* might be wrong if actually extDict */ 43919fcbaf1SConrad Meyer match = base + matchIndex; 44019fcbaf1SConrad Meyer matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend); 44119fcbaf1SConrad Meyer } else { 44219fcbaf1SConrad Meyer match = dictBase + matchIndex; 44319fcbaf1SConrad Meyer matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart); 44419fcbaf1SConrad Meyer if (matchIndex+matchLength >= dictLimit) 44519fcbaf1SConrad Meyer match = base + matchIndex; /* to prepare for next usage of match[matchLength] */ 44619fcbaf1SConrad Meyer } 44719fcbaf1SConrad Meyer 44819fcbaf1SConrad Meyer if (matchLength > bestLength) { 44919fcbaf1SConrad Meyer bestLength = matchLength; 45019fcbaf1SConrad Meyer if (matchLength > matchEndIdx - matchIndex) 45119fcbaf1SConrad Meyer matchEndIdx = matchIndex + (U32)matchLength; 45219fcbaf1SConrad Meyer } 45319fcbaf1SConrad Meyer 45419fcbaf1SConrad Meyer if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */ 45519fcbaf1SConrad Meyer break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */ 45619fcbaf1SConrad Meyer } 45719fcbaf1SConrad Meyer 45819fcbaf1SConrad Meyer if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */ 45919fcbaf1SConrad Meyer /* match is smaller than current */ 46019fcbaf1SConrad Meyer *smallerPtr = matchIndex; /* update smaller idx */ 46119fcbaf1SConrad Meyer commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */ 46219fcbaf1SConrad Meyer if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */ 46319fcbaf1SConrad Meyer smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */ 46419fcbaf1SConrad Meyer matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */ 46519fcbaf1SConrad Meyer } else { 46619fcbaf1SConrad Meyer /* match is larger than current */ 46719fcbaf1SConrad Meyer *largerPtr = matchIndex; 46819fcbaf1SConrad Meyer commonLengthLarger = matchLength; 46919fcbaf1SConrad Meyer if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */ 47019fcbaf1SConrad Meyer largerPtr = nextPtr; 47119fcbaf1SConrad Meyer matchIndex = nextPtr[0]; 47219fcbaf1SConrad Meyer } } 47319fcbaf1SConrad Meyer 47419fcbaf1SConrad Meyer *smallerPtr = *largerPtr = 0; 4754d3f1eafSConrad Meyer { U32 positions = 0; 4764d3f1eafSConrad Meyer if (bestLength > 384) positions = MIN(192, (U32)(bestLength - 384)); /* speed optimization */ 47719fcbaf1SConrad Meyer assert(matchEndIdx > current + 8); 4784d3f1eafSConrad Meyer return MAX(positions, matchEndIdx - (current + 8)); 4794d3f1eafSConrad Meyer } 48019fcbaf1SConrad Meyer } 48119fcbaf1SConrad Meyer 48219fcbaf1SConrad Meyer FORCE_INLINE_TEMPLATE 48319fcbaf1SConrad Meyer void ZSTD_updateTree_internal( 4840f743729SConrad Meyer ZSTD_matchState_t* ms, 48519fcbaf1SConrad Meyer const BYTE* const ip, const BYTE* const iend, 4860f743729SConrad Meyer const U32 mls, const ZSTD_dictMode_e dictMode) 48719fcbaf1SConrad Meyer { 48819fcbaf1SConrad Meyer const BYTE* const base = ms->window.base; 48919fcbaf1SConrad Meyer U32 const target = (U32)(ip - base); 49019fcbaf1SConrad Meyer U32 idx = ms->nextToUpdate; 491a0483764SConrad Meyer DEBUGLOG(6, "ZSTD_updateTree_internal, from %u to %u (dictMode:%u)", 4920f743729SConrad Meyer idx, target, dictMode); 49319fcbaf1SConrad Meyer 4944d3f1eafSConrad Meyer while(idx < target) { 4954d3f1eafSConrad Meyer U32 const forward = ZSTD_insertBt1(ms, base+idx, iend, mls, dictMode == ZSTD_extDict); 4964d3f1eafSConrad Meyer assert(idx < (U32)(idx + forward)); 4974d3f1eafSConrad Meyer idx += forward; 4984d3f1eafSConrad Meyer } 4994d3f1eafSConrad Meyer assert((size_t)(ip - base) <= (size_t)(U32)(-1)); 5004d3f1eafSConrad Meyer assert((size_t)(iend - base) <= (size_t)(U32)(-1)); 50119fcbaf1SConrad Meyer ms->nextToUpdate = target; 50219fcbaf1SConrad Meyer } 50319fcbaf1SConrad Meyer 5040f743729SConrad Meyer void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) { 505a0483764SConrad Meyer ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict); 50619fcbaf1SConrad Meyer } 50719fcbaf1SConrad Meyer 508052d3c12SConrad Meyer FORCE_INLINE_TEMPLATE 509052d3c12SConrad Meyer U32 ZSTD_insertBtAndGetAllMatches ( 5104d3f1eafSConrad Meyer ZSTD_match_t* matches, /* store result (found matches) in this table (presumed large enough) */ 5110f743729SConrad Meyer ZSTD_matchState_t* ms, 5124d3f1eafSConrad Meyer U32* nextToUpdate3, 5130f743729SConrad Meyer const BYTE* const ip, const BYTE* const iLimit, const ZSTD_dictMode_e dictMode, 5144d3f1eafSConrad Meyer const U32 rep[ZSTD_REP_NUM], 515a0483764SConrad Meyer U32 const ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */ 516a0483764SConrad Meyer const U32 lengthToBeat, 517a0483764SConrad Meyer U32 const mls /* template */) 5180c16b537SWarner Losh { 5190f743729SConrad Meyer const ZSTD_compressionParameters* const cParams = &ms->cParams; 52019fcbaf1SConrad Meyer U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1); 52119fcbaf1SConrad Meyer const BYTE* const base = ms->window.base; 522052d3c12SConrad Meyer U32 const current = (U32)(ip-base); 52319fcbaf1SConrad Meyer U32 const hashLog = cParams->hashLog; 524052d3c12SConrad Meyer U32 const minMatch = (mls==3) ? 3 : 4; 52519fcbaf1SConrad Meyer U32* const hashTable = ms->hashTable; 526052d3c12SConrad Meyer size_t const h = ZSTD_hashPtr(ip, hashLog, mls); 5270c16b537SWarner Losh U32 matchIndex = hashTable[h]; 52819fcbaf1SConrad Meyer U32* const bt = ms->chainTable; 52919fcbaf1SConrad Meyer U32 const btLog = cParams->chainLog - 1; 530052d3c12SConrad Meyer U32 const btMask= (1U << btLog) - 1; 5310c16b537SWarner Losh size_t commonLengthSmaller=0, commonLengthLarger=0; 53219fcbaf1SConrad Meyer const BYTE* const dictBase = ms->window.dictBase; 53319fcbaf1SConrad Meyer U32 const dictLimit = ms->window.dictLimit; 5340c16b537SWarner Losh const BYTE* const dictEnd = dictBase + dictLimit; 5350c16b537SWarner Losh const BYTE* const prefixStart = base + dictLimit; 5364d3f1eafSConrad Meyer U32 const btLow = (btMask >= current) ? 0 : current - btMask; 5379cbefe25SConrad Meyer U32 const windowLow = ZSTD_getLowestMatchIndex(ms, current, cParams->windowLog); 5380f743729SConrad Meyer U32 const matchLow = windowLow ? windowLow : 1; 5390c16b537SWarner Losh U32* smallerPtr = bt + 2*(current&btMask); 5400c16b537SWarner Losh U32* largerPtr = bt + 2*(current&btMask) + 1; 541052d3c12SConrad Meyer U32 matchEndIdx = current+8+1; /* farthest referenced position of any match => detects repetitive patterns */ 5420c16b537SWarner Losh U32 dummy32; /* to be nullified at the end */ 5430c16b537SWarner Losh U32 mnum = 0; 54419fcbaf1SConrad Meyer U32 nbCompares = 1U << cParams->searchLog; 5450c16b537SWarner Losh 5460f743729SConrad Meyer const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL; 5470f743729SConrad Meyer const ZSTD_compressionParameters* const dmsCParams = 5480f743729SConrad Meyer dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL; 5490f743729SConrad Meyer const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL; 5500f743729SConrad Meyer const BYTE* const dmsEnd = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL; 5510f743729SConrad Meyer U32 const dmsHighLimit = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0; 5520f743729SConrad Meyer U32 const dmsLowLimit = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0; 5530f743729SConrad Meyer U32 const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0; 5540f743729SConrad Meyer U32 const dmsHashLog = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog; 5550f743729SConrad Meyer U32 const dmsBtLog = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog; 5560f743729SConrad Meyer U32 const dmsBtMask = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0; 5570f743729SConrad Meyer U32 const dmsBtLow = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit; 5580f743729SConrad Meyer 559052d3c12SConrad Meyer size_t bestLength = lengthToBeat-1; 5600f743729SConrad Meyer DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", current); 5610c16b537SWarner Losh 562052d3c12SConrad Meyer /* check repCode */ 563a0483764SConrad Meyer assert(ll0 <= 1); /* necessarily 1 or 0 */ 564052d3c12SConrad Meyer { U32 const lastR = ZSTD_REP_NUM + ll0; 565052d3c12SConrad Meyer U32 repCode; 566052d3c12SConrad Meyer for (repCode = ll0; repCode < lastR; repCode++) { 567052d3c12SConrad Meyer U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode]; 568052d3c12SConrad Meyer U32 const repIndex = current - repOffset; 569052d3c12SConrad Meyer U32 repLen = 0; 570052d3c12SConrad Meyer assert(current >= dictLimit); 571052d3c12SConrad Meyer if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < current-dictLimit) { /* equivalent to `current > repIndex >= dictLimit` */ 572*37f1f268SConrad Meyer /* We must validate the repcode offset because when we're using a dictionary the 573*37f1f268SConrad Meyer * valid offset range shrinks when the dictionary goes out of bounds. 574*37f1f268SConrad Meyer */ 575*37f1f268SConrad Meyer if ((repIndex >= windowLow) & (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch))) { 576052d3c12SConrad Meyer repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch; 577052d3c12SConrad Meyer } 578052d3c12SConrad Meyer } else { /* repIndex < dictLimit || repIndex >= current */ 5790f743729SConrad Meyer const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ? 5800f743729SConrad Meyer dmsBase + repIndex - dmsIndexDelta : 5810f743729SConrad Meyer dictBase + repIndex; 582052d3c12SConrad Meyer assert(current >= windowLow); 5830f743729SConrad Meyer if ( dictMode == ZSTD_extDict 584052d3c12SConrad Meyer && ( ((repOffset-1) /*intentional overflow*/ < current - windowLow) /* equivalent to `current > repIndex >= windowLow` */ 585052d3c12SConrad Meyer & (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */) 586052d3c12SConrad Meyer && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) { 587052d3c12SConrad Meyer repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch; 5880f743729SConrad Meyer } 5890f743729SConrad Meyer if (dictMode == ZSTD_dictMatchState 5900f743729SConrad Meyer && ( ((repOffset-1) /*intentional overflow*/ < current - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `current > repIndex >= dmsLowLimit` */ 5910f743729SConrad Meyer & ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */ 5920f743729SConrad Meyer && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) { 5930f743729SConrad Meyer repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch; 594052d3c12SConrad Meyer } } 595052d3c12SConrad Meyer /* save longer solution */ 596052d3c12SConrad Meyer if (repLen > bestLength) { 5970f743729SConrad Meyer DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u", 5980f743729SConrad Meyer repCode, ll0, repOffset, repLen); 599052d3c12SConrad Meyer bestLength = repLen; 600052d3c12SConrad Meyer matches[mnum].off = repCode - ll0; 601052d3c12SConrad Meyer matches[mnum].len = (U32)repLen; 602052d3c12SConrad Meyer mnum++; 603052d3c12SConrad Meyer if ( (repLen > sufficient_len) 604052d3c12SConrad Meyer | (ip+repLen == iLimit) ) { /* best possible */ 605052d3c12SConrad Meyer return mnum; 606052d3c12SConrad Meyer } } } } 607052d3c12SConrad Meyer 608052d3c12SConrad Meyer /* HC3 match finder */ 609052d3c12SConrad Meyer if ((mls == 3) /*static*/ && (bestLength < mls)) { 6104d3f1eafSConrad Meyer U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, nextToUpdate3, ip); 6110f743729SConrad Meyer if ((matchIndex3 >= matchLow) 612052d3c12SConrad Meyer & (current - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) { 613052d3c12SConrad Meyer size_t mlen; 6140f743729SConrad Meyer if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) { 615052d3c12SConrad Meyer const BYTE* const match = base + matchIndex3; 616052d3c12SConrad Meyer mlen = ZSTD_count(ip, match, iLimit); 6170c16b537SWarner Losh } else { 618052d3c12SConrad Meyer const BYTE* const match = dictBase + matchIndex3; 619052d3c12SConrad Meyer mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart); 6200c16b537SWarner Losh } 6210c16b537SWarner Losh 6220c16b537SWarner Losh /* save best solution */ 623052d3c12SConrad Meyer if (mlen >= mls /* == 3 > bestLength */) { 624052d3c12SConrad Meyer DEBUGLOG(8, "found small match with hlog3, of length %u", 625052d3c12SConrad Meyer (U32)mlen); 626052d3c12SConrad Meyer bestLength = mlen; 627052d3c12SConrad Meyer assert(current > matchIndex3); 628052d3c12SConrad Meyer assert(mnum==0); /* no prior solution */ 629052d3c12SConrad Meyer matches[0].off = (current - matchIndex3) + ZSTD_REP_MOVE; 630052d3c12SConrad Meyer matches[0].len = (U32)mlen; 631052d3c12SConrad Meyer mnum = 1; 632052d3c12SConrad Meyer if ( (mlen > sufficient_len) | 633052d3c12SConrad Meyer (ip+mlen == iLimit) ) { /* best possible length */ 63419fcbaf1SConrad Meyer ms->nextToUpdate = current+1; /* skip insertion */ 635052d3c12SConrad Meyer return 1; 6364d3f1eafSConrad Meyer } } } 6370f743729SConrad Meyer /* no dictMatchState lookup: dicts don't have a populated HC3 table */ 6380f743729SConrad Meyer } 6390c16b537SWarner Losh 6400c16b537SWarner Losh hashTable[h] = current; /* Update Hash Table */ 6410c16b537SWarner Losh 6420f743729SConrad Meyer while (nbCompares-- && (matchIndex >= matchLow)) { 643052d3c12SConrad Meyer U32* const nextPtr = bt + 2*(matchIndex & btMask); 6440c16b537SWarner Losh const BYTE* match; 6459cbefe25SConrad Meyer size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */ 646052d3c12SConrad Meyer assert(current > matchIndex); 6470c16b537SWarner Losh 6480f743729SConrad Meyer if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) { 649052d3c12SConrad Meyer assert(matchIndex+matchLength >= dictLimit); /* ensure the condition is correct when !extDict */ 6500c16b537SWarner Losh match = base + matchIndex; 6519cbefe25SConrad Meyer if (matchIndex >= dictLimit) assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */ 652052d3c12SConrad Meyer matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit); 6530c16b537SWarner Losh } else { 6540c16b537SWarner Losh match = dictBase + matchIndex; 6559cbefe25SConrad Meyer assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */ 6560c16b537SWarner Losh matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart); 6570c16b537SWarner Losh if (matchIndex+matchLength >= dictLimit) 6589cbefe25SConrad Meyer match = base + matchIndex; /* prepare for match[matchLength] read */ 6590c16b537SWarner Losh } 6600c16b537SWarner Losh 6610c16b537SWarner Losh if (matchLength > bestLength) { 6620f743729SConrad Meyer DEBUGLOG(8, "found match of length %u at distance %u (offCode=%u)", 6630f743729SConrad Meyer (U32)matchLength, current - matchIndex, current - matchIndex + ZSTD_REP_MOVE); 664052d3c12SConrad Meyer assert(matchEndIdx > matchIndex); 665052d3c12SConrad Meyer if (matchLength > matchEndIdx - matchIndex) 666052d3c12SConrad Meyer matchEndIdx = matchIndex + (U32)matchLength; 6670c16b537SWarner Losh bestLength = matchLength; 668052d3c12SConrad Meyer matches[mnum].off = (current - matchIndex) + ZSTD_REP_MOVE; 6690c16b537SWarner Losh matches[mnum].len = (U32)matchLength; 6700c16b537SWarner Losh mnum++; 6710f743729SConrad Meyer if ( (matchLength > ZSTD_OPT_NUM) 6720f743729SConrad Meyer | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) { 6730f743729SConrad Meyer if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */ 674052d3c12SConrad Meyer break; /* drop, to preserve bt consistency (miss a little bit of compression) */ 675052d3c12SConrad Meyer } 6760c16b537SWarner Losh } 6770c16b537SWarner Losh 6780c16b537SWarner Losh if (match[matchLength] < ip[matchLength]) { 679052d3c12SConrad Meyer /* match smaller than current */ 6800c16b537SWarner Losh *smallerPtr = matchIndex; /* update smaller idx */ 6810c16b537SWarner Losh commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */ 6820c16b537SWarner Losh if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */ 683052d3c12SConrad Meyer smallerPtr = nextPtr+1; /* new candidate => larger than match, which was smaller than current */ 684052d3c12SConrad Meyer matchIndex = nextPtr[1]; /* new matchIndex, larger than previous, closer to current */ 6850c16b537SWarner Losh } else { 6860c16b537SWarner Losh *largerPtr = matchIndex; 6870c16b537SWarner Losh commonLengthLarger = matchLength; 6880c16b537SWarner Losh if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */ 6890c16b537SWarner Losh largerPtr = nextPtr; 6900c16b537SWarner Losh matchIndex = nextPtr[0]; 6910c16b537SWarner Losh } } 6920c16b537SWarner Losh 6930c16b537SWarner Losh *smallerPtr = *largerPtr = 0; 6940c16b537SWarner Losh 6950f743729SConrad Meyer if (dictMode == ZSTD_dictMatchState && nbCompares) { 6960f743729SConrad Meyer size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls); 6970f743729SConrad Meyer U32 dictMatchIndex = dms->hashTable[dmsH]; 6980f743729SConrad Meyer const U32* const dmsBt = dms->chainTable; 6990f743729SConrad Meyer commonLengthSmaller = commonLengthLarger = 0; 7000f743729SConrad Meyer while (nbCompares-- && (dictMatchIndex > dmsLowLimit)) { 7010f743729SConrad Meyer const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask); 7020f743729SConrad Meyer size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */ 7030f743729SConrad Meyer const BYTE* match = dmsBase + dictMatchIndex; 7040f743729SConrad Meyer matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart); 7050f743729SConrad Meyer if (dictMatchIndex+matchLength >= dmsHighLimit) 7060f743729SConrad Meyer match = base + dictMatchIndex + dmsIndexDelta; /* to prepare for next usage of match[matchLength] */ 7070f743729SConrad Meyer 7080f743729SConrad Meyer if (matchLength > bestLength) { 7090f743729SConrad Meyer matchIndex = dictMatchIndex + dmsIndexDelta; 7100f743729SConrad Meyer DEBUGLOG(8, "found dms match of length %u at distance %u (offCode=%u)", 7110f743729SConrad Meyer (U32)matchLength, current - matchIndex, current - matchIndex + ZSTD_REP_MOVE); 7120f743729SConrad Meyer if (matchLength > matchEndIdx - matchIndex) 7130f743729SConrad Meyer matchEndIdx = matchIndex + (U32)matchLength; 7140f743729SConrad Meyer bestLength = matchLength; 7150f743729SConrad Meyer matches[mnum].off = (current - matchIndex) + ZSTD_REP_MOVE; 7160f743729SConrad Meyer matches[mnum].len = (U32)matchLength; 7170f743729SConrad Meyer mnum++; 7180f743729SConrad Meyer if ( (matchLength > ZSTD_OPT_NUM) 7190f743729SConrad Meyer | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) { 7200f743729SConrad Meyer break; /* drop, to guarantee consistency (miss a little bit of compression) */ 7210f743729SConrad Meyer } 7220f743729SConrad Meyer } 7230f743729SConrad Meyer 7240f743729SConrad Meyer if (dictMatchIndex <= dmsBtLow) { break; } /* beyond tree size, stop the search */ 7250f743729SConrad Meyer if (match[matchLength] < ip[matchLength]) { 7260f743729SConrad Meyer commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */ 7270f743729SConrad Meyer dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */ 7280f743729SConrad Meyer } else { 7290f743729SConrad Meyer /* match is larger than current */ 7300f743729SConrad Meyer commonLengthLarger = matchLength; 7310f743729SConrad Meyer dictMatchIndex = nextPtr[0]; 7320f743729SConrad Meyer } 7330f743729SConrad Meyer } 7340f743729SConrad Meyer } 7350f743729SConrad Meyer 736052d3c12SConrad Meyer assert(matchEndIdx > current+8); 73719fcbaf1SConrad Meyer ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */ 7380c16b537SWarner Losh return mnum; 7390c16b537SWarner Losh } 7400c16b537SWarner Losh 7410c16b537SWarner Losh 742052d3c12SConrad Meyer FORCE_INLINE_TEMPLATE U32 ZSTD_BtGetAllMatches ( 7434d3f1eafSConrad Meyer ZSTD_match_t* matches, /* store result (match found, increasing size) in this table */ 7440f743729SConrad Meyer ZSTD_matchState_t* ms, 7454d3f1eafSConrad Meyer U32* nextToUpdate3, 7460f743729SConrad Meyer const BYTE* ip, const BYTE* const iHighLimit, const ZSTD_dictMode_e dictMode, 7474d3f1eafSConrad Meyer const U32 rep[ZSTD_REP_NUM], 7484d3f1eafSConrad Meyer U32 const ll0, 7494d3f1eafSConrad Meyer U32 const lengthToBeat) 7500c16b537SWarner Losh { 7510f743729SConrad Meyer const ZSTD_compressionParameters* const cParams = &ms->cParams; 752a0483764SConrad Meyer U32 const matchLengthSearch = cParams->minMatch; 7530f743729SConrad Meyer DEBUGLOG(8, "ZSTD_BtGetAllMatches"); 75419fcbaf1SConrad Meyer if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */ 7550f743729SConrad Meyer ZSTD_updateTree_internal(ms, ip, iHighLimit, matchLengthSearch, dictMode); 7560c16b537SWarner Losh switch(matchLengthSearch) 7570c16b537SWarner Losh { 7584d3f1eafSConrad Meyer case 3 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 3); 7590c16b537SWarner Losh default : 7604d3f1eafSConrad Meyer case 4 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 4); 7614d3f1eafSConrad Meyer case 5 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 5); 7620c16b537SWarner Losh case 7 : 7634d3f1eafSConrad Meyer case 6 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 6); 7640c16b537SWarner Losh } 7650c16b537SWarner Losh } 7660c16b537SWarner Losh 7670c16b537SWarner Losh 7680c16b537SWarner Losh /*-******************************* 7690c16b537SWarner Losh * Optimal parser 7700c16b537SWarner Losh *********************************/ 771052d3c12SConrad Meyer 772052d3c12SConrad Meyer 7730f743729SConrad Meyer static U32 ZSTD_totalLen(ZSTD_optimal_t sol) 774052d3c12SConrad Meyer { 7750f743729SConrad Meyer return sol.litlen + sol.mlen; 776052d3c12SConrad Meyer } 777052d3c12SConrad Meyer 778a0483764SConrad Meyer #if 0 /* debug */ 779a0483764SConrad Meyer 780a0483764SConrad Meyer static void 781a0483764SConrad Meyer listStats(const U32* table, int lastEltID) 782a0483764SConrad Meyer { 783a0483764SConrad Meyer int const nbElts = lastEltID + 1; 784a0483764SConrad Meyer int enb; 785a0483764SConrad Meyer for (enb=0; enb < nbElts; enb++) { 786a0483764SConrad Meyer (void)table; 787*37f1f268SConrad Meyer /* RAWLOG(2, "%3i:%3i, ", enb, table[enb]); */ 788a0483764SConrad Meyer RAWLOG(2, "%4i,", table[enb]); 789a0483764SConrad Meyer } 790a0483764SConrad Meyer RAWLOG(2, " \n"); 791a0483764SConrad Meyer } 792a0483764SConrad Meyer 793a0483764SConrad Meyer #endif 794a0483764SConrad Meyer 7950f743729SConrad Meyer FORCE_INLINE_TEMPLATE size_t 7960f743729SConrad Meyer ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms, 7970f743729SConrad Meyer seqStore_t* seqStore, 79819fcbaf1SConrad Meyer U32 rep[ZSTD_REP_NUM], 799052d3c12SConrad Meyer const void* src, size_t srcSize, 800a0483764SConrad Meyer const int optLevel, 801a0483764SConrad Meyer const ZSTD_dictMode_e dictMode) 8020c16b537SWarner Losh { 80319fcbaf1SConrad Meyer optState_t* const optStatePtr = &ms->opt; 8040c16b537SWarner Losh const BYTE* const istart = (const BYTE*)src; 8050c16b537SWarner Losh const BYTE* ip = istart; 8060c16b537SWarner Losh const BYTE* anchor = istart; 8070c16b537SWarner Losh const BYTE* const iend = istart + srcSize; 8080c16b537SWarner Losh const BYTE* const ilimit = iend - 8; 80919fcbaf1SConrad Meyer const BYTE* const base = ms->window.base; 81019fcbaf1SConrad Meyer const BYTE* const prefixStart = base + ms->window.dictLimit; 8110f743729SConrad Meyer const ZSTD_compressionParameters* const cParams = &ms->cParams; 8120c16b537SWarner Losh 81319fcbaf1SConrad Meyer U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1); 814a0483764SConrad Meyer U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4; 8154d3f1eafSConrad Meyer U32 nextToUpdate3 = ms->nextToUpdate; 8160c16b537SWarner Losh 817052d3c12SConrad Meyer ZSTD_optimal_t* const opt = optStatePtr->priceTable; 818052d3c12SConrad Meyer ZSTD_match_t* const matches = optStatePtr->matchTable; 8190f743729SConrad Meyer ZSTD_optimal_t lastSequence; 8200c16b537SWarner Losh 8210c16b537SWarner Losh /* init */ 822a0483764SConrad Meyer DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u", 823a0483764SConrad Meyer (U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate); 8240f743729SConrad Meyer assert(optLevel <= 2); 8250f743729SConrad Meyer ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel); 8260c16b537SWarner Losh ip += (ip==prefixStart); 8270c16b537SWarner Losh 8280c16b537SWarner Losh /* Match Loop */ 8290c16b537SWarner Losh while (ip < ilimit) { 830052d3c12SConrad Meyer U32 cur, last_pos = 0; 8310c16b537SWarner Losh 832052d3c12SConrad Meyer /* find first match */ 833052d3c12SConrad Meyer { U32 const litlen = (U32)(ip - anchor); 834052d3c12SConrad Meyer U32 const ll0 = !litlen; 8354d3f1eafSConrad Meyer U32 const nbMatches = ZSTD_BtGetAllMatches(matches, ms, &nextToUpdate3, ip, iend, dictMode, rep, ll0, minMatch); 836052d3c12SConrad Meyer if (!nbMatches) { ip++; continue; } 8370c16b537SWarner Losh 8380c16b537SWarner Losh /* initialize opt[0] */ 8390c16b537SWarner Losh { U32 i ; for (i=0; i<ZSTD_REP_NUM; i++) opt[0].rep[i] = rep[i]; } 8400f743729SConrad Meyer opt[0].mlen = 0; /* means is_a_literal */ 8410c16b537SWarner Losh opt[0].litlen = litlen; 842*37f1f268SConrad Meyer /* We don't need to include the actual price of the literals because 843*37f1f268SConrad Meyer * it is static for the duration of the forward pass, and is included 844*37f1f268SConrad Meyer * in every price. We include the literal length to avoid negative 845*37f1f268SConrad Meyer * prices when we subtract the previous literal length. 846*37f1f268SConrad Meyer */ 847*37f1f268SConrad Meyer opt[0].price = ZSTD_litLengthPrice(litlen, optStatePtr, optLevel); 8480c16b537SWarner Losh 849052d3c12SConrad Meyer /* large match -> immediate encoding */ 850052d3c12SConrad Meyer { U32 const maxML = matches[nbMatches-1].len; 8510f743729SConrad Meyer U32 const maxOffset = matches[nbMatches-1].off; 8522b9c00cbSConrad Meyer DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffCode=%u at cPos=%u => start new series", 8530f743729SConrad Meyer nbMatches, maxML, maxOffset, (U32)(ip-prefixStart)); 8540c16b537SWarner Losh 855052d3c12SConrad Meyer if (maxML > sufficient_len) { 8560f743729SConrad Meyer lastSequence.litlen = litlen; 8570f743729SConrad Meyer lastSequence.mlen = maxML; 8580f743729SConrad Meyer lastSequence.off = maxOffset; 8590f743729SConrad Meyer DEBUGLOG(6, "large match (%u>%u), immediate encoding", 8600f743729SConrad Meyer maxML, sufficient_len); 861052d3c12SConrad Meyer cur = 0; 8620f743729SConrad Meyer last_pos = ZSTD_totalLen(lastSequence); 863052d3c12SConrad Meyer goto _shortestPath; 864052d3c12SConrad Meyer } } 865052d3c12SConrad Meyer 866052d3c12SConrad Meyer /* set prices for first matches starting position == 0 */ 8670f743729SConrad Meyer { U32 const literalsPrice = opt[0].price + ZSTD_litLengthPrice(0, optStatePtr, optLevel); 868052d3c12SConrad Meyer U32 pos; 869052d3c12SConrad Meyer U32 matchNb; 8700f743729SConrad Meyer for (pos = 1; pos < minMatch; pos++) { 8710f743729SConrad Meyer opt[pos].price = ZSTD_MAX_PRICE; /* mlen, litlen and price will be fixed during forward scanning */ 872052d3c12SConrad Meyer } 873052d3c12SConrad Meyer for (matchNb = 0; matchNb < nbMatches; matchNb++) { 874052d3c12SConrad Meyer U32 const offset = matches[matchNb].off; 875052d3c12SConrad Meyer U32 const end = matches[matchNb].len; 876052d3c12SConrad Meyer for ( ; pos <= end ; pos++ ) { 8770f743729SConrad Meyer U32 const matchPrice = ZSTD_getMatchPrice(offset, pos, optStatePtr, optLevel); 8780f743729SConrad Meyer U32 const sequencePrice = literalsPrice + matchPrice; 8790f743729SConrad Meyer DEBUGLOG(7, "rPos:%u => set initial price : %.2f", 8800f743729SConrad Meyer pos, ZSTD_fCost(sequencePrice)); 881052d3c12SConrad Meyer opt[pos].mlen = pos; 882052d3c12SConrad Meyer opt[pos].off = offset; 883052d3c12SConrad Meyer opt[pos].litlen = litlen; 8840f743729SConrad Meyer opt[pos].price = sequencePrice; 885052d3c12SConrad Meyer } } 886052d3c12SConrad Meyer last_pos = pos-1; 887052d3c12SConrad Meyer } 8880c16b537SWarner Losh } 8890c16b537SWarner Losh 890052d3c12SConrad Meyer /* check further positions */ 891052d3c12SConrad Meyer for (cur = 1; cur <= last_pos; cur++) { 892052d3c12SConrad Meyer const BYTE* const inr = ip + cur; 893052d3c12SConrad Meyer assert(cur < ZSTD_OPT_NUM); 8940f743729SConrad Meyer DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur) 895052d3c12SConrad Meyer 896052d3c12SConrad Meyer /* Fix current position with one literal if cheaper */ 8970f743729SConrad Meyer { U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1; 8980f743729SConrad Meyer int const price = opt[cur-1].price 8990f743729SConrad Meyer + ZSTD_rawLiteralsCost(ip+cur-1, 1, optStatePtr, optLevel) 9000f743729SConrad Meyer + ZSTD_litLengthPrice(litlen, optStatePtr, optLevel) 9010f743729SConrad Meyer - ZSTD_litLengthPrice(litlen-1, optStatePtr, optLevel); 902052d3c12SConrad Meyer assert(price < 1000000000); /* overflow check */ 903052d3c12SConrad Meyer if (price <= opt[cur].price) { 9040f743729SConrad Meyer DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)", 9050f743729SConrad Meyer inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen, 9060f743729SConrad Meyer opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]); 9070f743729SConrad Meyer opt[cur].mlen = 0; 908052d3c12SConrad Meyer opt[cur].off = 0; 909052d3c12SConrad Meyer opt[cur].litlen = litlen; 910052d3c12SConrad Meyer opt[cur].price = price; 9110f743729SConrad Meyer } else { 9120f743729SConrad Meyer DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)", 9130f743729SConrad Meyer inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), 9140f743729SConrad Meyer opt[cur].rep[0], opt[cur].rep[1], opt[cur].rep[2]); 9150f743729SConrad Meyer } 9160f743729SConrad Meyer } 917052d3c12SConrad Meyer 918*37f1f268SConrad Meyer /* Set the repcodes of the current position. We must do it here 919*37f1f268SConrad Meyer * because we rely on the repcodes of the 2nd to last sequence being 920*37f1f268SConrad Meyer * correct to set the next chunks repcodes during the backward 921*37f1f268SConrad Meyer * traversal. 922*37f1f268SConrad Meyer */ 923*37f1f268SConrad Meyer ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t)); 924*37f1f268SConrad Meyer assert(cur >= opt[cur].mlen); 925*37f1f268SConrad Meyer if (opt[cur].mlen != 0) { 926*37f1f268SConrad Meyer U32 const prev = cur - opt[cur].mlen; 927*37f1f268SConrad Meyer repcodes_t newReps = ZSTD_updateRep(opt[prev].rep, opt[cur].off, opt[cur].litlen==0); 928*37f1f268SConrad Meyer memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t)); 929*37f1f268SConrad Meyer } else { 930*37f1f268SConrad Meyer memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t)); 931*37f1f268SConrad Meyer } 932*37f1f268SConrad Meyer 933052d3c12SConrad Meyer /* last match must start at a minimum distance of 8 from oend */ 934052d3c12SConrad Meyer if (inr > ilimit) continue; 9350c16b537SWarner Losh 9360c16b537SWarner Losh if (cur == last_pos) break; 9370c16b537SWarner Losh 9380f743729SConrad Meyer if ( (optLevel==0) /*static_test*/ 9390f743729SConrad Meyer && (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) { 9400f743729SConrad Meyer DEBUGLOG(7, "move to next rPos:%u : price is <=", cur+1); 941052d3c12SConrad Meyer continue; /* skip unpromising positions; about ~+6% speed, -0.01 ratio */ 9420f743729SConrad Meyer } 9430c16b537SWarner Losh 9440f743729SConrad Meyer { U32 const ll0 = (opt[cur].mlen != 0); 9450f743729SConrad Meyer U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0; 9460f743729SConrad Meyer U32 const previousPrice = opt[cur].price; 9470f743729SConrad Meyer U32 const basePrice = previousPrice + ZSTD_litLengthPrice(0, optStatePtr, optLevel); 9484d3f1eafSConrad Meyer U32 const nbMatches = ZSTD_BtGetAllMatches(matches, ms, &nextToUpdate3, inr, iend, dictMode, opt[cur].rep, ll0, minMatch); 949052d3c12SConrad Meyer U32 matchNb; 9500f743729SConrad Meyer if (!nbMatches) { 9510f743729SConrad Meyer DEBUGLOG(7, "rPos:%u : no match found", cur); 9520f743729SConrad Meyer continue; 9530f743729SConrad Meyer } 9540c16b537SWarner Losh 955052d3c12SConrad Meyer { U32 const maxML = matches[nbMatches-1].len; 9560f743729SConrad Meyer DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of maxLength=%u", 9570f743729SConrad Meyer inr-istart, cur, nbMatches, maxML); 9580c16b537SWarner Losh 959052d3c12SConrad Meyer if ( (maxML > sufficient_len) 9600f743729SConrad Meyer || (cur + maxML >= ZSTD_OPT_NUM) ) { 9610f743729SConrad Meyer lastSequence.mlen = maxML; 9620f743729SConrad Meyer lastSequence.off = matches[nbMatches-1].off; 9630f743729SConrad Meyer lastSequence.litlen = litlen; 9640f743729SConrad Meyer cur -= (opt[cur].mlen==0) ? opt[cur].litlen : 0; /* last sequence is actually only literals, fix cur to last match - note : may underflow, in which case, it's first sequence, and it's okay */ 9650f743729SConrad Meyer last_pos = cur + ZSTD_totalLen(lastSequence); 9660f743729SConrad Meyer if (cur > ZSTD_OPT_NUM) cur = 0; /* underflow => first match */ 967052d3c12SConrad Meyer goto _shortestPath; 9680f743729SConrad Meyer } } 9690c16b537SWarner Losh 970052d3c12SConrad Meyer /* set prices using matches found at position == cur */ 971052d3c12SConrad Meyer for (matchNb = 0; matchNb < nbMatches; matchNb++) { 972052d3c12SConrad Meyer U32 const offset = matches[matchNb].off; 973052d3c12SConrad Meyer U32 const lastML = matches[matchNb].len; 974052d3c12SConrad Meyer U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch; 975052d3c12SConrad Meyer U32 mlen; 9760c16b537SWarner Losh 9770f743729SConrad Meyer DEBUGLOG(7, "testing match %u => offCode=%4u, mlen=%2u, llen=%2u", 978052d3c12SConrad Meyer matchNb, matches[matchNb].off, lastML, litlen); 979052d3c12SConrad Meyer 9800f743729SConrad Meyer for (mlen = lastML; mlen >= startML; mlen--) { /* scan downward */ 981052d3c12SConrad Meyer U32 const pos = cur + mlen; 982052d3c12SConrad Meyer int const price = basePrice + ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel); 983052d3c12SConrad Meyer 984052d3c12SConrad Meyer if ((pos > last_pos) || (price < opt[pos].price)) { 9850f743729SConrad Meyer DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)", 9860f743729SConrad Meyer pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price)); 9870f743729SConrad Meyer while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; } /* fill empty positions */ 988052d3c12SConrad Meyer opt[pos].mlen = mlen; 989052d3c12SConrad Meyer opt[pos].off = offset; 990052d3c12SConrad Meyer opt[pos].litlen = litlen; 991052d3c12SConrad Meyer opt[pos].price = price; 9920c16b537SWarner Losh } else { 9930f743729SConrad Meyer DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)", 9940f743729SConrad Meyer pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price)); 9950f743729SConrad Meyer if (optLevel==0) break; /* early update abort; gets ~+10% speed for about -0.01 ratio loss */ 9960c16b537SWarner Losh } 9970c16b537SWarner Losh } } } 998052d3c12SConrad Meyer } /* for (cur = 1; cur <= last_pos; cur++) */ 9990c16b537SWarner Losh 10000f743729SConrad Meyer lastSequence = opt[last_pos]; 10010f743729SConrad Meyer cur = last_pos > ZSTD_totalLen(lastSequence) ? last_pos - ZSTD_totalLen(lastSequence) : 0; /* single sequence, and it starts before `ip` */ 10020f743729SConrad Meyer assert(cur < ZSTD_OPT_NUM); /* control overflow*/ 10030c16b537SWarner Losh 1004052d3c12SConrad Meyer _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ 10050f743729SConrad Meyer assert(opt[0].mlen == 0); 10060c16b537SWarner Losh 1007*37f1f268SConrad Meyer /* Set the next chunk's repcodes based on the repcodes of the beginning 1008*37f1f268SConrad Meyer * of the last match, and the last sequence. This avoids us having to 1009*37f1f268SConrad Meyer * update them while traversing the sequences. 1010*37f1f268SConrad Meyer */ 1011*37f1f268SConrad Meyer if (lastSequence.mlen != 0) { 1012*37f1f268SConrad Meyer repcodes_t reps = ZSTD_updateRep(opt[cur].rep, lastSequence.off, lastSequence.litlen==0); 1013*37f1f268SConrad Meyer memcpy(rep, &reps, sizeof(reps)); 1014*37f1f268SConrad Meyer } else { 1015*37f1f268SConrad Meyer memcpy(rep, opt[cur].rep, sizeof(repcodes_t)); 1016*37f1f268SConrad Meyer } 1017*37f1f268SConrad Meyer 10180f743729SConrad Meyer { U32 const storeEnd = cur + 1; 10190f743729SConrad Meyer U32 storeStart = storeEnd; 10200f743729SConrad Meyer U32 seqPos = cur; 10210f743729SConrad Meyer 10220f743729SConrad Meyer DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)", 10230f743729SConrad Meyer last_pos, cur); (void)last_pos; 10240f743729SConrad Meyer assert(storeEnd < ZSTD_OPT_NUM); 10250f743729SConrad Meyer DEBUGLOG(6, "last sequence copied into pos=%u (llen=%u,mlen=%u,ofc=%u)", 10260f743729SConrad Meyer storeEnd, lastSequence.litlen, lastSequence.mlen, lastSequence.off); 10270f743729SConrad Meyer opt[storeEnd] = lastSequence; 10280f743729SConrad Meyer while (seqPos > 0) { 10290f743729SConrad Meyer U32 const backDist = ZSTD_totalLen(opt[seqPos]); 10300f743729SConrad Meyer storeStart--; 10310f743729SConrad Meyer DEBUGLOG(6, "sequence from rPos=%u copied into pos=%u (llen=%u,mlen=%u,ofc=%u)", 10320f743729SConrad Meyer seqPos, storeStart, opt[seqPos].litlen, opt[seqPos].mlen, opt[seqPos].off); 10330f743729SConrad Meyer opt[storeStart] = opt[seqPos]; 10340f743729SConrad Meyer seqPos = (seqPos > backDist) ? seqPos - backDist : 0; 10350f743729SConrad Meyer } 10360c16b537SWarner Losh 1037052d3c12SConrad Meyer /* save sequences */ 10380f743729SConrad Meyer DEBUGLOG(6, "sending selected sequences into seqStore") 10390f743729SConrad Meyer { U32 storePos; 10400f743729SConrad Meyer for (storePos=storeStart; storePos <= storeEnd; storePos++) { 10410f743729SConrad Meyer U32 const llen = opt[storePos].litlen; 10420f743729SConrad Meyer U32 const mlen = opt[storePos].mlen; 10430f743729SConrad Meyer U32 const offCode = opt[storePos].off; 10440f743729SConrad Meyer U32 const advance = llen + mlen; 10450f743729SConrad Meyer DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u", 1046a0483764SConrad Meyer anchor - istart, (unsigned)llen, (unsigned)mlen); 10470f743729SConrad Meyer 10480f743729SConrad Meyer if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */ 10490f743729SConrad Meyer assert(storePos == storeEnd); /* must be last sequence */ 10500f743729SConrad Meyer ip = anchor + llen; /* last "sequence" is a bunch of literals => don't progress anchor */ 10510f743729SConrad Meyer continue; /* will finish */ 10520f743729SConrad Meyer } 10530c16b537SWarner Losh 10540f743729SConrad Meyer assert(anchor + llen <= iend); 10550f743729SConrad Meyer ZSTD_updateStats(optStatePtr, llen, anchor, offCode, mlen); 10569cbefe25SConrad Meyer ZSTD_storeSeq(seqStore, llen, anchor, iend, offCode, mlen-MINMATCH); 10570f743729SConrad Meyer anchor += advance; 10580f743729SConrad Meyer ip = anchor; 10590f743729SConrad Meyer } } 10600f743729SConrad Meyer ZSTD_setBasePrices(optStatePtr, optLevel); 10610c16b537SWarner Losh } 1062052d3c12SConrad Meyer } /* while (ip < ilimit) */ 10630c16b537SWarner Losh 10640c16b537SWarner Losh /* Return the last literals size */ 10654d3f1eafSConrad Meyer return (size_t)(iend - anchor); 10660c16b537SWarner Losh } 10670c16b537SWarner Losh 10680c16b537SWarner Losh 106919fcbaf1SConrad Meyer size_t ZSTD_compressBlock_btopt( 107019fcbaf1SConrad Meyer ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 10710f743729SConrad Meyer const void* src, size_t srcSize) 10720c16b537SWarner Losh { 1073052d3c12SConrad Meyer DEBUGLOG(5, "ZSTD_compressBlock_btopt"); 10740f743729SConrad Meyer return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_noDict); 10750f743729SConrad Meyer } 10760f743729SConrad Meyer 10770f743729SConrad Meyer 10780f743729SConrad Meyer /* used in 2-pass strategy */ 1079a0483764SConrad Meyer static U32 ZSTD_upscaleStat(unsigned* table, U32 lastEltIndex, int bonus) 10800f743729SConrad Meyer { 10810f743729SConrad Meyer U32 s, sum=0; 1082a0483764SConrad Meyer assert(ZSTD_FREQ_DIV+bonus >= 0); 1083a0483764SConrad Meyer for (s=0; s<lastEltIndex+1; s++) { 10840f743729SConrad Meyer table[s] <<= ZSTD_FREQ_DIV+bonus; 10850f743729SConrad Meyer table[s]--; 10860f743729SConrad Meyer sum += table[s]; 10870f743729SConrad Meyer } 10880f743729SConrad Meyer return sum; 10890f743729SConrad Meyer } 10900f743729SConrad Meyer 10910f743729SConrad Meyer /* used in 2-pass strategy */ 10920f743729SConrad Meyer MEM_STATIC void ZSTD_upscaleStats(optState_t* optPtr) 10930f743729SConrad Meyer { 10942b9c00cbSConrad Meyer if (ZSTD_compressedLiterals(optPtr)) 10950f743729SConrad Meyer optPtr->litSum = ZSTD_upscaleStat(optPtr->litFreq, MaxLit, 0); 1096a0483764SConrad Meyer optPtr->litLengthSum = ZSTD_upscaleStat(optPtr->litLengthFreq, MaxLL, 0); 1097a0483764SConrad Meyer optPtr->matchLengthSum = ZSTD_upscaleStat(optPtr->matchLengthFreq, MaxML, 0); 1098a0483764SConrad Meyer optPtr->offCodeSum = ZSTD_upscaleStat(optPtr->offCodeFreq, MaxOff, 0); 1099a0483764SConrad Meyer } 1100a0483764SConrad Meyer 1101a0483764SConrad Meyer /* ZSTD_initStats_ultra(): 1102a0483764SConrad Meyer * make a first compression pass, just to seed stats with more accurate starting values. 1103a0483764SConrad Meyer * only works on first block, with no dictionary and no ldm. 11042b9c00cbSConrad Meyer * this function cannot error, hence its contract must be respected. 1105a0483764SConrad Meyer */ 1106a0483764SConrad Meyer static void 1107a0483764SConrad Meyer ZSTD_initStats_ultra(ZSTD_matchState_t* ms, 1108a0483764SConrad Meyer seqStore_t* seqStore, 1109a0483764SConrad Meyer U32 rep[ZSTD_REP_NUM], 1110a0483764SConrad Meyer const void* src, size_t srcSize) 1111a0483764SConrad Meyer { 1112a0483764SConrad Meyer U32 tmpRep[ZSTD_REP_NUM]; /* updated rep codes will sink here */ 1113a0483764SConrad Meyer memcpy(tmpRep, rep, sizeof(tmpRep)); 1114a0483764SConrad Meyer 1115a0483764SConrad Meyer DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize); 1116a0483764SConrad Meyer assert(ms->opt.litLengthSum == 0); /* first block */ 1117a0483764SConrad Meyer assert(seqStore->sequences == seqStore->sequencesStart); /* no ldm */ 1118a0483764SConrad Meyer assert(ms->window.dictLimit == ms->window.lowLimit); /* no dictionary */ 1119a0483764SConrad Meyer assert(ms->window.dictLimit - ms->nextToUpdate <= 1); /* no prefix (note: intentional overflow, defined as 2-complement) */ 1120a0483764SConrad Meyer 1121a0483764SConrad Meyer ZSTD_compressBlock_opt_generic(ms, seqStore, tmpRep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict); /* generate stats into ms->opt*/ 1122a0483764SConrad Meyer 1123a0483764SConrad Meyer /* invalidate first scan from history */ 1124a0483764SConrad Meyer ZSTD_resetSeqStore(seqStore); 1125a0483764SConrad Meyer ms->window.base -= srcSize; 1126a0483764SConrad Meyer ms->window.dictLimit += (U32)srcSize; 1127a0483764SConrad Meyer ms->window.lowLimit = ms->window.dictLimit; 1128a0483764SConrad Meyer ms->nextToUpdate = ms->window.dictLimit; 1129a0483764SConrad Meyer 1130a0483764SConrad Meyer /* re-inforce weight of collected statistics */ 1131a0483764SConrad Meyer ZSTD_upscaleStats(&ms->opt); 11320c16b537SWarner Losh } 11330c16b537SWarner Losh 113419fcbaf1SConrad Meyer size_t ZSTD_compressBlock_btultra( 113519fcbaf1SConrad Meyer ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 11360f743729SConrad Meyer const void* src, size_t srcSize) 11370c16b537SWarner Losh { 11380f743729SConrad Meyer DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize); 1139a0483764SConrad Meyer return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict); 1140a0483764SConrad Meyer } 1141a0483764SConrad Meyer 1142a0483764SConrad Meyer size_t ZSTD_compressBlock_btultra2( 1143a0483764SConrad Meyer ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 1144a0483764SConrad Meyer const void* src, size_t srcSize) 1145a0483764SConrad Meyer { 1146a0483764SConrad Meyer U32 const current = (U32)((const BYTE*)src - ms->window.base); 1147a0483764SConrad Meyer DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize); 1148a0483764SConrad Meyer 1149a0483764SConrad Meyer /* 2-pass strategy: 11500f743729SConrad Meyer * this strategy makes a first pass over first block to collect statistics 11510f743729SConrad Meyer * and seed next round's statistics with it. 1152a0483764SConrad Meyer * After 1st pass, function forgets everything, and starts a new block. 1153a0483764SConrad Meyer * Consequently, this can only work if no data has been previously loaded in tables, 1154a0483764SConrad Meyer * aka, no dictionary, no prefix, no ldm preprocessing. 11550f743729SConrad Meyer * The compression ratio gain is generally small (~0.5% on first block), 11560f743729SConrad Meyer * the cost is 2x cpu time on first block. */ 11570f743729SConrad Meyer assert(srcSize <= ZSTD_BLOCKSIZE_MAX); 11580f743729SConrad Meyer if ( (ms->opt.litLengthSum==0) /* first block */ 11590f743729SConrad Meyer && (seqStore->sequences == seqStore->sequencesStart) /* no ldm */ 1160a0483764SConrad Meyer && (ms->window.dictLimit == ms->window.lowLimit) /* no dictionary */ 1161a0483764SConrad Meyer && (current == ms->window.dictLimit) /* start of frame, nothing already loaded nor skipped */ 1162a0483764SConrad Meyer && (srcSize > ZSTD_PREDEF_THRESHOLD) 1163a0483764SConrad Meyer ) { 1164a0483764SConrad Meyer ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize); 11650f743729SConrad Meyer } 1166a0483764SConrad Meyer 11670f743729SConrad Meyer return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict); 11680f743729SConrad Meyer } 11690f743729SConrad Meyer 11700f743729SConrad Meyer size_t ZSTD_compressBlock_btopt_dictMatchState( 11710f743729SConrad Meyer ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 11720f743729SConrad Meyer const void* src, size_t srcSize) 11730f743729SConrad Meyer { 11740f743729SConrad Meyer return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_dictMatchState); 11750f743729SConrad Meyer } 11760f743729SConrad Meyer 11770f743729SConrad Meyer size_t ZSTD_compressBlock_btultra_dictMatchState( 11780f743729SConrad Meyer ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 11790f743729SConrad Meyer const void* src, size_t srcSize) 11800f743729SConrad Meyer { 11810f743729SConrad Meyer return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_dictMatchState); 11820c16b537SWarner Losh } 11830c16b537SWarner Losh 118419fcbaf1SConrad Meyer size_t ZSTD_compressBlock_btopt_extDict( 118519fcbaf1SConrad Meyer ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 11860f743729SConrad Meyer const void* src, size_t srcSize) 11870c16b537SWarner Losh { 11880f743729SConrad Meyer return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_extDict); 11890c16b537SWarner Losh } 11900c16b537SWarner Losh 119119fcbaf1SConrad Meyer size_t ZSTD_compressBlock_btultra_extDict( 119219fcbaf1SConrad Meyer ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], 11930f743729SConrad Meyer const void* src, size_t srcSize) 11940c16b537SWarner Losh { 11950f743729SConrad Meyer return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_extDict); 11960c16b537SWarner Losh } 1197a0483764SConrad Meyer 1198a0483764SConrad Meyer /* note : no btultra2 variant for extDict nor dictMatchState, 1199a0483764SConrad Meyer * because btultra2 is not meant to work with dictionaries 1200a0483764SConrad Meyer * and is only specific for the first block (no prefix) */ 1201