zstd_opt.c 54 KB

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