Coverage Report

Created: 2025-08-11 06:32

/src/lzma-fuzz/sdk/C/LzmaEnc.c
Line
Count
Source (jump to first uncovered line)
1
/* LzmaEnc.c -- LZMA Encoder
2
2019-01-10: Igor Pavlov : Public domain */
3
4
#include "Precomp.h"
5
6
#include <string.h>
7
8
/* #define SHOW_STAT */
9
/* #define SHOW_STAT2 */
10
11
#if defined(SHOW_STAT) || defined(SHOW_STAT2)
12
#include <stdio.h>
13
#endif
14
15
#include "LzmaEnc.h"
16
17
#include "LzFind.h"
18
#ifndef _7ZIP_ST
19
#include "LzFindMt.h"
20
#endif
21
22
#ifdef SHOW_STAT
23
static unsigned g_STAT_OFFSET = 0;
24
#endif
25
26
14.1k
#define kLzmaMaxHistorySize ((UInt32)3 << 29)
27
/* #define kLzmaMaxHistorySize ((UInt32)7 << 29) */
28
29
33.0M
#define kNumTopBits 24
30
33.0M
#define kTopValue ((UInt32)1 << kNumTopBits)
31
32
8.58G
#define kNumBitModelTotalBits 11
33
8.55G
#define kBitModelTotal (1 << kNumBitModelTotalBits)
34
82.3M
#define kNumMoveBits 5
35
8.44G
#define kProbInitValue (kBitModelTotal >> 1)
36
37
100M
#define kNumMoveReducingBits 4
38
1.63M
#define kNumBitPriceShiftBits 4
39
#define kBitPrice (1 << kNumBitPriceShiftBits)
40
41
10.1k
#define REP_LEN_COUNT 64
42
43
void LzmaEncProps_Init(CLzmaEncProps *p)
44
14.1k
{
45
14.1k
  p->level = 5;
46
14.1k
  p->dictSize = p->mc = 0;
47
14.1k
  p->reduceSize = (UInt64)(Int64)-1;
48
14.1k
  p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
49
14.1k
  p->writeEndMark = 0;
50
14.1k
}
51
52
void LzmaEncProps_Normalize(CLzmaEncProps *p)
53
21.2k
{
54
21.2k
  int level = p->level;
55
21.2k
  if (level < 0) level = 5;
56
21.2k
  p->level = level;
57
  
58
21.2k
  if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level <= 7 ? (1 << 25) : (1 << 26)));
59
21.2k
  if (p->dictSize > p->reduceSize)
60
0
  {
61
0
    unsigned i;
62
0
    UInt32 reduceSize = (UInt32)p->reduceSize;
63
0
    for (i = 11; i <= 30; i++)
64
0
    {
65
0
      if (reduceSize <= ((UInt32)2 << i)) { p->dictSize = ((UInt32)2 << i); break; }
66
0
      if (reduceSize <= ((UInt32)3 << i)) { p->dictSize = ((UInt32)3 << i); break; }
67
0
    }
68
0
  }
69
70
21.2k
  if (p->lc < 0) p->lc = 3;
71
21.2k
  if (p->lp < 0) p->lp = 0;
72
21.2k
  if (p->pb < 0) p->pb = 2;
73
74
21.2k
  if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
75
21.2k
  if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
76
21.2k
  if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
77
21.2k
  if (p->numHashBytes < 0) p->numHashBytes = 4;
78
21.2k
  if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
79
  
80
21.2k
  if (p->numThreads < 0)
81
14.1k
    p->numThreads =
82
      #ifndef _7ZIP_ST
83
      ((p->btMode && p->algo) ? 2 : 1);
84
      #else
85
14.1k
      1;
86
21.2k
      #endif
87
21.2k
}
88
89
UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
90
0
{
91
0
  CLzmaEncProps props = *props2;
92
0
  LzmaEncProps_Normalize(&props);
93
0
  return props.dictSize;
94
0
}
95
96
#if (_MSC_VER >= 1400)
97
/* BSR code is fast for some new CPUs */
98
/* #define LZMA_LOG_BSR */
99
#endif
100
101
#ifdef LZMA_LOG_BSR
102
103
#define kDicLogSizeMaxCompress 32
104
105
#define BSR2_RET(pos, res) { unsigned long zz; _BitScanReverse(&zz, (pos)); res = (zz + zz) + ((pos >> (zz - 1)) & 1); }
106
107
static unsigned GetPosSlot1(UInt32 pos)
108
{
109
  unsigned res;
110
  BSR2_RET(pos, res);
111
  return res;
112
}
113
#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
114
#define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
115
116
#else
117
118
3.07M
#define kNumLogBits (9 + sizeof(size_t) / 2)
119
/* #define kNumLogBits (11 + sizeof(size_t) / 8 * 3) */
120
121
14.1k
#define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
122
123
static void LzmaEnc_FastPosInit(Byte *g_FastPos)
124
7.08k
{
125
7.08k
  unsigned slot;
126
7.08k
  g_FastPos[0] = 0;
127
7.08k
  g_FastPos[1] = 1;
128
7.08k
  g_FastPos += 2;
129
  
130
177k
  for (slot = 2; slot < kNumLogBits * 2; slot++)
131
170k
  {
132
170k
    size_t k = ((size_t)1 << ((slot >> 1) - 1));
133
170k
    size_t j;
134
58.2M
    for (j = 0; j < k; j++)
135
58.0M
      g_FastPos[j] = (Byte)slot;
136
170k
    g_FastPos += k;
137
170k
  }
138
7.08k
}
139
140
/* we can use ((limit - pos) >> 31) only if (pos < ((UInt32)1 << 31)) */
141
/*
142
#define BSR2_RET(pos, res) { unsigned zz = 6 + ((kNumLogBits - 1) & \
143
  (0 - (((((UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
144
  res = p->g_FastPos[pos >> zz] + (zz * 2); }
145
*/
146
147
/*
148
#define BSR2_RET(pos, res) { unsigned zz = 6 + ((kNumLogBits - 1) & \
149
  (0 - (((((UInt32)1 << (kNumLogBits)) - 1) - (pos >> 6)) >> 31))); \
150
  res = p->g_FastPos[pos >> zz] + (zz * 2); }
151
*/
152
153
2.87M
#define BSR2_RET(pos, res) { unsigned zz = (pos < (1 << (kNumLogBits + 6))) ? 6 : 6 + kNumLogBits - 1; \
154
2.87M
  res = p->g_FastPos[pos >> zz] + (zz * 2); }
155
156
/*
157
#define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
158
  p->g_FastPos[pos >> 6] + 12 : \
159
  p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
160
*/
161
162
3.13M
#define GetPosSlot1(pos) p->g_FastPos[pos]
163
2.76M
#define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
164
558k
#define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos & (kNumFullDistances - 1)]; else BSR2_RET(pos, res); }
165
166
#endif
167
168
169
41.4M
#define LZMA_NUM_REPS 4
170
171
typedef UInt16 CState;
172
typedef UInt16 CExtra;
173
174
typedef struct
175
{
176
  UInt32 price;
177
  CState state;
178
  CExtra extra;
179
      // 0   : normal
180
      // 1   : LIT : MATCH
181
      // > 1 : MATCH (extra-1) : LIT : REP0 (len)
182
  UInt32 len;
183
  UInt32 dist;
184
  UInt32 reps[LZMA_NUM_REPS];
185
} COptimal;
186
187
188
// 18.06
189
22.0M
#define kNumOpts (1 << 11)
190
0
#define kPackReserve (kNumOpts * 8)
191
// #define kNumOpts (1 << 12)
192
// #define kPackReserve (1 + kNumOpts * 2)
193
194
21.5M
#define kNumLenToPosStates 4
195
14.4M
#define kNumPosSlotBits 6
196
#define kDicLogSizeMin 0
197
127k
#define kDicLogSizeMax 32
198
#define kDistTableSizeMax (kDicLogSizeMax * 2)
199
200
5.08M
#define kNumAlignBits 4
201
4.91M
#define kAlignTableSize (1 << kNumAlignBits)
202
4.80M
#define kAlignMask (kAlignTableSize - 1)
203
204
568k
#define kStartPosModelIndex 4
205
24.4M
#define kEndPosModelIndex 14
206
24.8M
#define kNumFullDistances (1 << (kEndPosModelIndex >> 1))
207
208
typedef
209
#ifdef _LZMA_PROB32
210
  UInt32
211
#else
212
  UInt16
213
#endif
214
  CLzmaProb;
215
216
5.11M
#define LZMA_PB_MAX 4
217
28.3k
#define LZMA_LC_MAX 8
218
28.3k
#define LZMA_LP_MAX 4
219
220
5.08M
#define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
221
222
11.6M
#define kLenNumLowBits 3
223
6.67M
#define kLenNumLowSymbols (1 << kLenNumLowBits)
224
10.0M
#define kLenNumHighBits 8
225
8.04M
#define kLenNumHighSymbols (1 << kLenNumHighBits)
226
4.40M
#define kLenNumSymbolsTotal (kLenNumLowSymbols * 2 + kLenNumHighSymbols)
227
228
130M
#define LZMA_MATCH_LEN_MIN 2
229
4.40M
#define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1)
230
231
92.1k
#define kNumStates 12
232
233
234
typedef struct
235
{
236
  CLzmaProb low[LZMA_NUM_PB_STATES_MAX << (kLenNumLowBits + 1)];
237
  CLzmaProb high[kLenNumHighSymbols];
238
} CLenEnc;
239
240
241
typedef struct
242
{
243
  unsigned tableSize;
244
  UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
245
  // UInt32 prices1[LZMA_NUM_PB_STATES_MAX][kLenNumLowSymbols * 2];
246
  // UInt32 prices2[kLenNumSymbolsTotal];
247
} CLenPriceEnc;
248
249
#define GET_PRICE_LEN(p, posState, len) \
250
124M
    ((p)->prices[posState][(size_t)(len) - LZMA_MATCH_LEN_MIN])
251
252
/*
253
#define GET_PRICE_LEN(p, posState, len) \
254
    ((p)->prices2[(size_t)(len) - 2] + ((p)->prices1[posState][((len) - 2) & (kLenNumLowSymbols * 2 - 1)] & (((len) - 2 - kLenNumLowSymbols * 2) >> 9)))
255
*/
256
257
typedef struct
258
{
259
  UInt32 range;
260
  unsigned cache;
261
  UInt64 low;
262
  UInt64 cacheSize;
263
  Byte *buf;
264
  Byte *bufLim;
265
  Byte *bufBase;
266
  ISeqOutStream *outStream;
267
  UInt64 processed;
268
  SRes res;
269
} CRangeEnc;
270
271
272
typedef struct
273
{
274
  CLzmaProb *litProbs;
275
276
  unsigned state;
277
  UInt32 reps[LZMA_NUM_REPS];
278
279
  CLzmaProb posAlignEncoder[1 << kNumAlignBits];
280
  CLzmaProb isRep[kNumStates];
281
  CLzmaProb isRepG0[kNumStates];
282
  CLzmaProb isRepG1[kNumStates];
283
  CLzmaProb isRepG2[kNumStates];
284
  CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
285
  CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
286
287
  CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
288
  CLzmaProb posEncoders[kNumFullDistances];
289
  
290
  CLenEnc lenProbs;
291
  CLenEnc repLenProbs;
292
293
} CSaveState;
294
295
296
typedef UInt32 CProbPrice;
297
298
299
typedef struct
300
{
301
  void *matchFinderObj;
302
  IMatchFinder matchFinder;
303
304
  unsigned optCur;
305
  unsigned optEnd;
306
307
  unsigned longestMatchLen;
308
  unsigned numPairs;
309
  UInt32 numAvail;
310
311
  unsigned state;
312
  unsigned numFastBytes;
313
  unsigned additionalOffset;
314
  UInt32 reps[LZMA_NUM_REPS];
315
  unsigned lpMask, pbMask;
316
  CLzmaProb *litProbs;
317
  CRangeEnc rc;
318
319
  UInt32 backRes;
320
321
  unsigned lc, lp, pb;
322
  unsigned lclp;
323
324
  BoolInt fastMode;
325
  BoolInt writeEndMark;
326
  BoolInt finished;
327
  BoolInt multiThread;
328
  BoolInt needInit;
329
  // BoolInt _maxMode;
330
331
  UInt64 nowPos64;
332
  
333
  unsigned matchPriceCount;
334
  // unsigned alignPriceCount;
335
  int repLenEncCounter;
336
337
  unsigned distTableSize;
338
339
  UInt32 dictSize;
340
  SRes result;
341
342
  #ifndef _7ZIP_ST
343
  BoolInt mtMode;
344
  // begin of CMatchFinderMt is used in LZ thread
345
  CMatchFinderMt matchFinderMt;
346
  // end of CMatchFinderMt is used in BT and HASH threads
347
  #endif
348
349
  CMatchFinder matchFinderBase;
350
351
  #ifndef _7ZIP_ST
352
  Byte pad[128];
353
  #endif
354
  
355
  // LZ thread
356
  CProbPrice ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
357
358
  UInt32 matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
359
360
  UInt32 alignPrices[kAlignTableSize];
361
  UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
362
  UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
363
364
  CLzmaProb posAlignEncoder[1 << kNumAlignBits];
365
  CLzmaProb isRep[kNumStates];
366
  CLzmaProb isRepG0[kNumStates];
367
  CLzmaProb isRepG1[kNumStates];
368
  CLzmaProb isRepG2[kNumStates];
369
  CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
370
  CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
371
  CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
372
  CLzmaProb posEncoders[kNumFullDistances];
373
  
374
  CLenEnc lenProbs;
375
  CLenEnc repLenProbs;
376
377
  #ifndef LZMA_LOG_BSR
378
  Byte g_FastPos[1 << kNumLogBits];
379
  #endif
380
381
  CLenPriceEnc lenEnc;
382
  CLenPriceEnc repLenEnc;
383
384
  COptimal opt[kNumOpts];
385
386
  CSaveState saveState;
387
388
  #ifndef _7ZIP_ST
389
  Byte pad2[128];
390
  #endif
391
} CLzmaEnc;
392
393
394
395
0
#define COPY_ARR(dest, src, arr) memcpy(dest->arr, src->arr, sizeof(src->arr));
396
397
void LzmaEnc_SaveState(CLzmaEncHandle pp)
398
0
{
399
0
  CLzmaEnc *p = (CLzmaEnc *)pp;
400
0
  CSaveState *dest = &p->saveState;
401
  
402
0
  dest->state = p->state;
403
  
404
0
  dest->lenProbs = p->lenProbs;
405
0
  dest->repLenProbs = p->repLenProbs;
406
407
0
  COPY_ARR(dest, p, reps);
408
409
0
  COPY_ARR(dest, p, posAlignEncoder);
410
0
  COPY_ARR(dest, p, isRep);
411
0
  COPY_ARR(dest, p, isRepG0);
412
0
  COPY_ARR(dest, p, isRepG1);
413
0
  COPY_ARR(dest, p, isRepG2);
414
0
  COPY_ARR(dest, p, isMatch);
415
0
  COPY_ARR(dest, p, isRep0Long);
416
0
  COPY_ARR(dest, p, posSlotEncoder);
417
0
  COPY_ARR(dest, p, posEncoders);
418
419
0
  memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << p->lclp) * sizeof(CLzmaProb));
