LzmaEnc.c 91 KB

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