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