420
0
}
421
422
423
void LzmaEnc_RestoreState(CLzmaEncHandle pp)
424
0
{
425
0
  CLzmaEnc *dest = (CLzmaEnc *)pp;
426
0
  const CSaveState *p = &dest->saveState;
427
428
0
  dest->state = p->state;
429
430
0
  dest->lenProbs = p->lenProbs;
431
0
  dest->repLenProbs = p->repLenProbs;
432
  
433
0
  COPY_ARR(dest, p, reps);
434
  
435
0
  COPY_ARR(dest, p, posAlignEncoder);
436
0
  COPY_ARR(dest, p, isRep);
437
0
  COPY_ARR(dest, p, isRepG0);
438
0
  COPY_ARR(dest, p, isRepG1);
439
0
  COPY_ARR(dest, p, isRepG2);
440
0
  COPY_ARR(dest, p, isMatch);
441
0
  COPY_ARR(dest, p, isRep0Long);
442
0
  COPY_ARR(dest, p, posSlotEncoder);
443
0
  COPY_ARR(dest, p, posEncoders);
444
445
0
  memcpy(dest->litProbs, p->litProbs, ((UInt32)0x300 << dest->lclp) * sizeof(CLzmaProb));
446
0
}
447
448
449
450
SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
451
14.1k
{
452
14.1k
  CLzmaEnc *p = (CLzmaEnc *)pp;
453
14.1k
  CLzmaEncProps props = *props2;
454
14.1k
  LzmaEncProps_Normalize(&props);
455
456
14.1k
  if (props.lc > LZMA_LC_MAX
457
14.1k
      || props.lp > LZMA_LP_MAX
458
14.1k
      || props.pb > LZMA_PB_MAX
459
14.1k
      || props.dictSize > ((UInt64)1 << kDicLogSizeMaxCompress)
460
14.1k
      || props.dictSize > kLzmaMaxHistorySize)
461
0
    return SZ_ERROR_PARAM;
462
463
14.1k
  p->dictSize = props.dictSize;
464
14.1k
  {
465
14.1k
    unsigned fb = props.fb;
466
14.1k
    if (fb < 5)
467
0
      fb = 5;
468
14.1k
    if (fb > LZMA_MATCH_LEN_MAX)
469
0
      fb = LZMA_MATCH_LEN_MAX;
470
14.1k
    p->numFastBytes = fb;
471
14.1k
  }
472
14.1k
  p->lc = props.lc;
473
14.1k
  p->lp = props.lp;
474
14.1k
  p->pb = props.pb;
475
14.1k
  p->fastMode = (props.algo == 0);
476
  // p->_maxMode = True;
477
14.1k
  p->matchFinderBase.btMode = (Byte)(props.btMode ? 1 : 0);
478
14.1k
  {
479
14.1k
    unsigned numHashBytes = 4;
480
14.1k
    if (props.btMode)
481
12.7k
    {
482
12.7k
      if (props.numHashBytes < 2)
483
0
        numHashBytes = 2;
484
12.7k
      else if (props.numHashBytes < 4)
485
4.45k
        numHashBytes = props.numHashBytes;
486
12.7k
    }
487
14.1k
    p->matchFinderBase.numHashBytes = numHashBytes;
488
14.1k
  }
489
490
14.1k
  p->matchFinderBase.cutValue = props.mc;
491
492
14.1k
  p->writeEndMark = props.writeEndMark;
493
494
  #ifndef _7ZIP_ST
495
  /*
496
  if (newMultiThread != _multiThread)
497
  {
498
    ReleaseMatchFinder();
499
    _multiThread = newMultiThread;
500
  }
501
  */
502
  p->multiThread = (props.numThreads > 1);
503
  #endif
504
505
14.1k
  return SZ_OK;
506
14.1k
}
507
508
509
void LzmaEnc_SetDataSize(CLzmaEncHandle pp, UInt64 expectedDataSiize)
510
7.08k
{
511
7.08k
  CLzmaEnc *p = (CLzmaEnc *)pp;
512
7.08k
  p->matchFinderBase.expectedDataSize = expectedDataSiize;
513
7.08k
}
514
515
516
7.08k
#define kState_Start 0
517
802k
#define kState_LitAfterMatch 4
518
2.03M
#define kState_LitAfterRep   5
519
0
#define kState_MatchAfterLit 7
520
102k
#define kState_RepAfterLit   8
521
522
static const Byte kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4,  5,  6,   4, 5};
523
static const Byte kMatchNextStates[kNumStates]   = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
524
static const Byte kRepNextStates[kNumStates]     = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
525
static const Byte kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
526
527
7.07M
#define IsLitState(s) ((s) < 7)
528
11.5M
#define GetLenToPosState2(len) (((len) < kNumLenToPosStates - 1) ? (len) : kNumLenToPosStates - 1)
529
816k
#define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
530
531
26.1M
#define kInfinityPrice (1 << 30)
532
533
static void RangeEnc_Construct(CRangeEnc *p)
534
7.08k
{
535
7.08k
  p->outStream = NULL;
536
7.08k
  p->bufBase = NULL;
537
7.08k
}
538
539
#define RangeEnc_GetProcessed(p)       ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
540
0
#define RangeEnc_GetProcessed_sizet(p) ((size_t)(p)->processed + ((p)->buf - (p)->bufBase) + (size_t)(p)->cacheSize)
541
542
7.08k
#define RC_BUF_SIZE (1 << 16)
543
544
static int RangeEnc_Alloc(CRangeEnc *p, ISzAllocPtr alloc)
545
7.08k
{
546
7.08k
  if (!p->bufBase)
547
7.08k
  {
548
7.08k
    p->bufBase = (Byte *)ISzAlloc_Alloc(alloc, RC_BUF_SIZE);
549
7.08k
    if (!p->bufBase)
550
0
      return 0;
551
7.08k
    p->bufLim = p->bufBase + RC_BUF_SIZE;
552
7.08k
  }
553
7.08k
  return 1;
554
7.08k
}
555
556
static void RangeEnc_Free(CRangeEnc *p, ISzAllocPtr alloc)
557
7.08k
{
558
7.08k
  ISzAlloc_Free(alloc, p->bufBase);
559
7.08k
  p->bufBase = 0;
560
7.08k
}
561
562
static void RangeEnc_Init(CRangeEnc *p)
563
7.08k
{
564
  /* Stream.Init(); */
565
7.08k
  p->range = 0xFFFFFFFF;
566
7.08k
  p->cache = 0;
567
7.08k
  p->low = 0;
568
7.08k
  p->cacheSize = 0;
569
570
7.08k
  p->buf = p->bufBase;
571
572
7.08k
  p->processed = 0;
573
7.08k
  p->res = SZ_OK;
574
7.08k
}
575
576
MY_NO_INLINE static void RangeEnc_FlushStream(CRangeEnc *p)
577
7.09k
{
578
7.09k
  size_t num;
579
7.09k
  if (p->res != SZ_OK)
580
0
    return;
581
7.09k
  num = p->buf - p->bufBase;
582
7.09k
  if (num != ISeqOutStream_Write(p->outStream, p->bufBase, num))
583
0
    p->res = SZ_ERROR_WRITE;
584
7.09k
  p->processed += num;
585
7.09k
  p->buf = p->bufBase;
586
7.09k
}
587
588
MY_NO_INLINE static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
589
2.90M
{
590
2.90M
  UInt32 low = (UInt32)p->low;
591
2.90M
  unsigned high = (unsigned)(p->low >> 32);
592
2.90M
  p->low = (UInt32)(low << 8);
593
2.90M
  if (low < (UInt32)0xFF000000 || high != 0)
594
2.88M
  {
595
2.88M
    {
596
2.88M
      Byte *buf = p->buf;
597
2.88M
      *buf++ = (Byte)(p->cache + high);
598
2.88M
      p->cache = (unsigned)(low >> 24);
599
2.88M
      p->buf = buf;
600
2.88M
      if (buf == p->bufLim)
601
3
        RangeEnc_FlushStream(p);
602
2.88M
      if (p->cacheSize == 0)
603
2.86M
        return;
604
2.88M
    }
605
16.7k
    high += 0xFF;
606
16.7k
    for (;;)
607
21.1k
    {
608
21.1k
      Byte *buf = p->buf;
609
21.1k
      *buf++ = (Byte)(high);
610
21.1k
      p->buf = buf;
611
21.1k
      if (buf == p->bufLim)
612
1
        RangeEnc_FlushStream(p);
613
21.1k
      if (--p->cacheSize == 0)
614
16.7k
        return;
615
21.1k
    }
616
16.7k
  }
617
21.1k
  p->cacheSize++;
618
21.1k
}
619
620
static void RangeEnc_FlushData(CRangeEnc *p)
621
7.08k
{
622
7.08k
  int i;
623
42.5k
  for (i = 0; i < 5; i++)
624
35.4k
    RangeEnc_ShiftLow(p);
625
7.08k
}
626
627
33.0M
#define RC_NORM(p) if (range < kTopValue) { range <<= 8; RangeEnc_ShiftLow(p); }
628
629
#define RC_BIT_PRE(p, prob) \
630
32.5M
  ttt = *(prob); \
631
32.5M
  newBound = (range >> kNumBitModelTotalBits) * ttt;
632
633
// #define _LZMA_ENC_USE_BRANCH
634
635
#ifdef _LZMA_ENC_USE_BRANCH
636
637
#define RC_BIT(p, prob, bit) { \
638
  RC_BIT_PRE(p, prob) \
639
  if (bit == 0) { range = newBound; ttt += (kBitModelTotal - ttt) >> kNumMoveBits; } \
640
  else { (p)->low += newBound; range -= newBound; ttt -= ttt >> kNumMoveBits; } \
641
  *(prob) = (CLzmaProb)ttt; \
642
  RC_NORM(p) \
643
  }
644
645
#else
646
647
24.9M
#define RC_BIT(p, prob, bit) { \
648
24.9M
  UInt32 mask; \
649
24.9M
  RC_BIT_PRE(p, prob) \
650
24.9M
  mask = 0 - (UInt32)bit; \
651
24.9M
  range &= mask; \
652
24.9M
  mask &= newBound; \
653
24.9M
  range -= mask; \
654
24.9M
  (p)->low += mask; \
655
24.9M
  mask = (UInt32)bit - 1; \
656
24.9M
  range += newBound & mask; \
657
24.9M
  mask &= (kBitModelTotal - ((1 << kNumMoveBits) - 1)); \
658
24.9M
  mask += ((1 << kNumMoveBits) - 1); \
659
24.9M
  ttt += (Int32)(mask - ttt) >> kNumMoveBits; \
660
24.9M
  *(prob) = (CLzmaProb)ttt; \
661
24.9M
  RC_NORM(p) \
662
24.9M
  }
663
664
#endif
665
666
667
668
669
#define RC_BIT_0_BASE(p, prob) \
670
4.42M
  range = newBound; *(prob) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits));
671
672
#define RC_BIT_1_BASE(p, prob) \
673
3.19M
  range -= newBound; (p)->low += newBound; *(prob) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); \
674
675
#define RC_BIT_0(p, prob) \
676
3.97M
  RC_BIT_0_BASE(p, prob) \
677
3.97M
  RC_NORM(p)
678
679
#define RC_BIT_1(p, prob) \
680
2.93M
  RC_BIT_1_BASE(p, prob) \
681
2.93M
  RC_NORM(p)
