LzmaEnc.cpp 61 KB

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