LzmaEnc.c 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282
  1. /* LzmaEnc.c -- 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 > (1 << kDicLogSizeMaxCompress) || props.dictSize > (1 << 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. #else
  1852. pp = pp;
  1853. #endif
  1854. }
  1855. typedef struct _CSeqOutStreamBuf
  1856. {
  1857. ISeqOutStream funcTable;
  1858. Byte *data;
  1859. SizeT rem;
  1860. Bool overflow;
  1861. } CSeqOutStreamBuf;
  1862. static size_t MyWrite(void *pp, const void *data, size_t size)
  1863. {
  1864. CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp;
  1865. if (p->rem < size)
  1866. {
  1867. size = p->rem;
  1868. p->overflow = True;
  1869. }
  1870. memcpy(p->data, data, size);
  1871. p->rem -= size;
  1872. p->data += size;
  1873. return size;
  1874. }
  1875. UInt32 LzmaEnc_GetNumAvailableBytes(CLzmaEncHandle pp)
  1876. {
  1877. const CLzmaEnc *p = (CLzmaEnc *)pp;
  1878. return p->matchFinder.GetNumAvailableBytes(p->matchFinderObj);
  1879. }
  1880. const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp)
  1881. {
  1882. const CLzmaEnc *p = (CLzmaEnc *)pp;
  1883. return p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset;
  1884. }
  1885. SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit,
  1886. Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize)
  1887. {
  1888. CLzmaEnc *p = (CLzmaEnc *)pp;
  1889. UInt64 nowPos64;
  1890. SRes res;
  1891. CSeqOutStreamBuf outStream;
  1892. outStream.funcTable.Write = MyWrite;
  1893. outStream.data = dest;
  1894. outStream.rem = *destLen;
  1895. outStream.overflow = False;
  1896. p->writeEndMark = False;
  1897. p->finished = False;
  1898. p->result = SZ_OK;
  1899. if (reInit)
  1900. LzmaEnc_Init(p);
  1901. LzmaEnc_InitPrices(p);
  1902. nowPos64 = p->nowPos64;
  1903. RangeEnc_Init(&p->rc);
  1904. p->rc.outStream = &outStream.funcTable;
  1905. res = LzmaEnc_CodeOneBlock(p, True, desiredPackSize, *unpackSize);
  1906. *unpackSize = (UInt32)(p->nowPos64 - nowPos64);
  1907. *destLen -= outStream.rem;
  1908. if (outStream.overflow)
  1909. return SZ_ERROR_OUTPUT_EOF;
  1910. return res;
  1911. }
  1912. SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress,
  1913. ISzAlloc *alloc, ISzAlloc *allocBig)
  1914. {
  1915. CLzmaEnc *p = (CLzmaEnc *)pp;
  1916. SRes res = SZ_OK;
  1917. #ifdef COMPRESS_MF_MT
  1918. Byte allocaDummy[0x300];
  1919. int i = 0;
  1920. for (i = 0; i < 16; i++)
  1921. allocaDummy[i] = (Byte)i;
  1922. #endif
  1923. RINOK(LzmaEnc_Prepare(pp, inStream, outStream, alloc, allocBig));
  1924. for (;;)
  1925. {
  1926. res = LzmaEnc_CodeOneBlock(p, False, 0, 0);
  1927. if (res != SZ_OK || p->finished != 0)
  1928. break;
  1929. if (progress != 0)
  1930. {
  1931. res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc));
  1932. if (res != SZ_OK)
  1933. {
  1934. res = SZ_ERROR_PROGRESS;
  1935. break;
  1936. }
  1937. }
  1938. }
  1939. LzmaEnc_Finish(pp);
  1940. return res;
  1941. }
  1942. SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size)
  1943. {
  1944. CLzmaEnc *p = (CLzmaEnc *)pp;
  1945. int i;
  1946. UInt32 dictSize = p->dictSize;
  1947. if (*size < LZMA_PROPS_SIZE)
  1948. return SZ_ERROR_PARAM;
  1949. *size = LZMA_PROPS_SIZE;
  1950. props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc);
  1951. for (i = 11; i <= 30; i++)
  1952. {
  1953. if (dictSize <= ((UInt32)2 << i))
  1954. {
  1955. dictSize = (2 << i);
  1956. break;
  1957. }
  1958. if (dictSize <= ((UInt32)3 << i))
  1959. {
  1960. dictSize = (3 << i);
  1961. break;
  1962. }
  1963. }
  1964. for (i = 0; i < 4; i++)
  1965. props[1 + i] = (Byte)(dictSize >> (8 * i));
  1966. return SZ_OK;
  1967. }
  1968. SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
  1969. int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
  1970. {
  1971. SRes res;
  1972. CLzmaEnc *p = (CLzmaEnc *)pp;
  1973. CSeqOutStreamBuf outStream;
  1974. LzmaEnc_SetInputBuf(p, src, srcLen);
  1975. outStream.funcTable.Write = MyWrite;
  1976. outStream.data = dest;
  1977. outStream.rem = *destLen;
  1978. outStream.overflow = False;
  1979. p->writeEndMark = writeEndMark;
  1980. res = LzmaEnc_Encode(pp, &outStream.funcTable, &p->seqBufInStream.funcTable,
  1981. progress, alloc, allocBig);
  1982. *destLen -= outStream.rem;
  1983. if (outStream.overflow)
  1984. return SZ_ERROR_OUTPUT_EOF;
  1985. return res;
  1986. }
  1987. SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen,
  1988. const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark,
  1989. ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig)
  1990. {
  1991. CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc);
  1992. SRes res;
  1993. if (p == 0)
  1994. return SZ_ERROR_MEM;
  1995. res = LzmaEnc_SetProps(p, props);
  1996. if (res == SZ_OK)
  1997. {
  1998. res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize);
  1999. if (res == SZ_OK)
  2000. res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen,
  2001. writeEndMark, progress, alloc, allocBig);
  2002. }
  2003. LzmaEnc_Destroy(p, alloc, allocBig);
  2004. return res;
  2005. }