682
683
static void RangeEnc_EncodeBit_0(CRangeEnc *p, CLzmaProb *prob)
684
7.08k
{
685
7.08k
  UInt32 range, ttt, newBound;
686
7.08k
  range = p->range;
687
7.08k
  RC_BIT_PRE(p, prob)
688
7.08k
  RC_BIT_0(p, prob)
689
7.08k
  p->range = range;
690
7.08k
}
691
692
static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 sym)
693
1.69M
{
694
1.69M
  UInt32 range = p->range;
695
1.69M
  sym |= 0x100;
696
1.69M
  do
697
13.5M
  {
698
13.5M
    UInt32 ttt, newBound;
699
    // RangeEnc_EncodeBit(p, probs + (sym >> 8), (sym >> 7) & 1);
700
13.5M
    CLzmaProb *prob = probs + (sym >> 8);
701
13.5M
    UInt32 bit = (sym >> 7) & 1;
702
13.5M
    sym <<= 1;
703
13.5M
    RC_BIT(p, prob, bit);
704
13.5M
  }
705
13.5M
  while (sym < 0x10000);
706
1.69M
  p->range = range;
707
1.69M
}
708
709
static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 sym, UInt32 matchByte)
710
434k
{
711
434k
  UInt32 range = p->range;
712
434k
  UInt32 offs = 0x100;
713
434k
  sym |= 0x100;
714
434k
  do
715
3.47M
  {
716
3.47M
    UInt32 ttt, newBound;
717
3.47M
    CLzmaProb *prob;
718
3.47M
    UInt32 bit;
719
3.47M
    matchByte <<= 1;
720
    // RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (sym >> 8)), (sym >> 7) & 1);
721
3.47M
    prob = probs + (offs + (matchByte & offs) + (sym >> 8));
722
3.47M
    bit = (sym >> 7) & 1;
723
3.47M
    sym <<= 1;
724
3.47M
    offs &= ~(matchByte ^ sym);
725
3.47M
    RC_BIT(p, prob, bit);
726
3.47M
  }
727
3.47M
  while (sym < 0x10000);
728
434k
  p->range = range;
729
434k
}
730
731
732
733
static void LzmaEnc_InitPriceTables(CProbPrice *ProbPrices)
734
7.08k
{
735
7.08k
  UInt32 i;
736
914k
  for (i = 0; i < (kBitModelTotal >> kNumMoveReducingBits); i++)
737
907k
  {
738
907k
    const unsigned kCyclesBits = kNumBitPriceShiftBits;
739
907k
    UInt32 w = (i << kNumMoveReducingBits) + (1 << (kNumMoveReducingBits - 1));
740
907k
    unsigned bitCount = 0;
741
907k
    unsigned j;
742
4.53M
    for (j = 0; j < kCyclesBits; j++)
743
3.62M
    {
744
3.62M
      w = w * w;
745
3.62M
      bitCount <<= 1;
746
48.8M
      while (w >= ((UInt32)1 << 16))
747
45.2M
      {
748
45.2M
        w >>= 1;
749
45.2M
        bitCount++;
750
45.2M
      }
751
3.62M
    }
752
907k
    ProbPrices[i] = (CProbPrice)((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
753
    // printf("\n%3d: %5d", i, ProbPrices[i]);
754
907k
  }
755
7.08k
}
756
757
758
#define GET_PRICE(prob, bit) \
759
1.74M
  p->ProbPrices[((prob) ^ (unsigned)(((-(int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
760
761
#define GET_PRICEa(prob, bit) \
762
49.6M
     ProbPrices[((prob) ^ (unsigned)((-((int)(bit))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
763
764
15.1M
#define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
765
22.8M
#define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
766
767
4.03M
#define GET_PRICEa_0(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
768
4.02M
#define GET_PRICEa_1(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
769
770
771
static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 sym, const CProbPrice *ProbPrices)
772
380k
{
773
380k
  UInt32 price = 0;
774
380k
  sym |= 0x100;
775
380k
  do
776
3.04M
  {
777
3.04M
    unsigned bit = sym & 1;
778
3.04M
    sym >>= 1;
779
3.04M
    price += GET_PRICEa(probs[sym], bit);
780
3.04M
  }
781
3.04M
  while (sym >= 2);
782
380k
  return price;
783
380k
}
784
785
786
static UInt32 LitEnc_Matched_GetPrice(const CLzmaProb *probs, UInt32 sym, UInt32 matchByte, const CProbPrice *ProbPrices)
787
3.73M
{
788
3.73M
  UInt32 price = 0;
789
3.73M
  UInt32 offs = 0x100;
790
3.73M
  sym |= 0x100;
791
3.73M
  do
792
29.8M
  {
793
29.8M
    matchByte <<= 1;
794
29.8M
    price += GET_PRICEa(probs[offs + (matchByte & offs) + (sym >> 8)], (sym >> 7) & 1);
795
29.8M
    sym <<= 1;
796
29.8M
    offs &= ~(matchByte ^ sym);
797
29.8M
  }
798
29.8M
  while (sym < 0x10000);
799
3.73M
  return price;
800
3.73M
}
801
802
803
static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, unsigned numBits, unsigned sym)
804
298k
{
805
298k
  UInt32 range = rc->range;
806
298k
  unsigned m = 1;
807
298k
  do
808
701k
  {
809
701k
    UInt32 ttt, newBound;
810
701k
    unsigned bit = sym & 1;
811
    // RangeEnc_EncodeBit(rc, probs + m, bit);
812
701k
    sym >>= 1;
813
701k
    RC_BIT(rc, probs + m, bit);
814
701k
    m = (m << 1) | bit;
815
701k
  }
816
701k
  while (--numBits);
817
298k
  rc->range = range;
818
298k
}
819
820
821
822
static void LenEnc_Init(CLenEnc *p)
823
14.1k
{
824
14.1k
  unsigned i;
825
3.64M
  for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << (kLenNumLowBits + 1)); i++)
826
3.62M
    p->low[i] = kProbInitValue;
827
3.64M
  for (i = 0; i < kLenNumHighSymbols; i++)
828
3.62M
    p->high[i] = kProbInitValue;
829
14.1k
}
830
831
static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, unsigned sym, unsigned posState)
832
1.20M
{
833
1.20M
  UInt32 range, ttt, newBound;
834
1.20M
  CLzmaProb *probs = p->low;
835
1.20M
  range = rc->range;
836
1.20M
  RC_BIT_PRE(rc, probs);
837
1.20M
  if (sym >= kLenNumLowSymbols)
838
163k
  {
839
163k
    RC_BIT_1(rc, probs);
840
163k
    probs += kLenNumLowSymbols;
841
163k
    RC_BIT_PRE(rc, probs);
842
163k
    if (sym >= kLenNumLowSymbols * 2)
843
86.3k
    {
844
86.3k
      RC_BIT_1(rc, probs);
845
86.3k
      rc->range = range;
846
      // RcTree_Encode(rc, p->high, kLenNumHighBits, sym - kLenNumLowSymbols * 2);
847
86.3k
      LitEnc_Encode(rc, p->high, sym - kLenNumLowSymbols * 2);
848
86.3k
      return;
849
86.3k
    }
850
77.2k
    sym -= kLenNumLowSymbols;
851
77.2k
  }
852
853
  // RcTree_Encode(rc, probs + (posState << kLenNumLowBits), kLenNumLowBits, sym);
854
1.11M
  {
855
1.11M
    unsigned m;
856
1.11M
    unsigned bit;
857
1.11M
    RC_BIT_0(rc, probs);
858
1.11M
    probs += (posState << (1 + kLenNumLowBits));
859
1.11M
    bit = (sym >> 2)    ; RC_BIT(rc, probs + 1, bit); m = (1 << 1) + bit;
860
1.11M
    bit = (sym >> 1) & 1; RC_BIT(rc, probs + m, bit); m = (m << 1) + bit;
861
1.11M
    bit =  sym       & 1; RC_BIT(rc, probs + m, bit);
862
1.11M
    rc->range = range;
863
1.11M
  }
864
1.11M
}
865
866
static void SetPrices_3(const CLzmaProb *probs, UInt32 startPrice, UInt32 *prices, const CProbPrice *ProbPrices)
867
324k
{
868
324k
  unsigned i;
869
1.62M
  for (i = 0; i < 8; i += 2)
870
1.29M
  {
871
1.29M
    UInt32 price = startPrice;
872
1.29M
    UInt32 prob;
873
1.29M
    price += GET_PRICEa(probs[1           ], (i >> 2));
874
1.29M
    price += GET_PRICEa(probs[2 + (i >> 2)], (i >> 1) & 1);
875
1.29M
    prob = probs[4 + (i >> 1)];
876
1.29M
    prices[i    ] = price + GET_PRICEa_0(prob);
877
1.29M
    prices[i + 1] = price + GET_PRICEa_1(prob);
878
1.29M
  }
879
324k
}
880
881
882
MY_NO_INLINE static void MY_FAST_CALL LenPriceEnc_UpdateTables(
883
    CLenPriceEnc *p,
884
    unsigned numPosStates,
885
    const CLenEnc *enc,
886
    const CProbPrice *ProbPrices)
887
22.3k
{
888
22.3k
  UInt32 b;
889
 
890
22.3k
  {
891
22.3k
    unsigned prob = enc->low[0];
892
22.3k
    UInt32 a, c;
893
22.3k
    unsigned posState;
894
22.3k
    b = GET_PRICEa_1(prob);
895
22.3k
    a = GET_PRICEa_0(prob);
896
22.3k
    c = b + GET_PRICEa_0(enc->low[kLenNumLowSymbols]);
897
184k
    for (posState = 0; posState < numPosStates; posState++)
898
162k
    {
899
162k
      UInt32 *prices = p->prices[posState];
900
162k
      const CLzmaProb *probs = enc->low + (posState << (1 + kLenNumLowBits));
901
162k
      SetPrices_3(probs, a, prices, ProbPrices);
902
162k
      SetPrices_3(probs + kLenNumLowSymbols, c, prices + kLenNumLowSymbols, ProbPrices);
903
162k
    }
904
22.3k
  }
905
906
  /*
907
  {
908
    unsigned i;
909
    UInt32 b;
910
    a = GET_PRICEa_0(enc->low[0]);
911
    for (i = 0; i < kLenNumLowSymbols; i++)
912
      p->prices2[i] = a;
913
    a = GET_PRICEa_1(enc->low[0]);
914
    b = a + GET_PRICEa_0(enc->low[kLenNumLowSymbols]);
915
    for (i = kLenNumLowSymbols; i < kLenNumLowSymbols * 2; i++)
916
      p->prices2[i] = b;
917
    a += GET_PRICEa_1(enc->low[kLenNumLowSymbols]);
918
  }
919
  */
920
 
921
  // p->counter = numSymbols;
922
  // p->counter = 64;
923
924
22.3k
  {
925
22.3k
    unsigned i = p->tableSize;
926
    
927
22.3k
    if (i > kLenNumLowSymbols * 2)
928
12.4k
    {
929
12.4k
      const CLzmaProb *probs = enc->high;
930
12.4k
      UInt32 *prices = p->prices[0] + kLenNumLowSymbols * 2;
931
12.4k
      i -= kLenNumLowSymbols * 2 - 1;
932
12.4k
      i >>= 1;
933
12.4k
      b += GET_PRICEa_1(enc->low[kLenNumLowSymbols]);
934
12.4k
      do
935
1.01M
      {
936
        /*
937
        p->prices2[i] = a +
938
        // RcTree_GetPrice(enc->high, kLenNumHighBits, i - kLenNumLowSymbols * 2, ProbPrices);
939
        LitEnc_GetPrice(probs, i - kLenNumLowSymbols * 2, ProbPrices);
940
        */
941
        // UInt32 price = a + RcTree_GetPrice(probs, kLenNumHighBits - 1, sym, ProbPrices);
942
1.01M
        unsigned sym = --i + (1 << (kLenNumHighBits - 1));
943
1.01M
        UInt32 price = b;
944
1.01M
        do
945
7.10M
        {
946
7.10M
          unsigned bit = sym & 1;
947
7.10M
          sym >>= 1;
948
7.10M
          price += GET_PRICEa(probs[sym], bit);
949
7.10M
        }
950
7.10M
        while (sym >= 2);
951
952
1.01M
        {
953
1.01M
          unsigned prob = probs[(size_t)i + (1 << (kLenNumHighBits - 1))];
954
1.01M
          prices[(size_t)i * 2    ] = price + GET_PRICEa_0(prob);
955
1.01M
          prices[(size_t)i * 2 + 1] = price + GET_PRICEa_1(prob);
956
1.01M
        }
957
1.01M
      }
958
1.01M
      while (i);
959
960
12.4k
      {
961
12.4k
        unsigned posState;
962
12.4k
        size_t num = (p->tableSize - kLenNumLowSymbols * 2) * sizeof(p->prices[0][0]);
963
108k
        for (posState = 1; posState < numPosStates; posState++)
964
96.5k
          memcpy(p->prices[posState] + kLenNumLowSymbols * 2, p->prices[0] + kLenNumLowSymbols * 2, num);
965
12.4k
      }
966
12.4k
    }
967
22.3k
  }
968
22.3k
}
969
970
/*
971
  #ifdef SHOW_STAT
972
  g_STAT_OFFSET += num;
973
  printf("\n MovePos %u", num);
974
  #endif
975
*/
976
  
977
360k
#define MOVE_POS(p, num) { \
978
360k
    p->additionalOffset += (num); \
979
360k
    p->matchFinder.Skip(p->matchFinderObj, (UInt32)(num)); }
980
981
982
static unsigned ReadMatchDistances(CLzmaEnc *p, unsigned *numPairsRes)
983
5.97M
{
984
5.97M
  unsigned numPairs;
985
  
986
5.97M
  p->additionalOffset++;
987
5.97M
  p->numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
988
5.97M
  numPairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matches);
989
5.97M
  *numPairsRes = numPairs;
990
  
991
  #ifdef SHOW_STAT
992
  printf("\n i = %u numPairs = %u    ", g_STAT_OFFSET, numPairs / 2);
993
  g_STAT_OFFSET++;
994
  {
995
    unsigned i;
996
    for (i = 0; i < numPairs; i += 2)
997
      printf("%2u %6u   | ", p->matches[i], p->matches[i + 1]);
998
  }
999
  #endif
1000
  
1001
5.97M
  if (numPairs == 0)
1002
1.42M
    return 0;
1003
4.55M
  {
1004
4.55M
    unsigned len = p->matches[(size_t)numPairs - 2];
1005
4.55M
    if (len != p->numFastBytes)
1006
4.38M
      return len;
1007
172k
    {
1008
172k
      UInt32 numAvail = p->numAvail;
1009
172k
      if (numAvail > LZMA_MATCH_LEN_MAX)
1010
162k
        numAvail = LZMA_MATCH_LEN_MAX;
1011
172k
      {
1012
172k
        const Byte *p1 = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1013
172k
        const Byte *p2 = p1 + len;
1014
172k
        ptrdiff_t dif = (ptrdiff_t)-1 - p->matches[(size_t)numPairs - 1];
1015
172k
        const Byte *lim = p1 + numAvail;
1016
3.37M
        for (; p2 != lim && *p2 == p2[dif]; p2++)
1017
3.19M
        {}
1018
172k
        return (unsigned)(p2 - p1);
1019
4.55M
      }
1020
4.55M
    }
1021
4.55M
  }
1022
4.55M
}
1023
1024
6.11M
#define MARK_LIT ((UInt32)(Int32)-1)
1025
1026
805k
#define MakeAs_Lit(p)       { (p)->dist = MARK_LIT; (p)->extra = 0; }
1027
180k
#define MakeAs_ShortRep(p)  { (p)->dist = 0; (p)->extra = 0; }
1028
900k
#define IsShortRep(p)       ((p)->dist == 0)
1029
1030
1031
#define GetPrice_ShortRep(p, state, posState) \
1032
224k
  ( GET_PRICE_0(p->isRepG0[state]) + GET_PRICE_0(p->isRep0Long[state][posState]))
1033
1034
2.93M
#define GetPrice_Rep_0(p, state, posState) ( \
1035
2.93M
    GET_PRICE_1(p->isMatch[state][posState]) \
1036
2.93M
  + GET_PRICE_1(p->isRep0Long[state][posState])) \
1037
2.93M
  + GET_PRICE_1(p->isRep[state]) \
1038
2.93M
  + GET_PRICE_0(p->isRepG0[state])
1039
  
1040
MY_FORCE_INLINE
1041
static UInt32 GetPrice_PureRep(const CLzmaEnc *p, unsigned repIndex, size_t state, size_t posState)
1042
4.49M
{
1043
4.49M
  UInt32 price;
1044
4.49M
  UInt32 prob = p->isRepG0[state];
1045
4.49M
  if (repIndex == 0)
1046
1.71M
  {
1047
1.71M
    price = GET_PRICE_0(prob);
1048
1.71M
    price += GET_PRICE_1(p->isRep0Long[state][posState]);
1049
1.71M
  }
1050
2.78M
  else
1051
2.78M
  {
1052
2.78M
    price = GET_PRICE_1(prob);
1053
2.78M
    prob = p->isRepG1[state];
1054
2.78M
    if (repIndex == 1)
1055
1.03M
      price += GET_PRICE_0(prob);
1056
1.74M
    else
1057
1.74M
    {
1058
1.74M
      price += GET_PRICE_1(prob);
1059
1.74M
      price += GET_PRICE(p->isRepG2[state], repIndex - 2);
1060
1.74M
    }
1061
2.78M
  }
1062
4.49M
  return price;
1063
4.49M
}
1064
1065
1066
static unsigned Backward(CLzmaEnc *p, unsigned cur)
1067
107k
{
1068
107k
  unsigned wr = cur + 1;
1069
107k
  p->optEnd = wr;
1070
1071
107k
  for (;;)
1072
1.14M
  {
1073
1.14M
    UInt32 dist = p->opt[cur].dist;
1074
1.14M
    unsigned len = (unsigned)p->opt[cur].len;
1075
1.14M
    unsigned extra = (unsigned)p->opt[cur].extra;
1076
1.14M
    cur -= len;
1077
1078
1.14M
    if (extra)
1079
72.9k
    {
1080
72.9k
      wr--;
1081
72.9k
      p->opt[wr].len = (UInt32)len;
1082
72.9k
      cur -= extra;
1083
72.9k
      len = extra;
1084
72.9k
      if (extra == 1)
1085
809
      {
1086
809
        p->opt[wr].dist = dist;
1087
809
        dist = MARK_LIT;
1088
809
      }
1089
72.1k
      else
1090
72.1k
      {
1091
72.1k
        p->opt[wr].dist = 0;
1092
72.1k
        len--;
1093
72.1k
        wr--;
1094
72.1k
        p->opt[wr].dist = MARK_LIT;
1095
72.1k
        p->opt[wr].len = 1;
1096
72.1k
      }
1097
72.9k
    }
1098
1099
1.14M
    if (cur == 0)
1100
107k
    {
1101
107k
      p->backRes = dist;
1102
107k
      p->optCur = wr;
1103
107k
      return len;
1104
107k
    }
1105
    
1106
1.03M
    wr--;
1107
1.03M
    p->opt[wr].dist = dist;
1108
1.03M
    p->opt[wr].len = (UInt32)len;
1109
1.03M
  }
1110
107k
}
1111
1112
1113
1114
#define LIT_PROBS(pos, prevByte) \
1115
6.14M
  (p->litProbs + (UInt32)3 * (((((pos) << 8) + (prevByte)) & p->lpMask) << p->lc))
1116
1117
1118
static unsigned GetOptimum(CLzmaEnc *p, UInt32 position)
1119
549k
{
1120
549k
  unsigned last, cur;
1121
549k
  UInt32 reps[LZMA_NUM_REPS];
1122
549k
  unsigned repLens[LZMA_NUM_REPS];
1123
549k
  UInt32 *matches;
1124
1125
549k
  {
1126
549k
    UInt32 numAvail;
1127
549k
    unsigned numPairs, mainLen, repMaxIndex, i, posState;
1128
549k
    UInt32 matchPrice, repMatchPrice;
1129
549k
    const Byte *data;
1130
549k
    Byte curByte, matchByte;
1131
    
1132
549k
    p->optCur = p->optEnd = 0;
1133
    
1134
549k
    if (p->additionalOffset == 0)
1135
531k
      mainLen = ReadMatchDistances(p, &numPairs);
1136
17.8k
    else
1137
17.8k
    {
1138
17.8k
      mainLen = p->longestMatchLen;
1139
17.8k
      numPairs = p->numPairs;
1140
17.8k
    }
1141
    
1142
549k
    numAvail = p->numAvail;
1143
549k
    if (numAvail < 2)
1144
2.31k
    {
1145
2.31k
      p->backRes = MARK_LIT;
1146
2.31k
      return 1;
1147
2.31k
    }
1148
547k
    if (numAvail > LZMA_MATCH_LEN_MAX)
1149
445k
      numAvail = LZMA_MATCH_LEN_MAX;
1150
    
1151
547k
    data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1152
547k
    repMaxIndex = 0;
1153
    
1154
2.73M
    for (i = 0; i < LZMA_NUM_REPS; i++)
1155
2.18M
    {
1156
2.18M
      unsigned len;
1157
2.18M
      const Byte *data2;
1158
2.18M
      reps[i] = p->reps[i];
1159
2.18M
      data2 = data - reps[i];
1160
2.18M
      if (data[0] != data2[0] || data[1] != data2[1])
1161
2.09M
      {
1162
2.09M
        repLens[i] = 0;
1163
2.09M
        continue;
1164
2.09M
      }
1165
3.24M
      for (len = 2; len < numAvail && data[len] == data2[len]; len++)
1166
3.14M
      {}
1167
93.8k
      repLens[i] = len;
1168
93.8k
      if (len > repLens[repMaxIndex])
1169
39.2k
        repMaxIndex = i;
1170
93.8k
    }
1171
    
1172
547k
    if (repLens[repMaxIndex] >= p->numFastBytes)
1173
25.0k
    {
1174
25.0k
      unsigned len;
1175
25.0k
      p->backRes = (UInt32)repMaxIndex;
1176
25.0k
      len = repLens[repMaxIndex];
1177
25.0k
      MOVE_POS(p, len - 1)
1178
25.0k
      return len;
1179
25.0k
    }
1180
    
1181
522k
    matches = p->matches;
1182
    
1183
522k
    if (mainLen >= p->numFastBytes)
1184
30.2k
    {
1185
30.2k
      p->backRes = matches[(size_t)numPairs - 1] + LZMA_NUM_REPS;
1186
30.2k
      MOVE_POS(p, mainLen - 1)
1187
30.2k
      return mainLen;
1188
30.2k
    }
1189
    
1190
491k
    curByte = *data;
1191
491k
    matchByte = *(data - reps[0]);
1192
1193
491k
    last = repLens[repMaxIndex];
1194
491k
    if (last <= mainLen)
1195
488k
      last = mainLen;
1196
    
1197
491k
    if (last < 2 && curByte != matchByte)
1198
370k
    {
1199
370k
      p->backRes = MARK_LIT;
1200
370k
      return 1;
1201
370k
    }
1202
    
1203
121k
    p->opt[0].state = (CState)p->state;
1204
    
1205
121k
    posState = (position & p->pbMask);
1206
    
1207
121k
    {
1208
121k
      const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
1209
121k
      p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
1210
121k
        (!IsLitState(p->state) ?
1211
36.7k
          LitEnc_Matched_GetPrice(probs, curByte, matchByte, p->ProbPrices) :
1212
121k
          LitEnc_GetPrice(probs, curByte, p->ProbPrices));
1213
121k
    }
1214
1215
121k
    MakeAs_Lit(&p->opt[1]);
1216
    
1217
121k
    matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
1218
121k
    repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
1219
    
1220
    // 18.06
1221
121k
    if (matchByte == curByte && repLens[0] == 0)
1222
23.1k
    {
1223
23.1k
      UInt32 shortRepPrice = repMatchPrice + GetPrice_ShortRep(p, p->state, posState);
1224
23.1k
      if (shortRepPrice < p->opt[1].price)
1225
21.9k
      {
1226
21.9k
        p->opt[1].price = shortRepPrice;
1227
21.9k
        MakeAs_ShortRep(&p->opt[1]);
1228
21.9k
      }
1229
23.1k
      if (last < 2)
1230
14.0k
      {
1231
14.0k
        p->backRes = p->opt[1].dist;
1232
14.0k
        return 1;
1233
14.0k
      }
1234
23.1k
    }
1235
   
1236
107k
    p->opt[1].len = 1;
1237
    
1238
107k
    p->opt[0].reps[0] = reps[0];
1239
107k
    p->opt[0].reps[1] = reps[1];
1240
107k
    p->opt[0].reps[2] = reps[2];
1241
107k
    p->opt[0].reps[3] = reps[3];
1242
    
1243
    // ---------- REP ----------
1244
    
1245
537k
    for (i = 0; i < LZMA_NUM_REPS; i++)
1246
429k
    {
1247
429k
      unsigned repLen = repLens[i];
1248
429k
      UInt32 price;
1249
429k
      if (repLen < 2)
1250
394k
        continue;
1251
35.0k
      price = repMatchPrice + GetPrice_PureRep(p, i, p->state, posState);
1252
35.0k
      do
1253
336k
      {
1254
336k
        UInt32 price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState, repLen);
1255
336k
        COptimal *opt = &p->opt[repLen];
1256
336k
        if (price2 < opt->price)
1257
240k
        {
1258
240k
          opt->price = price2;
1259
240k
          opt->len = (UInt32)repLen;
1260
240k
          opt->dist = (UInt32)i;
1261
240k
          opt->extra = 0;
1262
240k
        }
1263
336k
      }
1264
336k
      while (--repLen >= 2);
1265
35.0k
    }
1266
    
1267
    
1268
    // ---------- MATCH ----------
1269
107k
    {
1270
107k
      unsigned len = repLens[0] + 1;
1271
107k
      if (len <= mainLen)
1272
99.7k
      {
1273
99.7k
        unsigned offs = 0;
1274
99.7k
        UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
1275
1276
99.7k
        if (len < 2)
1277
98.7k
          len = 2;
1278
999
        else
1279
3.61k
          while (len > matches[offs])
1280
2.61k
            offs += 2;
1281
    
1282
158k
        for (; ; len++)
1283
258k
        {
1284
258k
          COptimal *opt;
1285
258k
          UInt32 dist = matches[(size_t)offs + 1];
1286
258k
          UInt32 price = normalMatchPrice + GET_PRICE_LEN(&p->lenEnc, posState, len);
1287
258k
          unsigned lenToPosState = GetLenToPosState(len);
1288
       
1289
258k
          if (dist < kNumFullDistances)
1290
162k
            price += p->distancesPrices[lenToPosState][dist & (kNumFullDistances - 1)];
1291
95.6k
          else
1292
95.6k
          {
1293
95.6k
            unsigned slot;
1294
95.6k
            GetPosSlot2(dist, slot);
1295
95.6k
            price += p->alignPrices[dist & kAlignMask];
1296
95.6k
            price += p->posSlotPrices[lenToPosState][slot];
1297
95.6k
          }
1298
          
1299
258k
          opt = &p->opt[len];
1300
          
1301
258k
          if (price < opt->price)
1302
216k
          {
1303
216k
            opt->price = price;
1304
216k
            opt->len = (UInt32)len;
1305
216k
            opt->dist = dist + LZMA_NUM_REPS;
1306
216k
            opt->extra = 0;
1307
216k
          }
1308
          
1309
258k
          if (len == matches[offs])
1310
131k
          {
1311
131k
            offs += 2;
1312
131k
            if (offs == numPairs)
1313
99.7k
              break;
1314
131k
          }
1315
258k
        }
1316
99.7k
      }
1317
107k
    }
1318
    
1319
1320
107k
    cur = 0;
1321
1322
    #ifdef SHOW_STAT2
1323
    /* if (position >= 0) */
1324
    {
1325
      unsigned i;
1326
      printf("\n pos = %4X", position);
1327
      for (i = cur; i <= last; i++)
1328
      printf("\nprice[%4X] = %u", position - cur + i, p->opt[i].price);
1329
    }
1330
    #endif
1331
107k
  }
1332
1333
1334
  
1335
  // ---------- Optimal Parsing ----------
1336
1337
0
  for (;;)
1338
3.87M
  {
1339
3.87M
    unsigned numAvail;
1340
3.87M
    UInt32 numAvailFull;
1341
3.87M
    unsigned newLen, numPairs, prev, state, posState, startLen;
1342
3.87M
    UInt32 litPrice, matchPrice, repMatchPrice;
1343
3.87M
    BoolInt nextIsLit;
1344
3.87M
    Byte curByte, matchByte;
1345
3.87M
    const Byte *data;
1346
3.87M
    COptimal *curOpt, *nextOpt;
1347
1348
3.87M
    if (++cur == last)
1349
89.0k
      break;
1350
    
1351
    // 18.06
1352
3.78M
    if (cur >= kNumOpts - 64)
1353
449
    {
1354
449
      unsigned j, best;
1355
449
      UInt32 price = p->opt[cur].price;
1356
449
      best = cur;
1357
10.4k
      for (j = cur + 1; j <= last; j++)
1358
9.99k
      {
1359
9.99k
        UInt32 price2 = p->opt[j].price;
1360
9.99k
        if (price >= price2)
1361
907
        {
1362
907
          price = price2;
1363
907
          best = j;
1364
907
        }
1365
9.99k
      }
1366
449
      {
1367
449
        unsigned delta = best - cur;
1368
449
        if (delta != 0)
1369
243
        {
1370
243
          MOVE_POS(p, delta);
1371
243
        }
1372
449
      }
1373
449
      cur = best;
1374
449
      break;
1375
449
    }
1376
1377
3.78M
    newLen = ReadMatchDistances(p, &numPairs);
1378
    
1379
3.78M
    if (newLen >= p->numFastBytes)
1380
17.8k
    {
1381
17.8k
      p->numPairs = numPairs;
1382
17.8k
      p->longestMatchLen = newLen;
1383
17.8k
      break;
1384
17.8k
    }
1385
    
1386
3.76M
    curOpt = &p->opt[cur];
1387
1388
3.76M
    position++;
1389
1390
    // we need that check here, if skip_items in p->opt are possible
1391
    /*
1392
    if (curOpt->price >= kInfinityPrice)
1393
      continue;
1394
    */
1395
1396
3.76M
    prev = cur - curOpt->len;
1397
1398
3.76M
    if (curOpt->len == 1)
1399
900k
    {
1400
900k
      state = (unsigned)p->opt[prev].state;
1401
900k
      if (IsShortRep(curOpt))
1402
160k
        state = kShortRepNextStates[state];
1403
739k
      else
1404
739k
        state = kLiteralNextStates[state];
1405
900k
    }
1406
2.86M
    else
1407
2.86M
    {
1408
2.86M
      const COptimal *prevOpt;
1409
2.86M
      UInt32 b0;
1410
2.86M
      UInt32 dist = curOpt->dist;
1411
1412
2.86M
      if (curOpt->extra)
1413
101k
      {
1414
101k
        prev -= (unsigned)curOpt->extra;
1415
101k
        state = kState_RepAfterLit;
1416
101k
        if (curOpt->extra == 1)
1417
1.19k
          state = (dist < LZMA_NUM_REPS ? kState_RepAfterLit : kState_MatchAfterLit);
1418
101k
      }
1419
2.76M
      else
1420
2.76M
      {
1421
2.76M
        state = (unsigned)p->opt[prev].state;
1422
2.76M
        if (dist < LZMA_NUM_REPS)
1423
1.69M
          state = kRepNextStates[state];
1424
1.07M
        else
1425
1.07M
          state = kMatchNextStates[state];
1426
2.76M
      }
1427
1428
2.86M
      prevOpt = &p->opt[prev];
1429
2.86M
      b0 = prevOpt->reps[0];
1430
1431
2.86M
      if (dist < LZMA_NUM_REPS)
1432
1.78M
      {
1433
1.78M
        if (dist == 0)
1434
683k
        {
1435
683k
          reps[0] = b0;
1436
683k
          reps[1] = prevOpt->reps[1];
1437
683k
          reps[2] = prevOpt->reps[2];
1438
683k
          reps[3] = prevOpt->reps[3];
1439
683k
        }
1440
1.10M
        else
1441
1.10M
        {
1442
1.10M
          reps[1] = b0;
1443
1.10M
          b0 = prevOpt->reps[1];
1444
1.10M
          if (dist == 1)
1445
656k
          {
1446
656k
            reps[0] = b0;
1447
656k
            reps[2] = prevOpt->reps[2];
1448
656k
            reps[3] = prevOpt->reps[3];
1449
656k
          }
1450
445k
          else
1451
445k
          {
1452
445k
            reps[2] = b0;
1453
445k
            reps[0] = prevOpt->reps[dist];
1454
445k
            reps[3] = prevOpt->reps[dist ^ 1];
1455
445k
          }
1456
1.10M
        }
1457
1.78M
      }
1458
1.07M
      else
1459
1.07M
      {
1460
1.07M
        reps[0] = (dist - LZMA_NUM_REPS + 1);
1461
1.07M
        reps[1] = b0;
1462
1.07M
        reps[2] = prevOpt->reps[1];
1463
1.07M
        reps[3] = prevOpt->reps[2];
1464
1.07M
      }
1465
2.86M
    }
1466
    
1467
3.76M
    curOpt->state = (CState)state;
1468
3.76M
    curOpt->reps[0] = reps[0];
1469
3.76M
    curOpt->reps[1] = reps[1];
1470
3.76M
    curOpt->reps[2] = reps[2];
1471
3.76M
    curOpt->reps[3] = reps[3];
1472
1473
3.76M
    data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1474
3.76M
    curByte = *data;
1475
3.76M
    matchByte = *(data - reps[0]);
1476
1477
3.76M
    posState = (position & p->pbMask);
1478
1479
    /*
1480
    The order of Price checks:
1481
       <  LIT
1482
       <= SHORT_REP
1483
       <  LIT : REP_0
1484
       <  REP    [ : LIT : REP_0 ]
1485
       <  MATCH  [ : LIT : REP_0 ]
1486
    */
1487
1488
3.76M
    {
1489
3.76M
      UInt32 curPrice = curOpt->price;
1490
3.76M
      unsigned prob = p->isMatch[state][posState];
1491
3.76M
      matchPrice = curPrice + GET_PRICE_1(prob);
1492
3.76M
      litPrice = curPrice + GET_PRICE_0(prob);
1493
3.76M
    }
1494
1495
3.76M
    nextOpt = &p->opt[(size_t)cur + 1];
1496
3.76M
    nextIsLit = False;
1497
1498
    // here we can allow skip_items in p->opt, if we don't check (nextOpt->price < kInfinityPrice)
1499
    // 18.new.06
1500
3.76M
    if ((nextOpt->price < kInfinityPrice
1501
        // && !IsLitState(state)
1502
3.76M
        && matchByte == curByte)
1503
3.76M
        || litPrice > nextOpt->price
1504
3.76M
        )
1505
2.61M
      litPrice = 0;
1506
1.14M
    else
1507
1.14M
    {
1508
1.14M
      const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
1509
1.14M
      litPrice += (!IsLitState(state) ?
1510
852k
          LitEnc_Matched_GetPrice(probs, curByte, matchByte, p->ProbPrices) :
1511
1.14M
          LitEnc_GetPrice(probs, curByte, p->ProbPrices));
1512
      
1513
1.14M
      if (litPrice < nextOpt->price)
1514
684k
      {
1515
684k
        nextOpt->price = litPrice;
1516
684k
        nextOpt->len = 1;
1517
684k
        MakeAs_Lit(nextOpt);
1518
684k
        nextIsLit = True;
1519
684k
      }
1520
1.14M
    }
1521
1522
3.76M
    repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
1523
    
1524
3.76M
    numAvailFull = p->numAvail;
1525
3.76M
    {
1526
3.76M
      unsigned temp = kNumOpts - 1 - cur;
1527
3.76M
      if (numAvailFull > temp)
1528
3.00M
        numAvailFull = (UInt32)temp;
1529
3.76M
    }
1530
1531
    // 18.06
1532
    // ---------- SHORT_REP ----------
1533
3.76M
    if (IsLitState(state)) // 18.new
1534
739k
    if (matchByte == curByte)
1535
288k
    if (repMatchPrice < nextOpt->price) // 18.new
1536
    // if (numAvailFull < 2 || data[1] != *(data - reps[0] + 1))
1537
202k
    if (
1538
        // nextOpt->price >= kInfinityPrice ||
1539
202k
        nextOpt->len < 2   // we can check nextOpt->len, if skip items are not allowed in p->opt
1540
202k
        || (nextOpt->dist != 0
1541
            // && nextOpt->extra <= 1 // 17.old
1542
195k
            )
1543
202k
        )
1544
201k
    {
1545
201k
      UInt32 shortRepPrice = repMatchPrice + GetPrice_ShortRep(p, state, posState);
1546
      // if (shortRepPrice <= nextOpt->price) // 17.old
1547
201k
      if (shortRepPrice < nextOpt->price)  // 18.new
1548
158k
      {
1549
158k
        nextOpt->price = shortRepPrice;
1550
158k
        nextOpt->len = 1;
1551
158k
        MakeAs_ShortRep(nextOpt);
1552
158k
        nextIsLit = False;
1553
158k
      }
1554
201k
    }
1555
    
1556
3.76M
    if (numAvailFull < 2)
1557
2.44k
      continue;
1558
3.76M
    numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes);
1559
1560
    // numAvail <= p->numFastBytes
1561
1562
    // ---------- LIT : REP_0 ----------
1563
1564
3.76M
    if (!nextIsLit
1565
3.76M
        && litPrice != 0 // 18.new
1566
3.76M
        && matchByte != curByte
1567
3.76M
        && numAvailFull > 2)
1568
462k
    {
1569
462k
      const Byte *data2 = data - reps[0];
1570
462k
      if (data[1] == data2[1] && data[2] == data2[2])
1571
96.0k
      {
1572
96.0k
        unsigned len;
1573
96.0k
        unsigned limit = p->numFastBytes + 1;
1574
96.0k
        if (limit > numAvailFull)
1575
6.21k
          limit = numAvailFull;
1576
249k
        for (len = 3; len < limit && data[len] == data2[len]; len++)
1577
153k
        {}
1578
        
1579
96.0k
        {
1580
96.0k
          unsigned state2 = kLiteralNextStates[state];
1581
96.0k
          unsigned posState2 = (position + 1) & p->pbMask;
1582
96.0k
          UInt32 price = litPrice + GetPrice_Rep_0(p, state2, posState2);
1583
96.0k
          {
1584
96.0k
            unsigned offset = cur + len;
1585
1586
96.0k
            if (last < offset)
1587
3.89k
              last = offset;
1588
          
1589
            // do
1590
96.0k
            {
1591
96.0k
              UInt32 price2;
1592
96.0k
              COptimal *opt;
1593
96.0k
              len--;
1594
              // price2 = price + GetPrice_Len_Rep_0(p, len, state2, posState2);
1595
96.0k
              price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState2, len);
1596
1597
96.0k
              opt = &p->opt[offset];
1598
              // offset--;
1599
96.0k
              if (price2 < opt->price)
1600
8.32k
              {
1601
8.32k
                opt->price = price2;
1602
8.32k
                opt->len = (UInt32)len;
1603
8.32k
                opt->dist = 0;
1604
8.32k
                opt->extra = 1;
1605
8.32k
              }
1606
96.0k
            }
1607
            // while (len >= 3);
1608
96.0k
          }
1609
96.0k
        }
1610
96.0k
      }
1611
462k
    }
1612
    
1613
3.76M
    startLen = 2; /* speed optimization */
1614
1615
3.76M
    {
1616
      // ---------- REP ----------
1617
3.76M
      unsigned repIndex = 0; // 17.old
1618
      // unsigned repIndex = IsLitState(state) ? 0 : 1; // 18.notused
1619
18.8M
      for (; repIndex < LZMA_NUM_REPS; repIndex++)
1620
15.0M
      {
1621
15.0M
        unsigned len;
1622
15.0M
        UInt32 price;
1623
15.0M
        const Byte *data2 = data - reps[repIndex];
1624
15.0M
        if (data[0] != data2[0] || data[1] != data2[1])
1625
10.5M
          continue;
1626
        
1627
107M
        for (len = 2; len < numAvail && data[len] == data2[len]; len++)
1628
102M
        {}
1629
        
1630
        // if (len < startLen) continue; // 18.new: speed optimization
1631
1632
4.45M
        {
1633
4.45M
          unsigned offset = cur + len;
1634
4.45M
          if (last < offset)
1635
257k
            last = offset;
1636
4.45M
        }
1637
4.45M
        {
1638
4.45M
          unsigned len2 = len;
1639
4.45M
          price = repMatchPrice + GetPrice_PureRep(p, repIndex, state, posState);
1640
4.45M
          do
1641
107M
          {
1642
107M
            UInt32 price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState, len2);
1643
107M
            COptimal *opt = &p->opt[cur + len2];
1644
107M
            if (price2 < opt->price)
1645
2.80M
            {
1646
2.80M
              opt->price = price2;
1647
2.80M
              opt->len = (UInt32)len2;
1648
2.80M
              opt->dist = (UInt32)repIndex;
1649
2.80M
              opt->extra = 0;
1650
2.80M
            }
1651
107M
          }
1652
107M
          while (--len2 >= 2);
1653
4.45M
        }
1654
        
1655
4.45M
        if (repIndex == 0) startLen = len + 1;  // 17.old
1656
        // startLen = len + 1; // 18.new
1657
1658
        /* if (_maxMode) */
1659
4.45M
        {
1660
          // ---------- REP : LIT : REP_0 ----------
1661
          // numFastBytes + 1 + numFastBytes
1662
1663
4.45M
          unsigned len2 = len + 1;
1664
4.45M
          unsigned limit = len2 + p->numFastBytes;
1665
4.45M
          if (limit > numAvailFull)
1666
417k
            limit = numAvailFull;
1667
          
1668
4.45M
          len2 += 2;
1669
4.45M
          if (len2 <= limit)
1670
4.36M
          if (data[len2 - 2] == data2[len2 - 2])
1671
2.44M
          if (data[len2 - 1] == data2[len2 - 1])
1672
2.03M
          {
1673
2.03M
            unsigned state2 = kRepNextStates[state];
1674
2.03M
            unsigned posState2 = (position + len) & p->pbMask;
1675
2.03M
            price += GET_PRICE_LEN(&p->repLenEnc, posState, len)
1676
2.03M
                + GET_PRICE_0(p->isMatch[state2][posState2])
1677
2.03M
                + LitEnc_Matched_GetPrice(LIT_PROBS(position + len, data[(size_t)len - 1]),
1678
2.03M
                    data[len], data2[len], p->ProbPrices);
1679
            
1680
            // state2 = kLiteralNextStates[state2];
1681
2.03M
            state2 = kState_LitAfterRep;
1682
2.03M
            posState2 = (posState2 + 1) & p->pbMask;
1683
1684
1685
2.03M
            price += GetPrice_Rep_0(p, state2, posState2);
1686
1687
50.3M
          for (; len2 < limit && data[len2] == data2[len2]; len2++)
1688
48.3M
          {}
1689
          
1690
2.03M
          len2 -= len;
1691
          // if (len2 >= 3)
1692
2.03M
          {
1693
2.03M
            {
1694
2.03M
              unsigned offset = cur + len + len2;
1695
1696
2.03M
              if (last < offset)
1697
521k
                last = offset;
1698
              // do
1699
2.03M
              {
1700
2.03M
                UInt32 price2;
1701
2.03M
                COptimal *opt;
1702
2.03M
                len2--;
1703
                // price2 = price + GetPrice_Len_Rep_0(p, len2, state2, posState2);
1704
2.03M
                price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState2, len2);
1705
1706
2.03M
                opt = &p->opt[offset];
1707
                // offset--;
1708
2.03M
                if (price2 < opt->price)
1709
608k
                {
1710
608k
                  opt->price = price2;
1711
608k
                  opt->len = (UInt32)len2;
1712
608k
                  opt->extra = (CExtra)(len + 1);
1713
608k
                  opt->dist = (UInt32)repIndex;
1714
608k
                }
1715
2.03M
              }
1716
              // while (len2 >= 3);
1717
2.03M
            }
1718
2.03M
          }
1719
2.03M
          }
1720
4.45M
        }
1721
4.45M
      }
1722
3.76M
    }
1723
1724
1725
    // ---------- MATCH ----------
1726
    /* for (unsigned len = 2; len <= newLen; len++) */
1727
3.76M
    if (newLen > numAvail)
1728
625
    {
1729
625
      newLen = numAvail;
1730
1.93k
      for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2);
1731
625
      matches[numPairs] = (UInt32)newLen;
1732
625
      numPairs += 2;
1733
625
    }
