zstd_opt.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. /*
  2. * Copyright (c) 2016-present, Przemyslaw Skibinski, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #include "zstd_compress_internal.h"
  11. #include "hist.h"
  12. #include "zstd_opt.h"
  13. #define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */
  14. #define ZSTD_FREQ_DIV 4 /* log factor when using previous stats to init next stats */
  15. #define ZSTD_MAX_PRICE (1<<30)
  16. #define ZSTD_PREDEF_THRESHOLD 1024 /* if srcSize < ZSTD_PREDEF_THRESHOLD, symbols' cost is assumed static, directly determined by pre-defined distributions */
  17. /*-*************************************
  18. * Price functions for optimal parser
  19. ***************************************/
  20. #if 0 /* approximation at bit level */
  21. # define BITCOST_ACCURACY 0
  22. # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
  23. # define WEIGHT(stat) ((void)opt, ZSTD_bitWeight(stat))
  24. #elif 0 /* fractional bit accuracy */
  25. # define BITCOST_ACCURACY 8
  26. # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
  27. # define WEIGHT(stat,opt) ((void)opt, ZSTD_fracWeight(stat))
  28. #else /* opt==approx, ultra==accurate */
  29. # define BITCOST_ACCURACY 8
  30. # define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
  31. # define WEIGHT(stat,opt) (opt ? ZSTD_fracWeight(stat) : ZSTD_bitWeight(stat))
  32. #endif
  33. MEM_STATIC U32 ZSTD_bitWeight(U32 stat)
  34. {
  35. return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER);
  36. }
  37. MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat)
  38. {
  39. U32 const stat = rawStat + 1;
  40. U32 const hb = ZSTD_highbit32(stat);
  41. U32 const BWeight = hb * BITCOST_MULTIPLIER;
  42. U32 const FWeight = (stat << BITCOST_ACCURACY) >> hb;
  43. U32 const weight = BWeight + FWeight;
  44. assert(hb + BITCOST_ACCURACY < 31);
  45. return weight;
  46. }
  47. #if (DEBUGLEVEL>=2)
  48. /* debugging function,
  49. * @return price in bytes as fractional value
  50. * for debug messages only */
  51. MEM_STATIC double ZSTD_fCost(U32 price)
  52. {
  53. return (double)price / (BITCOST_MULTIPLIER*8);
  54. }
  55. #endif
  56. static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel)
  57. {
  58. optPtr->litSumBasePrice = WEIGHT(optPtr->litSum, optLevel);
  59. optPtr->litLengthSumBasePrice = WEIGHT(optPtr->litLengthSum, optLevel);
  60. optPtr->matchLengthSumBasePrice = WEIGHT(optPtr->matchLengthSum, optLevel);
  61. optPtr->offCodeSumBasePrice = WEIGHT(optPtr->offCodeSum, optLevel);
  62. }
  63. /* ZSTD_downscaleStat() :
  64. * reduce all elements in table by a factor 2^(ZSTD_FREQ_DIV+malus)
  65. * return the resulting sum of elements */
  66. static U32 ZSTD_downscaleStat(unsigned* table, U32 lastEltIndex, int malus)
  67. {
  68. U32 s, sum=0;
  69. DEBUGLOG(5, "ZSTD_downscaleStat (nbElts=%u)", (unsigned)lastEltIndex+1);
  70. assert(ZSTD_FREQ_DIV+malus > 0 && ZSTD_FREQ_DIV+malus < 31);
  71. for (s=0; s<lastEltIndex+1; s++) {
  72. table[s] = 1 + (table[s] >> (ZSTD_FREQ_DIV+malus));
  73. sum += table[s];
  74. }
  75. return sum;
  76. }
  77. /* ZSTD_rescaleFreqs() :
  78. * if first block (detected by optPtr->litLengthSum == 0) : init statistics
  79. * take hints from dictionary if there is one
  80. * or init from zero, using src for literals stats, or flat 1 for match symbols
  81. * otherwise downscale existing stats, to be used as seed for next block.
  82. */
  83. static void
  84. ZSTD_rescaleFreqs(optState_t* const optPtr,
  85. const BYTE* const src, size_t const srcSize,
  86. int const optLevel)
  87. {
  88. DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize);
  89. optPtr->priceType = zop_dynamic;
  90. if (optPtr->litLengthSum == 0) { /* first block : init */
  91. if (srcSize <= ZSTD_PREDEF_THRESHOLD) { /* heuristic */
  92. DEBUGLOG(5, "(srcSize <= ZSTD_PREDEF_THRESHOLD) => zop_predef");
  93. optPtr->priceType = zop_predef;
  94. }
  95. assert(optPtr->symbolCosts != NULL);
  96. if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) {
  97. /* huffman table presumed generated by dictionary */
  98. optPtr->priceType = zop_dynamic;
  99. assert(optPtr->litFreq != NULL);
  100. optPtr->litSum = 0;
  101. { unsigned lit;
  102. for (lit=0; lit<=MaxLit; lit++) {
  103. U32 const scaleLog = 11; /* scale to 2K */
  104. U32 const bitCost = HUF_getNbBits(optPtr->symbolCosts->huf.CTable, lit);
  105. assert(bitCost <= scaleLog);
  106. optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
  107. optPtr->litSum += optPtr->litFreq[lit];
  108. } }
  109. { unsigned ll;
  110. FSE_CState_t llstate;
  111. FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable);
  112. optPtr->litLengthSum = 0;
  113. for (ll=0; ll<=MaxLL; ll++) {
  114. U32 const scaleLog = 10; /* scale to 1K */
  115. U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll);
  116. assert(bitCost < scaleLog);
  117. optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
  118. optPtr->litLengthSum += optPtr->litLengthFreq[ll];
  119. } }
  120. { unsigned ml;
  121. FSE_CState_t mlstate;
  122. FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable);
  123. optPtr->matchLengthSum = 0;
  124. for (ml=0; ml<=MaxML; ml++) {
  125. U32 const scaleLog = 10;
  126. U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml);
  127. assert(bitCost < scaleLog);
  128. optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
  129. optPtr->matchLengthSum += optPtr->matchLengthFreq[ml];
  130. } }
  131. { unsigned of;
  132. FSE_CState_t ofstate;
  133. FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable);
  134. optPtr->offCodeSum = 0;
  135. for (of=0; of<=MaxOff; of++) {
  136. U32 const scaleLog = 10;
  137. U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of);
  138. assert(bitCost < scaleLog);
  139. optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
  140. optPtr->offCodeSum += optPtr->offCodeFreq[of];
  141. } }
  142. } else { /* not a dictionary */
  143. assert(optPtr->litFreq != NULL);
  144. { unsigned lit = MaxLit;
  145. HIST_count_simple(optPtr->litFreq, &lit, src, srcSize); /* use raw first block to init statistics */
  146. }
  147. optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1);
  148. { unsigned ll;
  149. for (ll=0; ll<=MaxLL; ll++)
  150. optPtr->litLengthFreq[ll] = 1;
  151. }
  152. optPtr->litLengthSum = MaxLL+1;
  153. { unsigned ml;
  154. for (ml=0; ml<=MaxML; ml++)
  155. optPtr->matchLengthFreq[ml] = 1;
  156. }
  157. optPtr->matchLengthSum = MaxML+1;
  158. { unsigned of;
  159. for (of=0; of<=MaxOff; of++)
  160. optPtr->offCodeFreq[of] = 1;
  161. }
  162. optPtr->offCodeSum = MaxOff+1;
  163. }
  164. } else { /* new block : re-use previous statistics, scaled down */
  165. optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1);
  166. optPtr->litLengthSum = ZSTD_downscaleStat(optPtr->litLengthFreq, MaxLL, 0);
  167. optPtr->matchLengthSum = ZSTD_downscaleStat(optPtr->matchLengthFreq, MaxML, 0);
  168. optPtr->offCodeSum = ZSTD_downscaleStat(optPtr->offCodeFreq, MaxOff, 0);
  169. }
  170. ZSTD_setBasePrices(optPtr, optLevel);
  171. }
  172. /* ZSTD_rawLiteralsCost() :
  173. * price of literals (only) in specified segment (which length can be 0).
  174. * does not include price of literalLength symbol */
  175. static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength,
  176. const optState_t* const optPtr,
  177. int optLevel)
  178. {
  179. if (litLength == 0) return 0;
  180. if (optPtr->priceType == zop_predef)
  181. return (litLength*6) * BITCOST_MULTIPLIER; /* 6 bit per literal - no statistic used */
  182. /* dynamic statistics */
  183. { U32 price = litLength * optPtr->litSumBasePrice;
  184. U32 u;
  185. for (u=0; u < litLength; u++) {
  186. assert(WEIGHT(optPtr->litFreq[literals[u]], optLevel) <= optPtr->litSumBasePrice); /* literal cost should never be negative */
  187. price -= WEIGHT(optPtr->litFreq[literals[u]], optLevel);
  188. }
  189. return price;
  190. }
  191. }
  192. /* ZSTD_litLengthPrice() :
  193. * cost of literalLength symbol */
  194. static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel)
  195. {
  196. if (optPtr->priceType == zop_predef) return WEIGHT(litLength, optLevel);
  197. /* dynamic statistics */
  198. { U32 const llCode = ZSTD_LLcode(litLength);
  199. return (LL_bits[llCode] * BITCOST_MULTIPLIER)
  200. + optPtr->litLengthSumBasePrice
  201. - WEIGHT(optPtr->litLengthFreq[llCode], optLevel);
  202. }
  203. }
  204. /* ZSTD_litLengthContribution() :
  205. * @return ( cost(litlength) - cost(0) )
  206. * this value can then be added to rawLiteralsCost()
  207. * to provide a cost which is directly comparable to a match ending at same position */
  208. static int ZSTD_litLengthContribution(U32 const litLength, const optState_t* const optPtr, int optLevel)
  209. {
  210. if (optPtr->priceType >= zop_predef) return WEIGHT(litLength, optLevel);
  211. /* dynamic statistics */
  212. { U32 const llCode = ZSTD_LLcode(litLength);
  213. int const contribution = (LL_bits[llCode] * BITCOST_MULTIPLIER)
  214. + WEIGHT(optPtr->litLengthFreq[0], optLevel) /* note: log2litLengthSum cancel out */
  215. - WEIGHT(optPtr->litLengthFreq[llCode], optLevel);
  216. #if 1
  217. return contribution;
  218. #else
  219. return MAX(0, contribution); /* sometimes better, sometimes not ... */
  220. #endif
  221. }
  222. }
  223. /* ZSTD_literalsContribution() :
  224. * creates a fake cost for the literals part of a sequence
  225. * which can be compared to the ending cost of a match
  226. * should a new match start at this position */
  227. static int ZSTD_literalsContribution(const BYTE* const literals, U32 const litLength,
  228. const optState_t* const optPtr,
  229. int optLevel)
  230. {
  231. int const contribution = ZSTD_rawLiteralsCost(literals, litLength, optPtr, optLevel)
  232. + ZSTD_litLengthContribution(litLength, optPtr, optLevel);
  233. return contribution;
  234. }
  235. /* ZSTD_getMatchPrice() :
  236. * Provides the cost of the match part (offset + matchLength) of a sequence
  237. * Must be combined with ZSTD_fullLiteralsCost() to get the full cost of a sequence.
  238. * optLevel: when <2, favors small offset for decompression speed (improved cache efficiency) */
  239. FORCE_INLINE_TEMPLATE U32
  240. ZSTD_getMatchPrice(U32 const offset,
  241. U32 const matchLength,
  242. const optState_t* const optPtr,
  243. int const optLevel)
  244. {
  245. U32 price;
  246. U32 const offCode = ZSTD_highbit32(offset+1);
  247. U32 const mlBase = matchLength - MINMATCH;
  248. assert(matchLength >= MINMATCH);
  249. if (optPtr->priceType == zop_predef) /* fixed scheme, do not use statistics */
  250. return WEIGHT(mlBase, optLevel) + ((16 + offCode) * BITCOST_MULTIPLIER);
  251. /* dynamic statistics */
  252. price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel));
  253. if ((optLevel<2) /*static*/ && offCode >= 20)
  254. price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */
  255. /* match Length */
  256. { U32 const mlCode = ZSTD_MLcode(mlBase);
  257. price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel));
  258. }
  259. price += BITCOST_MULTIPLIER / 5; /* heuristic : make matches a bit more costly to favor less sequences -> faster decompression speed */
  260. DEBUGLOG(8, "ZSTD_getMatchPrice(ml:%u) = %u", matchLength, price);
  261. return price;
  262. }
  263. /* ZSTD_updateStats() :
  264. * assumption : literals + litLengtn <= iend */
  265. static void ZSTD_updateStats(optState_t* const optPtr,
  266. U32 litLength, const BYTE* literals,
  267. U32 offsetCode, U32 matchLength)
  268. {
  269. /* literals */
  270. { U32 u;
  271. for (u=0; u < litLength; u++)
  272. optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD;
  273. optPtr->litSum += litLength*ZSTD_LITFREQ_ADD;
  274. }
  275. /* literal Length */
  276. { U32 const llCode = ZSTD_LLcode(litLength);
  277. optPtr->litLengthFreq[llCode]++;
  278. optPtr->litLengthSum++;
  279. }
  280. /* match offset code (0-2=>repCode; 3+=>offset+2) */
  281. { U32 const offCode = ZSTD_highbit32(offsetCode+1);
  282. assert(offCode <= MaxOff);
  283. optPtr->offCodeFreq[offCode]++;
  284. optPtr->offCodeSum++;
  285. }
  286. /* match Length */
  287. { U32 const mlBase = matchLength - MINMATCH;
  288. U32 const mlCode = ZSTD_MLcode(mlBase);
  289. optPtr->matchLengthFreq[mlCode]++;
  290. optPtr->matchLengthSum++;
  291. }
  292. }
  293. /* ZSTD_readMINMATCH() :
  294. * function safe only for comparisons
  295. * assumption : memPtr must be at least 4 bytes before end of buffer */
  296. MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length)
  297. {
  298. switch (length)
  299. {
  300. default :
  301. case 4 : return MEM_read32(memPtr);
  302. case 3 : if (MEM_isLittleEndian())
  303. return MEM_read32(memPtr)<<8;
  304. else
  305. return MEM_read32(memPtr)>>8;
  306. }
  307. }
  308. /* Update hashTable3 up to ip (excluded)
  309. Assumption : always within prefix (i.e. not within extDict) */
  310. static U32 ZSTD_insertAndFindFirstIndexHash3 (ZSTD_matchState_t* ms, const BYTE* const ip)
  311. {
  312. U32* const hashTable3 = ms->hashTable3;
  313. U32 const hashLog3 = ms->hashLog3;
  314. const BYTE* const base = ms->window.base;
  315. U32 idx = ms->nextToUpdate3;
  316. U32 const target = ms->nextToUpdate3 = (U32)(ip - base);
  317. size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3);
  318. assert(hashLog3 > 0);
  319. while(idx < target) {
  320. hashTable3[ZSTD_hash3Ptr(base+idx, hashLog3)] = idx;
  321. idx++;
  322. }
  323. return hashTable3[hash3];
  324. }
  325. /*-*************************************
  326. * Binary Tree search
  327. ***************************************/
  328. /** ZSTD_insertBt1() : add one or multiple positions to tree.
  329. * ip : assumed <= iend-8 .
  330. * @return : nb of positions added */
  331. static U32 ZSTD_insertBt1(
  332. ZSTD_matchState_t* ms,
  333. const BYTE* const ip, const BYTE* const iend,
  334. U32 const mls, const int extDict)
  335. {
  336. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  337. U32* const hashTable = ms->hashTable;
  338. U32 const hashLog = cParams->hashLog;
  339. size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
  340. U32* const bt = ms->chainTable;
  341. U32 const btLog = cParams->chainLog - 1;
  342. U32 const btMask = (1 << btLog) - 1;
  343. U32 matchIndex = hashTable[h];
  344. size_t commonLengthSmaller=0, commonLengthLarger=0;
  345. const BYTE* const base = ms->window.base;
  346. const BYTE* const dictBase = ms->window.dictBase;
  347. const U32 dictLimit = ms->window.dictLimit;
  348. const BYTE* const dictEnd = dictBase + dictLimit;
  349. const BYTE* const prefixStart = base + dictLimit;
  350. const BYTE* match;
  351. const U32 current = (U32)(ip-base);
  352. const U32 btLow = btMask >= current ? 0 : current - btMask;
  353. U32* smallerPtr = bt + 2*(current&btMask);
  354. U32* largerPtr = smallerPtr + 1;
  355. U32 dummy32; /* to be nullified at the end */
  356. U32 const windowLow = ms->window.lowLimit;
  357. U32 matchEndIdx = current+8+1;
  358. size_t bestLength = 8;
  359. U32 nbCompares = 1U << cParams->searchLog;
  360. #ifdef ZSTD_C_PREDICT
  361. U32 predictedSmall = *(bt + 2*((current-1)&btMask) + 0);
  362. U32 predictedLarge = *(bt + 2*((current-1)&btMask) + 1);
  363. predictedSmall += (predictedSmall>0);
  364. predictedLarge += (predictedLarge>0);
  365. #endif /* ZSTD_C_PREDICT */
  366. DEBUGLOG(8, "ZSTD_insertBt1 (%u)", current);
  367. assert(ip <= iend-8); /* required for h calculation */
  368. hashTable[h] = current; /* Update Hash Table */
  369. assert(windowLow > 0);
  370. while (nbCompares-- && (matchIndex >= windowLow)) {
  371. U32* const nextPtr = bt + 2*(matchIndex & btMask);
  372. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  373. assert(matchIndex < current);
  374. #ifdef ZSTD_C_PREDICT /* note : can create issues when hlog small <= 11 */
  375. const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */
  376. if (matchIndex == predictedSmall) {
  377. /* no need to check length, result known */
  378. *smallerPtr = matchIndex;
  379. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  380. smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
  381. matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  382. predictedSmall = predictPtr[1] + (predictPtr[1]>0);
  383. continue;
  384. }
  385. if (matchIndex == predictedLarge) {
  386. *largerPtr = matchIndex;
  387. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  388. largerPtr = nextPtr;
  389. matchIndex = nextPtr[0];
  390. predictedLarge = predictPtr[0] + (predictPtr[0]>0);
  391. continue;
  392. }
  393. #endif
  394. if (!extDict || (matchIndex+matchLength >= dictLimit)) {
  395. assert(matchIndex+matchLength >= dictLimit); /* might be wrong if actually extDict */
  396. match = base + matchIndex;
  397. matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
  398. } else {
  399. match = dictBase + matchIndex;
  400. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
  401. if (matchIndex+matchLength >= dictLimit)
  402. match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
  403. }
  404. if (matchLength > bestLength) {
  405. bestLength = matchLength;
  406. if (matchLength > matchEndIdx - matchIndex)
  407. matchEndIdx = matchIndex + (U32)matchLength;
  408. }
  409. if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
  410. break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
  411. }
  412. if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */
  413. /* match is smaller than current */
  414. *smallerPtr = matchIndex; /* update smaller idx */
  415. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  416. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */
  417. smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */
  418. matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */
  419. } else {
  420. /* match is larger than current */
  421. *largerPtr = matchIndex;
  422. commonLengthLarger = matchLength;
  423. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */
  424. largerPtr = nextPtr;
  425. matchIndex = nextPtr[0];
  426. } }
  427. *smallerPtr = *largerPtr = 0;
  428. if (bestLength > 384) return MIN(192, (U32)(bestLength - 384)); /* speed optimization */
  429. assert(matchEndIdx > current + 8);
  430. return matchEndIdx - (current + 8);
  431. }
  432. FORCE_INLINE_TEMPLATE
  433. void ZSTD_updateTree_internal(
  434. ZSTD_matchState_t* ms,
  435. const BYTE* const ip, const BYTE* const iend,
  436. const U32 mls, const ZSTD_dictMode_e dictMode)
  437. {
  438. const BYTE* const base = ms->window.base;
  439. U32 const target = (U32)(ip - base);
  440. U32 idx = ms->nextToUpdate;
  441. DEBUGLOG(6, "ZSTD_updateTree_internal, from %u to %u (dictMode:%u)",
  442. idx, target, dictMode);
  443. while(idx < target)
  444. idx += ZSTD_insertBt1(ms, base+idx, iend, mls, dictMode == ZSTD_extDict);
  445. ms->nextToUpdate = target;
  446. }
  447. void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) {
  448. ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);
  449. }
  450. FORCE_INLINE_TEMPLATE
  451. U32 ZSTD_insertBtAndGetAllMatches (
  452. ZSTD_matchState_t* ms,
  453. const BYTE* const ip, const BYTE* const iLimit, const ZSTD_dictMode_e dictMode,
  454. U32 rep[ZSTD_REP_NUM],
  455. U32 const ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */
  456. ZSTD_match_t* matches,
  457. const U32 lengthToBeat,
  458. U32 const mls /* template */)
  459. {
  460. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  461. U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
  462. const BYTE* const base = ms->window.base;
  463. U32 const current = (U32)(ip-base);
  464. U32 const hashLog = cParams->hashLog;
  465. U32 const minMatch = (mls==3) ? 3 : 4;
  466. U32* const hashTable = ms->hashTable;
  467. size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
  468. U32 matchIndex = hashTable[h];
  469. U32* const bt = ms->chainTable;
  470. U32 const btLog = cParams->chainLog - 1;
  471. U32 const btMask= (1U << btLog) - 1;
  472. size_t commonLengthSmaller=0, commonLengthLarger=0;
  473. const BYTE* const dictBase = ms->window.dictBase;
  474. U32 const dictLimit = ms->window.dictLimit;
  475. const BYTE* const dictEnd = dictBase + dictLimit;
  476. const BYTE* const prefixStart = base + dictLimit;
  477. U32 const btLow = btMask >= current ? 0 : current - btMask;
  478. U32 const windowLow = ms->window.lowLimit;
  479. U32 const matchLow = windowLow ? windowLow : 1;
  480. U32* smallerPtr = bt + 2*(current&btMask);
  481. U32* largerPtr = bt + 2*(current&btMask) + 1;
  482. U32 matchEndIdx = current+8+1; /* farthest referenced position of any match => detects repetitive patterns */
  483. U32 dummy32; /* to be nullified at the end */
  484. U32 mnum = 0;
  485. U32 nbCompares = 1U << cParams->searchLog;
  486. const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL;
  487. const ZSTD_compressionParameters* const dmsCParams =
  488. dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL;
  489. const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL;
  490. const BYTE* const dmsEnd = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL;
  491. U32 const dmsHighLimit = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0;
  492. U32 const dmsLowLimit = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0;
  493. U32 const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0;
  494. U32 const dmsHashLog = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog;
  495. U32 const dmsBtLog = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog;
  496. U32 const dmsBtMask = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0;
  497. U32 const dmsBtLow = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit;
  498. size_t bestLength = lengthToBeat-1;
  499. DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", current);
  500. /* check repCode */
  501. assert(ll0 <= 1); /* necessarily 1 or 0 */
  502. { U32 const lastR = ZSTD_REP_NUM + ll0;
  503. U32 repCode;
  504. for (repCode = ll0; repCode < lastR; repCode++) {
  505. U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
  506. U32 const repIndex = current - repOffset;
  507. U32 repLen = 0;
  508. assert(current >= dictLimit);
  509. if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < current-dictLimit) { /* equivalent to `current > repIndex >= dictLimit` */
  510. if (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch)) {
  511. repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch;
  512. }
  513. } else { /* repIndex < dictLimit || repIndex >= current */
  514. const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ?
  515. dmsBase + repIndex - dmsIndexDelta :
  516. dictBase + repIndex;
  517. assert(current >= windowLow);
  518. if ( dictMode == ZSTD_extDict
  519. && ( ((repOffset-1) /*intentional overflow*/ < current - windowLow) /* equivalent to `current > repIndex >= windowLow` */
  520. & (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */)
  521. && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
  522. repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch;
  523. }
  524. if (dictMode == ZSTD_dictMatchState
  525. && ( ((repOffset-1) /*intentional overflow*/ < current - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `current > repIndex >= dmsLowLimit` */
  526. & ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */
  527. && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
  528. repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch;
  529. } }
  530. /* save longer solution */
  531. if (repLen > bestLength) {
  532. DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u",
  533. repCode, ll0, repOffset, repLen);
  534. bestLength = repLen;
  535. matches[mnum].off = repCode - ll0;
  536. matches[mnum].len = (U32)repLen;
  537. mnum++;
  538. if ( (repLen > sufficient_len)
  539. | (ip+repLen == iLimit) ) { /* best possible */
  540. return mnum;
  541. } } } }
  542. /* HC3 match finder */
  543. if ((mls == 3) /*static*/ && (bestLength < mls)) {
  544. U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, ip);
  545. if ((matchIndex3 >= matchLow)
  546. & (current - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) {
  547. size_t mlen;
  548. if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) {
  549. const BYTE* const match = base + matchIndex3;
  550. mlen = ZSTD_count(ip, match, iLimit);
  551. } else {
  552. const BYTE* const match = dictBase + matchIndex3;
  553. mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart);
  554. }
  555. /* save best solution */
  556. if (mlen >= mls /* == 3 > bestLength */) {
  557. DEBUGLOG(8, "found small match with hlog3, of length %u",
  558. (U32)mlen);
  559. bestLength = mlen;
  560. assert(current > matchIndex3);
  561. assert(mnum==0); /* no prior solution */
  562. matches[0].off = (current - matchIndex3) + ZSTD_REP_MOVE;
  563. matches[0].len = (U32)mlen;
  564. mnum = 1;
  565. if ( (mlen > sufficient_len) |
  566. (ip+mlen == iLimit) ) { /* best possible length */
  567. ms->nextToUpdate = current+1; /* skip insertion */
  568. return 1;
  569. }
  570. }
  571. }
  572. /* no dictMatchState lookup: dicts don't have a populated HC3 table */
  573. }
  574. hashTable[h] = current; /* Update Hash Table */
  575. while (nbCompares-- && (matchIndex >= matchLow)) {
  576. U32* const nextPtr = bt + 2*(matchIndex & btMask);
  577. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  578. const BYTE* match;
  579. assert(current > matchIndex);
  580. if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) {
  581. assert(matchIndex+matchLength >= dictLimit); /* ensure the condition is correct when !extDict */
  582. match = base + matchIndex;
  583. matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit);
  584. } else {
  585. match = dictBase + matchIndex;
  586. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart);
  587. if (matchIndex+matchLength >= dictLimit)
  588. match = base + matchIndex; /* prepare for match[matchLength] */
  589. }
  590. if (matchLength > bestLength) {
  591. DEBUGLOG(8, "found match of length %u at distance %u (offCode=%u)",
  592. (U32)matchLength, current - matchIndex, current - matchIndex + ZSTD_REP_MOVE);
  593. assert(matchEndIdx > matchIndex);
  594. if (matchLength > matchEndIdx - matchIndex)
  595. matchEndIdx = matchIndex + (U32)matchLength;
  596. bestLength = matchLength;
  597. matches[mnum].off = (current - matchIndex) + ZSTD_REP_MOVE;
  598. matches[mnum].len = (U32)matchLength;
  599. mnum++;
  600. if ( (matchLength > ZSTD_OPT_NUM)
  601. | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
  602. if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */
  603. break; /* drop, to preserve bt consistency (miss a little bit of compression) */
  604. }
  605. }
  606. if (match[matchLength] < ip[matchLength]) {
  607. /* match smaller than current */
  608. *smallerPtr = matchIndex; /* update smaller idx */
  609. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  610. if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  611. smallerPtr = nextPtr+1; /* new candidate => larger than match, which was smaller than current */
  612. matchIndex = nextPtr[1]; /* new matchIndex, larger than previous, closer to current */
  613. } else {
  614. *largerPtr = matchIndex;
  615. commonLengthLarger = matchLength;
  616. if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
  617. largerPtr = nextPtr;
  618. matchIndex = nextPtr[0];
  619. } }
  620. *smallerPtr = *largerPtr = 0;
  621. if (dictMode == ZSTD_dictMatchState && nbCompares) {
  622. size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls);
  623. U32 dictMatchIndex = dms->hashTable[dmsH];
  624. const U32* const dmsBt = dms->chainTable;
  625. commonLengthSmaller = commonLengthLarger = 0;
  626. while (nbCompares-- && (dictMatchIndex > dmsLowLimit)) {
  627. const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask);
  628. size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
  629. const BYTE* match = dmsBase + dictMatchIndex;
  630. matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart);
  631. if (dictMatchIndex+matchLength >= dmsHighLimit)
  632. match = base + dictMatchIndex + dmsIndexDelta; /* to prepare for next usage of match[matchLength] */
  633. if (matchLength > bestLength) {
  634. matchIndex = dictMatchIndex + dmsIndexDelta;
  635. DEBUGLOG(8, "found dms match of length %u at distance %u (offCode=%u)",
  636. (U32)matchLength, current - matchIndex, current - matchIndex + ZSTD_REP_MOVE);
  637. if (matchLength > matchEndIdx - matchIndex)
  638. matchEndIdx = matchIndex + (U32)matchLength;
  639. bestLength = matchLength;
  640. matches[mnum].off = (current - matchIndex) + ZSTD_REP_MOVE;
  641. matches[mnum].len = (U32)matchLength;
  642. mnum++;
  643. if ( (matchLength > ZSTD_OPT_NUM)
  644. | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
  645. break; /* drop, to guarantee consistency (miss a little bit of compression) */
  646. }
  647. }
  648. if (dictMatchIndex <= dmsBtLow) { break; } /* beyond tree size, stop the search */
  649. if (match[matchLength] < ip[matchLength]) {
  650. commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
  651. dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
  652. } else {
  653. /* match is larger than current */
  654. commonLengthLarger = matchLength;
  655. dictMatchIndex = nextPtr[0];
  656. }
  657. }
  658. }
  659. assert(matchEndIdx > current+8);
  660. ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */
  661. return mnum;
  662. }
  663. FORCE_INLINE_TEMPLATE U32 ZSTD_BtGetAllMatches (
  664. ZSTD_matchState_t* ms,
  665. const BYTE* ip, const BYTE* const iHighLimit, const ZSTD_dictMode_e dictMode,
  666. U32 rep[ZSTD_REP_NUM], U32 const ll0,
  667. ZSTD_match_t* matches, U32 const lengthToBeat)
  668. {
  669. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  670. U32 const matchLengthSearch = cParams->minMatch;
  671. DEBUGLOG(8, "ZSTD_BtGetAllMatches");
  672. if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */
  673. ZSTD_updateTree_internal(ms, ip, iHighLimit, matchLengthSearch, dictMode);
  674. switch(matchLengthSearch)
  675. {
  676. case 3 : return ZSTD_insertBtAndGetAllMatches(ms, ip, iHighLimit, dictMode, rep, ll0, matches, lengthToBeat, 3);
  677. default :
  678. case 4 : return ZSTD_insertBtAndGetAllMatches(ms, ip, iHighLimit, dictMode, rep, ll0, matches, lengthToBeat, 4);
  679. case 5 : return ZSTD_insertBtAndGetAllMatches(ms, ip, iHighLimit, dictMode, rep, ll0, matches, lengthToBeat, 5);
  680. case 7 :
  681. case 6 : return ZSTD_insertBtAndGetAllMatches(ms, ip, iHighLimit, dictMode, rep, ll0, matches, lengthToBeat, 6);
  682. }
  683. }
  684. /*-*******************************
  685. * Optimal parser
  686. *********************************/
  687. typedef struct repcodes_s {
  688. U32 rep[3];
  689. } repcodes_t;
  690. static repcodes_t ZSTD_updateRep(U32 const rep[3], U32 const offset, U32 const ll0)
  691. {
  692. repcodes_t newReps;
  693. if (offset >= ZSTD_REP_NUM) { /* full offset */
  694. newReps.rep[2] = rep[1];
  695. newReps.rep[1] = rep[0];
  696. newReps.rep[0] = offset - ZSTD_REP_MOVE;
  697. } else { /* repcode */
  698. U32 const repCode = offset + ll0;
  699. if (repCode > 0) { /* note : if repCode==0, no change */
  700. U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
  701. newReps.rep[2] = (repCode >= 2) ? rep[1] : rep[2];
  702. newReps.rep[1] = rep[0];
  703. newReps.rep[0] = currentOffset;
  704. } else { /* repCode == 0 */
  705. memcpy(&newReps, rep, sizeof(newReps));
  706. }
  707. }
  708. return newReps;
  709. }
  710. static U32 ZSTD_totalLen(ZSTD_optimal_t sol)
  711. {
  712. return sol.litlen + sol.mlen;
  713. }
  714. #if 0 /* debug */
  715. static void
  716. listStats(const U32* table, int lastEltID)
  717. {
  718. int const nbElts = lastEltID + 1;
  719. int enb;
  720. for (enb=0; enb < nbElts; enb++) {
  721. (void)table;
  722. //RAWLOG(2, "%3i:%3i, ", enb, table[enb]);
  723. RAWLOG(2, "%4i,", table[enb]);
  724. }
  725. RAWLOG(2, " \n");
  726. }
  727. #endif
  728. FORCE_INLINE_TEMPLATE size_t
  729. ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
  730. seqStore_t* seqStore,
  731. U32 rep[ZSTD_REP_NUM],
  732. const void* src, size_t srcSize,
  733. const int optLevel,
  734. const ZSTD_dictMode_e dictMode)
  735. {
  736. optState_t* const optStatePtr = &ms->opt;
  737. const BYTE* const istart = (const BYTE*)src;
  738. const BYTE* ip = istart;
  739. const BYTE* anchor = istart;
  740. const BYTE* const iend = istart + srcSize;
  741. const BYTE* const ilimit = iend - 8;
  742. const BYTE* const base = ms->window.base;
  743. const BYTE* const prefixStart = base + ms->window.dictLimit;
  744. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  745. U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
  746. U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4;
  747. ZSTD_optimal_t* const opt = optStatePtr->priceTable;
  748. ZSTD_match_t* const matches = optStatePtr->matchTable;
  749. ZSTD_optimal_t lastSequence;
  750. /* init */
  751. DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u",
  752. (U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate);
  753. assert(optLevel <= 2);
  754. ms->nextToUpdate3 = ms->nextToUpdate;
  755. ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel);
  756. ip += (ip==prefixStart);
  757. /* Match Loop */
  758. while (ip < ilimit) {
  759. U32 cur, last_pos = 0;
  760. /* find first match */
  761. { U32 const litlen = (U32)(ip - anchor);
  762. U32 const ll0 = !litlen;
  763. U32 const nbMatches = ZSTD_BtGetAllMatches(ms, ip, iend, dictMode, rep, ll0, matches, minMatch);
  764. if (!nbMatches) { ip++; continue; }
  765. /* initialize opt[0] */
  766. { U32 i ; for (i=0; i<ZSTD_REP_NUM; i++) opt[0].rep[i] = rep[i]; }
  767. opt[0].mlen = 0; /* means is_a_literal */
  768. opt[0].litlen = litlen;
  769. opt[0].price = ZSTD_literalsContribution(anchor, litlen, optStatePtr, optLevel);
  770. /* large match -> immediate encoding */
  771. { U32 const maxML = matches[nbMatches-1].len;
  772. U32 const maxOffset = matches[nbMatches-1].off;
  773. DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffCode=%u at cPos=%u => start new serie",
  774. nbMatches, maxML, maxOffset, (U32)(ip-prefixStart));
  775. if (maxML > sufficient_len) {
  776. lastSequence.litlen = litlen;
  777. lastSequence.mlen = maxML;
  778. lastSequence.off = maxOffset;
  779. DEBUGLOG(6, "large match (%u>%u), immediate encoding",
  780. maxML, sufficient_len);
  781. cur = 0;
  782. last_pos = ZSTD_totalLen(lastSequence);
  783. goto _shortestPath;
  784. } }
  785. /* set prices for first matches starting position == 0 */
  786. { U32 const literalsPrice = opt[0].price + ZSTD_litLengthPrice(0, optStatePtr, optLevel);
  787. U32 pos;
  788. U32 matchNb;
  789. for (pos = 1; pos < minMatch; pos++) {
  790. opt[pos].price = ZSTD_MAX_PRICE; /* mlen, litlen and price will be fixed during forward scanning */
  791. }
  792. for (matchNb = 0; matchNb < nbMatches; matchNb++) {
  793. U32 const offset = matches[matchNb].off;
  794. U32 const end = matches[matchNb].len;
  795. repcodes_t const repHistory = ZSTD_updateRep(rep, offset, ll0);
  796. for ( ; pos <= end ; pos++ ) {
  797. U32 const matchPrice = ZSTD_getMatchPrice(offset, pos, optStatePtr, optLevel);
  798. U32 const sequencePrice = literalsPrice + matchPrice;
  799. DEBUGLOG(7, "rPos:%u => set initial price : %.2f",
  800. pos, ZSTD_fCost(sequencePrice));
  801. opt[pos].mlen = pos;
  802. opt[pos].off = offset;
  803. opt[pos].litlen = litlen;
  804. opt[pos].price = sequencePrice;
  805. ZSTD_STATIC_ASSERT(sizeof(opt[pos].rep) == sizeof(repHistory));
  806. memcpy(opt[pos].rep, &repHistory, sizeof(repHistory));
  807. } }
  808. last_pos = pos-1;
  809. }
  810. }
  811. /* check further positions */
  812. for (cur = 1; cur <= last_pos; cur++) {
  813. const BYTE* const inr = ip + cur;
  814. assert(cur < ZSTD_OPT_NUM);
  815. DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur)
  816. /* Fix current position with one literal if cheaper */
  817. { U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;
  818. int const price = opt[cur-1].price
  819. + ZSTD_rawLiteralsCost(ip+cur-1, 1, optStatePtr, optLevel)
  820. + ZSTD_litLengthPrice(litlen, optStatePtr, optLevel)
  821. - ZSTD_litLengthPrice(litlen-1, optStatePtr, optLevel);
  822. assert(price < 1000000000); /* overflow check */
  823. if (price <= opt[cur].price) {
  824. DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
  825. inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
  826. opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
  827. opt[cur].mlen = 0;
  828. opt[cur].off = 0;
  829. opt[cur].litlen = litlen;
  830. opt[cur].price = price;
  831. memcpy(opt[cur].rep, opt[cur-1].rep, sizeof(opt[cur].rep));
  832. } else {
  833. DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)",
  834. inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price),
  835. opt[cur].rep[0], opt[cur].rep[1], opt[cur].rep[2]);
  836. }
  837. }
  838. /* last match must start at a minimum distance of 8 from oend */
  839. if (inr > ilimit) continue;
  840. if (cur == last_pos) break;
  841. if ( (optLevel==0) /*static_test*/
  842. && (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {
  843. DEBUGLOG(7, "move to next rPos:%u : price is <=", cur+1);
  844. continue; /* skip unpromising positions; about ~+6% speed, -0.01 ratio */
  845. }
  846. { U32 const ll0 = (opt[cur].mlen != 0);
  847. U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0;
  848. U32 const previousPrice = opt[cur].price;
  849. U32 const basePrice = previousPrice + ZSTD_litLengthPrice(0, optStatePtr, optLevel);
  850. U32 const nbMatches = ZSTD_BtGetAllMatches(ms, inr, iend, dictMode, opt[cur].rep, ll0, matches, minMatch);
  851. U32 matchNb;
  852. if (!nbMatches) {
  853. DEBUGLOG(7, "rPos:%u : no match found", cur);
  854. continue;
  855. }
  856. { U32 const maxML = matches[nbMatches-1].len;
  857. DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of maxLength=%u",
  858. inr-istart, cur, nbMatches, maxML);
  859. if ( (maxML > sufficient_len)
  860. || (cur + maxML >= ZSTD_OPT_NUM) ) {
  861. lastSequence.mlen = maxML;
  862. lastSequence.off = matches[nbMatches-1].off;
  863. lastSequence.litlen = litlen;
  864. 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 */
  865. last_pos = cur + ZSTD_totalLen(lastSequence);
  866. if (cur > ZSTD_OPT_NUM) cur = 0; /* underflow => first match */
  867. goto _shortestPath;
  868. } }
  869. /* set prices using matches found at position == cur */
  870. for (matchNb = 0; matchNb < nbMatches; matchNb++) {
  871. U32 const offset = matches[matchNb].off;
  872. repcodes_t const repHistory = ZSTD_updateRep(opt[cur].rep, offset, ll0);
  873. U32 const lastML = matches[matchNb].len;
  874. U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch;
  875. U32 mlen;
  876. DEBUGLOG(7, "testing match %u => offCode=%4u, mlen=%2u, llen=%2u",
  877. matchNb, matches[matchNb].off, lastML, litlen);
  878. for (mlen = lastML; mlen >= startML; mlen--) { /* scan downward */
  879. U32 const pos = cur + mlen;
  880. int const price = basePrice + ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);
  881. if ((pos > last_pos) || (price < opt[pos].price)) {
  882. DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",
  883. pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
  884. while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; } /* fill empty positions */
  885. opt[pos].mlen = mlen;
  886. opt[pos].off = offset;
  887. opt[pos].litlen = litlen;
  888. opt[pos].price = price;
  889. ZSTD_STATIC_ASSERT(sizeof(opt[pos].rep) == sizeof(repHistory));
  890. memcpy(opt[pos].rep, &repHistory, sizeof(repHistory));
  891. } else {
  892. DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",
  893. pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
  894. if (optLevel==0) break; /* early update abort; gets ~+10% speed for about -0.01 ratio loss */
  895. }
  896. } } }
  897. } /* for (cur = 1; cur <= last_pos; cur++) */
  898. lastSequence = opt[last_pos];
  899. cur = last_pos > ZSTD_totalLen(lastSequence) ? last_pos - ZSTD_totalLen(lastSequence) : 0; /* single sequence, and it starts before `ip` */
  900. assert(cur < ZSTD_OPT_NUM); /* control overflow*/
  901. _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */
  902. assert(opt[0].mlen == 0);
  903. { U32 const storeEnd = cur + 1;
  904. U32 storeStart = storeEnd;
  905. U32 seqPos = cur;
  906. DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",
  907. last_pos, cur); (void)last_pos;
  908. assert(storeEnd < ZSTD_OPT_NUM);
  909. DEBUGLOG(6, "last sequence copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
  910. storeEnd, lastSequence.litlen, lastSequence.mlen, lastSequence.off);
  911. opt[storeEnd] = lastSequence;
  912. while (seqPos > 0) {
  913. U32 const backDist = ZSTD_totalLen(opt[seqPos]);
  914. storeStart--;
  915. DEBUGLOG(6, "sequence from rPos=%u copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
  916. seqPos, storeStart, opt[seqPos].litlen, opt[seqPos].mlen, opt[seqPos].off);
  917. opt[storeStart] = opt[seqPos];
  918. seqPos = (seqPos > backDist) ? seqPos - backDist : 0;
  919. }
  920. /* save sequences */
  921. DEBUGLOG(6, "sending selected sequences into seqStore")
  922. { U32 storePos;
  923. for (storePos=storeStart; storePos <= storeEnd; storePos++) {
  924. U32 const llen = opt[storePos].litlen;
  925. U32 const mlen = opt[storePos].mlen;
  926. U32 const offCode = opt[storePos].off;
  927. U32 const advance = llen + mlen;
  928. DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u",
  929. anchor - istart, (unsigned)llen, (unsigned)mlen);
  930. if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */
  931. assert(storePos == storeEnd); /* must be last sequence */
  932. ip = anchor + llen; /* last "sequence" is a bunch of literals => don't progress anchor */
  933. continue; /* will finish */
  934. }
  935. /* repcodes update : like ZSTD_updateRep(), but update in place */
  936. if (offCode >= ZSTD_REP_NUM) { /* full offset */
  937. rep[2] = rep[1];
  938. rep[1] = rep[0];
  939. rep[0] = offCode - ZSTD_REP_MOVE;
  940. } else { /* repcode */
  941. U32 const repCode = offCode + (llen==0);
  942. if (repCode) { /* note : if repCode==0, no change */
  943. U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
  944. if (repCode >= 2) rep[2] = rep[1];
  945. rep[1] = rep[0];
  946. rep[0] = currentOffset;
  947. } }
  948. assert(anchor + llen <= iend);
  949. ZSTD_updateStats(optStatePtr, llen, anchor, offCode, mlen);
  950. ZSTD_storeSeq(seqStore, llen, anchor, offCode, mlen-MINMATCH);
  951. anchor += advance;
  952. ip = anchor;
  953. } }
  954. ZSTD_setBasePrices(optStatePtr, optLevel);
  955. }
  956. } /* while (ip < ilimit) */
  957. /* Return the last literals size */
  958. return iend - anchor;
  959. }
  960. size_t ZSTD_compressBlock_btopt(
  961. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  962. const void* src, size_t srcSize)
  963. {
  964. DEBUGLOG(5, "ZSTD_compressBlock_btopt");
  965. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_noDict);
  966. }
  967. /* used in 2-pass strategy */
  968. static U32 ZSTD_upscaleStat(unsigned* table, U32 lastEltIndex, int bonus)
  969. {
  970. U32 s, sum=0;
  971. assert(ZSTD_FREQ_DIV+bonus >= 0);
  972. for (s=0; s<lastEltIndex+1; s++) {
  973. table[s] <<= ZSTD_FREQ_DIV+bonus;
  974. table[s]--;
  975. sum += table[s];
  976. }
  977. return sum;
  978. }
  979. /* used in 2-pass strategy */
  980. MEM_STATIC void ZSTD_upscaleStats(optState_t* optPtr)
  981. {
  982. optPtr->litSum = ZSTD_upscaleStat(optPtr->litFreq, MaxLit, 0);
  983. optPtr->litLengthSum = ZSTD_upscaleStat(optPtr->litLengthFreq, MaxLL, 0);
  984. optPtr->matchLengthSum = ZSTD_upscaleStat(optPtr->matchLengthFreq, MaxML, 0);
  985. optPtr->offCodeSum = ZSTD_upscaleStat(optPtr->offCodeFreq, MaxOff, 0);
  986. }
  987. /* ZSTD_initStats_ultra():
  988. * make a first compression pass, just to seed stats with more accurate starting values.
  989. * only works on first block, with no dictionary and no ldm.
  990. * this function cannot error, hence its constract must be respected.
  991. */
  992. static void
  993. ZSTD_initStats_ultra(ZSTD_matchState_t* ms,
  994. seqStore_t* seqStore,
  995. U32 rep[ZSTD_REP_NUM],
  996. const void* src, size_t srcSize)
  997. {
  998. U32 tmpRep[ZSTD_REP_NUM]; /* updated rep codes will sink here */
  999. memcpy(tmpRep, rep, sizeof(tmpRep));
  1000. DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize);
  1001. assert(ms->opt.litLengthSum == 0); /* first block */
  1002. assert(seqStore->sequences == seqStore->sequencesStart); /* no ldm */
  1003. assert(ms->window.dictLimit == ms->window.lowLimit); /* no dictionary */
  1004. assert(ms->window.dictLimit - ms->nextToUpdate <= 1); /* no prefix (note: intentional overflow, defined as 2-complement) */
  1005. ZSTD_compressBlock_opt_generic(ms, seqStore, tmpRep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict); /* generate stats into ms->opt*/
  1006. /* invalidate first scan from history */
  1007. ZSTD_resetSeqStore(seqStore);
  1008. ms->window.base -= srcSize;
  1009. ms->window.dictLimit += (U32)srcSize;
  1010. ms->window.lowLimit = ms->window.dictLimit;
  1011. ms->nextToUpdate = ms->window.dictLimit;
  1012. ms->nextToUpdate3 = ms->window.dictLimit;
  1013. /* re-inforce weight of collected statistics */
  1014. ZSTD_upscaleStats(&ms->opt);
  1015. }
  1016. size_t ZSTD_compressBlock_btultra(
  1017. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1018. const void* src, size_t srcSize)
  1019. {
  1020. DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize);
  1021. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict);
  1022. }
  1023. size_t ZSTD_compressBlock_btultra2(
  1024. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1025. const void* src, size_t srcSize)
  1026. {
  1027. U32 const current = (U32)((const BYTE*)src - ms->window.base);
  1028. DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize);
  1029. /* 2-pass strategy:
  1030. * this strategy makes a first pass over first block to collect statistics
  1031. * and seed next round's statistics with it.
  1032. * After 1st pass, function forgets everything, and starts a new block.
  1033. * Consequently, this can only work if no data has been previously loaded in tables,
  1034. * aka, no dictionary, no prefix, no ldm preprocessing.
  1035. * The compression ratio gain is generally small (~0.5% on first block),
  1036. * the cost is 2x cpu time on first block. */
  1037. assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
  1038. if ( (ms->opt.litLengthSum==0) /* first block */
  1039. && (seqStore->sequences == seqStore->sequencesStart) /* no ldm */
  1040. && (ms->window.dictLimit == ms->window.lowLimit) /* no dictionary */
  1041. && (current == ms->window.dictLimit) /* start of frame, nothing already loaded nor skipped */
  1042. && (srcSize > ZSTD_PREDEF_THRESHOLD)
  1043. ) {
  1044. ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);
  1045. }
  1046. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict);
  1047. }
  1048. size_t ZSTD_compressBlock_btopt_dictMatchState(
  1049. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1050. const void* src, size_t srcSize)
  1051. {
  1052. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_dictMatchState);
  1053. }
  1054. size_t ZSTD_compressBlock_btultra_dictMatchState(
  1055. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1056. const void* src, size_t srcSize)
  1057. {
  1058. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_dictMatchState);
  1059. }
  1060. size_t ZSTD_compressBlock_btopt_extDict(
  1061. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1062. const void* src, size_t srcSize)
  1063. {
  1064. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_extDict);
  1065. }
  1066. size_t ZSTD_compressBlock_btultra_extDict(
  1067. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  1068. const void* src, size_t srcSize)
  1069. {
  1070. return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_extDict);
  1071. }
  1072. /* note : no btultra2 variant for extDict nor dictMatchState,
  1073. * because btultra2 is not meant to work with dictionaries
  1074. * and is only specific for the first block (no prefix) */