zstd_opt.c 56 KB

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