1734
    
1735
    // startLen = 2; /* speed optimization */
1736
1737
3.76M
    if (newLen >= startLen)
1738
2.20M
    {
1739
2.20M
      UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
1740
2.20M
      UInt32 dist;
1741
2.20M
      unsigned offs, posSlot, len;
1742
      
1743
2.20M
      {
1744
2.20M
        unsigned offset = cur + newLen;
1745
2.20M
        if (last < offset)
1746
490k
          last = offset;
1747
2.20M
      }
1748
1749
2.20M
      offs = 0;
1750
2.54M
      while (startLen > matches[offs])
1751
332k
        offs += 2;
1752
2.20M
      dist = matches[(size_t)offs + 1];
1753
      
1754
      // if (dist >= kNumFullDistances)
1755
2.20M
      GetPosSlot2(dist, posSlot);
1756
      
1757
9.33M
      for (len = /*2*/ startLen; ; len++)
1758
11.5M
      {
1759
11.5M
        UInt32 price = normalMatchPrice + GET_PRICE_LEN(&p->lenEnc, posState, len);
1760
11.5M
        {
1761
11.5M
          COptimal *opt;
1762
11.5M
          unsigned lenNorm = len - 2;
1763
11.5M
          lenNorm = GetLenToPosState2(lenNorm);
1764
11.5M
          if (dist < kNumFullDistances)
1765
6.83M
            price += p->distancesPrices[lenNorm][dist & (kNumFullDistances - 1)];
1766
4.71M
          else
1767
4.71M
            price += p->posSlotPrices[lenNorm][posSlot] + p->alignPrices[dist & kAlignMask];
1768
          
1769
11.5M
          opt = &p->opt[cur + len];
1770
11.5M
          if (price < opt->price)
1771
2.07M
          {
1772
2.07M
            opt->price = price;
1773
2.07M
            opt->len = (UInt32)len;
1774
2.07M
            opt->dist = dist + LZMA_NUM_REPS;
1775
2.07M
            opt->extra = 0;
1776
2.07M
          }
1777
11.5M
        }
1778
1779
11.5M
        if (len == matches[offs])
1780
2.67M
        {
1781
          // if (p->_maxMode) {
1782
          // MATCH : LIT : REP_0
1783
1784
2.67M
          const Byte *data2 = data - dist - 1;
1785
2.67M
          unsigned len2 = len + 1;
1786
2.67M
          unsigned limit = len2 + p->numFastBytes;
1787
2.67M
          if (limit > numAvailFull)
1788
169k
            limit = numAvailFull;
1789
          
1790
2.67M
          len2 += 2;
1791
2.67M
          if (len2 <= limit)
1792
2.66M
          if (data[len2 - 2] == data2[len2 - 2])
1793
1.17M
          if (data[len2 - 1] == data2[len2 - 1])
1794
802k
          {
1795
4.42M
          for (; len2 < limit && data[len2] == data2[len2]; len2++)
1796
3.61M
          {}
1797
          
1798
802k
          len2 -= len;
1799
          
1800
          // if (len2 >= 3)
1801
802k
          {
1802
802k
            unsigned state2 = kMatchNextStates[state];
1803
802k
            unsigned posState2 = (position + len) & p->pbMask;
1804
802k
            unsigned offset;
1805
802k
            price += GET_PRICE_0(p->isMatch[state2][posState2]);
1806
802k
            price += LitEnc_Matched_GetPrice(LIT_PROBS(position + len, data[(size_t)len - 1]),
1807
802k
                    data[len], data2[len], p->ProbPrices);
1808
1809
            // state2 = kLiteralNextStates[state2];
1810
802k
            state2 = kState_LitAfterMatch;
1811
1812
802k
            posState2 = (posState2 + 1) & p->pbMask;
1813
802k
            price += GetPrice_Rep_0(p, state2, posState2);
1814
1815
802k
            offset = cur + len + len2;
1816
1817
802k
            if (last < offset)
1818
158k
              last = offset;
1819
            // do
1820
802k
            {
1821
802k
              UInt32 price2;
1822
802k
              COptimal *opt;
1823
802k
              len2--;
1824
              // price2 = price + GetPrice_Len_Rep_0(p, len2, state2, posState2);
1825
802k
              price2 = price + GET_PRICE_LEN(&p->repLenEnc, posState2, len2);
1826
802k
              opt = &p->opt[offset];
1827
              // offset--;
1828
802k
              if (price2 < opt->price)
1829
247k
              {
1830
247k
                opt->price = price2;
1831
247k
                opt->len = (UInt32)len2;
1832
247k
                opt->extra = (CExtra)(len + 1);
1833
247k
                opt->dist = dist + LZMA_NUM_REPS;
1834
247k
              }
1835
802k
            }
1836
            // while (len2 >= 3);
1837
802k
          }
1838
1839
802k
          }
1840
        
1841
2.67M
          offs += 2;
1842
2.67M
          if (offs == numPairs)
1843
2.20M
            break;
1844
464k
          dist = matches[(size_t)offs + 1];
1845
          // if (dist >= kNumFullDistances)
1846
464k
            GetPosSlot2(dist, posSlot);
1847
464k
        }
1848
11.5M
      }
1849
2.20M
    }
