LzmaEnc.c 64 KB

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