Debian Codegraph @

src/lzma/LzmaEnc.c

raw
1 /* LzmaEnc.c -- LZMA Encoder
2 2009-02-02 : Igor Pavlov : Public domain */
3 // ----------------------------------------------------------------------------
4 // Copyright (C) 2014
5 // David Freese, W1HKJ
6 //
7 // This file is part of flmsg
8 //
9 // flrig is free software; you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation; either version 3 of the License, or
12 // (at your option) any later version.
13 //
14 // flrig is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 // GNU General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program. If not, see <http://www.gnu.org/licenses/>.
21 // ----------------------------------------------------------------------------
22
23 #include <string.h>
24
25 /* #define SHOW_STAT */
26 /* #define SHOW_STAT2 */
27
28 #if defined(SHOW_STAT) || defined(SHOW_STAT2)
29 #include <stdio.h>
30 #endif
31
32 #include "LzmaEnc.h"
33
34 #include "LzFind.h"
35 #ifdef COMPRESS_MF_MT
36 #include "LzFindMt.h"
37 #endif
38
39 #ifdef SHOW_STAT
40 static int ttt = 0;
41 #endif
42
43 #define kBlockSizeMax ((1 << LZMA_NUM_BLOCK_SIZE_BITS) - 1)
44
45 #define kBlockSize (9 << 10)
46 #define kUnpackBlockSize (1 << 18)
47 #define kMatchArraySize (1 << 21)
48 #define kMatchRecordMaxSize ((LZMA_MATCH_LEN_MAX * 2 + 3) * LZMA_MATCH_LEN_MAX)
49
50 #define kNumMaxDirectBits (31)
51
52 #define kNumTopBits 24
53 #define kTopValue ((LZ_UInt32)1 << kNumTopBits)
54
55 #define kNumBitModelTotalBits 11
56 #define kBitModelTotal (1 << kNumBitModelTotalBits)
57 #define kNumMoveBits 5
58 #define kProbInitValue (kBitModelTotal >> 1)
59
60 #define kNumMoveReducingBits 4
61 #define kNumBitPriceShiftBits 4
62 #define kBitPrice (1 << kNumBitPriceShiftBits)
63
64 void LzmaEncProps_Init(CLzmaEncProps *p)
65 {
66 p->level = 5;
67 p->dictSize = p->mc = 0;
68 p->lc = p->lp = p->pb = p->algo = p->fb = p->btMode = p->numHashBytes = p->numThreads = -1;
69 p->writeEndMark = 0;
70 }
71
72 void LzmaEncProps_Normalize(CLzmaEncProps *p)
73 {
74 int level = p->level;
75 if (level < 0) level = 5;
76 p->level = level;
77 if (p->dictSize == 0) p->dictSize = (level <= 5 ? (1 << (level * 2 + 14)) : (level == 6 ? (1 << 25) : (1 << 26)));
78 if (p->lc < 0) p->lc = 3;
79 if (p->lp < 0) p->lp = 0;
80 if (p->pb < 0) p->pb = 2;
81 if (p->algo < 0) p->algo = (level < 5 ? 0 : 1);
82 if (p->fb < 0) p->fb = (level < 7 ? 32 : 64);
83 if (p->btMode < 0) p->btMode = (p->algo == 0 ? 0 : 1);
84 if (p->numHashBytes < 0) p->numHashBytes = 4;
85 if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1);
86 if (p->numThreads < 0)
87 p->numThreads =
88 #ifdef COMPRESS_MF_MT
89 ((p->btMode && p->algo) ? 2 : 1);
90 #else
91 1;
92 #endif
93 }
94
95 LZ_UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2)
96 {
97 CLzmaEncProps props = *props2;
98 LzmaEncProps_Normalize(&props);
99 return props.dictSize;
100 }
101
102 /* #define LZMA_LOG_BSR */
103 /* Define it for Intel's CPU */
104
105
106 #ifdef LZMA_LOG_BSR
107
108 #define kDicLogSizeMaxCompress 30
109
110 #define BSR2_RET(pos, res) { unsigned long i; _BitScanReverse(&i, (pos)); res = (i + i) + ((pos >> (i - 1)) & 1); }
111
112 LZ_UInt32 GetPosSlot1(LZ_UInt32 pos)
113 {
114 LZ_UInt32 res;
115 BSR2_RET(pos, res);
116 return res;
117 }
118 #define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
119 #define GetPosSlot(pos, res) { if (pos < 2) res = pos; else BSR2_RET(pos, res); }
120
121 #else
122
123 #define kNumLogBits (9 + (int)sizeof(size_t) / 2)
124 #define kDicLogSizeMaxCompress ((kNumLogBits - 1) * 2 + 7)
125
126 void LzmaEnc_FastPosInit(Byte *g_FastPos)
127 {
128 int c = 2, slotFast;
129 g_FastPos[0] = 0;
130 g_FastPos[1] = 1;
131
132 for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++)
133 {
134 LZ_UInt32 k = (1 << ((slotFast >> 1) - 1));
135 LZ_UInt32 j;
136 for (j = 0; j < k; j++, c++)
137 g_FastPos[c] = (Byte)slotFast;
138 }
139 }
140
141 #define BSR2_RET(pos, res) { LZ_UInt32 i = 6 + ((kNumLogBits - 1) & \
142 (0 - (((((LZ_UInt32)1 << (kNumLogBits + 6)) - 1) - pos) >> 31))); \
143 res = p->g_FastPos[pos >> i] + (i * 2); }
144 /*
145 #define BSR2_RET(pos, res) { res = (pos < (1 << (kNumLogBits + 6))) ? \
146 p->g_FastPos[pos >> 6] + 12 : \
147 p->g_FastPos[pos >> (6 + kNumLogBits - 1)] + (6 + (kNumLogBits - 1)) * 2; }
148 */
149
150 #define GetPosSlot1(pos) p->g_FastPos[pos]
151 #define GetPosSlot2(pos, res) { BSR2_RET(pos, res); }
152 #define GetPosSlot(pos, res) { if (pos < kNumFullDistances) res = p->g_FastPos[pos]; else BSR2_RET(pos, res); }
153
154 #endif
155
156
157 #define LZMA_NUM_REPS 4
158
159 typedef unsigned CState;
160
161 typedef struct _COptimal
162 {
163 LZ_UInt32 price;
164
165 CState state;
166 int prev1IsChar;
167 int prev2;
168
169 LZ_UInt32 posPrev2;
170 LZ_UInt32 backPrev2;
171
172 LZ_UInt32 posPrev;
173 LZ_UInt32 backPrev;
174 LZ_UInt32 backs[LZMA_NUM_REPS];
175 } COptimal;
176
177 #define kNumOpts (1 << 12)
178
179 #define kNumLenToPosStates 4
180 #define kNumPosSlotBits 6
181 #define kDicLogSizeMin 0
182 #define kDicLogSizeMax 32
183 #define kDistTableSizeMax (kDicLogSizeMax * 2)
184
185
186 #define kNumAlignBits 4
187 #define kAlignTableSize (1 << kNumAlignBits)
188 #define kAlignMask (kAlignTableSize - 1)
189
190 #define kStartPosModelIndex 4
191 #define kEndPosModelIndex 14
192 #define kNumPosModels (kEndPosModelIndex - kStartPosModelIndex)
193
194 #define kNumFullDistances (1 << (kEndPosModelIndex / 2))
195
196 #ifdef _LZMA_PROB32
197 #define CLzmaProb LZ_UInt32
198 #else
199 #define CLzmaProb UInt16
200 #endif
201
202 #define LZMA_PB_MAX 4
203 #define LZMA_LC_MAX 8
204 #define LZMA_LP_MAX 4
205
206 #define LZMA_NUM_PB_STATES_MAX (1 << LZMA_PB_MAX)
207
208
209 #define kLenNumLowBits 3
210 #define kLenNumLowSymbols (1 << kLenNumLowBits)
211 #define kLenNumMidBits 3
212 #define kLenNumMidSymbols (1 << kLenNumMidBits)
213 #define kLenNumHighBits 8
214 #define kLenNumHighSymbols (1 << kLenNumHighBits)
215
216 #define kLenNumSymbolsTotal (kLenNumLowSymbols + kLenNumMidSymbols + kLenNumHighSymbols)
217
218 #define LZMA_MATCH_LEN_MIN 2
219 #define LZMA_MATCH_LEN_MAX (LZMA_MATCH_LEN_MIN + kLenNumSymbolsTotal - 1)
220
221 #define kNumStates 12
222
223 typedef struct
224 {
225 CLzmaProb choice;
226 CLzmaProb choice2;
227 CLzmaProb low[LZMA_NUM_PB_STATES_MAX << kLenNumLowBits];
228 CLzmaProb mid[LZMA_NUM_PB_STATES_MAX << kLenNumMidBits];
229 CLzmaProb high[kLenNumHighSymbols];
230 } CLenEnc;
231
232 typedef struct
233 {
234 CLenEnc p;
235 LZ_UInt32 prices[LZMA_NUM_PB_STATES_MAX][kLenNumSymbolsTotal];
236 LZ_UInt32 tableSize;
237 LZ_UInt32 counters[LZMA_NUM_PB_STATES_MAX];
238 } CLenPriceEnc;
239
240 typedef struct _CRangeEnc
241 {
242 LZ_UInt32 range;
243 Byte cache;
244 LZ_UInt64 low;
245 LZ_UInt64 cacheSize;
246 Byte *buf;
247 Byte *bufLim;
248 Byte *bufBase;
249 ISeqOutStream *outStream;
250 LZ_UInt64 processed;
251 SRes res;
252 } CRangeEnc;
253
254 typedef struct _CSeqInStreamBuf
255 {
256 ISeqInStream funcTable;
257 const Byte *data;
258 SizeT rem;
259 } CSeqInStreamBuf;
260
261 static SRes MyRead(void *pp, void *data, size_t *size)
262 {
263 size_t curSize = *size;
264 CSeqInStreamBuf *p = (CSeqInStreamBuf *)pp;
265 if (p->rem < curSize)
266 curSize = p->rem;
267 memcpy(data, p->data, curSize);
268 p->rem -= curSize;
269 p->data += curSize;
270 *size = curSize;
271 return SZ_OK;
272 }
273
274 typedef struct
275 {
276 CLzmaProb *litProbs;
277
278 CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
279 CLzmaProb isRep[kNumStates];
280 CLzmaProb isRepG0[kNumStates];
281 CLzmaProb isRepG1[kNumStates];
282 CLzmaProb isRepG2[kNumStates];
283 CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
284
285 CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
286 CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
287 CLzmaProb posAlignEncoder[1 << kNumAlignBits];
288
289 CLenPriceEnc lenEnc;
290 CLenPriceEnc repLenEnc;
291
292 LZ_UInt32 reps[LZMA_NUM_REPS];
293 LZ_UInt32 state;
294 } CSaveState;
295
296 typedef struct _CLzmaEnc
297 {
298 IMatchFinder matchFinder;
299 void *matchFinderObj;
300
301 #ifdef COMPRESS_MF_MT
302 int mtMode;
303 CMatchFinderMt matchFinderMt;
304 #endif
305
306 CMatchFinder matchFinderBase;
307
308 #ifdef COMPRESS_MF_MT
309 Byte pad[128];
310 #endif
311
312 LZ_UInt32 optimumEndIndex;
313 LZ_UInt32 optimumCurrentIndex;
314
315 LZ_UInt32 longestMatchLength;
316 LZ_UInt32 numPairs;
317 LZ_UInt32 numAvail;
318 COptimal opt[kNumOpts];
319
320 #ifndef LZMA_LOG_BSR
321 Byte g_FastPos[1 << kNumLogBits];
322 #endif
323
324 LZ_UInt32 ProbPrices[kBitModelTotal >> kNumMoveReducingBits];
325 LZ_UInt32 matches[LZMA_MATCH_LEN_MAX * 2 + 2 + 1];
326 LZ_UInt32 numFastBytes;
327 LZ_UInt32 additionalOffset;
328 LZ_UInt32 reps[LZMA_NUM_REPS];
329 LZ_UInt32 state;
330
331 LZ_UInt32 posSlotPrices[kNumLenToPosStates][kDistTableSizeMax];
332 LZ_UInt32 distancesPrices[kNumLenToPosStates][kNumFullDistances];
333 LZ_UInt32 alignPrices[kAlignTableSize];
334 LZ_UInt32 alignPriceCount;
335
336 LZ_UInt32 distTableSize;
337
338 unsigned lc, lp, pb;
339 unsigned lpMask, pbMask;
340
341 CLzmaProb *litProbs;
342
343 CLzmaProb isMatch[kNumStates][LZMA_NUM_PB_STATES_MAX];
344 CLzmaProb isRep[kNumStates];
345 CLzmaProb isRepG0[kNumStates];
346 CLzmaProb isRepG1[kNumStates];
347 CLzmaProb isRepG2[kNumStates];
348 CLzmaProb isRep0Long[kNumStates][LZMA_NUM_PB_STATES_MAX];
349
350 CLzmaProb posSlotEncoder[kNumLenToPosStates][1 << kNumPosSlotBits];
351 CLzmaProb posEncoders[kNumFullDistances - kEndPosModelIndex];
352 CLzmaProb posAlignEncoder[1 << kNumAlignBits];
353
354 CLenPriceEnc lenEnc;
355 CLenPriceEnc repLenEnc;
356
357 unsigned lclp;
358
359 int fastMode;
360
361 CRangeEnc rc;
362
363 int writeEndMark;
364 LZ_UInt64 nowPos64;
365 LZ_UInt32 matchPriceCount;
366 int finished;
367 int multiThread;
368
369 SRes result;
370 LZ_UInt32 dictSize;
371 LZ_UInt32 matchFinderCycles;
372
373 ISeqInStream *inStream;
374 CSeqInStreamBuf seqBufInStream;
375
376 CSaveState saveState;
377 } CLzmaEnc;
378
379 void LzmaEnc_SaveState(CLzmaEncHandle pp)
380 {
381 CLzmaEnc *p = (CLzmaEnc *)pp;
382 CSaveState *dest = &p->saveState;
383 int i;
384 dest->lenEnc = p->lenEnc;
385 dest->repLenEnc = p->repLenEnc;
386 dest->state = p->state;
387
388 for (i = 0; i < kNumStates; i++)
389 {
390 memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
391 memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
392 }
393 for (i = 0; i < kNumLenToPosStates; i++)
394 memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
395 memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
396 memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
397 memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
398 memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
399 memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
400 memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
401 memcpy(dest->reps, p->reps, sizeof(p->reps));
402 memcpy(dest->litProbs, p->litProbs, (0x300 << p->lclp) * sizeof(CLzmaProb));
403 }
404
405 void LzmaEnc_RestoreState(CLzmaEncHandle pp)
406 {
407 CLzmaEnc *dest = (CLzmaEnc *)pp;
408 const CSaveState *p = &dest->saveState;
409 int i;
410 dest->lenEnc = p->lenEnc;
411 dest->repLenEnc = p->repLenEnc;
412 dest->state = p->state;
413
414 for (i = 0; i < kNumStates; i++)
415 {
416 memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i]));
417 memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i]));
418 }
419 for (i = 0; i < kNumLenToPosStates; i++)
420 memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i]));
421 memcpy(dest->isRep, p->isRep, sizeof(p->isRep));
422 memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0));
423 memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1));
424 memcpy(dest->isRepG2, p->isRepG2, sizeof(p->isRepG2));
425 memcpy(dest->posEncoders, p->posEncoders, sizeof(p->posEncoders));
426 memcpy(dest->posAlignEncoder, p->posAlignEncoder, sizeof(p->posAlignEncoder));
427 memcpy(dest->reps, p->reps, sizeof(p->reps));
428 memcpy(dest->litProbs, p->litProbs, (0x300 << dest->lclp) * sizeof(CLzmaProb));
429 }
430
431 SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2)
432 {
433 CLzmaEnc *p = (CLzmaEnc *)pp;
434 CLzmaEncProps props = *props2;
435 LzmaEncProps_Normalize(&props);
436
437 if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX ||
438 props.dictSize > (1 << kDicLogSizeMaxCompress) || props.dictSize > (1 << 30))
439 return SZ_ERROR_PARAM;
440 p->dictSize = props.dictSize;
441 p->matchFinderCycles = props.mc;
442 {
443 unsigned fb = props.fb;
444 if (fb < 5)
445 fb = 5;
446 if (fb > LZMA_MATCH_LEN_MAX)
447 fb = LZMA_MATCH_LEN_MAX;
448 p->numFastBytes = fb;
449 }
450 p->lc = props.lc;
451 p->lp = props.lp;
452 p->pb = props.pb;
453 p->fastMode = (props.algo == 0);
454 p->matchFinderBase.btMode = props.btMode;
455 {
456 LZ_UInt32 numHashBytes = 4;
457 if (props.btMode)
458 {
459 if (props.numHashBytes < 2)
460 numHashBytes = 2;
461 else if (props.numHashBytes < 4)
462 numHashBytes = props.numHashBytes;
463 }
464 p->matchFinderBase.numHashBytes = numHashBytes;
465 }
466
467 p->matchFinderBase.cutValue = props.mc;
468
469 p->writeEndMark = props.writeEndMark;
470
471 #ifdef COMPRESS_MF_MT
472 /*
473 if (newMultiThread != _multiThread)
474 {
475 ReleaseMatchFinder();
476 _multiThread = newMultiThread;
477 }
478 */
479 p->multiThread = (props.numThreads > 1);
480 #endif
481
482 return SZ_OK;
483 }
484
485 static const int kLiteralNextStates[kNumStates] = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5};
486 static const int kMatchNextStates[kNumStates] = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10};
487 static const int kRepNextStates[kNumStates] = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11};
488 static const int kShortRepNextStates[kNumStates]= {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11};
489
490 #define IsCharState(s) ((s) < 7)
491
492 #define GetLenToPosState(len) (((len) < kNumLenToPosStates + 1) ? (len) - 2 : kNumLenToPosStates - 1)
493
494 #define kInfinityPrice (1 << 30)
495
496 static void RangeEnc_Construct(CRangeEnc *p)
497 {
498 p->outStream = 0;
499 p->bufBase = 0;
500 }
501
502 #define RangeEnc_GetProcessed(p) ((p)->processed + ((p)->buf - (p)->bufBase) + (p)->cacheSize)
503
504 #define RC_BUF_SIZE (1 << 16)
505 static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc)
506 {
507 if (p->bufBase == 0)
508 {
509 p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE);
510 if (p->bufBase == 0)
511 return 0;
512 p->bufLim = p->bufBase + RC_BUF_SIZE;
513 }
514 return 1;
515 }
516
517 static void RangeEnc_Free(CRangeEnc *p, ISzAlloc *alloc)
518 {
519 alloc->Free(alloc, p->bufBase);
520 p->bufBase = 0;
521 }
522
523 static void RangeEnc_Init(CRangeEnc *p)
524 {
525 /* Stream.Init(); */
526 p->low = 0;
527 p->range = 0xFFFFFFFF;
528 p->cacheSize = 1;
529 p->cache = 0;
530
531 p->buf = p->bufBase;
532
533 p->processed = 0;
534 p->res = SZ_OK;
535 }
536
537 static void RangeEnc_FlushStream(CRangeEnc *p)
538 {
539 size_t num;
540 if (p->res != SZ_OK)
541 return;
542 num = p->buf - p->bufBase;
543 if (num != p->outStream->Write(p->outStream, p->bufBase, num))
544 p->res = SZ_ERROR_WRITE;
545 p->processed += num;
546 p->buf = p->bufBase;
547 }
548
549 static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p)
550 {
551 if ((LZ_UInt32)p->low < (LZ_UInt32)0xFF000000 || (int)(p->low >> 32) != 0)
552 {
553 Byte temp = p->cache;
554 do
555 {
556 Byte *buf = p->buf;
557 *buf++ = (Byte)(temp + (Byte)(p->low >> 32));
558 p->buf = buf;
559 if (buf == p->bufLim)
560 RangeEnc_FlushStream(p);
561 temp = 0xFF;
562 }
563 while (--p->cacheSize != 0);
564 p->cache = (Byte)((LZ_UInt32)p->low >> 24);
565 }
566 p->cacheSize++;
567 p->low = (LZ_UInt32)p->low << 8;
568 }
569
570 static void RangeEnc_FlushData(CRangeEnc *p)
571 {
572 int i;
573 for (i = 0; i < 5; i++)
574 RangeEnc_ShiftLow(p);
575 }
576
577 static void RangeEnc_EncodeDirectBits(CRangeEnc *p, LZ_UInt32 value, int numBits)
578 {
579 do
580 {
581 p->range >>= 1;
582 p->low += p->range & (0 - ((value >> --numBits) & 1));
583 if (p->range < kTopValue)
584 {
585 p->range <<= 8;
586 RangeEnc_ShiftLow(p);
587 }
588 }
589 while (numBits != 0);
590 }
591
592 static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, LZ_UInt32 symbol)
593 {
594 LZ_UInt32 ttt = *prob;
595 LZ_UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt;
596 if (symbol == 0)
597 {
598 p->range = newBound;
599 ttt += (kBitModelTotal - ttt) >> kNumMoveBits;
600 }
601 else
602 {
603 p->low += newBound;
604 p->range -= newBound;
605 ttt -= ttt >> kNumMoveBits;
606 }
607 *prob = (CLzmaProb)ttt;
608 if (p->range < kTopValue)
609 {
610 p->range <<= 8;
611 RangeEnc_ShiftLow(p);
612 }
613 }
614
615 static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, LZ_UInt32 symbol)
616 {
617 symbol |= 0x100;
618 do
619 {
620 RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1);
621 symbol <<= 1;
622 }
623 while (symbol < 0x10000);
624 }
625
626 static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, LZ_UInt32 symbol, LZ_UInt32 matchByte)
627 {
628 LZ_UInt32 offs = 0x100;
629 symbol |= 0x100;
630 do
631 {
632 matchByte <<= 1;
633 RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1);
634 symbol <<= 1;
635 offs &= ~(matchByte ^ symbol);
636 }
637 while (symbol < 0x10000);
638 }
639
640 void LzmaEnc_InitPriceTables(LZ_UInt32 *ProbPrices)
641 {
642 LZ_UInt32 i;
643 for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits))
644 {
645 const int kCyclesBits = kNumBitPriceShiftBits;
646 LZ_UInt32 w = i;
647 LZ_UInt32 bitCount = 0;
648 int j;
649 for (j = 0; j < kCyclesBits; j++)
650 {
651 w = w * w;
652 bitCount <<= 1;
653 while (w >= ((LZ_UInt32)1 << 16))
654 {
655 w >>= 1;
656 bitCount++;
657 }
658 }
659 ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount);
660 }
661 }
662
663
664 #define GET_PRICE(prob, symbol) \
665 p->ProbPrices[((prob) ^ (((-(int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
666
667 #define GET_PRICEa(prob, symbol) \
668 ProbPrices[((prob) ^ ((-((int)(symbol))) & (kBitModelTotal - 1))) >> kNumMoveReducingBits];
669
670 #define GET_PRICE_0(prob) p->ProbPrices[(prob) >> kNumMoveReducingBits]
671 #define GET_PRICE_1(prob) p->ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
672
673 #define GET_PRICE_0a(prob) ProbPrices[(prob) >> kNumMoveReducingBits]
674 #define GET_PRICE_1a(prob) ProbPrices[((prob) ^ (kBitModelTotal - 1)) >> kNumMoveReducingBits]
675
676 static LZ_UInt32 LitEnc_GetPrice(const CLzmaProb *probs, LZ_UInt32 symbol, LZ_UInt32 *ProbPrices)
677 {
678 LZ_UInt32 price = 0;
679 symbol |= 0x100;
680 do
681 {
682 price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1);
683 symbol <<= 1;
684 }
685 while (symbol < 0x10000);
686 return price;
687 }
688
689 static LZ_UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, LZ_UInt32 symbol, LZ_UInt32 matchByte, LZ_UInt32 *ProbPrices)
690 {
691 LZ_UInt32 price = 0;
692 LZ_UInt32 offs = 0x100;
693 symbol |= 0x100;
694 do
695 {
696 matchByte <<= 1;
697 price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1);
698 symbol <<= 1;
699 offs &= ~(matchByte ^ symbol);
700 }
701 while (symbol < 0x10000);
702 return price;
703 }
704
705
706 static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, LZ_UInt32 symbol)
707 {
708 LZ_UInt32 m = 1;
709 int i;
710 for (i = numBitLevels; i != 0;)
711 {
712 LZ_UInt32 bit;
713 i--;
714 bit = (symbol >> i) & 1;
715 RangeEnc_EncodeBit(rc, probs + m, bit);
716 m = (m << 1) | bit;
717 }
718 }
719
720 static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, LZ_UInt32 symbol)
721 {
722 LZ_UInt32 m = 1;
723 int i;
724 for (i = 0; i < numBitLevels; i++)
725 {
726 LZ_UInt32 bit = symbol & 1;
727 RangeEnc_EncodeBit(rc, probs + m, bit);
728 m = (m << 1) | bit;
729 symbol >>= 1;
730 }
731 }
732
733 static LZ_UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, LZ_UInt32 symbol, LZ_UInt32 *ProbPrices)
734 {
735 LZ_UInt32 price = 0;
736 symbol |= (1 << numBitLevels);
737 while (symbol != 1)
738 {
739 price += GET_PRICEa(probs[symbol >> 1], symbol & 1);
740 symbol >>= 1;
741 }
742 return price;
743 }
744
745 static LZ_UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, LZ_UInt32 symbol, LZ_UInt32 *ProbPrices)
746 {
747 LZ_UInt32 price = 0;
748 LZ_UInt32 m = 1;
749 int i;
750 for (i = numBitLevels; i != 0; i--)
751 {
752 LZ_UInt32 bit = symbol & 1;
753 symbol >>= 1;
754 price += GET_PRICEa(probs[m], bit);
755 m = (m << 1) | bit;
756 }
757 return price;
758 }
759
760
761 static void LenEnc_Init(CLenEnc *p)
762 {
763 unsigned i;
764 p->choice = p->choice2 = kProbInitValue;
765 for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++)
766 p->low[i] = kProbInitValue;
767 for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++)
768 p->mid[i] = kProbInitValue;
769 for (i = 0; i < kLenNumHighSymbols; i++)
770 p->high[i] = kProbInitValue;
771 }
772
773 static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, LZ_UInt32 symbol, LZ_UInt32 posState)
774 {
775 if (symbol < kLenNumLowSymbols)
776 {
777 RangeEnc_EncodeBit(rc, &p->choice, 0);
778 RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol);
779 }
780 else
781 {
782 RangeEnc_EncodeBit(rc, &p->choice, 1);
783 if (symbol < kLenNumLowSymbols + kLenNumMidSymbols)
784 {
785 RangeEnc_EncodeBit(rc, &p->choice2, 0);
786 RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols);
787 }
788 else
789 {
790 RangeEnc_EncodeBit(rc, &p->choice2, 1);
791 RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols);
792 }
793 }
794 }
795
796 static void LenEnc_SetPrices(CLenEnc *p, LZ_UInt32 posState, LZ_UInt32 numSymbols, LZ_UInt32 *prices, LZ_UInt32 *ProbPrices)
797 {
798 LZ_UInt32 a0 = GET_PRICE_0a(p->choice);
799 LZ_UInt32 a1 = GET_PRICE_1a(p->choice);
800 LZ_UInt32 b0 = a1 + GET_PRICE_0a(p->choice2);
801 LZ_UInt32 b1 = a1 + GET_PRICE_1a(p->choice2);
802 LZ_UInt32 i = 0;
803 for (i = 0; i < kLenNumLowSymbols; i++)
804 {
805 if (i >= numSymbols)
806 return;
807 prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices);
808 }
809 for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++)
810 {
811 if (i >= numSymbols)
812 return;
813 prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices);
814 }
815 for (; i < numSymbols; i++)
816 prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices);
817 }
818
819 static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, LZ_UInt32 posState, LZ_UInt32 *ProbPrices)
820 {
821 LenEnc_SetPrices(&p->p, posState, p->tableSize, p->prices[posState], ProbPrices);
822 p->counters[posState] = p->tableSize;
823 }
824
825 static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, LZ_UInt32 numPosStates, LZ_UInt32 *ProbPrices)
826 {
827 LZ_UInt32 posState;
828 for (posState = 0; posState < numPosStates; posState++)
829 LenPriceEnc_UpdateTable(p, posState, ProbPrices);
830 }
831
832 static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, LZ_UInt32 symbol, LZ_UInt32 posState, int updatePrice, LZ_UInt32 *ProbPrices)
833 {
834 LenEnc_Encode(&p->p, rc, symbol, posState);
835 if (updatePrice)
836 if (--p->counters[posState] == 0)
837 LenPriceEnc_UpdateTable(p, posState, ProbPrices);
838 }
839
840
841
842
843 static void MovePos(CLzmaEnc *p, LZ_UInt32 num)
844 {
845 #ifdef SHOW_STAT
846 ttt += num;
847 printf("\n MovePos %d", num);
848 #endif
849 if (num != 0)
850 {
851 p->additionalOffset += num;
852 p->matchFinder.Skip(p->matchFinderObj, num);
853 }
854 }
855
856 static LZ_UInt32 ReadMatchDistances(CLzmaEnc *p, LZ_UInt32 *numDistancePairsRes)
857 {
858 LZ_UInt32 lenRes = 0, numPairs;
859 p->numAvail = p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
860 numPairs = p->matchFinder.GetMatches(p->matchFinderObj, p->matches);
861 #ifdef SHOW_STAT
862 printf("\n i = %d numPairs = %d ", ttt, numPairs / 2);
863 ttt++;
864 {
865 LZ_UInt32 i;
866 for (i = 0; i < numPairs; i += 2)
867 printf("%2d %6d | ", p->matches[i], p->matches[i + 1]);
868 }
869 #endif
870 if (numPairs > 0)
871 {
872 lenRes = p->matches[numPairs - 2];
873 if (lenRes == p->numFastBytes)
874 {
875 const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
876 LZ_UInt32 distance = p->matches[numPairs - 1] + 1;
877 LZ_UInt32 numAvail = p->numAvail;
878 if (numAvail > LZMA_MATCH_LEN_MAX)
879 numAvail = LZMA_MATCH_LEN_MAX;
880 {
881 const Byte *pby2 = pby - distance;
882 for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++);
883 }
884 }
885 }
886 p->additionalOffset++;
887 *numDistancePairsRes = numPairs;
888 return lenRes;
889 }
890
891
892 #define MakeAsChar(p) (p)->backPrev = (LZ_UInt32)(-1); (p)->prev1IsChar = False;
893 #define MakeAsShortRep(p) (p)->backPrev = 0; (p)->prev1IsChar = False;
894 #define IsShortRep(p) ((p)->backPrev == 0)
895
896 static LZ_UInt32 GetRepLen1Price(CLzmaEnc *p, LZ_UInt32 state, LZ_UInt32 posState)
897 {
898 return
899 GET_PRICE_0(p->isRepG0[state]) +
900 GET_PRICE_0(p->isRep0Long[state][posState]);
901 }
902
903 static LZ_UInt32 GetPureRepPrice(CLzmaEnc *p, LZ_UInt32 repIndex, LZ_UInt32 state, LZ_UInt32 posState)
904 {
905 LZ_UInt32 price;
906 if (repIndex == 0)
907 {
908 price = GET_PRICE_0(p->isRepG0[state]);
909 price += GET_PRICE_1(p->isRep0Long[state][posState]);
910 }
911 else
912 {
913 price = GET_PRICE_1(p->isRepG0[state]);
914 if (repIndex == 1)
915 price += GET_PRICE_0(p->isRepG1[state]);
916 else
917 {
918 price += GET_PRICE_1(p->isRepG1[state]);
919 price += GET_PRICE(p->isRepG2[state], repIndex - 2);
920 }
921 }
922 return price;
923 }
924
925 static LZ_UInt32 GetRepPrice(CLzmaEnc *p, LZ_UInt32 repIndex, LZ_UInt32 len, LZ_UInt32 state, LZ_UInt32 posState)
926 {
927 return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] +
928 GetPureRepPrice(p, repIndex, state, posState);
929 }
930
931 static LZ_UInt32 Backward(CLzmaEnc *p, LZ_UInt32 *backRes, LZ_UInt32 cur)
932 {
933 LZ_UInt32 posMem = p->opt[cur].posPrev;
934 LZ_UInt32 backMem = p->opt[cur].backPrev;
935 p->optimumEndIndex = cur;
936 do
937 {
938 if (p->opt[cur].prev1IsChar)
939 {
940 MakeAsChar(&p->opt[posMem])
941 p->opt[posMem].posPrev = posMem - 1;
942 if (p->opt[cur].prev2)
943 {
944 p->opt[posMem - 1].prev1IsChar = False;
945 p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2;
946 p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2;
947 }
948 }
949 {
950 LZ_UInt32 posPrev = posMem;
951 LZ_UInt32 backCur = backMem;
952
953 backMem = p->opt[posPrev].backPrev;
954 posMem = p->opt[posPrev].posPrev;
955
956 p->opt[posPrev].backPrev = backCur;
957 p->opt[posPrev].posPrev = cur;
958 cur = posPrev;
959 }
960 }
961 while (cur != 0);
962 *backRes = p->opt[0].backPrev;
963 p->optimumCurrentIndex = p->opt[0].posPrev;
964 return p->optimumCurrentIndex;
965 }
966
967 #define LIT_PROBS(pos, prevByte) (p->litProbs + ((((pos) & p->lpMask) << p->lc) + ((prevByte) >> (8 - p->lc))) * 0x300)
968
969 static LZ_UInt32 GetOptimum(CLzmaEnc *p, LZ_UInt32 position, LZ_UInt32 *backRes)
970 {
971 LZ_UInt32 numAvail, mainLen, numPairs, repMaxIndex, i, posState, lenEnd, len, cur;
972 LZ_UInt32 matchPrice, repMatchPrice, normalMatchPrice;
973 LZ_UInt32 reps[LZMA_NUM_REPS], repLens[LZMA_NUM_REPS];
974 LZ_UInt32 *matches;
975 const Byte *data;
976 Byte curByte, matchByte;
977 if (p->optimumEndIndex != p->optimumCurrentIndex)
978 {
979 const COptimal *opt = &p->opt[p->optimumCurrentIndex];
980 LZ_UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex;
981 *backRes = opt->backPrev;
982 p->optimumCurrentIndex = opt->posPrev;
983 return lenRes;
984 }
985 p->optimumCurrentIndex = p->optimumEndIndex = 0;
986
987 if (p->additionalOffset == 0)
988 mainLen = ReadMatchDistances(p, &numPairs);
989 else
990 {
991 mainLen = p->longestMatchLength;
992 numPairs = p->numPairs;
993 }
994
995 numAvail = p->numAvail;
996 if (numAvail < 2)
997 {
998 *backRes = (LZ_UInt32)(-1);
999 return 1;
1000 }
1001 if (numAvail > LZMA_MATCH_LEN_MAX)
1002 numAvail = LZMA_MATCH_LEN_MAX;
1003
1004 data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1005 repMaxIndex = 0;
1006 for (i = 0; i < LZMA_NUM_REPS; i++)
1007 {
1008 LZ_UInt32 lenTest;
1009 const Byte *data2;
1010 reps[i] = p->reps[i];
1011 data2 = data - (reps[i] + 1);
1012 if (data[0] != data2[0] || data[1] != data2[1])
1013 {
1014 repLens[i] = 0;
1015 continue;
1016 }
1017 for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++);
1018 repLens[i] = lenTest;
1019 if (lenTest > repLens[repMaxIndex])
1020 repMaxIndex = i;
1021 }
1022 if (repLens[repMaxIndex] >= p->numFastBytes)
1023 {
1024 LZ_UInt32 lenRes;
1025 *backRes = repMaxIndex;
1026 lenRes = repLens[repMaxIndex];
1027 MovePos(p, lenRes - 1);
1028 return lenRes;
1029 }
1030
1031 matches = p->matches;
1032 if (mainLen >= p->numFastBytes)
1033 {
1034 *backRes = matches[numPairs - 1] + LZMA_NUM_REPS;
1035 MovePos(p, mainLen - 1);
1036 return mainLen;
1037 }
1038 curByte = *data;
1039 matchByte = *(data - (reps[0] + 1));
1040
1041 if (mainLen < 2 && curByte != matchByte && repLens[repMaxIndex] < 2)
1042 {
1043 *backRes = (LZ_UInt32)-1;
1044 return 1;
1045 }
1046
1047 p->opt[0].state = (CState)p->state;
1048
1049 posState = (position & p->pbMask);
1050
1051 {
1052 const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
1053 p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) +
1054 (!IsCharState(p->state) ?
1055 LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) :
1056 LitEnc_GetPrice(probs, curByte, p->ProbPrices));
1057 }
1058
1059 MakeAsChar(&p->opt[1]);
1060
1061 matchPrice = GET_PRICE_1(p->isMatch[p->state][posState]);
1062 repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[p->state]);
1063
1064 if (matchByte == curByte)
1065 {
1066 LZ_UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState);
1067 if (shortRepPrice < p->opt[1].price)
1068 {
1069 p->opt[1].price = shortRepPrice;
1070 MakeAsShortRep(&p->opt[1]);
1071 }
1072 }
1073 lenEnd = ((mainLen >= repLens[repMaxIndex]) ? mainLen : repLens[repMaxIndex]);
1074
1075 if (lenEnd < 2)
1076 {
1077 *backRes = p->opt[1].backPrev;
1078 return 1;
1079 }
1080
1081 p->opt[1].posPrev = 0;
1082 for (i = 0; i < LZMA_NUM_REPS; i++)
1083 p->opt[0].backs[i] = reps[i];
1084
1085 len = lenEnd;
1086 do
1087 p->opt[len--].price = kInfinityPrice;
1088 while (len >= 2);
1089
1090 for (i = 0; i < LZMA_NUM_REPS; i++)
1091 {
1092 LZ_UInt32 repLen = repLens[i];
1093 LZ_UInt32 price;
1094 if (repLen < 2)
1095 continue;
1096 price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState);
1097 do
1098 {
1099 LZ_UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2];
1100 COptimal *opt = &p->opt[repLen];
1101 if (curAndLenPrice < opt->price)
1102 {
1103 opt->price = curAndLenPrice;
1104 opt->posPrev = 0;
1105 opt->backPrev = i;
1106 opt->prev1IsChar = False;
1107 }
1108 }
1109 while (--repLen >= 2);
1110 }
1111
1112 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]);
1113
1114 len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
1115 if (len <= mainLen)
1116 {
1117 LZ_UInt32 offs = 0;
1118 while (len > matches[offs])
1119 offs += 2;
1120 for (; ; len++)
1121 {
1122 COptimal *opt;
1123 LZ_UInt32 distance = matches[offs + 1];
1124
1125 LZ_UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN];
1126 LZ_UInt32 lenToPosState = GetLenToPosState(len);
1127 if (distance < kNumFullDistances)
1128 curAndLenPrice += p->distancesPrices[lenToPosState][distance];
1129 else
1130 {
1131 LZ_UInt32 slot;
1132 GetPosSlot2(distance, slot);
1133 curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot];
1134 }
1135 opt = &p->opt[len];
1136 if (curAndLenPrice < opt->price)
1137 {
1138 opt->price = curAndLenPrice;
1139 opt->posPrev = 0;
1140 opt->backPrev = distance + LZMA_NUM_REPS;
1141 opt->prev1IsChar = False;
1142 }
1143 if (len == matches[offs])
1144 {
1145 offs += 2;
1146 if (offs == numPairs)
1147 break;
1148 }
1149 }
1150 }
1151
1152 cur = 0;
1153
1154 #ifdef SHOW_STAT2
1155 if (position >= 0)
1156 {
1157 unsigned i;
1158 printf("\n pos = %4X", position);
1159 for (i = cur; i <= lenEnd; i++)
1160 printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price);
1161 }
1162 #endif
1163
1164 for (;;)
1165 {
1166 LZ_UInt32 numAvailFull, newLen, numPairs, posPrev, state, posState, startLen;
1167 LZ_UInt32 curPrice, curAnd1Price, matchPrice, repMatchPrice;
1168 int nextIsChar;
1169 Byte curByte, matchByte;
1170 const Byte *data;
1171 COptimal *curOpt;
1172 COptimal *nextOpt;
1173
1174 cur++;
1175 if (cur == lenEnd)
1176 return Backward(p, backRes, cur);
1177
1178 newLen = ReadMatchDistances(p, &numPairs);
1179 if (newLen >= p->numFastBytes)
1180 {
1181 p->numPairs = numPairs;
1182 p->longestMatchLength = newLen;
1183 return Backward(p, backRes, cur);
1184 }
1185 position++;
1186 curOpt = &p->opt[cur];
1187 posPrev = curOpt->posPrev;
1188 if (curOpt->prev1IsChar)
1189 {
1190 posPrev--;
1191 if (curOpt->prev2)
1192 {
1193 state = p->opt[curOpt->posPrev2].state;
1194 if (curOpt->backPrev2 < LZMA_NUM_REPS)
1195 state = kRepNextStates[state];
1196 else
1197 state = kMatchNextStates[state];
1198 }
1199 else
1200 state = p->opt[posPrev].state;
1201 state = kLiteralNextStates[state];
1202 }
1203 else
1204 state = p->opt[posPrev].state;
1205 if (posPrev == cur - 1)
1206 {
1207 if (IsShortRep(curOpt))
1208 state = kShortRepNextStates[state];
1209 else
1210 state = kLiteralNextStates[state];
1211 }
1212 else
1213 {
1214 LZ_UInt32 pos;
1215 const COptimal *prevOpt;
1216 if (curOpt->prev1IsChar && curOpt->prev2)
1217 {
1218 posPrev = curOpt->posPrev2;
1219 pos = curOpt->backPrev2;
1220 state = kRepNextStates[state];
1221 }
1222 else
1223 {
1224 pos = curOpt->backPrev;
1225 if (pos < LZMA_NUM_REPS)
1226 state = kRepNextStates[state];
1227 else
1228 state = kMatchNextStates[state];
1229 }
1230 prevOpt = &p->opt[posPrev];
1231 if (pos < LZMA_NUM_REPS)
1232 {
1233 LZ_UInt32 i;
1234 reps[0] = prevOpt->backs[pos];
1235 for (i = 1; i <= pos; i++)
1236 reps[i] = prevOpt->backs[i - 1];
1237 for (; i < LZMA_NUM_REPS; i++)
1238 reps[i] = prevOpt->backs[i];
1239 }
1240 else
1241 {
1242 LZ_UInt32 i;
1243 reps[0] = (pos - LZMA_NUM_REPS);
1244 for (i = 1; i < LZMA_NUM_REPS; i++)
1245 reps[i] = prevOpt->backs[i - 1];
1246 }
1247 }
1248 curOpt->state = (CState)state;
1249
1250 curOpt->backs[0] = reps[0];
1251 curOpt->backs[1] = reps[1];
1252 curOpt->backs[2] = reps[2];
1253 curOpt->backs[3] = reps[3];
1254
1255 curPrice = curOpt->price;
1256 nextIsChar = False;
1257 data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1258 curByte = *data;
1259 matchByte = *(data - (reps[0] + 1));
1260
1261 posState = (position & p->pbMask);
1262
1263 curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]);
1264 {
1265 const CLzmaProb *probs = LIT_PROBS(position, *(data - 1));
1266 curAnd1Price +=
1267 (!IsCharState(state) ?
1268 LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) :
1269 LitEnc_GetPrice(probs, curByte, p->ProbPrices));
1270 }
1271
1272 nextOpt = &p->opt[cur + 1];
1273
1274 if (curAnd1Price < nextOpt->price)
1275 {
1276 nextOpt->price = curAnd1Price;
1277 nextOpt->posPrev = cur;
1278 MakeAsChar(nextOpt);
1279 nextIsChar = True;
1280 }
1281
1282 matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]);
1283 repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]);
1284
1285 if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0))
1286 {
1287 LZ_UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState);
1288 if (shortRepPrice <= nextOpt->price)
1289 {
1290 nextOpt->price = shortRepPrice;
1291 nextOpt->posPrev = cur;
1292 MakeAsShortRep(nextOpt);
1293 nextIsChar = True;
1294 }
1295 }
1296 numAvailFull = p->numAvail;
1297 {
1298 LZ_UInt32 temp = kNumOpts - 1 - cur;
1299 if (temp < numAvailFull)
1300 numAvailFull = temp;
1301 }
1302
1303 if (numAvailFull < 2)
1304 continue;
1305 numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes);
1306
1307 if (!nextIsChar && matchByte != curByte) /* speed optimization */
1308 {
1309 /* try Literal + rep0 */
1310 LZ_UInt32 temp;
1311 LZ_UInt32 lenTest2;
1312 const Byte *data2 = data - (reps[0] + 1);
1313 LZ_UInt32 limit = p->numFastBytes + 1;
1314 if (limit > numAvailFull)
1315 limit = numAvailFull;
1316
1317 for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++);
1318 lenTest2 = temp - 1;
1319 if (lenTest2 >= 2)
1320 {
1321 LZ_UInt32 state2 = kLiteralNextStates[state];
1322 LZ_UInt32 posStateNext = (position + 1) & p->pbMask;
1323 LZ_UInt32 nextRepMatchPrice = curAnd1Price +
1324 GET_PRICE_1(p->isMatch[state2][posStateNext]) +
1325 GET_PRICE_1(p->isRep[state2]);
1326 /* for (; lenTest2 >= 2; lenTest2--) */
1327 {
1328 LZ_UInt32 curAndLenPrice;
1329 COptimal *opt;
1330 LZ_UInt32 offset = cur + 1 + lenTest2;
1331 while (lenEnd < offset)
1332 p->opt[++lenEnd].price = kInfinityPrice;
1333 curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
1334 opt = &p->opt[offset];
1335 if (curAndLenPrice < opt->price)
1336 {
1337 opt->price = curAndLenPrice;
1338 opt->posPrev = cur + 1;
1339 opt->backPrev = 0;
1340 opt->prev1IsChar = True;
1341 opt->prev2 = False;
1342 }
1343 }
1344 }
1345 }
1346
1347 startLen = 2; /* speed optimization */
1348 {
1349 LZ_UInt32 repIndex;
1350 for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++)
1351 {
1352 LZ_UInt32 lenTest;
1353 LZ_UInt32 lenTestTemp;
1354 LZ_UInt32 price;
1355 const Byte *data2 = data - (reps[repIndex] + 1);
1356 if (data[0] != data2[0] || data[1] != data2[1])
1357 continue;
1358 for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++);
1359 while (lenEnd < cur + lenTest)
1360 p->opt[++lenEnd].price = kInfinityPrice;
1361 lenTestTemp = lenTest;
1362 price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState);
1363 do
1364 {
1365 LZ_UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2];
1366 COptimal *opt = &p->opt[cur + lenTest];
1367 if (curAndLenPrice < opt->price)
1368 {
1369 opt->price = curAndLenPrice;
1370 opt->posPrev = cur;
1371 opt->backPrev = repIndex;
1372 opt->prev1IsChar = False;
1373 }
1374 }
1375 while (--lenTest >= 2);
1376 lenTest = lenTestTemp;
1377
1378 if (repIndex == 0)
1379 startLen = lenTest + 1;
1380
1381 /* if (_maxMode) */
1382 {
1383 LZ_UInt32 lenTest2 = lenTest + 1;
1384 LZ_UInt32 limit = lenTest2 + p->numFastBytes;
1385 LZ_UInt32 nextRepMatchPrice;
1386 if (limit > numAvailFull)
1387 limit = numAvailFull;
1388 for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
1389 lenTest2 -= lenTest + 1;
1390 if (lenTest2 >= 2)
1391 {
1392 LZ_UInt32 state2 = kRepNextStates[state];
1393 LZ_UInt32 posStateNext = (position + lenTest) & p->pbMask;
1394 LZ_UInt32 curAndLenCharPrice =
1395 price + p->repLenEnc.prices[posState][lenTest - 2] +
1396 GET_PRICE_0(p->isMatch[state2][posStateNext]) +
1397 LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
1398 data[lenTest], data2[lenTest], p->ProbPrices);
1399 state2 = kLiteralNextStates[state2];
1400 posStateNext = (position + lenTest + 1) & p->pbMask;
1401 nextRepMatchPrice = curAndLenCharPrice +
1402 GET_PRICE_1(p->isMatch[state2][posStateNext]) +
1403 GET_PRICE_1(p->isRep[state2]);
1404
1405 /* for (; lenTest2 >= 2; lenTest2--) */
1406 {
1407 LZ_UInt32 curAndLenPrice;
1408 COptimal *opt;
1409 LZ_UInt32 offset = cur + lenTest + 1 + lenTest2;
1410 while (lenEnd < offset)
1411 p->opt[++lenEnd].price = kInfinityPrice;
1412 curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
1413 opt = &p->opt[offset];
1414 if (curAndLenPrice < opt->price)
1415 {
1416 opt->price = curAndLenPrice;
1417 opt->posPrev = cur + lenTest + 1;
1418 opt->backPrev = 0;
1419 opt->prev1IsChar = True;
1420 opt->prev2 = True;
1421 opt->posPrev2 = cur;
1422 opt->backPrev2 = repIndex;
1423 }
1424 }
1425 }
1426 }
1427 }
1428 }
1429 /* for (LZ_UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */
1430 if (newLen > numAvail)
1431 {
1432 newLen = numAvail;
1433 for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2);
1434 matches[numPairs] = newLen;
1435 numPairs += 2;
1436 }
1437 if (newLen >= startLen)
1438 {
1439 LZ_UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]);
1440 LZ_UInt32 offs, curBack, posSlot;
1441 LZ_UInt32 lenTest;
1442 while (lenEnd < cur + newLen)
1443 p->opt[++lenEnd].price = kInfinityPrice;
1444
1445 offs = 0;
1446 while (startLen > matches[offs])
1447 offs += 2;
1448 curBack = matches[offs + 1];
1449 GetPosSlot2(curBack, posSlot);
1450 for (lenTest = /*2*/ startLen; ; lenTest++)
1451 {
1452 LZ_UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN];
1453 LZ_UInt32 lenToPosState = GetLenToPosState(lenTest);
1454 COptimal *opt;
1455 if (curBack < kNumFullDistances)
1456 curAndLenPrice += p->distancesPrices[lenToPosState][curBack];
1457 else
1458 curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask];
1459
1460 opt = &p->opt[cur + lenTest];
1461 if (curAndLenPrice < opt->price)
1462 {
1463 opt->price = curAndLenPrice;
1464 opt->posPrev = cur;
1465 opt->backPrev = curBack + LZMA_NUM_REPS;
1466 opt->prev1IsChar = False;
1467 }
1468
1469 if (/*_maxMode && */lenTest == matches[offs])
1470 {
1471 /* Try Match + Literal + Rep0 */
1472 const Byte *data2 = data - (curBack + 1);
1473 LZ_UInt32 lenTest2 = lenTest + 1;
1474 LZ_UInt32 limit = lenTest2 + p->numFastBytes;
1475 LZ_UInt32 nextRepMatchPrice;
1476 if (limit > numAvailFull)
1477 limit = numAvailFull;
1478 for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++);
1479 lenTest2 -= lenTest + 1;
1480 if (lenTest2 >= 2)
1481 {
1482 LZ_UInt32 state2 = kMatchNextStates[state];
1483 LZ_UInt32 posStateNext = (position + lenTest) & p->pbMask;
1484 LZ_UInt32 curAndLenCharPrice = curAndLenPrice +
1485 GET_PRICE_0(p->isMatch[state2][posStateNext]) +
1486 LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]),
1487 data[lenTest], data2[lenTest], p->ProbPrices);
1488 state2 = kLiteralNextStates[state2];
1489 posStateNext = (posStateNext + 1) & p->pbMask;
1490 nextRepMatchPrice = curAndLenCharPrice +
1491 GET_PRICE_1(p->isMatch[state2][posStateNext]) +
1492 GET_PRICE_1(p->isRep[state2]);
1493
1494 /* for (; lenTest2 >= 2; lenTest2--) */
1495 {
1496 LZ_UInt32 offset = cur + lenTest + 1 + lenTest2;
1497 LZ_UInt32 curAndLenPrice;
1498 COptimal *opt;
1499 while (lenEnd < offset)
1500 p->opt[++lenEnd].price = kInfinityPrice;
1501 curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext);
1502 opt = &p->opt[offset];
1503 if (curAndLenPrice < opt->price)
1504 {
1505 opt->price = curAndLenPrice;
1506 opt->posPrev = cur + lenTest + 1;
1507 opt->backPrev = 0;
1508 opt->prev1IsChar = True;
1509 opt->prev2 = True;
1510 opt->posPrev2 = cur;
1511 opt->backPrev2 = curBack + LZMA_NUM_REPS;
1512 }
1513 }
1514 }
1515 offs += 2;
1516 if (offs == numPairs)
1517 break;
1518 curBack = matches[offs + 1];
1519 if (curBack >= kNumFullDistances)
1520 GetPosSlot2(curBack, posSlot);
1521 }
1522 }
1523 }
1524 }
1525 }
1526
1527 #define ChangePair(smallDist, bigDist) (((bigDist) >> 7) > (smallDist))
1528
1529 static LZ_UInt32 GetOptimumFast(CLzmaEnc *p, LZ_UInt32 *backRes)
1530 {
1531 LZ_UInt32 numAvail, mainLen, mainDist, numPairs, repIndex, repLen, i;
1532 const Byte *data;
1533 const LZ_UInt32 *matches;
1534
1535 if (p->additionalOffset == 0)
1536 mainLen = ReadMatchDistances(p, &numPairs);
1537 else
1538 {
1539 mainLen = p->longestMatchLength;
1540 numPairs = p->numPairs;
1541 }
1542
1543 numAvail = p->numAvail;
1544 *backRes = (LZ_UInt32)-1;
1545 if (numAvail < 2)
1546 return 1;
1547 if (numAvail > LZMA_MATCH_LEN_MAX)
1548 numAvail = LZMA_MATCH_LEN_MAX;
1549 data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1550
1551 repLen = repIndex = 0;
1552 for (i = 0; i < LZMA_NUM_REPS; i++)
1553 {
1554 LZ_UInt32 len;
1555 const Byte *data2 = data - (p->reps[i] + 1);
1556 if (data[0] != data2[0] || data[1] != data2[1])
1557 continue;
1558 for (len = 2; len < numAvail && data[len] == data2[len]; len++);
1559 if (len >= p->numFastBytes)
1560 {
1561 *backRes = i;
1562 MovePos(p, len - 1);
1563 return len;
1564 }
1565 if (len > repLen)
1566 {
1567 repIndex = i;
1568 repLen = len;
1569 }
1570 }
1571
1572 matches = p->matches;
1573 if (mainLen >= p->numFastBytes)
1574 {
1575 *backRes = matches[numPairs - 1] + LZMA_NUM_REPS;
1576 MovePos(p, mainLen - 1);
1577 return mainLen;
1578 }
1579
1580 mainDist = 0; /* for GCC */
1581 if (mainLen >= 2)
1582 {
1583 mainDist = matches[numPairs - 1];
1584 while (numPairs > 2 && mainLen == matches[numPairs - 4] + 1)
1585 {
1586 if (!ChangePair(matches[numPairs - 3], mainDist))
1587 break;
1588 numPairs -= 2;
1589 mainLen = matches[numPairs - 2];
1590 mainDist = matches[numPairs - 1];
1591 }
1592 if (mainLen == 2 && mainDist >= 0x80)
1593 mainLen = 1;
1594 }
1595
1596 if (repLen >= 2 && (
1597 (repLen + 1 >= mainLen) ||
1598 (repLen + 2 >= mainLen && mainDist >= (1 << 9)) ||
1599 (repLen + 3 >= mainLen && mainDist >= (1 << 15))))
1600 {
1601 *backRes = repIndex;
1602 MovePos(p, repLen - 1);
1603 return repLen;
1604 }
1605
1606 if (mainLen < 2 || numAvail <= 2)
1607 return 1;
1608
1609 p->longestMatchLength = ReadMatchDistances(p, &p->numPairs);
1610 if (p->longestMatchLength >= 2)
1611 {
1612 LZ_UInt32 newDistance = matches[p->numPairs - 1];
1613 if ((p->longestMatchLength >= mainLen && newDistance < mainDist) ||
1614 (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) ||
1615 (p->longestMatchLength > mainLen + 1) ||
1616 (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist)))
1617 return 1;
1618 }
1619
1620 data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1;
1621 for (i = 0; i < LZMA_NUM_REPS; i++)
1622 {
1623 LZ_UInt32 len, limit;
1624 const Byte *data2 = data - (p->reps[i] + 1);
1625 if (data[0] != data2[0] || data[1] != data2[1])
1626 continue;
1627 limit = mainLen - 1;
1628 for (len = 2; len < limit && data[len] == data2[len]; len++);
1629 if (len >= limit)
1630 return 1;
1631 }
1632 *backRes = mainDist + LZMA_NUM_REPS;
1633 MovePos(p, mainLen - 2);
1634 return mainLen;
1635 }
1636
1637 static void WriteEndMarker(CLzmaEnc *p, LZ_UInt32 posState)
1638 {
1639 LZ_UInt32 len;
1640 RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
1641 RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
1642 p->state = kMatchNextStates[p->state];
1643 len = LZMA_MATCH_LEN_MIN;
1644 LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
1645 RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, (1 << kNumPosSlotBits) - 1);
1646 RangeEnc_EncodeDirectBits(&p->rc, (((LZ_UInt32)1 << 30) - 1) >> kNumAlignBits, 30 - kNumAlignBits);
1647 RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, kAlignMask);
1648 }
1649
1650 static SRes CheckErrors(CLzmaEnc *p)
1651 {
1652 if (p->result != SZ_OK)
1653 return p->result;
1654 if (p->rc.res != SZ_OK)
1655 p->result = SZ_ERROR_WRITE;
1656 if (p->matchFinderBase.result != SZ_OK)
1657 p->result = SZ_ERROR_READ;
1658 if (p->result != SZ_OK)
1659 p->finished = True;
1660 return p->result;
1661 }
1662
1663 static SRes Flush(CLzmaEnc *p, LZ_UInt32 nowPos)
1664 {
1665 /* ReleaseMFStream(); */
1666 p->finished = True;
1667 if (p->writeEndMark)
1668 WriteEndMarker(p, nowPos & p->pbMask);
1669 RangeEnc_FlushData(&p->rc);
1670 RangeEnc_FlushStream(&p->rc);
1671 return CheckErrors(p);
1672 }
1673
1674 static void FillAlignPrices(CLzmaEnc *p)
1675 {
1676 LZ_UInt32 i;
1677 for (i = 0; i < kAlignTableSize; i++)
1678 p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices);
1679 p->alignPriceCount = 0;
1680 }
1681
1682 static void FillDistancesPrices(CLzmaEnc *p)
1683 {
1684 LZ_UInt32 tempPrices[kNumFullDistances];
1685 LZ_UInt32 i, lenToPosState;
1686 for (i = kStartPosModelIndex; i < kNumFullDistances; i++)
1687 {
1688 LZ_UInt32 posSlot = GetPosSlot1(i);
1689 LZ_UInt32 footerBits = ((posSlot >> 1) - 1);
1690 LZ_UInt32 base = ((2 | (posSlot & 1)) << footerBits);
1691 tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices);
1692 }
1693
1694 for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++)
1695 {
1696 LZ_UInt32 posSlot;
1697 const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState];
1698 LZ_UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState];
1699 for (posSlot = 0; posSlot < p->distTableSize; posSlot++)
1700 posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices);
1701 for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++)
1702 posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits);
1703
1704 {
1705 LZ_UInt32 *distancesPrices = p->distancesPrices[lenToPosState];
1706 LZ_UInt32 i;
1707 for (i = 0; i < kStartPosModelIndex; i++)
1708 distancesPrices[i] = posSlotPrices[i];
1709 for (; i < kNumFullDistances; i++)
1710 distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i];
1711 }
1712 }
1713 p->matchPriceCount = 0;
1714 }
1715
1716 void LzmaEnc_Construct(CLzmaEnc *p)
1717 {
1718 RangeEnc_Construct(&p->rc);
1719 MatchFinder_Construct(&p->matchFinderBase);
1720 #ifdef COMPRESS_MF_MT
1721 MatchFinderMt_Construct(&p->matchFinderMt);
1722 p->matchFinderMt.MatchFinder = &p->matchFinderBase;
1723 #endif
1724
1725 {
1726 CLzmaEncProps props;
1727 LzmaEncProps_Init(&props);
1728 LzmaEnc_SetProps(p, &props);
1729 }
1730
1731 #ifndef LZMA_LOG_BSR
1732 LzmaEnc_FastPosInit(p->g_FastPos);
1733 #endif
1734
1735 LzmaEnc_InitPriceTables(p->ProbPrices);
1736 p->litProbs = 0;
1737 p->saveState.litProbs = 0;
1738 }
1739
1740 CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc)
1741 {
1742 void *p;
1743 p = alloc->Alloc(alloc, sizeof(CLzmaEnc));
1744 if (p != 0)
1745 LzmaEnc_Construct((CLzmaEnc *)p);
1746 return p;
1747 }
1748
1749 void LzmaEnc_FreeLits(CLzmaEnc *p, ISzAlloc *alloc)
1750 {
1751 alloc->Free(alloc, p->litProbs);
1752 alloc->Free(alloc, p->saveState.litProbs);
1753 p->litProbs = 0;
1754 p->saveState.litProbs = 0;
1755 }
1756
1757 void LzmaEnc_Destruct(CLzmaEnc *p, ISzAlloc *alloc, ISzAlloc *allocBig)
1758 {
1759 #ifdef COMPRESS_MF_MT
1760 MatchFinderMt_Destruct(&p->matchFinderMt, allocBig);
1761 #endif
1762 MatchFinder_Free(&p->matchFinderBase, allocBig);
1763 LzmaEnc_FreeLits(p, alloc);
1764 RangeEnc_Free(&p->rc, alloc);
1765 }
1766
1767 void LzmaEnc_Destroy(CLzmaEncHandle p, ISzAlloc *alloc, ISzAlloc *allocBig)
1768 {
1769 LzmaEnc_Destruct((CLzmaEnc *)p, alloc, allocBig);
1770 alloc->Free(alloc, p);
1771 }
1772
1773 static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, int useLimits, LZ_UInt32 maxPackSize, LZ_UInt32 maxUnpackSize)
1774 {
1775 LZ_UInt32 nowPos32, startPos32;
1776 if (p->inStream != 0)
1777 {
1778 p->matchFinderBase.stream = p->inStream;
1779 p->matchFinder.Init(p->matchFinderObj);
1780 p->inStream = 0;
1781 }
1782
1783 if (p->finished)
1784 return p->result;
1785 RINOK(CheckErrors(p));
1786
1787 nowPos32 = (LZ_UInt32)p->nowPos64;
1788 startPos32 = nowPos32;
1789
1790 if (p->nowPos64 == 0)
1791 {
1792 LZ_UInt32 numPairs;
1793 Byte curByte;
1794 if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
1795 return Flush(p, nowPos32);
1796 ReadMatchDistances(p, &numPairs);
1797 RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0);
1798 p->state = kLiteralNextStates[p->state];
1799 curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset);
1800 LitEnc_Encode(&p->rc, p->litProbs, curByte);
1801 p->additionalOffset--;
1802 nowPos32++;
1803 }
1804
1805 if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0)
1806 for (;;)
1807 {
1808 LZ_UInt32 pos, len, posState;
1809
1810 if (p->fastMode)
1811 len = GetOptimumFast(p, &pos);
1812 else
1813 len = GetOptimum(p, nowPos32, &pos);
1814
1815 #ifdef SHOW_STAT2
1816 printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos);
1817 #endif
1818
1819 posState = nowPos32 & p->pbMask;
1820 if (len == 1 && pos == (LZ_UInt32)-1)
1821 {
1822 Byte curByte;
1823 CLzmaProb *probs;
1824 const Byte *data;
1825
1826 RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0);
1827 data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
1828 curByte = *data;
1829 probs = LIT_PROBS(nowPos32, *(data - 1));
1830 if (IsCharState(p->state))
1831 LitEnc_Encode(&p->rc, probs, curByte);
1832 else
1833 LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1));
1834 p->state = kLiteralNextStates[p->state];
1835 }
1836 else
1837 {
1838 RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1);
1839 if (pos < LZMA_NUM_REPS)
1840 {
1841 RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1);
1842 if (pos == 0)
1843 {
1844 RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0);
1845 RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1));
1846 }
1847 else
1848 {
1849 LZ_UInt32 distance = p->reps[pos];
1850 RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1);
1851 if (pos == 1)
1852 RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0);
1853 else
1854 {
1855 RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1);
1856 RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2);
1857 if (pos == 3)
1858 p->reps[3] = p->reps[2];
1859 p->reps[2] = p->reps[1];
1860 }
1861 p->reps[1] = p->reps[0];
1862 p->reps[0] = distance;
1863 }
1864 if (len == 1)
1865 p->state = kShortRepNextStates[p->state];
1866 else
1867 {
1868 LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
1869 p->state = kRepNextStates[p->state];
1870 }
1871 }
1872 else
1873 {
1874 LZ_UInt32 posSlot;
1875 RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0);
1876 p->state = kMatchNextStates[p->state];
1877 LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices);
1878 pos -= LZMA_NUM_REPS;
1879 GetPosSlot(pos, posSlot);
1880 RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot);
1881
1882 if (posSlot >= kStartPosModelIndex)
1883 {
1884 LZ_UInt32 footerBits = ((posSlot >> 1) - 1);
1885 LZ_UInt32 base = ((2 | (posSlot & 1)) << footerBits);
1886 LZ_UInt32 posReduced = pos - base;
1887
1888 if (posSlot < kEndPosModelIndex)
1889 RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced);
1890 else
1891 {
1892 RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits);
1893 RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask);
1894 p->alignPriceCount++;
1895 }
1896 }
1897 p->reps[3] = p->reps[2];
1898 p->reps[2] = p->reps[1];
1899 p->reps[1] = p->reps[0];
1900 p->reps[0] = pos;
1901 p->matchPriceCount++;
1902 }
1903 }
1904 p->additionalOffset -= len;
1905 nowPos32 += len;
1906 if (p->additionalOffset == 0)
1907 {
1908 LZ_UInt32 processed;
1909 if (!p->fastMode)
1910 {
1911 if (p->matchPriceCount >= (1 << 7))
1912 FillDistancesPrices(p);
1913 if (p->alignPriceCount >= kAlignTableSize)
1914 FillAlignPrices(p);
1915 }
1916 if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0)
1917 break;
1918 processed = nowPos32 - startPos32;
1919 if (useLimits)
1920 {
1921 if (processed + kNumOpts + 300 >= maxUnpackSize ||
1922 RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize)
1923 break;
1924 }
1925 else if (processed >= (1 << 15))
1926 {
1927 p->nowPos64 += nowPos32 - startPos32;
1928 return CheckErrors(p);
1929 }
1930 }
1931 }
1932 p->nowPos64 += nowPos32 - startPos32;
1933 return Flush(p, nowPos32);
1934 }
1935
1936 #define kBigHashDicLimit ((LZ_UInt32)1 << 24)
1937
1938 static SRes LzmaEnc_Alloc(CLzmaEnc *p, LZ_UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
1939 {
1940 LZ_UInt32 beforeSize = kNumOpts;
1941 if (!RangeEnc_Alloc(&p->rc, alloc))
1942 return SZ_ERROR_MEM;
1943
1944 #ifdef COMPRESS_MF_MT
1945 int btMode;
1946 btMode = (p->matchFinderBase.btMode != 0);
1947 p->mtMode = (p->multiThread && !p->fastMode && btMode);
1948 #endif
1949
1950 {
1951 unsigned lclp = p->lc + p->lp;
1952 if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp)
1953 {
1954 LzmaEnc_FreeLits(p, alloc);
1955 p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
1956 p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb));
1957 if (p->litProbs == 0 || p->saveState.litProbs == 0)
1958 {
1959 LzmaEnc_FreeLits(p, alloc);
1960 return SZ_ERROR_MEM;
1961 }
1962 p->lclp = lclp;
1963 }
1964 }
1965
1966 p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit);
1967
1968 if (beforeSize + p->dictSize < keepWindowSize)
1969 beforeSize = keepWindowSize - p->dictSize;
1970
1971 #ifdef COMPRESS_MF_MT
1972 if (p->mtMode)
1973 {
1974 RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig));
1975 p->matchFinderObj = &p->matchFinderMt;
1976 MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder);
1977 }
1978 else
1979 #endif
1980 {
1981 if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig))
1982 return SZ_ERROR_MEM;
1983 p->matchFinderObj = &p->matchFinderBase;
1984 MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder);
1985 }
1986 return SZ_OK;
1987 }
1988
1989 void LzmaEnc_Init(CLzmaEnc *p)
1990 {
1991 LZ_UInt32 i;
1992 p->state = 0;
1993 for (i = 0 ; i < LZMA_NUM_REPS; i++)
1994 p->reps[i] = 0;
1995
1996 RangeEnc_Init(&p->rc);
1997
1998
1999 for (i = 0; i < kNumStates; i++)
2000 {
2001 LZ_UInt32 j;
2002 for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++)
2003 {
2004 p->isMatch[i][j] = kProbInitValue;
2005 p->isRep0Long[i][j] = kProbInitValue;
2006 }
2007 p->isRep[i] = kProbInitValue;
2008 p->isRepG0[i] = kProbInitValue;
2009 p->isRepG1[i] = kProbInitValue;
2010 p->isRepG2[i] = kProbInitValue;
2011 }
2012
2013 {
2014 LZ_UInt32 num = 0x300 << (p->lp + p->lc);
2015 for (i = 0; i < num; i++)
2016 p->litProbs[i] = kProbInitValue;
2017 }
2018
2019 {
2020 for (i = 0; i < kNumLenToPosStates; i++)
2021 {
2022 CLzmaProb *probs = p->posSlotEncoder[i];
2023 LZ_UInt32 j;
2024 for (j = 0; j < (1 << kNumPosSlotBits); j++)
2025 probs[j] = kProbInitValue;
2026 }
2027 }
2028 {
2029 for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++)
2030 p->posEncoders[i] = kProbInitValue;
2031 }
2032
2033 LenEnc_Init(&p->lenEnc.p);
2034 LenEnc_Init(&p->repLenEnc.p);
2035
2036 for (i = 0; i < (1 << kNumAlignBits); i++)
2037 p->posAlignEncoder[i] = kProbInitValue;
2038
2039 p->optimumEndIndex = 0;
2040 p->optimumCurrentIndex = 0;
2041 p->additionalOffset = 0;
2042
2043 p->pbMask = (1 << p->pb) - 1;
2044 p->lpMask = (1 << p->lp) - 1;
2045 }
2046
2047 void LzmaEnc_InitPrices(CLzmaEnc *p)
2048 {
2049 if (!p->fastMode)
2050 {
2051 FillDistancesPrices(p);
2052 FillAlignPrices(p);
2053 }
2054
2055 p->lenEnc.tableSize =
2056 p->repLenEnc.tableSize =
2057 p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN;
2058 LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices);
2059 LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices);
2060 }
2061
2062 static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, LZ_UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
2063 {
2064 LZ_UInt32 i;
2065 for (i = 0; i < (LZ_UInt32)kDicLogSizeMaxCompress; i++)
2066 if (p->dictSize <= ((LZ_UInt32)1 << i))
2067 break;
2068 p->distTableSize = i * 2;
2069
2070 p->finished = False;
2071 p->result = SZ_OK;
2072 RINOK(LzmaEnc_Alloc(p, keepWindowSize, alloc, allocBig));
2073 LzmaEnc_Init(p);
2074 LzmaEnc_InitPrices(p);
2075 p->nowPos64 = 0;
2076 return SZ_OK;
2077 }
2078
2079 static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqInStream *inStream, ISeqOutStream *outStream,
2080 ISzAlloc *alloc, ISzAlloc *allocBig)
2081 {
2082 CLzmaEnc *p = (CLzmaEnc *)pp;
2083 p->inStream = inStream;
2084 p->rc.outStream = outStream;
2085 return LzmaEnc_AllocAndInit(p, 0, alloc, allocBig);
2086 }
2087
2088 SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp,
2089 ISeqInStream *inStream, LZ_UInt32 keepWindowSize,
2090 ISzAlloc *alloc, ISzAlloc *allocBig)
2091 {
2092 CLzmaEnc *p = (CLzmaEnc *)pp;
2093 p->inStream = inStream;
2094 return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
2095 }
2096
2097 static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen)
2098 {
2099 p->seqBufInStream.funcTable.Read = MyRead;
2100 p->seqBufInStream.data = src;
2101 p->seqBufInStream.rem = srcLen;
2102 }
2103
2104 SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen,
2105 LZ_UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig)
2106 {
2107 CLzmaEnc *p = (CLzmaEnc *)pp;
2108 LzmaEnc_SetInputBuf(p, src, srcLen);
2109 p->inStream = &p->seqBufInStream.funcTable;
2110 return LzmaEnc_AllocAndInit(p, keepWindowSize, alloc, allocBig);
2111 }
2112
2113 void LzmaEnc_Finish(CLzmaEncHandle pp)
2114 {
2115 #ifdef COMPRESS_MF_MT
2116 CLzmaEnc *p = (CLzmaEnc *)pp;
2117 if (p->mtMode)
2118 MatchFinderMt_ReleaseStream(&p->matchFinderMt);
2119 #else
2120 pp = pp;
2121 #endif
2122 }
2123
2124 typedef struct _CSeqOutStreamBuf
2125 {
2126 ISeqOutStream funcTable;
2127 Byte *data;
2128 SizeT rem;
2129 int overflow;
2130 } CSeqOutStreamBuf;
2131
2132 static size_t MyWrite(void *pp, const void *data, size_t size)
2133 {
2134 CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp;
2135 if (p->rem < size)
2136 {
2137 size = p->rem;
2138 p->overflow = True;
2139 }
2140 memcpy(p->data, data, size);
2141 p->rem -= size;
2142 p->data += size;
2143 return size;
2144 }
2145
2146
2147 LZ_UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
2148 {
2149 const CLzmaEnc *p = (CLzmaEnc *)pp;
2150 return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
2151 }
2152
2153 const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
2154 {
2155 const CLzmaEnc *p = (CLzmaEnc *)pp;
2156 return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
2157 }
2158
2159 SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, int reInit,
2160 Byte *dest, size_t *destLen, LZ_UInt32 desiredPackSize, LZ_UInt32 *unpackSize)
2161 {
2162 CLzmaEnc *p = (CLzmaEnc *)pp;
2163 LZ_UInt64 nowPos64;
2164 SRes res;
2165 CSeqOutStreamBuf outStream;
2166
2167 outStream.funcTable.Write = MyWrite;
2168 outStream.data = dest;
2169 outStream.rem = *destLen;
2170 outStream.overflow = False;
2171
2172 p->writeEndMark = False;
2173 p->finished = False;
2174 p->result = SZ_OK;
2175
2176 if (reInit)
2177 LzmaEnc_Init(p);
2178 LzmaEnc_InitPrices(p);
2179 nowPos64 = p->nowPos64;
2180 RangeEnc_Init(&p->rc);
2181 p->rc.outStream = &outStream.funcTable;
2182
2183 res = LzmaEnc_CodeOneBlock(p, True, desiredPackSize, *unpackSize);
2184
2185 *unpackSize = (LZ_UInt32)(p->nowPos64 - nowPos64);
2186 *destLen -= outStream.rem;
2187 if (outStream.overflow)
2188 return SZ_ERROR_OUTPUT_EOF;
2189
2190 return res;
2191 }
2192
2193 SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
2194 ISzAlloc *alloc, ISzAlloc *allocBig)
2195 {
2196 CLzmaEnc *p = (CLzmaEnc *)pp;
2197 SRes res = SZ_OK;
2198
2199 #ifdef COMPRESS_MF_MT
2200 Byte allocaDummy[0x300];
2201 int i = 0;
2202 for (i = 0; i < 16; i++)
2203 allocaDummy[i] = (Byte)i;
2204 #endif
2205
2206 RINOK(LzmaEnc_Prepare(pp, inStream, outStream, alloc, allocBig));
2207
2208 for (;;)
2209 {
2210 res = LzmaEnc_CodeOneBlock(p, False, 0, 0);
2211 if (res != SZ_OK || p->finished != 0)
2212 break;
2213 if (progress != 0)
2214 {
2215 res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
2216 if (res != SZ_OK)
2217 {
2218 res = SZ_ERROR_PROGRESS;
2219 break;
2220 }
2221 }
2222 }
2223 LzmaEnc_Finish(pp);
2224 return res;
2225 }
2226
2227 SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
2228 {
2229 CLzmaEnc *p = (CLzmaEnc *)pp;
2230 int i;
2231 LZ_UInt32 dictSize = p->dictSize;
2232 if (*size < LZMA_PROPS_SIZE)
2233 return SZ_ERROR_PARAM;
2234 *size = LZMA_PROPS_SIZE;
2235 props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
2236
2237 for (i = 11; i <= 30; i++)
2238 {
2239 if (dictSize <= ((LZ_UInt32)2 << i))
2240 {
2241 dictSize = (2 << i);
2242 break;
2243 }
2244 if (dictSize <= ((LZ_UInt32)3 << i))
2245 {
2246 dictSize = (3 << i);
2247 break;
2248 }
2249 }
2250
2251 for (i = 0; i < 4; i++)
2252 props[1 + i] = (Byte)(dictSize >> (8 * i));
2253 return SZ_OK;
2254 }
2255
2256 SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
2257 int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
2258 {
2259 SRes res;
2260 CLzmaEnc *p = (CLzmaEnc *)pp;
2261
2262 CSeqOutStreamBuf outStream;
2263
2264 LzmaEnc_SetInputBuf(p, src, srcLen);
2265
2266 outStream.funcTable.Write = MyWrite;
2267 outStream.data = dest;
2268 outStream.rem = *destLen;
2269 outStream.overflow = False;
2270
2271 p->writeEndMark = writeEndMark;
2272 res = LzmaEnc_Encode(pp, &outStream.funcTable, &p->seqBufInStream.funcTable,
2273 progress, alloc, allocBig);
2274
2275 *destLen -= outStream.rem;
2276 if (outStream.overflow)
2277 return SZ_ERROR_OUTPUT_EOF;
2278 return res;
2279 }
2280
2281 SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
2282 const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
2283 ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
2284 {
2285 CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
2286 SRes res;
2287 if (p == 0)
2288 return SZ_ERROR_MEM;
2289
2290 res = LzmaEnc_SetProps(p, props);
2291 if (res == SZ_OK)
2292 {
2293 res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
2294 if (res == SZ_OK)
2295 res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
2296 writeEndMark, progress, alloc, allocBig);
2297 }
2298
2299 LzmaEnc_Destroy(p, alloc, allocBig);
2300 return res;
2301 }