1850
3.76M
  }
1851
1852
107k
  do
1853
4.13M
    p->opt[last].price = kInfinityPrice;
1854
4.13M
  while (--last);
1855
1856
107k
  return Backward(p, cur);
1857
121k
}
1858
1859
1860
1861
124k
#define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
1862
1863
1864
1865
static unsigned GetOptimumFast(CLzmaEnc *p)
1866
1.56M
{
1867
1.56M
  UInt32 numAvail, mainDist;
1868
1.56M
  unsigned mainLen, numPairs, repIndex, repLen, i;
1869
1.56M
  const Byte *data;
1870
1871
1.56M
  if (p->additionalOffset == 0)
1872
1.48M
    mainLen = ReadMatchDistances(p, &numPairs);
1873
75.7k
  else
1874
75.7k
  {
1875
75.7k
    mainLen = p->longestMatchLen;
1876
75.7k
    numPairs = p->numPairs;
1877
75.7k
  }
1878
1879
1.56M
  numAvail = p->numAvail;
1880
1.56M
  p->backRes = MARK_LIT;
1881
1.56M
  if (numAvail < 2)
1882
1.24k
    return 1;
1883
  // if (mainLen < 2 && p->state == 0) return 1; // 18.06.notused
1884
1.56M
  if (numAvail > LZMA_MATCH_LEN_MAX)
1885
1.49M
    numAvail = LZMA_MATCH_LEN_MAX;
1886
1.56M
  data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1887
1.56M
  repLen = repIndex = 0;
1888
  
1889
7.63M
  for (i = 0; i < LZMA_NUM_REPS; i++)
1890
6.14M
  {
1891
6.14M
    unsigned len;
1892
6.14M
    const Byte *data2 = data - p->reps[i];
1893
6.14M
    if (data[0] != data2[0] || data[1] != data2[1])
1894
5.87M
      continue;
1895
3.97M
    for (len = 2; len < numAvail && data[len] == data2[len]; len++)
1896
3.70M
    {}
1897
267k
    if (len >= p->numFastBytes)
1898
67.0k
    {
1899
67.0k
      p->backRes = (UInt32)i;
1900
67.0k
      MOVE_POS(p, len - 1)
1901
67.0k
      return len;
1902
67.0k
    }
1903
200k
    if (len > repLen)
1904
159k
    {
1905
159k
      repIndex = i;
1906
159k
      repLen = len;
1907
159k
    }
1908
200k
  }
1909
1910
1.49M
  if (mainLen >= p->numFastBytes)
1911
65.4k
  {
1912
65.4k
    p->backRes = p->matches[(size_t)numPairs - 1] + LZMA_NUM_REPS;
1913
65.4k
    MOVE_POS(p, mainLen - 1)
1914
65.4k
    return mainLen;
1915
65.4k
  }
1916
1917
1.43M
  mainDist = 0; /* for GCC */
1918
  
1919
1.43M
  if (mainLen >= 2)
1920
538k
  {
1921
538k
    mainDist = p->matches[(size_t)numPairs - 1];
1922
541k
    while (numPairs > 2)
1923
96.3k
    {
1924
96.3k
      UInt32 dist2;
1925
96.3k
      if (mainLen != p->matches[(size_t)numPairs - 4] + 1)
1926
53.4k
        break;
1927
42.8k
      dist2 = p->matches[(size_t)numPairs - 3];
1928
42.8k
      if (!ChangePair(dist2, mainDist))
1929
39.8k
        break;
1930
3.01k
      numPairs -= 2;
1931
3.01k
      mainLen--;
1932
3.01k
      mainDist = dist2;
1933
3.01k
    }
1934
538k
    if (mainLen == 2 && mainDist >= 0x80)
1935
270k
      mainLen = 1;
1936
538k
  }
1937
1938
1.43M
  if (repLen >= 2)
1939
121k
    if (    repLen + 1 >= mainLen
1940
121k
        || (repLen + 2 >= mainLen && mainDist >= (1 << 9))
1941
121k
        || (repLen + 3 >= mainLen && mainDist >= (1 << 15)))
1942
101k
  {
1943
101k
    p->backRes = (UInt32)repIndex;
1944
101k
    MOVE_POS(p, repLen - 1)
1945
101k
    return repLen;
1946
101k
  }
1947
  
1948
1.32M
  if (mainLen < 2 || numAvail <= 2)
1949
1.16M
    return 1;
1950
1951
166k
  {
1952
166k
    unsigned len1 = ReadMatchDistances(p, &p->numPairs);
1953
166k
    p->longestMatchLen = len1;
1954
  
1955
166k
    if (len1 >= 2)
1956
150k
    {
1957
150k
      UInt32 newDist = p->matches[(size_t)p->numPairs - 1];
1958
150k
      if (   (len1 >= mainLen && newDist < mainDist)
1959
150k
          || (len1 == mainLen + 1 && !ChangePair(mainDist, newDist))
1960
150k
          || (len1 >  mainLen + 1)
1961
150k
          || (len1 + 1 >= mainLen && mainLen >= 3 && ChangePair(newDist, mainDist)))
1962
65.4k
        return 1;
1963
150k
    }
1964
166k
  }
1965
  
1966
101k
  data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1967
  
1968
475k
  for (i = 0; i < LZMA_NUM_REPS; i++)
1969
384k
  {
1970
384k
    unsigned len, limit;
1971
384k
    const Byte *data2 = data - p->reps[i];
1972
384k
    if (data[0] != data2[0] || data[1] != data2[1])
1973
346k
      continue;
1974
37.3k
    limit = mainLen - 1;
1975
41.5k
    for (len = 2;; len++)
1976
78.8k
    {
1977
78.8k
      if (len >= limit)
1978
10.3k
        return 1;
1979
68.5k
      if (data[len] != data2[len])
1980
26.9k
        break;
1981
68.5k
    }
1982
37.3k
  }
1983
  
1984
91.0k
  p->backRes = mainDist + LZMA_NUM_REPS;
1985
91.0k
  if (mainLen != 2)
1986
70.3k
  {
1987
70.3k
    MOVE_POS(p, mainLen - 2)
1988
70.3k
  }
1989
91.0k
  return mainLen;
1990
101k
}
1991
1992
1993
1994
1995
static void WriteEndMarker(CLzmaEnc *p, unsigned posState)
1996
4.87k
{
1997
4.87k
  UInt32 range;
1998
4.87k
  range = p->rc.range;
1999
4.87k
  {
2000
4.87k
    UInt32 ttt, newBound;
2001
4.87k
    CLzmaProb *prob = &p->isMatch[p->state][posState];
2002
4.87k
    RC_BIT_PRE(&p->rc, prob)
2003
4.87k
    RC_BIT_1(&p->rc, prob)
2004
4.87k
    prob = &p->isRep[p->state];
2005
4.87k
    RC_BIT_PRE(&p->rc, prob)
2006
4.87k
    RC_BIT_0(&p->rc, prob)
2007
4.87k
  }
2008
4.87k
  p->state = kMatchNextStates[p->state];
2009
  
2010
4.87k
  p->rc.range = range;
2011
4.87k
  LenEnc_Encode(&p->lenProbs, &p->rc, 0, posState);
2012
4.87k
  range = p->rc.range;
2013
2014
4.87k
  {
2015
    // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[0], (1 << kNumPosSlotBits) - 1);
2016
4.87k
    CLzmaProb *probs = p->posSlotEncoder[0];
2017
4.87k
    unsigned m = 1;
2018
4.87k
    do
2019
29.2k
    {
2020
29.2k
      UInt32 ttt, newBound;
2021
29.2k
      RC_BIT_PRE(p, probs + m)
2022
29.2k
      RC_BIT_1(&p->rc, probs + m);
2023
29.2k
      m = (m << 1) + 1;
2024
29.2k
    }
2025
29.2k
    while (m < (1 << kNumPosSlotBits));
2026
4.87k
  }
2027
4.87k
  {
2028
    // RangeEnc_EncodeDirectBits(&p->rc, ((UInt32)1 << (30 - kNumAlignBits)) - 1, 30 - kNumAlignBits);    UInt32 range = p->range;
2029
4.87k
    unsigned numBits = 30 - kNumAlignBits;
2030
4.87k
    do
2031
126k
    {
2032
126k
      range >>= 1;
2033
126k
      p->rc.low += range;
2034
126k
      RC_NORM(&p->rc)
2035
126k
    }
2036
126k
    while (--numBits);
2037
4.87k
  }
2038
   
2039
4.87k
  {
2040
    // RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
2041
4.87k
    CLzmaProb *probs = p->posAlignEncoder;
2042
4.87k
    unsigned m = 1;
2043
4.87k
    do
2044
19.5k
    {
2045
19.5k
      UInt32 ttt, newBound;
2046
19.5k
      RC_BIT_PRE(p, probs + m)
2047
19.5k
      RC_BIT_1(&p->rc, probs + m);
2048
19.5k
      m = (m << 1) + 1;
2049
19.5k
    }
2050
19.5k
    while (m < kAlignTableSize);
2051
4.87k
  }
2052
4.87k
  p->rc.range = range;
2053
4.87k
}
2054
2055
2056
static SRes CheckErrors(CLzmaEnc *p)
2057
14.1k
{
2058
14.1k
  if (p->result != SZ_OK)
2059
0
    return p->result;
2060
14.1k
  if (p->rc.res != SZ_OK)
2061
0
    p->result = SZ_ERROR_WRITE;
2062
14.1k
  if (p->matchFinderBase.result != SZ_OK)
2063
0
    p->result = SZ_ERROR_READ;
2064
14.1k
  if (p->result != SZ_OK)
2065
0
    p->finished = True;
2066
14.1k
  return p->result;
2067
14.1k
}
2068
2069
2070
MY_NO_INLINE static SRes Flush(CLzmaEnc *p, UInt32 nowPos)
2071
7.08k
{
2072
  /* ReleaseMFStream(); */
2073
7.08k
  p->finished = True;
2074
7.08k
  if (p->writeEndMark)
2075
4.87k
    WriteEndMarker(p, nowPos & p->pbMask);
2076
7.08k
  RangeEnc_FlushData(&p->rc);
2077
7.08k
  RangeEnc_FlushStream(&p->rc);
2078
7.08k
  return CheckErrors(p);
2079
7.08k
}
2080
2081
2082
MY_NO_INLINE static void FillAlignPrices(CLzmaEnc *p)
2083
10.0k
{
2084
10.0k
  unsigned i;
2085
10.0k
  const CProbPrice *ProbPrices = p->ProbPrices;
2086
10.0k
  const CLzmaProb *probs = p->posAlignEncoder;
2087
  // p->alignPriceCount = 0;
2088
90.8k
  for (i = 0; i < kAlignTableSize / 2; i++)
2089
80.7k
  {
2090
80.7k
    UInt32 price = 0;
2091
80.7k
    unsigned sym = i;
2092
80.7k
    unsigned m = 1;
2093
80.7k
    unsigned bit;
2094
80.7k
    UInt32 prob;
2095
80.7k
    bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[m], bit); m = (m << 1) + bit;
2096
80.7k
    bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[m], bit); m = (m << 1) + bit;
2097
80.7k
    bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[m], bit); m = (m << 1) + bit;
2098
80.7k
    prob = probs[m];
2099
80.7k
    p->alignPrices[i    ] = price + GET_PRICEa_0(prob);
2100
80.7k
    p->alignPrices[i + 8] = price + GET_PRICEa_1(prob);
2101
    // p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
2102
80.7k
  }
2103
10.0k
}
2104
2105
2106
MY_NO_INLINE static void FillDistancesPrices(CLzmaEnc *p)
2107
10.0k
{
2108
  // int y; for (y = 0; y < 100; y++) {
2109
2110
10.0k
  UInt32 tempPrices[kNumFullDistances];
2111
10.0k
  unsigned i, lps;
2112
2113
10.0k
  const CProbPrice *ProbPrices = p->ProbPrices;
2114
10.0k
  p->matchPriceCount = 0;
2115
2116
636k
  for (i = kStartPosModelIndex / 2; i < kNumFullDistances / 2; i++)
2117
626k
  {
2118
626k
    unsigned posSlot = GetPosSlot1(i);
2119
626k
    unsigned footerBits = (posSlot >> 1) - 1;
2120
626k
    unsigned base = ((2 | (posSlot & 1)) << footerBits);
2121
626k
    const CLzmaProb *probs = p->posEncoders + (size_t)base * 2;
2122
    // tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base, footerBits, i - base, p->ProbPrices);
2123
626k
    UInt32 price = 0;
2124
626k
    unsigned m = 1;
2125
626k
    unsigned sym = i;
2126
626k
    unsigned offset = (unsigned)1 << footerBits;
2127
626k
    base += i;
2128
    
2129
626k
    if (footerBits)
2130
605k
    do
2131
1.97M
    {
2132
1.97M
      unsigned bit = sym & 1;
2133
1.97M
      sym >>= 1;
2134
1.97M
      price += GET_PRICEa(probs[m], bit);
2135
1.97M
      m = (m << 1) + bit;
2136
1.97M
    }
2137
1.97M
    while (--footerBits);
2138
2139
626k
    {
2140
626k
      unsigned prob = probs[m];
2141
626k
      tempPrices[base         ] = price + GET_PRICEa_0(prob);
2142
626k
      tempPrices[base + offset] = price + GET_PRICEa_1(prob);
2143
626k
    }
2144
626k
  }
2145
2146
50.4k
  for (lps = 0; lps < kNumLenToPosStates; lps++)
2147
40.3k
  {
2148
40.3k
    unsigned slot;
2149
40.3k
    unsigned distTableSize2 = (p->distTableSize + 1) >> 1;
2150
40.3k
    UInt32 *posSlotPrices = p->posSlotPrices[lps];
2151
40.3k
    const CLzmaProb *probs = p->posSlotEncoder[lps];
2152
    
2153
1.00M
    for (slot = 0; slot < distTableSize2; slot++)
2154
969k
    {
2155
      // posSlotPrices[slot] = RcTree_GetPrice(encoder, kNumPosSlotBits, slot, p->ProbPrices);
2156
969k
      UInt32 price;
2157
969k
      unsigned bit;
2158
969k
      unsigned sym = slot + (1 << (kNumPosSlotBits - 1));
2159
969k
      unsigned prob;
2160
969k
      bit = sym & 1; sym >>= 1; price  = GET_PRICEa(probs[sym], bit);
2161
969k
      bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[sym], bit);
2162
969k
      bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[sym], bit);
2163
969k
      bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[sym], bit);
2164
969k
      bit = sym & 1; sym >>= 1; price += GET_PRICEa(probs[sym], bit);
2165
969k
      prob = probs[(size_t)slot + (1 << (kNumPosSlotBits - 1))];
2166
969k
      posSlotPrices[(size_t)slot * 2    ] = price + GET_PRICEa_0(prob);
2167
969k
      posSlotPrices[(size_t)slot * 2 + 1] = price + GET_PRICEa_1(prob);
2168
969k
    }
2169
    
2170
40.3k
    {
2171
40.3k
      UInt32 delta = ((UInt32)((kEndPosModelIndex / 2 - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
2172
726k
      for (slot = kEndPosModelIndex / 2; slot < distTableSize2; slot++)
2173
686k
      {
2174
686k
        posSlotPrices[(size_t)slot * 2    ] += delta;
2175
686k
        posSlotPrices[(size_t)slot * 2 + 1] += delta;
2176
686k
        delta += ((UInt32)1 << kNumBitPriceShiftBits);
2177
686k
      }
2178
40.3k
    }
2179
2180
40.3k
    {
2181
40.3k
      UInt32 *dp = p->distancesPrices[lps];
2182
      
2183
40.3k
      dp[0] = posSlotPrices[0];
2184
40.3k
      dp[1] = posSlotPrices[1];
2185
40.3k
      dp[2] = posSlotPrices[2];
2186
40.3k
      dp[3] = posSlotPrices[3];
2187
2188
2.54M
      for (i = 4; i < kNumFullDistances; i += 2)
2189
2.50M
      {
2190
2.50M
        UInt32 slotPrice = posSlotPrices[GetPosSlot1(i)];
2191
2.50M
        dp[i    ] = slotPrice + tempPrices[i];
2192
2.50M
        dp[i + 1] = slotPrice + tempPrices[i + 1];
2193
2.50M
      }
2194
40.3k
    }
2195
40.3k
  }
2196
  // }
2197
10.0k
}
2198
2199
2200
2201
void LzmaEnc_Construct(CLzmaEnc *p)
2202
7.08k
{
2203
7.08k
  RangeEnc_Construct(&p->rc);
2204
7.08k
  MatchFinder_Construct(&p->matchFinderBase);
2205
  
2206
  #ifndef _7ZIP_ST
2207
  MatchFinderMt_Construct(&p->matchFinderMt);
2208
  p->matchFinderMt.MatchFinder = &p->matchFinderBase;
2209
  #endif
2210
2211
7.08k
  {
2212
7.08k
    CLzmaEncProps props;
2213
7.08k
    LzmaEncProps_Init(&props);
2214
7.08k
    LzmaEnc_SetProps(p, &props);
2215
7.08k
  }
2216
2217
7.08k
  #ifndef LZMA_LOG_BSR
2218
7.08k
  LzmaEnc_FastPosInit(p->g_FastPos);
2219
7.08k
  #endif
2220
2221
7.08k
  LzmaEnc_InitPriceTables(p->ProbPrices);
2222
7.08k
  p->litProbs = NULL;
2223
7.08k
  p->saveState.litProbs = NULL;
2224
2225
7.08k
}
2226
2227
CLzmaEncHandle LzmaEnc_Create(ISzAllocPtr alloc)
2228
7.08k
{
2229
7.08k
  void *p;
2230
7.08k
  p = ISzAlloc_Alloc(alloc, sizeof(CLzmaEnc));
2231
7.08k
  if (p)
2232
7.08k
    LzmaEnc_Construct((CLzmaEnc *)p);
2233
7.08k
  return p;
2234
7.08k
}
2235
2236
void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAllocPtr alloc)
2237
14.1k
{
2238
14.1k
  ISzAlloc_Free(alloc, p->litProbs);
2239
14.1k
  ISzAlloc_Free(alloc, p->saveState.litProbs);
2240
14.1k
  p->litProbs = NULL;
2241
14.1k
  p->saveState.litProbs = NULL;
2242
14.1k
}
2243
2244
void LzmaEnc_Destruct(CLzmaEnc *p, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2245
7.08k
{
2246
  #ifndef _7ZIP_ST
2247
  MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
2248
  #endif
2249
  
2250
7.08k
  MatchFinder_Free(&p->matchFinderBase, allocBig);
2251
7.08k
  LzmaEnc_FreeLits(p, alloc);
2252
7.08k
  RangeEnc_Free(&p->rc, alloc);
2253
7.08k
}
2254
2255
void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2256
7.08k
{
2257
7.08k
  LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
2258
7.08k
  ISzAlloc_Free(alloc, p);
2259
7.08k
}
2260
2261
2262
static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, UInt32 maxPackSize, UInt32 maxUnpackSize)
2263
7.08k
{
2264
7.08k
  UInt32 nowPos32, startPos32;
2265
7.08k
  if (p->needInit)
2266
7.08k
  {
2267
7.08k
    p->matchFinder.Init(p->matchFinderObj);
2268
7.08k
    p->needInit = 0;
2269
7.08k
  }
2270
2271
7.08k
  if (p->finished)
2272
0
    return p->result;
2273
7.08k
  RINOK(CheckErrors(p));
2274
2275
7.08k
  nowPos32 = (UInt32)p->nowPos64;
2276
7.08k
  startPos32 = nowPos32;
2277
2278
7.08k
  if (p->nowPos64 == 0)
2279
7.08k
  {
2280
7.08k
    unsigned numPairs;
2281
7.08k
    Byte curByte;
2282
7.08k
    if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
2283
0
      return Flush(p, nowPos32);
2284
7.08k
    ReadMatchDistances(p, &numPairs);
2285
7.08k
    RangeEnc_EncodeBit_0(&p->rc, &p->isMatch[kState_Start][0]);
2286
    // p->state = kLiteralNextStates[p->state];
2287
7.08k
    curByte = *(p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset);
2288
7.08k
    LitEnc_Encode(&p->rc, p->litProbs, curByte);
2289
7.08k
    p->additionalOffset--;
2290
7.08k
    nowPos32++;
2291
7.08k
  }
2292
2293
7.08k
  if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
2294
  
2295
7.03k
  for (;;)
2296
3.29M
  {
2297
3.29M
    UInt32 dist;
2298
3.29M
    unsigned len, posState;
2299
3.29M
    UInt32 range, ttt, newBound;
2300
3.29M
    CLzmaProb *probs;
2301
  
2302
3.29M
    if (p->fastMode)
2303
1.56M
      len = GetOptimumFast(p);
2304
1.73M
    else
2305
1.73M
    {
2306
1.73M
      unsigned oci = p->optCur;
2307
1.73M
      if (p->optEnd == oci)
2308
549k
        len = GetOptimum(p, nowPos32);
2309
1.18M
      else
2310
1.18M
      {
2311
1.18M
        const COptimal *opt = &p->opt[oci];
2312
1.18M
        len = opt->len;
2313
1.18M
        p->backRes = opt->dist;
2314
1.18M
        p->optCur = oci + 1;
2315
1.18M
      }
2316
1.73M
    }
2317
2318
3.29M
    posState = (unsigned)nowPos32 & p->pbMask;
2319
3.29M
    range = p->rc.range;
2320
3.29M
    probs = &p->isMatch[p->state][posState];
2321
    
2322
3.29M
    RC_BIT_PRE(&p->rc, probs)
2323
    
2324
3.29M
    dist = p->backRes;
2325
2326
    #ifdef SHOW_STAT2
2327
    printf("\n pos = %6X, len = %3u  pos = %6u", nowPos32, len, dist);
2328
    #endif
2329
2330
3.29M
    if (dist == MARK_LIT)
2331
2.03M
    {
2332
2.03M
      Byte curByte;
2333
2.03M
      const Byte *data;
2334
2.03M
      unsigned state;
2335
2336
2.03M
      RC_BIT_0(&p->rc, probs);
2337
2.03M
      p->rc.range = range;
2338
2.03M
      data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
2339
2.03M
      probs = LIT_PROBS(nowPos32, *(data - 1));
2340
2.03M
      curByte = *data;
2341
2.03M
      state = p->state;
2342
2.03M
      p->state = kLiteralNextStates[state];
2343
2.03M
      if (IsLitState(state))
2344
1.60M
        LitEnc_Encode(&p->rc, probs, curByte);
2345
434k
      else
2346
434k
        LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0]));
2347
2.03M
    }
2348
1.26M
    else
2349
1.26M
    {
2350
1.26M
      RC_BIT_1(&p->rc, probs);
2351
1.26M
      probs = &p->isRep[p->state];
2352
1.26M
      RC_BIT_PRE(&p->rc, probs)
2353
      
2354
1.26M
      if (dist < LZMA_NUM_REPS)
2355
703k
      {
2356
703k
        RC_BIT_1(&p->rc, probs);
2357
703k
        probs = &p->isRepG0[p->state];
2358
703k
        RC_BIT_PRE(&p->rc, probs)
2359
703k
        if (dist == 0)
2360
250k
        {
2361
250k
          RC_BIT_0(&p->rc, probs);
2362
250k
          probs = &p->isRep0Long[p->state][posState];
2363
250k
          RC_BIT_PRE(&p->rc, probs)
2364
250k
          if (len != 1)
2365
190k
          {
2366
190k
            RC_BIT_1_BASE(&p->rc, probs);
2367
190k
          }
2368
60.4k
          else
2369
60.4k
          {
2370
60.4k
            RC_BIT_0_BASE(&p->rc, probs);
2371
60.4k
            p->state = kShortRepNextStates[p->state];
2372
60.4k
          }
2373
250k
        }
2374
452k
        else
2375
452k
        {
2376
452k
          RC_BIT_1(&p->rc, probs);
2377
452k
          probs = &p->isRepG1[p->state];
2378
452k
          RC_BIT_PRE(&p->rc, probs)
2379
452k
          if (dist == 1)
2380
235k
          {
2381
235k
            RC_BIT_0_BASE(&p->rc, probs);
2382
235k
            dist = p->reps[1];
2383
235k
          }
2384
217k
          else
2385
217k
          {
2386
217k
            RC_BIT_1(&p->rc, probs);
2387
217k
            probs = &p->isRepG2[p->state];
2388
217k
            RC_BIT_PRE(&p->rc, probs)
2389
217k
            if (dist == 2)
2390
154k
            {
2391
154k
              RC_BIT_0_BASE(&p->rc, probs);
2392
154k
              dist = p->reps[2];
2393
154k
            }
2394
62.7k
            else
2395
62.7k
            {
2396
62.7k
              RC_BIT_1_BASE(&p->rc, probs);
2397
62.7k
              dist = p->reps[3];
2398
62.7k
              p->reps[3] = p->reps[2];
2399
62.7k
            }
2400
217k
            p->reps[2] = p->reps[1];
2401
217k
          }
2402
452k
          p->reps[1] = p->reps[0];
2403
452k
          p->reps[0] = dist;
2404
452k
        }
2405
2406
703k
        RC_NORM(&p->rc)
2407
2408
703k
        p->rc.range = range;
2409
2410
703k
        if (len != 1)
2411
642k
        {
2412
642k
          LenEnc_Encode(&p->repLenProbs, &p->rc, len - LZMA_MATCH_LEN_MIN, posState);
2413
642k
          --p->repLenEncCounter;
2414
642k
          p->state = kRepNextStates[p->state];
2415
642k
        }
2416
703k
      }
2417
558k
      else
2418
558k
      {
2419
558k
        unsigned posSlot;
2420
558k
        RC_BIT_0(&p->rc, probs);
2421
558k
        p->rc.range = range;
2422
558k
        p->state = kMatchNextStates[p->state];
2423
2424
558k
        LenEnc_Encode(&p->lenProbs, &p->rc, len - LZMA_MATCH_LEN_MIN, posState);
2425
        // --p->lenEnc.counter;
2426
2427
558k
        dist -= LZMA_NUM_REPS;
2428
558k
        p->reps[3] = p->reps[2];
2429
558k
        p->reps[2] = p->reps[1];
2430
558k
        p->reps[1] = p->reps[0];
2431
558k
        p->reps[0] = dist + 1;
2432
        
2433
558k
        p->matchPriceCount++;
2434
558k
        GetPosSlot(dist, posSlot);
2435
        // RcTree_Encode_PosSlot(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], posSlot);
2436
558k
        {
2437
558k
          UInt32 sym = (UInt32)posSlot + (1 << kNumPosSlotBits);
2438
558k
          range = p->rc.range;
2439
558k
          probs = p->posSlotEncoder[GetLenToPosState(len)];
2440
558k
          do
2441
3.35M
          {
2442
3.35M
            CLzmaProb *prob = probs + (sym >> kNumPosSlotBits);
2443
3.35M
            UInt32 bit = (sym >> (kNumPosSlotBits - 1)) & 1;
2444
3.35M
            sym <<= 1;
2445
3.35M
            RC_BIT(&p->rc, prob, bit);
2446
3.35M
          }
2447
3.35M
          while (sym < (1 << kNumPosSlotBits * 2));
2448
558k
          p->rc.range = range;
2449
558k
        }
2450
        
2451
558k
        if (dist >= kStartPosModelIndex)
2452
408k
        {
2453
408k
          unsigned footerBits = ((posSlot >> 1) - 1);
2454
2455
408k
          if (dist < kNumFullDistances)
2456
298k
          {
2457
298k
            unsigned base = ((2 | (posSlot & 1)) << footerBits);
2458
298k
            RcTree_ReverseEncode(&p->rc, p->posEncoders + base, footerBits, (unsigned)(dist /* - base */));
2459
298k
          }
2460
110k
          else
2461
110k
          {
2462
110k
            UInt32 pos2 = (dist | 0xF) << (32 - footerBits);
2463
110k
            range = p->rc.range;
2464
            // RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
2465
            /*
2466
            do
2467
            {
2468
              range >>= 1;
2469
              p->rc.low += range & (0 - ((dist >> --footerBits) & 1));
2470
              RC_NORM(&p->rc)
2471
            }
2472
            while (footerBits > kNumAlignBits);
2473
            */
2474
110k
            do
2475
444k
            {
2476
444k
              range >>= 1;
2477
444k
              p->rc.low += range & (0 - (pos2 >> 31));
2478
444k
              pos2 += pos2;
2479
444k
              RC_NORM(&p->rc)
2480
444k
            }
2481
444k
            while (pos2 != 0xF0000000);
2482
2483
2484
            // RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
2485
2486
110k
            {
2487
110k
              unsigned m = 1;
2488
110k
              unsigned bit;
2489
110k
              bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit;
2490
110k
              bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit;
2491
110k
              bit = dist & 1; dist >>= 1; RC_BIT(&p->rc, p->posAlignEncoder + m, bit); m = (m << 1) + bit;
2492
110k
              bit = dist & 1;             RC_BIT(&p->rc, p->posAlignEncoder + m, bit);
2493
110k
              p->rc.range = range;
2494
              // p->alignPriceCount++;
2495
110k
            }
2496
110k
          }
2497
408k
        }
2498
558k
      }
2499
1.26M
    }
2500
2501
3.29M
    nowPos32 += (UInt32)len;
2502
3.29M
    p->additionalOffset -= len;
2503
    
2504
3.29M
    if (p->additionalOffset == 0)
2505
2.02M
    {
2506
2.02M
      UInt32 processed;
2507
2508
2.02M
      if (!p->fastMode)
2509
531k
      {
2510
        /*
2511
        if (p->alignPriceCount >= 16) // kAlignTableSize
2512
          FillAlignPrices(p);
2513
        if (p->matchPriceCount >= 128)
2514
          FillDistancesPrices(p);
2515
        if (p->lenEnc.counter <= 0)
2516
          LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
2517
        */
2518
531k
        if (p->matchPriceCount >= 64)
2519
5.11k
        {
2520
5.11k
          FillAlignPrices(p);
2521
          // { int y; for (y = 0; y < 100; y++) {
2522
5.11k
          FillDistancesPrices(p);
2523
          // }}
2524
5.11k
          LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
2525
5.11k
        }
2526
531k
        if (p->repLenEncCounter <= 0)
2527
3.05k
        {
2528
3.05k
          p->repLenEncCounter = REP_LEN_COUNT;
2529
3.05k
          LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, &p->repLenProbs, p->ProbPrices);
2530
3.05k
        }
2531
531k
      }
2532
    
2533
2.02M
      if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
2534
7.03k
        break;
2535
2.01M
      processed = nowPos32 - startPos32;
2536
      
2537
2.01M
      if (maxPackSize)
2538
0
      {
2539
0
        if (processed + kNumOpts + 300 >= maxUnpackSize
2540
0
            || RangeEnc_GetProcessed_sizet(&p->rc) + kPackReserve >= maxPackSize)
2541
0
          break;
2542
0
      }
2543
2.01M
      else if (processed >= (1 << 17))
2544
0
      {
2545
0
        p->nowPos64 += nowPos32 - startPos32;
2546
0
        return CheckErrors(p);
2547
0
      }
2548
2.01M
    }
2549
3.29M
  }
2550
2551
7.08k
  p->nowPos64 += nowPos32 - startPos32;
2552
7.08k
  return Flush(p, nowPos32);
2553
7.08k
}
2554
2555
2556
2557
7.08k
#define kBigHashDicLimit ((UInt32)1 << 24)
2558
2559
static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2560
7.08k
{
2561
7.08k
  UInt32 beforeSize = kNumOpts;
2562
7.08k
  if (!RangeEnc_Alloc(&p->rc, alloc))
2563
0
    return SZ_ERROR_MEM;
2564
2565
  #ifndef _7ZIP_ST
2566
  p->mtMode = (p->multiThread && !p->fastMode && (p->matchFinderBase.btMode != 0));
2567
  #endif
2568
2569
7.08k
  {
2570
7.08k
    unsigned lclp = p->lc + p->lp;
2571
7.08k
    if (!p->litProbs || !p->saveState.litProbs || p->lclp != lclp)
2572
7.08k
    {
2573
7.08k
      LzmaEnc_FreeLits(p, alloc);
2574
7.08k
      p->litProbs = (CLzmaProb *)ISzAlloc_Alloc(alloc, ((UInt32)0x300 << lclp) * sizeof(CLzmaProb));
2575
7.08k
      p->saveState.litProbs = (CLzmaProb *)ISzAlloc_Alloc(alloc, ((UInt32)0x300 << lclp) * sizeof(CLzmaProb));
2576
7.08k
      if (!p->litProbs || !p->saveState.litProbs)
2577
0
      {
2578
0
        LzmaEnc_FreeLits(p, alloc);
2579
0
        return SZ_ERROR_MEM;
2580
0
      }
2581
7.08k
      p->lclp = lclp;
2582
7.08k
    }
2583
7.08k
  }
2584
2585
7.08k
  p->matchFinderBase.bigHash = (Byte)(p->dictSize > kBigHashDicLimit ? 1 : 0);
2586
2587
7.08k
  if (beforeSize + p->dictSize < keepWindowSize)
2588
0
    beforeSize = keepWindowSize - p->dictSize;
2589
2590
  #ifndef _7ZIP_ST
2591
  if (p->mtMode)
2592
  {
2593
    RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes,
2594
        LZMA_MATCH_LEN_MAX
2595
        + 1  /* 18.04 */
2596
        , allocBig));
2597
    p->matchFinderObj = &p->matchFinderMt;
2598
    p->matchFinderBase.bigHash = (Byte)(
2599
        (p->dictSize > kBigHashDicLimit && p->matchFinderBase.hashMask >= 0xFFFFFF) ? 1 : 0);
2600
    MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
2601
  }
2602
  else
2603
  #endif
2604
7.08k
  {
2605
7.08k
    if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
2606
0
      return SZ_ERROR_MEM;
2607
7.08k
    p->matchFinderObj = &p->matchFinderBase;
2608
7.08k
    MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
2609
7.08k
  }
2610
  
2611
7.08k
  return SZ_OK;
2612
7.08k
}
2613
2614
void LzmaEnc_Init(CLzmaEnc *p)
2615
7.08k
{
2616
7.08k
  unsigned i;
2617
7.08k
  p->state = 0;
2618
7.08k
  p->reps[0] =
2619
7.08k
  p->reps[1] =
2620
7.08k
  p->reps[2] =
2621
7.08k
  p->reps[3] = 1;
2622
2623
7.08k
  RangeEnc_Init(&p->rc);
2624
2625
120k
  for (i = 0; i < (1 << kNumAlignBits); i++)
2626
113k
    p->posAlignEncoder[i] = kProbInitValue;
2627
2628
92.1k
  for (i = 0; i < kNumStates; i++)
2629
85.0k
  {
2630
85.0k
    unsigned j;
2631
1.44M
    for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
2632
1.36M
    {
2633
1.36M
      p->isMatch[i][j] = kProbInitValue;
2634
1.36M
      p->isRep0Long[i][j] = kProbInitValue;
2635
1.36M
    }
2636
85.0k
    p->isRep[i] = kProbInitValue;
2637
85.0k
    p->isRepG0[i] = kProbInitValue;
2638
85.0k
    p->isRepG1[i] = kProbInitValue;
2639
85.0k
    p->isRepG2[i] = kProbInitValue;
2640
85.0k
  }
2641
2642
7.08k
  {
2643
35.4k
    for (i = 0; i < kNumLenToPosStates; i++)
2644
28.3k
    {
2645
28.3k
      CLzmaProb *probs = p->posSlotEncoder[i];
2646
28.3k
      unsigned j;
2647
1.84M
      for (j = 0; j < (1 << kNumPosSlotBits); j++)
2648
1.81M
        probs[j] = kProbInitValue;
2649
28.3k
    }
2650
7.08k
  }
2651
7.08k
  {
2652
914k
    for (i = 0; i < kNumFullDistances; i++)
2653
907k
      p->posEncoders[i] = kProbInitValue;
2654
7.08k
  }
2655
2656
7.08k
  {
2657
7.08k
    UInt32 num = (UInt32)0x300 << (p->lp + p->lc);
2658
7.08k
    UInt32 k;
2659
7.08k
    CLzmaProb *probs = p->litProbs;
2660
8.42G
    for (k = 0; k < num; k++)
2661
8.42G
      probs[k] = kProbInitValue;
2662
7.08k
  }
2663
2664
2665
7.08k
  LenEnc_Init(&p->lenProbs);
2666
7.08k
  LenEnc_Init(&p->repLenProbs);
2667
2668
7.08k
  p->optEnd = 0;
2669
7.08k
  p->optCur = 0;
2670
2671
7.08k
  {
2672
14.5M
    for (i = 0; i < kNumOpts; i++)
2673
14.5M
      p->opt[i].price = kInfinityPrice;
2674
7.08k
  }
2675
2676
7.08k
  p->additionalOffset = 0;
2677
2678
7.08k
  p->pbMask = (1 << p->pb) - 1;
2679
7.08k
  p->lpMask = ((UInt32)0x100 << p->lp) - ((unsigned)0x100 >> p->lc);
2680
7.08k
}
2681
2682
2683
void LzmaEnc_InitPrices(CLzmaEnc *p)
2684
7.08k
{
2685
7.08k
  if (!p->fastMode)
2686
4.98k
  {
2687
4.98k
    FillDistancesPrices(p);
2688
4.98k
    FillAlignPrices(p);
2689
4.98k
  }
2690
2691
7.08k
  p->lenEnc.tableSize =
2692
7.08k
  p->repLenEnc.tableSize =
2693
7.08k
      p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
2694
2695
7.08k
  p->repLenEncCounter = REP_LEN_COUNT;
2696
2697
7.08k
  LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, &p->lenProbs, p->ProbPrices);
2698
7.08k
  LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, &p->repLenProbs, p->ProbPrices);
2699
7.08k
}
2700
2701
static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2702
7.08k
{
2703
7.08k
  unsigned i;
2704
127k
  for (i = kEndPosModelIndex / 2; i < kDicLogSizeMax; i++)
2705
127k
    if (p->dictSize <= ((UInt32)1 << i))
2706
7.08k
      break;
2707
7.08k
  p->distTableSize = i * 2;
2708
2709
7.08k
  p->finished = False;
2710
7.08k
  p->result = SZ_OK;
2711
7.08k
  RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
2712
7.08k
  LzmaEnc_Init(p);
2713
7.08k
  LzmaEnc_InitPrices(p);
2714
7.08k
  p->nowPos64 = 0;
2715
7.08k
  return SZ_OK;
2716
7.08k
}
2717
2718
static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream,
2719
    ISzAllocPtr alloc, ISzAllocPtr allocBig)
2720
7.08k
{
2721
7.08k
  CLzmaEnc *p = (CLzmaEnc *)pp;
2722
7.08k
  p->matchFinderBase.stream = inStream;
2723
7.08k
  p->needInit = 1;
2724
7.08k
  p->rc.outStream = outStream;
2725
7.08k
  return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
2726
7.08k
}
2727
2728
SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
2729
    ISeqInStream *inStream, UInt32 keepWindowSize,
2730
    ISzAllocPtr alloc, ISzAllocPtr allocBig)
2731
0
{
2732
0
  CLzmaEnc *p = (CLzmaEnc *)pp;
2733
0
  p->matchFinderBase.stream = inStream;
2734
0
  p->needInit = 1;
2735
0
  return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
2736
0
}
2737
2738
static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
2739
0
{
2740
0
  p->matchFinderBase.directInput = 1;
2741
0
  p->matchFinderBase.bufferBase = (Byte *)src;
2742
0
  p->matchFinderBase.directInputRem = srcLen;
2743
0
}
2744
2745
SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
2746
    UInt32 keepWindowSize, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2747
0
{
2748
0
  CLzmaEnc *p = (CLzmaEnc *)pp;
2749
0
  LzmaEnc_SetInputBuf(p, src, srcLen);
2750
0
  p->needInit = 1;
2751
2752
0
  LzmaEnc_SetDataSize(pp, srcLen);
2753
0
  return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
2754
0
}
2755
2756
void LzmaEnc_Finish(CLzmaEncHandle pp)
2757
7.08k
{
2758
  #ifndef _7ZIP_ST
2759
  CLzmaEnc *p = (CLzmaEnc *)pp;
2760
  if (p->mtMode)
2761
    MatchFinderMt_ReleaseStream(&p->matchFinderMt);
2762
  #else
2763
7.08k
  UNUSED_VAR(pp);
2764
7.08k
  #endif
2765
7.08k
}
2766
2767
2768
typedef struct
2769
{
2770
  ISeqOutStream vt;
2771
  Byte *data;
2772
  SizeT rem;
2773
  BoolInt overflow;
2774
} CLzmaEnc_SeqOutStreamBuf;
2775
2776
static size_t SeqOutStreamBuf_Write(const ISeqOutStream *pp, const void *data, size_t size)
2777
0
{
2778
0
  CLzmaEnc_SeqOutStreamBuf *p = CONTAINER_FROM_VTBL(pp, CLzmaEnc_SeqOutStreamBuf, vt);
2779
0
  if (p->rem < size)
2780
0
  {
2781
0
    size = p->rem;
2782
0
    p->overflow = True;
2783
0
  }
2784
0
  memcpy(p->data, data, size);
2785
0
  p->rem -= size;
2786
0
  p->data += size;
2787
0
  return size;
2788
0
}
2789
2790
2791
UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
2792
0
{
2793
0
  const CLzmaEnc *p = (CLzmaEnc *)pp;
2794
0
  return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
2795
0
}
2796
2797
2798
const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
2799
0
{
2800
0
  const CLzmaEnc *p = (CLzmaEnc *)pp;
2801
0
  return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
2802
0
}
2803
2804
2805
SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, BoolInt reInit,
2806
    Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
2807
0
{
2808
0
  CLzmaEnc *p = (CLzmaEnc *)pp;
2809
0
  UInt64 nowPos64;
2810
0
  SRes res;
2811
0
  CLzmaEnc_SeqOutStreamBuf outStream;
2812
2813
0
  outStream.vt.Write = SeqOutStreamBuf_Write;
2814
0
  outStream.data = dest;
2815
0
  outStream.rem = *destLen;
2816
0
  outStream.overflow = False;
2817
2818
0
  p->writeEndMark = False;
2819
0
  p->finished = False;
2820
0
  p->result = SZ_OK;
2821
2822
0
  if (reInit)
2823
0
    LzmaEnc_Init(p);
2824
0
  LzmaEnc_InitPrices(p);
2825
2826
0
  nowPos64 = p->nowPos64;
2827
0
  RangeEnc_Init(&p->rc);
2828
0
  p->rc.outStream = &outStream.vt;
2829
2830
0
  if (desiredPackSize == 0)
2831
0
    return SZ_ERROR_OUTPUT_EOF;
2832
2833
0
  res = LzmaEnc_CodeOneBlock(p, desiredPackSize, *unpackSize);
2834
  
2835
0
  *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
2836
0
  *destLen -= outStream.rem;
2837
0
  if (outStream.overflow)
2838
0
    return SZ_ERROR_OUTPUT_EOF;
2839
2840
0
  return res;
2841
0
}
2842
2843
2844
static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress)
2845
7.08k
{
2846
7.08k
  SRes res = SZ_OK;
2847
2848
  #ifndef _7ZIP_ST
2849
  Byte allocaDummy[0x300];
2850
  allocaDummy[0] = 0;
2851
  allocaDummy[1] = allocaDummy[0];
2852
  #endif
2853
2854
7.08k
  for (;;)
2855
7.08k
  {
2856
7.08k
    res = LzmaEnc_CodeOneBlock(p, 0, 0);
2857
7.08k
    if (res != SZ_OK || p->finished)
2858
7.08k
      break;
2859
0
    if (progress)
2860
0
    {
2861
0
      res = ICompressProgress_Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
2862
0
      if (res != SZ_OK)
2863
0
      {
2864
0
        res = SZ_ERROR_PROGRESS;
2865
0
        break;
2866
0
      }
2867
0
    }
2868
0
  }
2869
  
2870
7.08k
  LzmaEnc_Finish(p);
2871
2872
  /*
2873
  if (res == SZ_OK && !Inline_MatchFinder_IsFinishedOK(&p->matchFinderBase))
2874
    res = SZ_ERROR_FAIL;
2875
  }
2876
  */
2877
2878
7.08k
  return res;
2879
7.08k
}
2880
2881
2882
SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
2883
    ISzAllocPtr alloc, ISzAllocPtr allocBig)
2884
7.08k
{
2885
7.08k
  RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig));
2886
7.08k
  return LzmaEnc_Encode2((CLzmaEnc *)pp, progress);
2887
7.08k
}
2888
2889
2890
SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
2891
7.08k
{
2892
7.08k
  CLzmaEnc *p = (CLzmaEnc *)pp;
2893
7.08k
  unsigned i;
2894
7.08k
  UInt32 dictSize = p->dictSize;
2895
7.08k
  if (*size < LZMA_PROPS_SIZE)
2896
0
    return SZ_ERROR_PARAM;
2897
7.08k
  *size = LZMA_PROPS_SIZE;
2898
7.08k
  props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
2899
2900
7.08k
  if (dictSize >= ((UInt32)1 << 22))
2901
7.08k
  {
2902
7.08k
    UInt32 kDictMask = ((UInt32)1 << 20) - 1;
2903
7.08k
    if (dictSize < (UInt32)0xFFFFFFFF - kDictMask)
2904
7.08k
      dictSize = (dictSize + kDictMask) & ~kDictMask;
2905
7.08k
  }
2906
0
  else for (i = 11; i <= 30; i++)
2907
0
  {
2908
0
    if (dictSize <= ((UInt32)2 << i)) { dictSize = (2 << i); break; }
2909
0
    if (dictSize <= ((UInt32)3 << i)) { dictSize = (3 << i); break; }
2910
0
  }
2911
2912
35.4k
  for (i = 0; i < 4; i++)
2913
28.3k
    props[1 + i] = (Byte)(dictSize >> (8 * i));
2914
7.08k
  return SZ_OK;
2915
7.08k
}
2916
2917
2918
unsigned LzmaEnc_IsWriteEndMark(CLzmaEncHandle pp)
2919
0
{
2920
0
  return ((CLzmaEnc *)pp)->writeEndMark;
2921
0
}
2922
2923
2924
SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
2925
    int writeEndMark, ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2926
0
{
2927
0
  SRes res;
2928
0
  CLzmaEnc *p = (CLzmaEnc *)pp;
2929
2930
0
  CLzmaEnc_SeqOutStreamBuf outStream;
2931
2932
0
  outStream.vt.Write = SeqOutStreamBuf_Write;
2933
0
  outStream.data = dest;
2934
0
  outStream.rem = *destLen;
2935
0
  outStream.overflow = False;
2936
2937
0
  p->writeEndMark = writeEndMark;
2938
0
  p->rc.outStream = &outStream.vt;
2939
2940
0
  res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig);
2941
  
2942
0
  if (res == SZ_OK)
2943
0
  {
2944
0
    res = LzmaEnc_Encode2(p, progress);
2945
0
    if (res == SZ_OK && p->nowPos64 != srcLen)
2946
0
      res = SZ_ERROR_FAIL;
2947
0
  }
2948
2949
0
  *destLen -= outStream.rem;
2950
0
  if (outStream.overflow)
2951
0
    return SZ_ERROR_OUTPUT_EOF;
2952
0
  return res;
2953
0
}
2954
2955
2956
SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
2957
    const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
2958
    ICompressProgress *progress, ISzAllocPtr alloc, ISzAllocPtr allocBig)
2959
0
{
2960
0
  CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
2961
0
  SRes res;
2962
0
  if (!p)
2963
0
    return SZ_ERROR_MEM;
2964
2965
0
  res = LzmaEnc_SetProps(p, props);
2966
0
  if (res == SZ_OK)
2967
0
  {
2968
0
    res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
2969
0
    if (res == SZ_OK)
2970
0
      res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
2971
0
          writeEndMark, progress, alloc, allocBig);
2972
0
  }
2973
2974
0
  LzmaEnc_Destroy(p, alloc, allocBig);
2975
0
  return res;
2976
0
}